Compare commits

...
Author SHA1 Message Date
Connor Yoh 06c51f52fc payg(c9): address review — drop @Transactional around HTTP, validate returnUrl, swap FE to Java endpoint
- PaygWalletController.createPortalSession no longer holds a JPA connection during the
  outbound RestTemplate.exchange. DB work (membership + payg_team_extensions) moves into
  a small loadPortalContext helper; the HTTP call runs after the helper returns. JOIN
  FETCH on findPrimaryMembership means no lazy access happens outside the implicit per-
  repo tx, so a slow Supabase edge fn no longer pins HikariCP for 30s.
- Add payg.portal.allowed-return-hosts allowlist (CSV). Caller-supplied return_url is
  parsed (URI) and its host is matched case-insensitively against the allowlist before
  forwarding to the edge fn; scheme is restricted to http/https so javascript:/data:
  URLs can't slip past. Empty allowlist rejects any caller-supplied return_url with
  400 INVALID_RETURN_URL — operator must opt-in explicitly. Defense in depth: doesn't
  rely on the edge fn to enforce its own allowlist.
- @RequestBody is now required = false so the FE may POST with no body and let the edge
  fn fall back to its configured default. Drops the dead req != null guard.
- ManageBillingButton.tsx now POSTs /api/v1/payg/portal-session via apiClient instead of
  calling supabase.functions.invoke('manage-billing') directly, so the new endpoint is
  actually on the live path. Maps the controller error codes (TEAM_NOT_SUBSCRIBED,
  INVALID_RETURN_URL, PORTAL_NOT_CONFIGURED, PORTAL_UNAVAILABLE) to user-facing copy.
- Tests: add INVALID_RETURN_URL coverage (off-allowlist + javascript: scheme), empty
  allowlist with null returnUrl bypass, and null-body acceptance. All 16 PaygWalletController
  tests pass; coverage targets met.
2026-06-09 15:39:48 +01:00
Connor Yoh db11a32acb payg(c9): POST /portal-session — proxy to Supabase create-customer-portal-session
Adds the third PAYG wallet endpoint that mints a Stripe-hosted billing-portal
session via the Supabase create-customer-portal-session edge fn. The FE "Manage
billing" button calls this and redirects to the returned Stripe URL.

- PaygWalletController gains POST /api/v1/payg/portal-session
- Status map: 200 + {url}, 401 anonymous, 403 no-team, 404 TEAM_NOT_SUBSCRIBED,
  502 PORTAL_UNAVAILABLE (edge fn 5xx / success=false / unreachable), 503
  PORTAL_NOT_CONFIGURED (blank endpoint config — local dev / unit tests).
- Reuses the saasRestTemplate + Bearer service-role token pattern from
  PaygMeterReportingService (C10) so portal config stays alongside the rest of
  the Supabase-fronted billing pipeline.
- isSubscribed() helper now shared between GET /wallet and POST /portal-session
  so "team has Stripe customer" is sourced from one place.
- application-saas.properties: payg.portal.endpoint + service-role-token,
  both default empty so local dev returns 503 gracefully.
- 6 new tests in PaygWalletControllerTest covering happy path (verifies
  Bearer header + team_id + return_url forwarded), team-without-customer 404,
  edge fn success=false → 502, RestTemplate throws → 502, blank endpoint
  → 503, and anonymous → 401.
2026-06-09 15:26:39 +01:00
Connor Yoh 2d19d83ce4 payg(c8): PATCH /sub-caps/{userId} — leader sets per-member spend cap
Adds the sub-cap mutation endpoint on PaygWalletController. Leaders set
team_memberships.cap_units for a member of their team; values above the
team's wallet_policy.cap_units are silently clamped (returning
clamped=true) rather than rejected, so the leader's intent ("don't let
this member spend more than X") is honoured by the effective ceiling.
A null capUnits clears the sub-cap entirely.

Authorisation: caller must be LEADER (else 403); target userId must be
a member of the same team (else 404). No team-id on the path — derived
from the caller — to keep cross-team probing impossible.

Member capUnits is already exposed in GET /wallet's members[] field
(WalletSnapshotResponse.MemberRow.capUnits from C6); no projection
change needed.

Tests: 8 new MockitoExtension cases covering below-cap, above-cap clamp,
null-clear, no-team-cap-no-clamp, member-403, different-team-404,
no-team-403, anonymous-401. All 19 PaygWalletControllerTest cases pass.
2026-06-09 15:07:15 +01:00
Connor Yoh 102994ea64 payg(c4): fix annotation gate — EntitlementGuard + PaygChargeInterceptor were short-circuiting before reading @RequiresFeature
C4 review surfaced two interlocking bugs: both interceptors gated on
`@AutoJobPostMapping` BEFORE consulting `@RequiresFeature`, so the AI
controllers' class-level `@RequiresFeature(AI_SUPPORT)` had no effect
(AI controllers carry no `@AutoJobPostMapping` — they are JSON-bodied
proxies, not multipart tool POSTs).

EntitlementGuard (major #2 — functional entitlement gap):
- A team without AI entitlement could hit `/api/v1/ai/*` freely because
  the guard's scope check returned early on routes lacking
  `@AutoJobPostMapping`.
- Fix: in-scope == (`@AutoJobPostMapping` present) OR (`@RequiresFeature`
  present, method- or class-level). Routes with neither still skip
  (admin / info / config endpoints).

PaygChargeInterceptor (major #1 — billing classification gap):
- Same short-circuit, same root cause. `determineCategory` was never
  reached for AI controllers, so the AI billing category would never be
  set even if those routes did carry multipart payloads.
- Fix: same gate widening. Routes without multipart inputs still
  short-circuit inside `doPreHandle` without touching the charge service
  — the multipart materialisation logic only runs when actual file
  parts are present.

Tests:
- `EntitlementGuardTest`: two new tests covering (a) method-level
  `@RequiresFeature` without `@AutoJobPostMapping` returns 402 when
  entitlement is missing, and (b) class-level `@RequiresFeature`
  (AiCreateController shape) returns 401 for anonymous users.
- `PaygChargeInterceptorTest`: three new tests — `@RequiresFeature`-only
  endpoint with no multipart body short-circuits without counting as
  BYPASSED; same shape with multipart body lands in `BillingCategory.AI`;
  class-level `@RequiresFeature` is resolved via beanType lookup.

Build + verification:
- `STIRLING_FLAVOR=saas :saas:compileJava :saas:compileTestJava` — clean.
- `:saas:test --tests stirling.software.saas.payg.*` — PASS, JaCoCo
  thresholds met (line 25.78%, instruction 27.14%, branch 24.40%).
2026-06-09 14:58:38 +01:00
Connor Yoh 6eb41b6931 payg(c4): annotate AI controllers + tag InternalApiClient sub-steps as AUTOMATION
The saas PaygChargeInterceptor classifies a request as AI / AUTOMATION /
API / BYPASSED using a fixed precedence: X-Stirling-Automation header >
@RequiresFeature(AUTOMATION) > @RequiresFeature(AI_SUPPORT) > API-key
auth > BYPASSED (manual UI).

Plug the AI surface and the automation sub-step path:

AI controllers (saas → easy import):
- AiCreateController, AiCreateInternalController, AiProxyController each
  get class-level @RequiresFeature(AI_SUPPORT). The interceptor already
  falls back to the bean type via AnnotationUtils.findAnnotation when no
  method-level annotation is present.

Automation sub-step header (InternalApiClient in common):
- Every caller of InternalApiClient.post() is a parent automation flow
  (PipelineProcessor, AiWorkflowService, PolicyExecutor) running a child
  tool via loopback HTTP. Tag every dispatch with
  X-Stirling-Automation: true so the child step bills as AUTOMATION
  regardless of its own annotation — i.e. an AI-OCR step inside a
  policy run is correctly billed AUTOMATION rather than AI.

Deviation (documented in test javadoc): PipelineController lives in
core and PolicyController lives in proprietary. Neither module can
import @RequiresFeature from saas without a forbidden upward dependency
(both build under STIRLING_FLAVOR=core/proprietary where saas is
absent). Promoting RequiresFeature + FeatureGate to common is a
non-trivial refactor (touches 18 files across multiple C-bucket
commits) and out of scope for C4. The X-Stirling-Automation header
covers sub-step dispatch via InternalApiClient; direct user-facing
calls to /api/v1/pipeline/handleData therefore bill as BYPASSED (WEB)
or API (api-key auth) rather than AUTOMATION. Annotating those
controllers is left to a future refactor that promotes the cap types
to common.

Tests:
- RequiresFeatureAnnotationRolloutTest pins the AI controller
  classifications so a refactor can't silently regress to BYPASSED.
- InternalApiClientTest.postTagsRequestAsAutomation captures the
  HttpHeaders submitted to RestTemplate and asserts the marker.
2026-06-09 14:48:36 +01:00
Connor Yoh e80e1b2190 payg(c10): PaygMeterReportingService + JobChargeService.close() afterCommit hook
Push billable usage to Stripe via Supabase meter-payg-units edge function after the
ledger DEBIT durably commits. Closes the "we tracked it" → "Stripe knows" loop.

PaygMeterReportingService POSTs {team_id, stripe_customer_id, units, idempotency_key,
metadata.category} to a config-driven endpoint. Both payg.meter.endpoint and
payg.meter.service-role-token default empty → no-op in local dev / tests. Never
throws; non-2xx and exceptions bump payg.meter.errors counter and log WARN.

JobChargeService.close() delegates to JobService.close() and registers an
afterCommit synchronization that fires the meter event for paid teams. Skips
when: shadow row is REFUNDED, category is BYPASSED, team has no stripeCustomerId
(free tier — ledger entry suffices), or no synchronization is active (defensive).

Idempotency key: "process:<jobId>:close" — deterministic across pod retries and
the reconciliation backfill so Stripe never bills twice for one close.

Tests:
- PaygMeterReportingServiceTest: happy path body+headers, 5xx, ConnectException,
  RuntimeException, blank/null endpoint, zero units, blank service-role-token.
- JobChargeServiceTest extended: subscribed posts; free-tier skips; refunded skips;
  bypassed skips; no shadow row skips; no team-ext row skips; meter exception is
  swallowed inside afterCommit; close() without an active transaction skips the
  meter post but still closes the job.

Free-tier detection uses stripeCustomerId == null as the established pre-#6532
stand-in (see PaygWalletController for the same pattern). Tightens to
paygSubscriptionId != null when PR #6532's payg_team_extensions column lands.
2026-06-09 14:27:34 +01:00
Connor Yoh 9f5153f272 payg(c6): real PaygWalletController + WalletCategorySummaryDao + tests
GET /api/v1/payg/wallet returns the snapshot the FE useWallet hook
consumes — derived from EntitlementService (spend / cap / period),
PaygTeamExtensions (subscription state), and the wallet_category_summary
view (per-category breakdown). Leader callers get the team roster +
per-member sub-caps; member callers see an empty roster.

PATCH /api/v1/payg/cap updates wallet_policy.cap_units (no Stripe call —
cap is application-layer, enforced via the entitlement guard) and
invalidates the team's snapshot cache so the next read reflects the
change immediately. Leader-only — authorised inside the method since the
team is derived from the caller, not a path variable.

Adds findPrimaryMembership(userId) to TeamMembershipRepository so the
wallet endpoint can resolve the caller's team + role in a single query.

Tests: 11-case pure-Mockito slice covering free vs subscribed, leader vs
member, no-cap, anonymous → 401, teamless → empty free snapshot, plus
the cap update endpoint's leader-only enforcement and cache invalidation.

Known dependency on PR #6532: stripeSubscriptionId stays null until the
payg_subscription_id column lands; "subscribed" derived from
stripe_customer_id presence as a stand-in. billableLimit fallback of 500
units mirrors EntitlementService.DEFAULT_FREE_TIER_UNITS until
pricing_policy.free_tier_units_per_cycle ships.
2026-06-09 14:14:32 +01:00
Connor Yoh 0e03dd1732 payg(c5): EntitlementService + EntitlementGuard, MINIMAL keeps OFFSITE_PROCESSING
Build the missing pieces from PR-C1's original plan:

- EntitlementService: Caffeine-cached (30s TTL, 10k entries) per-team snapshot of
  spend vs cap, with invalidate(teamId) for explicit eviction after subscription
  changes / cap edits. Reads from wallet_policy when present, falls back to a
  500-unit free-tier default until PR #6532 lands payg_subscription_id +
  pricing_policy.free_tier_units_per_cycle.

- EntitlementGuard: HandlerInterceptor on @AutoJobPostMapping routes only.
  Anonymous + billable gate (AUTOMATION / AI_SUPPORT) -> 401 SIGNUP_REQUIRED.
  Authenticated + missing gate -> 402 FEATURE_DEGRADED with state, cap, spend,
  periodEnd, missingGates. Fails open on any internal error.

- MINIMAL semantics fix: CapEvaluator.gatesFor(MINIMAL) now returns
  {OFFSITE_PROCESSING, CLIENT_SIDE}. DEGRADED state still blocks AUTOMATION +
  AI_SUPPORT, but manual server-side tools stay available -- which is the
  v2.1 PAYG framing (manual tools are free).

- RequiresFeature: extend @Target to TYPE so class-level annotation is legal
  (the charge interceptor was already checking bean type).

- Register guard in PaygWebMvcConfig at order 1100, after the charge
  interceptor (1000). 402 short-circuits handler but charge interceptor's
  afterCompletion still cleans up temp files.

Tests: 50 new test cases across EntitlementServiceTest (12), EntitlementGuardTest
(13), updated CapEvaluatorTest (25, MINIMAL assertions). All 17 payg test suites
green.
2026-06-09 13:18:12 +01:00
Connor Yoh 9655360e69 payg(c3): wire BillingCategory through interceptor + bypass fast-path
Categorise every billable tool call before the charge pipeline runs. Manual
UI tools (BYPASSED) now short-circuit ahead of multipart materialisation and
openProcess — no temp files, no shadow row, no DB writes. API-key, AI, and
automation calls thread their category through ChargeContext onto the shadow
row alongside the originating JobSource so analytics survive job pruning.

Precedence (interceptor): X-Stirling-Automation header or
@RequiresFeature(AUTOMATION) -> AUTOMATION; @RequiresFeature(AI_SUPPORT) -> AI;
ApiKeyAuthenticationToken -> API; else BYPASSED.

- PaygChargeInterceptor: determineCategory() resolves category from header +
  @RequiresFeature + auth principal. Bypass fast-path runs before doPreHandle.
  New Micrometer counter payg.filter.bypassed counts skipped manual calls.
- ChargeContext: now carries BillingCategory as a non-null record component;
  any context that reaches openProcess is API / AI / AUTOMATION.
- JobChargeService.recordShadowRow: copies billingCategory + jobSource onto
  the shadow row so post-prune analytics joins stand alone.
- Tests: extended PaygChargeInterceptorTest with bypass + category resolution
  (header / annotation / API-key / AI-with-header precedence); existing
  billable-path tests switched from JWT to API-key auth since plain JWT now
  short-circuits as BYPASSED. JobChargeServiceTest verifies the shadow row
  carries billingCategory + jobSource end-to-end.

Stripe stays on a single flat-priced meter — category is metadata only.
2026-06-09 13:03:45 +01:00
Connor Yoh c4d579ad4c payg(c1): V16 billing_category column + BillingCategory enum + entity wiring
V16 adds wallet_ledger.billing_category, payg_shadow_charge.billing_category +
job_source, and pricing_policy_stripe_price.stripe_product_id (operator
populates manually). All adds are nullable so pre-V16 rows stay NULL — the
interceptor stamps the category for new rows.

PAYG stays on a single flat-priced Stripe meter forever; this axis is purely
for in-app breakdowns and analytics. The wallet_category_summary view
pre-groups debits by team / month / category for the dashboard widget.

BillingCategory enum lists BYPASSED first as the default sentinel; no
downstream relies on ordinal(). JPA mapping uses STRING so renames stay
backward-compatible.
2026-06-09 12:53:13 +01:00
Connor Yoh 09860bffef PAYG: CapEvaluator + @RequiresFeature annotation (Bucket 5 / PR-C1 part 1)
First chunk of Bucket 5 (cap evaluator + entitlement guard + wallet
controller + cap-setting endpoints). Pure compute layer only — no DB, no
caches, no Spring. The entitlement service (next commit) supplies the
inputs from wallet_policy + payg_shadow_charge sums; this just does the
math.

Ships:

- @RequiresFeature method-level annotation declaring required FeatureGate
  values. Per the design doc the annotation is NOT required on every
  @AutoJobPostMapping — the guard's default rule is "no annotation +
  AutoJob → OFFSITE_PROCESSING". Only AUTOMATION (pipeline) and AI_SUPPORT
  (AI proxies) need the explicit annotation.

- CapEvaluator with three static helpers:
  - evaluate(spend, cap, warn%, degrade%, degradedFeatureSet)
    → Evaluation(state, featureSet, enabledGates). Single integer compare
    on the hot path; defensive against null/zero/misconfigured inputs.
  - combineTeamAndMember(teamEval, memberEval) → effective eval,
    stricter state, intersected gates. Handles the per-member sub-cap
    case from §3.6.
  - allEnabled(required, enabled) → predicate the guard calls per request.

- 22 unit tests covering: null/zero cap, warn boundary, degrade boundary,
  over-threshold, misconfigured thresholds, member-team combination,
  state ordering, gate intersection, mapping FeatureSet → gates,
  guard predicate edge cases.

Next commits (same PR):
- EntitlementService — snapshot computation with 30s Caffeine cache
- EntitlementGuard — HandlerInterceptor reading @RequiresFeature
- PaygWalletController — GET /api/v1/payg/wallet (PaygSnapshot DTO matching FE)
- CapAdminController — admin direct cap-setting endpoints

Tracked in notes/PAYG_DESIGN.md §3.6 + §3.7 + §7.6 (PR-C1) and
notes/payg-launch-checklist.html Bucket 5.
2026-06-09 12:47:59 +01:00
James BruntonandGitHub 0e3cbb3cf2 Explicitly test for console warnings & errors (#6502)
# Description of Changes
Disallow warnings and errors from being thrown in the browser console
during tests unless explicitly expected in the test. Also adds a
Playwright test to prod around some main UI areas and checks that no
warnings/errors have been thrown.
2026-06-09 08:34:02 +00:00
James BruntonandGitHub 002de06411 Fix desktop app not being able to load pdfium (#6575)
# Description of Changes
The changes in
[#6279](https://github.com/Stirling-Tools/Stirling-PDF/pull/6279) broke
the desktop app because the wasm URL handling didn't deal with
`tauri://` paths. Also I noticed that `task desktop:build:dev:mac`
failed locally because it was attempting to sign the app with
credentials that developers won't have (and shouldn't need), so I fixed
that too.
2026-06-08 16:21:56 +00:00
James BruntonandGitHub 51478e5051 Policies backend (#6527)
# Description of Changes
Add a backend for running any multi-step PDF operations. This is
designed to be used for the upcoming Policies feature, along with
anything else that will require automated running of PDF operations,
like the Automate tool or Processing Folders.

The implementation is not complete. I've tried to get all the
infrastructure in there so that we can add in whichever triggers we need
in the future (like cron triggers or watching folders on disk) but
currently it just supports manual triggering of the policy.

The basis of this work was the operation running from the Stirling
Engine, which this PR removes in favour of this new system. The only
currently accessible frontend way to test this work is to ask the AI
chat to execute multiple operations on a PDF, but I've also extensively
tested with direct API calls to make sure that the policies work and
persist properly.
2026-06-08 10:50:55 +00:00
Anthony StirlingandGitHub 69e62d8949 exclude unused Redis auto-config (#6547)
fix(health): exclude unused Redis auto-config so default
/actuator/health stays UP

---

## 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/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 run `task check` to verify linters, typechecks, and tests
pass
- [ ] I have tested my changes locally. Refer to the [Testing
Guide](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/DeveloperGuide.md#7-testing)
for more details.
2026-06-08 10:41:38 +00:00
Anthony StirlingandGitHub 2f6b113a13 feat(settings): link ENTERPRISE badges to plan page (#6560)
## Summary
Make the remaining static ENTERPRISE badges in the admin settings
clickable so they navigate the user to `/settings/adminPlan`, matching
the pattern already used by the PRO badges in Connections / Features /
General sections.

### Before
Two ENTERPRISE badges were inert text chips with no affordance:
- `AdminSecuritySection.tsx` - Audit Logging
- `AdminDatabaseSection.tsx` - Database section header

### After
Both now use the same pattern as the existing clickable PRO badges:
- `cursor: pointer`
- `onClick={() => navigate("/settings/adminPlan")}`
- `title` tooltip with the existing
`admin.settings.badge.clickToUpgrade` i18n key ("Click to view plan
details")

No new strings, no new components - just wiring up existing behavior to
the two badges that were missing it.

### Existing already-clickable badges (kept identical for reference)
- `AdminConnectionsSection.tsx:585-596` - SSO Auto Login PRO
- `AdminFeaturesSection.tsx:175-186` - Server Certificate PRO
- `AdminGeneralSection.tsx:920-931` - Custom Metadata PRO
2026-06-08 10:40:35 +00:00
Anthony StirlingandGitHub af52134811 fix(automate): flip AutomationEntry tooltip to position=left (#6550)
# Description of Changes

automate description tooltip was facing wrong way

---

## 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/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 run `task check` to verify linters, typechecks, and tests
pass
- [ ] I have tested my changes locally. Refer to the [Testing
Guide](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/DeveloperGuide.md#7-testing)
for more details.
2026-06-08 10:38:00 +00:00
Anthony StirlingandGitHub 8a2474ff60 fix(desktop): enable in-page drag-drop in Tauri build (#6548)
## Summary

- Set `dragDropEnabled: false` on the Tauri window so HTML5 drag events
reach the WebView. Previously the default `true` made Tauri intercept
all drag-drop at the OS level, silently breaking in-page drag-to-reorder
(Pragmatic Drag and Drop in `FileEditorThumbnail` /
`useFileItemDragDrop`) in the desktop build. The Active Files tab
reorder, which feeds Merge ordering, was the user-visible symptom.
- Browser builds are unaffected (tauri.conf.json is desktop-only).
- The OS file-drop pipeline now flows through the existing Mantine
`Dropzone` in `FileEditor.tsx` via HTML5 events instead of the Rust
`WindowEvent::DragDrop` handler in `lib.rs:215`. Verified working.

## Test plan

- [x] Desktop: drag a thumbnail in Active Files past another - row goes
semi-transparent, order updates on drop.
- [x] Desktop: drag a PDF from File Explorer onto the window - file is
added.
- [x] Web build: drag-to-reorder still works (unchanged code path; flag
is desktop-only).
- [x] Merge tool: order set by drag in Active Files is the order used by
the merge output.

## Follow-up (not in this PR)

- `WindowEvent::DragDrop` arm in
`frontend/editor/src-tauri/src/lib.rs:215-229` is now unreachable for
window drops. The `forward_files_to_window` helper still serves the
macOS Finder "Open With" path (`RunEvent::Opened` at lib.rs:230), so
only the DragDrop arm can be deleted. Worth a small cleanup pass later.
2026-06-08 10:36:58 +00:00
Anthony StirlingandGitHub d202c9c32f Minor: sanitize SVG (#6572)
# Description of Changes

Sanitize SVG

---

## 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/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 run `task check` to verify linters, typechecks, and tests
pass
- [ ] I have tested my changes locally. Refer to the [Testing
Guide](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/DeveloperGuide.md#7-testing)
for more details.
2026-06-08 10:31:41 +00:00
Anthony StirlingandGitHub 1ef03c43b4 fix(i18n): wrap hard-coded English strings in t() across UI (#6566)
## Summary
Audit + bulk fix of hard-coded English UI strings - `aria-label`,
`title`, `placeholder`, `label`, and raw JSX literals that bypassed i18n
entirely. Each literal now goes through `t("key", "English Default")`
from `react-i18next`, and every new key has a corresponding entry in
`en-GB/translation.toml` so translators can pick it up.

## What this fixes
Strings were rendered untranslated in every non-EN locale because they
never went through `t()` at all (not just "value not translated yet").
Affects screen-reader labels, tooltips, form placeholders, empty/loading
states, plan card content, and the entire workflow ParticipantView.

## Coverage (~143 keys / 50 files)
- **Viewer chrome** - search bar (close, clear, prev/next, "of N"
results), link/signature/redaction actions, viewer error state, zoom
labels
- **Page editor** - undo/redo/rotate/delete toolbar tooltips, empty
state, bulk selection operator chip tooltips
- **Shared primitives** - Tooltip close, InfoBanner dismiss, TextInput
clear, Toast dismiss/toggle, UpdateModal close, EditableSecretField
edit, DropdownListWithFooter search, FileCard/FileDropdownMenu actions,
EmptyFilesState + AddFileCard upload
- **Tools** - Image upload + hint, ColorControl eyedropper, sign Use
Signature, CompressSettings, OCR loading, PageLayout
margin/border/row/col placeholders, FormFill switch + save + re-scan
- **Proprietary admin** - OverviewHeader signed-in line + logout,
AdminPremiumSection moved-features list (via `<Trans>`),
AdminPlanSection no-data alert, AdminAdvancedSection temp-dir
placeholders, AdminEndpointsSection multiselect placeholders,
AdminMailSection + AdminDatabaseSection password placeholders
- **Onboarding** - MFASetupSlide QR loading + auth code label,
SecurityCheckSlide role select + options
- **ParticipantView** - entire sign-document UI (~30 strings: loading,
error, badges, headings, cert-type Select, all input labels and
placeholders, action buttons, completion + expired alerts) - file
previously imported `useTranslation` but only used `t()` for cert
validation
- **planConstants.ts refactor** - replaced `PLAN_FEATURES` /
`PLAN_HIGHLIGHTS` const exports with `usePlanFeatures()` /
`usePlanHighlights()` hooks. Service layer (`licenseService.getPlans`)
updated to accept feature/highlight maps so it stays hook-free. Callers
(`usePlans`, `CheckoutContext`) resolve the hooks at the React boundary
- **Previously catalogued offenders** - `FileSidebarFileItem`
open/close-viewer aria-labels, `quickAccessBar/ActiveToolButton` "Back
to all tools" tooltip + aria, `AppConfigModal` close button

## Notes
- One small refactor in `usePageSelectionTips.ts` was needed to resolve
a TOML key-shape conflict: the existing scalar keys
`bulkSelection.operators.{and,not,comma}` needed to become tables to
hold the new `.title` subkeys for OperatorsSection's chip tooltips. The
existing descriptions moved to `[bulkSelection.operators.descriptions]`
and the three i18n key paths in usePageSelectionTips were updated to
match.
- Viewer sidebar close buttons
(Bookmark/Layer/Thumbnail/Attachment/Comments) were on the audit list
but are NOT on main - they're added by the unmerged PR #6552
(feat/viewer-sidebar-ux). Those particular strings will need wrapping
when that PR lands.
- TOML hook (`toml-sort-fix`) ran and re-sorted the translation file.

## Test plan
- [ ] `task frontend:typecheck` passes (core + proprietary + desktop
variants)
- [ ] `task frontend:lint` passes
- [ ] Switching language to Deutsch / Русский: previously-English
`aria-label`s + tooltips + placeholders + plan card bullets now render
translated (when the locale has values) or fall back to the English
default (when it doesn't)
- [ ] Plan page bullet points in EN render unchanged
- [ ] Sign-document flow (ParticipantView) renders unchanged in EN
2026-06-08 10:11:43 +00:00
159 changed files with 9374 additions and 702 deletions
+3 -3
View File
@@ -62,21 +62,21 @@ tasks:
deps: [prepare]
dir: editor
cmds:
- npx tauri build --bundles app
- npx tauri build --bundles app --config '{"bundle":{"createUpdaterArtifacts":false}}'
build:dev:windows:
desc: "Build Tauri desktop NSIS installer (Windows)"
deps: [prepare]
dir: editor
cmds:
- npx tauri build --bundles nsis
- npx tauri build --bundles nsis --config '{"bundle":{"createUpdaterArtifacts":false}}'
build:dev:linux:
desc: "Build Tauri desktop AppImage (Linux)"
deps: [prepare]
dir: editor
cmds:
- npx tauri build --bundles appimage
- npx tauri build --bundles appimage --config '{"bundle":{"createUpdaterArtifacts":false}}'
test:
desc: "Run Tauri/Cargo tests"
@@ -50,6 +50,16 @@ public class InternalApiClient {
"^/api/v1/(general|misc|security|convert|filter)(/[A-Za-z0-9_-]+)+$"
+ "|^/api/v1/ai/tools(/[A-Za-z0-9_-]+)+$");
/**
* Marker propagated on every internal sub-step dispatch so the saas PAYG interceptor classifies
* the call as {@code BillingCategory.AUTOMATION}. By construction every {@link
* InternalApiClient#post} caller is an automation surface (pipeline executor, AI workflow,
* policy runner) running a child tool inside a parent automation flow — see the saas {@code
* PaygChargeInterceptor.determineCategory} precedence chain, where this header dominates any
* per-tool {@code @RequiresFeature} annotation.
*/
public static final String AUTOMATION_HEADER = "X-Stirling-Automation";
private final ServletContext servletContext;
private final UserServiceInterface userService;
private final TempFileManager tempFileManager;
@@ -96,6 +106,11 @@ public class InternalApiClient {
if (apiKey != null && !apiKey.isEmpty()) {
headers.add("X-API-KEY", apiKey);
}
// Tag the sub-step as automation so PAYG bills it under AUTOMATION regardless of which
// tool-level @RequiresFeature annotation the dispatched controller carries (e.g. an AI-OCR
// step inside a policy run must bill as AUTOMATION, not AI). Set unconditionally because
// every caller of this dispatcher is an automation surface by design.
headers.add(AUTOMATION_HEADER, "true");
HttpEntity<MultiValueMap<String, Object>> entity = new HttpEntity<>(body, headers);
RequestCallback requestCallback = restTemplate.httpEntityCallback(entity, Resource.class);
@@ -1,11 +1,21 @@
package stirling.software.common.service;
import java.util.List;
/** Provides metadata about tool endpoints for internal dispatch. */
public interface ToolMetadataService {
/** Returns true if the given operation path accepts multiple input files. */
boolean isMultiInput(String operationPath);
/**
* Returns the file extensions (lowercase, no leading dot, e.g. {@code "pdf"}) that the
* operation accepts as input ({@code output=false}) or produces as output ({@code
* output=true}), derived from the endpoint's declared type. Returns {@code null} when the
* endpoint declares no specific type, which callers should treat as "any type accepted".
*/
List<String> getExtensionTypes(boolean output, String operationPath);
/**
* Returns true when the endpoint's ZIP response is a transport for multiple typed results and
* should be unpacked: multi-output endpoints (Type:SIMO / Type:MIMO) and wrapper declarations
@@ -59,6 +59,53 @@ class InternalApiClientTest {
servletContext, userService, tempFileManager, environment, applicationProperties);
}
@Test
void postTagsRequestAsAutomation() throws Exception {
// Every InternalApiClient.post() caller is a parent automation flow dispatching a child
// tool (pipeline executor, AI workflow, policy runner). Tagging the sub-step here means
// the saas PaygChargeInterceptor classifies it as BillingCategory.AUTOMATION regardless of
// the dispatched controller's @RequiresFeature — so an AI-OCR step inside a policy run
// bills as AUTOMATION, not AI. The header value is the literal string "true" because the
// interceptor compares case-insensitively-trimmed against that token.
MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
body.add("fileInput", namedResource("input.pdf", "data"));
Path tempPath = Files.createTempFile("internal-api-automation-test", ".tmp");
TempFile tempFile = mock(TempFile.class);
when(tempFile.getPath()).thenReturn(tempPath);
when(tempFile.getFile()).thenReturn(tempPath.toFile());
when(tempFileManager.createManagedTempFile("internal-api")).thenReturn(tempFile);
HttpHeaders[] captured = {null};
try (var ignored =
mockConstruction(
RestTemplate.class,
(rt, ctx) -> {
when(rt.httpEntityCallback(any(), eq(Resource.class)))
.thenAnswer(
inv -> {
HttpEntity<?> entity = inv.getArgument(0);
captured[0] = entity.getHeaders();
return (RequestCallback) req -> {};
});
when(rt.execute(anyString(), eq(HttpMethod.POST), any(), any()))
.thenAnswer(inv -> fakeOkResponse(inv.getArgument(3)));
})) {
InternalApiClient mockedClient = newClient();
mockedClient.post("/api/v1/general/merge-pdfs", body);
assertNotNull(captured[0]);
assertEquals(
"true",
captured[0].getFirst(InternalApiClient.AUTOMATION_HEADER),
"Sub-step dispatch must carry the automation marker header");
} finally {
Files.deleteIfExists(tempPath);
}
}
@Test
void postDoesNotForceContentType() throws Exception {
MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
@@ -25,6 +25,7 @@ import stirling.software.common.annotations.api.MiscApi;
import stirling.software.common.enumeration.ResourceWeight;
import stirling.software.common.service.CustomPDFDocumentFactory;
import stirling.software.common.util.GeneralUtils;
import stirling.software.common.util.SvgSanitizer;
import stirling.software.common.util.TempFile;
import stirling.software.common.util.TempFileManager;
import stirling.software.common.util.WebResponseUtils;
@@ -36,6 +37,7 @@ public class OverlayImageController {
private final CustomPDFDocumentFactory pdfDocumentFactory;
private final TempFileManager tempFileManager;
private final SvgSanitizer svgSanitizer;
@AutoJobPostMapping(
consumes = MediaType.MULTIPART_FORM_DATA_VALUE,
@@ -61,6 +63,9 @@ public class OverlayImageController {
byte[] imageBytes = imageFile.getBytes();
boolean isSvg = SvgOverlayUtil.isSvgImage(imageBytes);
if (isSvg) {
imageBytes = svgSanitizer.sanitize(imageBytes);
}
try (PDDocument document = pdfDocumentFactory.load(pdfBytes)) {
int pages = document.getNumberOfPages();
@@ -63,6 +63,7 @@ public class ApiDocService implements stirling.software.common.service.ToolMetad
return "http://localhost:" + port + contextPath + "/v1/api-docs";
}
@Override
public List<String> getExtensionTypes(boolean output, String operationName) {
if (outputToFileTypes.isEmpty()) {
outputToFileTypes.put("PDF", List.of("pdf"));
@@ -10,6 +10,7 @@ import org.apache.batik.bridge.GVTBuilder;
import org.apache.batik.bridge.UserAgent;
import org.apache.batik.bridge.UserAgentAdapter;
import org.apache.batik.gvt.GraphicsNode;
import org.apache.batik.util.ParsedURL;
import org.apache.batik.util.XMLResourceDescriptor;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
@@ -39,7 +40,16 @@ public class SvgOverlayUtil {
svgDoc = factory.createSVGDocument("file:///overlay.svg", inputStream);
}
UserAgent userAgent = new UserAgentAdapter();
UserAgent userAgent =
new UserAgentAdapter() {
@Override
public void checkLoadExternalResource(
ParsedURL resourceURL, ParsedURL docURL) {
throw new SecurityException(
"External resource loading is disabled for SVG overlays: "
+ resourceURL);
}
};
DocumentLoader loader = new DocumentLoader(userAgent);
BridgeContext ctx = new BridgeContext(userAgent, loader);
ctx.setDynamicState(BridgeContext.DYNAMIC);
@@ -93,6 +93,11 @@ posthog.host=https://eu.i.posthog.com
spring.main.allow-bean-definition-overriding=true
# spring-data-redis is on the classpath only for the optional Valkey backplane (which wires its own
# factory); exclude Spring Boot's stock Redis auto-config so a default install doesn't create a dead
# localhost:6379 factory that flips /actuator/health to DOWN.
spring.autoconfigure.exclude=org.springframework.boot.data.redis.autoconfigure.DataRedisAutoConfiguration,org.springframework.boot.data.redis.autoconfigure.DataRedisReactiveAutoConfiguration
# Set up a consistent temporary directory location
java.io.tmpdir=${stirling.tempfiles.directory:${java.io.tmpdir}/stirling-pdf}
@@ -32,6 +32,7 @@ import org.springframework.mock.web.MockMultipartFile;
import stirling.software.SPDF.model.api.misc.OverlayImageRequest;
import stirling.software.common.service.CustomPDFDocumentFactory;
import stirling.software.common.util.SvgSanitizer;
import stirling.software.common.util.TempFile;
import stirling.software.common.util.TempFileManager;
import stirling.software.common.util.WebResponseUtils;
@@ -52,6 +53,7 @@ class OverlayImageControllerTest {
@Mock private CustomPDFDocumentFactory pdfDocumentFactory;
@Mock private TempFileManager tempFileManager;
@Mock private SvgSanitizer svgSanitizer;
@InjectMocks private OverlayImageController controller;
@@ -205,6 +207,52 @@ class OverlayImageControllerTest {
mockDoc.close();
}
@Test
void overlayImage_svgInput_sanitizedBeforeOverlay() throws Exception {
byte[] maliciousSvg =
("<svg xmlns=\"http://www.w3.org/2000/svg\""
+ " xmlns:xlink=\"http://www.w3.org/1999/xlink\""
+ " width=\"10\" height=\"10\">"
+ "<image x=\"0\" y=\"0\" width=\"10\" height=\"10\""
+ " xlink:href=\"file:///etc/passwd\"/>"
+ "</svg>")
.getBytes();
byte[] sanitized =
("<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"10\" height=\"10\">"
+ "<image x=\"0\" y=\"0\" width=\"10\" height=\"10\"/>"
+ "</svg>")
.getBytes();
when(svgSanitizer.sanitize(maliciousSvg)).thenReturn(sanitized);
MockMultipartFile svgFile =
new MockMultipartFile("imageFile", "overlay.svg", "image/svg+xml", maliciousSvg);
OverlayImageRequest request = new OverlayImageRequest();
request.setFileInput(pdfFile);
request.setImageFile(svgFile);
request.setX(0);
request.setY(0);
request.setEveryPage(false);
PDDocument mockDoc = new PDDocument();
mockDoc.addPage(new PDPage(PDRectangle.A4));
when(pdfDocumentFactory.load(any(byte[].class))).thenReturn(mockDoc);
try (MockedStatic<WebResponseUtils> mockedWebResponse =
mockStatic(WebResponseUtils.class)) {
mockedWebResponse
.when(
() ->
WebResponseUtils.pdfFileToWebResponse(
any(TempFile.class), anyString()))
.thenReturn(streamingOk("result".getBytes()));
controller.overlayImage(request);
}
mockDoc.close();
verify(svgSanitizer).sanitize(maliciousSvg);
}
@Test
void overlayImage_withCoordinates_usesXY() throws Exception {
OverlayImageRequest request = new OverlayImageRequest();
@@ -0,0 +1,319 @@
package stirling.software.proprietary.policy.controller;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.server.ResponseStatusException;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import io.github.pixee.security.Filenames;
import io.swagger.v3.oas.annotations.Hidden;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import stirling.software.common.model.job.JobResponse;
import stirling.software.common.util.TempFile;
import stirling.software.common.util.TempFileManager;
import stirling.software.proprietary.policy.engine.PolicyRunHandle;
import stirling.software.proprietary.policy.engine.PolicyRunRegistry;
import stirling.software.proprietary.policy.model.PipelineDefinition;
import stirling.software.proprietary.policy.model.Policy;
import stirling.software.proprietary.policy.model.PolicyInputs;
import stirling.software.proprietary.policy.model.PolicyRun;
import stirling.software.proprietary.policy.model.PolicyRunStatus;
import stirling.software.proprietary.policy.model.PolicyRunView;
import stirling.software.proprietary.policy.progress.PolicyProgressListener;
import stirling.software.proprietary.policy.store.PolicyStore;
import stirling.software.proprietary.policy.trigger.ManualTrigger;
import stirling.software.proprietary.security.config.PremiumEndpoint;
import tools.jackson.core.JacksonException;
import tools.jackson.databind.ObjectMapper;
/**
* Manages policies and runs pipelines. The premium backend entry point: CRUD for stored {@code
* Policy} objects, running a stored policy by id, and running an ad-hoc pipeline (for AI/Automate
* one-offs).
*
* <p>Runs execute asynchronously and return a run id immediately. Poll {@code GET /run/{runId}} for
* status, and download outputs via the existing {@code GET /api/v1/general/files/{fileId}} using
* the file ids in the run view.
*/
@Slf4j
@RestController
@RequestMapping("/api/v1/policies")
@Hidden
@PremiumEndpoint
@RequiredArgsConstructor
@Tag(name = "Policies", description = "Run tool pipelines on the backend")
public class PolicyController {
private final ManualTrigger manualTrigger;
private final PolicyRunRegistry runRegistry;
private final PolicyStore policyStore;
private final ObjectMapper objectMapper;
private final TempFileManager tempFileManager;
/** SSE emitter timeout, generous enough for long multi-step runs on large files. */
@Value("${stirling.policies.streamTimeoutMs:1800000}")
private long streamTimeoutMs;
@PostMapping(value = "/run", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
@Operation(
summary = "Run a tool pipeline",
description =
"Accepts the documents to process (multipart field 'fileInput'), any supporting"
+ " files (each under a multipart field named as its asset key, e.g."
+ " 'company-logo'), and a JSON pipeline definition ('json'). Runs the"
+ " steps in order asynchronously and returns a run id. Poll the run"
+ " status endpoint and download outputs via /api/v1/general/files/{id}.")
public ResponseEntity<JobResponse<Void>> run(
@RequestParam("json") String json, MultipartHttpServletRequest request)
throws IOException {
PipelineDefinition definition = parseDefinition(json);
PolicyInputs inputs = collectInputs(request);
String runId = manualTrigger.fire(definition, inputs, PolicyProgressListener.NOOP).runId();
return ResponseEntity.accepted().body(new JobResponse<>(true, runId, null));
}
@PostMapping(value = "/run/stream", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
@Operation(
summary = "Run a tool pipeline with live progress",
description =
"Same as /run, but returns Server-Sent Events: a 'step' event as each step"
+ " starts and completes, then a terminal 'completed', 'failed',"
+ " 'cancelled', or 'waiting' event carrying the final run view.")
public SseEmitter runStream(
@RequestParam("json") String json, MultipartHttpServletRequest request)
throws IOException {
PipelineDefinition definition = parseDefinition(json);
PolicyInputs inputs = collectInputs(request);
SseEmitter emitter = new SseEmitter(streamTimeoutMs);
emitter.onError(e -> log.warn("Policy run SSE emitter error", e));
PolicyRunHandle handle = manualTrigger.fire(definition, inputs, streamListener(emitter));
// Close the stream with a terminal event once the run finishes. whenComplete runs on the
// engine's worker thread after the run is done, so this never races the step events.
handle.completion()
.whenComplete(
(run, throwable) -> {
if (throwable != null) {
sendEvent(
emitter,
"failed",
Map.of("message", throwable.getMessage()));
} else {
sendEvent(emitter, terminalEventName(run), PolicyRunView.of(run));
}
emitter.complete();
});
return emitter;
}
@GetMapping("/run/{runId}")
@Operation(
summary = "Get pipeline run status",
description = "Returns the current status, step cursor, and output files of a run.")
public ResponseEntity<PolicyRunView> status(@PathVariable String runId) {
PolicyRun run = runRegistry.get(runId);
if (run == null) {
return ResponseEntity.notFound().build();
}
return ResponseEntity.ok(PolicyRunView.of(run));
}
// --- Policy management ---
@PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE)
@Operation(
summary = "Create or update a policy",
description =
"Stores a policy (trigger config + steps + output + metadata). A blank id is"
+ " assigned; returns the stored policy with its id.")
public ResponseEntity<Policy> savePolicy(@RequestBody String json) {
return ResponseEntity.ok(policyStore.save(parsePolicy(json)));
}
@GetMapping
@Operation(summary = "List policies")
public List<Policy> listPolicies() {
return policyStore.all();
}
@GetMapping("/{policyId}")
@Operation(summary = "Get a policy by id")
public ResponseEntity<Policy> getPolicy(@PathVariable String policyId) {
return policyStore
.get(policyId)
.map(ResponseEntity::ok)
.orElseGet(() -> ResponseEntity.notFound().build());
}
@DeleteMapping("/{policyId}")
@Operation(summary = "Delete a policy by id")
public ResponseEntity<Void> deletePolicy(@PathVariable String policyId) {
return policyStore.delete(policyId)
? ResponseEntity.noContent().build()
: ResponseEntity.notFound().build();
}
@PostMapping(value = "/{policyId}/run", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
@Operation(
summary = "Run a stored policy",
description =
"Runs the stored policy's pipeline on the supplied files (primary documents"
+ " under 'fileInput', supporting files under their asset-key fields)."
+ " Runs regardless of the policy's enabled flag, which only gates"
+ " automatic triggering. Returns a run id.")
public ResponseEntity<JobResponse<Void>> runStoredPolicy(
@PathVariable String policyId, MultipartHttpServletRequest request) throws IOException {
Policy policy =
policyStore
.get(policyId)
.orElseThrow(
() ->
new ResponseStatusException(
HttpStatus.NOT_FOUND, "No policy: " + policyId));
PolicyInputs inputs = collectInputs(request);
String runId = manualTrigger.run(policy, inputs, PolicyProgressListener.NOOP).runId();
return ResponseEntity.accepted().body(new JobResponse<>(true, runId, null));
}
private Policy parsePolicy(String json) {
try {
return objectMapper.readValue(json, Policy.class);
} catch (JacksonException e) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Invalid policy JSON");
}
}
private PipelineDefinition parseDefinition(String json) {
PipelineDefinition definition;
try {
definition = objectMapper.readValue(json, PipelineDefinition.class);
} catch (JacksonException e) {
throw new ResponseStatusException(
HttpStatus.BAD_REQUEST, "Invalid pipeline definition JSON");
}
if (definition.steps().isEmpty()) {
throw new ResponseStatusException(
HttpStatus.BAD_REQUEST, "Pipeline definition has no steps");
}
return definition;
}
/**
* Split the multipart file parts into the primary document stream ("fileInput") and the named
* supporting-file store: every other file field becomes an asset keyed by its field name, which
* a step references from {@code fileParameters}.
*/
private PolicyInputs collectInputs(MultipartHttpServletRequest request) throws IOException {
MultiValueMap<String, MultipartFile> fileMap = request.getMultiFileMap();
List<Resource> primary = toResources(fileMap.get("fileInput"));
Map<String, List<Resource>> supportingFiles = new LinkedHashMap<>();
for (Map.Entry<String, List<MultipartFile>> entry : fileMap.entrySet()) {
if ("fileInput".equals(entry.getKey())) {
continue;
}
List<Resource> assets = toResources(entry.getValue());
if (!assets.isEmpty()) {
supportingFiles.put(entry.getKey(), assets);
}
}
return new PolicyInputs(primary, supportingFiles);
}
/**
* A progress listener that forwards each step transition to the SSE stream as a "step" event.
*/
private PolicyProgressListener streamListener(SseEmitter emitter) {
return new PolicyProgressListener() {
@Override
public void onStepStart(int stepIndex, int stepCount, String operation) {
sendEvent(emitter, "step", stepEvent("started", stepIndex, stepCount, operation));
}
@Override
public void onStepComplete(int stepIndex, int stepCount, String operation) {
sendEvent(emitter, "step", stepEvent("completed", stepIndex, stepCount, operation));
}
};
}
private static Map<String, Object> stepEvent(
String phase, int stepIndex, int stepCount, String operation) {
return Map.of(
"phase", phase,
"stepIndex", stepIndex,
"stepCount", stepCount,
"operation", operation);
}
private static String terminalEventName(PolicyRun run) {
PolicyRunStatus status = run.getStatus();
return switch (status) {
case COMPLETED -> "completed";
case FAILED -> "failed";
case CANCELLED -> "cancelled";
case WAITING_FOR_INPUT -> "waiting";
default -> "ended";
};
}
private void sendEvent(SseEmitter emitter, String name, Object data) {
try {
emitter.send(SseEmitter.event().name(name).data(data, MediaType.APPLICATION_JSON));
} catch (IOException | IllegalStateException e) {
// Client disconnected or the emitter already closed. The run continues and its results
// remain downloadable via the job endpoints; nothing useful left to stream.
log.debug("Dropping policy SSE event '{}': {}", name, e.getMessage());
}
}
private List<Resource> toResources(List<MultipartFile> files) throws IOException {
List<Resource> resources = new ArrayList<>();
if (files == null) {
return resources;
}
for (MultipartFile file : files) {
if (file == null || file.isEmpty()) {
continue;
}
TempFile tempFile = tempFileManager.createManagedTempFile("policy-run");
file.transferTo(tempFile.getPath());
final String originalName = Filenames.toSimpleFileName(file.getOriginalFilename());
resources.add(
new FileSystemResource(tempFile.getFile()) {
@Override
public String getFilename() {
return originalName;
}
});
}
return resources;
}
}
@@ -0,0 +1,261 @@
package stirling.software.proprietary.policy.engine;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import org.springframework.core.io.Resource;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import stirling.software.common.model.job.ResultFile;
import stirling.software.common.service.FileStorage;
import stirling.software.common.service.InternalApiTimeoutException;
import stirling.software.common.service.JobOwnershipService;
import stirling.software.common.service.JobQueue;
import stirling.software.common.service.ResourceMonitor;
import stirling.software.common.service.TaskManager;
import stirling.software.common.util.ExecutorFactory;
import stirling.software.proprietary.policy.model.OutputSpec;
import stirling.software.proprietary.policy.model.PipelineDefinition;
import stirling.software.proprietary.policy.model.Policy;
import stirling.software.proprietary.policy.model.PolicyInputs;
import stirling.software.proprietary.policy.model.PolicyRun;
import stirling.software.proprietary.policy.model.WaitState;
import stirling.software.proprietary.policy.output.PolicyOutputSink;
import stirling.software.proprietary.policy.progress.PolicyProgressListener;
/**
* Runs pipelines asynchronously as tracked jobs.
*
* <p>Each run is the unit of async work: {@link #submit} returns a run id immediately and the
* pipeline executes on a virtual thread, so a step blocking on a slow tool does not tie up a
* platform thread. The run drives {@link PolicyExecutor} for the actual step loop, registers its
* outputs and progress with {@link TaskManager} (so the existing job status/download endpoints work
* unchanged), and keeps rich state in {@link PolicyRunRegistry}.
*
* <p>The engine deliberately manages its own virtual-thread execution rather than routing through
* {@code JobExecutorService}: that path force-completes a job once its work returns, which is
* incompatible with a run that suspends in {@code WAITING_FOR_INPUT}. It still applies the shared
* {@link ResourceMonitor}/{@link JobQueue} admission control, so heavy runs queue under load
* instead of oversubscribing.
*/
@Slf4j
@Service
@RequiredArgsConstructor
public class PolicyEngine {
/**
* Resource weight of a pipeline run for admission control. A run chains many tools and holds
* intermediate files, so it is weighted as heavy work: the shared {@link ResourceMonitor}
* should let it start while the system is healthy but hold it back under memory/CPU pressure.
* See {@link ResourceMonitor#shouldQueueJob(int)} for how a weight maps to that decision.
*/
private static final int RUN_RESOURCE_WEIGHT = 50;
private final PolicyExecutor stepExecutor;
private final TaskManager taskManager;
private final PolicyRunRegistry registry;
private final FileStorage fileStorage;
private final JobOwnershipService jobOwnershipService;
private final List<PolicyOutputSink> outputSinks;
private final ResourceMonitor resourceMonitor;
private final JobQueue jobQueue;
private final ExecutorService asyncExecutor = ExecutorFactory.newVirtualThreadExecutor();
/**
* Submit a pipeline to run asynchronously. The returned handle's run id scopes a job in {@link
* TaskManager}, so progress (notes), status, and result files are observable via the existing
* job endpoints as well as via {@link #getRun(String)}; its completion future resolves when the
* run reaches a terminal or paused state.
*/
public PolicyRunHandle submit(
PipelineDefinition definition, PolicyInputs inputs, PolicyProgressListener listener) {
// Scope the run id to the current user (on this request thread) so the file-download
// ownership check passes; NoOpJobOwnershipService returns the id unchanged when security
// is off.
String runId = jobOwnershipService.createScopedJobKey(UUID.randomUUID().toString());
taskManager.createTask(runId);
PolicyRun run = new PolicyRun(runId, definition);
registry.register(run);
CompletableFuture<PolicyRun> completion = new CompletableFuture<>();
PolicyProgressListener tracking = trackingListener(runId, run, listener);
Runnable task = () -> runToCompletion(run, inputs, tracking, completion);
// Each run is one admission unit; steps run synchronously within it, so this gates heavy
// work under load without the pool-within-pool risk of queueing each tool call. Under
// resource pressure the run waits in the shared JobQueue; otherwise it starts immediately.
if (resourceMonitor.shouldQueueJob(RUN_RESOURCE_WEIGHT)) {
log.debug("Queueing policy run {} under resource pressure", runId);
jobQueue.queueJob(
runId,
RUN_RESOURCE_WEIGHT,
() -> {
task.run();
return null;
},
0L)
.exceptionally(ex -> failRejectedRun(run, completion, ex));
} else {
asyncExecutor.execute(task);
}
return new PolicyRunHandle(runId, completion);
}
/**
* Run a stored policy on demand. Builds the policy's pipeline and submits it. {@code enabled}
* gates automatic triggering, not explicit runs, so this runs regardless of that flag.
*/
public PolicyRunHandle runPolicy(
Policy policy, PolicyInputs inputs, PolicyProgressListener listener) {
return submit(policy.toDefinition(), inputs, listener);
}
public PolicyRun getRun(String runId) {
return registry.get(runId);
}
/**
* Request cancellation of a run. Stage 1 marks the run cancelled in the registry if it has not
* already finished; interrupting an in-flight tool call lands in a later stage.
*/
public boolean cancel(String runId) {
PolicyRun run = registry.get(runId);
if (run == null) {
return false;
}
boolean cancelled = run.cancel();
if (cancelled) {
taskManager.addNote(runId, "Run cancelled by request");
}
return cancelled;
}
/**
* Resume a run paused in {@code WAITING_FOR_INPUT}. Not yet implemented; the run shape and
* {@link WaitState} snapshot are in place so this can be added without reworking the engine.
*/
public String resume(String runId, List<Resource> additionalInputs) {
throw new UnsupportedOperationException("Pause/resume is not yet implemented");
}
private void runToCompletion(
PolicyRun run,
PolicyInputs inputs,
PolicyProgressListener listener,
CompletableFuture<PolicyRun> completion) {
String runId = run.getRunId();
try {
run.markRunning();
PolicyExecutionResult result =
stepExecutor.execute(run.getDefinition(), inputs, listener);
OutputSpec output = run.getDefinition().output();
List<ResultFile> outputs = sinkFor(output).deliver(runId, result.files(), output);
taskManager.setMultipleFileResults(runId, outputs);
taskManager.setComplete(runId);
run.complete(outputs);
} catch (PolicyInputRequiredException e) {
// Designed-for path: suspend the run rather than fail it. Persist intermediates as
// fileIds so the run can resume after this worker thread is gone.
WaitState wait = suspend(e);
run.waitForInput(wait);
taskManager.addNote(runId, "Waiting for input: " + e.getMessage());
} catch (InternalApiTimeoutException e) {
String message = toolTimeoutMessage(e);
log.error(
"Policy run {} timed out on {}: {}",
runId,
e.getEndpointPath(),
e.getMessage());
run.fail(message);
taskManager.setError(runId, message);
} catch (Exception e) {
String message = "Policy run failed: " + e.getMessage();
log.error("Policy run {} failed", runId, e);
run.fail(message);
taskManager.setError(runId, message);
} finally {
// Always resolve the handle with the run's final state so stream/await callers unblock.
completion.complete(run);
}
}
private ResponseEntity<?> failRejectedRun(
PolicyRun run, CompletableFuture<PolicyRun> completion, Throwable ex) {
// Only reached if the run never started (e.g. the queue was full). A run that started
// always resolves its own completion in runToCompletion.
if (!completion.isDone()) {
String message = "Policy run could not be queued: " + ex.getMessage();
log.error("Policy run {} was not admitted: {}", run.getRunId(), ex.getMessage());
run.fail(message);
taskManager.setError(run.getRunId(), message);
completion.complete(run);
}
return null;
}
private WaitState suspend(PolicyInputRequiredException e) {
List<String> fileIds = new ArrayList<>();
for (Resource resource : e.getPendingFiles()) {
String name = resource.getFilename() != null ? resource.getFilename() : "pending";
try (InputStream is = resource.getInputStream()) {
fileIds.add(fileStorage.storeInputStream(is, name).fileId());
} catch (IOException io) {
log.warn("Failed to persist pending file for paused run: {}", io.getMessage());
}
}
return new WaitState(e.getMessage(), e.getResumeStepIndex(), fileIds);
}
private PolicyProgressListener trackingListener(
String runId, PolicyRun run, PolicyProgressListener delegate) {
return new PolicyProgressListener() {
@Override
public void onStepStart(int stepIndex, int stepCount, String operation) {
run.enterStep(stepIndex);
taskManager.addNote(
runId,
"Step " + stepIndex + "/" + stepCount + ": " + operation + " started");
delegate.onStepStart(stepIndex, stepCount, operation);
}
@Override
public void onStepComplete(int stepIndex, int stepCount, String operation) {
taskManager.addNote(
runId,
"Step " + stepIndex + "/" + stepCount + ": " + operation + " completed");
delegate.onStepComplete(stepIndex, stepCount, operation);
}
@Override
public void onHeartbeat() {
delegate.onHeartbeat();
}
};
}
private PolicyOutputSink sinkFor(OutputSpec spec) {
return outputSinks.stream()
.filter(sink -> sink.supports(spec))
.findFirst()
.orElseThrow(
() ->
new IllegalStateException(
"No output sink supports spec: "
+ (spec == null ? "<null>" : spec.type())));
}
private static String toolTimeoutMessage(InternalApiTimeoutException e) {
return String.format(
"The %s tool did not respond within %d seconds and was aborted.",
e.getEndpointPath(), e.getReadTimeout().toSeconds());
}
}
@@ -0,0 +1,17 @@
package stirling.software.proprietary.policy.engine;
import java.util.List;
import org.springframework.core.io.Resource;
import tools.jackson.databind.JsonNode;
/**
* Result of running a pipeline through {@link PolicyExecutor}.
*
* <p>{@code files} are the final output resources (temp files, not yet stored to {@code
* FileStorage}). {@code report} is the structured metadata payload captured from the last step that
* produced one (a JSON body, or an {@code X-Stirling-Tool-Report} header), with {@code reportTool}
* naming the step it came from; both are null when no step produced a report.
*/
public record PolicyExecutionResult(List<Resource> files, JsonNode report, String reportTool) {}
@@ -0,0 +1,312 @@
package stirling.software.proprietary.policy.engine;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import stirling.software.common.service.InternalApiClient;
import stirling.software.common.service.InternalApiTimeoutException;
import stirling.software.common.service.ToolMetadataService;
import stirling.software.common.util.TempFileManager;
import stirling.software.common.util.ZipExtractionUtils;
import stirling.software.proprietary.policy.model.PipelineDefinition;
import stirling.software.proprietary.policy.model.PipelineStep;
import stirling.software.proprietary.policy.model.PolicyInputs;
import stirling.software.proprietary.policy.progress.PolicyProgressListener;
import stirling.software.proprietary.service.AiToolResponseHeaders;
import tools.jackson.core.JacksonException;
import tools.jackson.databind.JsonNode;
import tools.jackson.databind.ObjectMapper;
/**
* Runs an ordered chain of tool steps, chaining each step's output files into the next step's
* input.
*
* <p>This is the single execution loop for the proprietary surface (AI plans now;
* manually-triggered runs and watched folders later). Each step is dispatched synchronously via
* {@link InternalApiClient} loopback HTTP: the tool runs in its own handler and returns its file
* inline. The caller decides how to run the executor itself (the AI turn loop calls it directly;
* the engine runs it on a virtual thread for async runs). Files cross step boundaries as {@link
* Resource} temp files; they are only persisted to durable storage at the run boundaries by the
* caller.
*/
@Slf4j
@Service
@RequiredArgsConstructor
public class PolicyExecutor {
private static final String FILTER_OPERATION_PREFIX = "/api/v1/filter/filter-";
private final InternalApiClient internalApiClient;
private final ToolMetadataService toolMetadataService;
private final TempFileManager tempFileManager;
private final ObjectMapper objectMapper;
/**
* Internal value-class for tool responses. {@code files} holds any result files (typically one;
* multiple for ZIP-response tools). {@code report} holds an optional structured metadata
* payload the tool chose to surface alongside (or instead of) a file.
*/
private record ToolResult(List<Resource> files, JsonNode report) {}
/**
* Execute every step in {@code definition} in order, feeding each step's output into the next.
* Supporting files supplied in {@code inputs} are bound to steps' named file fields and never
* enter the document stream.
*
* @param definition the pipeline to run (must have at least one step)
* @param inputs the primary documents plus the named supporting-file store
* @param listener receives per-step progress
* @return the final output files plus the last structured report produced, if any
* @throws InternalApiTimeoutException if a tool does not respond within its read timeout
* @throws IOException if a tool returns a non-OK response, references a missing supporting
* file, or a file cannot be read
*/
public PolicyExecutionResult execute(
PipelineDefinition definition, PolicyInputs inputs, PolicyProgressListener listener)
throws IOException {
List<PipelineStep> steps = definition.steps();
if (steps.isEmpty()) {
throw new IllegalArgumentException("Pipeline definition has no steps");
}
List<Resource> currentFiles = inputs.primary();
Map<String, List<Resource>> supportingFiles = inputs.supportingFiles();
// Propagate the *last* non-null report; the terminal step defines the output.
JsonNode lastReport = null;
String lastReportTool = null;
for (int i = 0; i < steps.size(); i++) {
PipelineStep step = steps.get(i);
String operation = step.operation();
if (operation == null || operation.isBlank()) {
throw new IllegalArgumentException(
"Pipeline step " + (i + 1) + " has no operation");
}
listener.onStepStart(i + 1, steps.size(), operation);
ToolResult stepResult = executeStep(step, currentFiles, supportingFiles);
currentFiles = stepResult.files();
if (stepResult.report() != null) {
lastReport = stepResult.report();
lastReportTool = operation;
}
listener.onStepComplete(i + 1, steps.size(), operation);
}
return new PolicyExecutionResult(currentFiles, lastReport, lastReportTool);
}
/**
* Execute a single tool step. If the endpoint accepts multiple files, all files are sent in one
* call. Otherwise, the endpoint is called once per file. ZIP responses are unpacked so each
* inner file is treated as its own result (e.g. split outputs a ZIP of pages).
*
* <p>A structured {@code report} may be returned alongside (or instead of) files; see {@link
* ToolResult}. For per-file dispatch (single-input endpoints called once per input), the first
* non-null report wins.
*/
private ToolResult executeStep(
PipelineStep step,
List<Resource> inputFiles,
Map<String, List<Resource>> supportingFiles)
throws IOException {
requireAcceptedTypes(step.operation(), inputFiles);
List<Resource> files = new ArrayList<>();
JsonNode report = null;
if (toolMetadataService.isMultiInput(step.operation())) {
ToolResult r = callEndpoint(step, inputFiles, supportingFiles);
files.addAll(r.files());
report = r.report();
} else {
for (Resource file : inputFiles) {
ToolResult r = callEndpoint(step, List.of(file), supportingFiles);
files.addAll(r.files());
if (report == null) {
report = r.report();
}
}
}
return new ToolResult(files, report);
}
/**
* Call an endpoint and return its result files and optional report.
*
* <ul>
* <li>JSON body (Content-Type: application/json): the entire body is the report, no files are
* returned.
* <li>File body (PDF etc.): the file is returned; if an {@link
* AiToolResponseHeaders#TOOL_REPORT} header is present, its (minified JSON) value is
* parsed as the report.
* <li>ZIP responses declared by the tool metadata service are unpacked so callers always see
* a flat list of result files.
* </ul>
*/
private ToolResult callEndpoint(
PipelineStep step, List<Resource> files, Map<String, List<Resource>> supportingFiles)
throws IOException {
String endpointPath = step.operation();
MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
for (Resource file : files) {
body.add("fileInput", file);
}
// Bind supporting files to their named tool fields (e.g. stampImage, overlayFiles). These
// come from the run's named asset store, not the document stream.
for (Map.Entry<String, String> binding : step.fileParameters().entrySet()) {
String fieldName = binding.getKey();
String assetKey = binding.getValue();
List<Resource> assets = supportingFiles.get(assetKey);
if (assets == null || assets.isEmpty()) {
throw new IOException(
"Step "
+ endpointPath
+ " references supporting file '"
+ assetKey
+ "' for field '"
+ fieldName
+ "' but no such file was provided");
}
for (Resource asset : assets) {
body.add(fieldName, asset);
}
}
for (Map.Entry<String, Object> entry : step.parameters().entrySet()) {
if (entry.getValue() instanceof List<?> list) {
if (containsStructuredElements(list)) {
// Endpoints binding lists of structured objects (e.g. /security/redact's
// redactions, /general/edit-text's edits) parse a single JSON string field via
// a property editor. Pre-serialize the whole list so binding succeeds.
body.add(entry.getKey(), objectMapper.writeValueAsString(list));
} else {
for (Object item : list) {
body.add(entry.getKey(), item);
}
}
} else {
body.add(entry.getKey(), entry.getValue());
}
}
ResponseEntity<Resource> response = internalApiClient.post(endpointPath, body);
if (!HttpStatus.OK.equals(response.getStatusCode()) || response.getBody() == null) {
throw new IOException(
"Tool returned HTTP " + response.getStatusCode() + " for " + endpointPath);
}
Resource resource = response.getBody();
// Filter operations return an empty body to signal the file was filtered out: drop it
// rather than forwarding a zero-byte document.
if (isFilterOperation(endpointPath) && isEmpty(resource)) {
return new ToolResult(List.of(), null);
}
HttpHeaders headers = response.getHeaders();
MediaType contentType = headers.getContentType();
// JSON-only response: the whole body is the structured report, no result file.
if (contentType != null && MediaType.APPLICATION_JSON.isCompatibleWith(contentType)) {
try (InputStream is = resource.getInputStream()) {
JsonNode report = objectMapper.readTree(is);
return new ToolResult(List.of(), report);
}
}
JsonNode report = parseReportHeader(headers, endpointPath);
if (toolMetadataService.shouldUnpackZipResponse(endpointPath)) {
return new ToolResult(ZipExtractionUtils.extractZip(resource, tempFileManager), report);
}
return new ToolResult(List.of(resource), report);
}
/**
* Parse the optional {@link AiToolResponseHeaders#TOOL_REPORT} header into a {@link JsonNode},
* or return null.
*/
private JsonNode parseReportHeader(HttpHeaders headers, String endpointPath) {
String raw = headers.getFirst(AiToolResponseHeaders.TOOL_REPORT);
if (raw == null || raw.isBlank()) {
return null;
}
try {
return objectMapper.readTree(raw);
} catch (JacksonException e) {
log.warn(
"Ignoring malformed {} header from {}: {}",
AiToolResponseHeaders.TOOL_REPORT,
endpointPath,
e.getMessage());
return null;
}
}
private static boolean containsStructuredElements(List<?> list) {
for (Object item : list) {
if (item instanceof Map<?, ?> || item instanceof List<?>) {
return true;
}
}
return false;
}
/**
* Fail the run if any document in the primary stream is not a file type the step accepts. An
* endpoint that declares no specific input type accepts anything.
*/
private void requireAcceptedTypes(String operation, List<Resource> files) throws IOException {
List<String> accepted = toolMetadataService.getExtensionTypes(false, operation);
if (accepted == null || accepted.isEmpty()) {
return;
}
for (Resource file : files) {
if (!matchesType(file, accepted)) {
throw new IOException(
"Step "
+ operation
+ " accepts "
+ accepted
+ " but received '"
+ file.getFilename()
+ "'");
}
}
}
private static boolean matchesType(Resource file, List<String> acceptedExtensions) {
String filename = file.getFilename();
if (filename == null) {
return false;
}
int dot = filename.lastIndexOf('.');
if (dot < 0 || dot == filename.length() - 1) {
return false;
}
return acceptedExtensions.contains(filename.substring(dot + 1).toLowerCase(Locale.ROOT));
}
private static boolean isFilterOperation(String operation) {
return operation.startsWith(FILTER_OPERATION_PREFIX);
}
private static boolean isEmpty(Resource resource) {
try {
return resource.contentLength() == 0;
} catch (IOException e) {
return false;
}
}
}
@@ -0,0 +1,32 @@
package stirling.software.proprietary.policy.engine;
import java.util.List;
import org.springframework.core.io.Resource;
import lombok.Getter;
/**
* Thrown by a step to signal that the run cannot proceed without further user input, pausing the
* run in {@code WAITING_FOR_INPUT} rather than failing it.
*
* <p>Carries everything needed to resume: a human-readable reason, the 0-based index of the step to
* resume from, and the intermediate files produced so far. The engine persists those files and
* suspends the run.
*
* <p>Defined now to fix the run shape; no step throws it yet, and the resume handshake is
* implemented in a later stage.
*/
@Getter
public class PolicyInputRequiredException extends RuntimeException {
private final transient List<Resource> pendingFiles;
private final int resumeStepIndex;
public PolicyInputRequiredException(
String reason, int resumeStepIndex, List<Resource> pendingFiles) {
super(reason);
this.resumeStepIndex = resumeStepIndex;
this.pendingFiles = pendingFiles == null ? List.of() : pendingFiles;
}
}
@@ -0,0 +1,16 @@
package stirling.software.proprietary.policy.engine;
import java.util.concurrent.CompletableFuture;
import stirling.software.proprietary.policy.model.PolicyRun;
/**
* Returned by {@link PolicyEngine#submit}: the run id (for status polling and result download) plus
* a future that resolves when the run reaches a terminal or paused state.
*
* <p>The completion future lets callers react to the end of a run (e.g. an SSE endpoint sending a
* final event and closing the stream) without polling. It carries the {@link PolicyRun} whose
* status describes the outcome (completed, failed, cancelled, or waiting for input); it does not
* complete exceptionally for ordinary run failures.
*/
public record PolicyRunHandle(String runId, CompletableFuture<PolicyRun> completion) {}
@@ -0,0 +1,97 @@
package stirling.software.proprietary.policy.engine;
import java.time.Duration;
import java.time.Instant;
import java.util.Collection;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import jakarta.annotation.PreDestroy;
import lombok.extern.slf4j.Slf4j;
import stirling.software.proprietary.policy.model.PolicyRun;
/**
* In-memory store of live {@link PolicyRun} state, keyed by runId. Holds the authoritative run
* state machine; durable status/files for download are projected separately into {@code
* TaskManager}.
*
* <p>Finished runs are evicted on a fixed interval once they age past {@code
* stirling.policies.runExpiryMinutes}, mirroring the job-result expiry in {@code TaskManager} so a
* run's rich in-memory state does not outlive the process. Only terminal runs are evicted; active
* and paused ({@code WAITING_FOR_INPUT}) runs are retained regardless of age. Result files are not
* touched here: a run shares its runId with a {@code TaskManager} job, which owns file-lifecycle
* cleanup, so eviction only frees this map's entry.
*/
@Slf4j
@Service
public class PolicyRunRegistry {
private final Map<String, PolicyRun> runs = new ConcurrentHashMap<>();
private final Duration runExpiry;
private final ScheduledExecutorService cleanupExecutor =
Executors.newSingleThreadScheduledExecutor(
Thread.ofVirtual().name("policy-run-cleanup-", 0).factory());
public PolicyRunRegistry(
@Value("${stirling.policies.runExpiryMinutes:30}") int runExpiryMinutes) {
this.runExpiry = Duration.ofMinutes(runExpiryMinutes);
cleanupExecutor.scheduleAtFixedRate(this::evictExpiredRuns, 10, 10, TimeUnit.MINUTES);
log.debug(
"Policy run registry initialized with run expiry of {} minutes", runExpiryMinutes);
}
public void register(PolicyRun run) {
runs.put(run.getRunId(), run);
}
public PolicyRun get(String runId) {
return runs.get(runId);
}
public Collection<PolicyRun> all() {
return runs.values();
}
/** Scheduled hook: evict terminal runs that finished before the expiry window. */
private void evictExpiredRuns() {
try {
evictExpired(Instant.now().minus(runExpiry));
} catch (Exception e) {
log.error("Error during policy run cleanup: {}", e.getMessage(), e);
}
}
/**
* Remove every terminal run last updated before {@code cutoff}; active and paused runs are kept
* regardless of age. Returns the number evicted. Package-visible so the scheduled sweep and
* tests exercise the same path with an explicit cutoff.
*/
int evictExpired(Instant cutoff) {
int removed = 0;
for (Map.Entry<String, PolicyRun> entry : runs.entrySet()) {
PolicyRun run = entry.getValue();
if (run.getStatus().isTerminal() && run.getUpdatedAt().isBefore(cutoff)) {
runs.remove(entry.getKey());
removed++;
}
}
if (removed > 0) {
log.info("Evicted {} expired policy runs", removed);
}
return removed;
}
@PreDestroy
void shutdown() {
cleanupExecutor.shutdownNow();
}
}
@@ -0,0 +1,21 @@
package stirling.software.proprietary.policy.model;
import java.util.Map;
/**
* Describes where a pipeline run's output files should be delivered. {@code type} selects a {@code
* PolicyOutputSink} (e.g. "inline"); {@code options} carries sink-specific configuration.
*
* <p>New destinations (folder, S3) are added as new sink beans keyed on a new {@code type} without
* changing this shape or the engine.
*/
public record OutputSpec(String type, Map<String, Object> options) {
public OutputSpec {
options = options == null ? Map.of() : options;
}
/** The default destination: store outputs and return them to the caller for download. */
public static OutputSpec inline() {
return new OutputSpec("inline", Map.of());
}
}
@@ -0,0 +1,16 @@
package stirling.software.proprietary.policy.model;
import java.util.List;
/**
* An ordered chain of tool steps plus where the output should go.
*
* <p>This is the single shape executed by the policy engine, shared by AI plans, manually-triggered
* runs, and (later) watched folders. {@code output} may be null for callers that handle result
* files themselves (e.g. the AI workflow, which builds its own response payload).
*/
public record PipelineDefinition(String name, List<PipelineStep> steps, OutputSpec output) {
public PipelineDefinition {
steps = steps == null ? List.of() : steps;
}
}
@@ -0,0 +1,30 @@
package stirling.software.proprietary.policy.model;
import java.util.Map;
/**
* A single tool invocation in a pipeline: the API endpoint path to call and the inputs to pass.
*
* <p>{@code operation} is a Stirling tool endpoint path (e.g. {@code /api/v1/misc/compress-pdf}),
* matching the dispatch convention used by {@code InternalApiClient}. {@code parameters} are the
* tool-specific scalar form fields.
*
* <p>{@code fileParameters} binds a tool's named file fields (beyond the primary {@code fileInput}
* stream) to supporting files supplied with the run: it maps the form field name (e.g. {@code
* stampImage}, {@code overlayFiles}) to an asset key in the run's supporting-file store. This keeps
* supporting inputs (a stamp image, a certificate, an overlay) out of the document stream that
* flows step to step.
*/
public record PipelineStep(
String operation, Map<String, Object> parameters, Map<String, String> fileParameters) {
public PipelineStep {
parameters = parameters == null ? Map.of() : parameters;
fileParameters = fileParameters == null ? Map.of() : fileParameters;
}
/** A step with no supporting-file bindings. */
public PipelineStep(String operation, Map<String, Object> parameters) {
this(operation, parameters, Map.of());
}
}
@@ -0,0 +1,38 @@
package stirling.software.proprietary.policy.model;
import java.util.List;
/**
* A stored, owned automation: how it is triggered, the ordered tool steps to run, and where its
* output goes, plus identity and metadata.
*
* <p>This is the central object of the feature. Everything that runs a chain of tools is a use of a
* Policy: a watched folder is a Policy with a folder {@link TriggerConfig} and a folder {@link
* OutputSpec}; a scheduled job is a Policy with a schedule trigger; manual/Automate/AI runs execute
* a Policy (or an ad-hoc {@link PipelineDefinition}) on demand. The engine itself only ever
* executes the {@link PipelineDefinition} this exposes via {@link #toDefinition()} - it is
* trigger-agnostic.
*
* <p>{@code enabled} gates automatic triggering (a disabled policy is not picked up by its
* trigger); it does not block an explicit manual run.
*/
public record Policy(
String id,
String name,
String owner,
boolean enabled,
TriggerConfig trigger,
List<PipelineStep> steps,
OutputSpec output) {
public Policy {
trigger = trigger == null ? TriggerConfig.manual() : trigger;
steps = steps == null ? List.of() : steps;
output = output == null ? OutputSpec.inline() : output;
}
/** The engine-level, trigger-agnostic view of this policy's pipeline. */
public PipelineDefinition toDefinition() {
return new PipelineDefinition(name, steps, output);
}
}
@@ -0,0 +1,32 @@
package stirling.software.proprietary.policy.model;
import java.util.List;
import java.util.Map;
import org.springframework.core.io.Resource;
/**
* The files a run operates on, split into two roles:
*
* <ul>
* <li>{@code primary} - the documents that flow through the pipeline, each step's output becoming
* the next step's input.
* <li>{@code supportingFiles} - a named store of auxiliary files (a stamp image, certificate,
* overlay, attachments) that steps bind to their named file fields via {@link
* PipelineStep#fileParameters()}. These never enter the document stream.
* </ul>
*
* Asset values are lists so a single key can carry multi-file fields (e.g. attachments).
*/
public record PolicyInputs(List<Resource> primary, Map<String, List<Resource>> supportingFiles) {
public PolicyInputs {
primary = primary == null ? List.of() : primary;
supportingFiles = supportingFiles == null ? Map.of() : supportingFiles;
}
/** Inputs with primary documents only and no supporting files. */
public static PolicyInputs of(List<Resource> primary) {
return new PolicyInputs(primary, Map.of());
}
}
@@ -0,0 +1,87 @@
package stirling.software.proprietary.policy.model;
import java.time.Instant;
import java.util.List;
import lombok.Getter;
import stirling.software.common.model.job.ResultFile;
/**
* Live, mutable state of a single pipeline run, held in memory by {@code PolicyRunRegistry}.
*
* <p>This carries the rich execution state (status, step cursor, wait state) that the job system's
* {@code JobResult} does not model. The run is also projected into {@code TaskManager} for
* cluster-visible status, progress notes, and file download; this object is the authoritative
* source of the state machine.
*/
@Getter
public class PolicyRun {
private final String runId;
private final PipelineDefinition definition;
private final Instant createdAt = Instant.now();
private volatile PolicyRunStatus status = PolicyRunStatus.PENDING;
/** 1-based index of the step currently running (0 before the run starts). */
private volatile int currentStep = 0;
private volatile WaitState waitState;
private volatile String error;
private volatile List<ResultFile> outputs = List.of();
private volatile Instant updatedAt = Instant.now();
public PolicyRun(String runId, PipelineDefinition definition) {
this.runId = runId;
this.definition = definition;
}
public int stepCount() {
return definition.steps().size();
}
public synchronized void markRunning() {
this.status = PolicyRunStatus.RUNNING;
touch();
}
public synchronized void enterStep(int oneBasedStepIndex) {
this.currentStep = oneBasedStepIndex;
touch();
}
public synchronized void complete(List<ResultFile> resultFiles) {
this.outputs = resultFiles == null ? List.of() : List.copyOf(resultFiles);
this.status = PolicyRunStatus.COMPLETED;
touch();
}
public synchronized void fail(String message) {
this.error = message;
this.status = PolicyRunStatus.FAILED;
touch();
}
public synchronized void waitForInput(WaitState wait) {
this.waitState = wait;
this.status = PolicyRunStatus.WAITING_FOR_INPUT;
touch();
}
/**
* Mark cancelled if the run has not already reached a terminal state. Returns whether it did.
*/
public synchronized boolean cancel() {
if (status.isTerminal()) {
return false;
}
this.status = PolicyRunStatus.CANCELLED;
touch();
return true;
}
private void touch() {
this.updatedAt = Instant.now();
}
}
@@ -0,0 +1,21 @@
package stirling.software.proprietary.policy.model;
/**
* Lifecycle states of a {@link PolicyRun}.
*
* <p>{@code WAITING_FOR_INPUT} is modelled now so the engine and run shape support pausing a run
* (e.g. a step that blocks for a human decision) without holding a thread; the resume handshake is
* implemented in a later stage.
*/
public enum PolicyRunStatus {
PENDING,
RUNNING,
WAITING_FOR_INPUT,
COMPLETED,
FAILED,
CANCELLED;
public boolean isTerminal() {
return this == COMPLETED || this == FAILED || this == CANCELLED;
}
}
@@ -0,0 +1,28 @@
package stirling.software.proprietary.policy.model;
import java.util.List;
import stirling.software.common.model.job.ResultFile;
/**
* Read-only view of a {@link PolicyRun} returned by the status endpoint. Output files are surfaced
* as {@link ResultFile} so the caller can download each via {@code GET /api/v1/general/files/{id}}.
*/
public record PolicyRunView(
String runId,
PolicyRunStatus status,
int currentStep,
int stepCount,
String error,
List<ResultFile> outputs) {
public static PolicyRunView of(PolicyRun run) {
return new PolicyRunView(
run.getRunId(),
run.getStatus(),
run.getCurrentStep(),
run.stepCount(),
run.getError(),
run.getOutputs());
}
}
@@ -0,0 +1,25 @@
package stirling.software.proprietary.policy.model;
import java.util.Map;
/**
* How a {@link Policy} is automatically triggered. {@code type} selects a trigger kind ("manual",
* "folder", "schedule", "s3"); {@code options} carries type-specific configuration (a folder path,
* a cron expression, a bucket, ...).
*
* <p>Data-driven and parallel to {@link OutputSpec}: new trigger kinds are new {@code type} values
* handled by a new trigger bean, with no change to the model. {@code "manual"} means there is no
* automatic trigger - the policy is only ever run on demand.
*/
public record TriggerConfig(String type, Map<String, Object> options) {
public TriggerConfig {
type = type == null || type.isBlank() ? "manual" : type;
options = options == null ? Map.of() : options;
}
/** No automatic trigger; the policy is run on demand only. */
public static TriggerConfig manual() {
return new TriggerConfig("manual", Map.of());
}
}
@@ -0,0 +1,19 @@
package stirling.software.proprietary.policy.model;
import java.util.List;
/**
* Captured when a run pauses in {@link PolicyRunStatus#WAITING_FOR_INPUT}. Together with the run's
* {@link PipelineDefinition} this is the resumable snapshot: {@code resumeStepIndex} is the 0-based
* step to continue from, and {@code pendingFileIds} are the intermediate files (stored in {@code
* FileStorage}, so they survive the worker thread ending or a node restart) that become the input
* to the resumed run.
*
* <p>Stored as fileIds rather than in-memory resources by design: a paused run must be resumable
* long after its worker thread has gone.
*/
public record WaitState(String reason, int resumeStepIndex, List<String> pendingFileIds) {
public WaitState {
pendingFileIds = pendingFileIds == null ? List.of() : pendingFileIds;
}
}
@@ -0,0 +1,68 @@
package stirling.software.proprietary.policy.output;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import org.springframework.core.io.Resource;
import org.springframework.http.MediaType;
import org.springframework.http.MediaTypeFactory;
import org.springframework.stereotype.Service;
import lombok.RequiredArgsConstructor;
import stirling.software.common.model.job.ResultFile;
import stirling.software.common.service.FileStorage;
import stirling.software.proprietary.policy.model.OutputSpec;
/**
* Default output sink: stores each output file in {@code FileStorage} so it is downloadable via
* {@code GET /api/v1/general/files/{fileId}}. This is the destination for manually-triggered runs
* whose results are returned to the caller.
*/
@Service
@RequiredArgsConstructor
public class InlineOutputSink implements PolicyOutputSink {
private static final String TYPE = "inline";
private final FileStorage fileStorage;
@Override
public String type() {
return TYPE;
}
@Override
public boolean supports(OutputSpec spec) {
return spec == null || spec.type() == null || TYPE.equals(spec.type());
}
@Override
public List<ResultFile> deliver(String runId, List<Resource> outputs, OutputSpec spec)
throws IOException {
List<ResultFile> results = new ArrayList<>();
for (int i = 0; i < outputs.size(); i++) {
Resource resource = outputs.get(i);
String name =
resource.getFilename() != null ? resource.getFilename() : "result-" + (i + 1);
String contentType =
MediaTypeFactory.getMediaType(name)
.orElse(MediaType.APPLICATION_OCTET_STREAM)
.toString();
FileStorage.StoredFile stored;
try (InputStream is = resource.getInputStream()) {
stored = fileStorage.storeInputStream(is, name);
}
results.add(
ResultFile.builder()
.fileId(stored.fileId())
.fileName(name)
.contentType(contentType)
.fileSize(stored.size())
.build());
}
return results;
}
}
@@ -0,0 +1,35 @@
package stirling.software.proprietary.policy.output;
import java.io.IOException;
import java.util.List;
import org.springframework.core.io.Resource;
import stirling.software.common.model.job.ResultFile;
import stirling.software.proprietary.policy.model.OutputSpec;
/**
* Delivers a finished run's output files to a destination, returning durable {@link ResultFile}
* descriptors (fileId + metadata) for the run record.
*
* <p>Implementations are Spring beans selected by {@link #supports(OutputSpec)}. New destinations
* (folder, S3) are added as new beans without changing the engine.
*/
public interface PolicyOutputSink {
/** Stable identifier for this sink, matching {@code OutputSpec.type()} (e.g. "inline"). */
String type();
/** Whether this sink can handle the given output spec. */
boolean supports(OutputSpec spec);
/**
* Persist/deliver the output files and return their descriptors.
*
* @param runId the run these outputs belong to
* @param outputs the final pipeline output resources
* @param spec the requested destination
*/
List<ResultFile> deliver(String runId, List<Resource> outputs, OutputSpec spec)
throws IOException;
}
@@ -0,0 +1,22 @@
package stirling.software.proprietary.policy.progress;
/**
* Receives live progress as a pipeline run executes. Implementations forward to an SSE stream,
* write job notes for polling, or both. Step indices are 1-based.
*
* <p>All methods default to no-ops so callers implement only what they surface.
*/
public interface PolicyProgressListener {
/** A listener that ignores all progress. */
PolicyProgressListener NOOP = new PolicyProgressListener() {};
/** Called immediately before step {@code stepIndex} of {@code stepCount} begins. */
default void onStepStart(int stepIndex, int stepCount, String operation) {}
/** Called immediately after step {@code stepIndex} of {@code stepCount} completes. */
default void onStepComplete(int stepIndex, int stepCount, String operation) {}
/** Called on a keep-alive tick so downstream connections can detect disconnects promptly. */
default void onHeartbeat() {}
}
@@ -0,0 +1,61 @@
package stirling.software.proprietary.policy.store;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import stirling.software.proprietary.policy.model.Policy;
/**
* In-memory {@link PolicyStore}. Not the runtime bean - {@link JpaPolicyStore} is the durable
* store. Kept as a lightweight, dependency-free implementation for tests and for any future no-
* database mode.
*/
public class InProcessPolicyStore implements PolicyStore {
private final Map<String, Policy> policies = new ConcurrentHashMap<>();
@Override
public Policy save(Policy policy) {
String id =
policy.id() == null || policy.id().isBlank()
? UUID.randomUUID().toString()
: policy.id();
Policy stored =
new Policy(
id,
policy.name(),
policy.owner(),
policy.enabled(),
policy.trigger(),
policy.steps(),
policy.output());
policies.put(id, stored);
return stored;
}
@Override
public Optional<Policy> get(String id) {
return Optional.ofNullable(policies.get(id));
}
@Override
public List<Policy> all() {
return List.copyOf(policies.values());
}
@Override
public List<Policy> findByTriggerType(String triggerType) {
return policies.values().stream()
.filter(Policy::enabled)
.filter(policy -> triggerType.equals(policy.trigger().type()))
.toList();
}
@Override
public boolean delete(String id) {
return policies.remove(id) != null;
}
}
@@ -0,0 +1,83 @@
package stirling.software.proprietary.policy.store;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import org.springframework.stereotype.Service;
import lombok.RequiredArgsConstructor;
import stirling.software.proprietary.policy.model.Policy;
import tools.jackson.databind.ObjectMapper;
/**
* Durable {@link PolicyStore} backed by JPA. The runtime store whenever the proprietary module runs
* (a datasource is always present). Policies are persisted as JSON via {@link PolicyEntity}; the
* scalar columns are kept in sync for querying.
*/
@Service
@RequiredArgsConstructor
public class JpaPolicyStore implements PolicyStore {
private final PolicyRepository repository;
private final ObjectMapper objectMapper;
@Override
public Policy save(Policy policy) {
String id =
policy.id() == null || policy.id().isBlank()
? UUID.randomUUID().toString()
: policy.id();
Policy stored =
new Policy(
id,
policy.name(),
policy.owner(),
policy.enabled(),
policy.trigger(),
policy.steps(),
policy.output());
PolicyEntity entity = new PolicyEntity();
entity.setId(id);
entity.setName(stored.name());
entity.setOwner(stored.owner());
entity.setEnabled(stored.enabled());
entity.setTriggerType(stored.trigger().type());
entity.setPolicyJson(objectMapper.writeValueAsString(stored));
repository.save(entity);
return stored;
}
@Override
public Optional<Policy> get(String id) {
return repository.findById(id).map(this::toPolicy);
}
@Override
public List<Policy> all() {
return repository.findAll().stream().map(this::toPolicy).toList();
}
@Override
public List<Policy> findByTriggerType(String triggerType) {
return repository.findByTriggerTypeAndEnabledTrue(triggerType).stream()
.map(this::toPolicy)
.toList();
}
@Override
public boolean delete(String id) {
if (!repository.existsById(id)) {
return false;
}
repository.deleteById(id);
return true;
}
private Policy toPolicy(PolicyEntity entity) {
return objectMapper.readValue(entity.getPolicyJson(), Policy.class);
}
}
@@ -0,0 +1,50 @@
package stirling.software.proprietary.policy.store;
import java.io.Serializable;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
/**
* JPA row for a {@link stirling.software.proprietary.policy.model.Policy}.
*
* <p>The whole policy is stored as JSON in {@code policyJson} (authoritative on read, and the same
* serialization the API uses); the scalar columns are denormalized copies for querying - notably
* {@code triggerType} + {@code enabled} so background triggers can fetch their policies. Ownership
* is a plain {@code owner} string rather than a foreign key, to stay decoupled from the security
* entities; richer team scoping can be layered on later.
*/
@Entity
@Table(name = "policies")
@NoArgsConstructor
@Getter
@Setter
public class PolicyEntity implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Column(name = "id")
private String id;
@Column(name = "name")
private String name;
@Column(name = "owner")
private String owner;
@Column(name = "enabled")
private boolean enabled;
@Column(name = "trigger_type")
private String triggerType;
@Column(name = "policy_json", columnDefinition = "text")
private String policyJson;
}
@@ -0,0 +1,13 @@
package stirling.software.proprietary.policy.store;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface PolicyRepository extends JpaRepository<PolicyEntity, String> {
/** Enabled policies of a given trigger type, for background triggers to activate. */
List<PolicyEntity> findByTriggerTypeAndEnabledTrue(String triggerType);
}
@@ -0,0 +1,28 @@
package stirling.software.proprietary.policy.store;
import java.util.List;
import java.util.Optional;
import stirling.software.proprietary.policy.model.Policy;
/**
* Stores {@link Policy} definitions. The in-memory implementation backs simple deployments now; a
* durable (JPA) implementation can replace it behind this interface without touching callers.
*/
public interface PolicyStore {
/** Create or update a policy. A blank/absent id is assigned; returns the stored policy. */
Policy save(Policy policy);
Optional<Policy> get(String id);
List<Policy> all();
/**
* Enabled policies whose automatic trigger is of the given type (used by background triggers).
*/
List<Policy> findByTriggerType(String triggerType);
/** Remove a policy; returns whether it existed. */
boolean delete(String id);
}
@@ -0,0 +1,41 @@
package stirling.software.proprietary.policy.trigger;
import org.springframework.stereotype.Service;
import lombok.RequiredArgsConstructor;
import stirling.software.proprietary.policy.engine.PolicyEngine;
import stirling.software.proprietary.policy.engine.PolicyRunHandle;
import stirling.software.proprietary.policy.model.PipelineDefinition;
import stirling.software.proprietary.policy.model.Policy;
import stirling.software.proprietary.policy.model.PolicyInputs;
import stirling.software.proprietary.policy.progress.PolicyProgressListener;
/**
* Runs policies on demand, in response to a request (the {@code PolicyController} endpoints, an AI,
* or another automation). It is the request-driven trigger: no background lifecycle, it just
* forwards to the engine. Any policy can be run manually regardless of its configured trigger type.
*/
@Service
@RequiredArgsConstructor
public class ManualTrigger implements PolicyTrigger {
private final PolicyEngine policyEngine;
@Override
public String type() {
return "manual";
}
/** Run a stored policy immediately and return its run handle. */
public PolicyRunHandle run(
Policy policy, PolicyInputs inputs, PolicyProgressListener listener) {
return policyEngine.runPolicy(policy, inputs, listener);
}
/** Run an ad-hoc pipeline (no stored policy), e.g. for AI or Automate one-offs. */
public PolicyRunHandle fire(
PipelineDefinition definition, PolicyInputs inputs, PolicyProgressListener listener) {
return policyEngine.submit(definition, inputs, listener);
}
}
@@ -0,0 +1,24 @@
package stirling.software.proprietary.policy.trigger;
/**
* Activates policies of one trigger type. A trigger owns a {@link #type()} (matching {@code
* TriggerConfig.type()}); when its condition fires it runs the relevant {@code Policy} through the
* {@code PolicyEngine}.
*
* <p>Background triggers (folder watcher, schedule) are driven by configuration: on {@link
* #start()} they begin watching/scheduling for the policies returned by {@code
* PolicyStore.findByTriggerType(type())}, and stop on {@link #stop()}. Request-driven triggers
* (manual) have no background lifecycle and run a policy directly in response to a call. New
* trigger kinds are new beans of this type; the engine and the {@code Policy} model do not change.
*/
public interface PolicyTrigger {
/** Stable identifier for this trigger kind, matching {@code TriggerConfig.type()}. */
String type();
/** Begin activating policies of this type (e.g. start a folder watcher). No-op for manual. */
default void start() {}
/** Stop activating and release any resources. */
default void stop() {}
}
@@ -31,13 +31,15 @@ import stirling.software.common.model.exception.UnsupportedProviderException;
"stirling.software.proprietary.security.repository",
"stirling.software.proprietary.repository",
"stirling.software.proprietary.storage.repository",
"stirling.software.proprietary.workflow.repository"
"stirling.software.proprietary.workflow.repository",
"stirling.software.proprietary.policy.store"
})
@EntityScan({
"stirling.software.proprietary.security.model",
"stirling.software.proprietary.model",
"stirling.software.proprietary.storage.model",
"stirling.software.proprietary.workflow.model"
"stirling.software.proprietary.workflow.model",
"stirling.software.proprietary.policy.store"
})
public class DatabaseConfig {
@@ -14,14 +14,9 @@ import org.apache.pdfbox.pdmodel.PDDocument;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.MediaTypeFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.multipart.MultipartFile;
import io.github.pixee.security.Filenames;
@@ -32,14 +27,11 @@ import lombok.extern.slf4j.Slf4j;
import stirling.software.common.model.ApplicationProperties;
import stirling.software.common.service.CustomPDFDocumentFactory;
import stirling.software.common.service.FileStorage;
import stirling.software.common.service.InternalApiClient;
import stirling.software.common.service.InternalApiTimeoutException;
import stirling.software.common.service.ToolMetadataService;
import stirling.software.common.service.UserServiceInterface;
import stirling.software.common.util.ExceptionUtils;
import stirling.software.common.util.TempFile;
import stirling.software.common.util.TempFileManager;
import stirling.software.common.util.ZipExtractionUtils;
import stirling.software.proprietary.model.api.ai.AiConversationMessage;
import stirling.software.proprietary.model.api.ai.AiDocumentIngestRequest;
import stirling.software.proprietary.model.api.ai.AiEngineProgressDetail;
@@ -53,6 +45,13 @@ import stirling.software.proprietary.model.api.ai.AiWorkflowProgressEvent;
import stirling.software.proprietary.model.api.ai.AiWorkflowRequest;
import stirling.software.proprietary.model.api.ai.AiWorkflowResponse;
import stirling.software.proprietary.model.api.ai.AiWorkflowResultFile;
import stirling.software.proprietary.policy.engine.PolicyExecutionResult;
import stirling.software.proprietary.policy.engine.PolicyExecutor;
import stirling.software.proprietary.policy.model.OutputSpec;
import stirling.software.proprietary.policy.model.PipelineDefinition;
import stirling.software.proprietary.policy.model.PipelineStep;
import stirling.software.proprietary.policy.model.PolicyInputs;
import stirling.software.proprietary.policy.progress.PolicyProgressListener;
import stirling.software.proprietary.security.util.DesktopClientUtils;
import stirling.software.proprietary.service.PdfContentExtractor.LoadedFile;
import stirling.software.proprietary.service.PdfContentExtractor.PdfContentResult;
@@ -72,12 +71,11 @@ public class AiWorkflowService {
private final AiEngineClient aiEngineClient;
private final PdfContentExtractor pdfContentExtractor;
private final ObjectMapper objectMapper;
private final InternalApiClient internalApiClient;
private final FileStorage fileStorage;
private final ToolMetadataService toolMetadataService;
private final TempFileManager tempFileManager;
private final FileIdStrategy fileIdStrategy;
private final AiEngineEndpointResolver endpointResolver;
private final PolicyExecutor policyExecutor;
private final UserServiceInterface userService;
private final ApplicationProperties applicationProperties;
@@ -86,24 +84,22 @@ public class AiWorkflowService {
AiEngineClient aiEngineClient,
PdfContentExtractor pdfContentExtractor,
ObjectMapper objectMapper,
InternalApiClient internalApiClient,
FileStorage fileStorage,
ToolMetadataService toolMetadataService,
TempFileManager tempFileManager,
FileIdStrategy fileIdStrategy,
AiEngineEndpointResolver endpointResolver,
PolicyExecutor policyExecutor,
@Autowired(required = false) UserServiceInterface userService,
ApplicationProperties applicationProperties) {
this.pdfDocumentFactory = pdfDocumentFactory;
this.aiEngineClient = aiEngineClient;
this.pdfContentExtractor = pdfContentExtractor;
this.objectMapper = objectMapper;
this.internalApiClient = internalApiClient;
this.fileStorage = fileStorage;
this.toolMetadataService = toolMetadataService;
this.tempFileManager = tempFileManager;
this.fileIdStrategy = fileIdStrategy;
this.endpointResolver = endpointResolver;
this.policyExecutor = policyExecutor;
this.userService = userService;
this.applicationProperties = applicationProperties;
}
@@ -150,16 +146,6 @@ public class AiWorkflowService {
record Terminal(AiWorkflowResponse response) implements WorkflowState {}
}
/**
* Internal value-class for tool responses. {@code files} holds any result files (typically one;
* multiple for ZIP-response tools). {@code report} holds an optional structured metadata
* payload the tool chose to surface alongside (or instead of) a file.
*
* <p>Tools populate the report either by returning a JSON body (whole body → report) or by
* adding the {@link AiToolResponseHeaders#TOOL_REPORT} header alongside a file body.
*/
private record ToolResult(List<Resource> files, JsonNode report) {}
public AiWorkflowResponse orchestrate(AiWorkflowRequest request) throws IOException {
return orchestrate(request, NOOP_LISTENER);
}
@@ -377,7 +363,6 @@ public class AiWorkflowService {
pages.size());
}
@SuppressWarnings("unchecked")
private WorkflowState onToolCall(
AiWorkflowResponse response,
Map<String, MultipartFile> filesById,
@@ -394,8 +379,14 @@ public class AiWorkflowService {
try {
List<Resource> inputFiles = toResources(filesById);
listener.onProgress(AiWorkflowProgressEvent.executingTool(endpointPath, 1, 1));
ToolResult result = executeStep(endpointPath, parameters, inputFiles);
PipelineDefinition definition =
new PipelineDefinition(
null,
List.of(new PipelineStep(endpointPath, parameters)),
OutputSpec.inline());
PolicyExecutionResult result =
policyExecutor.execute(
definition, PolicyInputs.of(inputFiles), stepProgress(listener));
return new WorkflowState.Terminal(
buildCompletedResponse(
response.getRationale(),
@@ -469,38 +460,32 @@ public class AiWorkflowService {
cannotContinue("AI engine returned a plan with no steps."));
}
try {
List<Resource> currentFiles = toResources(filesById);
// Propagate the *last* non-null report — the terminal step defines the output.
JsonNode lastReport = null;
String lastReportTool = null;
for (int i = 0; i < steps.size(); i++) {
Map<String, Object> step = steps.get(i);
String endpointPath = (String) step.get("tool");
Map<String, Object> parameters =
step.containsKey("parameters")
? (Map<String, Object>) step.get("parameters")
: Map.of();
if (endpointPath == null || endpointPath.isBlank()) {
return new WorkflowState.Terminal(
cannotContinue("Plan step " + (i + 1) + " has no tool endpoint."));
}
listener.onProgress(
AiWorkflowProgressEvent.executingTool(endpointPath, i + 1, steps.size()));
ToolResult stepResult = executeStep(endpointPath, parameters, currentFiles);
currentFiles = stepResult.files();
if (stepResult.report() != null) {
lastReport = stepResult.report();
lastReportTool = endpointPath;
}
List<PipelineStep> pipelineSteps = new ArrayList<>();
for (int i = 0; i < steps.size(); i++) {
Map<String, Object> step = steps.get(i);
String endpointPath = (String) step.get("tool");
if (endpointPath == null || endpointPath.isBlank()) {
return new WorkflowState.Terminal(
cannotContinue("Plan step " + (i + 1) + " has no tool endpoint."));
}
Map<String, Object> parameters =
step.containsKey("parameters")
? (Map<String, Object>) step.get("parameters")
: Map.of();
pipelineSteps.add(new PipelineStep(endpointPath, parameters));
}
try {
List<Resource> inputFiles = toResources(filesById);
PipelineDefinition definition =
new PipelineDefinition(summary, pipelineSteps, OutputSpec.inline());
PolicyExecutionResult result =
policyExecutor.execute(
definition, PolicyInputs.of(inputFiles), stepProgress(listener));
// Multi-turn: if the plan was emitted with resume_with set, the delegate wants
// Java to re-invoke the orchestrator with any captured report as an artifact.
if (resumeWith != null && !resumeWith.isBlank() && lastReport != null) {
if (resumeWith != null && !resumeWith.isBlank() && result.report() != null) {
WorkflowTurnRequest resumeRequest = new WorkflowTurnRequest();
resumeRequest.setUserMessage(previousRequest.getUserMessage());
resumeRequest.setFiles(previousRequest.getFiles());
@@ -510,14 +495,14 @@ public class AiWorkflowService {
.getArtifacts()
.add(
new PdfContentExtractor.ToolReportArtifact(
lastReportTool, lastReport));
result.reportTool(), result.report()));
resumeRequest.setResumeWith(resumeWith);
return new WorkflowState.Pending(resumeRequest);
}
return new WorkflowState.Terminal(
buildCompletedResponse(
summary, currentFiles, inputFileNames(filesById), lastReport));
summary, result.files(), inputFileNames(filesById), result.report()));
} catch (InternalApiTimeoutException e) {
log.error("Plan step on tool {} timed out: {}", e.getEndpointPath(), e.getMessage());
return new WorkflowState.Terminal(
@@ -548,123 +533,19 @@ public class AiWorkflowService {
}
/**
* Execute a single tool step. If the endpoint accepts multiple files, all files are sent in one
* call. Otherwise, the endpoint is called once per file. ZIP responses are unpacked so each
* inner file is treated as its own result (e.g. split outputs a ZIP of pages).
*
* <p>A structured {@code report} may be returned alongside (or instead of) files — see {@link
* ToolResult}. For per-file dispatch (single-input endpoints called once per input), the first
* non-null report wins.
* Adapt the AI workflow's {@link ProgressListener} to the engine's {@link
* PolicyProgressListener}: each step start maps to an {@code EXECUTING_TOOL} progress event
* carrying the tool path and 1-based step position, preserving the event shape the frontend
* already renders.
*/
private ToolResult executeStep(
String endpointPath, Map<String, Object> parameters, List<Resource> inputFiles)
throws IOException {
List<Resource> files = new ArrayList<>();
JsonNode report = null;
if (toolMetadataService.isMultiInput(endpointPath)) {
ToolResult r = callEndpoint(endpointPath, parameters, inputFiles);
files.addAll(r.files());
report = r.report();
} else {
for (Resource file : inputFiles) {
ToolResult r = callEndpoint(endpointPath, parameters, List.of(file));
files.addAll(r.files());
if (report == null) {
report = r.report();
}
private static PolicyProgressListener stepProgress(ProgressListener listener) {
return new PolicyProgressListener() {
@Override
public void onStepStart(int stepIndex, int stepCount, String operation) {
listener.onProgress(
AiWorkflowProgressEvent.executingTool(operation, stepIndex, stepCount));
}
}
return new ToolResult(files, report);
}
/**
* Call an endpoint and return its result files and optional report.
*
* <ul>
* <li>JSON body (Content-Type: application/json) → the entire body is the report, no files
* are returned.
* <li>File body (PDF etc.) → the file is returned; if an {@link
* AiToolResponseHeaders#TOOL_REPORT} header is present, its (minified JSON) value is
* parsed as the report.
* <li>ZIP responses declared by the tool metadata service are unpacked so callers always see
* a flat list of result files.
* </ul>
*/
private ToolResult callEndpoint(
String endpointPath, Map<String, Object> parameters, List<Resource> files)
throws IOException {
MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
for (Resource file : files) {
body.add("fileInput", file);
}
for (Map.Entry<String, Object> entry : parameters.entrySet()) {
if (entry.getValue() instanceof List<?> list) {
if (containsStructuredElements(list)) {
// Endpoints binding lists of structured objects (e.g. /security/redact's
// redactions, /general/edit-text's edits) parse a single JSON string field via
// a property editor. Pre-serialize the whole list so binding succeeds.
body.add(entry.getKey(), objectMapper.writeValueAsString(list));
} else {
for (Object item : list) {
body.add(entry.getKey(), item);
}
}
} else {
body.add(entry.getKey(), entry.getValue());
}
}
ResponseEntity<Resource> response = internalApiClient.post(endpointPath, body);
if (!HttpStatus.OK.equals(response.getStatusCode()) || response.getBody() == null) {
throw new IOException(
"Tool returned HTTP " + response.getStatusCode() + " for " + endpointPath);
}
Resource resource = response.getBody();
HttpHeaders headers = response.getHeaders();
MediaType contentType = headers.getContentType();
// JSON-only response — the whole body is the structured report, no result file.
if (contentType != null && MediaType.APPLICATION_JSON.isCompatibleWith(contentType)) {
try (java.io.InputStream is = resource.getInputStream()) {
JsonNode report = objectMapper.readTree(is);
return new ToolResult(List.of(), report);
}
}
JsonNode report = parseReportHeader(headers, endpointPath);
if (toolMetadataService.shouldUnpackZipResponse(endpointPath)) {
return new ToolResult(ZipExtractionUtils.extractZip(resource, tempFileManager), report);
}
return new ToolResult(List.of(resource), report);
}
/**
* Parse the optional {@link AiToolResponseHeaders#TOOL_REPORT} header into a {@link JsonNode},
* or return null.
*/
private JsonNode parseReportHeader(HttpHeaders headers, String endpointPath) {
String raw = headers.getFirst(AiToolResponseHeaders.TOOL_REPORT);
if (raw == null || raw.isBlank()) {
return null;
}
try {
return objectMapper.readTree(raw);
} catch (JacksonException e) {
log.warn(
"Ignoring malformed {} header from {}: {}",
AiToolResponseHeaders.TOOL_REPORT,
endpointPath,
e.getMessage());
return null;
}
}
private static boolean containsStructuredElements(List<?> list) {
for (Object item : list) {
if (item instanceof Map<?, ?> || item instanceof List<?>) {
return true;
}
}
return false;
};
}
private List<Resource> toResources(Map<String, MultipartFile> filesById) throws IOException {
@@ -0,0 +1,255 @@
package stirling.software.proprietary.policy.engine;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.lenient;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.io.InputStream;
import java.nio.file.Path;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.api.io.TempDir;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.Resource;
import org.springframework.http.ResponseEntity;
import stirling.software.common.model.ApplicationProperties;
import stirling.software.common.service.FileStorage;
import stirling.software.common.service.FileStorage.StoredFile;
import stirling.software.common.service.InternalApiClient;
import stirling.software.common.service.JobOwnershipService;
import stirling.software.common.service.JobQueue;
import stirling.software.common.service.ResourceMonitor;
import stirling.software.common.service.TaskManager;
import stirling.software.common.service.ToolMetadataService;
import stirling.software.common.util.TempFileManager;
import stirling.software.common.util.TempFileRegistry;
import stirling.software.proprietary.policy.model.OutputSpec;
import stirling.software.proprietary.policy.model.PipelineDefinition;
import stirling.software.proprietary.policy.model.PipelineStep;
import stirling.software.proprietary.policy.model.Policy;
import stirling.software.proprietary.policy.model.PolicyInputs;
import stirling.software.proprietary.policy.model.PolicyRun;
import stirling.software.proprietary.policy.model.PolicyRunStatus;
import stirling.software.proprietary.policy.model.TriggerConfig;
import stirling.software.proprietary.policy.output.InlineOutputSink;
import stirling.software.proprietary.policy.progress.PolicyProgressListener;
import tools.jackson.databind.json.JsonMapper;
/**
* Tests for {@link PolicyEngine}: async submission runs the pipeline on a virtual thread, registers
* outputs and progress with {@link TaskManager}, and surfaces terminal state via {@link
* PolicyRunRegistry}. The step executor and inline sink are real (with mocked collaborators) so the
* full run path is exercised.
*/
@ExtendWith(MockitoExtension.class)
class PolicyEngineTest {
private static final String ROTATE = "/api/v1/general/rotate-pdf";
private static final String COMPRESS = "/api/v1/misc/compress-pdf";
@Mock private InternalApiClient internalApiClient;
@Mock private ToolMetadataService toolMetadataService;
@Mock private TaskManager taskManager;
@Mock private FileStorage fileStorage;
@Mock private JobOwnershipService jobOwnershipService;
@Mock private ResourceMonitor resourceMonitor;
@Mock private JobQueue jobQueue;
@TempDir Path tempDir;
private PolicyRunRegistry registry;
private PolicyEngine engine;
@BeforeEach
void setUp() {
ApplicationProperties props = new ApplicationProperties();
props.getSystem().getTempFileManagement().setBaseTmpDir(tempDir.toString());
props.getSystem().getTempFileManagement().setPrefix("policy-engine-test-");
TempFileManager tempFileManager = new TempFileManager(new TempFileRegistry(), props);
PolicyExecutor executor =
new PolicyExecutor(
internalApiClient,
toolMetadataService,
tempFileManager,
JsonMapper.builder().build());
registry = new PolicyRunRegistry(30);
InlineOutputSink sink = new InlineOutputSink(fileStorage);
engine =
new PolicyEngine(
executor,
taskManager,
registry,
fileStorage,
jobOwnershipService,
List.of(sink),
resourceMonitor,
jobQueue);
// Identity scoping: the run id is the generated UUID unchanged. Lenient because the
// resume/cancel tests do not submit a run.
lenient()
.when(jobOwnershipService.createScopedJobKey(anyString()))
.thenAnswer(inv -> inv.getArgument(0));
// Default to running immediately; the queueing test overrides this.
lenient().when(resourceMonitor.shouldQueueJob(anyInt())).thenReturn(false);
}
@Test
void submitRunsPipelineToCompletionAndRegistersOutputs() throws Exception {
when(toolMetadataService.isMultiInput(anyString())).thenReturn(false);
when(toolMetadataService.shouldUnpackZipResponse(anyString())).thenReturn(false);
stubEndpoint(ROTATE, pdf("rotated", "rotated.pdf"));
stubEndpoint(COMPRESS, pdf("compressed", "compressed.pdf"));
int[] counter = {0};
when(fileStorage.storeInputStream(any(InputStream.class), anyString()))
.thenAnswer(
inv -> {
InputStream is = inv.getArgument(0);
long size = is.readAllBytes().length;
return new StoredFile("file-" + ++counter[0], size);
});
PolicyRunHandle handle =
engine.submit(
definition(
new PipelineStep(ROTATE, Map.of()),
new PipelineStep(COMPRESS, Map.of())),
PolicyInputs.of(List.of(pdf("input", "input.pdf"))),
PolicyProgressListener.NOOP);
// The completion future resolves with the final run state, no polling needed.
String runId = handle.runId();
PolicyRun run = handle.completion().get(10, TimeUnit.SECONDS);
assertEquals(PolicyRunStatus.COMPLETED, run.getStatus());
assertEquals(1, run.getOutputs().size());
assertEquals("compressed.pdf", run.getOutputs().get(0).getFileName());
// The run self-registers its results and completion with the job system.
verify(taskManager).createTask(runId);
verify(taskManager).setMultipleFileResults(eq(runId), any());
verify(taskManager).setComplete(runId);
// Progress notes were written for each step.
verify(taskManager, atLeastOnce()).addNote(eq(runId), anyString());
}
@Test
void submitFailsRunWhenAToolErrors() throws Exception {
when(toolMetadataService.isMultiInput(ROTATE)).thenReturn(false);
when(internalApiClient.post(eq(ROTATE), any())).thenThrow(new RuntimeException("boom"));
PolicyRunHandle handle =
engine.submit(
definition(new PipelineStep(ROTATE, Map.of())),
PolicyInputs.of(List.of(pdf("input", "input.pdf"))),
PolicyProgressListener.NOOP);
String runId = handle.runId();
PolicyRun run = handle.completion().get(10, TimeUnit.SECONDS);
assertEquals(PolicyRunStatus.FAILED, run.getStatus());
verify(taskManager).setError(eq(runId), anyString());
verify(taskManager, never()).setComplete(runId);
}
@Test
void runPolicyExecutesThePolicysPipeline() throws Exception {
when(toolMetadataService.isMultiInput(anyString())).thenReturn(false);
when(toolMetadataService.shouldUnpackZipResponse(anyString())).thenReturn(false);
stubEndpoint(ROTATE, pdf("rotated", "rotated.pdf"));
int[] counter = {0};
when(fileStorage.storeInputStream(any(InputStream.class), anyString()))
.thenAnswer(
inv -> {
InputStream is = inv.getArgument(0);
return new StoredFile("file-" + ++counter[0], is.readAllBytes().length);
});
Policy policy =
new Policy(
"p1",
"rotate",
"owner",
true,
TriggerConfig.manual(),
List.of(new PipelineStep(ROTATE, Map.of())),
OutputSpec.inline());
PolicyRunHandle handle =
engine.runPolicy(
policy,
PolicyInputs.of(List.of(pdf("input", "input.pdf"))),
PolicyProgressListener.NOOP);
PolicyRun run = handle.completion().get(10, TimeUnit.SECONDS);
assertEquals(PolicyRunStatus.COMPLETED, run.getStatus());
verify(internalApiClient).post(eq(ROTATE), any());
}
@Test
void runIsQueuedUnderResourcePressure() {
when(resourceMonitor.shouldQueueJob(anyInt())).thenReturn(true);
// Returning an already-completed future keeps the run parked: the queued work (which would
// start the run) is never executed by this mock, so it stays PENDING.
doReturn(CompletableFuture.completedFuture(null))
.when(jobQueue)
.queueJob(anyString(), anyInt(), any(), anyLong());
PolicyRunHandle handle =
engine.submit(
definition(new PipelineStep(ROTATE, Map.of())),
PolicyInputs.of(List.of(pdf("input", "input.pdf"))),
PolicyProgressListener.NOOP);
verify(jobQueue).queueJob(eq(handle.runId()), anyInt(), any(), anyLong());
assertEquals(PolicyRunStatus.PENDING, registry.get(handle.runId()).getStatus());
}
@Test
void resumeIsNotYetImplemented() {
assertThrows(UnsupportedOperationException.class, () -> engine.resume("any", List.of()));
}
@Test
void cancelUnknownRunReturnsFalse() {
assertFalse(engine.cancel("does-not-exist"));
}
// --- helpers ---
private static PipelineDefinition definition(PipelineStep... steps) {
return new PipelineDefinition("test", List.of(steps), OutputSpec.inline());
}
private void stubEndpoint(String endpoint, Resource body) {
when(internalApiClient.post(eq(endpoint), any())).thenReturn(ResponseEntity.ok(body));
}
private static ByteArrayResource pdf(String content, String filename) {
return new ByteArrayResource(content.getBytes()) {
@Override
public String getFilename() {
return filename;
}
};
}
}
@@ -0,0 +1,378 @@
package stirling.software.proprietary.policy.engine;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.api.io.TempDir;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.Resource;
import org.springframework.http.ResponseEntity;
import org.springframework.util.MultiValueMap;
import stirling.software.common.model.ApplicationProperties;
import stirling.software.common.service.InternalApiClient;
import stirling.software.common.service.InternalApiTimeoutException;
import stirling.software.common.service.ToolMetadataService;
import stirling.software.common.util.TempFileManager;
import stirling.software.common.util.TempFileRegistry;
import stirling.software.proprietary.policy.model.OutputSpec;
import stirling.software.proprietary.policy.model.PipelineDefinition;
import stirling.software.proprietary.policy.model.PipelineStep;
import stirling.software.proprietary.policy.model.PolicyInputs;
import stirling.software.proprietary.policy.progress.PolicyProgressListener;
import tools.jackson.databind.ObjectMapper;
import tools.jackson.databind.json.JsonMapper;
/**
* Unit tests for {@link PolicyExecutor}, the shared pipeline step loop. Covers file chaining across
* steps, multi-input vs per-file dispatch, ZIP unpacking, structured-list parameter encoding,
* progress callbacks, and timeout propagation. External collaborators are mocked; {@link
* TempFileManager} is real so ZIP extraction exercises real code.
*/
@ExtendWith(MockitoExtension.class)
class PolicyExecutorTest {
private static final String ROTATE = "/api/v1/general/rotate-pdf";
private static final String COMPRESS = "/api/v1/misc/compress-pdf";
private static final String SPLIT = "/api/v1/general/split-pages";
private static final String MERGE = "/api/v1/general/merge-pdfs";
@Mock private InternalApiClient internalApiClient;
@Mock private ToolMetadataService toolMetadataService;
@TempDir Path tempDir;
private TempFileManager tempFileManager;
private PolicyExecutor executor;
@BeforeEach
void setUp() {
ApplicationProperties props = new ApplicationProperties();
props.getSystem().getTempFileManagement().setBaseTmpDir(tempDir.toString());
props.getSystem().getTempFileManagement().setPrefix("policy-test-");
tempFileManager = new TempFileManager(new TempFileRegistry(), props);
ObjectMapper objectMapper = JsonMapper.builder().build();
executor =
new PolicyExecutor(
internalApiClient, toolMetadataService, tempFileManager, objectMapper);
}
@Test
void executesStepsSequentiallyChainingOutputToInput() throws IOException {
when(toolMetadataService.isMultiInput(anyString())).thenReturn(false);
when(toolMetadataService.shouldUnpackZipResponse(anyString())).thenReturn(false);
stubEndpoint(ROTATE, pdf("rotated", "rotated.pdf"));
stubEndpoint(COMPRESS, pdf("compressed", "compressed.pdf"));
List<Integer> steps = new ArrayList<>();
PolicyProgressListener listener =
new PolicyProgressListener() {
@Override
public void onStepStart(int stepIndex, int stepCount, String operation) {
steps.add(stepIndex);
}
};
PolicyExecutionResult result =
executor.execute(
definition(
new PipelineStep(ROTATE, Map.of()),
new PipelineStep(COMPRESS, Map.of())),
PolicyInputs.of(List.of(pdf("input", "input.pdf"))),
listener);
assertEquals(1, result.files().size());
assertEquals("compressed.pdf", result.files().get(0).getFilename());
verify(internalApiClient, times(1)).post(eq(ROTATE), any());
verify(internalApiClient, times(1)).post(eq(COMPRESS), any());
// Progress fired once per step, in order.
assertEquals(List.of(1, 2), steps);
}
@Test
void multiInputEndpointIsCalledOnceWithAllFiles() throws IOException {
when(toolMetadataService.isMultiInput(MERGE)).thenReturn(true);
when(toolMetadataService.shouldUnpackZipResponse(MERGE)).thenReturn(false);
stubEndpoint(MERGE, pdf("merged", "merged.pdf"));
PolicyExecutionResult result =
executor.execute(
definition(new PipelineStep(MERGE, Map.of())),
PolicyInputs.of(List.of(pdf("a", "a.pdf"), pdf("b", "b.pdf"))),
PolicyProgressListener.NOOP);
assertEquals(1, result.files().size());
verify(internalApiClient, times(1)).post(eq(MERGE), any());
}
@Test
void singleInputEndpointIsCalledOncePerFile() throws IOException {
when(toolMetadataService.isMultiInput(ROTATE)).thenReturn(false);
when(toolMetadataService.shouldUnpackZipResponse(ROTATE)).thenReturn(false);
stubEndpoint(ROTATE, pdf("rotated", "rotated.pdf"));
PolicyExecutionResult result =
executor.execute(
definition(new PipelineStep(ROTATE, Map.of())),
PolicyInputs.of(List.of(pdf("a", "a.pdf"), pdf("b", "b.pdf"))),
PolicyProgressListener.NOOP);
assertEquals(2, result.files().size());
verify(internalApiClient, times(2)).post(eq(ROTATE), any());
}
@Test
void zipResponseIsUnpackedIntoIndividualFiles() throws IOException {
when(toolMetadataService.isMultiInput(SPLIT)).thenReturn(false);
when(toolMetadataService.shouldUnpackZipResponse(SPLIT)).thenReturn(true);
stubEndpoint(
SPLIT,
zip(
"doc.zip",
List.of(new Entry("page-1.pdf", "one"), new Entry("page-2.pdf", "two"))));
PolicyExecutionResult result =
executor.execute(
definition(new PipelineStep(SPLIT, Map.of())),
PolicyInputs.of(List.of(pdf("doc", "doc.pdf"))),
PolicyProgressListener.NOOP);
assertEquals(2, result.files().size());
assertEquals("page-1.pdf", result.files().get(0).getFilename());
assertEquals("page-2.pdf", result.files().get(1).getFilename());
}
@Test
void structuredListParameterIsJsonEncodedAsSingleField() throws IOException {
String editText = "/api/v1/general/edit-text";
when(toolMetadataService.isMultiInput(editText)).thenReturn(false);
when(toolMetadataService.shouldUnpackZipResponse(editText)).thenReturn(false);
stubEndpoint(editText, pdf("edited", "edited.pdf"));
// LinkedHashMap so the serialized key order is deterministic for the assertion below.
Map<String, Object> edit = new LinkedHashMap<>();
edit.put("find", "foo");
edit.put("replace", "bar");
Map<String, Object> params = new LinkedHashMap<>();
params.put("edits", List.of(edit));
params.put("useRegex", false);
executor.execute(
definition(new PipelineStep(editText, params)),
PolicyInputs.of(List.of(pdf("in", "in.pdf"))),
PolicyProgressListener.NOOP);
@SuppressWarnings("unchecked")
ArgumentCaptor<MultiValueMap<String, Object>> bodyCaptor =
ArgumentCaptor.forClass(MultiValueMap.class);
verify(internalApiClient).post(eq(editText), bodyCaptor.capture());
MultiValueMap<String, Object> body = bodyCaptor.getValue();
List<Object> edits = body.get("edits");
assertNotNull(edits);
assertEquals(1, edits.size());
assertEquals("[{\"find\":\"foo\",\"replace\":\"bar\"}]", edits.get(0));
}
@Test
void supportingFilesAreBoundToTheirNamedFields() throws IOException {
String addStamp = "/api/v1/misc/add-stamp-to-pdf";
when(toolMetadataService.isMultiInput(addStamp)).thenReturn(false);
when(toolMetadataService.shouldUnpackZipResponse(addStamp)).thenReturn(false);
stubEndpoint(addStamp, pdf("stamped", "stamped.pdf"));
PipelineStep step =
new PipelineStep(addStamp, Map.of("opacity", 0.5), Map.of("stampImage", "logo"));
PolicyInputs inputs =
new PolicyInputs(
List.of(pdf("doc", "doc.pdf")),
Map.of("logo", List.of(pdf("logo-bytes", "logo.png"))));
executor.execute(
new PipelineDefinition("stamp", List.of(step), OutputSpec.inline()),
inputs,
PolicyProgressListener.NOOP);
@SuppressWarnings("unchecked")
ArgumentCaptor<MultiValueMap<String, Object>> bodyCaptor =
ArgumentCaptor.forClass(MultiValueMap.class);
verify(internalApiClient).post(eq(addStamp), bodyCaptor.capture());
MultiValueMap<String, Object> body = bodyCaptor.getValue();
// The document goes to fileInput; the supporting image is bound to its named field and is
// not part of the document stream.
assertEquals(1, body.get("fileInput").size());
assertNotNull(body.get("stampImage"));
assertEquals(1, body.get("stampImage").size());
}
@Test
void missingSupportingFileFailsTheStep() {
String addStamp = "/api/v1/misc/add-stamp-to-pdf";
when(toolMetadataService.isMultiInput(addStamp)).thenReturn(false);
PipelineStep step = new PipelineStep(addStamp, Map.of(), Map.of("stampImage", "logo"));
IOException ex =
assertThrows(
IOException.class,
() ->
executor.execute(
new PipelineDefinition(
"stamp", List.of(step), OutputSpec.inline()),
PolicyInputs.of(List.of(pdf("doc", "doc.pdf"))),
PolicyProgressListener.NOOP));
assertTrue(ex.getMessage().contains("logo"));
}
@Test
void documentOfAnUnacceptedTypeFailsTheStep() {
String compress = "/api/v1/misc/compress-pdf";
when(toolMetadataService.getExtensionTypes(false, compress)).thenReturn(List.of("pdf"));
IOException ex =
assertThrows(
IOException.class,
() ->
executor.execute(
definition(new PipelineStep(compress, Map.of())),
PolicyInputs.of(List.of(pdf("img", "image.png"))),
PolicyProgressListener.NOOP));
assertTrue(ex.getMessage().contains("image.png"));
// Type check happens before any dispatch.
verify(internalApiClient, never()).post(anyString(), any());
}
@Test
void documentOfAnAcceptedTypeProceeds() throws IOException {
String compress = "/api/v1/misc/compress-pdf";
when(toolMetadataService.getExtensionTypes(false, compress)).thenReturn(List.of("pdf"));
when(toolMetadataService.isMultiInput(compress)).thenReturn(false);
when(toolMetadataService.shouldUnpackZipResponse(compress)).thenReturn(false);
stubEndpoint(compress, pdf("compressed", "compressed.pdf"));
PolicyExecutionResult result =
executor.execute(
definition(new PipelineStep(compress, Map.of())),
PolicyInputs.of(List.of(pdf("doc", "doc.pdf"))),
PolicyProgressListener.NOOP);
assertEquals(1, result.files().size());
verify(internalApiClient, times(1)).post(eq(compress), any());
}
@Test
void filterOperationWithEmptyResultDropsTheFile() throws IOException {
String filter = "/api/v1/filter/filter-page-count";
when(toolMetadataService.isMultiInput(filter)).thenReturn(false);
stubEndpoint(filter, pdf("", "filtered.pdf")); // empty body => filtered out
PolicyExecutionResult result =
executor.execute(
definition(new PipelineStep(filter, Map.of())),
PolicyInputs.of(List.of(pdf("doc", "doc.pdf"))),
PolicyProgressListener.NOOP);
assertEquals(0, result.files().size());
}
@Test
void timeoutFromAStepPropagates() {
when(toolMetadataService.isMultiInput(ROTATE)).thenReturn(false);
when(internalApiClient.post(eq(ROTATE), any()))
.thenThrow(
new InternalApiTimeoutException(
ROTATE,
java.time.Duration.ofSeconds(300),
new IOException("Read timed out")));
assertThrows(
InternalApiTimeoutException.class,
() ->
executor.execute(
definition(new PipelineStep(ROTATE, Map.of())),
PolicyInputs.of(List.of(pdf("in", "in.pdf"))),
PolicyProgressListener.NOOP));
}
@Test
void emptyPipelineIsRejected() {
assertThrows(
IllegalArgumentException.class,
() ->
executor.execute(
new PipelineDefinition("empty", List.of(), OutputSpec.inline()),
PolicyInputs.of(List.of(pdf("in", "in.pdf"))),
PolicyProgressListener.NOOP));
}
// --- helpers ---
private static PipelineDefinition definition(PipelineStep... steps) {
return new PipelineDefinition("test", List.of(steps), OutputSpec.inline());
}
private void stubEndpoint(String endpoint, Resource body) {
when(internalApiClient.post(eq(endpoint), any())).thenReturn(ResponseEntity.ok(body));
}
private static ByteArrayResource pdf(String content, String filename) {
return new ByteArrayResource(content.getBytes()) {
@Override
public String getFilename() {
return filename;
}
};
}
private static ByteArrayResource zip(String filename, List<Entry> entries) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try (ZipOutputStream zos = new ZipOutputStream(baos)) {
for (Entry entry : entries) {
zos.putNextEntry(new ZipEntry(entry.name()));
zos.write(entry.content().getBytes());
zos.closeEntry();
}
}
byte[] zipBytes = baos.toByteArray();
return new ByteArrayResource(zipBytes) {
@Override
public String getFilename() {
return filename;
}
@Override
public InputStream getInputStream() {
return new ByteArrayInputStream(zipBytes);
}
};
}
private record Entry(String name, String content) {}
}
@@ -0,0 +1,101 @@
package stirling.software.proprietary.policy.engine;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.time.Instant;
import java.util.List;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import stirling.software.proprietary.policy.model.PipelineDefinition;
import stirling.software.proprietary.policy.model.PolicyRun;
import stirling.software.proprietary.policy.model.WaitState;
/**
* Tests for {@link PolicyRunRegistry} eviction: terminal runs expire, active/paused runs persist.
*/
class PolicyRunRegistryTest {
private PolicyRunRegistry registry;
@BeforeEach
void setUp() {
registry = new PolicyRunRegistry(30);
}
@AfterEach
void tearDown() {
registry.shutdown();
}
@Test
void evictsTerminalRunsPastTheCutoff() {
PolicyRun completed = register("completed");
completed.complete(List.of());
PolicyRun failed = register("failed");
failed.fail("boom");
PolicyRun cancelled = register("cancelled");
cancelled.cancel();
// A cutoff in the future means every terminal run finished "before" it.
int removed = registry.evictExpired(Instant.now().plusSeconds(60));
assertEquals(3, removed);
assertNull(registry.get("completed"));
assertNull(registry.get("failed"));
assertNull(registry.get("cancelled"));
}
@Test
void retainsActiveAndPausedRunsRegardlessOfAge() {
register("pending"); // PENDING: never started
PolicyRun running = register("running");
running.markRunning();
PolicyRun waiting = register("waiting");
waiting.waitForInput(new WaitState("needs a signature", 1, List.of()));
int removed = registry.evictExpired(Instant.now().plusSeconds(60));
assertEquals(0, removed);
assertNotNull(registry.get("pending"));
assertNotNull(registry.get("running"));
assertNotNull(registry.get("waiting"));
}
@Test
void keepsTerminalRunsStillWithinTheExpiryWindow() {
PolicyRun completed = register("recent");
completed.complete(List.of());
// A cutoff in the past means the run was updated "after" it: too young to evict.
int removed = registry.evictExpired(Instant.now().minusSeconds(60));
assertEquals(0, removed);
assertNotNull(registry.get("recent"));
}
@Test
void evictionLeavesUnrelatedRunsInPlace() {
PolicyRun completed = register("done");
completed.complete(List.of());
PolicyRun running = register("busy");
running.markRunning();
registry.evictExpired(Instant.now().plusSeconds(60));
assertNull(registry.get("done"));
assertNotNull(registry.get("busy"));
assertTrue(registry.all().stream().anyMatch(r -> r.getRunId().equals("busy")));
}
private PolicyRun register(String runId) {
PolicyRun run = new PolicyRun(runId, new PipelineDefinition(runId, List.of(), null));
registry.register(run);
return run;
}
}
@@ -0,0 +1,87 @@
package stirling.software.proprietary.policy.store;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.List;
import java.util.Map;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import stirling.software.proprietary.policy.model.OutputSpec;
import stirling.software.proprietary.policy.model.PipelineStep;
import stirling.software.proprietary.policy.model.Policy;
import stirling.software.proprietary.policy.model.TriggerConfig;
/** Tests for {@link InProcessPolicyStore}: id assignment, upsert, trigger-type lookup, delete. */
class InProcessPolicyStoreTest {
private PolicyStore store;
@BeforeEach
void setUp() {
store = new InProcessPolicyStore();
}
@Test
void savedPolicyGetsAnIdAndIsRetrievable() {
Policy saved = store.save(policy(null, "compress", "manual", true));
assertNotNull(saved.id());
assertFalse(saved.id().isBlank());
assertEquals(saved, store.get(saved.id()).orElseThrow());
}
@Test
void savingWithAnExistingIdUpdatesInPlace() {
Policy created = store.save(policy(null, "before", "manual", true));
store.save(
new Policy(
created.id(),
"after",
"owner",
true,
TriggerConfig.manual(),
List.of(),
OutputSpec.inline()));
assertEquals(1, store.all().size());
assertEquals("after", store.get(created.id()).orElseThrow().name());
}
@Test
void findByTriggerTypeReturnsOnlyEnabledMatches() {
store.save(policy(null, "watch", "folder", true));
store.save(policy(null, "watch-disabled", "folder", false));
store.save(policy(null, "nightly", "schedule", true));
List<Policy> folder = store.findByTriggerType("folder");
assertEquals(1, folder.size());
assertEquals("watch", folder.get(0).name());
}
@Test
void deleteRemovesThePolicy() {
Policy saved = store.save(policy(null, "p", "manual", true));
assertTrue(store.delete(saved.id()));
assertTrue(store.get(saved.id()).isEmpty());
assertFalse(store.delete(saved.id()));
}
private static Policy policy(String id, String name, String triggerType, boolean enabled) {
return new Policy(
id,
name,
"owner",
enabled,
new TriggerConfig(triggerType, Map.of()),
List.of(new PipelineStep("/api/v1/misc/compress-pdf", Map.of())),
OutputSpec.inline());
}
}
@@ -0,0 +1,129 @@
package stirling.software.proprietary.policy.store;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import stirling.software.proprietary.policy.model.OutputSpec;
import stirling.software.proprietary.policy.model.PipelineStep;
import stirling.software.proprietary.policy.model.Policy;
import stirling.software.proprietary.policy.model.TriggerConfig;
import tools.jackson.databind.ObjectMapper;
import tools.jackson.databind.json.JsonMapper;
/**
* Tests for {@link JpaPolicyStore}'s entity mapping and query delegation. The repository is mocked;
* real Hibernate/H2 persistence is exercised at application boot (this module's convention is
* Mockito unit tests for store/service logic).
*/
@ExtendWith(MockitoExtension.class)
class JpaPolicyStoreTest {
@Mock private PolicyRepository repository;
private final ObjectMapper objectMapper = JsonMapper.builder().build();
private JpaPolicyStore store;
@BeforeEach
void setUp() {
store = new JpaPolicyStore(repository, objectMapper);
}
@Test
void saveAssignsAnIdAndPersistsThePolicyAsJson() {
Policy saved =
store.save(
new Policy(
null,
"compress incoming",
"alice",
true,
new TriggerConfig("folder", Map.of("path", "/in")),
List.of(new PipelineStep("/api/v1/misc/compress-pdf", Map.of())),
OutputSpec.inline()));
assertNotNull(saved.id());
ArgumentCaptor<PolicyEntity> captor = ArgumentCaptor.forClass(PolicyEntity.class);
verify(repository).save(captor.capture());
PolicyEntity entity = captor.getValue();
assertEquals(saved.id(), entity.getId());
assertEquals("folder", entity.getTriggerType());
assertTrue(entity.isEnabled());
// The stored JSON round-trips back to an equal policy.
assertEquals(saved, objectMapper.readValue(entity.getPolicyJson(), Policy.class));
}
@Test
void getDeserializesThePolicyFromJson() {
Policy policy =
new Policy(
"p1",
"rotate",
"alice",
true,
TriggerConfig.manual(),
List.of(
new PipelineStep(
"/api/v1/general/rotate-pdf", Map.of("angle", 90))),
OutputSpec.inline());
when(repository.findById("p1")).thenReturn(Optional.of(entityFor(policy)));
assertEquals(policy, store.get("p1").orElseThrow());
}
@Test
void findByTriggerTypeUsesTheEnabledQuery() {
Policy policy =
new Policy(
"p1",
"watch",
"alice",
true,
new TriggerConfig("folder", Map.of()),
List.of(new PipelineStep("/api/v1/misc/compress-pdf", Map.of())),
OutputSpec.inline());
when(repository.findByTriggerTypeAndEnabledTrue("folder"))
.thenReturn(List.of(entityFor(policy)));
List<Policy> folder = store.findByTriggerType("folder");
assertEquals(1, folder.size());
assertEquals("p1", folder.get(0).id());
}
@Test
void deleteReturnsWhetherThePolicyExisted() {
when(repository.existsById("p1")).thenReturn(true);
assertTrue(store.delete("p1"));
verify(repository).deleteById("p1");
when(repository.existsById("missing")).thenReturn(false);
assertFalse(store.delete("missing"));
}
private PolicyEntity entityFor(Policy policy) {
PolicyEntity entity = new PolicyEntity();
entity.setId(policy.id());
entity.setName(policy.name());
entity.setOwner(policy.owner());
entity.setEnabled(policy.enabled());
entity.setTriggerType(policy.trigger().type());
entity.setPolicyJson(objectMapper.writeValueAsString(policy));
return entity;
}
}
@@ -57,6 +57,7 @@ import stirling.software.proprietary.model.api.ai.AiWorkflowFileInput;
import stirling.software.proprietary.model.api.ai.AiWorkflowOutcome;
import stirling.software.proprietary.model.api.ai.AiWorkflowRequest;
import stirling.software.proprietary.model.api.ai.AiWorkflowResponse;
import stirling.software.proprietary.policy.engine.PolicyExecutor;
import tools.jackson.databind.ObjectMapper;
import tools.jackson.databind.json.JsonMapper;
@@ -107,18 +108,20 @@ class AiWorkflowServiceTest {
.when(fileIdStrategy.idFor(any(MultipartFile.class)))
.thenAnswer(inv -> ((MultipartFile) inv.getArgument(0)).getOriginalFilename());
PolicyExecutor policyExecutor =
new PolicyExecutor(
internalApiClient, toolMetadataService, tempFileManager, objectMapper);
service =
new AiWorkflowService(
pdfDocumentFactory,
aiEngineClient,
pdfContentExtractor,
objectMapper,
internalApiClient,
fileStorage,
toolMetadataService,
tempFileManager,
fileIdStrategy,
endpointResolver,
policyExecutor,
null,
new ApplicationProperties());
when(endpointResolver.getEnabledEndpointUrls()).thenReturn(List.of());
@@ -40,6 +40,8 @@ import stirling.software.saas.ai.model.AiCreateSession;
import stirling.software.saas.ai.repository.AiCreateSessionRepository;
import stirling.software.saas.ai.service.AiCreateProxyService;
import stirling.software.saas.ai.service.AiCreateSessionService;
import stirling.software.saas.payg.cap.RequiresFeature;
import stirling.software.saas.payg.model.FeatureGate;
import stirling.software.saas.service.CreditService;
import stirling.software.saas.service.TeamCreditService;
import stirling.software.saas.util.AuthenticationUtils;
@@ -49,6 +51,7 @@ import stirling.software.saas.util.CreditHeaderUtils;
@Profile("saas")
@RequestMapping("/api/v1/ai/create")
@RequiredArgsConstructor
@RequiresFeature(FeatureGate.AI_SUPPORT)
@Slf4j
public class AiCreateController {
@@ -23,11 +23,14 @@ import lombok.extern.slf4j.Slf4j;
import stirling.software.saas.ai.model.AiCreateSession;
import stirling.software.saas.ai.model.AiCreateSessionStatus;
import stirling.software.saas.ai.service.AiCreateSessionService;
import stirling.software.saas.payg.cap.RequiresFeature;
import stirling.software.saas.payg.model.FeatureGate;
@RestController
@Profile("saas")
@RequestMapping("/api/v1/ai/create/internal")
@RequiredArgsConstructor
@RequiresFeature(FeatureGate.AI_SUPPORT)
@Slf4j
public class AiCreateInternalController {
@@ -25,6 +25,8 @@ import lombok.extern.slf4j.Slf4j;
import stirling.software.proprietary.security.database.repository.UserRepository;
import stirling.software.proprietary.security.model.User;
import stirling.software.saas.ai.service.AiProxyService;
import stirling.software.saas.payg.cap.RequiresFeature;
import stirling.software.saas.payg.model.FeatureGate;
import stirling.software.saas.service.CreditService;
import stirling.software.saas.service.TeamCreditService;
import stirling.software.saas.util.AuthenticationUtils;
@@ -33,6 +35,7 @@ import stirling.software.saas.util.CreditHeaderUtils;
@RestController
@Profile("saas")
@RequestMapping("/api/v1/ai")
@RequiresFeature(FeatureGate.AI_SUPPORT)
@Slf4j
public class AiProxyController {
@@ -0,0 +1,56 @@
package stirling.software.saas.payg.api;
/**
* Cap conversion between the dollar amount the leader edits in the UI and the unit count stored on
* {@code wallet_policy.cap_units}.
*
* <p>The cap is application-layer only — Stripe stays on a flat-priced single meter, so the
* conversion rate here doesn't need to match any Stripe price. It only needs to be stable: a leader
* who set "$25" should read back "$25" on the next page load.
*
* <p>V1 rate: {@value #UNITS_PER_USD} units = $1. This anchors the in-app cap representation to the
* same unit count the ledger writes, so the "X of Y units used" widget in the FE lines up against
* the cap. A future iteration can read this from {@code pricing_policy} once the per-policy money
* conversion lands.
*
* <p>Both directions floor: $24.50 → 2450 units, 2450 units → $24. The FE only sends whole-dollar
* inputs (the cap-edit field is an integer text box) so the floor on the read path is the only
* place rounding ever shows up, and only when an admin set a non-multiple via SQL.
*/
public final class CapMoneyUnits {
/**
* Doc-units per USD. {@code 100} = "1 cent per unit" at the in-app display layer. Tied to the
* unit-count meter the engine writes to the ledger; not tied to Stripe pricing.
*/
public static final int UNITS_PER_USD = 100;
/** Smallest currency unit per USD (always 100 cents in USD; explicit for clarity). */
public static final int CENTS_PER_USD = 100;
private CapMoneyUnits() {}
/** Convert a dollar cap entered by the leader to doc-units for {@code cap_units}. */
public static long usdToUnits(int capUsd) {
if (capUsd < 0) {
throw new IllegalArgumentException("capUsd must be >= 0");
}
return (long) capUsd * UNITS_PER_USD;
}
/** Convert {@code cap_units} back to dollars for the response payload. Floor on read. */
public static int unitsToUsd(long capUnits) {
if (capUnits < 0L) {
return 0;
}
return (int) (capUnits / UNITS_PER_USD);
}
/** Convert a dollar cap to smallest-currency-unit cents for {@code cap_source_money}. */
public static long usdToCents(int capUsd) {
if (capUsd < 0) {
throw new IllegalArgumentException("capUsd must be >= 0");
}
return (long) capUsd * CENTS_PER_USD;
}
}
@@ -0,0 +1,714 @@
package stirling.software.saas.payg.api;
import java.net.URI;
import java.net.URISyntaxException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Profile;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PatchMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import io.swagger.v3.oas.annotations.Hidden;
import jakarta.validation.Valid;
import jakarta.validation.constraints.Min;
import lombok.extern.slf4j.Slf4j;
import stirling.software.common.model.enumeration.TeamRole;
import stirling.software.proprietary.security.database.repository.UserRepository;
import stirling.software.proprietary.security.model.User;
import stirling.software.saas.model.TeamMembership;
import stirling.software.saas.payg.api.WalletSnapshotResponse.CategoryBreakdown;
import stirling.software.saas.payg.api.WalletSnapshotResponse.MemberRow;
import stirling.software.saas.payg.entitlement.EntitlementService;
import stirling.software.saas.payg.entitlement.EntitlementSnapshot;
import stirling.software.saas.payg.model.BillingCategory;
import stirling.software.saas.payg.model.LedgerEntryType;
import stirling.software.saas.payg.policy.PaygTeamExtensions;
import stirling.software.saas.payg.repository.PaygTeamExtensionsRepository;
import stirling.software.saas.payg.repository.WalletCategorySummaryDao;
import stirling.software.saas.payg.repository.WalletLedgerRepository;
import stirling.software.saas.payg.repository.WalletPolicyRepository;
import stirling.software.saas.payg.wallet.WalletPolicy;
import stirling.software.saas.repository.TeamMembershipRepository;
import stirling.software.saas.util.AuthenticationUtils;
/**
* Read + cap-mutation surface backing the FE PAYG Plan page.
*
* <p>{@code GET /api/v1/payg/wallet} is the single fetch the {@code useWallet} hook calls. Returns
* a fully-populated {@link WalletSnapshotResponse} — derived from {@link EntitlementService} (for
* spend / cap / period), {@link PaygTeamExtensions} (for subscription state), and the {@code
* wallet_category_summary} view (for the per-category breakdown widget). Leader callers also get a
* roster of team members + their sub-caps; member callers see an empty roster.
*
* <p>{@code PATCH /api/v1/payg/cap} updates {@code wallet_policy.cap_units} (no Stripe call — the
* cap is enforced application-side via the entitlement guard) and invalidates the team's snapshot
* cache so the next read reflects the change immediately. Only leaders may call this; the team is
* derived from the caller, so we authorise inside the method rather than via {@code @PreAuthorize}
* — the team id never appears on the path or query string.
*
* <p><b>Known dependency on PR #6532:</b> {@code stripeSubscriptionId} is sourced from {@code
* payg_team_extensions.payg_subscription_id} once that column ships; on this branch the column
* doesn't exist yet, so the response always returns {@code null} for that field. {@link
* #STATUS_SUBSCRIBED} is determined by the presence of {@code stripeCustomerId} as a stand-in until
* #6532 lands; once it does, swap to checking {@code paygSubscriptionId} instead.
*/
@Slf4j
@Hidden
@RestController
@RequestMapping("/api/v1/payg")
@Profile("saas")
public class PaygWalletController {
static final String STATUS_FREE = "free";
static final String STATUS_SUBSCRIBED = "subscribed";
static final String ROLE_LEADER = "leader";
static final String ROLE_MEMBER = "member";
/**
* Free-tier ceiling shown to un-subscribed teams. Mirrors {@link
* EntitlementService#DEFAULT_FREE_TIER_UNITS} until {@code
* pricing_policy.free_tier_units_per_cycle} lands and the value can be read live.
*/
private static final int FREE_TIER_LIMIT_UNITS_FALLBACK = 500;
private static final DateTimeFormatter ISO_DATE = DateTimeFormatter.ISO_LOCAL_DATE;
private final EntitlementService entitlementService;
private final TeamMembershipRepository memberRepo;
private final PaygTeamExtensionsRepository extRepo;
private final WalletPolicyRepository policyRepo;
private final WalletLedgerRepository ledgerRepo;
private final WalletCategorySummaryDao categorySummaryDao;
private final UserRepository userRepository;
private final RestTemplate saasRestTemplate;
private final String portalEndpoint;
private final String portalServiceRoleToken;
private final Set<String> portalReturnUrlAllowedHosts;
public PaygWalletController(
EntitlementService entitlementService,
TeamMembershipRepository memberRepo,
PaygTeamExtensionsRepository extRepo,
WalletPolicyRepository policyRepo,
WalletLedgerRepository ledgerRepo,
WalletCategorySummaryDao categorySummaryDao,
UserRepository userRepository,
RestTemplate saasRestTemplate,
@Value("${payg.portal.endpoint:}") String portalEndpoint,
@Value("${payg.portal.service-role-token:}") String portalServiceRoleToken,
@Value("${payg.portal.allowed-return-hosts:}") String portalReturnUrlAllowedHostsCsv) {
this.entitlementService = Objects.requireNonNull(entitlementService, "entitlementService");
this.memberRepo = Objects.requireNonNull(memberRepo, "memberRepo");
this.extRepo = Objects.requireNonNull(extRepo, "extRepo");
this.policyRepo = Objects.requireNonNull(policyRepo, "policyRepo");
this.ledgerRepo = Objects.requireNonNull(ledgerRepo, "ledgerRepo");
this.categorySummaryDao = Objects.requireNonNull(categorySummaryDao, "categorySummaryDao");
this.userRepository = Objects.requireNonNull(userRepository, "userRepository");
this.saasRestTemplate = Objects.requireNonNull(saasRestTemplate, "saasRestTemplate");
this.portalEndpoint = portalEndpoint == null ? "" : portalEndpoint;
this.portalServiceRoleToken = portalServiceRoleToken == null ? "" : portalServiceRoleToken;
this.portalReturnUrlAllowedHosts = parseHostAllowlist(portalReturnUrlAllowedHostsCsv);
}
private static Set<String> parseHostAllowlist(String csv) {
if (csv == null || csv.isBlank()) {
return Collections.emptySet();
}
Set<String> out = new HashSet<>();
for (String raw : Arrays.asList(csv.split(","))) {
String trimmed = raw.trim().toLowerCase(Locale.ROOT);
if (!trimmed.isEmpty()) {
out.add(trimmed);
}
}
return Collections.unmodifiableSet(out);
}
// ---------------------------------------------------------------------------------------
// GET /wallet — the single FE fetch
// ---------------------------------------------------------------------------------------
@GetMapping("/wallet")
@PreAuthorize("isAuthenticated()")
@Transactional(readOnly = true)
public ResponseEntity<WalletSnapshotResponse> getWallet(Authentication auth) {
User user;
try {
user = AuthenticationUtils.getCurrentUser(auth, userRepository);
} catch (SecurityException e) {
// SecurityException maps to 401 per the existing controller convention.
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
}
Optional<TeamMembership> primary = primaryMembership(user.getId());
if (primary.isEmpty()) {
// Authenticated user without a team — shouldn't happen post-migration, but we don't
// want to 500. Return a free-tier-shaped empty snapshot so the FE renders the gated UI
// rather than blowing up on a null body.
return ResponseEntity.ok(emptySnapshot());
}
TeamMembership membership = primary.get();
Long teamId = membership.getTeam().getId();
boolean isLeader = membership.getRole() == TeamRole.LEADER;
Optional<PaygTeamExtensions> extOpt = extRepo.findById(teamId);
Optional<WalletPolicy> policyOpt = policyRepo.findByTeamId(teamId);
EntitlementSnapshot snap = entitlementService.getSnapshot(teamId);
boolean subscribed = isSubscribed(extOpt);
String status = subscribed ? STATUS_SUBSCRIBED : STATUS_FREE;
Long capUnits = policyOpt.map(WalletPolicy::getCapUnits).orElse(null);
boolean noCap = subscribed && capUnits == null;
Integer capUsd =
(subscribed && capUnits != null) ? CapMoneyUnits.unitsToUsd(capUnits) : null;
int spend = clampToInt(snap.periodSpendUnits());
int limit = resolveBillableLimit(subscribed, snap);
LocalDate periodStartDate = snap.periodStart().toLocalDate();
Map<BillingCategory, Long> byCategory =
categorySummaryDao.sumByCategory(teamId, periodStartDate);
CategoryBreakdown breakdown =
new CategoryBreakdown(
clampToInt(byCategory.getOrDefault(BillingCategory.API, 0L)),
clampToInt(byCategory.getOrDefault(BillingCategory.AI, 0L)),
clampToInt(byCategory.getOrDefault(BillingCategory.AUTOMATION, 0L)));
List<MemberRow> members = isLeader ? buildMemberRows(teamId) : List.of();
WalletSnapshotResponse body =
new WalletSnapshotResponse(
status,
isLeader ? ROLE_LEADER : ROLE_MEMBER,
ISO_DATE.format(periodStartDate),
ISO_DATE.format(snap.periodEnd().toLocalDate()),
spend,
limit,
capUsd,
noCap,
// Subscription id sourced from PR #6532's payg_subscription_id column;
// null on this branch until that ships.
null,
spend,
breakdown,
members,
Collections.emptyList());
return ResponseEntity.ok(body);
}
// ---------------------------------------------------------------------------------------
// PATCH /cap — leader-only, cap is application-layer, no Stripe call
// ---------------------------------------------------------------------------------------
@PatchMapping("/cap")
@PreAuthorize("isAuthenticated()")
@Transactional
public ResponseEntity<Void> updateCap(
@Valid @RequestBody UpdateCapRequest req, Authentication auth) {
User user;
try {
user = AuthenticationUtils.getCurrentUser(auth, userRepository);
} catch (SecurityException e) {
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
}
Optional<TeamMembership> primary = primaryMembership(user.getId());
if (primary.isEmpty()) {
// No team → can't have a wallet to cap.
return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
}
TeamMembership membership = primary.get();
if (membership.getRole() != TeamRole.LEADER) {
return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
}
Long teamId = membership.getTeam().getId();
WalletPolicy policy =
policyRepo
.findByTeamId(teamId)
.orElseGet(
() -> {
WalletPolicy created = new WalletPolicy();
created.setTeamId(teamId);
return created;
});
if (req.noCap()) {
policy.setCapUnits(null);
policy.setCapSourceMoney(null);
} else {
policy.setCapUnits(CapMoneyUnits.usdToUnits(req.capUsd()));
policy.setCapSourceMoney(CapMoneyUnits.usdToCents(req.capUsd()));
}
policyRepo.save(policy);
entitlementService.invalidate(teamId);
return ResponseEntity.noContent().build();
}
/** Request body for {@link #updateCap}. */
public record UpdateCapRequest(@Min(0) int capUsd, boolean noCap) {}
// ---------------------------------------------------------------------------------------
// PATCH /sub-caps/{userId} — leader sets a per-member sub-cap inside the team wallet
// ---------------------------------------------------------------------------------------
/**
* Updates {@code team_memberships.cap_units} for the given member of the caller's team.
*
* <p>Authorisation:
*
* <ul>
* <li>caller must be authenticated (else 401);
* <li>caller must be a {@code LEADER} of a team (else 403);
* <li>the target {@code userId} must be a member of the caller's team (else 404).
* </ul>
*
* <p>Clamp rule (per design): if the requested sub-cap exceeds the team-wide {@code
* wallet_policy.cap_units}, the value is silently clamped to the team cap and the response
* carries {@code clamped=true}. We do this at save time rather than rejecting so the leader
* doesn't see a confusing 4xx when they typed a number bigger than the team's own cap — the
* intent ("don't let this member spend more than X") is honoured by setting the effective
* maximum, which is the team cap. If the team has no cap (subscribed, no-cap mode), no clamping
* applies. A {@code null} {@code capUnits} clears the sub-cap entirely (member is bounded only
* by the team cap).
*/
@PatchMapping("/sub-caps/{userId}")
@PreAuthorize("isAuthenticated()")
@Transactional
public ResponseEntity<Map<String, Object>> updateSubCap(
@PathVariable Long userId,
@Valid @RequestBody UpdateSubCapRequest req,
Authentication auth) {
User caller;
try {
caller = AuthenticationUtils.getCurrentUser(auth, userRepository);
} catch (SecurityException e) {
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
}
Optional<TeamMembership> primary = primaryMembership(caller.getId());
if (primary.isEmpty() || primary.get().getRole() != TeamRole.LEADER) {
return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
}
Long teamId = primary.get().getTeam().getId();
// Target must be a member of the same team. Anything else (different team, unknown user)
// is 404 — leaks no information about other teams.
Optional<TeamMembership> targetOpt = memberRepo.findByTeamIdAndUserId(teamId, userId);
if (targetOpt.isEmpty()) {
return ResponseEntity.status(HttpStatus.NOT_FOUND).build();
}
TeamMembership target = targetOpt.get();
// Team cap: null means unlimited (subscribed no-cap). Anything else is a Long ceiling.
Long teamCap = policyRepo.findByTeamId(teamId).map(WalletPolicy::getCapUnits).orElse(null);
Long effective;
boolean clamped = false;
if (req.capUnits() == null) {
effective = null;
} else {
long requested = req.capUnits().longValue();
if (teamCap != null && requested > teamCap) {
effective = teamCap;
clamped = true;
} else {
effective = requested;
}
}
target.setCapUnits(effective);
memberRepo.save(target);
entitlementService.invalidate(teamId);
Map<String, Object> body = new HashMap<>();
body.put("success", true);
// Effective value after clamp; null means "no sub-cap" (member bounded by team cap).
body.put("capUnits", effective);
body.put("clamped", clamped);
return ResponseEntity.ok(body);
}
/**
* Request body for {@link #updateSubCap}.
*
* @param capUnits per-member sub-cap in doc units; {@code null} clears the sub-cap so the
* member is bounded only by the team cap.
*/
public record UpdateSubCapRequest(@Min(0) Integer capUnits) {}
// ---------------------------------------------------------------------------------------
// POST /portal-session — proxy to Supabase create-customer-portal-session edge function
// ---------------------------------------------------------------------------------------
/**
* Mints a Stripe-hosted billing-portal session URL for the caller's team and returns it for the
* FE to redirect to. We proxy through Supabase's {@code create-customer-portal-session} edge
* function rather than calling Stripe directly so the Stripe secret never leaves Supabase and
* portal config stays version-controlled alongside the rest of the billing pipeline.
*
* <p>Authorisation: any authenticated team member can open the portal. The portal itself shows
* billing for the whole team (Stripe customer is per-team), so this is by design — we don't
* gate to leaders the way {@code PATCH /cap} does. If product later wants leader-only access
* we'd add a {@code TeamRole.LEADER} check here.
*
* <p>We pre-check that the team actually has a Stripe customer before calling the edge fn so a
* free-tier team gets a clean 404 + {@code TEAM_NOT_SUBSCRIBED} instead of a generic 502 from a
* downstream error. {@link #isSubscribed(Optional)} stays the source of truth for "subscribed"
* across both this endpoint and {@code GET /wallet}.
*
* <p>The {@code returnUrl} (optional, body field) is validated against the {@code
* payg.portal.allowed-return-hosts} allowlist before forwarding to the edge fn — an
* authenticated attacker can otherwise mint a legit Stripe portal session that bounces the
* victim back to {@code https://evil.example} after they "Return to Stirling." Defense in
* depth: even if the Supabase edge fn enforces its own allowlist, we enforce one here too so
* the security contract is visible in this controller's tests.
*
* <p>Transaction scope: the DB lookup (team membership + {@code payg_team_extensions}) runs
* inside {@link #loadPortalContext}; each Spring Data repo call uses its own short transaction,
* and the {@code JOIN FETCH} on {@code findPrimaryMembership} eagerly hydrates the team so no
* lazy access happens later. The outbound HTTP call to Supabase therefore runs with no DB
* connection held — a slow edge fn cannot pin a HikariCP connection for the full 30s read
* timeout. Same pattern as {@code PaygMeterReportingService}, which fires from a {@code
* JobChargeService} afterCommit hook.
*
* <p>Status map:
*
* <ul>
* <li>200 + {@code {url}} — happy path.
* <li>400 + {@code {error: "INVALID_RETURN_URL"}} — caller-supplied {@code returnUrl} is
* malformed or its host isn't in {@code payg.portal.allowed-return-hosts}.
* <li>401 — anonymous / missing principal.
* <li>403 — authenticated but no team (caller can't have a portal session without one).
* <li>404 + {@code {error: "TEAM_NOT_SUBSCRIBED"}} — team has no Stripe customer yet.
* <li>502 + {@code {error: "PORTAL_UNAVAILABLE"}} — edge fn returned non-2xx or {@code
* success=false}, or the call itself threw.
* <li>503 + {@code {error: "PORTAL_NOT_CONFIGURED"}} — {@code payg.portal.endpoint} is blank
* (local dev / unit tests).
* </ul>
*/
@PostMapping("/portal-session")
@PreAuthorize("isAuthenticated()")
public ResponseEntity<Map<String, Object>> createPortalSession(
@Valid @RequestBody(required = false) PortalSessionRequest req, Authentication auth) {
if (portalEndpoint.isBlank()) {
// Local dev / unit tests without Supabase configured — return a clean 503 instead of
// letting RestTemplate explode on a blank URL.
return ResponseEntity.status(HttpStatus.SERVICE_UNAVAILABLE)
.body(Map.of("error", "PORTAL_NOT_CONFIGURED"));
}
// returnUrl is the only optional field on the body; the body itself is optional too, so a
// caller that doesn't care about a custom return URL can POST with no body at all and let
// the edge fn fall back to its configured default.
String requestedReturnUrl = req == null ? null : req.returnUrl();
if (requestedReturnUrl != null
&& !requestedReturnUrl.isBlank()
&& !isReturnUrlAllowed(requestedReturnUrl)) {
log.warn("Portal session rejected: returnUrl host not on allowlist");
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
.body(Map.of("error", "INVALID_RETURN_URL"));
}
// DB work is in its own readOnly tx; the HTTP call runs outside any transaction.
PortalContext ctx;
try {
ctx = loadPortalContext(auth);
} catch (SecurityException e) {
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
}
if (ctx.notFoundReason() != null) {
return ResponseEntity.status(ctx.status()).body(Map.of("error", ctx.notFoundReason()));
}
if (ctx.status() != HttpStatus.OK) {
return ResponseEntity.status(ctx.status()).build();
}
Long teamId = ctx.teamId();
try {
HttpHeaders headers = new HttpHeaders();
if (!portalServiceRoleToken.isBlank()) {
headers.setBearerAuth(portalServiceRoleToken);
}
headers.setContentType(MediaType.APPLICATION_JSON);
Map<String, Object> body = new HashMap<>();
body.put("team_id", teamId.toString());
if (requestedReturnUrl != null && !requestedReturnUrl.isBlank()) {
body.put("return_url", requestedReturnUrl);
}
ResponseEntity<Map> response =
saasRestTemplate.exchange(
portalEndpoint,
HttpMethod.POST,
new HttpEntity<>(body, headers),
Map.class);
if (!response.getStatusCode().is2xxSuccessful() || response.getBody() == null) {
log.warn(
"Portal session edge fn returned {} for team {}",
response.getStatusCode(),
teamId);
return ResponseEntity.status(HttpStatus.BAD_GATEWAY)
.body(Map.of("error", "PORTAL_UNAVAILABLE"));
}
@SuppressWarnings("unchecked")
Map<String, Object> respBody = (Map<String, Object>) response.getBody();
Object successVal = respBody.get("success");
Object urlVal = respBody.get("url");
boolean success = Boolean.TRUE.equals(successVal);
if (!success || !(urlVal instanceof String) || ((String) urlVal).isBlank()) {
log.warn(
"Portal session edge fn payload invalid for team {}: success={} urlPresent={}",
teamId,
successVal,
urlVal != null);
return ResponseEntity.status(HttpStatus.BAD_GATEWAY)
.body(Map.of("error", "PORTAL_UNAVAILABLE"));
}
return ResponseEntity.ok(Map.of("url", urlVal));
} catch (Exception e) {
// Edge fn unreachable, timeout, malformed response, etc. Anything that propagates up
// becomes a 502 — the caller hits "Manage billing" again or contacts support; we
// never 500 on a downstream wobble.
log.warn("Portal session edge fn call failed for team {}: {}", teamId, e.getMessage());
return ResponseEntity.status(HttpStatus.BAD_GATEWAY)
.body(Map.of("error", "PORTAL_UNAVAILABLE"));
}
}
/**
* Loads the team + subscription state needed by {@link #createPortalSession}.
*
* <p>Each Spring Data repo call gets its own short transaction (managed by the repository
* proxy); {@link TeamMembershipRepository#findPrimaryMembership} uses {@code JOIN FETCH} so the
* returned {@link TeamMembership#getTeam()} is fully initialised — no lazy access happens after
* the call returns. Crucially, by the time this method returns there is <em>no</em> active
* transaction, so the outbound RestTemplate call in {@link #createPortalSession} runs with no
* DB connection held. We deliberately do <em>not</em> mark this {@code @Transactional} because
* Spring's self-invocation proxy semantics mean the annotation would be silently no-op when
* called via {@code this.loadPortalContext(...)}, which is exactly how it is called below.
* Documenting the intent here rather than relying on a non-functional annotation.
*
* <p>Returned {@link PortalContext#status} drives the caller's response: {@code OK} means
* forward to the edge fn, anything else short-circuits with that status (and the optional
* {@code notFoundReason} error body for the 404 case).
*/
PortalContext loadPortalContext(Authentication auth) {
User user = AuthenticationUtils.getCurrentUser(auth, userRepository);
Optional<TeamMembership> primary = primaryMembership(user.getId());
if (primary.isEmpty()) {
// Authenticated but no team → no Stripe customer can exist for them. 403 mirrors the
// cap endpoints' "no team to act on" response.
return new PortalContext(null, HttpStatus.FORBIDDEN, null);
}
Long teamId = primary.get().getTeam().getId();
Optional<PaygTeamExtensions> extOpt = extRepo.findById(teamId);
if (!isSubscribed(extOpt)) {
// Free-tier team — no Stripe customer means no portal to open. The FE shows "Subscribe
// first" rather than a generic error toast.
return new PortalContext(teamId, HttpStatus.NOT_FOUND, "TEAM_NOT_SUBSCRIBED");
}
return new PortalContext(teamId, HttpStatus.OK, null);
}
/** Snapshot of the DB state used by {@link #createPortalSession}. Package-private for tests. */
record PortalContext(Long teamId, HttpStatus status, String notFoundReason) {}
/**
* Returns {@code true} iff the caller-supplied {@code returnUrl} parses cleanly and its host
* appears in {@code payg.portal.allowed-return-hosts}. If the allowlist is empty we reject any
* caller-supplied {@code returnUrl} — the operator must explicitly opt-in to which hosts the
* portal may redirect through. Match is case-insensitive on host; scheme is restricted to
* {@code https} (and {@code http} for local-dev tools that pin to {@code localhost}) so a
* caller can't smuggle a {@code javascript:} or {@code data:} URL past the edge fn.
*/
private boolean isReturnUrlAllowed(String returnUrl) {
if (portalReturnUrlAllowedHosts.isEmpty()) {
return false;
}
URI uri;
try {
uri = new URI(returnUrl);
} catch (URISyntaxException e) {
return false;
}
String scheme = uri.getScheme();
String host = uri.getHost();
if (scheme == null || host == null) {
return false;
}
String lowerScheme = scheme.toLowerCase(Locale.ROOT);
if (!"https".equals(lowerScheme) && !"http".equals(lowerScheme)) {
return false;
}
return portalReturnUrlAllowedHosts.contains(host.toLowerCase(Locale.ROOT));
}
/**
* Request body for {@link #createPortalSession}. {@code returnUrl} is optional — if blank /
* null the edge function falls back to its configured default. We validate the URL's host
* against {@code payg.portal.allowed-return-hosts} before forwarding; see {@link
* #createPortalSession} for the security rationale.
*/
public record PortalSessionRequest(String returnUrl) {}
// ---------------------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------------------
private Optional<TeamMembership> primaryMembership(Long userId) {
List<TeamMembership> rows = memberRepo.findPrimaryMembership(userId);
return rows.isEmpty() ? Optional.empty() : Optional.of(rows.get(0));
}
/**
* Until {@code payg_subscription_id} (PR #6532) lands we treat the presence of {@code
* stripe_customer_id} as a stand-in for "is subscribed." Once that PR merges this check
* collapses to {@code ext.getPaygSubscriptionId() != null}.
*/
private static boolean isSubscribed(Optional<PaygTeamExtensions> extOpt) {
return extOpt.map(PaygTeamExtensions::getStripeCustomerId)
.filter(s -> !s.isBlank())
.isPresent();
}
private List<MemberRow> buildMemberRows(Long teamId) {
List<TeamMembership> all = memberRepo.findByTeamId(teamId);
if (all.isEmpty()) {
return List.of();
}
LocalDateTime[] window = currentMonthWindow();
List<MemberRow> out = new ArrayList<>(all.size());
for (TeamMembership tm : all) {
User u = tm.getUser();
if (u == null) {
continue;
}
// We could batch these; team sizes are small (FE design assumes ≤ ~20 members per
// team on the Plan page) so a per-member sum is fine. If teams grow we'd switch to
// a single GROUP BY actor_user_id query.
long spend = 0L; // sumPeriodAmountForMember stores signed debits (negative); negate.
try {
spend = -memberSpend(teamId, u.getId(), window[0], window[1]);
} catch (RuntimeException e) {
log.warn(
"buildMemberRows: per-member spend lookup failed for user {}",
u.getId(),
e);
}
String displayName =
Optional.ofNullable(u.getUsername())
.orElse(Optional.ofNullable(u.getEmail()).orElse(""));
out.add(
new MemberRow(
Long.toString(u.getId()),
displayName,
Optional.ofNullable(u.getEmail()).orElse(""),
tm.getCapUnits() != null ? tm.getCapUnits().intValue() : null,
clampToInt(spend)));
}
return out;
}
/**
* Per-member period spend in signed ledger units (debits are negative). Helper so the test
* slice can override without standing up a real database, and so the controller doesn't inline
* the negation arithmetic at every call site.
*/
long memberSpend(Long teamId, Long userId, LocalDateTime start, LocalDateTime end) {
return ledgerRepo.sumPeriodAmountForMember(
teamId, userId, LedgerEntryType.DEBIT, start, end);
}
private static LocalDateTime[] currentMonthWindow() {
java.time.YearMonth ym = java.time.YearMonth.now();
LocalDateTime start = ym.atDay(1).atStartOfDay();
LocalDateTime end = ym.plusMonths(1).atDay(1).atStartOfDay();
return new LocalDateTime[] {start, end};
}
private static int clampToInt(long v) {
if (v <= 0) return 0;
if (v >= Integer.MAX_VALUE) return Integer.MAX_VALUE;
return (int) v;
}
private static int resolveBillableLimit(boolean subscribed, EntitlementSnapshot snap) {
if (subscribed) {
// Subscribed teams have no free-tier ceiling — their cap (if any) is what bounds
// them. FE uses billableLimit only to draw the "X of Y" progress when free; for
// subscribed users it reads capUsd/noCap. We still return a sane number so any
// stale UI that reads billableLimit doesn't divide by zero — use the cap if set,
// else MAX_VALUE-shaped sentinel via Integer.MAX_VALUE.
Long cap = snap.periodCapUnits();
if (cap != null) {
return clampToInt(cap);
}
return Integer.MAX_VALUE;
}
// Free tier — prefer the per-team cap if a wallet policy already exists (rare for free
// users), otherwise the fallback free-tier ceiling. PR #6532 will replace this with
// pricing_policy.free_tier_units_per_cycle.
Long cap = snap.periodCapUnits();
if (cap != null) {
return clampToInt(cap);
}
return FREE_TIER_LIMIT_UNITS_FALLBACK;
}
private WalletSnapshotResponse emptySnapshot() {
LocalDateTime[] window = currentMonthWindow();
return new WalletSnapshotResponse(
STATUS_FREE,
ROLE_MEMBER,
ISO_DATE.format(window[0].toLocalDate()),
ISO_DATE.format(window[1].toLocalDate()),
0,
FREE_TIER_LIMIT_UNITS_FALLBACK,
null,
false,
null,
0,
new CategoryBreakdown(0, 0, 0),
List.of(),
Collections.emptyList());
}
}
@@ -0,0 +1,65 @@
package stirling.software.saas.payg.api;
import java.util.List;
/**
* JSON payload returned by {@code GET /api/v1/payg/wallet}. Mirrors the {@code Wallet} type the
* frontend {@code useWallet} hook consumes, plus the leader-only fields ({@code members},
* breakdowns, recent activity) used by the PAYG Plan page.
*
* <p>Field shape is contract-stable: any new optional field must default to a sentinel that the
* frontend's reuse-if-equal comparison treats as "unchanged". {@code recent} is reserved for a
* future activity feed and stays empty in V1.
*
* @param status {@code "free"} when the team has no Stripe subscription; {@code "subscribed"} once
* a card is on file and the engine bills meter events.
* @param role the current caller's role within their team — {@code "leader"} or {@code "member"}.
* Controls which UI variant the frontend renders.
* @param billingPeriodStart inclusive ISO date (yyyy-MM-dd) for the current cycle.
* @param billingPeriodEnd exclusive ISO date (yyyy-MM-dd) for the current cycle.
* @param billableUsed alias of {@code spendUnitsThisPeriod} kept for clarity in the FE.
* @param billableLimit free-tier ceiling in units. {@code 500} during V1 until {@code
* pricing_policy.free_tier_units_per_cycle} (PR #6532) lands and feeds this number live.
* @param capUsd dollar cap when {@code status == "subscribed"}; {@code null} when free or when the
* leader has opted into no-cap.
* @param noCap {@code true} when the leader has explicitly disabled the cap. Only meaningful when
* subscribed.
* @param stripeSubscriptionId Stripe subscription id; {@code null} when status is free. Sourced
* from {@code payg_team_extensions.payg_subscription_id} once PR #6532 lands; falls back to
* {@code null} in this branch (the column doesn't exist yet — flagged dependency).
* @param spendUnitsThisPeriod sum of billable units debited this cycle.
* @param categoryBreakdown per-category spend slice driven by the {@code wallet_category_summary}
* view. Zeroed when the team has no billable activity this period.
* @param members leader-only roster of team members + their per-member sub-caps. Empty for member
* callers.
* @param recent reserved for a future "recent activity" feed; empty in V1.
*/
public record WalletSnapshotResponse(
String status,
String role,
String billingPeriodStart,
String billingPeriodEnd,
int billableUsed,
int billableLimit,
Integer capUsd,
boolean noCap,
String stripeSubscriptionId,
int spendUnitsThisPeriod,
CategoryBreakdown categoryBreakdown,
List<MemberRow> members,
List<Object> recent) {
/**
* Per-category breakdown of {@code spendUnitsThisPeriod} for the in-app analytics widget.
* Sourced from {@code wallet_category_summary} (a Postgres view that filters out {@code
* BYPASSED} and {@code NULL} rows so manual / pre-V16 entries don't pollute the breakdown).
*/
public record CategoryBreakdown(int api, int ai, int automation) {}
/**
* One row of the team-members table on the leader's Plan page. {@code capUnits} is the
* per-member sub-cap (null = bounded only by the team cap).
*/
public record MemberRow(
String userId, String name, String email, Integer capUnits, int spendUnits) {}
}
@@ -0,0 +1,150 @@
package stirling.software.saas.payg.cap;
import java.util.EnumSet;
import java.util.List;
import java.util.Set;
import stirling.software.saas.payg.model.EntitlementState;
import stirling.software.saas.payg.model.FeatureGate;
import stirling.software.saas.payg.model.FeatureSet;
/**
* Pure-compute cap evaluation. Given a team's (or member's) spend, cap, and warn / degrade
* thresholds, returns the {@link EntitlementState}, the {@link FeatureSet} that should be in
* effect, and the corresponding enabled {@link FeatureGate}s. No DB access, no caches — the caller
* (entitlement service) supplies the inputs.
*
* <p>State transitions (matching {@code notes/PAYG_DESIGN.md} §3.6):
*
* <ul>
* <li>{@code capUnits == null} → {@code FULL} / {@link FeatureSet#FULL} unconditionally.
* <li>{@code spend / cap &lt; warnPct} → {@code FULL}.
* <li><b>MINIMAL semantics:</b> under DEGRADED+MINIMAL manual server-side tools (gated by {@link
* FeatureGate#OFFSITE_PROCESSING}) and client-side tools still work; only {@link
* FeatureGate#AUTOMATION} and {@link FeatureGate#AI_SUPPORT} are blocked.
* <li>{@code warnPct ≤ spend / cap &lt; degradePct} → {@code WARNED}; feature set still {@link
* FeatureSet#FULL} — the warn band is a notification trigger, not a degradation.
* <li>{@code spend / cap ≥ degradePct} → {@code DEGRADED}; feature set drops to the policy's
* configured {@code degradedFeatureSet} (default {@link FeatureSet#MINIMAL}).
* </ul>
*
* <p>The percentage compare is integer math. We multiply spend by 100 before dividing — this keeps
* the precision and avoids floating-point on the hot path. Spend × 100 can overflow long at 9.2e16
* units, which is not a realistic value (would represent quintillions of charged documents); we
* don't guard against it.
*/
public final class CapEvaluator {
private CapEvaluator() {}
/**
* Snapshot of one cap evaluation. The caller persists this into the appropriate {@code
* wallet_entitlement_snapshot} row (team-wide or per-member).
*/
public record Evaluation(
EntitlementState state, FeatureSet featureSet, List<FeatureGate> enabledGates) {}
public static Evaluation evaluate(
long spendUnits,
Long capUnits,
int warnAtPct,
int degradeAtPct,
FeatureSet degradedFeatureSet) {
if (capUnits == null || capUnits <= 0) {
return full();
}
if (warnAtPct < 0 || degradeAtPct <= 0 || degradeAtPct < warnAtPct) {
// Defensive: misconfigured thresholds → treat as no-cap-effect to avoid surprise
// degradation. The admin endpoints that set the policy should validate; this
// protects the hot path from a bad row sneaking through.
return full();
}
// pct = floor((spend * 100) / cap). Integer arithmetic on the hot path.
long pct = (spendUnits * 100L) / capUnits;
if (pct >= degradeAtPct) {
FeatureSet effective =
degradedFeatureSet != null ? degradedFeatureSet : FeatureSet.MINIMAL;
return new Evaluation(EntitlementState.DEGRADED, effective, gatesFor(effective));
}
if (pct >= warnAtPct) {
// Warn band: still FULL feature set, but state flag is set so the FE can show a
// banner / send a notification. The wallet service emits a
// WalletEntitlementChanged event when state transitions; subscribers (email
// reminder, SSE to FE) act on that.
return new Evaluation(
EntitlementState.WARNED, FeatureSet.FULL, gatesFor(FeatureSet.FULL));
}
return full();
}
/**
* Combine a team-wide evaluation with a member-specific evaluation. The effective gates for a
* request are the <em>intersection</em> of the two (must be enabled in both), and the effective
* state is the stricter of the two (DEGRADED &gt; WARNED &gt; FULL). Either side may be {@code
* null} — if the member has no sub-cap configured, pass null and the team eval wins.
*/
public static Evaluation combineTeamAndMember(Evaluation team, Evaluation member) {
if (member == null) {
return team;
}
EntitlementState combinedState = strictest(team.state(), member.state());
FeatureSet combinedSet =
combinedState == EntitlementState.DEGRADED
? strictestSet(team.featureSet(), member.featureSet())
: FeatureSet.FULL;
// Intersect enabled gates so a degraded sub-cap can't accidentally let through a
// gate that the team has lost.
EnumSet<FeatureGate> intersection = EnumSet.copyOf(team.enabledGates());
intersection.retainAll(member.enabledGates());
return new Evaluation(combinedState, combinedSet, List.copyOf(intersection));
}
/**
* Default enabled gates for a given feature set. Kept in sync with the design doc §3.7 mapping
* table.
*/
public static List<FeatureGate> gatesFor(FeatureSet set) {
if (set == null) {
return List.of();
}
return switch (set) {
case FULL ->
List.of(
FeatureGate.OFFSITE_PROCESSING,
FeatureGate.AUTOMATION,
FeatureGate.AI_SUPPORT,
FeatureGate.CLIENT_SIDE);
case MINIMAL -> List.of(FeatureGate.OFFSITE_PROCESSING, FeatureGate.CLIENT_SIDE);
case CLIENT_ONLY -> List.of(FeatureGate.CLIENT_SIDE);
};
}
private static Evaluation full() {
return new Evaluation(EntitlementState.FULL, FeatureSet.FULL, gatesFor(FeatureSet.FULL));
}
private static EntitlementState strictest(EntitlementState a, EntitlementState b) {
// Ordinal works here: FULL=0, WARNED=1, DEGRADED=2 in the enum declaration. Higher
// ordinal = stricter. If that ordering changes, this helper must change too.
return a.ordinal() >= b.ordinal() ? a : b;
}
private static FeatureSet strictestSet(FeatureSet a, FeatureSet b) {
// FULL=0, MINIMAL=1, CLIENT_ONLY=2 in the enum declaration. Higher ordinal = stricter.
return a.ordinal() >= b.ordinal() ? a : b;
}
/**
* Helper for the entitlement guard: returns true if all of {@code required} are in {@code
* enabled}. Used to answer "can this request proceed?".
*/
public static boolean allEnabled(Set<FeatureGate> required, List<FeatureGate> enabled) {
if (required == null || required.isEmpty()) {
return true;
}
return enabled != null && enabled.containsAll(required);
}
}
@@ -0,0 +1,46 @@
package stirling.software.saas.payg.cap;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import stirling.software.saas.payg.model.FeatureGate;
/**
* Declares which {@link FeatureGate}(s) a controller method requires. Read at request time by
* {@code EntitlementGuard}; if any required gate is not in the team's currently-enabled gates the
* request is rejected with HTTP 402.
*
* <p>The annotation is <em>not required</em> on every endpoint. The guard's default rule is:
*
* <ul>
* <li>{@code @RequiresFeature} present → use exactly those gates.
* <li>No annotation, but the method has {@code @AutoJobPostMapping} → assume {@link
* FeatureGate#OFFSITE_PROCESSING}.
* <li>Neither → skip (admin endpoints, info, config — these don't accrue charges and shouldn't
* degrade).
* </ul>
*
* <p>So the only endpoints that need this annotation explicitly are those whose gate is
* <em>different</em> from the default {@code OFFSITE_PROCESSING} — chiefly {@code
* PipelineController} ({@link FeatureGate#AUTOMATION}) and the AI proxy layer ({@link
* FeatureGate#AI_SUPPORT}). Per-tool proliferation of the annotation is intentional non-goal.
*
* <p>Multiple gates declared = ALL must be enabled (AND, not OR). Realistic usage is single-gate;
* the array form is here for future combinations (e.g. an AI workflow inside a pipeline that needs
* both {@code AUTOMATION} and {@code AI_SUPPORT}).
*
* <pre>{@code
* @RequiresFeature(FeatureGate.AUTOMATION)
* @AutoJobPostMapping("/pipeline")
* public ResponseEntity<...> runPipeline(@ModelAttribute PipelineRequest req) { ... }
* }</pre>
*/
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface RequiresFeature {
/** One or more gates that must all be enabled for the request to proceed. */
FeatureGate[] value();
}
@@ -1,5 +1,6 @@
package stirling.software.saas.payg.charge;
import stirling.software.saas.payg.model.BillingCategory;
import stirling.software.saas.payg.model.JobSource;
import stirling.software.saas.payg.model.ProcessType;
@@ -8,9 +9,18 @@ import stirling.software.saas.payg.model.ProcessType;
* kind of process this is. Does NOT carry policy fields — the charge service resolves the effective
* policy from {@code PricingPolicyService} so a stale snapshot from the caller can't desync from
* the live policy.
*
* <p>{@code billingCategory} is the analytics axis for ledger + shadow rows and is determined by
* the interceptor before this context is built. Manual UI tools never reach {@code openProcess}
* (they short-circuit on {@link BillingCategory#BYPASSED}); any context constructed here therefore
* carries one of {@code API}, {@code AI}, or {@code AUTOMATION}.
*/
public record ChargeContext(
Long ownerUserId, Long ownerTeamId, JobSource source, ProcessType processType) {
Long ownerUserId,
Long ownerTeamId,
JobSource source,
ProcessType processType,
BillingCategory billingCategory) {
public ChargeContext {
if (ownerUserId == null) {
@@ -22,5 +32,8 @@ public record ChargeContext(
if (processType == null) {
throw new IllegalArgumentException("processType is required");
}
if (billingCategory == null) {
throw new IllegalArgumentException("billingCategory is required");
}
}
}
@@ -11,6 +11,8 @@ import java.util.UUID;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionSynchronization;
import org.springframework.transaction.support.TransactionSynchronizationManager;
import org.springframework.web.multipart.MultipartFile;
import lombok.extern.slf4j.Slf4j;
@@ -21,12 +23,16 @@ import stirling.software.saas.payg.job.JobContext;
import stirling.software.saas.payg.job.JobService;
import stirling.software.saas.payg.job.JoinOrOpenResult;
import stirling.software.saas.payg.job.ProcessingJob;
import stirling.software.saas.payg.meter.PaygMeterReportingService;
import stirling.software.saas.payg.model.BillingCategory;
import stirling.software.saas.payg.model.JobSource;
import stirling.software.saas.payg.model.JobStatus;
import stirling.software.saas.payg.model.ShadowChargeStatus;
import stirling.software.saas.payg.policy.PaygTeamExtensions;
import stirling.software.saas.payg.policy.PricingPolicy;
import stirling.software.saas.payg.policy.PricingPolicyService;
import stirling.software.saas.payg.repository.PaygShadowChargeRepository;
import stirling.software.saas.payg.repository.PaygTeamExtensionsRepository;
import stirling.software.saas.payg.repository.ProcessingJobRepository;
import stirling.software.saas.payg.shadow.PaygShadowCharge;
@@ -55,18 +61,26 @@ public class JobChargeService {
private final DocumentClassifier classifier;
private final PaygShadowChargeRepository shadowRepository;
private final ProcessingJobRepository jobRepository;
private final PaygTeamExtensionsRepository teamExtensionsRepository;
private final PaygMeterReportingService meterReportingService;
public JobChargeService(
JobService jobService,
PricingPolicyService policyService,
DocumentClassifier classifier,
PaygShadowChargeRepository shadowRepository,
ProcessingJobRepository jobRepository) {
ProcessingJobRepository jobRepository,
PaygTeamExtensionsRepository teamExtensionsRepository,
PaygMeterReportingService meterReportingService) {
this.jobService = Objects.requireNonNull(jobService, "jobService");
this.policyService = Objects.requireNonNull(policyService, "policyService");
this.classifier = Objects.requireNonNull(classifier, "classifier");
this.shadowRepository = Objects.requireNonNull(shadowRepository, "shadowRepository");
this.jobRepository = Objects.requireNonNull(jobRepository, "jobRepository");
this.teamExtensionsRepository =
Objects.requireNonNull(teamExtensionsRepository, "teamExtensionsRepository");
this.meterReportingService =
Objects.requireNonNull(meterReportingService, "meterReportingService");
}
/**
@@ -153,6 +167,10 @@ public class JobChargeService {
row.setLegacyCreditsCharged(0);
row.setDiffPct(0);
row.setStatus(ShadowChargeStatus.CHARGED);
// PAYG analytics axis + caller surface — copied from ctx so the row stays self-describing
// after processing_job is pruned. Never affects what Stripe meters (single flat meter).
row.setBillingCategory(ctx.billingCategory());
row.setJobSource(ctx.source());
shadowRepository.save(row);
}
@@ -197,6 +215,105 @@ public class JobChargeService {
}
}
/**
* Closes a process and — for paid teams — pushes a Stripe meter event for the units captured on
* the originating shadow row. Idempotent w.r.t. process state (delegates to {@link
* JobService#close(UUID)}, which silently no-ops on an already-closed row).
*
* <p>The meter POST runs in an {@code afterCommit} hook so we only tell Stripe about work that
* actually committed to our ledger (the customer's bill is authoritative — Stripe is the
* downstream invoice). A failed POST does not roll back the close; the reconciliation backfill
* (separate chunk) is the durability mechanism.
*
* <p>Skipped paths — no meter event fired:
*
* <ul>
* <li>{@code BillingCategory.BYPASSED} on the shadow row (manual UI tool — defensive; the
* interceptor never opens a process for these).
* <li>Refunded shadow row (the customer was credited; nothing to bill).
* <li>Team has no {@link PaygTeamExtensions#getStripeCustomerId() stripe_customer_id} (free
* tier; ledger entry suffices).
* <li>No shadow row at all (job opened outside the shadow path, e.g. legacy import).
* </ul>
*/
@Transactional
public ProcessingJob close(UUID jobId) {
Objects.requireNonNull(jobId, "jobId");
ProcessingJob closed = jobService.close(jobId);
// The afterCommit hook only fires if there's an active transaction (Spring's
// @Transactional ensures that). If we're called outside one — e.g. a test using the raw
// bean — fall through with a debug log: the close() above already happened in a
// sub-transaction created by JobService, but the surrounding scope has no synchronization.
if (!TransactionSynchronizationManager.isSynchronizationActive()) {
log.debug("close({}): no active synchronization; skipping meter POST", jobId);
return closed;
}
TransactionSynchronizationManager.registerSynchronization(
new TransactionSynchronization() {
@Override
public void afterCommit() {
try {
postMeterEventForClose(jobId);
} catch (RuntimeException e) {
// PaygMeterReportingService should already swallow; defence in depth so
// a thrown exception out of afterCommit doesn't leak past the
// synchronization boundary and bubble into the caller.
log.warn(
"afterCommit meter post for job {} threw unexpectedly: {}",
jobId,
e.getMessage());
}
}
});
return closed;
}
private void postMeterEventForClose(UUID jobId) {
Optional<PaygShadowCharge> rowOpt = shadowRepository.findFirstByJobIdOrderByIdAsc(jobId);
if (rowOpt.isEmpty()) {
// No shadow row → not a PAYG-tracked job; nothing to meter.
return;
}
PaygShadowCharge row = rowOpt.get();
if (row.getStatus() == ShadowChargeStatus.REFUNDED) {
// Refunded rows are zero-net charges; do not emit a meter event.
return;
}
BillingCategory category = row.getBillingCategory();
if (category == null || category == BillingCategory.BYPASSED) {
// Defensive: BYPASSED rows shouldn't exist (interceptor short-circuits before
// openProcess), but tolerate if a future caller writes one.
log.debug("close({}): shadow row category={} → no meter event", jobId, category);
return;
}
Integer units = row.getPaygUnits();
if (units == null || units <= 0) {
return;
}
Long teamId = row.getTeamId();
if (teamId == null) {
return;
}
Optional<PaygTeamExtensions> ext = teamExtensionsRepository.findById(teamId);
String stripeCustomerId = ext.map(PaygTeamExtensions::getStripeCustomerId).orElse(null);
if (stripeCustomerId == null || stripeCustomerId.isBlank()) {
// Free-tier team (no Stripe identity) — ledger entry is enough. When PR #6532 lands
// this check tightens to ext.getPaygSubscriptionId() != null, but on this branch the
// presence of stripe_customer_id is the established stand-in for "is subscribed."
log.debug(
"close({}): team {} has no stripeCustomerId → free-tier, no meter event",
jobId,
teamId);
return;
}
String idempotencyKey = "process:" + jobId + ":close";
meterReportingService.recordUsage(
teamId, stripeCustomerId, units, category, idempotencyKey);
}
/**
* Mid-chain 5xx on a JOINED step: return the step slot. The {@code lastStepAt} timestamp stays
* advanced (workflow window intentionally remains active for the next retry). No shadow-row
@@ -0,0 +1,301 @@
package stirling.software.saas.payg.entitlement;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import org.springframework.context.annotation.Profile;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.MeterRegistry;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import stirling.software.common.annotations.AutoJobPostMapping;
import stirling.software.proprietary.security.database.repository.UserRepository;
import stirling.software.proprietary.security.model.ApiKeyAuthenticationToken;
import stirling.software.proprietary.security.model.User;
import stirling.software.saas.payg.cap.RequiresFeature;
import stirling.software.saas.payg.model.FeatureGate;
import stirling.software.saas.util.AuthenticationUtils;
/**
* Hot-path entitlement check. Runs after {@code PaygChargeInterceptor} in the MVC chain and short-
* circuits the request before any handler work happens when the team's snapshot is missing one of
* the gates the route declared via {@link RequiresFeature}.
*
* <p>Scope: routes whose handler method (or bean type) carries either {@link AutoJobPostMapping}
* (multipart tool POSTs) or {@link RequiresFeature} (AI controllers, future non-multipart gated
* routes). Admin / info / config endpoints are excluded by the path-pattern in {@code
* PaygWebMvcConfig} and are additionally skipped here when they carry neither annotation, so non-
* billable infra never trips the guard.
*
* <p>Decision matrix:
*
* <table>
* <tr><th>auth</th><th>required gates</th><th>snapshot enabled?</th><th>outcome</th></tr>
* <tr><td>anonymous</td><td>AUTOMATION or AI_SUPPORT</td><td>n/a</td><td>401 SIGNUP_REQUIRED</td></tr>
* <tr><td>anonymous</td><td>OFFSITE_PROCESSING / CLIENT_SIDE</td><td>n/a</td><td>200 (pass through)</td></tr>
* <tr><td>authenticated</td><td>required ⊆ enabled</td><td>yes</td><td>200</td></tr>
* <tr><td>authenticated</td><td>required ⊄ enabled</td><td>no</td><td>402 FEATURE_DEGRADED</td></tr>
* </table>
*
* <p>Fail-open: any unexpected exception is logged at WARN and the request passes through. The cap
* pipeline must never block a customer because the guard tripped on a transient DB error.
*/
@Slf4j
@Component
@Profile("saas")
public class EntitlementGuard implements HandlerInterceptor {
private static final FeatureGate[] DEFAULT_REQUIRED_GATES = {FeatureGate.OFFSITE_PROCESSING};
private final EntitlementService entitlementService;
private final UserRepository userRepository;
private final ObjectMapper objectMapper;
private final Counter passCounter;
private final Counter deniedDegradedCounter;
private final Counter deniedSignupRequiredCounter;
private final Counter errorsCounter;
private final Counter skippedNoAnnotationCounter;
public EntitlementGuard(
EntitlementService entitlementService,
UserRepository userRepository,
MeterRegistry meterRegistry) {
this.entitlementService = entitlementService;
this.userRepository = userRepository;
this.objectMapper = new ObjectMapper();
this.passCounter =
Counter.builder("payg.entitlement.guard")
.tag("outcome", "pass")
.register(meterRegistry);
this.deniedDegradedCounter =
Counter.builder("payg.entitlement.guard")
.tag("outcome", "denied_degraded")
.register(meterRegistry);
this.deniedSignupRequiredCounter =
Counter.builder("payg.entitlement.guard")
.tag("outcome", "denied_signup_required")
.register(meterRegistry);
this.skippedNoAnnotationCounter =
Counter.builder("payg.entitlement.guard")
.tag("outcome", "skipped")
.register(meterRegistry);
this.errorsCounter =
Counter.builder("payg.entitlement.guard.errors")
.description("EntitlementGuard internal failures (fail-open)")
.register(meterRegistry);
}
@Override
public boolean preHandle(
HttpServletRequest request, HttpServletResponse response, Object handler) {
if (!(handler instanceof HandlerMethod hm)) {
return true;
}
// Scope: AutoJobPostMapping routes (multipart tool POSTs) OR routes that explicitly
// declare @RequiresFeature (e.g. AI controllers — JSON-bodied, no AutoJobPostMapping).
// Admin / info / config endpoints carry neither annotation and never trip the guard.
boolean hasAutoJobPostMapping =
AnnotationUtils.findAnnotation(hm.getMethod(), AutoJobPostMapping.class) != null
|| AnnotationUtils.findAnnotation(
hm.getBeanType(), AutoJobPostMapping.class)
!= null;
boolean hasRequiresFeature =
AnnotationUtils.findAnnotation(hm.getMethod(), RequiresFeature.class) != null
|| AnnotationUtils.findAnnotation(hm.getBeanType(), RequiresFeature.class)
!= null;
if (!hasAutoJobPostMapping && !hasRequiresFeature) {
skippedNoAnnotationCounter.increment();
return true;
}
FeatureGate[] required = resolveRequiredGates(hm);
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
boolean anonymous = isAnonymous(auth);
boolean billable = isBillable(required);
if (anonymous) {
if (billable) {
return write401SignupRequired(response, required);
}
// Anonymous user calling a manual / OFFSITE-only tool — let it through; PAYG only
// charges authenticated requests.
passCounter.increment();
return true;
}
Long teamId;
try {
teamId = resolveTeamId(auth);
} catch (RuntimeException e) {
log.warn("EntitlementGuard resolveTeamId failed; passing through", e);
errorsCounter.increment();
return true;
}
if (teamId == null) {
// Defensive: authenticated principal with no team — shouldn't happen post-migration,
// but we don't want to lock those users out. PaygChargeInterceptor short-circuits the
// same shape upstream.
passCounter.increment();
return true;
}
EntitlementSnapshot snapshot;
try {
snapshot = entitlementService.getSnapshot(teamId);
} catch (RuntimeException e) {
log.warn("EntitlementGuard getSnapshot failed for team {}; passing through", teamId, e);
errorsCounter.increment();
return true;
}
List<FeatureGate> enabled = snapshot.enabledGates();
for (FeatureGate gate : required) {
if (enabled == null || !enabled.contains(gate)) {
return write402FeatureDegraded(response, required, snapshot);
}
}
passCounter.increment();
return true;
}
static FeatureGate[] resolveRequiredGates(HandlerMethod hm) {
RequiresFeature ann = AnnotationUtils.findAnnotation(hm.getMethod(), RequiresFeature.class);
if (ann == null) {
ann = AnnotationUtils.findAnnotation(hm.getBeanType(), RequiresFeature.class);
}
if (ann != null && ann.value().length > 0) {
return ann.value();
}
return DEFAULT_REQUIRED_GATES;
}
private static boolean isAnonymous(Authentication auth) {
if (auth == null || !auth.isAuthenticated()) {
return true;
}
// Spring's anonymous filter installs a token whose name is "anonymousUser".
return "anonymousUser".equals(auth.getName());
}
private static boolean isBillable(FeatureGate[] required) {
for (FeatureGate g : required) {
if (g == FeatureGate.AUTOMATION || g == FeatureGate.AI_SUPPORT) {
return true;
}
}
return false;
}
private Long resolveTeamId(Authentication auth) {
if (auth instanceof ApiKeyAuthenticationToken
&& auth.getPrincipal() instanceof User apiUser) {
return apiUser.getTeam() == null ? null : apiUser.getTeam().getId();
}
String supabaseId = AuthenticationUtils.extractSupabaseId(auth);
if (supabaseId == null) {
return null;
}
UUID supabaseUuid;
try {
supabaseUuid = UUID.fromString(supabaseId);
} catch (IllegalArgumentException e) {
// Username-style principals (legacy local accounts) — no Supabase ID to look up. Skip.
return null;
}
return userRepository
.findBySupabaseId(supabaseUuid)
.map(u -> u.getTeam() == null ? null : u.getTeam().getId())
.orElse(null);
}
private boolean write401SignupRequired(HttpServletResponse response, FeatureGate[] required) {
deniedSignupRequiredCounter.increment();
Map<String, Object> body = new LinkedHashMap<>();
body.put("error", "SIGNUP_REQUIRED");
body.put("category", inferCategory(required));
writeJson(response, HttpStatus.UNAUTHORIZED, body);
return false;
}
private boolean write402FeatureDegraded(
HttpServletResponse response, FeatureGate[] required, EntitlementSnapshot snapshot) {
deniedDegradedCounter.increment();
Map<String, Object> body = new LinkedHashMap<>();
body.put("error", "FEATURE_DEGRADED");
body.put("missingGates", missingGates(required, snapshot.enabledGates()));
body.put("state", snapshot.state().name());
body.put(
"periodEnd",
Optional.ofNullable(snapshot.periodEnd()).map(Object::toString).orElse(null));
body.put("capUnits", snapshot.periodCapUnits());
body.put("spendUnits", snapshot.periodSpendUnits());
writeJson(response, HttpStatus.PAYMENT_REQUIRED, body);
return false;
}
private static List<String> missingGates(FeatureGate[] required, List<FeatureGate> enabled) {
List<FeatureGate> enabledOrEmpty = enabled == null ? Collections.emptyList() : enabled;
return Arrays.stream(required)
.filter(g -> !enabledOrEmpty.contains(g))
.map(Enum::name)
.toList();
}
private static String inferCategory(FeatureGate[] required) {
// Mirrors PaygChargeInterceptor.determineCategory precedence: AUTOMATION dominates AI.
for (FeatureGate g : required) {
if (g == FeatureGate.AUTOMATION) {
return "AUTOMATION";
}
}
for (FeatureGate g : required) {
if (g == FeatureGate.AI_SUPPORT) {
return "AI";
}
}
return "OFFSITE_PROCESSING";
}
private void writeJson(
HttpServletResponse response, HttpStatus status, Map<String, Object> body) {
response.setStatus(status.value());
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
response.setCharacterEncoding("UTF-8");
try {
byte[] payload = objectMapper.writeValueAsBytes(body);
response.setHeader(HttpHeaders.CONTENT_LENGTH, Integer.toString(payload.length));
response.getOutputStream().write(payload);
response.getOutputStream().flush();
} catch (IOException e) {
// Container will fall back to its default error page — we did set the status code,
// so the client still sees the right HTTP code even if the body fails to write.
log.warn("EntitlementGuard write response body failed", e);
errorsCounter.increment();
}
}
}
@@ -0,0 +1,227 @@
package stirling.software.saas.payg.entitlement;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.YearMonth;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import lombok.extern.slf4j.Slf4j;
import stirling.software.saas.payg.cap.CapEvaluator;
import stirling.software.saas.payg.cap.CapEvaluator.Evaluation;
import stirling.software.saas.payg.model.EntitlementState;
import stirling.software.saas.payg.model.FeatureGate;
import stirling.software.saas.payg.model.FeatureSet;
import stirling.software.saas.payg.model.LedgerEntryType;
import stirling.software.saas.payg.policy.PaygTeamExtensions;
import stirling.software.saas.payg.repository.PaygTeamExtensionsRepository;
import stirling.software.saas.payg.repository.WalletLedgerRepository;
import stirling.software.saas.payg.repository.WalletPolicyRepository;
import stirling.software.saas.payg.wallet.WalletPolicy;
/**
* Hot-path entitlement lookup. Returns the {@link EntitlementSnapshot} for a team, computed from
* the team's subscription state (subscribed → {@code wallet_policy.cap_units}; un-subscribed →
* free-tier units per cycle) and the team's current-period spend in the ledger.
*
* <p>Backed by a per-team Caffeine cache with {@value #CACHE_TTL_SECONDS}s TTL and {@value
* #CACHE_MAX_SIZE}-entry cap. The TTL is the correctness floor — a cap change becomes visible on
* every instance within that window without coordination. Mutators (wallet policy admin updates,
* subscription webhook handlers) call {@link #invalidate(Long)} to drop a single team's entry
* immediately on the originating instance.
*
* <p><b>Dependencies not on this branch (PR #6532):</b> the snapshot ideally reads {@code
* pricing_policy.free_tier_units_per_cycle} and {@code payg_team_extensions.payg_subscription_id}.
* Locally we fall back to {@value #DEFAULT_FREE_TIER_UNITS} units / cycle for teams without a
* wallet policy, which preserves the "MINIMAL once over the cap" behaviour the guard relies on.
* Once PR #6532 lands and those columns exist, the {@link #resolveCapUnits} branch should switch to
* reading {@code freeTierUnitsPerCycle} when {@code paygSubscriptionId} is null.
*/
@Slf4j
@Service
@Profile("saas")
public class EntitlementService {
static final int CACHE_TTL_SECONDS = 30;
private static final int CACHE_MAX_SIZE = 10_000;
/**
* Default free-tier cap used when no {@code wallet_policy} row exists for the team and the
* {@code free_tier_units_per_cycle} column isn't available yet (pre-#6532 local schema). Keeps
* un-subscribed teams gated on a sensible default rather than uncapped.
*/
static final long DEFAULT_FREE_TIER_UNITS = 500L;
private static final int WARN_AT_PCT = 80;
private static final int DEGRADE_AT_PCT = 100;
private final PaygTeamExtensionsRepository teamExtensionsRepository;
private final WalletPolicyRepository walletPolicyRepository;
private final WalletLedgerRepository ledgerRepository;
private final Cache<Long, EntitlementSnapshot> snapshotCache;
public EntitlementService(
PaygTeamExtensionsRepository teamExtensionsRepository,
WalletPolicyRepository walletPolicyRepository,
WalletLedgerRepository ledgerRepository) {
this.teamExtensionsRepository =
Objects.requireNonNull(teamExtensionsRepository, "teamExtensionsRepository");
this.walletPolicyRepository =
Objects.requireNonNull(walletPolicyRepository, "walletPolicyRepository");
this.ledgerRepository = Objects.requireNonNull(ledgerRepository, "ledgerRepository");
this.snapshotCache =
Caffeine.newBuilder()
.maximumSize(CACHE_MAX_SIZE)
.expireAfterWrite(Duration.ofSeconds(CACHE_TTL_SECONDS))
.recordStats()
.build();
}
/**
* Returns the entitlement snapshot for {@code teamId}. Caches per-team for {@value
* #CACHE_TTL_SECONDS}s — burst requests share a single SUM query against the ledger.
*
* <p>{@code null} teamId throws — the guard short-circuits team-less requests upstream so a
* null reach here is a programming error.
*/
public EntitlementSnapshot getSnapshot(Long teamId) {
Objects.requireNonNull(teamId, "teamId");
return snapshotCache.get(teamId, this::computeSnapshot);
}
/**
* Drops {@code teamId}'s cache entry. Call after subscription state changes (webhook handlers),
* cap edits, or manual ledger adjustments so the next read recomputes immediately rather than
* waiting out the TTL.
*/
public void invalidate(Long teamId) {
if (teamId != null) {
snapshotCache.invalidate(teamId);
}
}
/** Visible for tests. */
long cacheSize() {
return snapshotCache.estimatedSize();
}
@Transactional(readOnly = true)
EntitlementSnapshot computeSnapshot(Long teamId) {
Optional<PaygTeamExtensions> extensionsOpt = teamExtensionsRepository.findById(teamId);
Optional<WalletPolicy> walletPolicyOpt = walletPolicyRepository.findByTeamId(teamId);
Long capUnits = resolveCapUnits(extensionsOpt, walletPolicyOpt);
FeatureSet degradedSet =
walletPolicyOpt.map(WalletPolicy::getDegradedFeatureSet).orElse(FeatureSet.MINIMAL);
int warnAtPct =
walletPolicyOpt
.map(WalletPolicy::getWarnAtPct)
.filter(Objects::nonNull)
.orElse(WARN_AT_PCT);
int degradeAtPct =
walletPolicyOpt
.map(WalletPolicy::getDegradeAtPct)
.filter(Objects::nonNull)
.orElse(DEGRADE_AT_PCT);
LocalDateTime[] window = currentMonthWindow();
LocalDateTime periodStart = window[0];
LocalDateTime periodEnd = window[1];
// wallet_ledger stores debits as negative amount_units (signed). The cap evaluator wants
// positive spend, so we negate the SUM. COALESCE in the JPQL guarantees 0 for no-rows.
long signedDebitSum =
ledgerRepository.sumPeriodAmount(
teamId, LedgerEntryType.DEBIT, periodStart, periodEnd);
long spendUnits = signedDebitSum < 0 ? -signedDebitSum : 0L;
Evaluation eval =
CapEvaluator.evaluate(spendUnits, capUnits, warnAtPct, degradeAtPct, degradedSet);
return new EntitlementSnapshot(
eval.state(),
eval.featureSet(),
List.copyOf(eval.enabledGates()),
spendUnits,
capUnits,
periodStart,
periodEnd);
}
/**
* Resolve the period cap.
*
* <p>Target design (once PR #6532 lands):
*
* <ul>
* <li>{@code paygSubscriptionId != null} → {@code wallet_policy.cap_units}.
* <li>{@code paygSubscriptionId == null} → {@code pricing_policy.free_tier_units_per_cycle}.
* </ul>
*
* <p>Current branch (pre-#6532) doesn't have {@code paygSubscriptionId} or {@code
* freeTierUnitsPerCycle} columns. Fallback rule:
*
* <ul>
* <li>{@code wallet_policy} present → its {@code cap_units} (may be null → uncapped, which
* matches the "no cap configured" semantics of {@link CapEvaluator}).
* <li>{@code wallet_policy} absent → {@link #DEFAULT_FREE_TIER_UNITS} units / cycle.
* </ul>
*/
private Long resolveCapUnits(
Optional<PaygTeamExtensions> extensions, Optional<WalletPolicy> walletPolicy) {
// Suppress unused-variable warning until #6532 lands and we read paygSubscriptionId here.
if (extensions.isPresent()) {
// Intentionally read but unused: keep the lookup so the SELECT happens (warms team
// extensions caches the rest of the request path needs) and document where the
// post-#6532 branch will live.
}
if (walletPolicy.isPresent()) {
return walletPolicy.get().getCapUnits();
}
return DEFAULT_FREE_TIER_UNITS;
}
/**
* Inclusive-start / exclusive-end window for the calendar-month period. Calendar-month is the
* only period used at this stage; once {@code BILLING_CYCLE} ships the window resolution moves
* to the wallet policy.
*/
static LocalDateTime[] currentMonthWindow() {
return currentMonthWindow(LocalDateTime.now());
}
/** Test seam — accepts a clock value so tests don't race the calendar boundary. */
static LocalDateTime[] currentMonthWindow(LocalDateTime now) {
YearMonth ym = YearMonth.from(now);
LocalDateTime start = ym.atDay(1).atStartOfDay();
LocalDateTime end = ym.plusMonths(1).atDay(1).atStartOfDay();
return new LocalDateTime[] {start, end};
}
/** Snapshot for an anonymous / null-team request — never billable, never degraded. */
public static EntitlementSnapshot anonymousFull() {
LocalDateTime[] w = currentMonthWindow();
return new EntitlementSnapshot(
EntitlementState.FULL,
FeatureSet.FULL,
List.of(
FeatureGate.OFFSITE_PROCESSING,
FeatureGate.AUTOMATION,
FeatureGate.AI_SUPPORT,
FeatureGate.CLIENT_SIDE),
0L,
null,
w[0],
w[1]);
}
}
@@ -0,0 +1,42 @@
package stirling.software.saas.payg.entitlement;
import java.time.LocalDateTime;
import java.util.List;
import stirling.software.saas.payg.model.EntitlementState;
import stirling.software.saas.payg.model.FeatureGate;
import stirling.software.saas.payg.model.FeatureSet;
/**
* Immutable snapshot of a team's entitlement state as of a single point in time. Returned by {@link
* EntitlementService#getSnapshot(Long)} and consumed by {@code EntitlementGuard}.
*
* <p>Contrast with {@link WalletEntitlementSnapshot}: the JPA entity is the <em>persisted</em>
* snapshot that the recompute path writes (one row per team, optionally per member). This record is
* the <em>computed-now</em> view the hot-path guard reads — backed by a 30s Caffeine cache so a
* request burst doesn't hammer the ledger SUM.
*
* @param state aggregate state — FULL, WARNED, or DEGRADED.
* @param featureSet bundle name in effect (FULL on no-cap / warn band; degraded set on DEGRADED).
* @param enabledGates the gates the guard checks against — request proceeds only if every required
* gate is in this list.
* @param periodSpendUnits sum of debited units in {@code [periodStart, periodEnd)}, in canonical
* doc-units (positive).
* @param periodCapUnits the cap applied — free-tier units for un-subscribed teams, {@code
* wallet_policy.cap_units} for subscribed teams. {@code null} means uncapped.
* @param periodStart inclusive start of the current cap period.
* @param periodEnd exclusive end of the current cap period.
*/
public record EntitlementSnapshot(
EntitlementState state,
FeatureSet featureSet,
List<FeatureGate> enabledGates,
long periodSpendUnits,
Long periodCapUnits,
LocalDateTime periodStart,
LocalDateTime periodEnd) {
public boolean isDegraded() {
return state == EntitlementState.DEGRADED;
}
}
@@ -12,6 +12,7 @@ import java.util.Optional;
import java.util.UUID;
import org.springframework.context.annotation.Profile;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
@@ -36,11 +37,14 @@ import stirling.software.common.util.TempFileManager;
import stirling.software.proprietary.security.database.repository.UserRepository;
import stirling.software.proprietary.security.model.ApiKeyAuthenticationToken;
import stirling.software.proprietary.security.model.User;
import stirling.software.saas.payg.cap.RequiresFeature;
import stirling.software.saas.payg.charge.ChargeContext;
import stirling.software.saas.payg.charge.ChargeOutcome;
import stirling.software.saas.payg.charge.JobChargeService;
import stirling.software.saas.payg.charge.JobInput;
import stirling.software.saas.payg.job.JobService;
import stirling.software.saas.payg.model.BillingCategory;
import stirling.software.saas.payg.model.FeatureGate;
import stirling.software.saas.payg.model.JobSource;
import stirling.software.saas.payg.model.JobStepStatus;
import stirling.software.saas.payg.model.ProcessType;
@@ -51,10 +55,13 @@ import stirling.software.saas.util.AuthenticationUtils;
* after it in {@code PaygWebMvcConfig} so legacy credit-rejection short-circuits before we waste
* work hashing inputs.
*
* <p>{@code preHandle}: gates on {@code @AutoJobPostMapping}, reads the parsed multipart parts,
* materialises each input to a {@code TempFile}, and asks {@link JobChargeService#openProcess} to
* open (or join) a process. The resulting {@link ChargeOutcome} plus input temp-files are stashed
* as request attributes for {@code afterCompletion}.
* <p>{@code preHandle}: gates on {@code @AutoJobPostMapping} OR {@code @RequiresFeature} (the
* latter lets AI controllers — JSON-bodied, no AutoJobPostMapping — bill correctly), reads the
* parsed multipart parts, materialises each input to a {@code TempFile}, and asks {@link
* JobChargeService#openProcess} to open (or join) a process. The resulting {@link ChargeOutcome}
* plus input temp-files are stashed as request attributes for {@code afterCompletion}. Routes
* without multipart inputs short-circuit inside {@code doPreHandle} without touching the charge
* service.
*
* <p>{@code afterCompletion}: branches on HTTP status — 2xx hashes the response body for OUTPUT
* lineage; 4xx records a step append for audit; 5xx triggers refund-and-close (OPENED) or
@@ -93,6 +100,7 @@ public class PaygChargeInterceptor implements AsyncHandlerInterceptor {
private final Counter callsOpened;
private final Counter callsJoined;
private final Counter callsShortCircuit;
private final Counter callsBypassed;
private final Counter refundsCounter;
private final Timer durationTimer;
@@ -127,6 +135,11 @@ public class PaygChargeInterceptor implements AsyncHandlerInterceptor {
Counter.builder("payg.filter.calls")
.tag("disposition", "SHORT_CIRCUIT")
.register(meterRegistry);
this.callsBypassed =
Counter.builder("payg.filter.bypassed")
.description(
"Manual UI tool calls that skipped openProcess (BillingCategory.BYPASSED)")
.register(meterRegistry);
this.refundsCounter =
Counter.builder("payg.filter.refunds")
.description("First-step 5xx refunds applied to shadow rows")
@@ -145,13 +158,39 @@ public class PaygChargeInterceptor implements AsyncHandlerInterceptor {
if (!properties.isEnabled()) {
return true;
}
if (!(handler instanceof HandlerMethod hm)
|| hm.getMethodAnnotation(AutoJobPostMapping.class) == null) {
if (!(handler instanceof HandlerMethod hm)) {
callsShortCircuit.increment();
return true;
}
// In-scope when the handler carries @AutoJobPostMapping (multipart tool POSTs) OR
// @RequiresFeature (AI controllers, future non-multipart gated routes). Without one of
// these the interceptor short-circuits — admin / info / static routes never run
// determineCategory.
boolean hasAutoJobPostMapping =
AnnotationUtils.findAnnotation(hm.getMethod(), AutoJobPostMapping.class) != null
|| AnnotationUtils.findAnnotation(
hm.getBeanType(), AutoJobPostMapping.class)
!= null;
boolean hasRequiresFeature =
AnnotationUtils.findAnnotation(hm.getMethod(), RequiresFeature.class) != null
|| AnnotationUtils.findAnnotation(
hm.getBeanType(), RequiresFeature.class)
!= null;
if (!hasAutoJobPostMapping && !hasRequiresFeature) {
callsShortCircuit.increment();
return true;
}
// Bypass fast-path: determine the BillingCategory BEFORE any multipart
// materialisation or openProcess call. Manual UI tool calls (BYPASSED) skip the
// entire ledger/shadow pipeline — no temp files, no DB writes.
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
BillingCategory category = determineCategory(hm, request, auth);
if (category == BillingCategory.BYPASSED) {
callsBypassed.increment();
return true;
}
try {
doPreHandle(request);
doPreHandle(request, auth, category);
} catch (RuntimeException e) {
log.warn("PAYG preHandle failed; passing through unbilled", e);
errorsCounter.increment();
@@ -164,8 +203,8 @@ public class PaygChargeInterceptor implements AsyncHandlerInterceptor {
}
}
private void doPreHandle(HttpServletRequest request) {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
private void doPreHandle(
HttpServletRequest request, Authentication auth, BillingCategory category) {
User currentUser = resolveUser(auth);
if (currentUser == null) {
callsShortCircuit.increment();
@@ -225,7 +264,8 @@ public class PaygChargeInterceptor implements AsyncHandlerInterceptor {
currentUser.getId(),
currentUser.getTeam() == null ? null : currentUser.getTeam().getId(),
determineSource(request, auth),
ProcessType.SINGLE_TOOL);
ProcessType.SINGLE_TOOL,
category);
ChargeOutcome outcome;
try {
@@ -417,4 +457,44 @@ public class PaygChargeInterceptor implements AsyncHandlerInterceptor {
}
return JobSource.WEB;
}
/**
* Resolve the {@link BillingCategory} for this request. Precedence: {@code
* X-Stirling-Automation: true} or {@code @RequiresFeature(AUTOMATION)} → AUTOMATION;
* {@code @RequiresFeature(AI_SUPPORT)} → AI; API-key auth → API; otherwise BYPASSED (manual UI
* tool — short-circuited in {@link #preHandle}).
*
* <p>Method-level {@code @RequiresFeature} wins over class-level. Multiple gates: AUTOMATION
* dominates AI within a single annotation.
*/
private static BillingCategory determineCategory(
HandlerMethod handler, HttpServletRequest request, Authentication auth) {
String automationHeader = request.getHeader(AUTOMATION_HEADER);
if (automationHeader != null && "true".equalsIgnoreCase(automationHeader.trim())) {
return BillingCategory.AUTOMATION;
}
RequiresFeature ann =
AnnotationUtils.findAnnotation(handler.getMethod(), RequiresFeature.class);
if (ann == null) {
ann = AnnotationUtils.findAnnotation(handler.getBeanType(), RequiresFeature.class);
}
if (ann != null) {
boolean ai = false;
for (FeatureGate gate : ann.value()) {
if (gate == FeatureGate.AUTOMATION) {
return BillingCategory.AUTOMATION;
}
if (gate == FeatureGate.AI_SUPPORT) {
ai = true;
}
}
if (ai) {
return BillingCategory.AI;
}
}
if (auth instanceof ApiKeyAuthenticationToken) {
return BillingCategory.API;
}
return BillingCategory.BYPASSED;
}
}
@@ -9,6 +9,8 @@ import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import lombok.RequiredArgsConstructor;
import stirling.software.saas.payg.entitlement.EntitlementGuard;
/**
* Wires the PAYG filter + interceptor into Spring MVC. Two registrations:
*
@@ -28,6 +30,7 @@ import lombok.RequiredArgsConstructor;
public class PaygWebMvcConfig implements WebMvcConfigurer {
private final PaygChargeInterceptor paygChargeInterceptor;
private final EntitlementGuard entitlementGuard;
@Bean
public FilterRegistrationBean<PaygResponseBodyWrapperFilter>
@@ -46,6 +49,16 @@ public class PaygWebMvcConfig implements WebMvcConfigurer {
*/
public static final int INTERCEPTOR_ORDER = 1000;
/**
* The entitlement guard runs AFTER the charge interceptor so cap-rejected requests still leave
* the charge interceptor's preHandle state in the consistent open-or-bypassed shape (and so the
* guard's 402 reaches the client without the charge interceptor needing to know about it).
* Spring runs interceptors in registration order on the way in, reverse order on the way out;
* the guard's preHandle short-circuit ({@code return false}) prevents the handler from running
* but Spring still invokes the charge interceptor's afterCompletion to clean up temp files.
*/
public static final int ENTITLEMENT_GUARD_ORDER = 1100;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(paygChargeInterceptor)
@@ -56,5 +69,14 @@ public class PaygWebMvcConfig implements WebMvcConfigurer {
"/api/v1/info/**",
"/api/v1/admin/**")
.order(INTERCEPTOR_ORDER);
registry.addInterceptor(entitlementGuard)
.addPathPatterns("/api/**")
.excludePathPatterns(
"/api/v1/credits/**",
"/api/v1/config/**",
"/api/v1/info/**",
"/api/v1/admin/**")
.order(ENTITLEMENT_GUARD_ORDER);
}
}
@@ -0,0 +1,142 @@
package stirling.software.saas.payg.meter;
import java.util.Map;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Profile;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.MeterRegistry;
import lombok.extern.slf4j.Slf4j;
import stirling.software.saas.payg.model.BillingCategory;
/**
* POSTs PAYG billable usage to the Supabase {@code meter-payg-units} edge function. Called from
* {@code JobChargeService.close()} in an {@code afterCommit} hook, so the wallet ledger DEBIT (the
* customer's authoritative bill) is already durable before we tell Stripe about it.
*
* <p>Stripe is on a single flat-priced meter forever. {@link BillingCategory} ships as metadata for
* analytics — pricing never reads it. Free-tier teams (no Stripe subscription) skip this call
* entirely; the ledger entry is the only record needed.
*
* <p>Failure mode: we owe Stripe an event but the customer's bill via the ledger is correct. Log
* WARN, bump {@code payg.meter.errors}, and swallow — the meter event log table on Supabase plus
* the reconciliation job (separate chunk) is the durability story, not retries here. Caller's
* {@code close()} must not roll back because Stripe wobbled.
*
* <p>Both config keys default to empty so unit tests / local dev never crash on missing env. When
* blank, this service no-ops at WARN-debug level — useful for SaaS smoke tests that don't want to
* touch the real edge function.
*/
@Service
@Profile("saas")
@Slf4j
public class PaygMeterReportingService {
private final String endpoint;
private final String serviceRoleToken;
private final RestTemplate restTemplate;
private final Counter errorsCounter;
public PaygMeterReportingService(
@Value("${payg.meter.endpoint:}") String endpoint,
@Value("${payg.meter.service-role-token:}") String serviceRoleToken,
RestTemplate saasRestTemplate,
MeterRegistry meterRegistry) {
this.endpoint = endpoint;
this.serviceRoleToken = serviceRoleToken;
this.restTemplate = saasRestTemplate;
this.errorsCounter =
Counter.builder("payg.meter.errors")
.description("Failures POSTing PAYG meter events to Supabase edge function")
.register(meterRegistry);
}
/**
* Best-effort POST of a single billable event. Idempotency on the Supabase side is keyed on
* {@code idempotency_key} — supply a deterministic value (e.g. {@code "process:<uuid>:close"})
* so a retry, a reconciliation replay, or a double-fire from two pods never charges twice.
*
* <p>Never throws. The wallet ledger entry is the source of truth for what the customer is
* billed; if this method fails the only loss is that Stripe doesn't see this event until the
* reconciliation backfill runs.
*/
public void recordUsage(
Long teamId,
String stripeCustomerId,
int units,
BillingCategory category,
String idempotencyKey) {
if (endpoint == null || endpoint.isBlank()) {
log.debug(
"payg.meter.endpoint not configured; skipping meter event for team {} key {}",
teamId,
idempotencyKey);
return;
}
if (units <= 0) {
// Zero-unit events would inflate event count without changing the bill — defensive.
log.debug(
"Skipping meter event with units={} for team {} key {}",
units,
teamId,
idempotencyKey);
return;
}
try {
HttpHeaders headers = new HttpHeaders();
if (serviceRoleToken != null && !serviceRoleToken.isBlank()) {
headers.setBearerAuth(serviceRoleToken);
}
headers.setContentType(MediaType.APPLICATION_JSON);
Map<String, Object> body =
Map.of(
"team_id",
teamId == null ? "" : teamId.toString(),
"stripe_customer_id",
stripeCustomerId == null ? "" : stripeCustomerId,
"units",
units,
"idempotency_key",
idempotencyKey,
"metadata",
Map.of("category", category == null ? "UNKNOWN" : category.name()));
ResponseEntity<String> response =
restTemplate.exchange(
endpoint,
HttpMethod.POST,
new HttpEntity<>(body, headers),
String.class);
if (!response.getStatusCode().is2xxSuccessful()) {
log.warn(
"Meter event POST returned {} for team {} key {}: {}",
response.getStatusCode(),
teamId,
idempotencyKey,
response.getBody());
errorsCounter.increment();
}
} catch (Exception e) {
// Catch-all by design: this method MUST NOT propagate. The customer's bill via the
// ledger is correct; we just owe Stripe an event we'll backfill via reconciliation.
log.warn(
"Meter event POST failed for team {} key {}: {}",
teamId,
idempotencyKey,
e.getMessage());
errorsCounter.increment();
}
}
}
@@ -0,0 +1,18 @@
package stirling.software.saas.payg.model;
/**
* Analytics / in-app breakdown axis stamped on every billable ledger entry and shadow charge. PAYG
* stays on a single flat-priced Stripe meter — category is metadata only, never affects pricing.
*
* <p>Precedence at translation time (interceptor): AUTOMATION → AI → API → BYPASSED. {@link
* #BYPASSED} is the default for manual UI tool calls that never hit a billable code path.
*
* <p>Listing order matters only as the default sentinel ({@link #BYPASSED} first); no downstream
* relies on {@code ordinal()}.
*/
public enum BillingCategory {
BYPASSED,
API,
AI,
AUTOMATION
}
@@ -0,0 +1,79 @@
package stirling.software.saas.payg.repository;
import java.time.LocalDate;
import java.util.EnumMap;
import java.util.Map;
import java.util.Objects;
import org.springframework.context.annotation.Profile;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import stirling.software.saas.payg.model.BillingCategory;
/**
* Thin JDBC accessor for the {@code wallet_category_summary} view defined in V16. The view exists
* because the in-app PAYG breakdown needs a per-team, per-month, per-category aggregate; doing it
* as a view (rather than an ad-hoc query in the controller) keeps Supabase + Postgres on the same
* surface and lets us push the {@code WHERE billing_category IS NOT NULL} filter into the planner.
*
* <p>Returns an {@link EnumMap} keyed on {@link BillingCategory} — the controller picks out the
* three buckets the FE actually renders ({@code API}, {@code AI}, {@code AUTOMATION}). {@code
* BYPASSED} debits are filtered out at the view layer; non-billable categories that slipped through
* pre-V16 backfill are filtered on read.
*/
@Repository
@Profile("saas")
public class WalletCategorySummaryDao {
private static final String QUERY =
"SELECT billing_category, COALESCE(SUM(units_debited), 0) AS units"
+ " FROM wallet_category_summary"
+ " WHERE team_id = ?"
+ " AND period_start = ?"
+ " GROUP BY billing_category";
private final JdbcTemplate jdbcTemplate;
public WalletCategorySummaryDao(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = Objects.requireNonNull(jdbcTemplate, "jdbcTemplate");
}
/**
* Sum of units debited per {@link BillingCategory} for {@code teamId} in the calendar month
* containing {@code periodStart}. Missing categories are mapped to {@code 0}.
*
* @param teamId team to summarise
* @param periodStart first day of the calendar month — must match {@code date_trunc('month',
* occurred_at)} for the rows we want
*/
public Map<BillingCategory, Long> sumByCategory(Long teamId, LocalDate periodStart) {
Objects.requireNonNull(teamId, "teamId");
Objects.requireNonNull(periodStart, "periodStart");
Map<BillingCategory, Long> out = new EnumMap<>(BillingCategory.class);
for (BillingCategory c : BillingCategory.values()) {
out.put(c, 0L);
}
jdbcTemplate.query(
QUERY,
rs -> {
String name = rs.getString(1);
long units = rs.getLong(2);
if (name == null) {
return;
}
BillingCategory parsed;
try {
parsed = BillingCategory.valueOf(name);
} catch (IllegalArgumentException ignore) {
// Pre-V16 or out-of-band string; drop silently. View shouldn't emit these,
// but the FE doesn't render them anyway.
return;
}
out.put(parsed, units);
},
teamId,
java.sql.Date.valueOf(periodStart));
return out;
}
}
@@ -19,6 +19,8 @@ import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import stirling.software.saas.payg.model.BillingCategory;
import stirling.software.saas.payg.model.JobSource;
import stirling.software.saas.payg.model.ShadowChargeStatus;
/**
@@ -75,6 +77,24 @@ public class PaygShadowCharge implements Serializable {
@Column(name = "refund_reason", length = 128)
private String refundReason;
/**
* PAYG analytics axis copied from the request that produced this shadow row. {@code null} for
* pre-V16 rows; populated by the charge interceptor going forward. Never affects what Stripe
* would meter — the flat-meter assumption holds, this is breakdown metadata.
*/
@Enumerated(EnumType.STRING)
@Column(name = "billing_category", length = 16)
private BillingCategory billingCategory;
/**
* Caller surface that originated the job (copied from {@code processing_job.source} at write
* time so the row stays self-describing after the job table is pruned). {@code null} for
* pre-V16 rows backfilled when {@code processing_job} is no longer present.
*/
@Enumerated(EnumType.STRING)
@Column(name = "job_source", length = 32)
private JobSource jobSource;
@CreationTimestamp
@Column(name = "occurred_at", nullable = false, updatable = false)
private LocalDateTime occurredAt;
@@ -22,6 +22,7 @@ import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import stirling.software.saas.payg.model.BillingCategory;
import stirling.software.saas.payg.model.LedgerBucket;
import stirling.software.saas.payg.model.LedgerEntryType;
import stirling.software.saas.payg.model.ReferenceType;
@@ -76,6 +77,15 @@ public class WalletLedgerEntry implements Serializable {
@Column(name = "stripe_event_id", length = 128)
private String stripeEventId;
/**
* PAYG analytics axis. {@code null} for system entries (grants, resets) and pre-V16 rows; set
* by the charge interceptor for billable debits. Stripe pricing never reads this — it's a
* single flat meter — so the column stays soft-typed (no NOT NULL, no FK).
*/
@Enumerated(EnumType.STRING)
@Column(name = "billing_category", length = 16)
private BillingCategory billingCategory;
@CreationTimestamp
@Column(name = "occurred_at", nullable = false, updatable = false)
private LocalDateTime occurredAt;
@@ -42,6 +42,24 @@ public interface TeamMembershipRepository extends JpaRepository<TeamMembership,
@Query("SELECT tm FROM TeamMembership tm JOIN FETCH tm.team WHERE tm.user.id = :userId")
List<TeamMembership> findByUserId(@Param("userId") Long userId);
/**
* Resolve the single membership a user belongs to. In the PAYG design every user is owned by
* exactly one team — personal-team-for-new-signups, then optionally migrated when they accept
* an invite (the old personal team is deleted on accept). For diagnostic safety this picks the
* earliest-created row if multiple exist, but in steady state there is exactly one.
*
* <p>Returns both the team and its role so the PAYG wallet endpoint can answer "what does this
* user see?" in a single query rather than a list-then-filter dance.
*
* @param userId the user ID
* @return the user's primary membership, if any
*/
@Query(
"SELECT tm FROM TeamMembership tm JOIN FETCH tm.team"
+ " WHERE tm.user.id = :userId"
+ " ORDER BY tm.createdAt ASC")
List<TeamMembership> findPrimaryMembership(@Param("userId") Long userId);
/**
* Find all members with a specific role in a team
*
@@ -35,6 +35,31 @@ app.supabase.clock-skew-seconds=${app.jwt.clock-skew-seconds:120}
app.supabase.edge-function-url=https://${app.supabase.project-ref}.supabase.co/functions/v1
app.supabase.edge-function-secret=${SUPABASE_EDGE_FUNCTION_SECRET:}
# ---------- PAYG meter reporting ----------
# Posts billable usage to the Supabase `meter-payg-units` edge function in the JobChargeService
# close() afterCommit hook. Defaults to empty so unit tests / local dev are no-ops; set
# PAYG_METER_ENDPOINT + SUPABASE_SERVICE_ROLE_TOKEN in deployed envs to enable. Compose with the
# Supabase functions base via env (e.g. PAYG_METER_ENDPOINT=$SUPABASE_FUNCTIONS_URL/meter-payg-units)
# rather than templating here — concatenating an empty default would produce a half-valid URL.
payg.meter.endpoint=${PAYG_METER_ENDPOINT:}
payg.meter.service-role-token=${SUPABASE_SERVICE_ROLE_TOKEN:}
# ---------- PAYG customer portal ----------
# Proxies POST /api/v1/payg/portal-session to the Supabase `create-customer-portal-session` edge
# function, which mints a Stripe-hosted billing portal session for the team. Blank endpoint =>
# the controller returns 503 PORTAL_NOT_CONFIGURED so local dev / tests don't blow up on a missing
# URL. Compose via env (PAYG_PORTAL_ENDPOINT=$SUPABASE_FUNCTIONS_URL/create-customer-portal-session)
# rather than templating here so the default-empty branch stays clean.
payg.portal.endpoint=${PAYG_PORTAL_ENDPOINT:}
payg.portal.service-role-token=${SUPABASE_SERVICE_ROLE_TOKEN:}
# Comma-separated host allowlist for caller-supplied return_url on POST /api/v1/payg/portal-session.
# Stops an authenticated user smuggling https://evil.example into the Stripe-hosted portal so the
# "Return to Stirling" link bounces a victim through a legitimate session to an attacker host. If
# blank, any caller-supplied return_url is rejected with 400 INVALID_RETURN_URL and the edge fn
# falls back to its configured default. Set in deployed envs to the production + staging hostnames
# the FE may legitimately redirect to (e.g. "app.stirlingpdf.com,staging.stirlingpdf.com").
payg.portal.allowed-return-hosts=${PAYG_PORTAL_ALLOWED_RETURN_HOSTS:}
supabase.url=https://${app.supabase.project-ref}.supabase.co
spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://${app.supabase.project-ref}.supabase.co/auth/v1/.well-known/jwks.json
@@ -0,0 +1,58 @@
-- PAYG analytics axis: stamp every billable ledger entry / shadow row with the category that
-- produced it (API | AI | AUTOMATION | BYPASSED). PAYG stays on a single flat-priced Stripe meter
-- forever — this column is for in-app breakdowns and analytics, never for Stripe pricing.
--
-- All adds are nullable: pre-V16 rows have no category and stay NULL; the interceptor populates
-- it for new rows going forward.
-- ---------------------------------------------------------------------------------------------
-- 1. wallet_ledger.billing_category
-- ---------------------------------------------------------------------------------------------
ALTER TABLE wallet_ledger ADD COLUMN IF NOT EXISTS billing_category VARCHAR(16) NULL;
COMMENT ON COLUMN wallet_ledger.billing_category IS
'API | AI | AUTOMATION | BYPASSED. NULL = system entry or pre-V16 backfill.';
-- Partial index — only billable rows ever read this column, and NULLs would just bloat the tree.
CREATE INDEX IF NOT EXISTS idx_wallet_ledger_team_category_period
ON wallet_ledger (team_id, billing_category, occurred_at)
WHERE billing_category IS NOT NULL;
-- ---------------------------------------------------------------------------------------------
-- 2. payg_shadow_charge.billing_category + job_source
-- ---------------------------------------------------------------------------------------------
ALTER TABLE payg_shadow_charge
ADD COLUMN IF NOT EXISTS billing_category VARCHAR(16) NULL,
ADD COLUMN IF NOT EXISTS job_source VARCHAR(32) NULL;
-- Backfill job_source from processing_job (best-effort — rows whose job has already been pruned
-- stay NULL, which is fine: the shadow row is self-describing post-V16 and only legacy ones lack
-- the column.)
UPDATE payg_shadow_charge sc
SET job_source = pj.source
FROM processing_job pj
WHERE pj.job_id = sc.job_id
AND sc.job_source IS NULL;
-- ---------------------------------------------------------------------------------------------
-- 3. pricing_policy_stripe_price.stripe_product_id
-- Operator populates this manually per row when seeding new policies. Nullable for backward
-- compatibility with existing rows that don't carry a Product reference.
-- ---------------------------------------------------------------------------------------------
ALTER TABLE pricing_policy_stripe_price
ADD COLUMN IF NOT EXISTS stripe_product_id VARCHAR(128) NULL;
-- ---------------------------------------------------------------------------------------------
-- 4. wallet_category_summary view — pre-grouped per-team, per-month, per-category aggregate that
-- the in-app breakdown widget reads. Recomputed live on every SELECT; cheap thanks to the
-- partial index above.
-- ---------------------------------------------------------------------------------------------
CREATE OR REPLACE VIEW wallet_category_summary AS
SELECT
team_id,
date_trunc('month', occurred_at) AS period_start,
billing_category,
SUM(CASE WHEN amount_units < 0 THEN -amount_units ELSE 0 END) AS units_debited,
COUNT(*) FILTER (WHERE entry_type = 'DEBIT') AS debit_count
FROM wallet_ledger
WHERE billing_category IS NOT NULL
GROUP BY team_id, date_trunc('month', occurred_at), billing_category;
@@ -0,0 +1,909 @@
package stirling.software.saas.payg.api;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.EnumMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.web.client.ResourceAccessException;
import org.springframework.web.client.RestTemplate;
import stirling.software.common.model.enumeration.TeamRole;
import stirling.software.proprietary.model.Team;
import stirling.software.proprietary.security.database.repository.UserRepository;
import stirling.software.proprietary.security.model.User;
import stirling.software.saas.model.TeamMembership;
import stirling.software.saas.payg.api.PaygWalletController.PortalSessionRequest;
import stirling.software.saas.payg.api.PaygWalletController.UpdateCapRequest;
import stirling.software.saas.payg.api.PaygWalletController.UpdateSubCapRequest;
import stirling.software.saas.payg.api.WalletSnapshotResponse.MemberRow;
import stirling.software.saas.payg.entitlement.EntitlementService;
import stirling.software.saas.payg.entitlement.EntitlementSnapshot;
import stirling.software.saas.payg.model.BillingCategory;
import stirling.software.saas.payg.model.EntitlementState;
import stirling.software.saas.payg.model.FeatureGate;
import stirling.software.saas.payg.model.FeatureSet;
import stirling.software.saas.payg.policy.PaygTeamExtensions;
import stirling.software.saas.payg.repository.PaygTeamExtensionsRepository;
import stirling.software.saas.payg.repository.WalletCategorySummaryDao;
import stirling.software.saas.payg.repository.WalletLedgerRepository;
import stirling.software.saas.payg.repository.WalletPolicyRepository;
import stirling.software.saas.payg.wallet.WalletPolicy;
import stirling.software.saas.repository.TeamMembershipRepository;
import stirling.software.saas.security.EnhancedJwtAuthenticationToken;
/**
* Pure-Mockito unit tests for {@link PaygWalletController}. Covers the documented role / state
* matrix — free vs subscribed, leader vs member, anonymous — plus the cap update endpoint's
* leader-only enforcement and cache invalidation.
*/
@ExtendWith(MockitoExtension.class)
class PaygWalletControllerTest {
private static final String PORTAL_ENDPOINT =
"https://example.supabase.co/functions/v1/create-customer-portal-session";
private static final String PORTAL_TOKEN = "service-role-test-token";
private static final String PORTAL_ALLOWED_HOSTS = "app.example,staging.example";
@Mock private EntitlementService entitlementService;
@Mock private TeamMembershipRepository memberRepo;
@Mock private PaygTeamExtensionsRepository extRepo;
@Mock private WalletPolicyRepository policyRepo;
@Mock private WalletLedgerRepository ledgerRepo;
@Mock private WalletCategorySummaryDao categorySummaryDao;
@Mock private UserRepository userRepository;
@Mock private RestTemplate restTemplate;
private PaygWalletController controller;
@BeforeEach
void setUp() {
controller = newController(PORTAL_ENDPOINT, PORTAL_TOKEN, PORTAL_ALLOWED_HOSTS);
}
private PaygWalletController newController(
String portalEndpoint, String portalToken, String allowedHosts) {
return new PaygWalletController(
entitlementService,
memberRepo,
extRepo,
policyRepo,
ledgerRepo,
categorySummaryDao,
userRepository,
restTemplate,
portalEndpoint,
portalToken,
allowedHosts);
}
// -----------------------------------------------------------------------------------------
// GET /wallet
// -----------------------------------------------------------------------------------------
@Test
void getWallet_freeTier_returnsFreeShape() {
User user = userWithId(7L, UUID.randomUUID());
Team team = teamWithId(42L);
when(userRepository.findBySupabaseId(any())).thenReturn(Optional.of(user));
when(memberRepo.findPrimaryMembership(7L))
.thenReturn(List.of(membership(team, user, TeamRole.MEMBER)));
when(extRepo.findById(42L)).thenReturn(Optional.empty());
when(policyRepo.findByTeamId(42L)).thenReturn(Optional.empty());
when(entitlementService.getSnapshot(42L)).thenReturn(snapshot(0L, null));
when(categorySummaryDao.sumByCategory(eq(42L), any(LocalDate.class)))
.thenReturn(emptyCategoryMap());
ResponseEntity<WalletSnapshotResponse> resp =
controller.getWallet(jwtAuth(user.getSupabaseId()));
assertThat(resp.getStatusCode()).isEqualTo(HttpStatus.OK);
WalletSnapshotResponse body = resp.getBody();
assertThat(body).isNotNull();
assertThat(body.status()).isEqualTo("free");
assertThat(body.role()).isEqualTo("member");
assertThat(body.capUsd()).isNull();
assertThat(body.stripeSubscriptionId()).isNull();
assertThat(body.noCap()).isFalse();
assertThat(body.billableUsed()).isZero();
assertThat(body.billableLimit()).isEqualTo(500);
assertThat(body.members()).isEmpty();
assertThat(body.recent()).isEmpty();
assertThat(body.categoryBreakdown().api()).isZero();
assertThat(body.categoryBreakdown().ai()).isZero();
assertThat(body.categoryBreakdown().automation()).isZero();
}
@Test
void getWallet_subscribedMember_returnsCapInUsdAndEmptyMembers() {
User user = userWithId(8L, UUID.randomUUID());
Team team = teamWithId(99L);
when(userRepository.findBySupabaseId(any())).thenReturn(Optional.of(user));
when(memberRepo.findPrimaryMembership(8L))
.thenReturn(List.of(membership(team, user, TeamRole.MEMBER)));
// stripeCustomerId present → "subscribed" (until PR #6532's payg_subscription_id lands)
PaygTeamExtensions ext = new PaygTeamExtensions();
ext.setTeamId(99L);
ext.setStripeCustomerId("cus_test_123");
when(extRepo.findById(99L)).thenReturn(Optional.of(ext));
WalletPolicy policy = new WalletPolicy();
policy.setTeamId(99L);
policy.setCapUnits(2500L); // == $25 at 100 units / $
when(policyRepo.findByTeamId(99L)).thenReturn(Optional.of(policy));
when(entitlementService.getSnapshot(99L)).thenReturn(snapshot(312L, 2500L));
Map<BillingCategory, Long> byCat = emptyCategoryMap();
byCat.put(BillingCategory.API, 110L);
byCat.put(BillingCategory.AI, 200L);
byCat.put(BillingCategory.AUTOMATION, 2L);
when(categorySummaryDao.sumByCategory(eq(99L), any(LocalDate.class))).thenReturn(byCat);
ResponseEntity<WalletSnapshotResponse> resp =
controller.getWallet(jwtAuth(user.getSupabaseId()));
WalletSnapshotResponse body = resp.getBody();
assertThat(body.status()).isEqualTo("subscribed");
assertThat(body.role()).isEqualTo("member");
assertThat(body.capUsd()).isEqualTo(25);
assertThat(body.noCap()).isFalse();
assertThat(body.billableUsed()).isEqualTo(312);
assertThat(body.spendUnitsThisPeriod()).isEqualTo(312);
assertThat(body.members()).isEmpty();
assertThat(body.categoryBreakdown().api()).isEqualTo(110);
assertThat(body.categoryBreakdown().ai()).isEqualTo(200);
assertThat(body.categoryBreakdown().automation()).isEqualTo(2);
// stripeSubscriptionId still null until #6532 lands.
assertThat(body.stripeSubscriptionId()).isNull();
// Member role → ledger never queried per-user.
verify(ledgerRepo, never()).sumPeriodAmountForMember(any(), any(), any(), any(), any());
}
@Test
void getWallet_subscribedNoCap_returnsNoCapTrueAndNullCapUsd() {
User user = userWithId(9L, UUID.randomUUID());
Team team = teamWithId(11L);
when(userRepository.findBySupabaseId(any())).thenReturn(Optional.of(user));
when(memberRepo.findPrimaryMembership(9L))
.thenReturn(List.of(membership(team, user, TeamRole.LEADER)));
PaygTeamExtensions ext = new PaygTeamExtensions();
ext.setTeamId(11L);
ext.setStripeCustomerId("cus_nocap");
when(extRepo.findById(11L)).thenReturn(Optional.of(ext));
WalletPolicy policy = new WalletPolicy();
policy.setTeamId(11L);
policy.setCapUnits(null); // explicit no-cap
when(policyRepo.findByTeamId(11L)).thenReturn(Optional.of(policy));
when(entitlementService.getSnapshot(11L)).thenReturn(snapshot(50L, null));
when(categorySummaryDao.sumByCategory(eq(11L), any(LocalDate.class)))
.thenReturn(emptyCategoryMap());
when(memberRepo.findByTeamId(11L)).thenReturn(List.of());
ResponseEntity<WalletSnapshotResponse> resp =
controller.getWallet(jwtAuth(user.getSupabaseId()));
WalletSnapshotResponse body = resp.getBody();
assertThat(body.status()).isEqualTo("subscribed");
assertThat(body.role()).isEqualTo("leader");
assertThat(body.capUsd()).isNull();
assertThat(body.noCap()).isTrue();
}
@Test
void getWallet_leader_populatesMembers() {
User leader = userWithId(10L, UUID.randomUUID());
User member = userWithId(11L, UUID.randomUUID());
member.setUsername("alice");
member.setEmail("alice@example.com");
Team team = teamWithId(77L);
TeamMembership leaderRow = membership(team, leader, TeamRole.LEADER);
TeamMembership memberRow = membership(team, member, TeamRole.MEMBER);
memberRow.setCapUnits(1500L);
when(userRepository.findBySupabaseId(any())).thenReturn(Optional.of(leader));
when(memberRepo.findPrimaryMembership(10L)).thenReturn(List.of(leaderRow));
when(extRepo.findById(77L)).thenReturn(Optional.empty());
when(policyRepo.findByTeamId(77L)).thenReturn(Optional.empty());
when(entitlementService.getSnapshot(77L)).thenReturn(snapshot(0L, null));
when(categorySummaryDao.sumByCategory(eq(77L), any(LocalDate.class)))
.thenReturn(emptyCategoryMap());
when(memberRepo.findByTeamId(77L)).thenReturn(List.of(leaderRow, memberRow));
// Ledger returns signed (negative) debits.
when(ledgerRepo.sumPeriodAmountForMember(eq(77L), any(), any(), any(), any()))
.thenReturn(-42L);
ResponseEntity<WalletSnapshotResponse> resp =
controller.getWallet(jwtAuth(leader.getSupabaseId()));
WalletSnapshotResponse body = resp.getBody();
assertThat(body.role()).isEqualTo("leader");
assertThat(body.members()).hasSize(2);
MemberRow secondMember =
body.members().stream()
.filter(m -> "alice".equals(m.name()))
.findFirst()
.orElseThrow();
assertThat(secondMember.email()).isEqualTo("alice@example.com");
assertThat(secondMember.capUnits()).isEqualTo(1500);
assertThat(secondMember.spendUnits()).isEqualTo(42);
}
@Test
void getWallet_anonymousIsRejected() {
Authentication anon =
new AnonymousAuthenticationToken(
"k",
"anonymousUser",
List.of(new SimpleGrantedAuthority("ROLE_ANONYMOUS")));
ResponseEntity<WalletSnapshotResponse> resp = controller.getWallet(anon);
// AuthenticationUtils.getCurrentUser throws SecurityException for "anonymousUser" since it
// has no Supabase id and is not a User principal — the controller maps that to 401.
assertThat(resp.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED);
verifyNoInteractions(
entitlementService, memberRepo, extRepo, policyRepo, categorySummaryDao);
}
@Test
void getWallet_authenticatedNoTeam_returnsEmptyFreeShape() {
User user = userWithId(12L, UUID.randomUUID());
when(userRepository.findBySupabaseId(any())).thenReturn(Optional.of(user));
when(memberRepo.findPrimaryMembership(12L)).thenReturn(List.of());
ResponseEntity<WalletSnapshotResponse> resp =
controller.getWallet(jwtAuth(user.getSupabaseId()));
assertThat(resp.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(resp.getBody().status()).isEqualTo("free");
assertThat(resp.getBody().members()).isEmpty();
// Entitlement service must not be queried for a teamless user (avoids null-key NPE).
verifyNoInteractions(entitlementService);
}
// -----------------------------------------------------------------------------------------
// PATCH /cap
// -----------------------------------------------------------------------------------------
@Test
void updateCap_leaderUpdatesUnitsAndInvalidates() {
User leader = userWithId(20L, UUID.randomUUID());
Team team = teamWithId(33L);
when(userRepository.findBySupabaseId(any())).thenReturn(Optional.of(leader));
when(memberRepo.findPrimaryMembership(20L))
.thenReturn(List.of(membership(team, leader, TeamRole.LEADER)));
when(policyRepo.findByTeamId(33L)).thenReturn(Optional.empty());
ResponseEntity<Void> resp =
controller.updateCap(
new UpdateCapRequest(40, false), jwtAuth(leader.getSupabaseId()));
assertThat(resp.getStatusCode()).isEqualTo(HttpStatus.NO_CONTENT);
ArgumentCaptor<WalletPolicy> saved = ArgumentCaptor.forClass(WalletPolicy.class);
verify(policyRepo).save(saved.capture());
assertThat(saved.getValue().getCapUnits()).isEqualTo(4000L); // 40 USD * 100 units/USD
assertThat(saved.getValue().getCapSourceMoney()).isEqualTo(4000L); // 40 USD == 4000 cents
verify(entitlementService, times(1)).invalidate(33L);
}
@Test
void updateCap_noCapTrue_clearsCapUnits() {
User leader = userWithId(21L, UUID.randomUUID());
Team team = teamWithId(34L);
when(userRepository.findBySupabaseId(any())).thenReturn(Optional.of(leader));
when(memberRepo.findPrimaryMembership(21L))
.thenReturn(List.of(membership(team, leader, TeamRole.LEADER)));
WalletPolicy existing = new WalletPolicy();
existing.setTeamId(34L);
existing.setCapUnits(1000L);
existing.setCapSourceMoney(1000L);
when(policyRepo.findByTeamId(34L)).thenReturn(Optional.of(existing));
ResponseEntity<Void> resp =
controller.updateCap(
new UpdateCapRequest(0, true), jwtAuth(leader.getSupabaseId()));
assertThat(resp.getStatusCode()).isEqualTo(HttpStatus.NO_CONTENT);
ArgumentCaptor<WalletPolicy> saved = ArgumentCaptor.forClass(WalletPolicy.class);
verify(policyRepo).save(saved.capture());
assertThat(saved.getValue().getCapUnits()).isNull();
assertThat(saved.getValue().getCapSourceMoney()).isNull();
verify(entitlementService).invalidate(34L);
}
@Test
void updateCap_memberIsForbidden() {
User member = userWithId(22L, UUID.randomUUID());
Team team = teamWithId(35L);
when(userRepository.findBySupabaseId(any())).thenReturn(Optional.of(member));
when(memberRepo.findPrimaryMembership(22L))
.thenReturn(List.of(membership(team, member, TeamRole.MEMBER)));
ResponseEntity<Void> resp =
controller.updateCap(
new UpdateCapRequest(50, false), jwtAuth(member.getSupabaseId()));
assertThat(resp.getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN);
verify(policyRepo, never()).save(any());
verify(entitlementService, never()).invalidate(any());
}
@Test
void updateCap_noTeam_isForbidden() {
User user = userWithId(23L, UUID.randomUUID());
when(userRepository.findBySupabaseId(any())).thenReturn(Optional.of(user));
when(memberRepo.findPrimaryMembership(23L)).thenReturn(List.of());
ResponseEntity<Void> resp =
controller.updateCap(
new UpdateCapRequest(10, false), jwtAuth(user.getSupabaseId()));
assertThat(resp.getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN);
verify(policyRepo, never()).save(any());
}
@Test
void updateCap_anonymousIs401() {
Authentication anon =
new AnonymousAuthenticationToken(
"k",
"anonymousUser",
List.of(new SimpleGrantedAuthority("ROLE_ANONYMOUS")));
ResponseEntity<Void> resp = controller.updateCap(new UpdateCapRequest(10, false), anon);
assertThat(resp.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED);
verifyNoInteractions(policyRepo, entitlementService);
}
// -----------------------------------------------------------------------------------------
// PATCH /sub-caps/{userId}
// -----------------------------------------------------------------------------------------
@Test
void updateSubCap_leaderBelowTeamCap_savesAndReportsUnclamped() {
User leader = userWithId(30L, UUID.randomUUID());
User target = userWithId(31L, UUID.randomUUID());
Team team = teamWithId(50L);
TeamMembership leaderRow = membership(team, leader, TeamRole.LEADER);
TeamMembership targetRow = membership(team, target, TeamRole.MEMBER);
when(userRepository.findBySupabaseId(any())).thenReturn(Optional.of(leader));
when(memberRepo.findPrimaryMembership(30L)).thenReturn(List.of(leaderRow));
when(memberRepo.findByTeamIdAndUserId(50L, 31L)).thenReturn(Optional.of(targetRow));
WalletPolicy policy = new WalletPolicy();
policy.setTeamId(50L);
policy.setCapUnits(5000L);
when(policyRepo.findByTeamId(50L)).thenReturn(Optional.of(policy));
ResponseEntity<Map<String, Object>> resp =
controller.updateSubCap(
31L, new UpdateSubCapRequest(2000), jwtAuth(leader.getSupabaseId()));
assertThat(resp.getStatusCode()).isEqualTo(HttpStatus.OK);
Map<String, Object> body = resp.getBody();
assertThat(body).isNotNull();
assertThat(body.get("success")).isEqualTo(Boolean.TRUE);
assertThat(body.get("clamped")).isEqualTo(Boolean.FALSE);
assertThat(body.get("capUnits")).isEqualTo(2000L);
ArgumentCaptor<TeamMembership> saved = ArgumentCaptor.forClass(TeamMembership.class);
verify(memberRepo).save(saved.capture());
assertThat(saved.getValue().getCapUnits()).isEqualTo(2000L);
verify(entitlementService).invalidate(50L);
}
@Test
void updateSubCap_leaderAboveTeamCap_clampsToTeamCap() {
User leader = userWithId(32L, UUID.randomUUID());
User target = userWithId(33L, UUID.randomUUID());
Team team = teamWithId(51L);
TeamMembership leaderRow = membership(team, leader, TeamRole.LEADER);
TeamMembership targetRow = membership(team, target, TeamRole.MEMBER);
when(userRepository.findBySupabaseId(any())).thenReturn(Optional.of(leader));
when(memberRepo.findPrimaryMembership(32L)).thenReturn(List.of(leaderRow));
when(memberRepo.findByTeamIdAndUserId(51L, 33L)).thenReturn(Optional.of(targetRow));
WalletPolicy policy = new WalletPolicy();
policy.setTeamId(51L);
policy.setCapUnits(1000L);
when(policyRepo.findByTeamId(51L)).thenReturn(Optional.of(policy));
ResponseEntity<Map<String, Object>> resp =
controller.updateSubCap(
33L, new UpdateSubCapRequest(9999), jwtAuth(leader.getSupabaseId()));
assertThat(resp.getStatusCode()).isEqualTo(HttpStatus.OK);
Map<String, Object> body = resp.getBody();
assertThat(body.get("success")).isEqualTo(Boolean.TRUE);
assertThat(body.get("clamped")).isEqualTo(Boolean.TRUE);
assertThat(body.get("capUnits")).isEqualTo(1000L);
ArgumentCaptor<TeamMembership> saved = ArgumentCaptor.forClass(TeamMembership.class);
verify(memberRepo).save(saved.capture());
assertThat(saved.getValue().getCapUnits()).isEqualTo(1000L);
verify(entitlementService).invalidate(51L);
}
@Test
void updateSubCap_nullCapUnits_clearsSubCap() {
User leader = userWithId(34L, UUID.randomUUID());
User target = userWithId(35L, UUID.randomUUID());
Team team = teamWithId(52L);
TeamMembership leaderRow = membership(team, leader, TeamRole.LEADER);
TeamMembership targetRow = membership(team, target, TeamRole.MEMBER);
targetRow.setCapUnits(500L); // had a sub-cap before
when(userRepository.findBySupabaseId(any())).thenReturn(Optional.of(leader));
when(memberRepo.findPrimaryMembership(34L)).thenReturn(List.of(leaderRow));
when(memberRepo.findByTeamIdAndUserId(52L, 35L)).thenReturn(Optional.of(targetRow));
WalletPolicy policy = new WalletPolicy();
policy.setTeamId(52L);
policy.setCapUnits(5000L);
when(policyRepo.findByTeamId(52L)).thenReturn(Optional.of(policy));
ResponseEntity<Map<String, Object>> resp =
controller.updateSubCap(
35L, new UpdateSubCapRequest(null), jwtAuth(leader.getSupabaseId()));
assertThat(resp.getStatusCode()).isEqualTo(HttpStatus.OK);
Map<String, Object> body = resp.getBody();
assertThat(body.get("clamped")).isEqualTo(Boolean.FALSE);
assertThat(body.get("capUnits")).isNull();
ArgumentCaptor<TeamMembership> saved = ArgumentCaptor.forClass(TeamMembership.class);
verify(memberRepo).save(saved.capture());
assertThat(saved.getValue().getCapUnits()).isNull();
verify(entitlementService).invalidate(52L);
}
@Test
void updateSubCap_teamHasNoCap_neverClamps() {
// Subscribed no-cap team: wallet_policy.cap_units == null → any sub-cap is accepted as-is.
User leader = userWithId(36L, UUID.randomUUID());
User target = userWithId(37L, UUID.randomUUID());
Team team = teamWithId(53L);
TeamMembership leaderRow = membership(team, leader, TeamRole.LEADER);
TeamMembership targetRow = membership(team, target, TeamRole.MEMBER);
when(userRepository.findBySupabaseId(any())).thenReturn(Optional.of(leader));
when(memberRepo.findPrimaryMembership(36L)).thenReturn(List.of(leaderRow));
when(memberRepo.findByTeamIdAndUserId(53L, 37L)).thenReturn(Optional.of(targetRow));
WalletPolicy policy = new WalletPolicy();
policy.setTeamId(53L);
policy.setCapUnits(null); // no team cap
when(policyRepo.findByTeamId(53L)).thenReturn(Optional.of(policy));
ResponseEntity<Map<String, Object>> resp =
controller.updateSubCap(
37L, new UpdateSubCapRequest(1_000_000), jwtAuth(leader.getSupabaseId()));
assertThat(resp.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(resp.getBody().get("clamped")).isEqualTo(Boolean.FALSE);
assertThat(resp.getBody().get("capUnits")).isEqualTo(1_000_000L);
}
@Test
void updateSubCap_memberIsForbidden() {
User member = userWithId(38L, UUID.randomUUID());
Team team = teamWithId(54L);
when(userRepository.findBySupabaseId(any())).thenReturn(Optional.of(member));
when(memberRepo.findPrimaryMembership(38L))
.thenReturn(List.of(membership(team, member, TeamRole.MEMBER)));
ResponseEntity<Map<String, Object>> resp =
controller.updateSubCap(
99L, new UpdateSubCapRequest(100), jwtAuth(member.getSupabaseId()));
assertThat(resp.getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN);
verify(memberRepo, never()).save(any());
verify(entitlementService, never()).invalidate(any());
}
@Test
void updateSubCap_targetInDifferentTeam_returns404() {
User leader = userWithId(40L, UUID.randomUUID());
Team team = teamWithId(55L);
when(userRepository.findBySupabaseId(any())).thenReturn(Optional.of(leader));
when(memberRepo.findPrimaryMembership(40L))
.thenReturn(List.of(membership(team, leader, TeamRole.LEADER)));
// Target user 41 is not a member of team 55.
when(memberRepo.findByTeamIdAndUserId(55L, 41L)).thenReturn(Optional.empty());
ResponseEntity<Map<String, Object>> resp =
controller.updateSubCap(
41L, new UpdateSubCapRequest(500), jwtAuth(leader.getSupabaseId()));
assertThat(resp.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND);
verify(memberRepo, never()).save(any());
verify(entitlementService, never()).invalidate(any());
}
@Test
void updateSubCap_noTeam_isForbidden() {
User user = userWithId(42L, UUID.randomUUID());
when(userRepository.findBySupabaseId(any())).thenReturn(Optional.of(user));
when(memberRepo.findPrimaryMembership(42L)).thenReturn(List.of());
ResponseEntity<Map<String, Object>> resp =
controller.updateSubCap(
99L, new UpdateSubCapRequest(100), jwtAuth(user.getSupabaseId()));
assertThat(resp.getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN);
verify(memberRepo, never()).save(any());
}
@Test
void updateSubCap_anonymousIs401() {
Authentication anon =
new AnonymousAuthenticationToken(
"k",
"anonymousUser",
List.of(new SimpleGrantedAuthority("ROLE_ANONYMOUS")));
ResponseEntity<Map<String, Object>> resp =
controller.updateSubCap(99L, new UpdateSubCapRequest(100), anon);
assertThat(resp.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED);
verifyNoInteractions(memberRepo, policyRepo, entitlementService);
}
// -----------------------------------------------------------------------------------------
// POST /portal-session
// -----------------------------------------------------------------------------------------
@Test
void portalSession_subscribedTeam_returnsUrlAndCallsEdgeFnWithBearer() {
User user = userWithId(60L, UUID.randomUUID());
Team team = teamWithId(80L);
when(userRepository.findBySupabaseId(any())).thenReturn(Optional.of(user));
when(memberRepo.findPrimaryMembership(60L))
.thenReturn(List.of(membership(team, user, TeamRole.LEADER)));
PaygTeamExtensions ext = new PaygTeamExtensions();
ext.setTeamId(80L);
ext.setStripeCustomerId("cus_subscribed");
when(extRepo.findById(80L)).thenReturn(Optional.of(ext));
when(restTemplate.exchange(
eq(PORTAL_ENDPOINT),
eq(HttpMethod.POST),
any(HttpEntity.class),
eq(Map.class)))
.thenReturn(
ResponseEntity.ok(
(Map)
Map.of(
"success",
true,
"url",
"https://billing.stripe.com/p/session/xyz")));
ResponseEntity<Map<String, Object>> resp =
controller.createPortalSession(
new PortalSessionRequest("https://app.example/return"),
jwtAuth(user.getSupabaseId()));
assertThat(resp.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(resp.getBody()).isNotNull();
assertThat(resp.getBody().get("url")).isEqualTo("https://billing.stripe.com/p/session/xyz");
@SuppressWarnings("rawtypes")
ArgumentCaptor<HttpEntity> captor = ArgumentCaptor.forClass(HttpEntity.class);
verify(restTemplate)
.exchange(
eq(PORTAL_ENDPOINT), eq(HttpMethod.POST), captor.capture(), eq(Map.class));
HttpEntity<?> sent = captor.getValue();
// Bearer service-role header forwarded so the edge fn can authorise.
assertThat(sent.getHeaders().getFirst("Authorization")).isEqualTo("Bearer " + PORTAL_TOKEN);
// Body carries team_id (string) + the optional return_url.
@SuppressWarnings("unchecked")
Map<String, Object> body = (Map<String, Object>) sent.getBody();
assertThat(body).isNotNull();
assertThat(body.get("team_id")).isEqualTo("80");
assertThat(body.get("return_url")).isEqualTo("https://app.example/return");
}
@Test
void portalSession_teamWithoutStripeCustomer_returns404() {
User user = userWithId(61L, UUID.randomUUID());
Team team = teamWithId(81L);
when(userRepository.findBySupabaseId(any())).thenReturn(Optional.of(user));
when(memberRepo.findPrimaryMembership(61L))
.thenReturn(List.of(membership(team, user, TeamRole.LEADER)));
// No PaygTeamExtensions row at all → unsubscribed.
when(extRepo.findById(81L)).thenReturn(Optional.empty());
ResponseEntity<Map<String, Object>> resp =
controller.createPortalSession(
new PortalSessionRequest(null), jwtAuth(user.getSupabaseId()));
assertThat(resp.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND);
assertThat(resp.getBody()).isNotNull();
assertThat(resp.getBody().get("error")).isEqualTo("TEAM_NOT_SUBSCRIBED");
verifyNoInteractions(restTemplate);
}
@Test
void portalSession_edgeFnReturnsSuccessFalse_returns502() {
User user = userWithId(62L, UUID.randomUUID());
Team team = teamWithId(82L);
when(userRepository.findBySupabaseId(any())).thenReturn(Optional.of(user));
when(memberRepo.findPrimaryMembership(62L))
.thenReturn(List.of(membership(team, user, TeamRole.LEADER)));
PaygTeamExtensions ext = new PaygTeamExtensions();
ext.setTeamId(82L);
ext.setStripeCustomerId("cus_sad");
when(extRepo.findById(82L)).thenReturn(Optional.of(ext));
when(restTemplate.exchange(
eq(PORTAL_ENDPOINT),
eq(HttpMethod.POST),
any(HttpEntity.class),
eq(Map.class)))
.thenReturn(
ResponseEntity.ok((Map) Map.of("success", false, "error", "stripe_down")));
ResponseEntity<Map<String, Object>> resp =
controller.createPortalSession(
new PortalSessionRequest(null), jwtAuth(user.getSupabaseId()));
assertThat(resp.getStatusCode()).isEqualTo(HttpStatus.BAD_GATEWAY);
assertThat(resp.getBody()).isNotNull();
assertThat(resp.getBody().get("error")).isEqualTo("PORTAL_UNAVAILABLE");
}
@Test
void portalSession_edgeFnThrows_returns502() {
User user = userWithId(63L, UUID.randomUUID());
Team team = teamWithId(83L);
when(userRepository.findBySupabaseId(any())).thenReturn(Optional.of(user));
when(memberRepo.findPrimaryMembership(63L))
.thenReturn(List.of(membership(team, user, TeamRole.LEADER)));
PaygTeamExtensions ext = new PaygTeamExtensions();
ext.setTeamId(83L);
ext.setStripeCustomerId("cus_throw");
when(extRepo.findById(83L)).thenReturn(Optional.of(ext));
when(restTemplate.exchange(
eq(PORTAL_ENDPOINT),
eq(HttpMethod.POST),
any(HttpEntity.class),
eq(Map.class)))
.thenThrow(new ResourceAccessException("connect timeout"));
ResponseEntity<Map<String, Object>> resp =
controller.createPortalSession(
new PortalSessionRequest(null), jwtAuth(user.getSupabaseId()));
assertThat(resp.getStatusCode()).isEqualTo(HttpStatus.BAD_GATEWAY);
assertThat(resp.getBody()).isNotNull();
assertThat(resp.getBody().get("error")).isEqualTo("PORTAL_UNAVAILABLE");
}
@Test
void portalSession_endpointBlank_returns503() {
// Rebuild controller with blank endpoint to simulate local dev / unconfigured env.
controller = newController("", PORTAL_TOKEN, PORTAL_ALLOWED_HOSTS);
ResponseEntity<Map<String, Object>> resp =
controller.createPortalSession(
new PortalSessionRequest(null), jwtAuth(UUID.randomUUID()));
assertThat(resp.getStatusCode()).isEqualTo(HttpStatus.SERVICE_UNAVAILABLE);
assertThat(resp.getBody()).isNotNull();
assertThat(resp.getBody().get("error")).isEqualTo("PORTAL_NOT_CONFIGURED");
// Should short-circuit before resolving the user or hitting downstream.
verifyNoInteractions(userRepository, memberRepo, extRepo, restTemplate);
}
@Test
void portalSession_returnUrlNotOnAllowlist_returns400() {
// No DB / RestTemplate stubbing — rejection happens before the controller resolves the
// user, so none of those collaborators should be touched.
ResponseEntity<Map<String, Object>> resp =
controller.createPortalSession(
new PortalSessionRequest("https://evil.example/billing-return"),
jwtAuth(UUID.randomUUID()));
assertThat(resp.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST);
assertThat(resp.getBody()).isNotNull();
assertThat(resp.getBody().get("error")).isEqualTo("INVALID_RETURN_URL");
verifyNoInteractions(userRepository, memberRepo, extRepo, restTemplate);
}
@Test
void portalSession_returnUrlMalformed_returns400() {
// Non-http(s) scheme should be rejected before any DB / HTTP work.
ResponseEntity<Map<String, Object>> resp =
controller.createPortalSession(
new PortalSessionRequest("javascript:alert(1)"),
jwtAuth(UUID.randomUUID()));
assertThat(resp.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST);
assertThat(resp.getBody().get("error")).isEqualTo("INVALID_RETURN_URL");
verifyNoInteractions(userRepository, memberRepo, extRepo, restTemplate);
}
@Test
void portalSession_returnUrlEmpty_allowlistNotChecked() {
// returnUrl == null / blank → no allowlist enforcement; the edge fn falls back to its
// configured default. Use a controller with an EMPTY allowlist to prove the path bypasses
// it: with the empty allowlist any non-null URL would be rejected, but null sails through.
controller = newController(PORTAL_ENDPOINT, PORTAL_TOKEN, "");
User user = userWithId(64L, UUID.randomUUID());
Team team = teamWithId(84L);
when(userRepository.findBySupabaseId(any())).thenReturn(Optional.of(user));
when(memberRepo.findPrimaryMembership(64L))
.thenReturn(List.of(membership(team, user, TeamRole.LEADER)));
PaygTeamExtensions ext = new PaygTeamExtensions();
ext.setTeamId(84L);
ext.setStripeCustomerId("cus_blank");
when(extRepo.findById(84L)).thenReturn(Optional.of(ext));
when(restTemplate.exchange(
eq(PORTAL_ENDPOINT),
eq(HttpMethod.POST),
any(HttpEntity.class),
eq(Map.class)))
.thenReturn(
ResponseEntity.ok(
(Map)
Map.of(
"success",
true,
"url",
"https://billing.stripe.com/p/session/abc")));
ResponseEntity<Map<String, Object>> resp =
controller.createPortalSession(
new PortalSessionRequest(null), jwtAuth(user.getSupabaseId()));
assertThat(resp.getStatusCode()).isEqualTo(HttpStatus.OK);
// The forwarded body must NOT carry return_url when caller didn't supply one.
@SuppressWarnings("rawtypes")
ArgumentCaptor<HttpEntity> captor = ArgumentCaptor.forClass(HttpEntity.class);
verify(restTemplate)
.exchange(
eq(PORTAL_ENDPOINT), eq(HttpMethod.POST), captor.capture(), eq(Map.class));
@SuppressWarnings("unchecked")
Map<String, Object> sentBody = (Map<String, Object>) captor.getValue().getBody();
assertThat(sentBody).doesNotContainKey("return_url");
assertThat(sentBody.get("team_id")).isEqualTo("84");
}
@Test
void portalSession_nullBody_isAllowed() {
// FE may POST with no body at all — Spring binds @RequestBody(required = false) to null,
// and the controller treats that the same as a body with returnUrl=null.
User user = userWithId(65L, UUID.randomUUID());
Team team = teamWithId(85L);
when(userRepository.findBySupabaseId(any())).thenReturn(Optional.of(user));
when(memberRepo.findPrimaryMembership(65L))
.thenReturn(List.of(membership(team, user, TeamRole.LEADER)));
PaygTeamExtensions ext = new PaygTeamExtensions();
ext.setTeamId(85L);
ext.setStripeCustomerId("cus_nullbody");
when(extRepo.findById(85L)).thenReturn(Optional.of(ext));
when(restTemplate.exchange(
eq(PORTAL_ENDPOINT),
eq(HttpMethod.POST),
any(HttpEntity.class),
eq(Map.class)))
.thenReturn(
ResponseEntity.ok(
(Map)
Map.of(
"success",
true,
"url",
"https://billing.stripe.com/p/session/null")));
ResponseEntity<Map<String, Object>> resp =
controller.createPortalSession(null, jwtAuth(user.getSupabaseId()));
assertThat(resp.getStatusCode()).isEqualTo(HttpStatus.OK);
}
@Test
void portalSession_anonymous_returns401() {
Authentication anon =
new AnonymousAuthenticationToken(
"k",
"anonymousUser",
List.of(new SimpleGrantedAuthority("ROLE_ANONYMOUS")));
ResponseEntity<Map<String, Object>> resp =
controller.createPortalSession(new PortalSessionRequest(null), anon);
assertThat(resp.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED);
verifyNoInteractions(restTemplate, extRepo, memberRepo);
}
// -----------------------------------------------------------------------------------------
// Fixtures
// -----------------------------------------------------------------------------------------
private static User userWithId(Long id, UUID supabaseId) {
User u = new User();
u.setId(id);
u.setSupabaseId(supabaseId);
return u;
}
private static Team teamWithId(Long id) {
Team t = new Team();
t.setId(id);
t.setName("t-" + id);
return t;
}
private static TeamMembership membership(Team team, User user, TeamRole role) {
TeamMembership m = new TeamMembership();
m.setTeam(team);
m.setUser(user);
m.setRole(role);
return m;
}
private static EntitlementSnapshot snapshot(long spend, Long cap) {
LocalDateTime start = LocalDate.now().withDayOfMonth(1).atStartOfDay();
LocalDateTime end = start.plusMonths(1);
return new EntitlementSnapshot(
EntitlementState.FULL,
FeatureSet.FULL,
List.of(
FeatureGate.OFFSITE_PROCESSING,
FeatureGate.AUTOMATION,
FeatureGate.AI_SUPPORT,
FeatureGate.CLIENT_SIDE),
spend,
cap,
start,
end);
}
private static Map<BillingCategory, Long> emptyCategoryMap() {
EnumMap<BillingCategory, Long> m = new EnumMap<>(BillingCategory.class);
for (BillingCategory c : BillingCategory.values()) {
m.put(c, 0L);
}
return m;
}
private static Authentication jwtAuth(UUID supabaseId) {
Jwt jwt =
Jwt.withTokenValue("token")
.header("alg", "RS256")
.claim("sub", supabaseId.toString())
.claim("email", "user@example.com")
.build();
return new EnhancedJwtAuthenticationToken(
jwt, List.of(), "user@example.com", supabaseId.toString());
}
}
@@ -0,0 +1,261 @@
package stirling.software.saas.payg.cap;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.List;
import java.util.Set;
import org.junit.jupiter.api.Test;
import stirling.software.saas.payg.cap.CapEvaluator.Evaluation;
import stirling.software.saas.payg.model.EntitlementState;
import stirling.software.saas.payg.model.FeatureGate;
import stirling.software.saas.payg.model.FeatureSet;
class CapEvaluatorTest {
// ---------------------------------------------------------------------------------------
// evaluate(): single-axis cap evaluation
// ---------------------------------------------------------------------------------------
@Test
void nullCap_returnsFullStateAndFullGates() {
Evaluation e = CapEvaluator.evaluate(1_000_000L, null, 80, 100, FeatureSet.MINIMAL);
assertThat(e.state()).isEqualTo(EntitlementState.FULL);
assertThat(e.featureSet()).isEqualTo(FeatureSet.FULL);
assertThat(e.enabledGates())
.containsExactlyInAnyOrder(
FeatureGate.OFFSITE_PROCESSING,
FeatureGate.AUTOMATION,
FeatureGate.AI_SUPPORT,
FeatureGate.CLIENT_SIDE);
}
@Test
void zeroCap_treatedAsUnlimitedForSafety() {
// Defensive: a zero cap would divide-by-zero. The guard treats it as null (FULL).
Evaluation e = CapEvaluator.evaluate(50L, 0L, 80, 100, FeatureSet.MINIMAL);
assertThat(e.state()).isEqualTo(EntitlementState.FULL);
}
@Test
void wellBelowWarn_returnsFull() {
Evaluation e = CapEvaluator.evaluate(10L, 100L, 80, 100, FeatureSet.MINIMAL);
assertThat(e.state()).isEqualTo(EntitlementState.FULL);
assertThat(e.featureSet()).isEqualTo(FeatureSet.FULL);
}
@Test
void exactlyAtWarnThreshold_returnsWarned() {
// 80% of 100 = 80; pct = 80 / 100 * 100 = 80 → ≥ warnAtPct=80 → WARNED
Evaluation e = CapEvaluator.evaluate(80L, 100L, 80, 100, FeatureSet.MINIMAL);
assertThat(e.state()).isEqualTo(EntitlementState.WARNED);
// Warn band keeps the FULL feature set — only flags the FE to show a banner.
assertThat(e.featureSet()).isEqualTo(FeatureSet.FULL);
assertThat(e.enabledGates()).hasSize(4);
}
@Test
void betweenWarnAndDegrade_returnsWarned() {
Evaluation e = CapEvaluator.evaluate(95L, 100L, 80, 100, FeatureSet.MINIMAL);
assertThat(e.state()).isEqualTo(EntitlementState.WARNED);
assertThat(e.featureSet()).isEqualTo(FeatureSet.FULL);
}
@Test
void exactlyAtDegradeThreshold_returnsDegradedWithConfiguredSet() {
Evaluation e = CapEvaluator.evaluate(100L, 100L, 80, 100, FeatureSet.MINIMAL);
assertThat(e.state()).isEqualTo(EntitlementState.DEGRADED);
assertThat(e.featureSet()).isEqualTo(FeatureSet.MINIMAL);
// MINIMAL keeps manual server tools (OFFSITE_PROCESSING) + client-side; only
// AUTOMATION + AI_SUPPORT are blocked.
assertThat(e.enabledGates())
.containsExactlyInAnyOrder(FeatureGate.OFFSITE_PROCESSING, FeatureGate.CLIENT_SIDE);
}
@Test
void overDegradeThreshold_returnsDegradedAndCannotEscalate() {
Evaluation e = CapEvaluator.evaluate(500L, 100L, 80, 100, FeatureSet.MINIMAL);
assertThat(e.state()).isEqualTo(EntitlementState.DEGRADED);
assertThat(e.featureSet()).isEqualTo(FeatureSet.MINIMAL);
}
@Test
void degradedFeatureSetClientOnly_dropsEverythingButClientSide() {
Evaluation e = CapEvaluator.evaluate(100L, 100L, 80, 100, FeatureSet.CLIENT_ONLY);
assertThat(e.state()).isEqualTo(EntitlementState.DEGRADED);
assertThat(e.featureSet()).isEqualTo(FeatureSet.CLIENT_ONLY);
assertThat(e.enabledGates()).containsExactly(FeatureGate.CLIENT_SIDE);
}
@Test
void nullDegradedFeatureSet_fallsBackToMinimal() {
Evaluation e = CapEvaluator.evaluate(100L, 100L, 80, 100, null);
assertThat(e.state()).isEqualTo(EntitlementState.DEGRADED);
assertThat(e.featureSet()).isEqualTo(FeatureSet.MINIMAL);
}
@Test
void misconfiguredThresholds_treatedAsNoCap() {
// warn > degrade is malformed; the evaluator returns FULL rather than risk wrong
// degradation. The admin write path is supposed to validate this.
Evaluation e = CapEvaluator.evaluate(100L, 100L, 110, 100, FeatureSet.MINIMAL);
assertThat(e.state()).isEqualTo(EntitlementState.FULL);
// negative warn → bad config → FULL
Evaluation neg = CapEvaluator.evaluate(100L, 100L, -10, 100, FeatureSet.MINIMAL);
assertThat(neg.state()).isEqualTo(EntitlementState.FULL);
// zero degrade → bad config → FULL (would otherwise degrade on any spend)
Evaluation zero = CapEvaluator.evaluate(0L, 100L, 80, 0, FeatureSet.MINIMAL);
assertThat(zero.state()).isEqualTo(EntitlementState.FULL);
}
@Test
void zeroSpend_returnsFullEvenIfCapTiny() {
Evaluation e = CapEvaluator.evaluate(0L, 1L, 80, 100, FeatureSet.MINIMAL);
assertThat(e.state()).isEqualTo(EntitlementState.FULL);
}
@Test
void warnAtZeroPct_warnsImmediately() {
// Edge case: warn-at-0% means any spend → WARNED. Allowed even if quirky.
Evaluation e = CapEvaluator.evaluate(1L, 100L, 0, 100, FeatureSet.MINIMAL);
assertThat(e.state()).isEqualTo(EntitlementState.WARNED);
}
// ---------------------------------------------------------------------------------------
// combineTeamAndMember(): team-wide × member sub-cap combination
// ---------------------------------------------------------------------------------------
@Test
void combine_memberNull_teamEvalWins() {
Evaluation team = CapEvaluator.evaluate(50L, 100L, 80, 100, FeatureSet.MINIMAL);
Evaluation combined = CapEvaluator.combineTeamAndMember(team, null);
assertThat(combined).isSameAs(team);
}
@Test
void combine_memberDegradedButTeamFull_degradesEffectiveResult() {
Evaluation team = CapEvaluator.evaluate(10L, 100L, 80, 100, FeatureSet.MINIMAL);
Evaluation member = CapEvaluator.evaluate(50L, 50L, 80, 100, FeatureSet.MINIMAL);
Evaluation combined = CapEvaluator.combineTeamAndMember(team, member);
assertThat(combined.state()).isEqualTo(EntitlementState.DEGRADED);
assertThat(combined.featureSet()).isEqualTo(FeatureSet.MINIMAL);
// Intersection of FULL (4 gates) and MINIMAL (OFFSITE_PROCESSING + CLIENT_SIDE) =
// OFFSITE_PROCESSING + CLIENT_SIDE
assertThat(combined.enabledGates())
.containsExactlyInAnyOrder(FeatureGate.OFFSITE_PROCESSING, FeatureGate.CLIENT_SIDE);
}
@Test
void combine_teamDegradedButMemberFull_stayDegraded() {
Evaluation team = CapEvaluator.evaluate(100L, 100L, 80, 100, FeatureSet.MINIMAL);
Evaluation member = CapEvaluator.evaluate(10L, 1000L, 80, 100, FeatureSet.MINIMAL);
Evaluation combined = CapEvaluator.combineTeamAndMember(team, member);
assertThat(combined.state()).isEqualTo(EntitlementState.DEGRADED);
assertThat(combined.featureSet()).isEqualTo(FeatureSet.MINIMAL);
assertThat(combined.enabledGates())
.containsExactlyInAnyOrder(FeatureGate.OFFSITE_PROCESSING, FeatureGate.CLIENT_SIDE);
}
@Test
void combine_bothWarned_warnedState_butFullFeatureSet() {
Evaluation team = CapEvaluator.evaluate(80L, 100L, 80, 100, FeatureSet.MINIMAL);
Evaluation member = CapEvaluator.evaluate(85L, 100L, 80, 100, FeatureSet.MINIMAL);
Evaluation combined = CapEvaluator.combineTeamAndMember(team, member);
assertThat(combined.state()).isEqualTo(EntitlementState.WARNED);
assertThat(combined.featureSet()).isEqualTo(FeatureSet.FULL);
}
@Test
void combine_bothFull_returnsFull() {
Evaluation team = CapEvaluator.evaluate(10L, 100L, 80, 100, FeatureSet.MINIMAL);
Evaluation member = CapEvaluator.evaluate(5L, 50L, 80, 100, FeatureSet.MINIMAL);
Evaluation combined = CapEvaluator.combineTeamAndMember(team, member);
assertThat(combined.state()).isEqualTo(EntitlementState.FULL);
assertThat(combined.featureSet()).isEqualTo(FeatureSet.FULL);
}
@Test
void combine_differentDegradedSets_picksStrictest() {
// If team policy says degrade-to-MINIMAL and member's hypothetical sub-policy says
// degrade-to-CLIENT_ONLY, the stricter (CLIENT_ONLY) wins. In practice today member
// sub-policies use the same set as the team, but the helper is correct in either case.
Evaluation team = CapEvaluator.evaluate(100L, 100L, 80, 100, FeatureSet.MINIMAL);
Evaluation member = CapEvaluator.evaluate(100L, 100L, 80, 100, FeatureSet.CLIENT_ONLY);
Evaluation combined = CapEvaluator.combineTeamAndMember(team, member);
assertThat(combined.state()).isEqualTo(EntitlementState.DEGRADED);
assertThat(combined.featureSet()).isEqualTo(FeatureSet.CLIENT_ONLY);
}
// ---------------------------------------------------------------------------------------
// gatesFor(): mapping FeatureSet → declared gates
// ---------------------------------------------------------------------------------------
@Test
void gatesFor_full_listsAllFour() {
assertThat(CapEvaluator.gatesFor(FeatureSet.FULL))
.containsExactlyInAnyOrder(
FeatureGate.OFFSITE_PROCESSING,
FeatureGate.AUTOMATION,
FeatureGate.AI_SUPPORT,
FeatureGate.CLIENT_SIDE);
}
@Test
void gatesFor_minimal_keepsOffsiteAndClientSide() {
// MINIMAL keeps manual server tools (OFFSITE_PROCESSING) + client-side; AUTOMATION +
// AI_SUPPORT are the only gates dropped on degrade.
assertThat(CapEvaluator.gatesFor(FeatureSet.MINIMAL))
.containsExactlyInAnyOrder(FeatureGate.OFFSITE_PROCESSING, FeatureGate.CLIENT_SIDE);
}
@Test
void gatesFor_null_returnsEmpty() {
assertThat(CapEvaluator.gatesFor(null)).isEmpty();
}
// ---------------------------------------------------------------------------------------
// allEnabled(): the entitlement-guard predicate
// ---------------------------------------------------------------------------------------
@Test
void allEnabled_emptyRequired_returnsTrue() {
assertThat(CapEvaluator.allEnabled(Set.of(), List.of(FeatureGate.CLIENT_SIDE))).isTrue();
assertThat(CapEvaluator.allEnabled(null, List.of(FeatureGate.CLIENT_SIDE))).isTrue();
}
@Test
void allEnabled_subsetMatches_returnsTrue() {
assertThat(
CapEvaluator.allEnabled(
Set.of(FeatureGate.OFFSITE_PROCESSING),
List.of(FeatureGate.OFFSITE_PROCESSING, FeatureGate.CLIENT_SIDE)))
.isTrue();
}
@Test
void allEnabled_missingOneOfMany_returnsFalse() {
assertThat(
CapEvaluator.allEnabled(
Set.of(FeatureGate.OFFSITE_PROCESSING, FeatureGate.AI_SUPPORT),
List.of(FeatureGate.OFFSITE_PROCESSING)))
.isFalse();
}
@Test
void allEnabled_nullEnabled_returnsFalseUnlessRequiredEmpty() {
assertThat(CapEvaluator.allEnabled(Set.of(FeatureGate.OFFSITE_PROCESSING), null)).isFalse();
}
}
@@ -0,0 +1,52 @@
package stirling.software.saas.payg.cap;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.Test;
import org.springframework.core.annotation.AnnotationUtils;
import stirling.software.saas.ai.controller.AiCreateController;
import stirling.software.saas.ai.controller.AiCreateInternalController;
import stirling.software.saas.ai.controller.AiProxyController;
import stirling.software.saas.payg.model.FeatureGate;
/**
* Annotation-rollout guard. The saas {@code PaygChargeInterceptor} reads class-level
* {@code @RequiresFeature} via {@link AnnotationUtils#findAnnotation(Class, Class)} to decide
* whether a request bills as {@code AI}, {@code AUTOMATION}, or falls through to the auth-derived
* default. These tests pin the gate on each AI surface so the classification can't silently regress
* to {@code BYPASSED} if someone strips the annotation while refactoring.
*
* <p><b>Out of scope</b>: {@code PipelineController} (in core) and {@code PolicyController} (in
* proprietary) — neither module can import {@code @RequiresFeature} from saas without a forbidden
* upward dependency. Their automation classification is enforced via the {@code
* X-Stirling-Automation} header set unconditionally by {@code InternalApiClient.post}; see the
* dedicated test in that module.
*/
class RequiresFeatureAnnotationRolloutTest {
@Test
void aiCreateController_isClassifiedAsAiSupport() {
RequiresFeature ann =
AnnotationUtils.findAnnotation(AiCreateController.class, RequiresFeature.class);
assertThat(ann).isNotNull();
assertThat(ann.value()).containsExactly(FeatureGate.AI_SUPPORT);
}
@Test
void aiCreateInternalController_isClassifiedAsAiSupport() {
RequiresFeature ann =
AnnotationUtils.findAnnotation(
AiCreateInternalController.class, RequiresFeature.class);
assertThat(ann).isNotNull();
assertThat(ann.value()).containsExactly(FeatureGate.AI_SUPPORT);
}
@Test
void aiProxyController_isClassifiedAsAiSupport() {
RequiresFeature ann =
AnnotationUtils.findAnnotation(AiProxyController.class, RequiresFeature.class);
assertThat(ann).isNotNull();
assertThat(ann.value()).containsExactly(FeatureGate.AI_SUPPORT);
}
}
@@ -17,14 +17,18 @@ import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.transaction.support.TransactionSynchronization;
import org.springframework.transaction.support.TransactionSynchronizationManager;
import org.springframework.web.multipart.MultipartFile;
import stirling.software.saas.payg.docs.DocumentClassifier;
@@ -33,13 +37,17 @@ import stirling.software.saas.payg.job.JobContext;
import stirling.software.saas.payg.job.JobService;
import stirling.software.saas.payg.job.JoinOrOpenResult;
import stirling.software.saas.payg.job.ProcessingJob;
import stirling.software.saas.payg.meter.PaygMeterReportingService;
import stirling.software.saas.payg.model.BillingCategory;
import stirling.software.saas.payg.model.JobSource;
import stirling.software.saas.payg.model.JobStatus;
import stirling.software.saas.payg.model.ProcessType;
import stirling.software.saas.payg.model.ShadowChargeStatus;
import stirling.software.saas.payg.policy.PaygTeamExtensions;
import stirling.software.saas.payg.policy.PricingPolicy;
import stirling.software.saas.payg.policy.PricingPolicyService;
import stirling.software.saas.payg.repository.PaygShadowChargeRepository;
import stirling.software.saas.payg.repository.PaygTeamExtensionsRepository;
import stirling.software.saas.payg.repository.ProcessingJobRepository;
import stirling.software.saas.payg.shadow.PaygShadowCharge;
@@ -54,6 +62,8 @@ class JobChargeServiceTest {
private DocumentClassifier classifier;
private PaygShadowChargeRepository shadowRepo;
private ProcessingJobRepository jobRepo;
private PaygTeamExtensionsRepository teamExtRepo;
private PaygMeterReportingService meterReporter;
private JobChargeService service;
@BeforeEach
@@ -63,7 +73,26 @@ class JobChargeServiceTest {
classifier = Mockito.mock(DocumentClassifier.class);
shadowRepo = Mockito.mock(PaygShadowChargeRepository.class);
jobRepo = Mockito.mock(ProcessingJobRepository.class);
service = new JobChargeService(jobService, policyService, classifier, shadowRepo, jobRepo);
teamExtRepo = Mockito.mock(PaygTeamExtensionsRepository.class);
meterReporter = Mockito.mock(PaygMeterReportingService.class);
service =
new JobChargeService(
jobService,
policyService,
classifier,
shadowRepo,
jobRepo,
teamExtRepo,
meterReporter);
}
@AfterEach
void tearDown() {
// Defensive: a previous test could have left a fake synchronization registered. Clearing
// ensures isolation when tests run in any order.
if (TransactionSynchronizationManager.isSynchronizationActive()) {
TransactionSynchronizationManager.clear();
}
}
@Test
@@ -80,7 +109,12 @@ class JobChargeServiceTest {
ChargeOutcome out =
service.openProcess(
new ChargeContext(42L, 100L, JobSource.WEB, ProcessType.SINGLE_TOOL),
new ChargeContext(
42L,
100L,
JobSource.WEB,
ProcessType.SINGLE_TOOL,
BillingCategory.API),
List.of(in));
assertThat(out.disposition()).isEqualTo(ChargeOutcome.Disposition.JOINED);
@@ -106,7 +140,12 @@ class JobChargeServiceTest {
ChargeOutcome out =
service.openProcess(
new ChargeContext(42L, 100L, JobSource.WEB, ProcessType.SINGLE_TOOL),
new ChargeContext(
42L,
100L,
JobSource.WEB,
ProcessType.SINGLE_TOOL,
BillingCategory.API),
List.of(in));
assertThat(out.disposition()).isEqualTo(ChargeOutcome.Disposition.OPENED);
@@ -126,11 +165,42 @@ class JobChargeServiceTest {
// Legacy comparison not wired yet — zeroed until CreditService is wired in the follow-up.
assertThat(row.getLegacyCreditsCharged()).isZero();
assertThat(row.getDiffPct()).isZero();
// PAYG analytics axis: billing_category + job_source are copied from the context so the
// row stays self-describing after processing_job rows are pruned.
assertThat(row.getBillingCategory()).isEqualTo(BillingCategory.API);
assertThat(row.getJobSource()).isEqualTo(JobSource.WEB);
// Job entity carries the classified docUnits so close-time receipts can render correctly.
assertThat(newJob.getDocUnits()).isEqualTo(4);
}
@Test
void openProcess_openedAutomationContext_writesShadowRowWithAutomationCategory(
@TempDir Path tmp) throws IOException {
PricingPolicy policy =
stubPolicy(/*minCharge*/ 1, Map.of(JobSource.WEB, 10, JobSource.PIPELINE, 20));
when(policyService.getEffectivePolicy(100L)).thenReturn(policy);
ProcessingJob newJob = openJob(UUID.randomUUID());
when(jobService.joinOrOpen(any(JobContext.class), anyList()))
.thenReturn(new JoinOrOpenResult(newJob, JoinOrOpenResult.Disposition.OPENED));
when(classifier.classify(any(MultipartFile.class), any(Path.class), eq(policy)))
.thenReturn(new DocumentMetrics(1, 100L, "application/pdf", 1));
service.openProcess(
new ChargeContext(
42L,
100L,
JobSource.PIPELINE,
ProcessType.AUTOMATION,
BillingCategory.AUTOMATION),
List.of(jobInput(tmp, "in.pdf", "application/pdf")));
ArgumentCaptor<PaygShadowCharge> captor = ArgumentCaptor.forClass(PaygShadowCharge.class);
verify(shadowRepo).save(captor.capture());
assertThat(captor.getValue().getBillingCategory()).isEqualTo(BillingCategory.AUTOMATION);
assertThat(captor.getValue().getJobSource()).isEqualTo(JobSource.PIPELINE);
}
@Test
void openProcess_openedMultiFile_usesListClassifier(@TempDir Path tmp) throws IOException {
PricingPolicy policy = stubPolicy(/*minCharge*/ 1, Map.of(JobSource.WEB, 10));
@@ -146,7 +216,12 @@ class JobChargeServiceTest {
ChargeOutcome out =
service.openProcess(
new ChargeContext(42L, 100L, JobSource.WEB, ProcessType.AUTOMATION),
new ChargeContext(
42L,
100L,
JobSource.WEB,
ProcessType.AUTOMATION,
BillingCategory.AUTOMATION),
List.of(a, b));
assertThat(out.units()).isEqualTo(7);
@@ -167,7 +242,12 @@ class JobChargeServiceTest {
ChargeOutcome out =
service.openProcess(
new ChargeContext(42L, 100L, JobSource.WEB, ProcessType.SINGLE_TOOL),
new ChargeContext(
42L,
100L,
JobSource.WEB,
ProcessType.SINGLE_TOOL,
BillingCategory.API),
List.of(jobInput(tmp, "in.pdf", "application/pdf")));
assertThat(out.units()).isEqualTo(5);
@@ -187,7 +267,12 @@ class JobChargeServiceTest {
.thenReturn(new DocumentMetrics(1, 100L, "application/pdf", 1));
service.openProcess(
new ChargeContext(42L, 100L, JobSource.PIPELINE, ProcessType.AUTOMATION),
new ChargeContext(
42L,
100L,
JobSource.PIPELINE,
ProcessType.AUTOMATION,
BillingCategory.AUTOMATION),
List.of(jobInput(tmp, "in.pdf", "application/pdf")));
ArgumentCaptor<JobContext> ctxCaptor = ArgumentCaptor.forClass(JobContext.class);
@@ -211,7 +296,12 @@ class JobChargeServiceTest {
.thenReturn(new DocumentMetrics(1, 100L, "application/pdf", 1));
service.openProcess(
new ChargeContext(42L, 100L, JobSource.DESKTOP_APP, ProcessType.SINGLE_TOOL),
new ChargeContext(
42L,
100L,
JobSource.DESKTOP_APP,
ProcessType.SINGLE_TOOL,
BillingCategory.API),
List.of(jobInput(tmp, "in.pdf", "application/pdf")));
ArgumentCaptor<JobContext> ctxCaptor = ArgumentCaptor.forClass(JobContext.class);
@@ -225,7 +315,11 @@ class JobChargeServiceTest {
() ->
service.openProcess(
new ChargeContext(
42L, 100L, JobSource.WEB, ProcessType.SINGLE_TOOL),
42L,
100L,
JobSource.WEB,
ProcessType.SINGLE_TOOL,
BillingCategory.API),
List.of()))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("inputs must not be empty");
@@ -330,6 +424,198 @@ class JobChargeServiceTest {
verify(jobRepo, never()).save(any());
}
// --- close() — meter reporting in afterCommit -----------------------------------------------
@Test
void close_subscribedTeam_postsMeterEventAfterCommit() {
UUID jobId = UUID.randomUUID();
ProcessingJob job = openJob(jobId);
when(jobService.close(jobId)).thenReturn(job);
PaygShadowCharge row = chargedShadowRow(jobId, 100L, 4, BillingCategory.API);
when(shadowRepo.findFirstByJobIdOrderByIdAsc(jobId)).thenReturn(Optional.of(row));
PaygTeamExtensions ext = new PaygTeamExtensions();
ext.setTeamId(100L);
ext.setStripeCustomerId("cus_subscribed");
when(teamExtRepo.findById(100L)).thenReturn(Optional.of(ext));
withTransactionSynchronization(
() -> {
service.close(jobId);
Mockito.verifyNoInteractions(meterReporter);
});
// afterCommit ran on tearDown of withTransactionSynchronization → meter posted now.
verify(meterReporter)
.recordUsage(
100L,
"cus_subscribed",
4,
BillingCategory.API,
"process:" + jobId + ":close");
}
@Test
void close_freeTierTeam_doesNotPostMeterEvent() {
UUID jobId = UUID.randomUUID();
ProcessingJob job = openJob(jobId);
when(jobService.close(jobId)).thenReturn(job);
PaygShadowCharge row = chargedShadowRow(jobId, 100L, 4, BillingCategory.API);
when(shadowRepo.findFirstByJobIdOrderByIdAsc(jobId)).thenReturn(Optional.of(row));
// No stripe_customer_id → treated as free-tier on this branch (pre-#6532).
PaygTeamExtensions ext = new PaygTeamExtensions();
ext.setTeamId(100L);
ext.setStripeCustomerId(null);
when(teamExtRepo.findById(100L)).thenReturn(Optional.of(ext));
withTransactionSynchronization(() -> service.close(jobId));
Mockito.verifyNoInteractions(meterReporter);
}
@Test
void close_noTeamExtensionsRow_doesNotPostMeterEvent() {
UUID jobId = UUID.randomUUID();
ProcessingJob job = openJob(jobId);
when(jobService.close(jobId)).thenReturn(job);
PaygShadowCharge row = chargedShadowRow(jobId, 100L, 4, BillingCategory.API);
when(shadowRepo.findFirstByJobIdOrderByIdAsc(jobId)).thenReturn(Optional.of(row));
when(teamExtRepo.findById(100L)).thenReturn(Optional.empty());
withTransactionSynchronization(() -> service.close(jobId));
Mockito.verifyNoInteractions(meterReporter);
}
@Test
void close_refundedShadowRow_doesNotPostMeterEvent() {
UUID jobId = UUID.randomUUID();
ProcessingJob job = openJob(jobId);
when(jobService.close(jobId)).thenReturn(job);
PaygShadowCharge row = chargedShadowRow(jobId, 100L, 4, BillingCategory.API);
row.setStatus(ShadowChargeStatus.REFUNDED);
when(shadowRepo.findFirstByJobIdOrderByIdAsc(jobId)).thenReturn(Optional.of(row));
withTransactionSynchronization(() -> service.close(jobId));
Mockito.verifyNoInteractions(meterReporter);
Mockito.verifyNoInteractions(teamExtRepo);
}
@Test
void close_noShadowRow_doesNotPostMeterEvent() {
UUID jobId = UUID.randomUUID();
ProcessingJob job = openJob(jobId);
when(jobService.close(jobId)).thenReturn(job);
when(shadowRepo.findFirstByJobIdOrderByIdAsc(jobId)).thenReturn(Optional.empty());
withTransactionSynchronization(() -> service.close(jobId));
Mockito.verifyNoInteractions(meterReporter);
Mockito.verifyNoInteractions(teamExtRepo);
}
@Test
void close_bypassedCategoryOnShadowRow_doesNotPostMeterEvent() {
// Defensive: BYPASSED rows shouldn't normally exist (the interceptor short-circuits
// before openProcess), but if one slips through we must not meter it.
UUID jobId = UUID.randomUUID();
ProcessingJob job = openJob(jobId);
when(jobService.close(jobId)).thenReturn(job);
PaygShadowCharge row = chargedShadowRow(jobId, 100L, 4, BillingCategory.BYPASSED);
when(shadowRepo.findFirstByJobIdOrderByIdAsc(jobId)).thenReturn(Optional.of(row));
withTransactionSynchronization(() -> service.close(jobId));
Mockito.verifyNoInteractions(meterReporter);
Mockito.verifyNoInteractions(teamExtRepo);
}
@Test
void close_meterReporterThrowsRuntimeException_doesNotPropagate() {
// PaygMeterReportingService is documented to swallow; defence-in-depth in
// JobChargeService catches a misbehaving impl so the afterCommit hook can't poison the
// close flow.
UUID jobId = UUID.randomUUID();
ProcessingJob job = openJob(jobId);
when(jobService.close(jobId)).thenReturn(job);
PaygShadowCharge row = chargedShadowRow(jobId, 100L, 4, BillingCategory.AUTOMATION);
when(shadowRepo.findFirstByJobIdOrderByIdAsc(jobId)).thenReturn(Optional.of(row));
PaygTeamExtensions ext = new PaygTeamExtensions();
ext.setTeamId(100L);
ext.setStripeCustomerId("cus_subscribed");
when(teamExtRepo.findById(100L)).thenReturn(Optional.of(ext));
Mockito.doThrow(new RuntimeException("simulated meter failure"))
.when(meterReporter)
.recordUsage(
Mockito.anyLong(),
Mockito.anyString(),
Mockito.anyInt(),
Mockito.any(BillingCategory.class),
Mockito.anyString());
// Should not throw — afterCommit's defence-in-depth wraps the call.
withTransactionSynchronization(() -> service.close(jobId));
verify(meterReporter)
.recordUsage(
100L,
"cus_subscribed",
4,
BillingCategory.AUTOMATION,
"process:" + jobId + ":close");
}
@Test
void close_noActiveTransactionSync_skipsMeterPostButStillClosesJob() {
// Direct call without an outer @Transactional → no sync to register against. close()
// must still close the job; the meter post is implicitly deferred to whatever async path
// eventually wraps the call (or is never made, which is fine for ledger-only flows).
UUID jobId = UUID.randomUUID();
ProcessingJob job = openJob(jobId);
when(jobService.close(jobId)).thenReturn(job);
assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse();
service.close(jobId);
Mockito.verifyNoInteractions(meterReporter);
verify(jobService).close(jobId);
}
private static void withTransactionSynchronization(Runnable body) {
TransactionSynchronizationManager.initSynchronization();
try {
body.run();
// Drain registered synchronizations to simulate a successful commit.
for (TransactionSynchronization sync :
TransactionSynchronizationManager.getSynchronizations()) {
sync.afterCommit();
}
} finally {
TransactionSynchronizationManager.clear();
}
}
private static PaygShadowCharge chargedShadowRow(
UUID jobId, Long teamId, int units, BillingCategory category) {
PaygShadowCharge row = new PaygShadowCharge();
row.setJobId(jobId);
row.setTeamId(teamId);
row.setPaygUnits(units);
row.setStatus(ShadowChargeStatus.CHARGED);
row.setBillingCategory(category);
return row;
}
// --- helpers --------------------------------------------------------------------------------
private static PricingPolicy stubPolicy(int minCharge, Map<JobSource, Integer> stepLimits) {
@@ -0,0 +1,473 @@
package stirling.software.saas.payg.entitlement;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.lang.reflect.Method;
import java.time.Instant;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.web.method.HandlerMethod;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.simple.SimpleMeterRegistry;
import stirling.software.common.annotations.AutoJobPostMapping;
import stirling.software.proprietary.model.Team;
import stirling.software.proprietary.security.database.repository.UserRepository;
import stirling.software.proprietary.security.model.User;
import stirling.software.saas.payg.cap.RequiresFeature;
import stirling.software.saas.payg.model.EntitlementState;
import stirling.software.saas.payg.model.FeatureGate;
import stirling.software.saas.payg.model.FeatureSet;
import stirling.software.saas.security.EnhancedJwtAuthenticationToken;
/**
* Pure-Mockito tests for {@link EntitlementGuard}. Covers the four decision-matrix cells: anonymous
* billable → 401, anonymous manual → pass, authenticated FULL → pass, authenticated DEGRADED for a
* billable route → 402.
*/
class EntitlementGuardTest {
private EntitlementService entitlementService;
private UserRepository userRepository;
private MeterRegistry meterRegistry;
private EntitlementGuard guard;
private final ObjectMapper json = new ObjectMapper();
@BeforeEach
void setUp() {
entitlementService = Mockito.mock(EntitlementService.class);
userRepository = Mockito.mock(UserRepository.class);
meterRegistry = new SimpleMeterRegistry();
guard = new EntitlementGuard(entitlementService, userRepository, meterRegistry);
SecurityContextHolder.clearContext();
}
@AfterEach
void tearDown() {
SecurityContextHolder.clearContext();
}
// ---------------------------------------------------------------------------------------
// Scope: non-AutoJobPostMapping routes skip the guard entirely
// ---------------------------------------------------------------------------------------
@Test
void nonHandlerMethod_passesThrough() throws Exception {
MockHttpServletRequest req = new MockHttpServletRequest();
MockHttpServletResponse res = new MockHttpServletResponse();
boolean proceed = guard.preHandle(req, res, "someRawHandler");
assertThat(proceed).isTrue();
assertThat(res.getStatus()).isEqualTo(200);
}
@Test
void routeWithNeitherAnnotation_isSkipped() throws Exception {
HandlerMethod hm = handlerFor("plainEndpoint");
MockHttpServletRequest req = new MockHttpServletRequest();
MockHttpServletResponse res = new MockHttpServletResponse();
boolean proceed = guard.preHandle(req, res, hm);
assertThat(proceed).isTrue();
Mockito.verifyNoInteractions(entitlementService, userRepository);
}
@Test
void routeWithRequiresFeatureButNoAutoJobPostMapping_isInScope() throws Exception {
// Regression: @RequiresFeature alone (e.g. JSON-bodied AI controllers) must be in-scope.
// Previously the guard short-circuited unless @AutoJobPostMapping was present, which meant
// a team without AI entitlement could hit /api/v1/ai/* freely.
UUID supabaseId = UUID.randomUUID();
SecurityContextHolder.getContext().setAuthentication(jwtAuth(supabaseId));
when(userRepository.findBySupabaseId(supabaseId))
.thenReturn(Optional.of(userWithTeam(7L, 42L)));
when(entitlementService.getSnapshot(42L)).thenReturn(degradedSnapshot());
HandlerMethod hm = handlerFor("aiOnlyNoAutoJobPostMapping");
MockHttpServletRequest req = new MockHttpServletRequest();
MockHttpServletResponse res = new MockHttpServletResponse();
boolean proceed = guard.preHandle(req, res, hm);
assertThat(proceed).isFalse();
assertThat(res.getStatus()).isEqualTo(402);
JsonNode body = json.readTree(res.getContentAsByteArray());
assertThat(body.get("error").asText()).isEqualTo("FEATURE_DEGRADED");
assertThat(body.get("missingGates").get(0).asText()).isEqualTo("AI_SUPPORT");
verify(entitlementService).getSnapshot(42L);
}
@Test
void routeWithClassLevelRequiresFeatureOnly_isInScope() throws Exception {
// Mirrors AiCreateController shape: @RequiresFeature lives on the @RestController class,
// not the method. Must still be picked up by the guard.
SecurityContextHolder.getContext()
.setAuthentication(
new AnonymousAuthenticationToken(
"key",
"anonymousUser",
List.of(new SimpleGrantedAuthority("ROLE_ANONYMOUS"))));
HandlerMethod hm = handlerForClassLevel("classLevelAiMethod");
MockHttpServletRequest req = new MockHttpServletRequest();
MockHttpServletResponse res = new MockHttpServletResponse();
boolean proceed = guard.preHandle(req, res, hm);
assertThat(proceed).isFalse();
assertThat(res.getStatus()).isEqualTo(401);
JsonNode body = json.readTree(res.getContentAsByteArray());
assertThat(body.get("error").asText()).isEqualTo("SIGNUP_REQUIRED");
assertThat(body.get("category").asText()).isEqualTo("AI");
}
// ---------------------------------------------------------------------------------------
// Anonymous user
// ---------------------------------------------------------------------------------------
@Test
void anonymousUser_billableRoute_returns401SignupRequired() throws Exception {
SecurityContextHolder.getContext()
.setAuthentication(
new AnonymousAuthenticationToken(
"key",
"anonymousUser",
List.of(new SimpleGrantedAuthority("ROLE_ANONYMOUS"))));
HandlerMethod hm = handlerFor("automationOnly");
MockHttpServletRequest req = new MockHttpServletRequest();
MockHttpServletResponse res = new MockHttpServletResponse();
boolean proceed = guard.preHandle(req, res, hm);
assertThat(proceed).isFalse();
assertThat(res.getStatus()).isEqualTo(401);
assertThat(res.getContentType()).startsWith(MediaType.APPLICATION_JSON_VALUE);
JsonNode body = json.readTree(res.getContentAsByteArray());
assertThat(body.get("error").asText()).isEqualTo("SIGNUP_REQUIRED");
assertThat(body.get("category").asText()).isEqualTo("AUTOMATION");
Mockito.verifyNoInteractions(entitlementService);
}
@Test
void anonymousUser_aiRoute_returns401WithAiCategory() throws Exception {
SecurityContextHolder.getContext()
.setAuthentication(
new AnonymousAuthenticationToken(
"key",
"anonymousUser",
List.of(new SimpleGrantedAuthority("ROLE_ANONYMOUS"))));
HandlerMethod hm = handlerFor("aiOnly");
MockHttpServletRequest req = new MockHttpServletRequest();
MockHttpServletResponse res = new MockHttpServletResponse();
boolean proceed = guard.preHandle(req, res, hm);
assertThat(proceed).isFalse();
JsonNode body = json.readTree(res.getContentAsByteArray());
assertThat(body.get("category").asText()).isEqualTo("AI");
}
@Test
void anonymousUser_manualTool_passesThroughUnbilled() throws Exception {
SecurityContextHolder.getContext()
.setAuthentication(
new AnonymousAuthenticationToken(
"key",
"anonymousUser",
List.of(new SimpleGrantedAuthority("ROLE_ANONYMOUS"))));
HandlerMethod hm = handlerFor("manualTool");
MockHttpServletRequest req = new MockHttpServletRequest();
MockHttpServletResponse res = new MockHttpServletResponse();
boolean proceed = guard.preHandle(req, res, hm);
assertThat(proceed).isTrue();
assertThat(res.getStatus()).isEqualTo(200);
Mockito.verifyNoInteractions(entitlementService);
}
// ---------------------------------------------------------------------------------------
// Authenticated user — FULL vs DEGRADED
// ---------------------------------------------------------------------------------------
@Test
void authenticatedUser_fullState_passesThrough() throws Exception {
UUID supabaseId = UUID.randomUUID();
SecurityContextHolder.getContext().setAuthentication(jwtAuth(supabaseId));
when(userRepository.findBySupabaseId(supabaseId))
.thenReturn(Optional.of(userWithTeam(7L, 42L)));
when(entitlementService.getSnapshot(42L)).thenReturn(fullSnapshot());
HandlerMethod hm = handlerFor("automationOnly");
MockHttpServletRequest req = new MockHttpServletRequest();
MockHttpServletResponse res = new MockHttpServletResponse();
boolean proceed = guard.preHandle(req, res, hm);
assertThat(proceed).isTrue();
assertThat(res.getStatus()).isEqualTo(200);
}
@Test
void authenticatedUser_degradedAndBillable_returns402() throws Exception {
UUID supabaseId = UUID.randomUUID();
SecurityContextHolder.getContext().setAuthentication(jwtAuth(supabaseId));
when(userRepository.findBySupabaseId(supabaseId))
.thenReturn(Optional.of(userWithTeam(7L, 42L)));
when(entitlementService.getSnapshot(42L)).thenReturn(degradedSnapshot());
HandlerMethod hm = handlerFor("automationOnly");
MockHttpServletRequest req = new MockHttpServletRequest();
MockHttpServletResponse res = new MockHttpServletResponse();
boolean proceed = guard.preHandle(req, res, hm);
assertThat(proceed).isFalse();
assertThat(res.getStatus()).isEqualTo(402);
assertThat(res.getContentType()).startsWith(MediaType.APPLICATION_JSON_VALUE);
JsonNode body = json.readTree(res.getContentAsByteArray());
assertThat(body.get("error").asText()).isEqualTo("FEATURE_DEGRADED");
assertThat(body.get("state").asText()).isEqualTo("DEGRADED");
assertThat(body.get("capUnits").asLong()).isEqualTo(500L);
assertThat(body.get("spendUnits").asLong()).isEqualTo(500L);
assertThat(body.get("missingGates").isArray()).isTrue();
assertThat(body.get("missingGates").get(0).asText()).isEqualTo("AUTOMATION");
}
@Test
void authenticatedUser_degradedButManualTool_passesThrough() throws Exception {
// KEY assertion: DEGRADED+MINIMAL must still allow manual server tools (OFFSITE_PROCESSING)
// — that's the whole point of moving OFFSITE into MINIMAL.
UUID supabaseId = UUID.randomUUID();
SecurityContextHolder.getContext().setAuthentication(jwtAuth(supabaseId));
when(userRepository.findBySupabaseId(supabaseId))
.thenReturn(Optional.of(userWithTeam(7L, 42L)));
when(entitlementService.getSnapshot(42L)).thenReturn(degradedSnapshot());
HandlerMethod hm = handlerFor("manualTool");
MockHttpServletRequest req = new MockHttpServletRequest();
MockHttpServletResponse res = new MockHttpServletResponse();
boolean proceed = guard.preHandle(req, res, hm);
assertThat(proceed).isTrue();
assertThat(res.getStatus()).isEqualTo(200);
}
@Test
void authenticatedUser_aiRouteDegraded_returns402() throws Exception {
UUID supabaseId = UUID.randomUUID();
SecurityContextHolder.getContext().setAuthentication(jwtAuth(supabaseId));
when(userRepository.findBySupabaseId(supabaseId))
.thenReturn(Optional.of(userWithTeam(7L, 42L)));
when(entitlementService.getSnapshot(42L)).thenReturn(degradedSnapshot());
HandlerMethod hm = handlerFor("aiOnly");
MockHttpServletRequest req = new MockHttpServletRequest();
MockHttpServletResponse res = new MockHttpServletResponse();
boolean proceed = guard.preHandle(req, res, hm);
assertThat(proceed).isFalse();
assertThat(res.getStatus()).isEqualTo(402);
JsonNode body = json.readTree(res.getContentAsByteArray());
assertThat(body.get("missingGates").get(0).asText()).isEqualTo("AI_SUPPORT");
}
// ---------------------------------------------------------------------------------------
// Fail-open
// ---------------------------------------------------------------------------------------
@Test
void snapshotLookupThrows_failsOpenAndPasses() throws Exception {
UUID supabaseId = UUID.randomUUID();
SecurityContextHolder.getContext().setAuthentication(jwtAuth(supabaseId));
when(userRepository.findBySupabaseId(supabaseId))
.thenReturn(Optional.of(userWithTeam(7L, 42L)));
when(entitlementService.getSnapshot(42L))
.thenThrow(new RuntimeException("transient DB outage"));
HandlerMethod hm = handlerFor("automationOnly");
MockHttpServletRequest req = new MockHttpServletRequest();
MockHttpServletResponse res = new MockHttpServletResponse();
boolean proceed = guard.preHandle(req, res, hm);
assertThat(proceed).isTrue();
assertThat(res.getStatus()).isEqualTo(200);
}
@Test
void noTeam_passesThrough() throws Exception {
UUID supabaseId = UUID.randomUUID();
SecurityContextHolder.getContext().setAuthentication(jwtAuth(supabaseId));
User u = new User();
u.setId(7L);
u.setTeam(null);
when(userRepository.findBySupabaseId(supabaseId)).thenReturn(Optional.of(u));
HandlerMethod hm = handlerFor("automationOnly");
MockHttpServletRequest req = new MockHttpServletRequest();
MockHttpServletResponse res = new MockHttpServletResponse();
boolean proceed = guard.preHandle(req, res, hm);
assertThat(proceed).isTrue();
verify(entitlementService, never()).getSnapshot(any());
}
// ---------------------------------------------------------------------------------------
// resolveRequiredGates fallback
// ---------------------------------------------------------------------------------------
@Test
void resolveRequiredGates_noAnnotation_defaultsToOffsiteProcessing() throws Exception {
HandlerMethod hm = handlerFor("manualTool");
FeatureGate[] gates = EntitlementGuard.resolveRequiredGates(hm);
assertThat(gates).containsExactly(FeatureGate.OFFSITE_PROCESSING);
}
@Test
void resolveRequiredGates_withAnnotation_usesAnnotationValue() throws Exception {
HandlerMethod hm = handlerFor("automationOnly");
FeatureGate[] gates = EntitlementGuard.resolveRequiredGates(hm);
assertThat(gates).containsExactly(FeatureGate.AUTOMATION);
}
// ---------------------------------------------------------------------------------------
// Helpers / fixture controller
// ---------------------------------------------------------------------------------------
private static EntitlementSnapshot fullSnapshot() {
return new EntitlementSnapshot(
EntitlementState.FULL,
FeatureSet.FULL,
List.of(
FeatureGate.OFFSITE_PROCESSING,
FeatureGate.AUTOMATION,
FeatureGate.AI_SUPPORT,
FeatureGate.CLIENT_SIDE),
0L,
500L,
LocalDateTime.of(2026, 6, 1, 0, 0),
LocalDateTime.of(2026, 7, 1, 0, 0));
}
private static EntitlementSnapshot degradedSnapshot() {
return new EntitlementSnapshot(
EntitlementState.DEGRADED,
FeatureSet.MINIMAL,
List.of(FeatureGate.OFFSITE_PROCESSING, FeatureGate.CLIENT_SIDE),
500L,
500L,
LocalDateTime.of(2026, 6, 1, 0, 0),
LocalDateTime.of(2026, 7, 1, 0, 0));
}
private static User userWithTeam(long userId, long teamId) {
User u = new User();
u.setId(userId);
Team t = new Team();
t.setId(teamId);
u.setTeam(t);
return u;
}
private static EnhancedJwtAuthenticationToken jwtAuth(UUID supabaseId) {
Map<String, Object> headers = new HashMap<>();
headers.put("alg", "RS256");
Map<String, Object> claims = new HashMap<>();
claims.put("sub", supabaseId.toString());
claims.put("email", "user@example.com");
Jwt jwt = new Jwt("token", Instant.now(), Instant.now().plusSeconds(3600), headers, claims);
return new EnhancedJwtAuthenticationToken(
jwt,
List.of(new SimpleGrantedAuthority("ROLE_USER")),
"user@example.com",
supabaseId.toString());
}
private static HandlerMethod handlerFor(String methodName) throws NoSuchMethodException {
Method m = TestController.class.getDeclaredMethod(methodName);
return new HandlerMethod(new TestController(), m);
}
private static HandlerMethod handlerForClassLevel(String methodName)
throws NoSuchMethodException {
Method m = ClassLevelAiController.class.getDeclaredMethod(methodName);
return new HandlerMethod(new ClassLevelAiController(), m);
}
/** Fixture mounting route shapes the guard's resolver needs to discriminate. */
static class TestController {
@AutoJobPostMapping("/manual")
public String manualTool() {
return "ok";
}
@AutoJobPostMapping("/automation")
@RequiresFeature(FeatureGate.AUTOMATION)
public String automationOnly() {
return "ok";
}
@AutoJobPostMapping("/ai")
@RequiresFeature(FeatureGate.AI_SUPPORT)
public String aiOnly() {
return "ok";
}
/** Endpoint without any annotation — guard must skip. */
public String plainEndpoint() {
return "ok";
}
/** AI-controller shape: @RequiresFeature with NO @AutoJobPostMapping (JSON body). */
@RequiresFeature(FeatureGate.AI_SUPPORT)
public String aiOnlyNoAutoJobPostMapping() {
return "ok";
}
}
/**
* Mirrors {@code AiCreateController} layout: @RequiresFeature on the class, plain methods. The
* guard must pick up the class-level annotation.
*/
@RequiresFeature(FeatureGate.AI_SUPPORT)
static class ClassLevelAiController {
public String classLevelAiMethod() {
return "ok";
}
}
}
@@ -0,0 +1,228 @@
package stirling.software.saas.payg.entitlement;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.time.LocalDateTime;
import java.util.Optional;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import stirling.software.saas.payg.model.EntitlementState;
import stirling.software.saas.payg.model.FeatureGate;
import stirling.software.saas.payg.model.FeatureSet;
import stirling.software.saas.payg.model.LedgerEntryType;
import stirling.software.saas.payg.policy.PaygTeamExtensions;
import stirling.software.saas.payg.repository.PaygTeamExtensionsRepository;
import stirling.software.saas.payg.repository.WalletLedgerRepository;
import stirling.software.saas.payg.repository.WalletPolicyRepository;
import stirling.software.saas.payg.wallet.WalletPolicy;
/**
* Unit tests for {@link EntitlementService}: cap resolution (wallet policy vs default free-tier),
* spend window computation, cache hit/miss + invalidate, and snapshot shape for FULL / WARNED /
* DEGRADED bands.
*/
class EntitlementServiceTest {
private PaygTeamExtensionsRepository extensionsRepo;
private WalletPolicyRepository walletPolicyRepo;
private WalletLedgerRepository ledgerRepo;
private EntitlementService service;
@BeforeEach
void setUp() {
extensionsRepo = Mockito.mock(PaygTeamExtensionsRepository.class);
walletPolicyRepo = Mockito.mock(WalletPolicyRepository.class);
ledgerRepo = Mockito.mock(WalletLedgerRepository.class);
service = new EntitlementService(extensionsRepo, walletPolicyRepo, ledgerRepo);
}
@Test
void getSnapshot_nullTeamId_throws() {
assertThatThrownBy(() -> service.getSnapshot(null))
.isInstanceOf(NullPointerException.class);
}
@Test
void noWalletPolicy_usesDefaultFreeTierCap() {
when(extensionsRepo.findById(42L)).thenReturn(Optional.empty());
when(walletPolicyRepo.findByTeamId(42L)).thenReturn(Optional.empty());
when(ledgerRepo.sumPeriodAmount(eq(42L), eq(LedgerEntryType.DEBIT), any(), any()))
.thenReturn(-100L); // 100 units spent (signed negative in ledger)
EntitlementSnapshot snap = service.getSnapshot(42L);
assertThat(snap.periodCapUnits()).isEqualTo(EntitlementService.DEFAULT_FREE_TIER_UNITS);
assertThat(snap.periodSpendUnits()).isEqualTo(100L);
// 100/500 = 20% — well below warn → FULL
assertThat(snap.state()).isEqualTo(EntitlementState.FULL);
assertThat(snap.featureSet()).isEqualTo(FeatureSet.FULL);
}
@Test
void walletPolicyPresent_usesCapUnitsFromPolicy() {
WalletPolicy policy = walletPolicyWithCap(2000L, FeatureSet.MINIMAL);
when(extensionsRepo.findById(42L)).thenReturn(Optional.empty());
when(walletPolicyRepo.findByTeamId(42L)).thenReturn(Optional.of(policy));
when(ledgerRepo.sumPeriodAmount(eq(42L), eq(LedgerEntryType.DEBIT), any(), any()))
.thenReturn(-500L);
EntitlementSnapshot snap = service.getSnapshot(42L);
assertThat(snap.periodCapUnits()).isEqualTo(2000L);
assertThat(snap.periodSpendUnits()).isEqualTo(500L);
// 500/2000 = 25% — FULL
assertThat(snap.state()).isEqualTo(EntitlementState.FULL);
}
@Test
void spendAtDegradeThreshold_returnsDegradedWithMinimalGates() {
WalletPolicy policy = walletPolicyWithCap(100L, FeatureSet.MINIMAL);
when(extensionsRepo.findById(42L)).thenReturn(Optional.empty());
when(walletPolicyRepo.findByTeamId(42L)).thenReturn(Optional.of(policy));
when(ledgerRepo.sumPeriodAmount(eq(42L), eq(LedgerEntryType.DEBIT), any(), any()))
.thenReturn(-100L);
EntitlementSnapshot snap = service.getSnapshot(42L);
assertThat(snap.state()).isEqualTo(EntitlementState.DEGRADED);
assertThat(snap.featureSet()).isEqualTo(FeatureSet.MINIMAL);
// MINIMAL now keeps OFFSITE_PROCESSING + CLIENT_SIDE (manual tools); AUTOMATION + AI gone.
assertThat(snap.enabledGates())
.containsExactlyInAnyOrder(FeatureGate.OFFSITE_PROCESSING, FeatureGate.CLIENT_SIDE);
assertThat(snap.enabledGates())
.doesNotContain(FeatureGate.AUTOMATION, FeatureGate.AI_SUPPORT);
}
@Test
void spendInWarnBand_returnsWarnedButFullFeatureSet() {
WalletPolicy policy = walletPolicyWithCap(100L, FeatureSet.MINIMAL);
when(extensionsRepo.findById(42L)).thenReturn(Optional.empty());
when(walletPolicyRepo.findByTeamId(42L)).thenReturn(Optional.of(policy));
when(ledgerRepo.sumPeriodAmount(eq(42L), eq(LedgerEntryType.DEBIT), any(), any()))
.thenReturn(-85L); // 85% — between warn(80) and degrade(100)
EntitlementSnapshot snap = service.getSnapshot(42L);
assertThat(snap.state()).isEqualTo(EntitlementState.WARNED);
assertThat(snap.featureSet()).isEqualTo(FeatureSet.FULL);
assertThat(snap.enabledGates()).hasSize(4);
}
@Test
void positiveSignedSum_treatedAsZeroSpend() {
// Defensive: if the ledger has only credits (positive SUM), spend is zero.
WalletPolicy policy = walletPolicyWithCap(100L, FeatureSet.MINIMAL);
when(extensionsRepo.findById(42L)).thenReturn(Optional.empty());
when(walletPolicyRepo.findByTeamId(42L)).thenReturn(Optional.of(policy));
when(ledgerRepo.sumPeriodAmount(eq(42L), eq(LedgerEntryType.DEBIT), any(), any()))
.thenReturn(50L);
EntitlementSnapshot snap = service.getSnapshot(42L);
assertThat(snap.periodSpendUnits()).isZero();
assertThat(snap.state()).isEqualTo(EntitlementState.FULL);
}
@Test
void cacheHit_secondCallSkipsLedgerLookup() {
when(extensionsRepo.findById(42L)).thenReturn(Optional.empty());
when(walletPolicyRepo.findByTeamId(42L)).thenReturn(Optional.empty());
when(ledgerRepo.sumPeriodAmount(eq(42L), eq(LedgerEntryType.DEBIT), any(), any()))
.thenReturn(0L);
service.getSnapshot(42L);
service.getSnapshot(42L);
service.getSnapshot(42L);
// Only one underlying ledger SUM despite 3 calls — second + third hit the cache.
verify(ledgerRepo, times(1))
.sumPeriodAmount(eq(42L), eq(LedgerEntryType.DEBIT), any(), any());
assertThat(service.cacheSize()).isEqualTo(1);
}
@Test
void invalidate_dropsCacheAndForcesRecompute() {
when(extensionsRepo.findById(42L)).thenReturn(Optional.empty());
when(walletPolicyRepo.findByTeamId(42L)).thenReturn(Optional.empty());
when(ledgerRepo.sumPeriodAmount(eq(42L), eq(LedgerEntryType.DEBIT), any(), any()))
.thenReturn(0L);
service.getSnapshot(42L);
service.invalidate(42L);
service.getSnapshot(42L);
verify(ledgerRepo, times(2))
.sumPeriodAmount(eq(42L), eq(LedgerEntryType.DEBIT), any(), any());
}
@Test
void invalidate_otherTeamLeavesEntryAlone() {
when(extensionsRepo.findById(any())).thenReturn(Optional.empty());
when(walletPolicyRepo.findByTeamId(any())).thenReturn(Optional.empty());
when(ledgerRepo.sumPeriodAmount(any(), eq(LedgerEntryType.DEBIT), any(), any()))
.thenReturn(0L);
service.getSnapshot(42L);
service.invalidate(99L);
service.getSnapshot(42L);
// Only one fetch for team 42 — 99 invalidate didn't touch its entry.
verify(ledgerRepo, times(1))
.sumPeriodAmount(eq(42L), eq(LedgerEntryType.DEBIT), any(), any());
}
@Test
void teamExtensionsPresent_doesNotChangeOutcomeOnPreSubscriptionBranch() {
// Pre-#6532 the team_extensions row carries no subscription field — its presence shouldn't
// change cap resolution.
PaygTeamExtensions ext = new PaygTeamExtensions();
ext.setTeamId(42L);
when(extensionsRepo.findById(42L)).thenReturn(Optional.of(ext));
when(walletPolicyRepo.findByTeamId(42L)).thenReturn(Optional.empty());
when(ledgerRepo.sumPeriodAmount(eq(42L), eq(LedgerEntryType.DEBIT), any(), any()))
.thenReturn(0L);
EntitlementSnapshot snap = service.getSnapshot(42L);
assertThat(snap.periodCapUnits()).isEqualTo(EntitlementService.DEFAULT_FREE_TIER_UNITS);
}
@Test
void currentMonthWindow_isStartOfMonthInclusiveToStartOfNextMonthExclusive() {
LocalDateTime mid = LocalDateTime.of(2026, 6, 15, 14, 30);
LocalDateTime[] w = EntitlementService.currentMonthWindow(mid);
assertThat(w[0]).isEqualTo(LocalDateTime.of(2026, 6, 1, 0, 0));
assertThat(w[1]).isEqualTo(LocalDateTime.of(2026, 7, 1, 0, 0));
}
@Test
void anonymousFull_isFullAndUncapped() {
EntitlementSnapshot snap = EntitlementService.anonymousFull();
assertThat(snap.state()).isEqualTo(EntitlementState.FULL);
assertThat(snap.periodCapUnits()).isNull();
assertThat(snap.enabledGates())
.contains(
FeatureGate.OFFSITE_PROCESSING,
FeatureGate.AUTOMATION,
FeatureGate.AI_SUPPORT,
FeatureGate.CLIENT_SIDE);
}
private static WalletPolicy walletPolicyWithCap(Long capUnits, FeatureSet degradedSet) {
WalletPolicy p = new WalletPolicy();
p.setCapUnits(capUnits);
p.setDegradedFeatureSet(degradedSet);
p.setWarnAtPct(80);
p.setDegradeAtPct(100);
return p;
}
}
@@ -130,7 +130,8 @@ class PaygChargeInterceptorTest {
@Test
void preHandle_openedDisposition_stashesJobIdAndDisposition() throws Exception {
authenticateWithUser(makeUser(7L, 42L));
// API-key auth → BillingCategory.API → billable path engaged.
authenticateWithApiKey(makeUser(7L, 42L));
UUID jobId = UUID.randomUUID();
when(chargeService.openProcess(any(), anyList()))
.thenReturn(new ChargeOutcome(jobId, 4, ChargeOutcome.Disposition.OPENED));
@@ -153,7 +154,8 @@ class PaygChargeInterceptorTest {
@Test
void preHandle_chargeServiceThrows_failsOpenAndIncrementsErrorCounter() throws Exception {
authenticateWithUser(makeUser(7L, 42L));
// API-key auth → API category → reaches openProcess so the throw can be observed.
authenticateWithApiKey(makeUser(7L, 42L));
when(chargeService.openProcess(any(), anyList())).thenThrow(new RuntimeException("boom"));
MockMultipartHttpServletRequest req = newMultipart();
@@ -170,7 +172,7 @@ class PaygChargeInterceptorTest {
@Test
void afterCompletion_2xx_appendsStepAndRecordsOutputs() throws Exception {
authenticateWithUser(makeUser(7L, 42L));
authenticateWithApiKey(makeUser(7L, 42L));
UUID jobId = UUID.randomUUID();
when(chargeService.openProcess(any(), anyList()))
.thenReturn(new ChargeOutcome(jobId, 1, ChargeOutcome.Disposition.OPENED));
@@ -207,7 +209,7 @@ class PaygChargeInterceptorTest {
@Test
void afterCompletion_5xx_opened_callsMarkFirstStepFailed() throws Exception {
authenticateWithUser(makeUser(7L, 42L));
authenticateWithApiKey(makeUser(7L, 42L));
UUID jobId = UUID.randomUUID();
when(chargeService.openProcess(any(), anyList()))
.thenReturn(new ChargeOutcome(jobId, 1, ChargeOutcome.Disposition.OPENED));
@@ -230,7 +232,7 @@ class PaygChargeInterceptorTest {
@Test
void afterCompletion_5xx_joined_callsDecrementStepCount() throws Exception {
authenticateWithUser(makeUser(7L, 42L));
authenticateWithApiKey(makeUser(7L, 42L));
UUID jobId = UUID.randomUUID();
when(chargeService.openProcess(any(), anyList()))
.thenReturn(new ChargeOutcome(jobId, 0, ChargeOutcome.Disposition.JOINED));
@@ -249,7 +251,7 @@ class PaygChargeInterceptorTest {
@Test
void afterCompletion_4xx_appendsFailedStepNoRefundNoOutputs() throws Exception {
authenticateWithUser(makeUser(7L, 42L));
authenticateWithApiKey(makeUser(7L, 42L));
UUID jobId = UUID.randomUUID();
when(chargeService.openProcess(any(), anyList()))
.thenReturn(new ChargeOutcome(jobId, 1, ChargeOutcome.Disposition.OPENED));
@@ -293,7 +295,7 @@ class PaygChargeInterceptorTest {
@Test
void afterCompletion_maxBytesExceeded_skipsOutputRecording() throws Exception {
properties.getResponse().setMaxBytes(2L);
authenticateWithUser(makeUser(7L, 42L));
authenticateWithApiKey(makeUser(7L, 42L));
UUID jobId = UUID.randomUUID();
when(chargeService.openProcess(any(), anyList()))
.thenReturn(new ChargeOutcome(jobId, 1, ChargeOutcome.Disposition.OPENED));
@@ -317,7 +319,7 @@ class PaygChargeInterceptorTest {
@Test
void preHandle_pipelineHeader_setsJobSourcePipeline() throws Exception {
authenticateWithUser(makeUser(7L, 42L));
authenticateWithApiKey(makeUser(7L, 42L));
UUID jobId = UUID.randomUUID();
when(chargeService.openProcess(any(), anyList()))
.thenReturn(new ChargeOutcome(jobId, 1, ChargeOutcome.Disposition.OPENED));
@@ -336,6 +338,184 @@ class PaygChargeInterceptorTest {
.isEqualTo(stirling.software.saas.payg.model.JobSource.PIPELINE);
}
// --- BillingCategory categorisation + bypass fast-path -------------------------------------
@Test
void preHandle_manualToolJwt_isBypassedAndSkipsOpenProcess() throws Exception {
// JWT-authenticated, plain @AutoJobPostMapping endpoint, no automation header → BYPASSED.
// The interceptor must skip openProcess entirely (no temp files, no DB writes) and bump
// the payg.filter.bypassed counter.
authenticateWithUser(makeUser(7L, 42L));
MockMultipartHttpServletRequest req = newMultipart();
req.addFile(new MockMultipartFile("file", "x.pdf", "application/pdf", "abc".getBytes()));
boolean cont =
interceptor.preHandle(
req, new MockHttpServletResponse(), handlerMethodForFakeController());
assertThat(cont).isTrue();
verify(chargeService, never()).openProcess(any(), anyList());
assertThat(req.getAttribute(PaygChargeInterceptor.ATTR_JOB_ID)).isNull();
assertThat(req.getAttribute(PaygChargeInterceptor.ATTR_INPUT_TEMP_FILES)).isNull();
assertThat(meterRegistry.counter("payg.filter.bypassed").count()).isEqualTo(1.0);
}
@Test
void preHandle_apiKeyAuth_setsBillingCategoryApi() throws Exception {
authenticateWithApiKey(makeUser(7L, 42L));
UUID jobId = UUID.randomUUID();
when(chargeService.openProcess(any(), anyList()))
.thenReturn(new ChargeOutcome(jobId, 1, ChargeOutcome.Disposition.OPENED));
org.mockito.ArgumentCaptor<stirling.software.saas.payg.charge.ChargeContext> ctxCaptor =
org.mockito.ArgumentCaptor.forClass(
stirling.software.saas.payg.charge.ChargeContext.class);
MockMultipartHttpServletRequest req = newMultipart();
req.addFile(new MockMultipartFile("file", "x.pdf", "application/pdf", "abc".getBytes()));
interceptor.preHandle(req, new MockHttpServletResponse(), handlerMethodForFakeController());
verify(chargeService).openProcess(ctxCaptor.capture(), anyList());
assertThat(ctxCaptor.getValue().billingCategory())
.isEqualTo(stirling.software.saas.payg.model.BillingCategory.API);
}
@Test
void preHandle_requiresFeatureAutomation_setsBillingCategoryAutomation() throws Exception {
// JWT auth on a @RequiresFeature(AUTOMATION) endpoint → AUTOMATION category.
authenticateWithUser(makeUser(7L, 42L));
UUID jobId = UUID.randomUUID();
when(chargeService.openProcess(any(), anyList()))
.thenReturn(new ChargeOutcome(jobId, 1, ChargeOutcome.Disposition.OPENED));
org.mockito.ArgumentCaptor<stirling.software.saas.payg.charge.ChargeContext> ctxCaptor =
org.mockito.ArgumentCaptor.forClass(
stirling.software.saas.payg.charge.ChargeContext.class);
MockMultipartHttpServletRequest req = newMultipart();
req.addFile(new MockMultipartFile("file", "x.pdf", "application/pdf", "abc".getBytes()));
interceptor.preHandle(req, new MockHttpServletResponse(), handlerMethodForAutomation());
verify(chargeService).openProcess(ctxCaptor.capture(), anyList());
assertThat(ctxCaptor.getValue().billingCategory())
.isEqualTo(stirling.software.saas.payg.model.BillingCategory.AUTOMATION);
}
@Test
void preHandle_requiresFeatureAiSupport_setsBillingCategoryAi() throws Exception {
// JWT auth on a @RequiresFeature(AI_SUPPORT) endpoint → AI category.
authenticateWithUser(makeUser(7L, 42L));
UUID jobId = UUID.randomUUID();
when(chargeService.openProcess(any(), anyList()))
.thenReturn(new ChargeOutcome(jobId, 1, ChargeOutcome.Disposition.OPENED));
org.mockito.ArgumentCaptor<stirling.software.saas.payg.charge.ChargeContext> ctxCaptor =
org.mockito.ArgumentCaptor.forClass(
stirling.software.saas.payg.charge.ChargeContext.class);
MockMultipartHttpServletRequest req = newMultipart();
req.addFile(new MockMultipartFile("file", "x.pdf", "application/pdf", "abc".getBytes()));
interceptor.preHandle(req, new MockHttpServletResponse(), handlerMethodForAi());
verify(chargeService).openProcess(ctxCaptor.capture(), anyList());
assertThat(ctxCaptor.getValue().billingCategory())
.isEqualTo(stirling.software.saas.payg.model.BillingCategory.AI);
}
@Test
void preHandle_requiresFeatureWithoutAutoJobPostMapping_reachesCategoryGate() throws Exception {
// Regression: AI controllers carry @RequiresFeature but NO @AutoJobPostMapping. They must
// still flow past the short-circuit gate so determineCategory runs (and so future
// multipart-bearing @RequiresFeature routes bill correctly). API-key auth +
// @RequiresFeature
// — even without multipart inputs — should land in the BillingCategory.API branch via
// determineCategory's auth check, then short-circuit inside doPreHandle because there are
// no multipart parts.
authenticateWithApiKey(makeUser(7L, 42L));
MockMultipartHttpServletRequest req = newMultipart();
// No file parts — emulates a JSON-bodied AI controller request that happens to be wrapped
// as multipart. doPreHandle short-circuits with no openProcess call.
req.addFile(new MockMultipartFile("file", "x.pdf", "application/pdf", new byte[0]));
boolean cont =
interceptor.preHandle(
req, new MockHttpServletResponse(), handlerMethodForAiNoAutoJob());
assertThat(cont).isTrue();
verify(chargeService, never()).openProcess(any(), anyList());
// Importantly: not counted as BYPASSED — the AI category was determined correctly.
assertThat(meterRegistry.counter("payg.filter.bypassed").count()).isEqualTo(0.0);
}
@Test
void preHandle_aiEndpointWithoutAutoJobPostMapping_categoryIsAi() throws Exception {
// With multipart parts present + @RequiresFeature(AI_SUPPORT) but no @AutoJobPostMapping:
// the interceptor must run determineCategory and tag the ChargeContext as AI.
authenticateWithApiKey(makeUser(7L, 42L));
UUID jobId = UUID.randomUUID();
when(chargeService.openProcess(any(), anyList()))
.thenReturn(new ChargeOutcome(jobId, 1, ChargeOutcome.Disposition.OPENED));
org.mockito.ArgumentCaptor<stirling.software.saas.payg.charge.ChargeContext> ctxCaptor =
org.mockito.ArgumentCaptor.forClass(
stirling.software.saas.payg.charge.ChargeContext.class);
MockMultipartHttpServletRequest req = newMultipart();
req.addFile(new MockMultipartFile("file", "x.pdf", "application/pdf", "abc".getBytes()));
interceptor.preHandle(req, new MockHttpServletResponse(), handlerMethodForAiNoAutoJob());
verify(chargeService).openProcess(ctxCaptor.capture(), anyList());
assertThat(ctxCaptor.getValue().billingCategory())
.isEqualTo(stirling.software.saas.payg.model.BillingCategory.AI);
}
@Test
void preHandle_classLevelRequiresFeatureOnly_isInScope() throws Exception {
// Mirrors AiCreateController shape: @RequiresFeature on the @RestController class.
// The interceptor must resolve it via beanType lookup and not short-circuit as
// "no annotation".
authenticateWithApiKey(makeUser(7L, 42L));
UUID jobId = UUID.randomUUID();
when(chargeService.openProcess(any(), anyList()))
.thenReturn(new ChargeOutcome(jobId, 1, ChargeOutcome.Disposition.OPENED));
org.mockito.ArgumentCaptor<stirling.software.saas.payg.charge.ChargeContext> ctxCaptor =
org.mockito.ArgumentCaptor.forClass(
stirling.software.saas.payg.charge.ChargeContext.class);
MockMultipartHttpServletRequest req = newMultipart();
req.addFile(new MockMultipartFile("file", "x.pdf", "application/pdf", "abc".getBytes()));
interceptor.preHandle(req, new MockHttpServletResponse(), handlerMethodForClassLevelAi());
verify(chargeService).openProcess(ctxCaptor.capture(), anyList());
assertThat(ctxCaptor.getValue().billingCategory())
.isEqualTo(stirling.software.saas.payg.model.BillingCategory.AI);
}
@Test
void preHandle_aiEndpointWithAutomationHeader_automationWinsByPrecedence() throws Exception {
// X-Stirling-Automation: true on an @RequiresFeature(AI_SUPPORT) endpoint → AUTOMATION
// (header beats annotation by design — pipeline-driven AI counts as automation usage).
authenticateWithUser(makeUser(7L, 42L));
UUID jobId = UUID.randomUUID();
when(chargeService.openProcess(any(), anyList()))
.thenReturn(new ChargeOutcome(jobId, 1, ChargeOutcome.Disposition.OPENED));
org.mockito.ArgumentCaptor<stirling.software.saas.payg.charge.ChargeContext> ctxCaptor =
org.mockito.ArgumentCaptor.forClass(
stirling.software.saas.payg.charge.ChargeContext.class);
MockMultipartHttpServletRequest req = newMultipart();
req.addFile(new MockMultipartFile("file", "x.pdf", "application/pdf", "abc".getBytes()));
req.addHeader("X-Stirling-Automation", "true");
interceptor.preHandle(req, new MockHttpServletResponse(), handlerMethodForAi());
verify(chargeService).openProcess(ctxCaptor.capture(), anyList());
assertThat(ctxCaptor.getValue().billingCategory())
.isEqualTo(stirling.software.saas.payg.model.BillingCategory.AUTOMATION);
}
// --- helpers --------------------------------------------------------------------------------
private MockMultipartHttpServletRequest newMultipart() {
@@ -396,11 +576,78 @@ class PaygChargeInterceptorTest {
}
}
private static HandlerMethod handlerMethodForAutomation() {
try {
Method m = FakeController.class.getDeclaredMethod("handleAutomation");
return new HandlerMethod(new FakeController(), m);
} catch (NoSuchMethodException e) {
throw new RuntimeException(e);
}
}
private static HandlerMethod handlerMethodForAi() {
try {
Method m = FakeController.class.getDeclaredMethod("handleAi");
return new HandlerMethod(new FakeController(), m);
} catch (NoSuchMethodException e) {
throw new RuntimeException(e);
}
}
private static HandlerMethod handlerMethodForAiNoAutoJob() {
try {
Method m = FakeController.class.getDeclaredMethod("handleAiNoAutoJob");
return new HandlerMethod(new FakeController(), m);
} catch (NoSuchMethodException e) {
throw new RuntimeException(e);
}
}
private static HandlerMethod handlerMethodForClassLevelAi() {
try {
Method m = ClassLevelAiController.class.getDeclaredMethod("classLevelAi");
return new HandlerMethod(new ClassLevelAiController(), m);
} catch (NoSuchMethodException e) {
throw new RuntimeException(e);
}
}
private void authenticateWithApiKey(User user) {
stirling.software.proprietary.security.model.ApiKeyAuthenticationToken token =
new stirling.software.proprietary.security.model.ApiKeyAuthenticationToken(
user, "test-api-key", List.of(new SimpleGrantedAuthority("ROLE_API")));
SecurityContextHolder.getContext().setAuthentication(token);
}
static class FakeController {
@AutoJobPostMapping(value = "/x", resourceWeight = 1)
public void handleAuto() {}
public void handlePlain() {}
@AutoJobPostMapping(value = "/auto", resourceWeight = 1)
@stirling.software.saas.payg.cap.RequiresFeature(
stirling.software.saas.payg.model.FeatureGate.AUTOMATION)
public void handleAutomation() {}
@AutoJobPostMapping(value = "/ai", resourceWeight = 1)
@stirling.software.saas.payg.cap.RequiresFeature(
stirling.software.saas.payg.model.FeatureGate.AI_SUPPORT)
public void handleAi() {}
/**
* AI-controller shape: @RequiresFeature without @AutoJobPostMapping (JSON body / proxy).
*/
@stirling.software.saas.payg.cap.RequiresFeature(
stirling.software.saas.payg.model.FeatureGate.AI_SUPPORT)
public void handleAiNoAutoJob() {}
}
/** Mirrors AiCreateController layout: @RequiresFeature on the class, plain methods. */
@stirling.software.saas.payg.cap.RequiresFeature(
stirling.software.saas.payg.model.FeatureGate.AI_SUPPORT)
static class ClassLevelAiController {
public void classLevelAi() {}
}
/** Placeholder so AutoCloseable resources flow in some helper methods. */
@@ -0,0 +1,196 @@
package stirling.software.saas.payg.meter;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatCode;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.net.ConnectException;
import java.util.Map;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.ResourceAccessException;
import org.springframework.web.client.RestTemplate;
import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.simple.SimpleMeterRegistry;
import stirling.software.saas.payg.model.BillingCategory;
/**
* Covers the contract documented on {@link PaygMeterReportingService#recordUsage}: never throws,
* skips when endpoint is blank, counts non-2xx and exceptions on {@code payg.meter.errors}.
*/
class PaygMeterReportingServiceTest {
private static final String ENDPOINT =
"https://example.supabase.co/functions/v1/meter-payg-units";
private static final String TOKEN = "test-service-role-token";
private RestTemplate restTemplate;
private MeterRegistry meterRegistry;
private Counter errorsCounter;
@BeforeEach
void setUp() {
restTemplate = Mockito.mock(RestTemplate.class);
meterRegistry = new SimpleMeterRegistry();
errorsCounter = meterRegistry.counter("payg.meter.errors");
}
private PaygMeterReportingService newService(String endpoint, String token) {
return new PaygMeterReportingService(endpoint, token, restTemplate, meterRegistry);
}
@Test
void recordUsage_happyPath_postsBodyAndDoesNotIncrementErrorCounter() {
when(restTemplate.exchange(eq(ENDPOINT), eq(HttpMethod.POST), any(), eq(String.class)))
.thenReturn(new ResponseEntity<>("{\"ok\":true}", HttpStatus.OK));
PaygMeterReportingService service = newService(ENDPOINT, TOKEN);
service.recordUsage(100L, "cus_abc", 5, BillingCategory.API, "process:job1:close");
@SuppressWarnings("unchecked")
ArgumentCaptor<HttpEntity<Map<String, Object>>> entityCaptor =
ArgumentCaptor.forClass(HttpEntity.class);
verify(restTemplate)
.exchange(
eq(ENDPOINT),
eq(HttpMethod.POST),
entityCaptor.capture(),
eq(String.class));
HttpEntity<Map<String, Object>> sent = entityCaptor.getValue();
Map<String, Object> body = sent.getBody();
assertThat(body).isNotNull();
assertThat(body.get("team_id")).isEqualTo("100");
assertThat(body.get("stripe_customer_id")).isEqualTo("cus_abc");
assertThat(body.get("units")).isEqualTo(5);
assertThat(body.get("idempotency_key")).isEqualTo("process:job1:close");
assertThat(body.get("metadata")).isEqualTo(Map.of("category", "API"));
HttpHeaders headers = sent.getHeaders();
assertThat(headers.getFirst("Authorization")).isEqualTo("Bearer " + TOKEN);
assertThat(headers.getContentType()).isNotNull();
assertThat(headers.getContentType().toString()).startsWith("application/json");
assertThat(errorsCounter.count()).isZero();
}
@Test
void recordUsage_5xxResponse_incrementsErrorCounterAndDoesNotThrow() {
when(restTemplate.exchange(eq(ENDPOINT), eq(HttpMethod.POST), any(), eq(String.class)))
.thenReturn(new ResponseEntity<>("oops", HttpStatus.INTERNAL_SERVER_ERROR));
PaygMeterReportingService service = newService(ENDPOINT, TOKEN);
assertThatCode(
() ->
service.recordUsage(
100L,
"cus_abc",
3,
BillingCategory.AUTOMATION,
"process:job2:close"))
.doesNotThrowAnyException();
assertThat(errorsCounter.count()).isEqualTo(1.0);
}
@Test
void recordUsage_connectionRefused_incrementsErrorCounterAndDoesNotThrow() {
when(restTemplate.exchange(eq(ENDPOINT), eq(HttpMethod.POST), any(), eq(String.class)))
.thenThrow(new ResourceAccessException("connect refused", new ConnectException()));
PaygMeterReportingService service = newService(ENDPOINT, TOKEN);
assertThatCode(
() ->
service.recordUsage(
100L,
"cus_abc",
7,
BillingCategory.AI,
"process:job3:close"))
.doesNotThrowAnyException();
assertThat(errorsCounter.count()).isEqualTo(1.0);
}
@Test
void recordUsage_runtimeException_swallowed() {
when(restTemplate.exchange(eq(ENDPOINT), eq(HttpMethod.POST), any(), eq(String.class)))
.thenThrow(new RuntimeException("boom"));
PaygMeterReportingService service = newService(ENDPOINT, TOKEN);
assertThatCode(
() ->
service.recordUsage(
100L,
"cus_abc",
7,
BillingCategory.AI,
"process:job4:close"))
.doesNotThrowAnyException();
assertThat(errorsCounter.count()).isEqualTo(1.0);
}
@Test
void recordUsage_blankEndpoint_noopsAndDoesNotCallRestTemplate() {
PaygMeterReportingService service = newService("", TOKEN);
service.recordUsage(100L, "cus_abc", 5, BillingCategory.API, "process:job5:close");
verify(restTemplate, never()).exchange(any(String.class), any(), any(), any(Class.class));
assertThat(errorsCounter.count()).isZero();
}
@Test
void recordUsage_nullEndpoint_noopsAndDoesNotCallRestTemplate() {
PaygMeterReportingService service = newService(null, TOKEN);
service.recordUsage(100L, "cus_abc", 5, BillingCategory.API, "process:job6:close");
verify(restTemplate, never()).exchange(any(String.class), any(), any(), any(Class.class));
assertThat(errorsCounter.count()).isZero();
}
@Test
void recordUsage_zeroUnits_noopsAndDoesNotCallRestTemplate() {
PaygMeterReportingService service = newService(ENDPOINT, TOKEN);
service.recordUsage(100L, "cus_abc", 0, BillingCategory.API, "process:job7:close");
verify(restTemplate, never()).exchange(any(String.class), any(), any(), any(Class.class));
assertThat(errorsCounter.count()).isZero();
}
@Test
void recordUsage_blankServiceRoleToken_postsWithoutAuthorizationHeader() {
when(restTemplate.exchange(eq(ENDPOINT), eq(HttpMethod.POST), any(), eq(String.class)))
.thenReturn(new ResponseEntity<>("{}", HttpStatus.OK));
PaygMeterReportingService service = newService(ENDPOINT, "");
service.recordUsage(100L, "cus_abc", 5, BillingCategory.API, "process:job8:close");
@SuppressWarnings("unchecked")
ArgumentCaptor<HttpEntity<Map<String, Object>>> entityCaptor =
ArgumentCaptor.forClass(HttpEntity.class);
verify(restTemplate, times(1))
.exchange(
eq(ENDPOINT),
eq(HttpMethod.POST),
entityCaptor.capture(),
eq(String.class));
assertThat(entityCaptor.getValue().getHeaders().getFirst("Authorization")).isNull();
}
}
@@ -107,6 +107,16 @@ class PaygEntitiesSmokeTest {
assertThat(entry.getAmountUnits()).isEqualTo(-4);
}
@Test
void walletLedgerEntry_billingCategoryRoundTrips() {
WalletLedgerEntry entry = new WalletLedgerEntry();
// Default (unset) is null — captured by both the legacy debit path and pre-V16 rows.
assertThat(entry.getBillingCategory()).isNull();
entry.setBillingCategory(BillingCategory.AUTOMATION);
assertThat(entry.getBillingCategory()).isEqualTo(BillingCategory.AUTOMATION);
}
@Test
void walletPolicy_carriesSensibleDefaults() {
WalletPolicy policy = new WalletPolicy();
@@ -148,4 +158,29 @@ class PaygEntitiesSmokeTest {
assertThat(row.getDiffPct()).isNegative();
}
@Test
void paygShadowCharge_billingCategoryAndJobSourceRoundTrip() {
PaygShadowCharge row = new PaygShadowCharge();
assertThat(row.getBillingCategory()).isNull();
assertThat(row.getJobSource()).isNull();
row.setBillingCategory(BillingCategory.AI);
row.setJobSource(JobSource.API);
assertThat(row.getBillingCategory()).isEqualTo(BillingCategory.AI);
assertThat(row.getJobSource()).isEqualTo(JobSource.API);
}
@Test
void billingCategory_listingOrderIsStable() {
// No downstream relies on ordinal() today, but the comment in the enum claims BYPASSED is
// declared first as the default sentinel — guard against an accidental reorder.
assertThat(BillingCategory.values())
.containsExactly(
BillingCategory.BYPASSED,
BillingCategory.API,
BillingCategory.AI,
BillingCategory.AUTOMATION);
}
}
@@ -12,7 +12,6 @@ cancel = "Cancel"
changedCredsMessage = "Credentials changed!"
chooseFile = "Choose File"
close = "Close"
color = "Colour"
comingSoon = "Coming soon"
confirm = "Confirm"
confirmClose = "Confirm Close"
@@ -199,6 +198,10 @@ ssoDescription = "Two-factor authentication is managed by your identity provider
ssoManaged = "Configure MFA through your identity provider."
title = "Two-factor authentication"
[account.overview]
logOut = "Log out"
signedInAs = "Signed in as: {{email}}"
[add-page-numbers]
tags = "paginate,label,organize,index"
@@ -226,6 +229,9 @@ title = "What it does"
[AddAttachmentsRequest.tooltip.header]
title = "About Add Attachments"
[addFileCard]
upload = "Upload"
[addImage]
applySignatures = "Apply Images"
header = "Add images to PDFs"
@@ -606,6 +612,7 @@ label = "Temp File Management"
[admin.settings.advanced.tempFileManagement.baseTmpDir]
description = "Base directory for temporary files (leave empty for default: java.io.tmpdir/stirling-pdf)"
label = "Base Temp Directory"
placeholder = "Default: java.io.tmpdir/stirling-pdf"
[admin.settings.advanced.tempFileManagement.cleanupIntervalMinutes]
description = "How often to run cleanup (in minutes)"
@@ -618,6 +625,7 @@ label = "Cleanup System Temp"
[admin.settings.advanced.tempFileManagement.libreofficeDir]
description = "Directory for LibreOffice temp files (leave empty for default: baseTmpDir/libreoffice)"
label = "LibreOffice Temp Directory"
placeholder = "Default: baseTmpDir/libreoffice"
[admin.settings.advanced.tempFileManagement.maxAgeHours]
description = "Maximum age in hours before temp files are cleaned up"
@@ -634,6 +642,7 @@ label = "Startup Cleanup"
[admin.settings.advanced.tempFileManagement.systemTempDir]
description = "System temp directory to clean (only used if cleanupSystemTemp is enabled)"
label = "System Temp Directory"
placeholder = "System temp directory path"
[admin.settings.advanced.tessdataDir]
description = "Path to the tessdata directory for OCR language files"
@@ -839,6 +848,7 @@ label = "Database Name"
[admin.settings.database.password]
description = "Database authentication password"
label = "Password"
placeholder = "Enter database password"
[admin.settings.database.port]
description = "Database server port (not used if custom URL is provided)"
@@ -870,10 +880,12 @@ label = "Hide unavailable tools by default"
[admin.settings.endpoints.groupsToRemove]
description = "Select endpoint groups to disable"
label = "Disabled Endpoint Groups"
placeholder = "Select groups to disable"
[admin.settings.endpoints.toRemove]
description = "Select individual endpoints to disable"
label = "Disabled Endpoints"
placeholder = "Select endpoints to disable"
[admin.settings.enterpriseRequired]
message = "An Enterprise license is required to access {{featureName}}. You are viewing demo data for reference."
@@ -1088,6 +1100,7 @@ label = "SMTP Host"
[admin.settings.mail.password]
description = "Password for SMTP authentication"
label = "SMTP Password"
placeholder = "Enter SMTP password"
[admin.settings.mail.port]
description = "The port number for SMTP connection (typically 25, 465, or 587)"
@@ -1097,6 +1110,10 @@ label = "SMTP Port"
description = "Username for SMTP authentication"
label = "SMTP Username"
[admin.settings.plan.noData]
message = "Plans data is not available at the moment."
title = "No data available"
[admin.settings.premium]
description = "Configure your premium or enterprise license key."
license = "License Configuration"
@@ -1143,6 +1160,9 @@ info = "If you have a license key or certificate file from a direct purchase, yo
toggle = "Got a license key or certificate file?"
[admin.settings.premium.movedFeatures]
auditLogging = "<0>Audit Logging</0> (ENTERPRISE) - Security"
customMetadata = "<0>Custom Metadata</0> (PRO) - General"
databaseConfiguration = "<0>Database Configuration</0> (ENTERPRISE) - Database"
message = "Premium and Enterprise features are now organized in their respective sections:"
title = "Premium Features Distributed"
@@ -1526,10 +1546,10 @@ section_title = "Agents"
show_less = "Show less"
start_chat = "Start chatting"
stirling_description = "Your general-purpose PDF assistant"
stirling_running = "Running..."
stirling_full_name = "Stirling General Agent"
stirling_long_description = "General purpose PDF assistant that can run tools, create PDFs and extract insights from your documents."
stirling_name = "Stirling"
stirling_running = "Running..."
stirling_tooltip = "Stirling agent"
view_all = "View all agents"
@@ -2126,11 +2146,31 @@ placeholder = "Number of pages"
title = "Last N Pages"
[bulkSelection.operators]
text = "AND has higher precedence than comma. NOT applies within the document range."
title = "Operators"
[bulkSelection.operators.and]
title = "Combine selections (both conditions must be true)"
[bulkSelection.operators.descriptions]
and = "AND: & or \"and\" - require both conditions (e.g., 1-50 & even)"
comma = "Comma: , or | - combine selections (e.g., 1-10, 20)"
not = "NOT: ! or \"not\" - exclude pages (e.g., 3n & not 30)"
text = "AND has higher precedence than comma. NOT applies within the document range."
title = "Operators"
[bulkSelection.operators.even]
title = "Select all even-numbered pages (2, 4, 6, 8...)"
[bulkSelection.operators.not]
title = "Exclude from selection"
[bulkSelection.operators.odd]
title = "Select all odd-numbered pages (1, 3, 5, 7...)"
[bulkSelection.operators.or]
title = "Add to selection (either condition can be true)"
[bulkSelection.pageSelection]
title = "Page Selection"
[bulkSelection.range]
fromPlaceholder = "From"
@@ -2782,6 +2822,9 @@ unknownTool = "Unknown tool"
[cloudBadge]
tooltip = "This operation will use your cloud credits"
[color.eyeDropper]
tooltip = "Pick colour from screen"
[colorPicker]
title = "Choose colour"
@@ -3006,6 +3049,10 @@ title = "Compression Method"
1 = "1-3 PDF compression,</br> 4-6 lite image compression,</br> 7-9 intense image compression Will dramatically reduce image quality"
_value = "Compression Settings"
[compress.settings]
desiredSize = "Desired File Size"
desiredSizePlaceholder = "Enter size"
[compress.tooltip.description]
text = "Compression is an easy way to reduce your file size. Pick File Size to enter a target size and have us adjust quality for you. Pick Quality to set compression strength manually."
title = "Description"
@@ -3496,6 +3543,13 @@ docsLink = "View installation documentation"
message = "Stirling-PDF does not have permission to update itself on this machine."
title = "Administrator permissions required"
[dropdownList]
searchPlaceholder = "Search..."
[editableSecretField]
edit = "Edit"
editSecretValue = "Edit secret value"
[editTableOfContents]
submit = "Apply table of contents"
@@ -3583,6 +3637,9 @@ tabTitle = "Outline workspace"
description = "Select the Edit Table of Contents tool to load its workspace."
title = "Open the tool to start editing"
[emptyFilesState]
upload = "Upload"
[encryptedPdfUnlock]
description = "This PDF is password protected. Enter the password so you can continue working with it."
emptyResponse = "Password removal did not produce a file."
@@ -3697,6 +3754,10 @@ title = "Settings"
[extractPages.tooltip]
description = "Extracts the selected pages into a new PDF, preserving order."
[fileCard]
openInFileEditor = "Open in File Editor"
viewInViewer = "View in Viewer"
[fileChooser]
click = "Click"
dragAndDrop = "Drag & Drop"
@@ -3706,6 +3767,9 @@ extractPDF = "Extracting..."
hoveredDragAndDrop = "Drag & Drop file(s) here"
or = "or"
[fileDropdownMenu]
closeFile = "Close file"
[fileEditor]
addFiles = "Add Files"
pageCount = "{{count}} pages"
@@ -3872,6 +3936,10 @@ openSettings = "Open settings"
search = "Search"
searchPlaceholder = "Search files..."
[fileSidebar.fileItem]
closeViewer = "Close viewer"
openInViewer = "Open in viewer"
[filesPage]
addToWorkspace = "Add to workspace"
addToWorkspaceCount = "Add {{count}} to workspace"
@@ -4178,6 +4246,15 @@ title = "About Flattening PDFs"
discord = "Discord"
issues = "GitHub"
[formFill]
flattenAfterFilling = "Flatten after filling"
rescanFields = "Re-scan fields"
rescanFormFields = "Re-scan form fields"
save = "Save"
[formFill.sidebar]
close = "Close sidebar"
[getPdfInfo]
downloadJson = "Download JSON"
downloads = "Downloads"
@@ -4737,6 +4814,11 @@ tags = "markup,web-content,transformation,convert"
title = "HTML To PDF"
zoom = "Zoom level for displaying the website."
[image.upload]
hint = "Upload a PNG, JPG, SVG, or other image file to place on the PDF. SVG files will be converted to PNG for compatibility."
label = "Upload Image"
placeholder = "Select image file"
[imageToPdf]
tags = "conversion,img,jpg,picture,photo"
@@ -4755,6 +4837,9 @@ title = "Image to PDF"
4 = "Merge into single PDF"
5 = "Convert to separate PDFs"
[infoBanner]
dismiss = "Dismiss"
[invite]
acceptError = "Failed to create account"
accountFor = "Creating account for"
@@ -5090,6 +5175,7 @@ failed = "OCR operation failed"
[ocr.languagePicker]
additionalLanguages = "Looking for additional languages?"
loading = "Loading available languages..."
viewSetupGuide = "View setup guide →"
[ocr.operation]
@@ -5226,6 +5312,10 @@ daysRemainingSingular = "{{days}} day remaining"
title = "Your 30-Day Pro Trial"
trialEnds = "Trial ends {{date}}"
[onboarding.mfa]
authenticationCode = "Authentication code"
qrCodeLoading = "Generating your QR code…"
[onboarding.planOverview]
adminBodyLoginDisabled = "Once you enable login mode, you can manage users, configure settings, and monitor server health. The first <strong>{{freeTierLimit}}</strong> people on your server get to use Stirling free of charge."
adminBodyLoginEnabled = "As an admin, you can manage users, configure settings, and monitor server health. The first <strong>{{freeTierLimit}}</strong> people on your server get to use Stirling free of charge."
@@ -5235,6 +5325,9 @@ userTitle = "Plan Overview"
[onboarding.securityCheck]
message = "The application has undergone significant changes recently. Your server admin's attention may be required. Please confirm your role to continue."
roleAdmin = "Admin"
rolePlaceholder = "Confirm your role"
roleUser = "User"
[onboarding.serverLicense]
freeBody = "Our <strong>Open-Core</strong> licensing permits up to <strong>{{freeTierLimit}}</strong> users for free per server. To scale uninterrupted, we recommend the Stirling Server plan - <strong>unlimited seats</strong> and <strong>SSO support</strong> for $99/server/mo."
@@ -5360,6 +5453,17 @@ title = "Page Editor"
zoomIn = "Zoom In"
zoomOut = "Zoom Out"
[pageEditor.emptyState]
body = "Add files to start editing pages"
title = "No PDF files loaded"
[pageEditor.toolbar]
delete = "Delete Selected"
redo = "Redo"
rotateLeft = "Rotate Selected Left"
rotateRight = "Rotate Selected Right"
undo = "Undo"
[pageExtracter]
header = "Extract Pages"
placeholder = "(e.g. 1,2,8 or 4,7,12-16 or 2n-1)"
@@ -5371,12 +5475,14 @@ addBorder = "Add Borders"
borderWidth = "Border Thickness"
bottom = "Bottom Margin"
cols = "Columns"
colsPlaceholder = "Enter columns"
header = "Multi Page Layout"
innerMargin = "Inner Margin"
left = "Left Margin"
pagesPerSheet = "Pages per sheet:"
right = "Right Margin"
rows = "Rows"
rowsPlaceholder = "Enter rows"
submit = "Submit"
tags = "merge,composite,single-view,organize"
title = "Multi Page Layout"
@@ -5418,6 +5524,14 @@ innerMarginTooLarge = "Inner margin is too large for the selected layout."
outerHorizontalMarginsTooLarge = "Left/Right margins are too large for this page size."
outerVerticalMarginsTooLarge = "Top/Bottom margins are too large for this page size."
[pageLayout.margins]
borderThicknessPlaceholder = "Enter border thickness"
bottomPlaceholder = "Enter bottom margin"
innerPlaceholder = "Enter inner margin"
leftPlaceholder = "Enter left margin"
rightPlaceholder = "Enter right margin"
topPlaceholder = "Enter top margin"
[pageLayout.marginsBorders.tooltip.borders]
text = "Enable borders to draw lines around each placed page. This can help visual separation or trimming."
title = "Add Borders"
@@ -6071,6 +6185,26 @@ pdfTools = "Basic PDF Tools"
priority = "Priority Support"
title = "Feature"
[plan.features]
allPdfOperations = "All PDF operations"
auditing = "Auditing"
communitySupport = "Community support"
customPdfMetadata = "Custom PDF metadata"
editingTextInPdfs = "Editing text in pdfs"
externalDatabase = "External Database"
googleDriveIntegration = "Google drive integration"
prometheusSupport = "Prometheus Support"
regularUpdates = "Regular updates"
saml = "SAML"
secureLoginSupport = "Secure Login Support"
selfHostedDeployment = "Self-hosted deployment"
sso = "SSO"
unlimitedUsers = "Unlimited users"
upToFiveUsers = "Up to 5 users"
upToFiveUsersLowercase = "up to 5 users"
usageTracking = "Usage tracking"
usersLimitedToSeats = "Users limited to seats"
[plan.free]
forever = "Forever free"
highlight1 = "Limited Tool Usage Per week"
@@ -6079,6 +6213,22 @@ highlight3 = "Community support"
included = "Included"
name = "Free"
[plan.highlights]
advancedIntegrations = "Advanced integrations"
allBasicFeatures = "All basic features"
cancelAnytime = "Cancel anytime"
customPdfMetadata = "Custom PDF metadata"
editingTextInPdfsCaps = "Editing text in PDFs"
enterpriseFeatures = "Enterprise features (SAML, Auditing)"
perSeatLicensing = "Per-seat licensing"
saveWithAnnualBilling = "Save with annual billing"
selfHosted = "Self-hosted"
selfHostedOnInfrastructure = "Self-hosted on your infrastructure"
ssoOAuth = "SSO (OAuth2/OIDC)"
unlimitedUsers = "Unlimited users"
upToFiveUsers = "Up to 5 users"
usageTrackingPrometheus = "Usage tracking & Prometheus"
[plan.licenseWarning]
body = "You have {{total}} users but the free tier only supports {{limit}} per server. Upgrade to keep Stirling PDF running smoothly."
cta = "See plans"
@@ -6389,6 +6539,7 @@ allSessions = "All Sessions"
allTools = "Tools"
automate = "Automate"
back = "Back"
backToAllTools = "Back to all tools"
certSign = "Certificate Sign"
completedSessions = "Completed Sessions"
completedTab = "Completed"
@@ -7060,6 +7211,9 @@ bullet3 = "Critical for approval workflows and legal chains of custody"
description = "The order you specify when creating the session determines who signs first."
title = "Signature Order"
[settings]
close = "Close"
[settings.configuration]
advanced = "Advanced"
database = "Database"
@@ -7542,6 +7696,7 @@ sharedDescription = "All users can see and use these signatures."
sharedHeading = "Shared Signatures"
tempStorageDescription = "Signatures are stored in your browser only. They will be lost if you clear browser data or switch browsers."
tempStorageTitle = "Temporary browser storage"
use = "Use signature"
[sign.saved.status]
saved = "Saved"
@@ -8122,9 +8277,18 @@ center = "Center"
left = "Left"
right = "Right"
[textInput]
clear = "Clear input"
[theme]
toggle = "Toggle Theme"
[time.relative]
daysAgo = "{{count}}d ago"
hoursAgo = "{{count}}h ago"
justNow = "just now"
minutesAgo = "{{count}}m ago"
[timestampPdf]
completed = "PDF timestamped successfully"
desc = "Add an RFC 3161 document timestamp to your PDF using a trusted Time Stamp Authority (TSA) server."
@@ -8151,11 +8315,9 @@ label = "Select a TSA server"
[timestampPdf.steps]
settings = "Settings"
[time.relative]
daysAgo = "{{count}}d ago"
hoursAgo = "{{count}}h ago"
justNow = "just now"
minutesAgo = "{{count}}m ago"
[toast]
dismiss = "Dismiss"
toggleDetails = "Toggle details"
[tool]
endpointUnavailable = "This tool is unavailable on your server."
@@ -8243,6 +8405,9 @@ verification = "Verification"
noSearchResults = "No tools found"
noTools = "No tools available"
[tooltip]
close = "Close tooltip"
[unlockPDFForms]
description = "This tool will remove read-only restrictions from PDF form fields, making them editable and fillable."
filenamePrefix = "unlocked_forms"
@@ -8269,6 +8434,7 @@ breakingChangesDefault = "This version contains breaking changes."
breakingChangesDetected = "Breaking Changes Detected"
breakingChangesMessage = "Some versions contain breaking changes. Please review the migration guides below before updating."
close = "Close"
closeModal = "Close update modal"
current = "Current Version"
defaultRecommendation = "This update contains important fixes and improvements."
downloadLatest = "Download Latest"
@@ -8520,6 +8686,9 @@ typeInsertText = "Insert Text"
typeReplaceText = "Replace Text"
viewComment = "View comment"
[viewer.error]
noFileProvided = "Error: No file provided to viewer"
[viewer.formBar]
apply = "Apply Changes"
dismiss = "Dismiss"
@@ -8529,6 +8698,9 @@ title = "Form Fields"
unsavedBadge = "Unsaved"
unsavedDesc = "You have unsaved changes"
[viewer.link]
delete = "Delete link"
[viewer.nonPdf]
columnDefault = "Column {{index}}"
convertToPdf = "Convert to PDF"
@@ -8544,6 +8716,19 @@ renderMarkdown = "Render markdown"
sortedBy = "Sorted by: {{column}}"
textStats = "{{lines}} lines · {{size}}"
[viewer.redaction]
removeMark = "Remove this mark"
[viewer.search]
clear = "Clear search"
close = "Close search"
next = "Next result"
previous = "Previous result"
resultsOf = "of {{total}}"
[viewer.signature]
delete = "Delete signature"
[viewPdf]
header = "View PDF"
tags = "view,read,annotate,text,image,highlight,edit"
@@ -8792,6 +8977,37 @@ toggleSidebar = "Toggle Sidebar"
toggleTheme = "Toggle Theme"
viewer = "Viewer"
[workflow.participant]
accessExpired = "Your access to this document has expired."
certificateFile = "Certificate File"
certificateFilePlaceholder = "Select certificate file"
certificatePassword = "Certificate Password"
certificateType = "Certificate Type"
certTypeJks = "JKS Keystore"
certTypeP12 = "P12/PKCS12 Certificate"
certTypeServer = "Server Certificate (if available)"
completedDeclined = "You have declined this document."
completedSigned = "You have signed this document."
decline = "Decline"
downloadDocument = "Download Document"
dueDate = "Due Date: {{date}}"
errorTitle = "Error"
from = "From: {{name}}"
loadingSession = "Loading session..."
location = "Location"
locationPlaceholder = "e.g., San Francisco, CA"
pageNumber = "Page Number (optional)"
reason = "Reason"
reasonPlaceholder = "e.g., Document approval"
sessionNotFound = "Session not found or access denied."
signDocument = "Sign Document"
statusDeclined = "Declined"
statusNotified = "Notified"
statusPending = "Pending"
statusSigned = "Signed"
statusViewed = "Viewed"
submitSignature = "Submit Signature"
[workspace]
title = "Workspace"
@@ -17,6 +17,7 @@
"height": 800,
"resizable": true,
"fullscreen": false,
"dragDropEnabled": false,
"additionalBrowserArgs": "--enable-features=CertVerifierBuiltinFeature"
}
]
@@ -8,6 +8,7 @@ import {
Group,
} from "@mantine/core";
import { useState, useCallback, useEffect } from "react";
import { useTranslation } from "react-i18next";
import ColorizeIcon from "@mui/icons-material/Colorize";
// safari and firefox do not support the eye dropper API, only edge, chrome and opera do.
@@ -33,6 +34,7 @@ export function ColorControl({
label,
disabled = false,
}: ColorControlProps) {
const { t } = useTranslation();
const [opened, setOpened] = useState(false);
// Buffer the colour locally so the picker stays responsive during drag.
// Only propagate to the parent (which triggers expensive annotation updates)
@@ -111,7 +113,9 @@ export function ColorControl({
/>
{supportsEyeDropper && (
<Group justify="flex-end">
<Tooltip label="Pick colour from screen">
<Tooltip
label={t("color.eyeDropper.tooltip", "Pick colour from screen")}
>
<ActionIcon
variant="subtle"
color="gray"
@@ -1,5 +1,6 @@
import React, { useState } from "react";
import { Stack } from "@mantine/core";
import { useTranslation } from "react-i18next";
import { BaseAnnotationTool } from "@app/components/annotation/shared/BaseAnnotationTool";
import { ImageUploader } from "@app/components/annotation/shared/ImageUploader";
@@ -12,6 +13,7 @@ export const ImageTool: React.FC<ImageToolProps> = ({
onImageChange,
disabled = false,
}) => {
const { t } = useTranslation();
const [, setImageData] = useState<string | null>(null);
const handleImageUpload = async (file: File | null) => {
@@ -57,9 +59,12 @@ export const ImageTool: React.FC<ImageToolProps> = ({
<ImageUploader
onImageChange={handleImageUpload}
disabled={disabled}
label="Upload Image"
placeholder="Select image file"
hint="Upload a PNG, JPG, SVG, or other image file to place on the PDF. SVG files will be converted to PNG for compatibility."
label={t("image.upload.label", "Upload Image")}
placeholder={t("image.upload.placeholder", "Select image file")}
hint={t(
"image.upload.hint",
"Upload a PNG, JPG, SVG, or other image file to place on the PDF. SVG files will be converted to PNG for compatibility.",
)}
/>
</Stack>
</BaseAnnotationTool>
@@ -134,7 +134,7 @@ const AddFileCard = ({
)}
</Button>
<Button
aria-label="Upload"
aria-label={t("addFileCard.upload", "Upload")}
style={{
backgroundColor: "var(--landing-button-bg)",
color: "var(--landing-button-color)",
@@ -77,7 +77,7 @@ const EmptyFilesState: React.FC = () => {
onMouseLeave={() => setIsUploadHover(false)}
>
<Button
aria-label="Upload"
aria-label={t("emptyFilesState.upload", "Upload")}
style={{
backgroundColor: "var(--bg-file-manager)",
color: "var(--landing-button-color)",
@@ -16,6 +16,7 @@ import {
TextInput,
} from "@mantine/core";
import { QRCodeSVG } from "qrcode.react";
import { useTranslation } from "react-i18next";
import { SlideConfig } from "@app/types/types";
import { UNIFIED_CIRCLE_CONFIG } from "@app/components/onboarding/slides/unifiedBackgroundConfig";
import { accountService } from "@app/services/accountService";
@@ -31,6 +32,7 @@ interface MFASetupSlideProps {
}
function MFASetupContent({ onMfaSetupComplete }: MFASetupSlideProps) {
const { t } = useTranslation();
const [mfaSetupData, setMfaSetupData] = useState<MfaSetupResponse | null>(
null,
);
@@ -179,7 +181,9 @@ function MFASetupContent({ onMfaSetupComplete }: MFASetupSlideProps) {
{mfaLoading && !isReady && (
<Group gap="sm">
<Loader size="sm" />
<Text size="sm">Generating your QR code…</Text>
<Text size="sm">
{t("onboarding.mfa.qrCodeLoading", "Generating your QR code…")}
</Text>
</Group>
)}
@@ -189,7 +193,10 @@ function MFASetupContent({ onMfaSetupComplete }: MFASetupSlideProps) {
<Stack gap="sm">
<TextInput
id="mfa-setup-code"
label="Authentication code"
label={t(
"onboarding.mfa.authenticationCode",
"Authentication code",
)}
placeholder="123456"
value={mfaSetupCode}
onChange={(event) =>
@@ -37,11 +37,20 @@ export default function SecurityCheckSlide({
</div>
<Select
placeholder="Confirm your role"
placeholder={i18n.t(
"onboarding.securityCheck.rolePlaceholder",
"Confirm your role",
)}
value={selectedRole}
data={[
{ value: "admin", label: "Admin" },
{ value: "user", label: "User" },
{
value: "admin",
label: i18n.t("onboarding.securityCheck.roleAdmin", "Admin"),
},
{
value: "user",
label: i18n.t("onboarding.securityCheck.roleUser", "User"),
},
]}
onChange={(value) =>
onRoleSelect((value as "admin" | "user") ?? null)
@@ -1,5 +1,6 @@
import { useState, useCallback, useRef, useEffect, useMemo } from "react";
import { Text, Center, Box, LoadingOverlay, Stack } from "@mantine/core";
import { useTranslation } from "react-i18next";
import { useFileState, useFileActions } from "@app/contexts/FileContext";
import {
useNavigationGuard,
@@ -33,6 +34,7 @@ export interface PageEditorProps {
}
const PageEditor = ({ onFunctionsReady }: PageEditorProps) => {
const { t } = useTranslation();
// Use split contexts to prevent re-renders
const { state, selectors } = useFileState();
const { actions } = useFileActions();
@@ -688,9 +690,14 @@ const PageEditor = ({ onFunctionsReady }: PageEditorProps) => {
<Text size="lg" c="dimmed">
📄
</Text>
<Text c="dimmed">No PDF files loaded</Text>
<Text c="dimmed">
{t("pageEditor.emptyState.title", "No PDF files loaded")}
</Text>
<Text size="sm" c="dimmed">
Add files to start editing pages
{t(
"pageEditor.emptyState.body",
"Add files to start editing pages",
)}
</Text>
</Stack>
</Center>
@@ -6,6 +6,7 @@ import RotateLeftIcon from "@mui/icons-material/RotateLeft";
import RotateRightIcon from "@mui/icons-material/RotateRight";
import DeleteIcon from "@mui/icons-material/Delete";
import InsertPageBreakIcon from "@mui/icons-material/InsertPageBreak";
import { useTranslation } from "react-i18next";
interface PageEditorControlsProps {
// Close/Reset functions
@@ -51,6 +52,7 @@ const PageEditorControls = ({
displayDocument,
splitPositions,
}: PageEditorControlsProps) => {
const { t } = useTranslation();
// Calculate split tooltip text using smart toggle logic
const getSplitTooltip = () => {
if (!splitPositions || !displayDocument || selectedPageIds.length === 0) {
@@ -131,7 +133,7 @@ const PageEditorControls = ({
}}
>
{/* Undo/Redo */}
<Tooltip label="Undo">
<Tooltip label={t("pageEditor.toolbar.undo", "Undo")}>
<ActionIcon
onClick={onUndo}
disabled={!canUndo}
@@ -145,7 +147,7 @@ const PageEditorControls = ({
<UndoIcon />
</ActionIcon>
</Tooltip>
<Tooltip label="Redo">
<Tooltip label={t("pageEditor.toolbar.redo", "Redo")}>
<ActionIcon
onClick={onRedo}
disabled={!canRedo}
@@ -170,7 +172,9 @@ const PageEditorControls = ({
/>
{/* Page Operations */}
<Tooltip label="Rotate Selected Left">
<Tooltip
label={t("pageEditor.toolbar.rotateLeft", "Rotate Selected Left")}
>
<ActionIcon
onClick={() => onRotate("left")}
disabled={selectedPageIds.length === 0}
@@ -187,7 +191,9 @@ const PageEditorControls = ({
<RotateLeftIcon />
</ActionIcon>
</Tooltip>
<Tooltip label="Rotate Selected Right">
<Tooltip
label={t("pageEditor.toolbar.rotateRight", "Rotate Selected Right")}
>
<ActionIcon
onClick={() => onRotate("right")}
disabled={selectedPageIds.length === 0}
@@ -204,7 +210,7 @@ const PageEditorControls = ({
<RotateRightIcon />
</ActionIcon>
</Tooltip>
<Tooltip label="Delete Selected">
<Tooltip label={t("pageEditor.toolbar.delete", "Delete Selected")}>
<ActionIcon
onClick={onDelete}
disabled={selectedPageIds.length === 0}
@@ -26,7 +26,10 @@ const OperatorsSection = ({
className={classes.operatorChip}
onClick={() => onInsertOperator("and")}
disabled={!csvInput.trim()}
title="Combine selections (both conditions must be true)"
title={t(
"bulkSelection.operators.and.title",
"Combine selections (both conditions must be true)",
)}
>
<Text size="xs" fw={500}>
and
@@ -38,7 +41,10 @@ const OperatorsSection = ({
className={classes.operatorChip}
onClick={() => onInsertOperator("or")}
disabled={!csvInput.trim()}
title="Add to selection (either condition can be true)"
title={t(
"bulkSelection.operators.or.title",
"Add to selection (either condition can be true)",
)}
>
<Text size="xs" fw={500}>
or
@@ -50,7 +56,10 @@ const OperatorsSection = ({
className={classes.operatorChip}
onClick={() => onInsertOperator("not")}
disabled={!csvInput.trim()}
title="Exclude from selection"
title={t(
"bulkSelection.operators.not.title",
"Exclude from selection",
)}
>
<Text size="xs" fw={500}>
not
@@ -64,7 +73,10 @@ const OperatorsSection = ({
variant="outline"
className={classes.operatorChip}
onClick={() => onInsertOperator("even")}
title="Select all even-numbered pages (2, 4, 6, 8...)"
title={t(
"bulkSelection.operators.even.title",
"Select all even-numbered pages (2, 4, 6, 8...)",
)}
>
<Text size="xs" fw={500}>
even
@@ -75,7 +87,10 @@ const OperatorsSection = ({
variant="outline"
className={classes.operatorChip}
onClick={() => onInsertOperator("odd")}
title="Select all odd-numbered pages (1, 3, 5, 7...)"
title={t(
"bulkSelection.operators.odd.title",
"Select all odd-numbered pages (1, 3, 5, 7...)",
)}
>
<Text size="xs" fw={500}>
odd
@@ -45,7 +45,9 @@ const PageSelectionInput = ({
height="1rem"
style={{ color: "var(--text-instruction)" }}
/>
<Text>Page Selection</Text>
<Text>
{t("bulkSelection.pageSelection.title", "Page Selection")}
</Text>
</Flex>
</Tooltip>
{typeof advancedOpened === "boolean" && (
@@ -7,6 +7,7 @@ import React, {
} from "react";
import { Badge, Modal, Text, ActionIcon, Tooltip, Group } from "@mantine/core";
import { useNavigate, useLocation } from "react-router-dom";
import { useTranslation } from "react-i18next";
import LocalIcon from "@app/components/shared/LocalIcon";
import { useConfigNavSections } from "@app/components/shared/config/configNavSections";
import { NavKey, VALID_NAV_KEYS } from "@app/components/shared/config/types";
@@ -33,6 +34,7 @@ const AppConfigModalInner: React.FC<AppConfigModalProps> = ({
opened,
onClose,
}) => {
const { t } = useTranslation();
const [active, setActive] = useState<NavKey>("general");
const isMobile = useIsMobile();
const navigate = useNavigate();
@@ -332,7 +334,7 @@ const AppConfigModalInner: React.FC<AppConfigModalProps> = ({
ref={closeButtonRef}
variant="subtle"
onClick={handleClose}
aria-label="Close"
aria-label={t("settings.close", "Close")}
data-autofocus
>
<LocalIcon icon="close-rounded" width={18} height={18} />
@@ -8,6 +8,7 @@ import {
Group,
TextInput,
} from "@mantine/core";
import { useTranslation } from "react-i18next";
import UnfoldMoreIcon from "@mui/icons-material/UnfoldMore";
import SearchIcon from "@mui/icons-material/Search";
import { Z_INDEX_AUTOMATE_DROPDOWN } from "@app/styles/zIndex";
@@ -71,6 +72,7 @@ const DropdownListWithFooter: React.FC<DropdownListWithFooterProps> = ({
withinPortal = true,
zIndex = Z_INDEX_AUTOMATE_DROPDOWN,
}) => {
const { t } = useTranslation();
const [searchTerm, setSearchTerm] = useState("");
const isMultiValue = Array.isArray(value);
@@ -184,7 +186,7 @@ const DropdownListWithFooter: React.FC<DropdownListWithFooterProps> = ({
}}
>
<TextInput
placeholder="Search..."
placeholder={t("dropdownList.searchPlaceholder", "Search...")}
value={searchTerm}
onChange={handleSearchChange}
leftSection={<SearchIcon style={{ fontSize: "1rem" }} />}
@@ -98,8 +98,11 @@ export default function EditableSecretField({
variant="light"
onClick={handleEdit}
disabled={disabled}
title="Edit"
aria-label="Edit secret value"
title={t("editableSecretField.edit", "Edit")}
aria-label={t(
"editableSecretField.editSecretValue",
"Edit secret value",
)}
>
<LocalIcon icon="edit" width="1rem" height="1rem" />
</ActionIcon>
@@ -111,7 +111,7 @@ const FileCard = ({
onClick={(e) => e.stopPropagation()}
>
{onView && (
<Tooltip label="View in Viewer">
<Tooltip label={t("fileCard.viewInViewer", "View in Viewer")}>
<ActionIcon
size="sm"
variant="subtle"
@@ -126,7 +126,9 @@ const FileCard = ({
</Tooltip>
)}
{onEdit && (
<Tooltip label="Open in File Editor">
<Tooltip
label={t("fileCard.openInFileEditor", "Open in File Editor")}
>
<ActionIcon
size="sm"
variant="subtle"
@@ -1,5 +1,6 @@
import React from "react";
import { Menu, Loader, Group, Text, ActionIcon, Tooltip } from "@mantine/core";
import { useTranslation } from "react-i18next";
import InsertDriveFileIcon from "@mui/icons-material/InsertDriveFile";
import KeyboardArrowDownIcon from "@mui/icons-material/KeyboardArrowDown";
import CloseIcon from "@mui/icons-material/Close";
@@ -28,6 +29,7 @@ export const FileDropdownMenu: React.FC<FileDropdownMenuProps> = ({
switchingTo,
viewOptionStyle,
}) => {
const { t } = useTranslation();
return (
<Menu trigger="click" position="bottom" width="30rem">
<Menu.Target>
@@ -95,7 +97,10 @@ export const FileDropdownMenu: React.FC<FileDropdownMenuProps> = ({
</Text>
)}
{onFileRemove && (
<Tooltip label="Close file" withArrow>
<Tooltip
label={t("fileDropdownMenu.closeFile", "Close file")}
withArrow
>
<ActionIcon
component="div"
size="xs"
@@ -1,5 +1,6 @@
import { useState, useCallback, useRef } from "react";
import { createPortal } from "react-dom";
import { useTranslation } from "react-i18next";
import VisibilityOutlinedIcon from "@mui/icons-material/VisibilityOutlined";
import VisibilityOffOutlinedIcon from "@mui/icons-material/VisibilityOffOutlined";
import type { FileId } from "@app/types/file";
@@ -141,6 +142,7 @@ export function FileItem({
onClick,
onEyeClick,
}: FileItemProps) {
const { t } = useTranslation();
const ext = getFileExtension(name);
const dateLabel = lastModified ? formatFileDate(lastModified) : "";
const typeLabel = ext ? ext.toUpperCase() : "File";
@@ -215,7 +217,11 @@ export function FileItem({
}}
tabIndex={-1}
type="button"
aria-label={isViewedInViewer ? "Close viewer" : "Open in viewer"}
aria-label={
isViewedInViewer
? t("fileSidebar.fileItem.closeViewer", "Close viewer")
: t("fileSidebar.fileItem.openInViewer", "Open in viewer")
}
>
<VisibilityOutlinedIcon
className="file-sidebar-eye-open"
@@ -1,5 +1,6 @@
import React, { ReactNode } from "react";
import { Paper, Group, Text, Button, ActionIcon, Stack } from "@mantine/core";
import { useTranslation } from "react-i18next";
import LocalIcon from "@app/components/shared/LocalIcon";
type InfoBannerTone = "info" | "warning";
@@ -85,6 +86,7 @@ export const InfoBanner: React.FC<InfoBannerProps> = ({
closeIconColor,
compact = false,
}) => {
const { t } = useTranslation();
if (!show) {
return null;
}
@@ -192,7 +194,7 @@ export const InfoBanner: React.FC<InfoBannerProps> = ({
color={closeIconColor ? undefined : "gray"}
size="sm"
onClick={handleDismiss}
aria-label="Dismiss"
aria-label={t("infoBanner.dismiss", "Dismiss")}
style={closeIconColor ? { color: closeIconColor } : undefined}
>
<LocalIcon
@@ -1,4 +1,5 @@
import React, { forwardRef } from "react";
import { useTranslation } from "react-i18next";
import LocalIcon from "@app/components/shared/LocalIcon";
import styles from "@app/components/shared/textInput/TextInput.module.css";
@@ -63,6 +64,7 @@ export const TextInput = forwardRef<HTMLInputElement, TextInputProps>(
},
ref,
) => {
const { t } = useTranslation();
const handleClear = () => {
if (onClear) {
onClear();
@@ -112,7 +114,7 @@ export const TextInput = forwardRef<HTMLInputElement, TextInputProps>(
type="button"
className={styles.clearButton}
onClick={handleClear}
aria-label="Clear input"
aria-label={t("textInput.clear", "Clear input")}
>
<LocalIcon icon="close-rounded" width="1.25rem" height="1.25rem" />
</button>
@@ -6,6 +6,7 @@ import React, {
useCallback,
} from "react";
import { createPortal } from "react-dom";
import { useTranslation } from "react-i18next";
import LocalIcon from "@app/components/shared/LocalIcon";
import { addEventListenerWithCleanup } from "@app/utils/genericUtils";
import { useTooltipPosition } from "@app/hooks/useTooltipPosition";
@@ -68,6 +69,7 @@ export const Tooltip: React.FC<TooltipProps> = ({
manualCloseOnly = false,
showCloseButton = false,
}) => {
const { t } = useTranslation();
const [internalOpen, setInternalOpen] = useState(false);
const [isPinned, setIsPinned] = useState(false);
const { tooltipLogo } = useLogoAssets();
@@ -401,8 +403,8 @@ export const Tooltip: React.FC<TooltipProps> = ({
setIsPinned(false);
setOpen(false);
}}
title="Close tooltip"
aria-label="Close tooltip"
title={t("tooltip.close", "Close tooltip")}
aria-label={t("tooltip.close", "Close tooltip")}
>
<LocalIcon icon="close-rounded" width="1.25rem" height="1.25rem" />
</button>
@@ -259,7 +259,7 @@ const UpdateModal: React.FC<UpdateModalProps> = ({
onClick={onClose}
size="lg"
variant="subtle"
aria-label="Close update modal"
aria-label={t("update.closeModal", "Close update modal")}
/>
)}
</Group>
@@ -1,5 +1,6 @@
import React, { useState, useEffect } from "react";
import { ActionIcon, Slider } from "@mantine/core";
import { useTranslation } from "react-i18next";
import { useViewer } from "@app/contexts/ViewerContext";
import { useNavigationState } from "@app/contexts/NavigationContext";
import ZoomInIcon from "@mui/icons-material/ZoomIn";
@@ -9,6 +10,7 @@ import ZoomOutIcon from "@mui/icons-material/ZoomOut";
* Compact zoom controls rendered inline in the WorkbenchBar when the current workbench is "viewer".
*/
export function ViewerInlineControls() {
const { t } = useTranslation();
const { workbench } = useNavigationState();
const viewer = useViewer();
@@ -39,7 +41,7 @@ export function ViewerInlineControls() {
radius="md"
className="workbench-bar-action-icon"
onClick={() => viewer.zoomActions.zoomOut()}
aria-label="Zoom out"
aria-label={t("viewer.zoomOut", "Zoom out")}
>
<ZoomOutIcon sx={{ fontSize: "1rem" }} />
</ActionIcon>
@@ -68,7 +70,7 @@ export function ViewerInlineControls() {
radius="md"
className="workbench-bar-action-icon"
onClick={() => viewer.zoomActions.zoomIn()}
aria-label="Zoom in"
aria-label={t("viewer.zoomIn", "Zoom in")}
>
<ZoomInIcon sx={{ fontSize: "1rem" }} />
</ActionIcon>
@@ -15,6 +15,7 @@
import React, { useEffect, useRef, useState } from "react";
import { ActionIcon, Divider } from "@mantine/core";
import ArrowBackRoundedIcon from "@mui/icons-material/ArrowBackRounded";
import { useTranslation } from "react-i18next";
import { useToolWorkflow } from "@app/contexts/ToolWorkflowContext";
import {
useNavigationState,
@@ -37,6 +38,7 @@ const ActiveToolButton: React.FC<ActiveToolButtonProps> = ({
setActiveButton,
tooltipPosition = "right",
}) => {
const { t } = useTranslation();
const { selectedTool, selectedToolKey, leftPanelView, handleBackToTools } =
useToolWorkflow();
const { hasUnsavedChanges } = useNavigationState();
@@ -158,7 +160,11 @@ const ActiveToolButton: React.FC<ActiveToolButtonProps> = ({
<div className="current-tool-content">
<div className="flex flex-col items-center gap-1">
<Tooltip
content={isBackHover ? "Back to all tools" : indicatorTool.name}
content={
isBackHover
? t("quickAccess.backToAllTools", "Back to all tools")
: indicatorTool.name
}
position={tooltipPosition}
arrow
maxWidth={140}
@@ -183,7 +189,9 @@ const ActiveToolButton: React.FC<ActiveToolButtonProps> = ({
onMouseEnter={() => setIsBackHover(true)}
onMouseLeave={() => setIsBackHover(false)}
aria-label={
isBackHover ? "Back to all tools" : indicatorTool.name
isBackHover
? t("quickAccess.backToAllTools", "Back to all tools")
: indicatorTool.name
}
style={{
backgroundColor: isBackHover

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