Skip to content

#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere

Keep Enterprise processing unlimited with local usage metering (#7994)

ConnorYohd2d11011d0e8
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/FreeTierUsageService.java b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/FreeTierUsageService.java
index 8f6d4e1432..f65e532b1d 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/FreeTierUsageService.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/FreeTierUsageService.java
@@ -20,7 +20,8 @@ import stirling.software.proprietary.billing.BillingStepLimit;
import stirling.software.proprietary.billing.ContentHasher;
/**
- * The local free-tier ledger an unlinked instance meters itself against.
+ * Local monthly usage for unlinked and Enterprise instances. Only non-Enterprise requests enforce
+ * the free-tier balance; Enterprise usage accrues without a ceiling.
*
* <p>Touches only {@link FreeTierUsageCounter} / {@link FreeTierPeriod}, which {@link
* UsageSyncService} never reads, so local usage never reaches SaaS and a link/unlink cycle cannot
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/GateDecision.java b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/GateDecision.java
index b225f04bde..7a4386e997 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/GateDecision.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/GateDecision.java
@@ -14,7 +14,7 @@ public record GateDecision(boolean allowed, Reason reason) {
MANUAL_FREE,
/** Linked + within entitlement — billable work allowed. */
ENTITLED,
- /** Active local Enterprise licence includes processing without credit charges. */
+ /** Enterprise license permits processing with local-only usage metering. */
ENTERPRISE_LICENSE,
FREE_TIER,
/** Entitlement source unreachable — fail open, allow. */
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/InstanceEntitlementGate.java b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/InstanceEntitlementGate.java
index f0966049ec..eaf166056e 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/InstanceEntitlementGate.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/InstanceEntitlementGate.java
@@ -17,7 +17,7 @@ import stirling.software.common.service.LicenseServiceInterface;
* <ol>
* <li>Flag off → always allow (feature inert).
* <li>Manual tool → always allow (manual tools are free, never metered).
- * <li>Active Enterprise licence → allow without consuming credits.
+ * <li>Enterprise license → always allow, with local-only metering.
* <li>Billable + not linked → {@code FREE_TIER} while units remain, else {@code
* FREE_TIER_EXHAUSTED}. Linking buys a further grant, it does not activate the feature.
* <li>Billable + linked + entitlement unknown (unreachable) → <b>fail open</b>, allow — unless
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/InstanceEntitlementInterceptor.java b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/InstanceEntitlementInterceptor.java
index 4a36228dc4..73804a705a 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/InstanceEntitlementInterceptor.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/InstanceEntitlementInterceptor.java
@@ -40,12 +40,13 @@ import stirling.software.proprietary.security.model.ApiKeyAuthenticationToken;
/**
* Request-time gate + meter for combined billing. {@code preHandle} blocks billable (API / AI /
- * automation) work once the applicable allowance is spent; manual tools pass through. {@code
- * afterCompletion} costs the op and accrues it.
+ * automation) work once the applicable allowance is spent; Enterprise licenses and manual tools
+ * pass through. {@code afterCompletion} costs the op and accrues it.
*
* <p>The ledger follows the gate's own reason rather than re-deriving linked-ness, so the two
* cannot disagree. Only the cloud one sits behind {@code …metering.enabled}: with it off a linked
- * instance accrues nothing while the free tier still meters and holds.
+ * instance accrues nothing while the free tier still meters and holds. Enterprise usage stays in
+ * the local ledger even when linked, so it cannot become PAYG spend.
*/
@Slf4j
@Component
@@ -172,9 +173,6 @@ public class InstanceEntitlementInterceptor implements HandlerInterceptor {
HttpServletResponse response,
Object handler,
Exception ex) {
- if (request.getAttribute(ATTR_REASON) == GateDecision.Reason.ENTERPRISE_LICENSE) {
- return;
- }
// Meter successful billable ops only.
if (ex != null || response.getStatus() >= 400) {
return;
@@ -184,7 +182,9 @@ public class InstanceEntitlementInterceptor implements HandlerInterceptor {
return;
}
try {
- if (request.getAttribute(ATTR_REASON) == GateDecision.Reason.FREE_TIER) {
+ Object reason = request.getAttribute(ATTR_REASON);
+ if (reason == GateDecision.Reason.FREE_TIER
+ || reason == GateDecision.Reason.ENTERPRISE_LICENSE) {
MeteredOp op = measure(request, UnitCalcPolicy.DEFAULT);
if (op != null) {
freeTierUsageService.accrue(category, op.units(), op.dedupKey());
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/EnterpriseProcessingHttpIntegrationTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/EnterpriseProcessingHttpIntegrationTest.java
new file mode 100644
index 0000000000..57b7dc4495
--- /dev/null
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/EnterpriseProcessingHttpIntegrationTest.java
@@ -0,0 +1,348 @@
+package stirling.software.proprietary.accountlink;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyLong;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.clearInvocations;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.reset;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.verifyNoInteractions;
+import static org.mockito.Mockito.when;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.net.URI;
+import java.net.http.HttpClient;
+import java.net.http.HttpRequest;
+import java.net.http.HttpResponse;
+import java.nio.charset.StandardCharsets;
+import java.time.Duration;
+import java.time.LocalDateTime;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+
+import org.apache.pdfbox.Loader;
+import org.apache.pdfbox.pdmodel.PDDocument;
+import org.apache.pdfbox.pdmodel.PDPage;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.EnumSource;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.SpringBootConfiguration;
+import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
+import org.springframework.boot.persistence.autoconfigure.EntityScan;
+import org.springframework.boot.security.autoconfigure.SecurityAutoConfiguration;
+import org.springframework.boot.security.autoconfigure.UserDetailsServiceAutoConfiguration;
+import org.springframework.boot.security.autoconfigure.actuate.web.servlet.ManagementWebSecurityAutoConfiguration;
+import org.springframework.boot.security.autoconfigure.web.servlet.SecurityFilterAutoConfiguration;
+import org.springframework.boot.security.autoconfigure.web.servlet.ServletWebSecurityAutoConfiguration;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.boot.test.web.server.LocalServerPort;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Import;
+import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
+
+import jakarta.servlet.Filter;
+import jakarta.servlet.FilterChain;
+import jakarta.servlet.ServletException;
+import jakarta.servlet.ServletRequest;
+import jakarta.servlet.ServletResponse;
+
+import stirling.software.common.model.ApplicationProperties;
+import stirling.software.common.service.CustomPDFDocumentFactory;
+import stirling.software.common.service.InternalApiClient;
+import stirling.software.common.service.PdfMetadataService;
+import stirling.software.common.util.TempFileManager;
+import stirling.software.common.util.TempFileRegistry;
+import stirling.software.proprietary.billing.BillingCategory;
+import stirling.software.proprietary.billing.UnitCalcPolicy;
+import stirling.software.proprietary.controller.api.converters.ConvertPdfToPdfUa;
+import stirling.software.proprietary.security.configuration.ee.DynamicLicenseService;
+import stirling.software.proprietary.security.configuration.ee.KeygenLicenseVerifier.License;
+import stirling.software.proprietary.security.configuration.ee.LicenseKeyChecker;
+import stirling.software.proprietary.service.ua.FontEmbeddingService;
+import stirling.software.proprietary.service.ua.PdfUaConversionService;
+import stirling.software.proprietary.service.ua.PdfUaValidationService;
+
+/**
+ * Real HTTP, multipart PDF conversion and H2 persistence through the production gate and meter.
+ * Only the license checker and outbound SaaS client are controlled; authentication is outside this
+ * fixture, which sends the automation marker used by server-dispatched pipeline steps.
+ */
+@SpringBootTest(
+ classes = EnterpriseProcessingHttpIntegrationTest.TestApp.class,
+ webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
+ properties = {
+ "spring.datasource.url=jdbc:h2:mem:enterprise-processing;DB_CLOSE_DELAY=-1",
+ "spring.jpa.hibernate.ddl-auto=create-drop",
+ "spring.jpa.open-in-view=false",
+ "stirling.billing.account-link.enabled=true",
+ "stirling.billing.account-link.metering.enabled=true"
+ })
+class EnterpriseProcessingHttpIntegrationTest {
+
+ private static final long SPENT_GRANT = 500;
+ private static final int PAGES = 26;
+ private static final long PDF_UNITS = 2;
+ private static final String BOUNDARY = "enterprise-processing-test";
+
+ @LocalServerPort private int port;
+ @Autowired private LicenseKeyChecker licenseChecker;
+ @Autowired private AccountLinkClient cloud;
+ @Autowired private DeviceCredentialStore credentials;
+ @Autowired private EntitlementCache entitlements;
+ @Autowired private FreeTierUsageService localUsage;
+ @Autowired private FreeTierUsageCounterRepository localCounters;
+ @Autowired private FreeTierPeriodRepository periods;
+ @Autowired private MeteredInputSignatureRepository signatures;
+ @Autowired private UsageCounterRepository cloudCounters;
+ @Autowired private AccountLinkSyncStateRepository syncState;
+ @Autowired private UsageSyncService sync;
+ @Autowired private RequestCompletion completion;
+
+ private final HttpClient http = HttpClient.newHttpClient();
+
+ @BeforeEach
+ void resetInstance() {
+ reset(licenseChecker, cloud);
+ credentials.clear();
+ entitlements.invalidate();
+ entitlements.current();
+ localCounters.deleteAll();
+ periods.deleteAll();
+ signatures.deleteAll();
+ cloudCounters.deleteAll();
+ syncState.deleteAll();
+ when(licenseChecker.getPremiumLicenseEnabledResult()).thenReturn(License.ENTERPRISE);
+ localUsage.accrue(BillingCategory.AUTOMATION, SPENT_GRANT, null);
+ assertThat(localUsage.balance().remainingUnits()).isZero();
+ }
+
+ @Test
+ void unlinkedEnterpriseProcessesRealPdfPastItsGrantAndPersistsUsage() throws Exception {
+ HttpResponse<byte[]> response = convert(pdf());
+
+ assertConvertedPdf(response);
+ assertLocalUsage(SPENT_GRANT + PDF_UNITS);
+ assertThat(cloudCounters.count()).isZero();
+ verifyNoInteractions(cloud);
+ }
+
+ @ParameterizedTest
+ @EnumSource(
+ value = EntitlementState.class,
+ names = {"OVER_LIMIT", "REVOKED"})
+ void linkedEnterpriseProcessesLocallyWithoutAddingPaygUsage(EntitlementState state)
+ throws Exception {
+ credentials.save("test-device", "test-secret", 42L);
+ LocalDateTime period = LocalDateTime.now().withNano(0);
+ InstanceEntitlement blocked =
+ new InstanceEntitlement(
+ true,
+ 0,
+ 100,
+ 100L,
+ state,
+ UnitCalcPolicy.DEFAULT,
+ period,
+ period.plusMonths(1),
+ null);
+ when(cloud.fetchEntitlement("test-device", "test-secret")).thenReturn(blocked);
+ entitlements.invalidate();
+ assertThat(entitlements.current().orElseThrow().state()).isEqualTo(state);
+ clearInvocations(cloud);
+
+ assertConvertedPdf(convert(pdf()));
+
+ assertLocalUsage(SPENT_GRANT + PDF_UNITS);
+ assertThat(cloudCounters.count()).isZero();
+ verifyNoInteractions(cloud);
+ sync.syncNow();
+ verify(cloud, never())
+ .reportUsage(
+ anyString(),
+ anyString(),
+ anyLong(),
+ any(),
+ anyLong(),
+ anyLong(),
+ anyLong());
+
+ cloudCounters.saveAndFlush(new UsageCounter(period, "API", 7, period));
+ when(cloud.reportUsage(
+ eq("test-device"),
+ eq("test-secret"),
+ anyLong(),
+ eq(period),
+ eq(7L),
+ eq(0L),
+ eq(0L)))
+ .thenReturn(blocked);
+ sync.syncNow();
+
+ verify(cloud).reportUsage("test-device", "test-secret", 1L, period, 7L, 0L, 0L);
+ assertThat(cloudCounters.findByPeriodStart(period).getFirst().getLastSyncedUnits())
+ .isEqualTo(7);
+ assertLocalUsage(SPENT_GRANT + PDF_UNITS);
+ }
+
+ @ParameterizedTest
+ @EnumSource(
+ value = License.class,
+ names = {"NORMAL", "SERVER"})
+ void losingEnterpriseStatusRestoresCreditEnforcementWithoutRestart(License nextLicense)
+ throws Exception {
+ byte[] input = pdf();
+ assertConvertedPdf(convert(input));
+ assertLocalUsage(SPENT_GRANT + PDF_UNITS);
+
+ when(licenseChecker.getPremiumLicenseEnabledResult()).thenReturn(nextLicense);
+ HttpResponse<byte[]> response = convert(input);
+
+ assertThat(response.statusCode()).isEqualTo(402);
+ assertThat(new String(response.body(), StandardCharsets.UTF_8))
+ .contains("ACCOUNT_LINK_REQUIRED", "FREE_TIER_EXHAUSTED");
+ assertLocalUsage(SPENT_GRANT + PDF_UNITS);
+ assertThat(cloudCounters.count()).isZero();
+ }
+
+ @Test
+ void failedEnterpriseProcessingDoesNotAccrueUsage() throws Exception {
+ HttpResponse<byte[]> response = convert("not a PDF".getBytes(StandardCharsets.UTF_8));
+
+ assertThat(response.statusCode()).isBetween(400, 599).isNotEqualTo(402);
+ assertLocalUsage(SPENT_GRANT);
+ assertThat(cloudCounters.count()).isZero();
+ verifyNoInteractions(cloud);
+ }
+
+ private void assertLocalUsage(long expected) {
+ assertThat(localUsage.balance().usedUnits()).isEqualTo(expected);
+ assertThat(localUsage.balance().usedByCategory()).containsEntry("AUTOMATION", expected);
+ assertThat(localCounters.findAll())
+ .singleElement()
+ .satisfies(counter -> assertThat(counter.getCumulativeUnits()).isEqualTo(expected));
+ }
+
+ private static void assertConvertedPdf(HttpResponse<byte[]> response) throws IOException {
+ assertThat(response.statusCode()).isEqualTo(200);
+ try (PDDocument output = Loader.loadPDF(response.body())) {
+ assertThat(output.getNumberOfPages()).isEqualTo(PAGES);
+ assertThat(output.getDocumentCatalog().getLanguage()).isEqualTo("en-US");
+ assertThat(output.getDocumentCatalog().getStructureTreeRoot()).isNotNull();
+ }
+ }
+
+ private HttpResponse<byte[]> convert(byte[] pdf) throws Exception {
+ ByteArrayOutputStream body = new ByteArrayOutputStream();
+ body.write(
+ ("--"
+ + BOUNDARY
+ + "\r\nContent-Disposition: form-data; name=\"fileInput\"; "
+ + "filename=\"input.pdf\"\r\nContent-Type: application/pdf\r\n\r\n")
+ .getBytes(StandardCharsets.UTF_8));
+ body.write(pdf);
+ body.write(
+ ("\r\n--"
+ + BOUNDARY
+ + "\r\nContent-Disposition: form-data; name=\"embedFonts\""
+ + "\r\n\r\nfalse\r\n--"
+ + BOUNDARY
+ + "\r\nContent-Disposition: form-data; name=\"language\"\r\n\r\nen-US\r\n--"
+ + BOUNDARY
+ + "--\r\n")
+ .getBytes(StandardCharsets.UTF_8));
+ completion.finished = new CountDownLatch(1);
+ HttpResponse<byte[]> response =
+ http.send(
+ HttpRequest.newBuilder(
+ URI.create(
+ "http://localhost:"
+ + port
+ + "/api/v1/convert/pdf/ua"))
+ .timeout(Duration.ofSeconds(30))
+ .header("Content-Type", "multipart/form-data; boundary=" + BOUNDARY)
+ .header(InternalApiClient.AUTOMATION_HEADER, "true")
+ .POST(HttpRequest.BodyPublishers.ofByteArray(body.toByteArray()))
+ .build(),
+ HttpResponse.BodyHandlers.ofByteArray());
+ assertThat(completion.finished.await(5, TimeUnit.SECONDS)).isTrue();
+ return response;
+ }
+
+ private static byte[] pdf() throws IOException {
+ try (PDDocument document = new PDDocument();
+ ByteArrayOutputStream out = new ByteArrayOutputStream()) {
+ for (int i = 0; i < PAGES; i++) {
+ document.addPage(new PDPage());
+ }
+ document.save(out);
+ return out.toByteArray();
+ }
+ }
+
+ /** Response bytes can arrive before afterCompletion commits the metering transaction. */
+ static class RequestCompletion implements Filter {
+ volatile CountDownLatch finished = new CountDownLatch(0);
+
+ @Override
+ public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
+ throws IOException, ServletException {
+ try {
+ chain.doFilter(request, response);
+ } finally {
+ finished.countDown();
+ }
+ }
+ }
+
+ @SpringBootConfiguration
+ @EnableAutoConfiguration(
+ exclude = {
+ SecurityAutoConfiguration.class, ServletWebSecurityAutoConfiguration.class,
+ ManagementWebSecurityAutoConfiguration.class, SecurityFilterAutoConfiguration.class,
+ UserDetailsServiceAutoConfiguration.class
+ })
+ @EntityScan(basePackageClasses = UsageCounter.class)
+ @EnableJpaRepositories(basePackageClasses = UsageCounterRepository.class)
+ @Import({
+ AccountLinkProperties.class, AccountLinkWebMvcConfig.class, InstanceEntitlementGate.class,
+ InstanceEntitlementInterceptor.class, FreeTierUsageService.class, LocalUsageService.class,
+ UsageMeterService.class, UsageSyncService.class, DeviceCredentialStore.class,
+ EntitlementCache.class, DynamicLicenseService.class, TempFileManager.class,
+ TempFileRegistry.class, ConvertPdfToPdfUa.class, PdfUaConversionService.class,
+ PdfUaValidationService.class, FontEmbeddingService.class
+ })
+ static class TestApp {
+ @Bean
+ LicenseKeyChecker licenseKeyChecker() {
+ return mock(LicenseKeyChecker.class);
+ }
+
+ @Bean
+ AccountLinkClient accountLinkClient() {
+ return mock(AccountLinkClient.class);
+ }
+
+ @Bean
+ ApplicationProperties applicationProperties() {
+ return new ApplicationProperties();
+ }
+
+ @Bean
+ CustomPDFDocumentFactory pdfDocumentFactory(ApplicationProperties properties) {
+ return new CustomPDFDocumentFactory(
+ new PdfMetadataService(properties, "test", true, null));
+ }
+
+ @Bean
+ RequestCompletion requestCompletion() {
+ return new RequestCompletion();
+ }
+ }
+}
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/InstanceEntitlementGateWiringTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/InstanceEntitlementGateWiringTest.java
index ca55092dc1..c48f216967 100644
--- a/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/InstanceEntitlementGateWiringTest.java
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/InstanceEntitlementGateWiringTest.java
@@ -12,10 +12,17 @@ import static org.mockito.Mockito.when;
import java.time.LocalDateTime;
import java.util.Optional;
+import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.EnumSource;
+import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import stirling.software.common.service.LicenseServiceInterface;
+import stirling.software.proprietary.security.configuration.ee.DynamicLicenseService;
+import stirling.software.proprietary.security.configuration.ee.KeygenLicenseVerifier.License;
+import stirling.software.proprietary.security.configuration.ee.LicenseKeyChecker;
/** Verifies {@link InstanceEntitlementGate#evaluate} resolves live state from store + cache. */
class InstanceEntitlementGateWiringTest {
@@ -25,27 +32,104 @@ class InstanceEntitlementGateWiringTest {
private EntitlementCache cache;
private LocalUsageService localUsage;
private FreeTierUsageService freeTier;
+ private AccountLinkSyncStateRepository syncState;
+ private LicenseKeyChecker licenseChecker;
+ private AnnotationConfigApplicationContext context;
private InstanceEntitlementGate gate;
- private LicenseServiceInterface licenseService;
@BeforeEach
void setUp() {
- licenseService = mock(LicenseServiceInterface.class);
properties = new AccountLinkProperties();
properties.setEnabled(true);
store = mock(DeviceCredentialStore.class);
cache = mock(EntitlementCache.class);
localUsage = mock(LocalUsageService.class);
freeTier = mock(FreeTierUsageService.class);
- gate =
- new InstanceEntitlementGate(
- properties,
- store,
- cache,
- mock(AccountLinkSyncStateRepository.class),
- localUsage,
- freeTier,
- licenseService);
+ syncState = mock(AccountLinkSyncStateRepository.class);
+ licenseChecker = mock(LicenseKeyChecker.class);
+ context = new AnnotationConfigApplicationContext();
+ context.registerBean(AccountLinkProperties.class, () -> properties);
+ context.registerBean(DeviceCredentialStore.class, () -> store);
+ context.registerBean(EntitlementCache.class, () -> cache);
+ context.registerBean(AccountLinkSyncStateRepository.class, () -> syncState);
+ context.registerBean(LocalUsageService.class, () -> localUsage);
+ context.registerBean(FreeTierUsageService.class, () -> freeTier);
+ context.registerBean(
+ LicenseServiceInterface.class, () -> new DynamicLicenseService(licenseChecker));
+ context.registerBean(InstanceEntitlementGate.class);
+ context.refresh();
+ gate = context.getBean(InstanceEntitlementGate.class);
+ }
+
+ @AfterEach
+ void tearDown() {
+ context.close();
+ }
+
+ @Test
+ void enterpriseBypassesExhaustedLocalCredits() {
+ when(licenseChecker.getPremiumLicenseEnabledResult()).thenReturn(License.ENTERPRISE);
+ when(freeTier.balance()).thenReturn(grant(0));
+
+ assertEquals(
+ GateDecision.allow(GateDecision.Reason.ENTERPRISE_LICENSE), gate.evaluate(true));
+
+ verifyNoInteractions(store, cache, syncState, localUsage, freeTier);
+ }
+
+ @ParameterizedTest
+ @EnumSource(EntitlementState.class)
+ void enterpriseBypassesLinkedBillingRestrictions(EntitlementState state) {
+ when(licenseChecker.getPremiumLicenseEnabledResult()).thenReturn(License.ENTERPRISE);
+ when(store.isLinked()).thenReturn(true);
+ when(cache.current())
+ .thenReturn(Optional.of(new InstanceEntitlement(true, 0, 100, 100L, state)));
+ when(localUsage.currentPeriodUnsynced())
+ .thenReturn(new LocalUsageService.LocalUsage(null, 0, 0, 0, 0));
+
+ assertEquals(
+ GateDecision.allow(GateDecision.Reason.ENTERPRISE_LICENSE), gate.evaluate(true));
+
+ verifyNoInteractions(store, cache, syncState, localUsage, freeTier);
+ }
+
+ @Test
+ void enterpriseBypassesExpiredCloudSyncGrace() {
+ when(licenseChecker.getPremiumLicenseEnabledResult()).thenReturn(License.ENTERPRISE);
+ properties.getMetering().setEnabled(true);
+ when(store.isLinked()).thenReturn(true);
+ when(cache.current()).thenReturn(Optional.empty());
+ AccountLinkSyncState stale = new AccountLinkSyncState();
+ stale.setLastSuccessAt(LocalDateTime.now().minusDays(10));
+ when(syncState.findById(AccountLinkSyncState.SINGLETON_ID)).thenReturn(Optional.of(stale));
+
+ assertEquals(
+ GateDecision.allow(GateDecision.Reason.ENTERPRISE_LICENSE), gate.evaluate(true));
+
+ verifyNoInteractions(store, cache, syncState, localUsage, freeTier);
+ }
+
+ @ParameterizedTest
+ @EnumSource(
+ value = License.class,
+ names = {"NORMAL", "SERVER"})
+ void nonEnterpriseLicensesStillEnforceCredits(License license) {
+ when(licenseChecker.getPremiumLicenseEnabledResult()).thenReturn(license);
+ when(freeTier.balance()).thenReturn(grant(0));
+
+ assertFalse(gate.evaluate(true).allowed());
+ }
+
+ @Test
+ void licenseChangesTakeEffectOnTheSameGate() {
+ when(licenseChecker.getPremiumLicenseEnabledResult())
+ .thenReturn(License.NORMAL, License.ENTERPRISE, License.NORMAL);
+ when(freeTier.balance()).thenReturn(grant(0));
+
+ assertFalse(gate.evaluate(true).allowed());
+ assertEquals(
+ GateDecision.allow(GateDecision.Reason.ENTERPRISE_LICENSE), gate.evaluate(true));
+ assertFalse(gate.evaluate(true).allowed());
}
private static FreeTierUsageService.FreeTierBalance grant(long remaining) {
@@ -91,7 +175,7 @@ class InstanceEntitlementGateWiringTest {
@Test
void enterpriseProcessingDoesNotConsultLinkStatusOrCreditBalances() {
- when(licenseService.isRunningEE()).thenReturn(true);
+ when(licenseChecker.getPremiumLicenseEnabledResult()).thenReturn(License.ENTERPRISE);
GateDecision decision = gate.evaluate(true);
assertTrue(decision.allowed());
assertEquals(GateDecision.Reason.ENTERPRISE_LICENSE, decision.reason());
@@ -100,7 +184,8 @@ class InstanceEntitlementGateWiringTest {
@Test
void removingEnterpriseLicenseRestoresCreditEnforcementWithoutRestart() {
- when(licenseService.isRunningEE()).thenReturn(true, false);
+ when(licenseChecker.getPremiumLicenseEnabledResult())
+ .thenReturn(License.ENTERPRISE, License.NORMAL);
assertTrue(gate.evaluate(true).allowed());
when(store.isLinked()).thenReturn(false);
when(freeTier.balance()).thenReturn(grant(0));
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/InstanceEntitlementInterceptorTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/InstanceEntitlementInterceptorTest.java
index 2d36c8f75b..2d56bbd8d2 100644
--- a/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/InstanceEntitlementInterceptorTest.java
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/InstanceEntitlementInterceptorTest.java
@@ -29,6 +29,7 @@ import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.api.io.TempDir;
import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.EnumSource;
import org.junit.jupiter.params.provider.ValueSource;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
@@ -101,11 +102,11 @@ class InstanceEntitlementInterceptorTest {
}
@Test
- void enterpriseProcessingNeverReachesEitherCreditLedger() throws Exception {
+ void enterpriseProcessingWithoutFilesDoesNotAccrueUsage() throws Exception {
when(gate.evaluate(anyBoolean()))
.thenReturn(GateDecision.allow(GateDecision.Reason.ENTERPRISE_LICENSE));
InstanceEntitlementInterceptor interceptor = interceptor();
- MockHttpServletRequest request = new MockHttpServletRequest("POST", "/api/v1/ai/x");
+ MockHttpServletRequest request = new MockHttpServletRequest("POST", "/api/v1/ai/tools/x");
MockHttpServletResponse response = new MockHttpServletResponse();
assertTrue(interceptor.preHandle(request, response, new Object()));
interceptor.afterCompletion(request, response, new Object(), null);
@@ -113,12 +114,12 @@ class InstanceEntitlementInterceptorTest {
freeTierUsageService, entitlementCache, meterProvider, tempFileManager);
}
- @Test
- void metersTheFreeTierLedgerWhenUnlinked() throws Exception {
- // FREE_TIER is the gate saying "unlinked, inside the grant", so the op must land on the
- // local ledger with the compiled-in policy and never touch the cloud one.
- when(gate.evaluate(anyBoolean()))
- .thenReturn(GateDecision.allow(GateDecision.Reason.FREE_TIER));
+ @ParameterizedTest
+ @EnumSource(
+ value = GateDecision.Reason.class,
+ names = {"FREE_TIER", "ENTERPRISE_LICENSE"})
+ void metersLocallyWithoutConsultingCloudBilling(GateDecision.Reason reason) throws Exception {
+ when(gate.evaluate(anyBoolean())).thenReturn(GateDecision.allow(reason));
InstanceEntitlementInterceptor interceptor = interceptor();
MockMultipartHttpServletRequest req = fileRequest("/api/v1/ai/tools/x");