Skip to content

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

Add Server license registration and user-count reporting (#8510)

ConnorYoh4cca666640f7
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/security/configuration/DatabaseConfig.java b/app/proprietary/src/main/java/stirling/software/proprietary/security/configuration/DatabaseConfig.java
index dde04fbc97..334a1189d8 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/security/configuration/DatabaseConfig.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/security/configuration/DatabaseConfig.java
@@ -37,6 +37,7 @@ import stirling.software.common.model.exception.UnsupportedProviderException;
"stirling.software.proprietary.policy.migration",
"stirling.software.proprietary.policy.ledger",
"stirling.software.proprietary.accountlink",
+ "stirling.software.proprietary.serverregistration",
"stirling.software.proprietary.access.repository",
"stirling.software.proprietary.integration.repository",
"stirling.software.proprietary.connectedaccount",
@@ -53,6 +54,7 @@ import stirling.software.common.model.exception.UnsupportedProviderException;
"stirling.software.proprietary.policy.migration",
"stirling.software.proprietary.policy.ledger",
"stirling.software.proprietary.accountlink",
+ "stirling.software.proprietary.serverregistration",
"stirling.software.proprietary.access.model",
"stirling.software.proprietary.integration.model",
"stirling.software.proprietary.connectedaccount",
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/serverregistration/LegacyServerRegistrationService.java b/app/proprietary/src/main/java/stirling/software/proprietary/serverregistration/LegacyServerRegistrationService.java
new file mode 100644
index 0000000000..3cc051c4f2
--- /dev/null
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/serverregistration/LegacyServerRegistrationService.java
@@ -0,0 +1,226 @@
+package stirling.software.proprietary.serverregistration;
+
+import java.io.IOException;
+import java.net.http.HttpTimeoutException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.time.Clock;
+import java.time.Duration;
+import java.time.Instant;
+
+import org.springframework.beans.factory.ObjectProvider;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.annotation.Qualifier;
+import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
+import org.springframework.context.annotation.Profile;
+import org.springframework.scheduling.annotation.SchedulingConfigurer;
+import org.springframework.scheduling.config.FixedDelayTask;
+import org.springframework.scheduling.config.ScheduledTaskRegistrar;
+import org.springframework.stereotype.Service;
+
+import lombok.extern.slf4j.Slf4j;
+
+import stirling.software.common.model.ApplicationProperties;
+import stirling.software.common.util.GeneralUtils;
+import stirling.software.proprietary.security.configuration.ee.KeygenLicenseVerifier.License;
+import stirling.software.proprietary.security.configuration.ee.LicenseKeyChecker;
+import stirling.software.proprietary.security.service.UserService;
+
+/**
+ * Reports installed Server licenses independently of Team linking, billing and entitlement refresh.
+ */
+@Slf4j
+@Service
+@Profile("!saas")
+@ConditionalOnProperty(name = "stirling.server-registration.enabled", havingValue = "true")
+public class LegacyServerRegistrationService implements SchedulingConfigurer {
+ private static final Duration MIN_FAILURE_BACKOFF = Duration.ofMinutes(15);
+ private static final Duration MAX_FAILURE_BACKOFF = Duration.ofHours(24);
+ private final LicenseKeyChecker licenses;
+ private final ApplicationProperties application;
+ private final ObjectProvider<UserService> users;
+ private final ServerRegistrationStateStore states;
+ private final ServerRegistrationClient client;
+ private final ServerRegistrationProperties properties;
+ private final String version;
+ private final Clock clock;
+ private Duration failureBackoff = Duration.ZERO;
+ private Instant nextAttemptAt = Instant.MIN;
+ private Instant nextWarningAt = Instant.MIN;
+ private String lastFailure;
+
+ @Autowired
+ public LegacyServerRegistrationService(
+ LicenseKeyChecker licenses,
+ ApplicationProperties application,
+ ObjectProvider<UserService> users,
+ ServerRegistrationStateStore states,
+ ServerRegistrationClient client,
+ ServerRegistrationProperties properties,
+ @Qualifier("appVersion") String version) {
+ this(licenses, application, users, states, client, properties, version, Clock.systemUTC());
+ }
+
+ LegacyServerRegistrationService(
+ LicenseKeyChecker licenses,
+ ApplicationProperties application,
+ ObjectProvider<UserService> users,
+ ServerRegistrationStateStore states,
+ ServerRegistrationClient client,
+ ServerRegistrationProperties properties,
+ String version,
+ Clock clock) {
+ this.licenses = licenses;
+ this.application = application;
+ this.users = users;
+ this.states = states;
+ this.client = client;
+ this.properties = properties;
+ this.version = version;
+ this.clock = clock;
+ }
+
+ @Override
+ public void configureTasks(ScheduledTaskRegistrar registrar) {
+ Duration interval = properties.getSyncInterval();
+ if (interval.compareTo(Duration.ofMinutes(1)) < 0) {
+ throw new IllegalArgumentException(
+ "Server registration interval must be at least one minute");
+ }
+ registrar.addFixedDelayTask(
+ new FixedDelayTask(this::reportNow, interval, Duration.ofSeconds(30)));
+ }
+
+ /**
+ * Serialized with scheduled runs. All reporting failures leave the working license untouched.
+ * Retry cooldowns and warning deduplication are per process and reset on restart.
+ */
+ public synchronized void reportNow() {
+ if (licenses.getLicenseKeyResult() != License.SERVER) return;
+ if (clock.instant().isBefore(nextAttemptAt)) return;
+ String operation = "reading license";
+ try {
+ String proof = readProof();
+ if (proof == null || proof.isBlank() || proof.length() > 65536) {
+ recordFailure(operation, "missing, blank or oversized proof", true, null);
+ return;
+ }
+ operation = "counting users";
+ UserService localUsers = users.getIfAvailable();
+ if (localUsers == null) {
+ recordFailure(operation, "user service unavailable", false, null);
+ return;
+ }
+ for (int attempt = 0; attempt < 2; attempt++) {
+ operation = "counting users";
+ long count = localUsers.getTotalUsersCount();
+ if (count < 0 || count > Integer.MAX_VALUE) {
+ recordFailure(operation, "count outside supported range", true, null);
+ return;
+ }
+ operation = "reserving local state";
+ ServerRegistrationState state = states.reserve(proof);
+ var report =
+ new ServerRegistrationProtocol.Report(
+ state.getReportSequence(),
+ count,
+ version,
+ ServerRegistrationProtocol.CAPABILITY_VERSION);
+ ServerRegistrationProtocol.Receipt receipt;
+ try {
+ if (state.getRegistrationId() == null
+ || state.getPurchaseMapping()
+ != ServerRegistrationProtocol.PurchaseMapping.RESOLVED) {
+ operation = "registering with cloud";
+ receipt =
+ client.register(
+ new ServerRegistrationProtocol.RegistrationRequest(
+ state.getInstallationId(),
+ proof,
+ GeneralUtils.generateMachineFingerprint(),
+ state.getRegistrationSecret(),
+ report));
+ } else {
+ operation = "syncing with cloud";
+ receipt =
+ client.sync(
+ new ServerRegistrationProtocol.SyncRequest(
+ state.getRegistrationId(),
+ state.getRegistrationSecret(),
+ report));
+ }
+ operation = "saving acknowledgement";
+ states.acknowledge(state, receipt);
+ if (lastFailure != null) log.info("Server registration reporting recovered");
+ lastFailure = null;
+ failureBackoff = Duration.ZERO;
+ nextAttemptAt = Instant.MIN;
+ nextWarningAt = Instant.MIN;
+ return;
+ } catch (ServerRegistrationClient.SequenceConflictException e) {
+ operation = "recovering report sequence";
+ if (attempt != 0 || !states.reconcile(state, e.conflict())) throw e;
+ }
+ }
+ } catch (IOException | RuntimeException e) {
+ if (Thread.currentThread().isInterrupted()) return;
+ if (e instanceof ServerRegistrationClient.HttpFailureException failure) {
+ int status = failure.status();
+ boolean rejected = status < 500 && status != 408 && status != 425 && status != 429;
+ String reason =
+ "HTTP " + status + (rejected ? "; check registration configuration" : "");
+ recordFailure(operation, reason, rejected, failure.retryNotBefore());
+ } else {
+ String reason =
+ e instanceof HttpTimeoutException
+ ? "request timed out"
+ : e.getClass().getSimpleName();
+ boolean rejected =
+ e instanceof ServerRegistrationClient.InvalidResponseException
+ || e instanceof ServerRegistrationClient.SequenceConflictException;
+ recordFailure(operation, reason, rejected, null);
+ }
+ }
+ }
+
+ private void recordFailure(
+ String operation, String reason, boolean rejected, Instant retryNotBefore) {
+ Instant now = clock.instant();
+ if (rejected) {
+ failureBackoff = MAX_FAILURE_BACKOFF;
+ } else if (failureBackoff.isZero()) {
+ failureBackoff = MIN_FAILURE_BACKOFF;
+ } else {
+ failureBackoff = failureBackoff.multipliedBy(2);
+ }
+ if (failureBackoff.compareTo(MAX_FAILURE_BACKOFF) > 0) {
+ failureBackoff = MAX_FAILURE_BACKOFF;
+ }
+ Duration delay =
+ properties.getSyncInterval().compareTo(failureBackoff) > 0
+ ? properties.getSyncInterval()
+ : failureBackoff;
+ nextAttemptAt = now.plus(delay);
+ if (retryNotBefore != null && retryNotBefore.isAfter(nextAttemptAt)) {
+ nextAttemptAt = retryNotBefore;
+ }
+ String failure = operation + ": " + reason;
+ if (!failure.equals(lastFailure) || !now.isBefore(nextWarningAt)) {
+ log.warn(
+ "Server registration failed while {} ({}); next attempt no earlier than {}. Installed license unchanged",
+ operation,
+ reason,
+ nextAttemptAt);
+ nextWarningAt = now.plus(MAX_FAILURE_BACKOFF);
+ }
+ lastFailure = failure;
+ }
+
+ private String readProof() throws IOException {
+ String configured = application.getPremium().getKey();
+ if (configured == null || !configured.startsWith("file:")) return configured;
+ Path path = Path.of(configured.substring(5));
+ if (Files.size(path) > 65536) return null;
+ return Files.readString(path);
+ }
+}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/serverregistration/RegistrationHttpTransport.java b/app/proprietary/src/main/java/stirling/software/proprietary/serverregistration/RegistrationHttpTransport.java
new file mode 100644
index 0000000000..acdbeb3f29
--- /dev/null
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/serverregistration/RegistrationHttpTransport.java
@@ -0,0 +1,33 @@
+package stirling.software.proprietary.serverregistration;
+
+import java.io.IOException;
+import java.net.http.HttpClient;
+import java.net.http.HttpRequest;
+import java.net.http.HttpResponse;
+import java.net.http.HttpTimeoutException;
+import java.time.Duration;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
+
+/** Applies collection HTTP deadlines through body completion without exposing upstream data. */
+public final class RegistrationHttpTransport {
+ private RegistrationHttpTransport() {}
+
+ /** Cancels the exchange on timeout or interruption, including a stalled response body. */
+ public static HttpResponse<String> send(HttpClient http, HttpRequest request, Duration timeout)
+ throws IOException, InterruptedException {
+ var exchange = http.sendAsync(request, HttpResponse.BodyHandlers.ofString());
+ try {
+ return exchange.get(timeout.toNanos(), TimeUnit.NANOSECONDS);
+ } catch (TimeoutException e) {
+ exchange.cancel(true);
+ throw new HttpTimeoutException("Registration HTTP deadline exceeded");
+ } catch (InterruptedException e) {
+ exchange.cancel(true);
+ throw e;
+ } catch (ExecutionException e) {
+ throw new IOException("Registration HTTP exchange failed");
+ }
+ }
+}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/serverregistration/ServerRegistrationClient.java b/app/proprietary/src/main/java/stirling/software/proprietary/serverregistration/ServerRegistrationClient.java
new file mode 100644
index 0000000000..604a66ad2a
--- /dev/null
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/serverregistration/ServerRegistrationClient.java
@@ -0,0 +1,198 @@
+package stirling.software.proprietary.serverregistration;
+
+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.time.Clock;
+import java.time.DateTimeException;
+import java.time.Duration;
+import java.time.Instant;
+import java.time.ZonedDateTime;
+import java.time.format.DateTimeFormatter;
+import java.util.Set;
+
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
+import org.springframework.context.annotation.Profile;
+import org.springframework.stereotype.Service;
+
+import stirling.software.proprietary.accountlink.AccountLinkProperties;
+
+import tools.jackson.databind.ObjectMapper;
+
+/**
+ * Bounded, nonredirecting transport. Neither license proofs nor upstream bodies enter exceptions.
+ */
+@Service
+@Profile("!saas")
+@ConditionalOnProperty(name = "stirling.server-registration.enabled", havingValue = "true")
+public class ServerRegistrationClient {
+ private final URI base;
+ private final Duration timeout;
+ private final ObjectMapper mapper;
+ private final HttpClient http;
+ private final Clock clock;
+
+ @Autowired
+ public ServerRegistrationClient(AccountLinkProperties properties, ObjectMapper mapper) {
+ this(
+ properties,
+ mapper,
+ HttpClient.newBuilder()
+ .connectTimeout(Duration.ofSeconds(properties.getRequestTimeoutSeconds()))
+ .followRedirects(HttpClient.Redirect.NEVER)
+ .build());
+ }
+
+ ServerRegistrationClient(
+ AccountLinkProperties properties, ObjectMapper mapper, HttpClient http) {
+ this(properties, mapper, http, Clock.systemUTC());
+ }
+
+ ServerRegistrationClient(
+ AccountLinkProperties properties, ObjectMapper mapper, HttpClient http, Clock clock) {
+ this.base = URI.create(properties.getSaasBaseUrl().replaceAll("/+$", ""));
+ this.timeout = Duration.ofSeconds(properties.getRequestTimeoutSeconds());
+ this.mapper = mapper;
+ this.http = http;
+ this.clock = clock;
+ boolean loopback =
+ base.getHost() != null
+ && Set.of("localhost", "127.0.0.1", "[::1]").contains(base.getHost());
+ if (base.getHost() == null
+ || (!"https".equals(base.getScheme())
+ && !("http".equals(base.getScheme()) && loopback))
+ || base.getRawUserInfo() != null
+ || base.getRawQuery() != null
+ || base.getRawFragment() != null) {
+ throw new IllegalArgumentException(
+ "Registration requires HTTPS, except loopback development");
+ }
+ }
+
+ /** Bootstraps with a license proof; retry with the same persisted secret after a lost reply. */
+ public ServerRegistrationProtocol.Receipt register(
+ ServerRegistrationProtocol.RegistrationRequest request) throws IOException {
+ return send(ServerRegistrationProtocol.PATH, request);
+ }
+
+ /** Reports with the tracking credential only; does not request or cache any entitlement. */
+ public ServerRegistrationProtocol.Receipt sync(ServerRegistrationProtocol.SyncRequest request)
+ throws IOException {
+ return send(ServerRegistrationProtocol.PATH + "/sync", request);
+ }
+
+ /** Authenticated conflict data is for sequence recovery only, never an acknowledgement. */
+ public static final class SequenceConflictException extends IOException {
+ private final ServerRegistrationProtocol.SequenceConflict conflict;
+
+ public SequenceConflictException(ServerRegistrationProtocol.SequenceConflict conflict) {
+ super("Report sequence already superseded");
+ this.conflict = conflict;
+ }
+
+ public ServerRegistrationProtocol.SequenceConflict conflict() {
+ return conflict;
+ }
+ }
+
+ /** Carries only the HTTP status and optional retry deadline, never the upstream body. */
+ public static final class HttpFailureException extends IOException {
+ private final int status;
+ private final Instant retryNotBefore;
+
+ public HttpFailureException(int status, Instant retryNotBefore) {
+ super("Registration returned HTTP " + status);
+ this.status = status;
+ this.retryNotBefore = retryNotBefore;
+ }
+
+ public int status() {
+ return status;
+ }
+
+ public Instant retryNotBefore() {
+ return retryNotBefore;
+ }
+ }
+
+ /** Identifies an unusable receipt without retaining credential-bearing parse errors. */
+ public static final class InvalidResponseException extends IOException {
+ public InvalidResponseException() {
+ super("Invalid registration response");
+ }
+ }
+
+ private ServerRegistrationProtocol.Receipt send(String path, Object payload)
+ throws IOException {
+ HttpRequest request =
+ HttpRequest.newBuilder(URI.create(base.toString() + path))
+ .timeout(timeout)
+ .header("Content-Type", "application/json")
+ .header("Accept", "application/json")
+ .POST(
+ HttpRequest.BodyPublishers.ofString(
+ mapper.writeValueAsString(payload)))
+ .build();
+ try {
+ HttpResponse<String> response = RegistrationHttpTransport.send(http, request, timeout);
+ if (response.statusCode() == 409) {
+ ServerRegistrationProtocol.SequenceConflict conflict;
+ try {
+ conflict =
+ mapper.readValue(
+ response.body(),
+ ServerRegistrationProtocol.SequenceConflict.class);
+ } catch (RuntimeException e) {
+ throw new InvalidResponseException();
+ }
+ if (conflict == null
+ || conflict.registrationId() == null
+ || conflict.acceptedSequence() < 1
+ || conflict.acceptedSequence() == Long.MAX_VALUE) {
+ throw new InvalidResponseException();
+ }
+ throw new SequenceConflictException(conflict);
+ }
+ if (response.statusCode() != 200) {
+ throw new HttpFailureException(response.statusCode(), retryNotBefore(response));
+ }
+ ServerRegistrationProtocol.Receipt receipt;
+ try {
+ receipt =
+ mapper.readValue(response.body(), ServerRegistrationProtocol.Receipt.class);
+ } catch (RuntimeException e) {
+ throw new InvalidResponseException();
+ }
+ if (receipt == null
+ || receipt.registrationId() == null
+ || receipt.acceptedSequence() < 1
+ || receipt.purchaseMapping() == null) {
+ throw new InvalidResponseException();
+ }
+ return receipt;
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ throw new IOException("Registration interrupted");
+ }
+ }
+
+ private Instant retryNotBefore(HttpResponse<?> response) {
+ if (response.statusCode() != 429 && response.statusCode() != 503) return null;
+ String value = response.headers().firstValue("Retry-After").orElse("").strip();
+ if (value.isEmpty()) return null;
+ try {
+ Instant now = clock.instant();
+ Instant deadline =
+ value.matches("[0-9]+")
+ ? now.plusSeconds(Long.parseLong(value))
+ : ZonedDateTime.parse(value, DateTimeFormatter.RFC_1123_DATE_TIME)
+ .toInstant();
+ return deadline.isBefore(now) ? null : deadline;
+ } catch (DateTimeException | ArithmeticException | NumberFormatException e) {
+ return null;
+ }
+ }
+}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/serverregistration/ServerRegistrationProperties.java b/app/proprietary/src/main/java/stirling/software/proprietary/serverregistration/ServerRegistrationProperties.java
new file mode 100644
index 0000000000..9df8c64f2d
--- /dev/null
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/serverregistration/ServerRegistrationProperties.java
@@ -0,0 +1,19 @@
+package stirling.software.proprietary.serverregistration;
+
+import java.time.Duration;
+
+import org.springframework.boot.context.properties.ConfigurationProperties;
+import org.springframework.stereotype.Component;
+
+import lombok.Getter;
+import lombok.Setter;
+
+/** Independent rollout switch; enabling reporting never enables migration or Team billing. */
+@Getter
+@Setter
+@Component
+@ConfigurationProperties(prefix = "stirling.server-registration")
+public class ServerRegistrationProperties {
+ private boolean enabled = false;
+ private Duration syncInterval = Duration.ofHours(24);
+}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/serverregistration/ServerRegistrationProtocol.java b/app/proprietary/src/main/java/stirling/software/proprietary/serverregistration/ServerRegistrationProtocol.java
new file mode 100644
index 0000000000..404aa9e07d
--- /dev/null
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/serverregistration/ServerRegistrationProtocol.java
@@ -0,0 +1,74 @@
+package stirling.software.proprietary.serverregistration;
+
+import java.util.UUID;
+
+import jakarta.validation.Valid;
+import jakarta.validation.constraints.Max;
+import jakarta.validation.constraints.Min;
+import jakarta.validation.constraints.NotBlank;
+import jakarta.validation.constraints.NotNull;
+import jakarta.validation.constraints.Pattern;
+import jakarta.validation.constraints.Size;
+
+/**
+ * Tracking-only wire contract. Counts exclude the internal API user and never convey entitlement.
+ */
+public final class ServerRegistrationProtocol {
+ public static final String PATH = "/api/v1/server-license/registrations";
+ public static final int CAPABILITY_VERSION = 1;
+
+ private ServerRegistrationProtocol() {}
+
+ /**
+ * A monotonic sequence is reserved durably before sending; receipt time determines freshness.
+ */
+ public record Report(
+ @NotNull @Min(1) Long sequence,
+ @NotNull @Min(0) @Max(Integer.MAX_VALUE) Long reportedUserCount,
+ @NotBlank @Size(max = 80) String applicationVersion,
+ @Min(1) @Max(1) int capabilityVersion) {}
+
+ /**
+ * The installation creates and saves its secret before bootstrap so a lost reply is
+ * recoverable.
+ */
+ public record RegistrationRequest(
+ @NotNull UUID installationId,
+ @NotBlank @Size(max = 65536) String licenseProof,
+ @NotBlank @Size(max = 256) String machineFingerprint,
+ @NotBlank @Pattern(regexp = "[A-Za-z0-9_-]{43}") String registrationSecret,
+ @NotNull @Valid Report report) {
+ @Override
+ public String toString() {
+ return "RegistrationRequest[installationId="
+ + installationId
+ + ", credentials=REDACTED]";
+ }
+ }
+
+ /** This secret authenticates only this tracking record, never a human or Team connection. */
+ public record SyncRequest(
+ @NotNull UUID registrationId,
+ @NotBlank @Pattern(regexp = "[A-Za-z0-9_-]{43}") String registrationSecret,
+ @NotNull @Valid Report report) {
+ @Override
+ public String toString() {
+ return "SyncRequest[registrationId=" + registrationId + ", credential=REDACTED]";
+ }
+ }
+
+ public enum PurchaseMapping {
+ RESOLVED,
+ UNRESOLVED
+ }
+
+ /**
+ * Acknowledges accepted tracking data only; no migration or entitlement instruction exists
+ * here.
+ */
+ public record Receipt(
+ UUID registrationId, long acceptedSequence, PurchaseMapping purchaseMapping) {}
+
+ /** Returned only after credential authentication; does not accept or refresh the report. */
+ public record SequenceConflict(UUID registrationId, long acceptedSequence) {}
+}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/serverregistration/ServerRegistrationState.java b/app/proprietary/src/main/java/stirling/software/proprietary/serverregistration/ServerRegistrationState.java
new file mode 100644
index 0000000000..33db97845b
--- /dev/null
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/serverregistration/ServerRegistrationState.java
@@ -0,0 +1,50 @@
+package stirling.software.proprietary.serverregistration;
+
+import java.time.Instant;
+import java.util.UUID;
+
+import jakarta.persistence.Column;
+import jakarta.persistence.Entity;
+import jakarta.persistence.EnumType;
+import jakarta.persistence.Enumerated;
+import jakarta.persistence.Id;
+import jakarta.persistence.Table;
+import jakarta.persistence.Version;
+
+import lombok.Getter;
+import lombok.Setter;
+
+/**
+ * Local singleton. The secret stays outside Team device storage and must survive lost cloud
+ * replies.
+ */
+@Entity
+@Table(name = "server_registration_state")
+@Getter
+@Setter
+public class ServerRegistrationState {
+ @Id private Long id = 1L;
+
+ @Version
+ @Column(nullable = false, columnDefinition = "bigint not null default 0")
+ private Long version;
+
+ @Column(nullable = false)
+ private UUID installationId;
+
+ @Column(nullable = false, length = 43)
+ private String registrationSecret;
+
+ @Column(nullable = false, length = 64)
+ private String proofHash;
+
+ private UUID registrationId;
+
+ @Enumerated(EnumType.STRING)
+ private ServerRegistrationProtocol.PurchaseMapping purchaseMapping;
+
+ @Column(nullable = false)
+ private long reportSequence;
+
+ private Instant lastSuccessAt;
+}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/serverregistration/ServerRegistrationStateRepository.java b/app/proprietary/src/main/java/stirling/software/proprietary/serverregistration/ServerRegistrationStateRepository.java
new file mode 100644
index 0000000000..f1f22e70f9
--- /dev/null
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/serverregistration/ServerRegistrationStateRepository.java
@@ -0,0 +1,17 @@
+package stirling.software.proprietary.serverregistration;
+
+import org.springframework.data.jpa.repository.JpaRepository;
+import org.springframework.data.jpa.repository.Lock;
+
+import jakarta.persistence.LockModeType;
+
+/**
+ * Local state only; this repository never accesses cloud registration or Team entitlement tables.
+ */
+public interface ServerRegistrationStateRepository
+ extends JpaRepository<ServerRegistrationState, Long> {
+ /** Serializes reservations and acknowledgements across reporters sharing the database. */
+ @Override
+ @Lock(LockModeType.PESSIMISTIC_WRITE)
+ java.util.Optional<ServerRegistrationState> findById(Long id);
+}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/serverregistration/ServerRegistrationStateStore.java b/app/proprietary/src/main/java/stirling/software/proprietary/serverregistration/ServerRegistrationStateStore.java
new file mode 100644
index 0000000000..17a61ed0e1
--- /dev/null
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/serverregistration/ServerRegistrationStateStore.java
@@ -0,0 +1,109 @@
+package stirling.software.proprietary.serverregistration;
+
+import java.nio.charset.StandardCharsets;
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
+import java.security.SecureRandom;
+import java.time.Instant;
+import java.util.Base64;
+import java.util.HexFormat;
+import java.util.UUID;
+
+import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
+import org.springframework.context.annotation.Profile;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Propagation;
+import org.springframework.transaction.annotation.Transactional;
+
+/** Commits the installation credential and reserved sequence before any outbound request. */
+@Service
+@Profile("!saas")
+@ConditionalOnProperty(name = "stirling.server-registration.enabled", havingValue = "true")
+public class ServerRegistrationStateStore {
+ private final ServerRegistrationStateRepository repository;
+ private final SecureRandom random = new SecureRandom();
+
+ public ServerRegistrationStateStore(ServerRegistrationStateRepository repository) {
+ this.repository = repository;
+ }
+
+ /**
+ * Called serially by the reporting service; failed sends burn a sequence without losing
+ * identity.
+ */
+ @Transactional(propagation = Propagation.REQUIRES_NEW)
+ public ServerRegistrationState reserve(String licenseProof) {
+ ServerRegistrationState state = repository.findById(1L).orElseGet(this::newState);
+ String hash = hash(licenseProof);
+ if (!hash.equals(state.getProofHash())) {
+ state.setProofHash(hash);
+ state.setRegistrationId(null);
+ state.setPurchaseMapping(null);
+ state.setLastSuccessAt(null);
+ }
+ state.setReportSequence(Math.incrementExact(state.getReportSequence()));
+ return repository.saveAndFlush(state);
+ }
+
+ /** A reply from an older reservation cannot attach to a replacement license. */
+ @Transactional(propagation = Propagation.REQUIRES_NEW)
+ public void acknowledge(
+ ServerRegistrationState sent, ServerRegistrationProtocol.Receipt receipt) {
+ ServerRegistrationState current = repository.findById(1L).orElseThrow();
+ if (current.getReportSequence() != sent.getReportSequence()
+ || !current.getProofHash().equals(sent.getProofHash())
+ || receipt.acceptedSequence() != sent.getReportSequence()
+ || (current.getRegistrationId() != null
+ && !current.getRegistrationId().equals(receipt.registrationId()))) {
+ return;
+ }
+ current.setRegistrationId(receipt.registrationId());
+ current.setPurchaseMapping(receipt.purchaseMapping());
+ current.setLastSuccessAt(Instant.now());
+ repository.saveAndFlush(current);
+ }
+
+ private ServerRegistrationState newState() {
+ ServerRegistrationState state = new ServerRegistrationState();
+ state.setInstallationId(UUID.randomUUID());
+ byte[] bytes = new byte[32];
+ random.nextBytes(bytes);
+ state.setRegistrationSecret(Base64.getUrlEncoder().withoutPadding().encodeToString(bytes));
+ return state;
+ }
+
+ /**
+ * Advances restored state to the authenticated cloud sequence without acknowledging old data. A
+ * concurrent reservation or identity change makes recovery inapplicable.
+ */
+ @Transactional(propagation = Propagation.REQUIRES_NEW)
+ public boolean reconcile(
+ ServerRegistrationState sent, ServerRegistrationProtocol.SequenceConflict conflict) {
+ ServerRegistrationState current = repository.findById(1L).orElseThrow();
+ if (current.getReportSequence() != sent.getReportSequence()
+ || !current.getProofHash().equals(sent.getProofHash())
+ || !current.getInstallationId().equals(sent.getInstallationId())
+ || !current.getRegistrationSecret().equals(sent.getRegistrationSecret())
+ || conflict.registrationId() == null
+ || conflict.acceptedSequence() < current.getReportSequence()
+ || conflict.acceptedSequence() == Long.MAX_VALUE
+ || (current.getRegistrationId() != null
+ && !current.getRegistrationId().equals(conflict.registrationId()))) {
+ return false;
+ }
+ current.setReportSequence(conflict.acceptedSequence());
+ repository.saveAndFlush(current);
+ return true;
+ }
+
+ private static String hash(String proof) {
+ try {
+ return HexFormat.of()
+ .formatHex(
+ MessageDigest.getInstance("SHA-256")
+ .digest(proof.getBytes(StandardCharsets.UTF_8)));
+ } catch (NoSuchAlgorithmException e) {
+ throw new IllegalStateException("SHA-256 unavailable", e);
+ }
+ }
+}
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/serverregistration/LegacyServerRegistrationServiceTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/serverregistration/LegacyServerRegistrationServiceTest.java
new file mode 100644
index 0000000000..772676f495
--- /dev/null
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/serverregistration/LegacyServerRegistrationServiceTest.java
@@ -0,0 +1,466 @@
+package stirling.software.proprietary.serverregistration;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.*;
+
+import java.io.IOException;
+import java.net.http.HttpTimeoutException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.time.Clock;
+import java.time.Duration;
+import java.time.Instant;
+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.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.CsvSource;
+import org.junit.jupiter.params.provider.ValueSource;
+import org.mockito.ArgumentCaptor;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.ObjectProvider;
+
+import stirling.software.common.model.ApplicationProperties;
+import stirling.software.proprietary.security.configuration.ee.KeygenLicenseVerifier.License;
+import stirling.software.proprietary.security.configuration.ee.LicenseKeyChecker;
+import stirling.software.proprietary.security.service.UserService;
+
+import ch.qos.logback.classic.Level;
+import ch.qos.logback.classic.Logger;
+import ch.qos.logback.classic.spi.ILoggingEvent;
+import ch.qos.logback.core.read.ListAppender;
+
+class LegacyServerRegistrationServiceTest {
+ private static final Instant NOW = Instant.parse("2026-11-16T12:00:00Z");
+ private final LicenseKeyChecker licenses = mock(LicenseKeyChecker.class);
+ private final UserService users = mock(UserService.class);
+ private final ServerRegistrationStateStore states = mock(ServerRegistrationStateStore.class);
+ private final ServerRegistrationClient client = mock(ServerRegistrationClient.class);
+ private final ApplicationProperties application = new ApplicationProperties();
+ private final ServerRegistrationProperties properties = new ServerRegistrationProperties();
+ private final Clock clock = mock(Clock.class);
+ private final Logger logger =
+ (Logger) LoggerFactory.getLogger(LegacyServerRegistrationService.class);
+ private final ListAppender<ILoggingEvent> logs = new ListAppender<>();
+ private Level previousLevel;
+ private LegacyServerRegistrationService service;
+ private ServerRegistrationState state;
+
+ @BeforeEach
+ @SuppressWarnings("unchecked")
+ void setup() {
+ when(clock.instant()).thenReturn(NOW);
+ previousLevel = logger.getLevel();
+ logger.setLevel(Level.INFO);
+ logs.start();
+ logger.addAppender(logs);
+ ObjectProvider<UserService> provider = mock(ObjectProvider.class);
+ when(provider.getIfAvailable()).thenReturn(users);
+ service =
+ new LegacyServerRegistrationService(
+ licenses,
+ application,
+ provider,
+ states,
+ client,
+ properties,
+ "test-version",
+ clock);
+ application.getPremium().setKey("test-license");
+ application.getPremium().setMaxUsers(0);
+ state = new ServerRegistrationState();
+ state.setInstallationId(UUID.randomUUID());
+ state.setRegistrationSecret("a".repeat(43));
+ state.setReportSequence(5);
+ }
+
+ @AfterEach
+ void restoreLogger() {
+ logger.detachAppender(logs);
+ logger.setLevel(previousLevel);
+ logs.stop();
+ }
+
+ @Test
+ void unlimitedLicenseReportsActualUsersWithoutChangingAllowance() throws Exception {
+ when(licenses.getLicenseKeyResult()).thenReturn(License.SERVER);
+ when(users.getTotalUsersCount()).thenReturn(147L);
+ when(states.reserve("test-license")).thenReturn(state);
+ var receipt =
+ new ServerRegistrationProtocol.Receipt(
+ UUID.randomUUID(),
+ 5,
+ ServerRegistrationProtocol.PurchaseMapping.UNRESOLVED);
+ when(client.register(any()))
+ .thenAnswer(
+ call -> {
+ var request =
+ call.getArgument(
+ 0,
+ ServerRegistrationProtocol.RegistrationRequest.class);
+ assertThat(request.report().reportedUserCount()).isEqualTo(147);
+ assertThat(request.report().sequence()).isEqualTo(5);
+ assertThat(request.installationId())
+ .isEqualTo(state.getInstallationId());
+ assertThat(request.licenseProof()).isEqualTo("test-license");
+ return receipt;
+ });
+ service.reportNow();
+ verify(states).acknowledge(state, receipt);
+ verify(licenses, only()).getLicenseKeyResult();
+ verify(client, never()).sync(any());
+ assertThat(application.getPremium().getMaxUsers()).isZero();
+ }
+
+ @Test
+ void validSignedFileIsSentAsProof(@TempDir Path directory) throws Exception {
+ Path proof = directory.resolve("license");
+ Files.writeString(proof, "signed-test-certificate");
+ application.getPremium().setKey("file:" + proof);
+ when(licenses.getLicenseKeyResult()).thenReturn(License.SERVER);
+ when(users.getTotalUsersCount()).thenReturn(0L);
+ when(states.reserve("signed-test-certificate")).thenReturn(state);
+ service.reportNow();
+ verify(client)
+ .register(
+ argThat(
+ request ->
+ request.licenseProof().equals("signed-test-certificate")
+ && request.report().reportedUserCount() == 0));
+ }
+
+ @Test
+ void linkedRegistrationUsesOnlyTrackingSecret() throws Exception {
+ state.setRegistrationId(UUID.randomUUID());
+ state.setPurchaseMapping(ServerRegistrationProtocol.PurchaseMapping.RESOLVED);
+ when(licenses.getLicenseKeyResult()).thenReturn(License.SERVER);
+ when(users.getTotalUsersCount()).thenReturn(200L);
+ when(states.reserve(any())).thenReturn(state);
+ service.reportNow();
+ verify(client)
+ .sync(
+ argThat(
+ request ->
+ request.registrationId().equals(state.getRegistrationId())
+ && request.report().reportedUserCount() == 200));
+ verify(client, never()).register(any());
+ }
+
+ @Test
+ void unresolvedPurchaseRetriesProofWithTheSameInstallationAndCredential() throws Exception {
+ state.setRegistrationId(UUID.randomUUID());
+ state.setPurchaseMapping(ServerRegistrationProtocol.PurchaseMapping.UNRESOLVED);
+ when(licenses.getLicenseKeyResult()).thenReturn(License.SERVER);
+ when(users.getTotalUsersCount()).thenReturn(200L);
+ when(states.reserve(any())).thenReturn(state);
+ service.reportNow();
+ verify(client)
+ .register(
+ argThat(
+ request ->
+ request.installationId().equals(state.getInstallationId())
+ && request.registrationSecret()
+ .equals(state.getRegistrationSecret())
+ && request.report().reportedUserCount() == 200));
+ verify(client, never()).sync(any());
+ }
+
+ @Test
+ void lostResponseDoesNotAcknowledgeOrTouchLicense() throws Exception {
+ when(licenses.getLicenseKeyResult()).thenReturn(License.SERVER);
+ when(users.getTotalUsersCount()).thenReturn(147L);
+ when(states.reserve(any())).thenReturn(state);
+ when(client.register(any())).thenThrow(new IOException("network unavailable"));
+ service.reportNow();
+ verify(states, never()).acknowledge(any(), any());
+ verify(licenses, only()).getLicenseKeyResult();
+ }
+
+ @Test
+ void recurringConflictRetriesOnlyOnceAndNeverAcknowledges() throws Exception {
+ when(licenses.getLicenseKeyResult()).thenReturn(License.SERVER);
+ when(users.getTotalUsersCount()).thenReturn(147L);
+ when(states.reserve(any())).thenReturn(state);
+ var conflict = new ServerRegistrationProtocol.SequenceConflict(UUID.randomUUID(), 100);
+ when(client.register(any()))
+ .thenThrow(new ServerRegistrationClient.SequenceConflictException(conflict));
+ when(states.reconcile(state, conflict)).thenReturn(true);
+ service.reportNow();
+ verify(client, times(2)).register(any());
+ verify(states).reconcile(state, conflict);
+ verify(states, never()).acknowledge(any(), any());
+ verify(licenses, only()).getLicenseKeyResult();
+ assertThat(logs.list)
+ .singleElement()
+ .satisfies(
+ event -> {
+ assertThat(event.getLevel()).isEqualTo(Level.WARN);
+ assertThat(event.getFormattedMessage())
+ .contains("recovering report sequence");
+ });
+ }
+
+ @Test
+ void recoveredConflictRetriesImmediatelyWithoutWarning() throws Exception {
+ prepareReport();
+ var conflict = new ServerRegistrationProtocol.SequenceConflict(UUID.randomUUID(), 100);
+ var receipt =
+ new ServerRegistrationProtocol.Receipt(
+ conflict.registrationId(),
+ 101,
+ ServerRegistrationProtocol.PurchaseMapping.RESOLVED);
+ when(client.register(any()))
+ .thenThrow(new ServerRegistrationClient.SequenceConflictException(conflict))
+ .thenReturn(receipt);
+ when(states.reconcile(state, conflict)).thenReturn(true);
+ service.reportNow();
+ verify(client, times(2)).register(any());
+ verify(states).acknowledge(state, receipt);
+ assertThat(logs.list).isEmpty();
+ }
+
+ @ParameterizedTest
+ @ValueSource(ints = {400, 401, 403, 404, 422})
+ void rejectedSyncWaitsADayAndKeepsIdentityWithFreshCounts(int status) throws Exception {
+ prepareReport();
+ properties.setSyncInterval(Duration.ofMinutes(1));
+ state.setRegistrationId(UUID.randomUUID());
+ state.setPurchaseMapping(ServerRegistrationProtocol.PurchaseMapping.RESOLVED);
+ when(users.getTotalUsersCount()).thenReturn(147L, 200L);
+ when(client.sync(any()))
+ .thenThrow(new ServerRegistrationClient.HttpFailureException(status, null));
+ service.reportNow();
+ service.reportNow();
+ when(clock.instant()).thenReturn(NOW.plus(Duration.ofDays(1)).minusNanos(1));
+ service.reportNow();
+ verify(client).sync(any());
+ when(clock.instant()).thenReturn(NOW.plus(Duration.ofDays(1)));
+ service.reportNow();
+ var requests = ArgumentCaptor.forClass(ServerRegistrationProtocol.SyncRequest.class);
+ verify(client, times(2)).sync(requests.capture());
+ assertThat(requests.getAllValues())
+ .allSatisfy(
+ request -> {
+ assertThat(request.registrationId())
+ .isEqualTo(state.getRegistrationId());
+ assertThat(request.registrationSecret())
+ .isEqualTo(state.getRegistrationSecret());
+ });
+ assertThat(requests.getAllValues())
+ .extracting(request -> request.report().reportedUserCount())
+ .containsExactly(147L, 200L);
+ verify(client, never()).register(any());
+ verify(states, never()).acknowledge(any(), any());
+ assertThat(logs.list)
+ .hasSize(2)
+ .allSatisfy(
+ event -> {
+ assertThat(event.getLevel()).isEqualTo(Level.WARN);
+ assertThat(event.getFormattedMessage())
+ .contains("HTTP " + status, "check registration configuration");
+ assertThat(event.getThrowableProxy()).isNull();
+ });
+ assertThat(application.getPremium().getKey()).isEqualTo("test-license");
+ assertThat(application.getPremium().getMaxUsers()).isZero();
+ }
+
+ @ParameterizedTest
+ @ValueSource(booleans = {false, true})
+ void transientFailuresBackOffToADayWithRateLimitedSecretSafeWarnings(boolean timeout)
+ throws Exception {
+ prepareReport();
+ properties.setSyncInterval(Duration.ofMinutes(1));
+ String sensitiveMessage = "test-license " + state.getRegistrationSecret();
+ when(client.register(any()))
+ .thenThrow(
+ timeout
+ ? new HttpTimeoutException(sensitiveMessage)
+ : new IOException(sensitiveMessage));
+ service.reportNow();
+ Instant now = NOW;
+ int attempts = 1;
+ for (int minutes : new int[] {15, 30, 60, 120, 240, 480, 960, 1440, 1440}) {
+ now = now.plus(Duration.ofMinutes(minutes));
+ when(clock.instant()).thenReturn(now.minusNanos(1));
+ service.reportNow();
+ verify(client, times(attempts)).register(any());
+ when(clock.instant()).thenReturn(now);
+ service.reportNow();
+ verify(client, times(++attempts)).register(any());
+ }
+ assertThat(logs.list)
+ .hasSize(4)
+ .allSatisfy(
+ event -> {
+ assertThat(event.getLevel()).isEqualTo(Level.WARN);
+ assertThat(event.getFormattedMessage())
+ .contains(
+ "registering with cloud",
+ timeout ? "request timed out" : "IOException",
+ "next attempt no earlier than")
+ .doesNotContain("test-license", state.getRegistrationSecret());
+ assertThat(event.getThrowableProxy()).isNull();
+ });
+ verify(states, never()).acknowledge(any(), any());
+ }
+
+ @ParameterizedTest
+ @CsvSource({
+ "408, 1, 15",
+ "425, 1, 15",
+ "429, 1, 15",
+ "500, 1, 15",
+ "503, 1, 15",
+ "503, 1440, 1440",
+ "503, 2880, 2880"
+ })
+ void transientHttpFailureRespectsBackoffAndNormalInterval(
+ int status, int intervalMinutes, int retryMinutes) throws Exception {
+ prepareReport();
+ properties.setSyncInterval(Duration.ofMinutes(intervalMinutes));
+ when(client.register(any()))
+ .thenThrow(new ServerRegistrationClient.HttpFailureException(status, null));
+ service.reportNow();
+ when(clock.instant()).thenReturn(NOW.plus(Duration.ofMinutes(retryMinutes)).minusNanos(1));
+ service.reportNow();
+ verify(client).register(any());
+ when(clock.instant()).thenReturn(NOW.plus(Duration.ofMinutes(retryMinutes)));
+ service.reportNow();
+ verify(client, times(2)).register(any());
+ }
+
+ @ParameterizedTest
+ @ValueSource(ints = {429, 503})
+ void serverRetryDeadlineCanExtendTheDailyCooldown(int status) throws Exception {
+ prepareReport();
+ Instant deadline = NOW.plus(Duration.ofDays(3));
+ when(client.register(any()))
+ .thenThrow(new ServerRegistrationClient.HttpFailureException(status, deadline));
+ service.reportNow();
+ when(clock.instant()).thenReturn(deadline.minusNanos(1));
+ service.reportNow();
+ verify(client).register(any());
+ when(clock.instant()).thenReturn(deadline);
+ service.reportNow();
+ verify(client, times(2)).register(any());
+ assertThat(logs.list.getFirst().getFormattedMessage()).contains(deadline.toString());
+ }
+
+ @Test
+ void successResetsBackoffAndLogsRecoveryOnlyOnce() throws Exception {
+ prepareReport();
+ properties.setSyncInterval(Duration.ofMinutes(1));
+ var receipt =
+ new ServerRegistrationProtocol.Receipt(
+ UUID.randomUUID(),
+ 5,
+ ServerRegistrationProtocol.PurchaseMapping.UNRESOLVED);
+ when(client.register(any()))
+ .thenThrow(new ServerRegistrationClient.HttpFailureException(401, null))
+ .thenReturn(receipt);
+ service.reportNow();
+ Instant recoveredAt = NOW.plus(Duration.ofDays(1));
+ when(clock.instant()).thenReturn(recoveredAt);
+ service.reportNow();
+ service.reportNow();
+ when(client.register(any())).thenThrow(new IOException("offline"));
+ when(clock.instant()).thenReturn(recoveredAt.plusSeconds(60));
+ service.reportNow();
+ when(clock.instant()).thenReturn(recoveredAt.plus(Duration.ofMinutes(16)).minusNanos(1));
+ service.reportNow();
+ verify(client, times(4)).register(any());
+ when(clock.instant()).thenReturn(recoveredAt.plus(Duration.ofMinutes(16)));
+ service.reportNow();
+ verify(client, times(5)).register(any());
+ assertThat(logs.list)
+ .extracting(ILoggingEvent::getLevel)
+ .containsExactly(Level.WARN, Level.INFO, Level.WARN);
+ assertThat(logs.list.get(1).getFormattedMessage()).contains("recovered");
+ }
+
+ @Test
+ void failureIsNotRetriedAfterLicenseBecomesEnterprise() throws Exception {
+ prepareReport();
+ when(client.register(any())).thenThrow(new IOException("offline"));
+ service.reportNow();
+ when(clock.instant()).thenReturn(NOW.plus(Duration.ofDays(1)));
+ when(licenses.getLicenseKeyResult()).thenReturn(License.ENTERPRISE);
+ service.reportNow();
+ verify(client).register(any());
+ }
+
+ @Test
+ void enterpriseAndTeamOnlyInstancesDoNotBootstrap() {
+ when(licenses.getLicenseKeyResult()).thenReturn(License.ENTERPRISE, License.NORMAL);
+ service.reportNow();
+ service.reportNow();
+ verifyNoInteractions(states, client, users);
+ }
+
+ @Test
+ void unknownOrInvalidCountNeverBecomesZero() {
+ when(licenses.getLicenseKeyResult()).thenReturn(License.SERVER);
+ when(users.getTotalUsersCount())
+ .thenThrow(new IllegalStateException("database unavailable: test-license"));
+ service.reportNow();
+ verifyNoInteractions(states, client);
+ assertThat(logs.list)
+ .singleElement()
+ .satisfies(
+ event -> {
+ assertThat(event.getLevel()).isEqualTo(Level.WARN);
+ assertThat(event.getFormattedMessage())
+ .contains("counting users", "IllegalStateException")
+ .doesNotContain("test-license");
+ assertThat(event.getThrowableProxy()).isNull();
+ });
+ }
+
+ @Test
+ void unreadableLicenseFileWarnsWithoutExposingItsPath(@TempDir Path directory) {
+ prepareReport();
+ application.getPremium().setKey("file:" + directory.resolve("private-license-key"));
+ service.reportNow();
+ verifyNoInteractions(states, client);
+ assertThat(logs.list)
+ .singleElement()
+ .satisfies(
+ event -> {
+ assertThat(event.getLevel()).isEqualTo(Level.WARN);
+ assertThat(event.getFormattedMessage())
+ .contains("reading license", "NoSuchFileException")
+ .doesNotContain(directory.toString(), "private-license-key");
+ assertThat(event.getThrowableProxy()).isNull();
+ });
+ }
+
+ @Test
+ void interruptionDoesNotProduceAnOutageWarning() throws Exception {
+ prepareReport();
+ when(client.register(any()))
+ .thenAnswer(
+ call -> {
+ Thread.currentThread().interrupt();
+ throw new IOException("interrupted");
+ });
+ try {
+ service.reportNow();
+ assertThat(Thread.currentThread().isInterrupted()).isTrue();
+ assertThat(logs.list).isEmpty();
+ verify(client).register(any());
+ verify(states, never()).acknowledge(any(), any());
+ } finally {
+ Thread.interrupted();
+ }
+ }
+
+ private void prepareReport() {
+ when(licenses.getLicenseKeyResult()).thenReturn(License.SERVER);
+ when(users.getTotalUsersCount()).thenReturn(147L);
+ when(states.reserve(any())).thenReturn(state);
+ }
+}
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/serverregistration/ServerRegistrationClientTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/serverregistration/ServerRegistrationClientTest.java
new file mode 100644
index 0000000000..2577a912de
--- /dev/null
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/serverregistration/ServerRegistrationClientTest.java
@@ -0,0 +1,312 @@
+package stirling.software.proprietary.serverregistration;
+
+import static org.assertj.core.api.Assertions.*;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.*;
+
+import java.io.IOException;
+import java.net.InetSocketAddress;
+import java.net.http.HttpClient;
+import java.net.http.HttpHeaders;
+import java.net.http.HttpResponse;
+import java.net.http.HttpTimeoutException;
+import java.time.Clock;
+import java.time.Instant;
+import java.time.ZoneOffset;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+import java.util.concurrent.CancellationException;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.stream.Stream;
+
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.Timeout;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.junit.jupiter.params.provider.ValueSource;
+
+import com.sun.net.httpserver.HttpServer;
+
+import jakarta.validation.Validation;
+
+import stirling.software.proprietary.accountlink.AccountLinkProperties;
+
+import tools.jackson.databind.ObjectMapper;
+
+class ServerRegistrationClientTest {
+ private static final Instant NOW = Instant.parse("2026-11-16T12:00:00Z");
+
+ @ParameterizedTest
+ @MethodSource("retryHeaders")
+ @SuppressWarnings("unchecked")
+ void httpFailuresCarrySafeStatusAndValidatedRetryDeadline(
+ int status, String retryAfter, Instant expectedDeadline) throws Exception {
+ var http = mock(HttpClient.class);
+ HttpResponse<String> response = mock(HttpResponse.class);
+ when(response.statusCode()).thenReturn(status);
+ when(response.headers())
+ .thenReturn(
+ HttpHeaders.of(
+ retryAfter == null
+ ? Map.of()
+ : Map.of("Retry-After", List.of(retryAfter)),
+ (name, value) -> true));
+ when(response.body()).thenReturn("sensitive-license-and-credential");
+ when(http.sendAsync(any(), any(HttpResponse.BodyHandler.class)))
+ .thenReturn(CompletableFuture.completedFuture(response));
+ var client =
+ new ServerRegistrationClient(
+ new AccountLinkProperties(),
+ new ObjectMapper(),
+ http,
+ Clock.fixed(NOW, ZoneOffset.UTC));
+ assertThatThrownBy(
+ () ->
+ client.sync(
+ new ServerRegistrationProtocol.SyncRequest(
+ UUID.randomUUID(),
+ "a".repeat(43),
+ new ServerRegistrationProtocol.Report(
+ 1L, 1L, "test", 1))))
+ .isInstanceOfSatisfying(
+ ServerRegistrationClient.HttpFailureException.class,
+ failure -> {
+ assertThat(failure.status()).isEqualTo(status);
+ assertThat(failure.retryNotBefore()).isEqualTo(expectedDeadline);
+ assertThat(failure.getCause()).isNull();
+ })
+ .hasMessage("Registration returned HTTP " + status)
+ .hasMessageNotContaining("sensitive-license-and-credential");
+ verify(response, never()).body();
+ }
+
+ private static Stream<Arguments> retryHeaders() {
+ return Stream.of(
+ Arguments.of(429, "120", NOW.plusSeconds(120)),
+ Arguments.of(503, "120", NOW.plusSeconds(120)),
+ Arguments.of(429, "0", NOW),
+ Arguments.of(429, "Mon, 16 Nov 2026 12:30:00 GMT", NOW.plusSeconds(1800)),
+ Arguments.of(503, "Mon, 16 Nov 2026 12:30:00 GMT", NOW.plusSeconds(1800)),
+ Arguments.of(503, "Sun, 15 Nov 2026 12:00:00 GMT", null),
+ Arguments.of(429, null, null),
+ Arguments.of(429, "", null),
+ Arguments.of(429, "-1", null),
+ Arguments.of(429, "1.5", null),
+ Arguments.of(503, "invalid-secret-value", null),
+ Arguments.of(429, "9999999999999999999999999", null),
+ Arguments.of(429, Long.toString(Long.MAX_VALUE), null),
+ Arguments.of(401, "120", null));
+ }
+
+ @Test
+ @Timeout(10)
+ @SuppressWarnings("unchecked")
+ void deadlineCancelsResponseThatStallsAfterHeaders() throws Exception {
+ var server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
+ var headersSent = new CountDownLatch(1);
+ server.createContext(
+ ServerRegistrationProtocol.PATH,
+ exchange -> {
+ exchange.getRequestBody().readAllBytes();
+ exchange.sendResponseHeaders(200, 100);
+ exchange.getResponseBody().write('{');
+ exchange.getResponseBody().flush();
+ headersSent.countDown();
+ });
+ server.start();
+ try (var realHttp = HttpClient.newHttpClient()) {
+ var http = mock(HttpClient.class);
+ var pending = new AtomicReference<CompletableFuture<HttpResponse<String>>>();
+ when(http.sendAsync(any(), any(HttpResponse.BodyHandler.class)))
+ .thenAnswer(
+ call -> {
+ var future =
+ realHttp.sendAsync(
+ call.getArgument(0),
+ HttpResponse.BodyHandlers.ofString());
+ pending.set(future);
+ return future;
+ });
+ var properties = new AccountLinkProperties();
+ properties.setSaasBaseUrl("http://127.0.0.1:" + server.getAddress().getPort());
+ properties.setRequestTimeoutSeconds(1);
+ var client = new ServerRegistrationClient(properties, new ObjectMapper(), http);
+ assertThatThrownBy(
+ () ->
+ client.sync(
+ new ServerRegistrationProtocol.SyncRequest(
+ UUID.randomUUID(),
+ "a".repeat(43),
+ new ServerRegistrationProtocol.Report(
+ 1L, 1L, "test", 1))))
+ .isInstanceOf(HttpTimeoutException.class);
+ assertThat(headersSent.getCount()).isZero();
+ assertThatThrownBy(() -> pending.get().get(1, TimeUnit.SECONDS))
+ .isInstanceOfAny(CancellationException.class, ExecutionException.class)
+ .satisfies(
+ failure ->
+ assertThat(
+ failure instanceof CancellationException
+ ? failure
+ : failure.getCause())
+ .isInstanceOf(CancellationException.class));
+ } finally {
+ server.stop(0);
+ }
+ }
+
+ @ParameterizedTest
+ @ValueSource(
+ strings = {
+ "null",
+ "{}",
+ "{\"registrationId\":\"not-a-uuid\",\"acceptedSequence\":100}"
+ })
+ @SuppressWarnings("unchecked")
+ void malformedConflictCannotReconcileState(String body) throws Exception {
+ var http = mock(HttpClient.class);
+ HttpResponse<String> response = mock(HttpResponse.class);
+ when(response.statusCode()).thenReturn(409);
+ when(response.body()).thenReturn(body);
+ when(http.sendAsync(any(), any(HttpResponse.BodyHandler.class)))
+ .thenReturn(CompletableFuture.completedFuture(response));
+ var client =
+ new ServerRegistrationClient(new AccountLinkProperties(), new ObjectMapper(), http);
+ assertThatThrownBy(
+ () ->
+ client.sync(
+ new ServerRegistrationProtocol.SyncRequest(
+ UUID.randomUUID(),
+ "a".repeat(43),
+ new ServerRegistrationProtocol.Report(
+ 1L, 1L, "test", 1))))
+ .isInstanceOf(IOException.class)
+ .isNotInstanceOf(ServerRegistrationClient.SequenceConflictException.class);
+ }
+
+ @Test
+ @SuppressWarnings("unchecked")
+ void interruptionCancelsOutstandingExchangeAndPreservesInterrupt() throws Exception {
+ var http = mock(HttpClient.class);
+ var pending = new CompletableFuture<HttpResponse<String>>();
+ when(http.sendAsync(any(), any(HttpResponse.BodyHandler.class))).thenReturn(pending);
+ var client =
+ new ServerRegistrationClient(new AccountLinkProperties(), new ObjectMapper(), http);
+ Thread.currentThread().interrupt();
+ try {
+ assertThatThrownBy(
+ () ->
+ client.sync(
+ new ServerRegistrationProtocol.SyncRequest(
+ UUID.randomUUID(),
+ "a".repeat(43),
+ new ServerRegistrationProtocol.Report(
+ 1L, 1L, "test", 1))))
+ .isInstanceOf(IOException.class)
+ .hasMessage("Registration interrupted");
+ assertThat(Thread.currentThread().isInterrupted()).isTrue();
+ assertThat(pending).isCancelled();
+ } finally {
+ Thread.interrupted();
+ }
+ }
+
+ @ParameterizedTest
+ @ValueSource(
+ strings = {
+ "http://remote.example",
+ "https://user:[email protected]",
+ "https://example.com?key=value"
+ })
+ void refusesUnsafeLicenseTransport(String url) {
+ var properties = new AccountLinkProperties();
+ properties.setSaasBaseUrl(url);
+ assertThatIllegalArgumentException()
+ .isThrownBy(
+ () ->
+ new ServerRegistrationClient(
+ properties, new ObjectMapper(), mock(HttpClient.class)));
+ }
+
+ @Test
+ @SuppressWarnings("unchecked")
+ void upstreamErrorsCannotLeakProofOrSecret() throws Exception {
+ var http = mock(HttpClient.class);
+ HttpResponse<String> response = mock(HttpResponse.class);
+ when(response.statusCode()).thenReturn(400);
+ when(response.body()).thenReturn("sensitive-license");
+ when(http.sendAsync(any(), any(HttpResponse.BodyHandler.class)))
+ .thenReturn(CompletableFuture.completedFuture(response));
+ var client =
+ new ServerRegistrationClient(new AccountLinkProperties(), new ObjectMapper(), http);
+ assertThatThrownBy(
+ () ->
+ client.sync(
+ new ServerRegistrationProtocol.SyncRequest(
+ UUID.randomUUID(),
+ "a".repeat(43),
+ new ServerRegistrationProtocol.Report(
+ 1L, 0L, "test", 1))))
+ .isInstanceOf(IOException.class)
+ .hasMessage("Registration returned HTTP 400");
+ verify(response, never()).body();
+ }
+
+ @Test
+ @SuppressWarnings("unchecked")
+ void nullResponseIsRejectedWithoutAcknowledging() throws Exception {
+ var http = mock(HttpClient.class);
+ HttpResponse<String> response = mock(HttpResponse.class);
+ when(response.statusCode()).thenReturn(200);
+ when(response.body()).thenReturn("null");
+ when(http.sendAsync(any(), any(HttpResponse.BodyHandler.class)))
+ .thenReturn(CompletableFuture.completedFuture(response));
+ var client =
+ new ServerRegistrationClient(new AccountLinkProperties(), new ObjectMapper(), http);
+ assertThatThrownBy(
+ () ->
+ client.sync(
+ new ServerRegistrationProtocol.SyncRequest(
+ UUID.randomUUID(),
+ "a".repeat(43),
+ new ServerRegistrationProtocol.Report(
+ 1L, 0L, "test", 1))))
+ .isInstanceOf(IOException.class)
+ .isInstanceOf(ServerRegistrationClient.InvalidResponseException.class)
+ .hasMessage("Invalid registration response");
+ }
+
+ @Test
+ void countsAndSequencesAreRequiredAndSecretsAreRedacted() {
+ try (var factory = Validation.buildDefaultValidatorFactory()) {
+ var validator = factory.getValidator();
+ assertThat(
+ validator.validate(
+ new ServerRegistrationProtocol.Report(1L, null, "test", 1)))
+ .isNotEmpty();
+ assertThat(validator.validate(new ServerRegistrationProtocol.Report(0L, 0L, "test", 1)))
+ .isNotEmpty();
+ assertThat(
+ validator.validate(
+ new ServerRegistrationProtocol.Report(1L, -1L, "test", 1)))
+ .isNotEmpty();
+ assertThat(validator.validate(new ServerRegistrationProtocol.Report(1L, 0L, "test", 1)))
+ .isEmpty();
+ var request =
+ new ServerRegistrationProtocol.RegistrationRequest(
+ UUID.randomUUID(),
+ "sensitive-license",
+ "fingerprint",
+ "a".repeat(43),
+ new ServerRegistrationProtocol.Report(1L, 147L, "test", 1));
+ assertThat(validator.validate(request)).isEmpty();
+ assertThat(request.toString()).doesNotContain("sensitive-license", "a".repeat(43));
+ }
+ }
+}
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/serverregistration/ServerRegistrationStateStoreDbTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/serverregistration/ServerRegistrationStateStoreDbTest.java
new file mode 100644
index 0000000000..e1184f2073
--- /dev/null
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/serverregistration/ServerRegistrationStateStoreDbTest.java
@@ -0,0 +1,333 @@
+package stirling.software.proprietary.serverregistration;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.Mockito.*;
+
+import java.net.InetSocketAddress;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.UUID;
+import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.Executors;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
+import org.springframework.beans.factory.ObjectProvider;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.SpringBootConfiguration;
+import org.springframework.boot.autoconfigure.AutoConfigurationPackage;
+import org.springframework.boot.data.jpa.test.autoconfigure.DataJpaTest;
+import org.springframework.context.annotation.Import;
+import org.springframework.dao.DataAccessException;
+import org.springframework.transaction.PlatformTransactionManager;
+import org.springframework.transaction.annotation.Propagation;
+import org.springframework.transaction.annotation.Transactional;
+import org.springframework.transaction.support.TransactionTemplate;
+
+import com.sun.net.httpserver.HttpServer;
+
+import stirling.software.common.model.ApplicationProperties;
+import stirling.software.proprietary.accountlink.AccountLinkProperties;
+import stirling.software.proprietary.security.configuration.ee.KeygenLicenseVerifier.License;
+import stirling.software.proprietary.security.configuration.ee.LicenseKeyChecker;
+import stirling.software.proprietary.security.service.UserService;
+
+import tools.jackson.databind.JsonNode;
+import tools.jackson.databind.ObjectMapper;
+
+@DataJpaTest(properties = "stirling.server-registration.enabled=true")
+@Import(ServerRegistrationStateStore.class)
+@Transactional(propagation = Propagation.NOT_SUPPORTED)
+class ServerRegistrationStateStoreDbTest {
+ @Autowired private ServerRegistrationStateStore store;
+ @Autowired private ServerRegistrationStateRepository repository;
+ @Autowired private PlatformTransactionManager transactionManager;
+
+ @BeforeEach
+ void clearState() {
+ repository.deleteAllInBatch();
+ }
+
+ @Test
+ void concurrentInitialReservationsCannotReplaceIdentityOrReuseSequences() throws Exception {
+ CountDownLatch ready = new CountDownLatch(2);
+ CountDownLatch start = new CountDownLatch(1);
+ List<ServerRegistrationState> reserved = new ArrayList<>();
+ try (var executor = Executors.newFixedThreadPool(2)) {
+ var action =
+ (java.util.concurrent.Callable<ServerRegistrationState>)
+ () -> {
+ ready.countDown();
+ assertThat(start.await(10, TimeUnit.SECONDS)).isTrue();
+ try {
+ return store.reserve("proof");
+ } catch (DataAccessException concurrentInitialization) {
+ return store.reserve("proof");
+ }
+ };
+ var first = executor.submit(action);
+ var second = executor.submit(action);
+ assertThat(ready.await(10, TimeUnit.SECONDS)).isTrue();
+ start.countDown();
+ reserved.add(first.get(20, TimeUnit.SECONDS));
+ reserved.add(second.get(20, TimeUnit.SECONDS));
+ }
+ var restored = store.reserve("proof");
+ assertThat(reserved)
+ .extracting(ServerRegistrationState::getInstallationId)
+ .containsOnly(restored.getInstallationId());
+ assertThat(reserved)
+ .extracting(ServerRegistrationState::getRegistrationSecret)
+ .containsOnly(restored.getRegistrationSecret());
+ assertThat(reserved)
+ .extracting(ServerRegistrationState::getReportSequence)
+ .containsExactlyInAnyOrder(1L, 2L);
+ assertThat(restored.getReportSequence()).isEqualTo(3);
+ assertThat(repository.count()).isEqualTo(1);
+ }
+
+ @Test
+ @SuppressWarnings("unchecked")
+ void reporterRetriesOfflineAndUnresolvedReportsAcrossRestartsWithoutChangingAllowance()
+ throws Exception {
+ var mapper = new ObjectMapper();
+ var requests = new CopyOnWriteArrayList<JsonNode>();
+ var paths = new CopyOnWriteArrayList<String>();
+ var responseNumber = new AtomicInteger();
+ UUID registrationId = UUID.randomUUID();
+ HttpServer cloud = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
+ cloud.createContext(
+ ServerRegistrationProtocol.PATH,
+ exchange -> {
+ JsonNode body = mapper.readTree(exchange.getRequestBody().readAllBytes());
+ requests.add(body);
+ paths.add(exchange.getRequestURI().getPath());
+ int attempt = responseNumber.incrementAndGet();
+ byte[] response =
+ attempt == 1
+ ? new byte[0]
+ : mapper.writeValueAsBytes(
+ new ServerRegistrationProtocol.Receipt(
+ registrationId,
+ body.path("report").path("sequence").asLong(),
+ attempt == 2
+ ? ServerRegistrationProtocol
+ .PurchaseMapping.UNRESOLVED
+ : ServerRegistrationProtocol
+ .PurchaseMapping.RESOLVED));
+ exchange.sendResponseHeaders(attempt == 1 ? 503 : 200, response.length);
+ exchange.getResponseBody().write(response);
+ exchange.close();
+ });
+ cloud.start();
+ try {
+ var application = new ApplicationProperties();
+ application.getPremium().setKey("test-license");
+ application.getPremium().setMaxUsers(100);
+ var licenses = mock(LicenseKeyChecker.class);
+ when(licenses.getLicenseKeyResult()).thenReturn(License.SERVER);
+ var users = mock(UserService.class);
+ when(users.getTotalUsersCount()).thenReturn(100L, 150L, 200L, 201L);
+ ObjectProvider<UserService> provider = mock(ObjectProvider.class);
+ when(provider.getIfAvailable()).thenReturn(users);
+ var properties = new AccountLinkProperties();
+ properties.setSaasBaseUrl("http://127.0.0.1:" + cloud.getAddress().getPort());
+ for (int attempt = 0; attempt < 4; attempt++) {
+ new LegacyServerRegistrationService(
+ licenses,
+ application,
+ provider,
+ store,
+ new ServerRegistrationClient(properties, mapper),
+ new ServerRegistrationProperties(),
+ "test-version")
+ .reportNow();
+ }
+ assertThat(paths)
+ .containsExactly(
+ ServerRegistrationProtocol.PATH,
+ ServerRegistrationProtocol.PATH,
+ ServerRegistrationProtocol.PATH,
+ ServerRegistrationProtocol.PATH + "/sync");
+ assertThat(requests)
+ .extracting(r -> r.at("/report/sequence").asLong())
+ .containsExactly(1L, 2L, 3L, 4L);
+ assertThat(requests)
+ .extracting(r -> r.at("/report/reportedUserCount").asLong())
+ .containsExactly(100L, 150L, 200L, 201L);
+ assertThat(requests.subList(0, 3))
+ .extracting(r -> r.path("installationId").asText())
+ .containsOnly(requests.getFirst().path("installationId").asText());
+ assertThat(requests)
+ .extracting(r -> r.path("registrationSecret").asText())
+ .containsOnly(requests.getFirst().path("registrationSecret").asText());
+ assertThat(requests.get(3).has("licenseProof")).isFalse();
+ assertThat(requests.get(3).path("registrationId").asText())
+ .isEqualTo(registrationId.toString());
+ assertThat(application.getPremium().getMaxUsers()).isEqualTo(100);
+ assertThat(repository.count()).isEqualTo(1);
+ verify(licenses, times(4)).getLicenseKeyResult();
+ verifyNoMoreInteractions(licenses);
+ } finally {
+ cloud.stop(0);
+ }
+ }
+
+ @Test
+ void failedOuterWorkCannotRollBackTheCredentialOrReservedSequence() {
+ var caller = new TransactionTemplate(transactionManager);
+ var first =
+ caller.execute(
+ status -> {
+ var state = store.reserve("proof");
+ status.setRollbackOnly();
+ return state;
+ });
+ var second = store.reserve("proof");
+ assertThat(second.getInstallationId()).isEqualTo(first.getInstallationId());
+ assertThat(second.getRegistrationSecret()).isEqualTo(first.getRegistrationSecret());
+ assertThat(second.getReportSequence()).isEqualTo(first.getReportSequence() + 1);
+ UUID registration = UUID.randomUUID();
+ store.acknowledge(
+ second,
+ new ServerRegistrationProtocol.Receipt(
+ registration,
+ second.getReportSequence(),
+ ServerRegistrationProtocol.PurchaseMapping.RESOLVED));
+ var restored = store.reserve("proof");
+ assertThat(restored.getRegistrationId()).isEqualTo(registration);
+ assertThat(restored.getPurchaseMapping())
+ .isEqualTo(ServerRegistrationProtocol.PurchaseMapping.RESOLVED);
+ assertThat(restored.getLastSuccessAt()).isNotNull();
+ assertThat(repository.count()).isEqualTo(1);
+ }
+
+ @ParameterizedTest
+ @ValueSource(booleans = {false, true})
+ @SuppressWarnings("unchecked")
+ void restoredReporterRecoversImmediatelyWithFreshCountAndSameIdentity(boolean linked)
+ throws Exception {
+ var original = store.reserve("test-license");
+ UUID registrationId = UUID.randomUUID();
+ if (linked) {
+ store.acknowledge(
+ original,
+ new ServerRegistrationProtocol.Receipt(
+ registrationId,
+ original.getReportSequence(),
+ ServerRegistrationProtocol.PurchaseMapping.RESOLVED));
+ }
+ var transaction = new TransactionTemplate(transactionManager);
+ transaction.executeWithoutResult(
+ status -> {
+ var restored = repository.findById(1L).orElseThrow();
+ restored.setReportSequence(10);
+ repository.saveAndFlush(restored);
+ });
+ var mapper = new ObjectMapper();
+ var requests = new CopyOnWriteArrayList<JsonNode>();
+ var paths = new CopyOnWriteArrayList<String>();
+ var cloud = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
+ cloud.createContext(
+ ServerRegistrationProtocol.PATH,
+ exchange -> {
+ var body = mapper.readTree(exchange.getRequestBody().readAllBytes());
+ requests.add(body);
+ paths.add(exchange.getRequestURI().getPath());
+ boolean stale = body.at("/report/sequence").asLong() <= 100;
+ byte[] response =
+ mapper.writeValueAsBytes(
+ stale
+ ? new ServerRegistrationProtocol.SequenceConflict(
+ registrationId, 100)
+ : new ServerRegistrationProtocol.Receipt(
+ registrationId,
+ 101,
+ ServerRegistrationProtocol.PurchaseMapping
+ .RESOLVED));
+ exchange.sendResponseHeaders(stale ? 409 : 200, response.length);
+ exchange.getResponseBody().write(response);
+ exchange.close();
+ });
+ cloud.start();
+ try {
+ var licenses = mock(LicenseKeyChecker.class);
+ when(licenses.getLicenseKeyResult()).thenReturn(License.SERVER);
+ var users = mock(UserService.class);
+ when(users.getTotalUsersCount()).thenReturn(200L, 201L);
+ ObjectProvider<UserService> provider = mock(ObjectProvider.class);
+ when(provider.getIfAvailable()).thenReturn(users);
+ var application = new ApplicationProperties();
+ application.getPremium().setKey("test-license");
+ application.getPremium().setMaxUsers(100);
+ var properties = new AccountLinkProperties();
+ properties.setSaasBaseUrl("http://127.0.0.1:" + cloud.getAddress().getPort());
+ new LegacyServerRegistrationService(
+ licenses,
+ application,
+ provider,
+ store,
+ new ServerRegistrationClient(properties, mapper),
+ new ServerRegistrationProperties(),
+ "test-version")
+ .reportNow();
+ assertThat(requests)
+ .extracting(r -> r.at("/report/sequence").asLong())
+ .containsExactly(11L, 101L);
+ assertThat(requests)
+ .extracting(r -> r.at("/report/reportedUserCount").asLong())
+ .containsExactly(200L, 201L);
+ assertThat(requests)
+ .extracting(r -> r.path("registrationSecret").asText())
+ .containsOnly(original.getRegistrationSecret());
+ assertThat(paths)
+ .containsOnly(ServerRegistrationProtocol.PATH + (linked ? "/sync" : ""));
+ var current = transaction.execute(status -> repository.findById(1L).orElseThrow());
+ assertThat(current.getReportSequence()).isEqualTo(101);
+ assertThat(current.getRegistrationId()).isEqualTo(registrationId);
+ assertThat(current.getInstallationId()).isEqualTo(original.getInstallationId());
+ assertThat(current.getLastSuccessAt()).isNotNull();
+ assertThat(application.getPremium().getMaxUsers()).isEqualTo(100);
+ assertThat(repository.count()).isEqualTo(1);
+ } finally {
+ cloud.stop(0);
+ }
+ }
+
+ @ParameterizedTest
+ @ValueSource(
+ strings = {"licenseChanged", "reservedAgain", "foreignId", "olderSequence", "overflow"})
+ void recoveryCannotApplyToChangedStateOrUnrelatedSequence(String change) {
+ var sent = store.reserve("proof");
+ UUID registration = UUID.randomUUID();
+ store.acknowledge(
+ sent,
+ new ServerRegistrationProtocol.Receipt(
+ registration,
+ sent.getReportSequence(),
+ ServerRegistrationProtocol.PurchaseMapping.RESOLVED));
+ if (change.equals("licenseChanged")) store.reserve("replacement");
+ if (change.equals("reservedAgain")) store.reserve("proof");
+ long sequence =
+ switch (change) {
+ case "olderSequence" -> 0;
+ case "overflow" -> Long.MAX_VALUE;
+ default -> 100;
+ };
+ UUID id = change.equals("foreignId") ? UUID.randomUUID() : registration;
+ assertThat(
+ store.reconcile(
+ sent,
+ new ServerRegistrationProtocol.SequenceConflict(id, sequence)))
+ .isFalse();
+ }
+
+ @SpringBootConfiguration
+ @AutoConfigurationPackage(basePackages = "stirling.software.proprietary.serverregistration")
+ static class TestApp {}
+}
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/serverregistration/ServerRegistrationStateStoreTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/serverregistration/ServerRegistrationStateStoreTest.java
new file mode 100644
index 0000000000..8bcec7379d
--- /dev/null
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/serverregistration/ServerRegistrationStateStoreTest.java
@@ -0,0 +1,83 @@
+package stirling.software.proprietary.serverregistration;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.*;
+
+import java.util.Optional;
+import java.util.UUID;
+import java.util.concurrent.atomic.AtomicReference;
+
+import org.junit.jupiter.api.Test;
+
+class ServerRegistrationStateStoreTest {
+ @Test
+ void restartAndProofRenewalRetainBootstrapSecretAndMonotonicSequence() {
+ var repository = mock(ServerRegistrationStateRepository.class);
+ AtomicReference<ServerRegistrationState> saved = new AtomicReference<>();
+ when(repository.findById(1L)).thenAnswer(call -> Optional.ofNullable(saved.get()));
+ when(repository.saveAndFlush(any()))
+ .thenAnswer(
+ call -> {
+ var state = call.getArgument(0, ServerRegistrationState.class);
+ saved.set(state);
+ return state;
+ });
+ var first = new ServerRegistrationStateStore(repository).reserve("old-proof");
+ String secret = first.getRegistrationSecret();
+ UUID installation = first.getInstallationId();
+ assertThat(secret).hasSize(43);
+ assertThat(first.getReportSequence()).isEqualTo(1);
+ var restarted = new ServerRegistrationStateStore(repository);
+ var second = restarted.reserve("old-proof");
+ assertThat(second.getReportSequence()).isEqualTo(2);
+ UUID registration = UUID.randomUUID();
+ restarted.acknowledge(
+ second,
+ new ServerRegistrationProtocol.Receipt(
+ registration, 2, ServerRegistrationProtocol.PurchaseMapping.RESOLVED));
+ var replacement = restarted.reserve("renewed-proof");
+ assertThat(replacement.getRegistrationId()).isNull();
+ assertThat(replacement.getInstallationId()).isEqualTo(installation);
+ assertThat(replacement.getRegistrationSecret()).isEqualTo(secret);
+ assertThat(replacement.getReportSequence()).isEqualTo(3);
+ }
+
+ @Test
+ void receiptCannotReplaceAnExistingRegistrationId() {
+ var repository = mock(ServerRegistrationStateRepository.class);
+ var state = new ServerRegistrationState();
+ state.setProofHash("proof");
+ state.setReportSequence(3);
+ state.setRegistrationId(UUID.randomUUID());
+ when(repository.findById(1L)).thenReturn(Optional.of(state));
+ new ServerRegistrationStateStore(repository)
+ .acknowledge(
+ state,
+ new ServerRegistrationProtocol.Receipt(
+ UUID.randomUUID(),
+ 3,
+ ServerRegistrationProtocol.PurchaseMapping.RESOLVED));
+ verify(repository, never()).saveAndFlush(any());
+ }
+
+ @Test
+ void staleAcknowledgementDoesNotBindReplacementLicense() {
+ var repository = mock(ServerRegistrationStateRepository.class);
+ var current = new ServerRegistrationState();
+ current.setProofHash("new");
+ current.setReportSequence(3);
+ when(repository.findById(1L)).thenReturn(Optional.of(current));
+ var old = new ServerRegistrationState();
+ old.setProofHash("old");
+ old.setReportSequence(2);
+ new ServerRegistrationStateStore(repository)
+ .acknowledge(
+ old,
+ new ServerRegistrationProtocol.Receipt(
+ UUID.randomUUID(),
+ 2,
+ ServerRegistrationProtocol.PurchaseMapping.RESOLVED));
+ verify(repository, never()).saveAndFlush(any());
+ }
+}
diff --git a/app/saas/build.gradle b/app/saas/build.gradle
index 93062d13d2..4f38ea6a7d 100644
--- a/app/saas/build.gradle
+++ b/app/saas/build.gradle
@@ -19,4 +19,6 @@ dependencies {
testImplementation 'org.springframework.boot:spring-boot-starter-data-jpa-test'
testImplementation "com.tngtech.archunit:archunit-junit5:${archunitVersion}"
+ testImplementation "org.testcontainers:postgresql:$testcontainersMinioVersion"
+ testImplementation "org.testcontainers:junit-jupiter:$testcontainersMinioVersion"
}
diff --git a/app/saas/src/main/java/stirling/software/saas/config/SaasSchemaOwnership.java b/app/saas/src/main/java/stirling/software/saas/config/SaasSchemaOwnership.java
index 622146f474..f077aec628 100644
--- a/app/saas/src/main/java/stirling/software/saas/config/SaasSchemaOwnership.java
+++ b/app/saas/src/main/java/stirling/software/saas/config/SaasSchemaOwnership.java
@@ -65,6 +65,7 @@ public final class SaasSchemaOwnership {
"procurement_quote",
"saas_team_extensions",
"saas_user_extensions",
+ "server_license_registrations",
"sessions",
"team_invitations",
"team_memberships",
@@ -106,6 +107,7 @@ public final class SaasSchemaOwnership {
"policy_source_doc_totals",
"policy_sources",
"resource_grants",
+ "server_registration_state",
"storage_cleanup_entries",
"stored_file_blobs",
"stored_files",
diff --git a/app/saas/src/main/java/stirling/software/saas/security/SupabaseSecurityConfig.java b/app/saas/src/main/java/stirling/software/saas/security/SupabaseSecurityConfig.java
index ce0064135a..d4f884599a 100644
--- a/app/saas/src/main/java/stirling/software/saas/security/SupabaseSecurityConfig.java
+++ b/app/saas/src/main/java/stirling/software/saas/security/SupabaseSecurityConfig.java
@@ -127,6 +127,14 @@ public class SupabaseSecurityConfig {
"/api/v1/account-link/connect/request",
"/api/v1/account-link/connect/claim")
.permitAll()
+ // These tracking endpoints verify a license proof or a
+ // scoped registration secret without creating a user
+ // session.
+ .requestMatchers(
+ HttpMethod.POST,
+ "/api/v1/server-license/registrations",
+ "/api/v1/server-license/registrations/sync")
+ .permitAll()
// Static legal documents, read before agreeing to them,
// which can be before the reader has an account.
.requestMatchers(HttpMethod.GET, "/api/v1/legal/*")
diff --git a/app/saas/src/main/java/stirling/software/saas/serverregistration/KeygenServerLicenseVerifier.java b/app/saas/src/main/java/stirling/software/saas/serverregistration/KeygenServerLicenseVerifier.java
new file mode 100644
index 0000000000..4c41b5f861
--- /dev/null
+++ b/app/saas/src/main/java/stirling/software/saas/serverregistration/KeygenServerLicenseVerifier.java
@@ -0,0 +1,295 @@
+package stirling.software.saas.serverregistration;
+
+import java.io.IOException;
+import java.net.URI;
+import java.net.URLEncoder;
+import java.net.http.HttpClient;
+import java.net.http.HttpRequest;
+import java.net.http.HttpResponse;
+import java.nio.charset.StandardCharsets;
+import java.security.KeyFactory;
+import java.security.MessageDigest;
+import java.security.Signature;
+import java.security.spec.X509EncodedKeySpec;
+import java.time.Clock;
+import java.time.Duration;
+import java.time.Instant;
+import java.util.Base64;
+import java.util.HexFormat;
+import java.util.Map;
+import java.util.UUID;
+
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
+import org.springframework.context.annotation.Profile;
+import org.springframework.http.HttpStatus;
+import org.springframework.stereotype.Service;
+import org.springframework.web.server.ResponseStatusException;
+
+import stirling.software.proprietary.serverregistration.RegistrationHttpTransport;
+import stirling.software.saas.procurement.config.KeygenConfigurationProperties;
+
+import tools.jackson.databind.JsonNode;
+import tools.jackson.databind.ObjectMapper;
+
+/**
+ * Verifies proof and live validity without activating machines, renewing licenses or changing
+ * capacity.
+ */
+@Service
+@Profile("saas")
+@ConditionalOnProperty(name = "stirling.server-registration.enabled", havingValue = "true")
+public class KeygenServerLicenseVerifier {
+ private static final String BEGIN = "-----BEGIN LICENSE FILE-----";
+ private static final String END = "-----END LICENSE FILE-----";
+ private static final Duration REQUEST_TIMEOUT = Duration.ofSeconds(10);
+ private final KeygenConfigurationProperties keygen;
+ private final ServerRegistrationCloudProperties properties;
+ private final ObjectMapper mapper;
+ private final HttpClient http;
+ private final Clock clock;
+ private final java.security.PublicKey licensePublicKey;
+ private volatile UUID canonicalAccountId;
+
+ @Autowired
+ public KeygenServerLicenseVerifier(
+ KeygenConfigurationProperties keygen,
+ ServerRegistrationCloudProperties properties,
+ ObjectMapper mapper) {
+ this(
+ keygen,
+ properties,
+ mapper,
+ HttpClient.newBuilder()
+ .connectTimeout(Duration.ofSeconds(10))
+ .followRedirects(HttpClient.Redirect.NEVER)
+ .build(),
+ Clock.systemUTC());
+ }
+
+ KeygenServerLicenseVerifier(
+ KeygenConfigurationProperties keygen,
+ ServerRegistrationCloudProperties properties,
+ ObjectMapper mapper,
+ HttpClient http,
+ Clock clock) {
+ this.keygen = keygen;
+ this.properties = properties;
+ this.mapper = mapper;
+ this.http = http;
+ this.clock = clock;
+ if (keygen.getAccountId() == null
+ || keygen.getAccountId().isBlank()
+ || keygen.getApiToken() == null
+ || keygen.getApiToken().isBlank()
+ || properties.getServerProductIds().isEmpty()) {
+ throw new IllegalStateException(
+ "Server registration needs Keygen credentials and an explicit Server product allowlist");
+ }
+ try {
+ UUID accountId = UUID.fromString(keygen.getAccountId());
+ if (accountId.toString().equalsIgnoreCase(keygen.getAccountId())) {
+ canonicalAccountId = accountId;
+ }
+ } catch (IllegalArgumentException ignored) {
+ // Slugs need a live account lookup; startup must not depend on Keygen availability.
+ }
+ try {
+ byte[] rawKey = HexFormat.of().parseHex(properties.getLicensePublicKey());
+ if (rawKey.length != 32) throw new IllegalArgumentException();
+ byte[] encodedKey = new byte[44];
+ System.arraycopy(
+ HexFormat.of().parseHex("302a300506032b6570032100"), 0, encodedKey, 0, 12);
+ System.arraycopy(rawKey, 0, encodedKey, 12, 32);
+ licensePublicKey =
+ KeyFactory.getInstance("Ed25519")
+ .generatePublic(new X509EncodedKeySpec(encodedKey));
+ } catch (Exception e) {
+ throw new IllegalStateException(
+ "Server registration needs the account's 32-byte Ed25519 license public key in hexadecimal");
+ }
+ }
+
+ /**
+ * Raw key is transient purchase-lookup material and must never be logged or copied into
+ * registration storage.
+ */
+ public record VerifiedLicense(UUID id, String key, Integer userLimit) {
+ @Override
+ public String toString() {
+ return "VerifiedLicense[id=" + id + ", key=REDACTED]";
+ }
+ }
+
+ /**
+ * A signed file proves possession; live validation is still mandatory for revocation and
+ * expiry.
+ */
+ public VerifiedLicense verify(String proof, String fingerprint) {
+ try {
+ boolean certificate = proof.strip().startsWith(BEGIN);
+ UUID certificateId = certificate ? certificateId(proof.strip()) : null;
+ UUID expectedAccountId = accountId();
+ Map<String, Object> scope = Map.of("fingerprint", fingerprint);
+ Map<String, Object> meta =
+ certificate ? Map.of("scope", scope) : Map.of("key", proof, "scope", scope);
+ String endpoint =
+ certificate
+ ? "/licenses/" + certificateId + "/actions/validate"
+ : "/licenses/actions/validate-key";
+ HttpRequest request =
+ request(endpoint)
+ .POST(
+ HttpRequest.BodyPublishers.ofString(
+ mapper.writeValueAsString(Map.of("meta", meta))))
+ .build();
+ HttpResponse<String> response =
+ RegistrationHttpTransport.send(http, request, REQUEST_TIMEOUT);
+ if (response.statusCode() == 429 || response.statusCode() >= 500) {
+ throw unavailable();
+ }
+ if (response.statusCode() != 200) throw denied();
+ JsonNode body = mapper.readTree(response.body());
+ JsonNode valid = body.path("meta").path("valid");
+ if (!valid.isBoolean() || !valid.asBoolean()) throw denied();
+ JsonNode license = body.path("data");
+ UUID id = UUID.fromString(license.path("id").asText());
+ JsonNode attrs = license.path("attributes");
+ JsonNode metadata = attrs.path("metadata");
+ String product = license.at("/relationships/product/data/id").asText();
+ String account = license.at("/relationships/account/data/id").asText();
+ String key = attrs.path("key").asText("");
+ if (!"licenses".equals(license.path("type").asText())
+ || !expectedAccountId.equals(UUID.fromString(account))
+ || !properties.getServerProductIds().contains(product)
+ || attrs.path("suspended").asBoolean(false)
+ || key.isBlank()
+ || (certificate && !id.equals(certificateId))
+ || (!certificate
+ && !MessageDigest.isEqual(
+ key.getBytes(StandardCharsets.UTF_8),
+ proof.getBytes(StandardCharsets.UTF_8)))) {
+ throw denied();
+ }
+ requireServerMetadata(metadata);
+ return new VerifiedLicense(id, key, userLimit(metadata.path("users")));
+ } catch (ResponseStatusException e) {
+ throw e;
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ throw unavailable();
+ } catch (IOException e) {
+ throw unavailable();
+ } catch (Exception e) {
+ throw denied();
+ }
+ }
+
+ private void requireServerMetadata(JsonNode metadata) {
+ boolean server = false;
+ JsonNode enterprise = metadata.path("isEnterprise");
+ if (!enterprise.isMissingNode() && !enterprise.isNull()) {
+ if (!(enterprise.isBoolean() && !enterprise.asBoolean())
+ && !(enterprise.isString()
+ && "false".equalsIgnoreCase(enterprise.asText().strip()))) {
+ throw denied();
+ }
+ server = true;
+ }
+ for (String field : new String[] {"planType", "plan_type"}) {
+ JsonNode plan = metadata.path(field);
+ if (plan.isMissingNode()
+ || plan.isNull()
+ || (plan.isString() && plan.asText().isBlank())) continue;
+ if (!plan.isString() || !"server".equalsIgnoreCase(plan.asText().strip()))
+ throw denied();
+ server = true;
+ }
+ if (!server) throw denied();
+ }
+
+ private Integer userLimit(JsonNode limit) {
+ // Allowance metadata is observational; unknown must not become the unlimited sentinel.
+ if (limit.isIntegralNumber() && limit.canConvertToInt()) {
+ return limit.asInt() >= 0 ? limit.asInt() : null;
+ }
+ if (limit.isString()) {
+ try {
+ int value = Integer.parseInt(limit.asText().strip());
+ return value >= 0 ? value : null;
+ } catch (NumberFormatException ignored) {
+ return null;
+ }
+ }
+ return null;
+ }
+
+ private UUID certificateId(String proof) throws Exception {
+ if (!proof.endsWith(END)) throw denied();
+ String envelope =
+ proof.substring(BEGIN.length(), proof.length() - END.length())
+ .replaceAll("\\s", "");
+ JsonNode signed = mapper.readTree(Base64.getDecoder().decode(envelope));
+ if (!"base64+ed25519".equals(signed.path("alg").asText())) throw denied();
+ String encoded = signed.path("enc").asText();
+ Signature signature = Signature.getInstance("Ed25519");
+ signature.initVerify(licensePublicKey);
+ signature.update(("license/" + encoded).getBytes(StandardCharsets.UTF_8));
+ if (!signature.verify(Base64.getDecoder().decode(signed.path("sig").asText())))
+ throw denied();
+ JsonNode snapshot = mapper.readTree(Base64.getDecoder().decode(encoded));
+ Instant issued = Instant.parse(snapshot.path("meta").path("issued").asText());
+ JsonNode expiry = snapshot.path("meta").path("expiry");
+ Instant now = clock.instant();
+ if (issued.isAfter(now)
+ || (!expiry.isNull() && !Instant.parse(expiry.asText()).isAfter(now)))
+ throw denied();
+ if (!"licenses".equals(snapshot.path("data").path("type").asText())) throw denied();
+ return UUID.fromString(snapshot.path("data").path("id").asText());
+ }
+
+ private UUID accountId() throws IOException, InterruptedException {
+ UUID cached = canonicalAccountId;
+ if (cached != null) return cached;
+ HttpResponse<String> response =
+ RegistrationHttpTransport.send(http, request("").GET().build(), REQUEST_TIMEOUT);
+ if (response.statusCode() != 200) throw unavailable();
+ try {
+ JsonNode account = mapper.readTree(response.body()).path("data");
+ if (!"accounts".equals(account.path("type").asText())
+ || !keygen.getAccountId()
+ .equals(account.path("attributes").path("slug").asText())) {
+ throw unavailable();
+ }
+ UUID resolved = UUID.fromString(account.path("id").asText());
+ canonicalAccountId = resolved;
+ return resolved;
+ } catch (RuntimeException e) {
+ throw unavailable();
+ }
+ }
+
+ private HttpRequest.Builder request(String endpoint) {
+ URI uri =
+ URI.create(
+ keygen.getApiBase().replaceAll("/+$", "")
+ + "/accounts/"
+ + URLEncoder.encode(keygen.getAccountId(), StandardCharsets.UTF_8)
+ + endpoint);
+ return HttpRequest.newBuilder(uri)
+ .timeout(REQUEST_TIMEOUT)
+ .header("Authorization", "Bearer " + keygen.getApiToken())
+ .header("Content-Type", "application/vnd.api+json")
+ .header("Accept", "application/vnd.api+json");
+ }
+
+ private static ResponseStatusException denied() {
+ return new ResponseStatusException(
+ HttpStatus.UNAUTHORIZED, "Server license proof rejected");
+ }
+
+ private static ResponseStatusException unavailable() {
+ return new ResponseStatusException(
+ HttpStatus.SERVICE_UNAVAILABLE, "License validation unavailable");
+ }
+}
diff --git a/app/saas/src/main/java/stirling/software/saas/serverregistration/ServerLicenseRegistrationController.java b/app/saas/src/main/java/stirling/software/saas/serverregistration/ServerLicenseRegistrationController.java
new file mode 100644
index 0000000000..d810f7e810
--- /dev/null
+++ b/app/saas/src/main/java/stirling/software/saas/serverregistration/ServerLicenseRegistrationController.java
@@ -0,0 +1,97 @@
+package stirling.software.saas.serverregistration;
+
+import java.time.Duration;
+
+import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
+import org.springframework.context.annotation.Profile;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.ProblemDetail;
+import org.springframework.http.ResponseEntity;
+import org.springframework.http.converter.HttpMessageNotReadableException;
+import org.springframework.web.bind.MethodArgumentNotValidException;
+import org.springframework.web.bind.annotation.ExceptionHandler;
+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.server.ResponseStatusException;
+
+import io.swagger.v3.oas.annotations.Hidden;
+
+import jakarta.servlet.http.HttpServletRequest;
+import jakarta.validation.Valid;
+
+import stirling.software.common.cluster.RateLimitStore;
+import stirling.software.proprietary.serverregistration.ServerRegistrationProtocol;
+import stirling.software.proprietary.serverregistration.ServerRegistrationProtocol.Receipt;
+import stirling.software.proprietary.serverregistration.ServerRegistrationProtocol.RegistrationRequest;
+import stirling.software.proprietary.serverregistration.ServerRegistrationProtocol.SyncRequest;
+
+/**
+ * Public transport with proof/credential authentication inside each operation, never a user
+ * session.
+ */
+@Hidden
+@RestController
+@Profile("saas")
+@RequestMapping(ServerRegistrationProtocol.PATH)
+@ConditionalOnProperty(name = "stirling.server-registration.enabled", havingValue = "true")
+public class ServerLicenseRegistrationController {
+ private final KeygenServerLicenseVerifier verifier;
+ private final ServerLicenseRegistrationStore store;
+ private final RateLimitStore rateLimits;
+
+ public ServerLicenseRegistrationController(
+ KeygenServerLicenseVerifier verifier,
+ ServerLicenseRegistrationStore store,
+ RateLimitStore rateLimits) {
+ this.verifier = verifier;
+ this.store = store;
+ this.rateLimits = rateLimits;
+ }
+
+ /** Validates live license ownership before any tracking record can be created. */
+ @PostMapping
+ public Receipt register(
+ @Valid @RequestBody RegistrationRequest request, HttpServletRequest http) {
+ rateLimit("bootstrap", http.getRemoteAddr(), 30);
+ return store.register(
+ request, verifier.verify(request.licenseProof(), request.machineFingerprint()));
+ }
+
+ /** Accepts sequenced counts only from the persisted registration credential. */
+ @PostMapping("/sync")
+ public Receipt sync(@Valid @RequestBody SyncRequest request, HttpServletRequest http) {
+ rateLimit("sync", http.getRemoteAddr(), 120);
+ return store.sync(request);
+ }
+
+ /** Rejects malformed bodies without rendering credential-bearing field errors. */
+ @ExceptionHandler({
+ MethodArgumentNotValidException.class,
+ HttpMessageNotReadableException.class
+ })
+ public ProblemDetail invalidRequest() {
+ return ProblemDetail.forStatusAndDetail(
+ HttpStatus.BAD_REQUEST, "Invalid registration request");
+ }
+
+ /** Exposes recovery information only after the store authenticates the tracking credential. */
+ @ExceptionHandler(ServerLicenseRegistrationStore.SequenceConflictException.class)
+ public ResponseEntity<ServerRegistrationProtocol.SequenceConflict> sequenceConflict(
+ ServerLicenseRegistrationStore.SequenceConflictException failure) {
+ return ResponseEntity.status(HttpStatus.CONFLICT).body(failure.conflict());
+ }
+
+ private void rateLimit(String operation, String address, long capacity) {
+ if (!rateLimits
+ .tryConsume(
+ "server-registration:" + operation + ":" + address,
+ capacity,
+ Duration.ofMinutes(1))
+ .allowed()) {
+ throw new ResponseStatusException(
+ HttpStatus.TOO_MANY_REQUESTS, "Registration rate limit exceeded");
+ }
+ }
+}
diff --git a/app/saas/src/main/java/stirling/software/saas/serverregistration/ServerLicenseRegistrationStore.java b/app/saas/src/main/java/stirling/software/saas/serverregistration/ServerLicenseRegistrationStore.java
new file mode 100644
index 0000000000..c8ea4f6ec1
--- /dev/null
+++ b/app/saas/src/main/java/stirling/software/saas/serverregistration/ServerLicenseRegistrationStore.java
@@ -0,0 +1,219 @@
+package stirling.software.saas.serverregistration;
+
+import java.nio.charset.StandardCharsets;
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.time.Instant;
+import java.util.HexFormat;
+import java.util.List;
+import java.util.UUID;
+
+import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
+import org.springframework.context.annotation.Profile;
+import org.springframework.http.HttpStatus;
+import org.springframework.jdbc.core.JdbcTemplate;
+import org.springframework.stereotype.Repository;
+import org.springframework.transaction.annotation.Transactional;
+import org.springframework.web.server.ResponseStatusException;
+
+import stirling.software.proprietary.serverregistration.ServerRegistrationProtocol.PurchaseMapping;
+import stirling.software.proprietary.serverregistration.ServerRegistrationProtocol.Receipt;
+import stirling.software.proprietary.serverregistration.ServerRegistrationProtocol.RegistrationRequest;
+import stirling.software.proprietary.serverregistration.ServerRegistrationProtocol.Report;
+import stirling.software.proprietary.serverregistration.ServerRegistrationProtocol.SequenceConflict;
+import stirling.software.proprietary.serverregistration.ServerRegistrationProtocol.SyncRequest;
+
+/**
+ * Migration-owned Postgres records only. No Team, license, account or billing mutation is reachable
+ * here.
+ */
+@Repository
+@Profile("saas")
+@ConditionalOnProperty(name = "stirling.server-registration.enabled", havingValue = "true")
+public class ServerLicenseRegistrationStore {
+ private final JdbcTemplate jdbc;
+
+ public ServerLicenseRegistrationStore(JdbcTemplate jdbc) {
+ this.jdbc = jdbc;
+ }
+
+ /**
+ * Unique license/installation identity plus a row lock prevents bootstrap retries rotating
+ * credentials.
+ */
+ @Transactional
+ public Receipt register(
+ RegistrationRequest request, KeygenServerLicenseVerifier.VerifiedLicense license) {
+ Purchase purchase = findPurchase(license.key());
+ jdbc.update(
+ """
+ INSERT INTO public.server_license_registrations
+ (registration_id, installation_id, keygen_license_id, credential_hash,
+ license_record_id, server_subscription_id, license_user_limit)
+ VALUES (?, ?, ?, ?, ?, ?, ?)
+ ON CONFLICT (keygen_license_id, installation_id) DO NOTHING
+ """,
+ UUID.randomUUID(),
+ request.installationId(),
+ license.id(),
+ hash(request.registrationSecret()),
+ purchase.id(),
+ purchase.subscription(),
+ license.userLimit());
+ Row row =
+ jdbc.queryForObject(
+ """
+ SELECT * FROM public.server_license_registrations
+ WHERE keygen_license_id = ? AND installation_id = ? FOR UPDATE
+ """,
+ this::read,
+ license.id(),
+ request.installationId());
+ authenticate(row, request.registrationSecret());
+ jdbc.update(
+ """
+ UPDATE public.server_license_registrations
+ SET license_user_limit = ?
+ WHERE registration_id = ?
+ """,
+ license.userLimit(),
+ row.id());
+ return accept(row, request.report(), purchase);
+ }
+
+ /** Replays never refresh liveness. Changed payloads at the same sequence are rejected. */
+ @Transactional
+ public Receipt sync(SyncRequest request) {
+ List<Row> rows =
+ jdbc.query(
+ "SELECT * FROM public.server_license_registrations WHERE registration_id = ? FOR UPDATE",
+ this::read,
+ request.registrationId());
+ if (rows.isEmpty()) throw unauthorized();
+ Row row = rows.getFirst();
+ authenticate(row, request.registrationSecret());
+ List<String> keys =
+ jdbc.query(
+ "SELECT license_key FROM public.license_keys WHERE id = ?",
+ (rs, index) -> rs.getString("license_key"),
+ row.licenseRecordId());
+ Purchase purchase =
+ keys.size() == 1 ? findPurchase(keys.getFirst()) : new Purchase(null, null);
+ return accept(row, request.report(), purchase);
+ }
+
+ private Purchase findPurchase(String key) {
+ List<Purchase> matches =
+ jdbc.query(
+ "SELECT id, nullif(trim(server_subscription_id), '') AS server_subscription_id FROM public.license_keys WHERE license_key = ?"
+ + " AND plan = 'server' AND enterprise_seat_subscription_id IS NULL LIMIT 2",
+ (rs, index) ->
+ new Purchase(
+ rs.getObject("id", UUID.class),
+ rs.getString("server_subscription_id")),
+ key);
+ return matches.size() == 1 ? matches.getFirst() : new Purchase(null, null);
+ }
+
+ private Receipt accept(Row row, Report report, Purchase purchase) {
+ if (report.sequence() < row.sequence()
+ || (report.sequence() == row.sequence()
+ && (!report.reportedUserCount().equals(row.users())
+ || !report.applicationVersion().equals(row.version())
+ || report.capabilityVersion() != row.capability()))) {
+ throw new SequenceConflictException(new SequenceConflict(row.id(), row.sequence()));
+ }
+ if (report.sequence() > row.sequence()) {
+ jdbc.update(
+ """
+ UPDATE public.server_license_registrations
+ SET report_sequence = ?, reported_user_count = ?, application_version = ?,
+ capability_version = ?, reported_at = now(), last_seen_at = now()
+ WHERE registration_id = ?
+ """,
+ report.sequence(),
+ report.reportedUserCount(),
+ report.applicationVersion(),
+ report.capabilityVersion(),
+ row.id());
+ }
+ jdbc.update(
+ "UPDATE public.server_license_registrations SET license_record_id = ?, server_subscription_id = ? WHERE registration_id = ?",
+ purchase.id(),
+ purchase.subscription(),
+ row.id());
+ return new Receipt(
+ row.id(),
+ report.sequence(),
+ purchase.subscription() == null
+ ? PurchaseMapping.UNRESOLVED
+ : PurchaseMapping.RESOLVED);
+ }
+
+ private void authenticate(Row row, String secret) {
+ if (row == null
+ || row.revokedAt() != null
+ || !MessageDigest.isEqual(
+ row.hash().getBytes(StandardCharsets.UTF_8),
+ hash(secret).getBytes(StandardCharsets.UTF_8))) {
+ throw unauthorized();
+ }
+ }
+
+ private Row read(ResultSet rs, int index) throws SQLException {
+ var revoked = rs.getTimestamp("revoked_at");
+ return new Row(
+ rs.getObject("registration_id", UUID.class),
+ rs.getString("credential_hash"),
+ rs.getObject("license_record_id", UUID.class),
+ rs.getLong("report_sequence"),
+ rs.getObject("reported_user_count", Long.class),
+ rs.getString("application_version"),
+ rs.getInt("capability_version"),
+ revoked == null ? null : revoked.toInstant());
+ }
+
+ private static String hash(String secret) {
+ try {
+ return HexFormat.of()
+ .formatHex(
+ MessageDigest.getInstance("SHA-256")
+ .digest(secret.getBytes(StandardCharsets.UTF_8)));
+ } catch (NoSuchAlgorithmException e) {
+ throw new IllegalStateException("SHA-256 unavailable", e);
+ }
+ }
+
+ private static ResponseStatusException unauthorized() {
+ return new ResponseStatusException(
+ HttpStatus.UNAUTHORIZED, "Registration credential rejected");
+ }
+
+ private record Purchase(UUID id, String subscription) {}
+
+ /** Carries only the authenticated record's sequence; the rejected transaction rolls back. */
+ static final class SequenceConflictException extends ResponseStatusException {
+ private final SequenceConflict conflict;
+
+ SequenceConflictException(SequenceConflict conflict) {
+ super(HttpStatus.CONFLICT, "Report sequence already superseded");
+ this.conflict = conflict;
+ }
+
+ SequenceConflict conflict() {
+ return conflict;
+ }
+ }
+
+ private record Row(
+ UUID id,
+ String hash,
+ UUID licenseRecordId,
+ long sequence,
+ Long users,
+ String version,
+ int capability,
+ Instant revokedAt) {}
+}
diff --git a/app/saas/src/main/java/stirling/software/saas/serverregistration/ServerRegistrationCloudProperties.java b/app/saas/src/main/java/stirling/software/saas/serverregistration/ServerRegistrationCloudProperties.java
new file mode 100644
index 0000000000..5220d45e6f
--- /dev/null
+++ b/app/saas/src/main/java/stirling/software/saas/serverregistration/ServerRegistrationCloudProperties.java
@@ -0,0 +1,24 @@
+package stirling.software.saas.serverregistration;
+
+import java.util.Set;
+
+import org.springframework.boot.context.properties.ConfigurationProperties;
+import org.springframework.context.annotation.Profile;
+import org.springframework.stereotype.Component;
+
+import lombok.Getter;
+import lombok.Setter;
+
+/**
+ * Cloud trust configuration; product IDs and the Ed25519 public key must belong to the configured
+ * account.
+ */
+@Getter
+@Setter
+@Component
+@Profile("saas")
+@ConfigurationProperties(prefix = "stirling.server-registration")
+public class ServerRegistrationCloudProperties {
+ private Set<String> serverProductIds = Set.of();
+ private String licensePublicKey;
+}
diff --git a/app/saas/src/test/java/stirling/software/saas/serverregistration/KeygenServerLicenseVerifierTest.java b/app/saas/src/test/java/stirling/software/saas/serverregistration/KeygenServerLicenseVerifierTest.java
new file mode 100644
index 0000000000..707f983d82
--- /dev/null
+++ b/app/saas/src/test/java/stirling/software/saas/serverregistration/KeygenServerLicenseVerifierTest.java
@@ -0,0 +1,480 @@
+package stirling.software.saas.serverregistration;
+
+import static org.assertj.core.api.Assertions.*;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.*;
+
+import java.net.InetSocketAddress;
+import java.net.http.HttpClient;
+import java.net.http.HttpRequest;
+import java.net.http.HttpResponse;
+import java.nio.charset.StandardCharsets;
+import java.security.KeyPair;
+import java.security.KeyPairGenerator;
+import java.security.Signature;
+import java.time.Clock;
+import java.time.Instant;
+import java.time.ZoneOffset;
+import java.util.Arrays;
+import java.util.Base64;
+import java.util.HashMap;
+import java.util.HexFormat;
+import java.util.Map;
+import java.util.Set;
+import java.util.UUID;
+import java.util.concurrent.CancellationException;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicReference;
+
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.Timeout;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.NullSource;
+import org.junit.jupiter.params.provider.ValueSource;
+import org.mockito.ArgumentCaptor;
+import org.springframework.http.HttpStatus;
+import org.springframework.web.server.ResponseStatusException;
+
+import com.sun.net.httpserver.HttpServer;
+
+import stirling.software.saas.procurement.config.KeygenConfigurationProperties;
+
+import tools.jackson.databind.ObjectMapper;
+import tools.jackson.databind.node.ObjectNode;
+
+class KeygenServerLicenseVerifierTest {
+ private static final UUID ACCOUNT = UUID.randomUUID();
+ private static final UUID PRODUCT = UUID.randomUUID();
+ private static final UUID LICENSE = UUID.randomUUID();
+ private static final Instant NOW = Instant.parse("2026-10-16T12:00:00Z");
+ private final ObjectMapper mapper = new ObjectMapper();
+ private final HttpClient http = mock(HttpClient.class);
+ private KeyPair signingKey;
+ private KeygenServerLicenseVerifier verifier;
+ private KeygenConfigurationProperties keygen;
+ private ServerRegistrationCloudProperties properties;
+
+ @BeforeEach
+ void setup() throws Exception {
+ signingKey = KeyPairGenerator.getInstance("Ed25519").generateKeyPair();
+ keygen = new KeygenConfigurationProperties();
+ keygen.setAccountId(ACCOUNT.toString());
+ keygen.setApiToken("test-token");
+ properties = new ServerRegistrationCloudProperties();
+ properties.setServerProductIds(Set.of(PRODUCT.toString()));
+ byte[] encoded = signingKey.getPublic().getEncoded();
+ properties.setLicensePublicKey(
+ HexFormat.of()
+ .formatHex(
+ Arrays.copyOfRange(encoded, encoded.length - 32, encoded.length)));
+ verifier =
+ new KeygenServerLicenseVerifier(
+ keygen, properties, mapper, http, Clock.fixed(NOW, ZoneOffset.UTC));
+ }
+
+ @Test
+ void rawKeyNeedsLiveValidationAndRetainsUnlimitedSentinel() throws Exception {
+ respond(200, liveBody());
+ var result = verifier.verify("test-license-secret", "machine");
+ assertThat(result.id()).isEqualTo(LICENSE);
+ assertThat(result.userLimit()).isZero();
+ assertThat(result.toString()).doesNotContain("test-license-secret");
+ var request = ArgumentCaptor.forClass(HttpRequest.class);
+ verify(http).sendAsync(request.capture(), any());
+ assertThat(request.getValue().uri().getPath()).endsWith("/licenses/actions/validate-key");
+ }
+
+ @Test
+ void signedFileStillRequiresLiveValidationOfTheSameLicense() throws Exception {
+ respond(200, liveBody());
+ assertThat(
+ verifier.verify(
+ certificate(
+ NOW.minusSeconds(1),
+ NOW.plusSeconds(60),
+ signingKey),
+ "machine")
+ .id())
+ .isEqualTo(LICENSE);
+ var request = ArgumentCaptor.forClass(HttpRequest.class);
+ verify(http).sendAsync(request.capture(), any());
+ assertThat(request.getValue().uri().getPath())
+ .endsWith("/licenses/" + LICENSE + "/actions/validate");
+ }
+
+ @Test
+ void perpetualSignedFileStillRequiresLiveValidation() throws Exception {
+ String proof = certificate(NOW.minusSeconds(1), null, signingKey);
+ respond(200, liveBody());
+ assertThat(verifier.verify(proof, "machine").id()).isEqualTo(LICENSE);
+ ObjectNode revoked = liveBody();
+ ((ObjectNode) revoked.path("meta")).put("valid", false);
+ respond(200, revoked);
+ assertThatThrownBy(() -> verifier.verify(proof, "machine"))
+ .isInstanceOfSatisfying(
+ ResponseStatusException.class,
+ e -> assertThat(e.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED));
+ verify(http, times(2)).sendAsync(any(), any());
+ }
+
+ @ParameterizedTest
+ @NullSource
+ @ValueSource(strings = {"", "not-hex", "abcd"})
+ void missingOrMalformedSigningKeyFailsAtStartup(String publicKey) {
+ properties.setLicensePublicKey(publicKey);
+ assertThatIllegalStateException()
+ .isThrownBy(
+ () ->
+ new KeygenServerLicenseVerifier(
+ keygen,
+ properties,
+ mapper,
+ http,
+ Clock.fixed(NOW, ZoneOffset.UTC)))
+ .withMessageContaining("license public key");
+ verifyNoInteractions(http);
+ }
+
+ @Test
+ void forgedExpiredOrFutureCertificatesNeverReachKeygen() throws Exception {
+ String forged =
+ certificate(
+ NOW.minusSeconds(1),
+ NOW.plusSeconds(60),
+ KeyPairGenerator.getInstance("Ed25519").generateKeyPair());
+ String expired = certificate(NOW.minusSeconds(60), NOW, signingKey);
+ String future = certificate(NOW.plusSeconds(1), NOW.plusSeconds(60), signingKey);
+ for (String proof : new String[] {forged, expired, future}) {
+ assertThatThrownBy(() -> verifier.verify(proof, "machine"))
+ .isInstanceOfSatisfying(
+ ResponseStatusException.class,
+ e -> assertThat(e.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED));
+ }
+ verifyNoInteractions(http);
+ }
+
+ @ParameterizedTest
+ @ValueSource(
+ strings = {
+ "invalid",
+ "untypedValidity",
+ "wrongPlan",
+ "wrongProduct",
+ "wrongAccount",
+ "enterprise",
+ "missingTier",
+ "suspended",
+ "changedKey"
+ })
+ void activeStatusAloneCannotAuthorizeRegistration(String problem) throws Exception {
+ ObjectNode body = liveBody();
+ ObjectNode attributes = (ObjectNode) body.at("/data/attributes");
+ ObjectNode metadata = (ObjectNode) attributes.path("metadata");
+ switch (problem) {
+ case "invalid" -> ((ObjectNode) body.path("meta")).put("valid", false);
+ case "untypedValidity" -> ((ObjectNode) body.path("meta")).put("valid", "true");
+ case "wrongPlan" -> metadata.put("planType", "enterprise");
+ case "wrongProduct" ->
+ ((ObjectNode) body.at("/data/relationships/product/data"))
+ .put("id", UUID.randomUUID().toString());
+ case "wrongAccount" ->
+ ((ObjectNode) body.at("/data/relationships/account/data"))
+ .put("id", UUID.randomUUID().toString());
+ case "enterprise" -> metadata.put("isEnterprise", true);
+ case "missingTier" -> metadata.remove("isEnterprise");
+ case "suspended" -> attributes.put("suspended", true);
+ case "changedKey" -> attributes.put("key", "different-key");
+ default -> throw new AssertionError(problem);
+ }
+ respond(200, body);
+ assertThatThrownBy(() -> verifier.verify("test-license-secret", "machine"))
+ .isInstanceOfSatisfying(
+ ResponseStatusException.class,
+ e -> assertThat(e.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED))
+ .hasMessageNotContaining("test-license-secret");
+ }
+
+ @Test
+ void mismatchedSignedLicenseIdIsRejected() throws Exception {
+ ObjectNode body = liveBody();
+ ((ObjectNode) body.path("data")).put("id", UUID.randomUUID().toString());
+ respond(200, body);
+ String proof = certificate(NOW.minusSeconds(1), NOW.plusSeconds(60), signingKey);
+ assertThatThrownBy(() -> verifier.verify(proof, "machine"))
+ .isInstanceOfSatisfying(
+ ResponseStatusException.class,
+ e -> assertThat(e.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED));
+ }
+
+ @ParameterizedTest
+ @ValueSource(ints = {429, 500, 503})
+ void upstreamOutageFailsClosedWithoutAnEntitlementDecision(int status) throws Exception {
+ respond(status, liveBody());
+ assertThatThrownBy(() -> verifier.verify("test-license-secret", "machine"))
+ .isInstanceOfSatisfying(
+ ResponseStatusException.class,
+ e ->
+ assertThat(e.getStatusCode())
+ .isEqualTo(HttpStatus.SERVICE_UNAVAILABLE));
+ }
+
+ @Test
+ @Timeout(20)
+ @SuppressWarnings("unchecked")
+ void deadlineCancelsKeygenResponseThatStallsAfterHeaders() throws Exception {
+ var server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
+ var headersSent = new CountDownLatch(1);
+ server.createContext(
+ "/",
+ exchange -> {
+ exchange.getRequestBody().readAllBytes();
+ exchange.sendResponseHeaders(200, 100);
+ exchange.getResponseBody().write('{');
+ exchange.getResponseBody().flush();
+ headersSent.countDown();
+ });
+ server.start();
+ try (var realHttp = HttpClient.newHttpClient()) {
+ keygen.setApiBase("http://127.0.0.1:" + server.getAddress().getPort());
+ var pending = new AtomicReference<CompletableFuture<HttpResponse<String>>>();
+ when(http.sendAsync(any(), any(HttpResponse.BodyHandler.class)))
+ .thenAnswer(
+ call -> {
+ var future =
+ realHttp.sendAsync(
+ call.getArgument(0),
+ HttpResponse.BodyHandlers.ofString());
+ pending.set(future);
+ return future;
+ });
+ assertThatThrownBy(() -> verifier.verify("test-license-secret", "machine"))
+ .isInstanceOfSatisfying(
+ ResponseStatusException.class,
+ e ->
+ assertThat(e.getStatusCode())
+ .isEqualTo(HttpStatus.SERVICE_UNAVAILABLE));
+ assertThat(headersSent.getCount()).isZero();
+ assertThatThrownBy(() -> pending.get().get(1, TimeUnit.SECONDS))
+ .isInstanceOfAny(CancellationException.class, ExecutionException.class)
+ .satisfies(
+ failure ->
+ assertThat(
+ failure instanceof CancellationException
+ ? failure
+ : failure.getCause())
+ .isInstanceOf(CancellationException.class));
+ } finally {
+ server.stop(0);
+ }
+ }
+
+ @ParameterizedTest
+ @ValueSource(strings = {"stirling-test", "1-2-3-4-5"})
+ @SuppressWarnings("unchecked")
+ void slugResolvesCanonicalAccountAndStillRejectsForeignLicenses(String slug) throws Exception {
+ useSlug(slug);
+ HttpResponse<String> accountResponse = mock(HttpResponse.class);
+ when(accountResponse.statusCode()).thenReturn(200);
+ when(accountResponse.body())
+ .thenReturn(
+ mapper.writeValueAsString(
+ Map.of(
+ "data",
+ Map.of(
+ "type",
+ "accounts",
+ "id",
+ ACCOUNT,
+ "attributes",
+ Map.of("slug", slug)))));
+ HttpResponse<String> licenseResponse = mock(HttpResponse.class);
+ when(licenseResponse.statusCode()).thenReturn(200);
+ when(licenseResponse.body()).thenReturn(mapper.writeValueAsString(liveBody()));
+ when(http.sendAsync(any(), any(HttpResponse.BodyHandler.class)))
+ .thenReturn(
+ CompletableFuture.completedFuture(accountResponse),
+ CompletableFuture.completedFuture(licenseResponse));
+ assertThat(verifier.verify("test-license-secret", "machine").id()).isEqualTo(LICENSE);
+ assertThat(verifier.verify("test-license-secret", "machine").id()).isEqualTo(LICENSE);
+ var body = liveBody();
+ ((ObjectNode) body.at("/data/relationships/account/data"))
+ .put("id", UUID.randomUUID().toString());
+ when(licenseResponse.body()).thenReturn(mapper.writeValueAsString(body));
+ assertThatThrownBy(() -> verifier.verify("test-license-secret", "machine"))
+ .isInstanceOfSatisfying(
+ ResponseStatusException.class,
+ e -> assertThat(e.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED));
+ var requests = ArgumentCaptor.forClass(HttpRequest.class);
+ verify(http, times(4)).sendAsync(requests.capture(), any());
+ assertThat(requests.getAllValues().getFirst().method()).isEqualTo("GET");
+ assertThat(requests.getAllValues().getFirst().uri().getPath())
+ .isEqualTo("/v1/accounts/" + slug);
+ assertThat(requests.getAllValues().subList(1, 4))
+ .allSatisfy(
+ request ->
+ assertThat(request.uri().getPath())
+ .endsWith("/" + slug + "/licenses/actions/validate-key"));
+ }
+
+ @ParameterizedTest
+ @ValueSource(ints = {403, 500, 200})
+ void failedOrMalformedSlugResolutionFailsClosedAndCanRetry(int status) throws Exception {
+ useSlug("stirling-test");
+ respond(status, liveBody());
+ for (int attempt = 0; attempt < 2; attempt++) {
+ assertThatThrownBy(() -> verifier.verify("test-license-secret", "machine"))
+ .isInstanceOfSatisfying(
+ ResponseStatusException.class,
+ e ->
+ assertThat(e.getStatusCode())
+ .isEqualTo(HttpStatus.SERVICE_UNAVAILABLE));
+ }
+ var requests = ArgumentCaptor.forClass(HttpRequest.class);
+ verify(http, times(2)).sendAsync(requests.capture(), any());
+ assertThat(requests.getAllValues())
+ .allSatisfy(request -> assertThat(request.method()).isEqualTo("GET"));
+ }
+
+ @Test
+ void explicitServerPlanMetadataIsAccepted() throws Exception {
+ var body = liveBody();
+ ((ObjectNode) body.at("/data/attributes/metadata")).put("planType", "server");
+ respond(200, body);
+ assertThat(verifier.verify("test-license-secret", "machine").id()).isEqualTo(LICENSE);
+ }
+
+ @ParameterizedTest
+ @ValueSource(
+ strings = {
+ "{\"isEnterprise\":false,\"users\":100}",
+ "{\"isEnterprise\":\" FALSE \",\"users\":\" 100 \"}",
+ "{\"planType\":\" Server \",\"users\":\"100\"}",
+ "{\"plan_type\":\"SERVER\",\"users\":100}",
+ "{\"isEnterprise\":null,\"plan_type\":\"server\",\"users\":100}",
+ "{\"isEnterprise\":false,\"planType\":\" \",\"users\":100}",
+ "{\"planType\":\"server\",\"plan_type\":\"SERVER\",\"users\":100,\"custom\":true}"
+ })
+ void manualServerMetadataAcceptsKnownAliasesAndFormatting(String metadata) throws Exception {
+ var body = liveBody();
+ ((ObjectNode) body.at("/data/attributes")).set("metadata", mapper.readTree(metadata));
+ respond(200, body);
+ assertThat(verifier.verify("test-license-secret", "machine").userLimit()).isEqualTo(100);
+ }
+
+ @ParameterizedTest
+ @ValueSource(
+ strings = {
+ "null",
+ "-1",
+ "2147483648",
+ "\"unlimited\"",
+ "\"invalid\"",
+ "1.5",
+ "true",
+ "{}"
+ })
+ void unparseableAllowanceIsUnknownRatherThanUnlimited(String limit) throws Exception {
+ var body = liveBody();
+ ((ObjectNode) body.at("/data/attributes/metadata")).set("users", mapper.readTree(limit));
+ respond(200, body);
+ assertThat(verifier.verify("test-license-secret", "machine").userLimit()).isNull();
+ }
+
+ @ParameterizedTest
+ @ValueSource(
+ strings = {
+ "{}",
+ "{\"isEnterprise\":true,\"plan_type\":\"server\"}",
+ "{\"isEnterprise\":\" TRUE \",\"planType\":\"server\"}",
+ "{\"isEnterprise\":false,\"plan_type\":\" Enterprise \"}",
+ "{\"planType\":\"server\",\"plan_type\":\"enterprise\"}",
+ "{\"isEnterprise\":\"unknown\",\"planType\":\"server\"}",
+ "{\"isEnterprise\":false,\"planType\":\"team\"}",
+ "{\"isEnterprise\":false,\"plan_type\":42}"
+ })
+ void conflictingOrUnknownTierNeverRegistersAsServer(String metadata) throws Exception {
+ var body = liveBody();
+ ((ObjectNode) body.at("/data/attributes")).set("metadata", mapper.readTree(metadata));
+ respond(200, body);
+ assertThatThrownBy(() -> verifier.verify("test-license-secret", "machine"))
+ .isInstanceOfSatisfying(
+ ResponseStatusException.class,
+ e -> assertThat(e.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED));
+ }
+
+ private void useSlug(String slug) {
+ keygen.setAccountId(slug);
+ verifier =
+ new KeygenServerLicenseVerifier(
+ keygen, properties, mapper, http, Clock.fixed(NOW, ZoneOffset.UTC));
+ }
+
+ private ObjectNode liveBody() {
+ return (ObjectNode)
+ mapper.valueToTree(
+ Map.of(
+ "meta",
+ Map.of("valid", true),
+ "data",
+ Map.of(
+ "id",
+ LICENSE,
+ "type",
+ "licenses",
+ "attributes",
+ Map.of(
+ "key",
+ "test-license-secret",
+ "status",
+ "ACTIVE",
+ "suspended",
+ false,
+ "metadata",
+ Map.of("isEnterprise", false, "users", 0)),
+ "relationships",
+ Map.of(
+ "account",
+ Map.of("data", Map.of("id", ACCOUNT)),
+ "product",
+ Map.of("data", Map.of("id", PRODUCT))))));
+ }
+
+ @SuppressWarnings("unchecked")
+ private void respond(int status, ObjectNode body) throws Exception {
+ HttpResponse<String> response = mock(HttpResponse.class);
+ when(response.statusCode()).thenReturn(status);
+ when(response.body()).thenReturn(mapper.writeValueAsString(body));
+ when(http.sendAsync(any(), any(HttpResponse.BodyHandler.class)))
+ .thenReturn(CompletableFuture.completedFuture(response));
+ }
+
+ private String certificate(Instant issued, Instant expiry, KeyPair key) throws Exception {
+ Map<String, Object> meta = new HashMap<>();
+ meta.put("issued", issued.toString());
+ meta.put("expiry", expiry == null ? null : expiry.toString());
+ byte[] snapshot =
+ mapper.writeValueAsBytes(
+ Map.of("meta", meta, "data", Map.of("type", "licenses", "id", LICENSE)));
+ String enc = Base64.getEncoder().encodeToString(snapshot);
+ Signature signature = Signature.getInstance("Ed25519");
+ signature.initSign(key.getPrivate());
+ signature.update(("license/" + enc).getBytes(StandardCharsets.UTF_8));
+ String envelope =
+ Base64.getEncoder()
+ .encodeToString(
+ mapper.writeValueAsBytes(
+ Map.of(
+ "alg",
+ "base64+ed25519",
+ "enc",
+ enc,
+ "sig",
+ Base64.getEncoder()
+ .encodeToString(signature.sign()))));
+ return "-----BEGIN LICENSE FILE-----\n" + envelope + "\n-----END LICENSE FILE-----";
+ }
+}
diff --git a/app/saas/src/test/java/stirling/software/saas/serverregistration/ServerLicenseRegistrationControllerTest.java b/app/saas/src/test/java/stirling/software/saas/serverregistration/ServerLicenseRegistrationControllerTest.java
new file mode 100644
index 0000000000..cafef55d80
--- /dev/null
+++ b/app/saas/src/test/java/stirling/software/saas/serverregistration/ServerLicenseRegistrationControllerTest.java
@@ -0,0 +1,189 @@
+package stirling.software.saas.serverregistration;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.ArgumentMatchers.*;
+import static org.mockito.Mockito.*;
+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
+
+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.springframework.boot.test.context.runner.ApplicationContextRunner;
+import org.springframework.boot.test.system.CapturedOutput;
+import org.springframework.boot.test.system.OutputCaptureExtension;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.MediaType;
+import org.springframework.test.web.servlet.MockMvc;
+import org.springframework.test.web.servlet.setup.MockMvcBuilders;
+import org.springframework.web.server.ResponseStatusException;
+
+import stirling.software.common.cluster.RateLimitStore;
+import stirling.software.common.cluster.RateLimitStore.RateLimitDecision;
+import stirling.software.proprietary.serverregistration.ServerRegistrationProtocol;
+import stirling.software.proprietary.serverregistration.ServerRegistrationProtocol.*;
+
+import tools.jackson.databind.ObjectMapper;
+
+class ServerLicenseRegistrationControllerTest {
+ private final KeygenServerLicenseVerifier verifier = mock(KeygenServerLicenseVerifier.class);
+ private final ServerLicenseRegistrationStore store = mock(ServerLicenseRegistrationStore.class);
+ private final RateLimitStore limits = mock(RateLimitStore.class);
+ private final ObjectMapper mapper = new ObjectMapper();
+ private MockMvc mvc;
+
+ @BeforeEach
+ void setup() {
+ when(limits.tryConsume(anyString(), anyLong(), any()))
+ .thenReturn(new RateLimitDecision(true, 29, 0));
+ mvc =
+ MockMvcBuilders.standaloneSetup(
+ new ServerLicenseRegistrationController(verifier, store, limits))
+ .build();
+ }
+
+ @Test
+ void featureIsAbsentByDefaultEvenInCloudProfile() {
+ new ApplicationContextRunner()
+ .withPropertyValues("spring.profiles.active=saas")
+ .withUserConfiguration(
+ ServerLicenseRegistrationController.class,
+ KeygenServerLicenseVerifier.class,
+ ServerLicenseRegistrationStore.class)
+ .run(
+ context -> {
+ assertThat(context).hasNotFailed();
+ assertThat(context)
+ .doesNotHaveBean(ServerLicenseRegistrationController.class);
+ assertThat(context).doesNotHaveBean(KeygenServerLicenseVerifier.class);
+ assertThat(context)
+ .doesNotHaveBean(ServerLicenseRegistrationStore.class);
+ });
+ }
+
+ @Test
+ void missingCountsAreRejectedBeforeProofValidationOrPersistence() throws Exception {
+ RegistrationRequest request = request(new Report(1L, null, "test", 1));
+ mvc.perform(
+ post(ServerRegistrationProtocol.PATH)
+ .contentType(MediaType.APPLICATION_JSON)
+ .content(mapper.writeValueAsString(request)))
+ .andExpect(status().isBadRequest());
+ verifyNoInteractions(verifier, store, limits);
+ }
+
+ @Test
+ @ExtendWith(OutputCaptureExtension.class)
+ void invalidCredentialsCannotAppearInValidationResponsesOrLogs(CapturedOutput output)
+ throws Exception {
+ String secret = "invalid-test-secret-that-must-stay-private";
+ RegistrationRequest request =
+ new RegistrationRequest(
+ UUID.randomUUID(),
+ "test-proof",
+ "machine",
+ secret,
+ new Report(1L, 147L, "test", 1));
+ String result =
+ mvc.perform(
+ post(ServerRegistrationProtocol.PATH)
+ .contentType(MediaType.APPLICATION_JSON)
+ .content(mapper.writeValueAsString(request)))
+ .andExpect(status().isBadRequest())
+ .andReturn()
+ .getResponse()
+ .getContentAsString();
+ assertThat(result)
+ .contains("Invalid registration request")
+ .doesNotContain(secret, "test-proof");
+ String malformed =
+ mapper.writeValueAsString(request)
+ .replace(request.installationId().toString(), secret);
+ String malformedResult =
+ mvc.perform(
+ post(ServerRegistrationProtocol.PATH)
+ .contentType(MediaType.APPLICATION_JSON)
+ .content(malformed))
+ .andExpect(status().isBadRequest())
+ .andReturn()
+ .getResponse()
+ .getContentAsString();
+ assertThat(malformedResult)
+ .contains("Invalid registration request")
+ .doesNotContain(secret, "test-proof");
+ assertThat(output.getAll()).doesNotContain(secret, "test-proof");
+ verifyNoInteractions(verifier, store, limits);
+ }
+
+ @Test
+ void rateLimitStopsKeygenAndRegistrationWrites() throws Exception {
+ when(limits.tryConsume(anyString(), anyLong(), any()))
+ .thenReturn(new RateLimitDecision(false, 0, 1));
+ mvc.perform(
+ post(ServerRegistrationProtocol.PATH)
+ .contentType(MediaType.APPLICATION_JSON)
+ .content(
+ mapper.writeValueAsString(
+ request(new Report(1L, 147L, "test", 1)))))
+ .andExpect(status().isTooManyRequests());
+ verifyNoInteractions(verifier, store);
+ }
+
+ @Test
+ void rejectedLicenseCannotCreateARecord() throws Exception {
+ when(verifier.verify(anyString(), anyString()))
+ .thenThrow(new ResponseStatusException(HttpStatus.UNAUTHORIZED));
+ mvc.perform(
+ post(ServerRegistrationProtocol.PATH)
+ .contentType(MediaType.APPLICATION_JSON)
+ .content(
+ mapper.writeValueAsString(
+ request(new Report(1L, 147L, "test", 1)))))
+ .andExpect(status().isUnauthorized());
+ verifyNoInteractions(store);
+ }
+
+ @Test
+ void syncUsesTrackingCredentialWithoutRepeatingLicenseProof() throws Exception {
+ SyncRequest request =
+ new SyncRequest(UUID.randomUUID(), "a".repeat(43), new Report(2L, 147L, "test", 1));
+ when(store.sync(request))
+ .thenReturn(new Receipt(request.registrationId(), 2, PurchaseMapping.RESOLVED));
+ mvc.perform(
+ post(ServerRegistrationProtocol.PATH + "/sync")
+ .contentType(MediaType.APPLICATION_JSON)
+ .content(mapper.writeValueAsString(request)))
+ .andExpect(status().isOk());
+ verify(store).sync(request);
+ verifyNoInteractions(verifier);
+ }
+
+ private RegistrationRequest request(Report report) {
+ return new RegistrationRequest(
+ UUID.randomUUID(), "test-proof", "machine", "a".repeat(43), report);
+ }
+
+ @Test
+ void conflictResponseCarriesSequenceWithoutAcknowledgingTheStaleReport() throws Exception {
+ var request =
+ new SyncRequest(
+ UUID.randomUUID(), "a".repeat(43), new Report(11L, 200L, "test", 1));
+ var conflict = new SequenceConflict(request.registrationId(), 100);
+ when(store.sync(request))
+ .thenThrow(new ServerLicenseRegistrationStore.SequenceConflictException(conflict));
+ String body =
+ mvc.perform(
+ post(ServerRegistrationProtocol.PATH + "/sync")
+ .contentType(MediaType.APPLICATION_JSON)
+ .content(mapper.writeValueAsString(request)))
+ .andExpect(status().isConflict())
+ .andReturn()
+ .getResponse()
+ .getContentAsString();
+ assertThat(mapper.readValue(body, SequenceConflict.class)).isEqualTo(conflict);
+ assertThat(body).doesNotContain(request.registrationSecret());
+ verifyNoInteractions(verifier);
+ }
+}
diff --git a/app/saas/src/test/java/stirling/software/saas/serverregistration/ServerLicenseRegistrationStorePostgresTest.java b/app/saas/src/test/java/stirling/software/saas/serverregistration/ServerLicenseRegistrationStorePostgresTest.java
new file mode 100644
index 0000000000..7bb226b758
--- /dev/null
+++ b/app/saas/src/test/java/stirling/software/saas/serverregistration/ServerLicenseRegistrationStorePostgresTest.java
@@ -0,0 +1,310 @@
+package stirling.software.saas.serverregistration;
+
+import static org.assertj.core.api.Assertions.*;
+
+import java.time.Instant;
+import java.util.UUID;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.Executors;
+import java.util.concurrent.TimeUnit;
+import java.util.function.Supplier;
+
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.springframework.http.HttpStatus;
+import org.springframework.jdbc.core.JdbcTemplate;
+import org.springframework.jdbc.datasource.DataSourceTransactionManager;
+import org.springframework.jdbc.datasource.DriverManagerDataSource;
+import org.springframework.transaction.support.TransactionTemplate;
+import org.springframework.web.server.ResponseStatusException;
+import org.testcontainers.containers.PostgreSQLContainer;
+import org.testcontainers.junit.jupiter.Container;
+import org.testcontainers.junit.jupiter.Testcontainers;
+
+import stirling.software.proprietary.serverregistration.ServerRegistrationProtocol.*;
+
+@Testcontainers(disabledWithoutDocker = true)
+class ServerLicenseRegistrationStorePostgresTest {
+ @Container
+ static final PostgreSQLContainer<?> POSTGRES = new PostgreSQLContainer<>("postgres:16-alpine");
+
+ private static final String SECRET = "a".repeat(43);
+ private JdbcTemplate jdbc;
+ private TransactionTemplate transactions;
+ private ServerLicenseRegistrationStore store;
+ private final UUID installation = UUID.randomUUID();
+ private final KeygenServerLicenseVerifier.VerifiedLicense license =
+ new KeygenServerLicenseVerifier.VerifiedLicense(UUID.randomUUID(), "test-license", 0);
+
+ @BeforeEach
+ void setup() {
+ var dataSource =
+ new DriverManagerDataSource(
+ POSTGRES.getJdbcUrl(), POSTGRES.getUsername(), POSTGRES.getPassword());
+ jdbc = new JdbcTemplate(dataSource);
+ transactions = new TransactionTemplate(new DataSourceTransactionManager(dataSource));
+ store = new ServerLicenseRegistrationStore(jdbc);
+ // Constraint and RLS coverage uses the real migration in the SaaS repository's PGlite test.
+ jdbc.execute(
+ "DROP TABLE IF EXISTS public.server_license_registrations, public.license_keys");
+ jdbc.execute(
+ """
+ CREATE TABLE public.license_keys(id UUID PRIMARY KEY, license_key TEXT, plan TEXT,
+ server_subscription_id TEXT, enterprise_seat_subscription_id TEXT);
+ CREATE TABLE public.server_license_registrations(
+ registration_id UUID PRIMARY KEY, installation_id UUID, keygen_license_id UUID,
+ credential_hash TEXT, license_record_id UUID, server_subscription_id TEXT, license_user_limit INTEGER,
+ report_sequence BIGINT DEFAULT 0, reported_user_count BIGINT, application_version TEXT,
+ capability_version INTEGER, reported_at TIMESTAMPTZ, last_seen_at TIMESTAMPTZ,
+ revoked_at TIMESTAMPTZ, UNIQUE(keygen_license_id,installation_id))
+ """);
+ jdbc.update(
+ "INSERT INTO public.license_keys VALUES (?, ?, 'server', 'sub_test', NULL)",
+ UUID.randomUUID(),
+ license.key());
+ }
+
+ @Test
+ void bootstrapRetriesPinOneCredentialAndSeparateUnlimitedFromObservedCount() {
+ Receipt first = register(1, 147, SECRET);
+ assertThat(register(1, 147, SECRET)).isEqualTo(first);
+ assertThat(first.purchaseMapping()).isEqualTo(PurchaseMapping.RESOLVED);
+ assertThat(
+ jdbc.queryForObject(
+ "SELECT count(*) FROM public.server_license_registrations",
+ Long.class))
+ .isEqualTo(1);
+ assertThat(
+ jdbc.queryForObject(
+ "SELECT license_user_limit FROM public.server_license_registrations",
+ Integer.class))
+ .isZero();
+ assertThat(
+ jdbc.queryForObject(
+ "SELECT reported_user_count FROM public.server_license_registrations",
+ Long.class))
+ .isEqualTo(147);
+ assertStatus(HttpStatus.UNAUTHORIZED, () -> register(2, 200, "b".repeat(43)));
+ assertThat(
+ jdbc.queryForObject(
+ "SELECT reported_user_count FROM public.server_license_registrations",
+ Long.class))
+ .isEqualTo(147);
+ assertThat(
+ jdbc.queryForObject(
+ "SELECT server_subscription_id FROM public.license_keys",
+ String.class))
+ .isEqualTo("sub_test");
+ assertThat(
+ jdbc.queryForObject(
+ "SELECT credential_hash FROM public.server_license_registrations",
+ String.class))
+ .doesNotContain(SECRET);
+ }
+
+ @Test
+ void staleAndChangedReportsCannotOverwriteCountsOrRefreshFreshness() {
+ Receipt first = register(3, 147, SECRET);
+ jdbc.update(
+ "UPDATE public.server_license_registrations SET last_seen_at='2020-01-01T00:00:00Z', reported_at='2020-01-01T00:00:00Z'");
+ sync(first, 3, 147, SECRET);
+ assertThat(
+ jdbc.queryForObject(
+ "SELECT last_seen_at FROM public.server_license_registrations",
+ java.sql.Timestamp.class)
+ .toInstant())
+ .isEqualTo(Instant.parse("2020-01-01T00:00:00Z"));
+ assertStatus(HttpStatus.CONFLICT, () -> sync(first, 2, 200, SECRET));
+ assertStatus(HttpStatus.CONFLICT, () -> sync(first, 3, 200, SECRET));
+ sync(first, 4, 200, SECRET);
+ assertThat(
+ jdbc.queryForObject(
+ "SELECT reported_user_count FROM public.server_license_registrations",
+ Long.class))
+ .isEqualTo(200);
+ assertThat(
+ jdbc.queryForObject(
+ "SELECT last_seen_at FROM public.server_license_registrations",
+ java.sql.Timestamp.class)
+ .toInstant())
+ .isAfter(Instant.parse("2020-01-01T00:00:00Z"));
+ }
+
+ @Test
+ void revokedAndUnknownCredentialsCannotReportOrReregister() {
+ Receipt first = register(1, 147, SECRET);
+ assertStatus(HttpStatus.UNAUTHORIZED, () -> sync(first, 2, 0, "b".repeat(43)));
+ assertStatus(
+ HttpStatus.UNAUTHORIZED,
+ () ->
+ sync(
+ new Receipt(UUID.randomUUID(), 1, PurchaseMapping.UNRESOLVED),
+ 2,
+ 0,
+ SECRET));
+ jdbc.update("UPDATE public.server_license_registrations SET revoked_at=now()");
+ assertStatus(HttpStatus.UNAUTHORIZED, () -> sync(first, 2, 0, SECRET));
+ assertStatus(HttpStatus.UNAUTHORIZED, () -> register(2, 0, SECRET));
+ }
+
+ @Test
+ void sequenceRecoveryRevealsOnlyAuthenticatedHighWaterMarkAndDoesNotAcceptStaleData() {
+ Receipt first = register(100, 147, SECRET);
+ jdbc.update(
+ "UPDATE public.server_license_registrations SET last_seen_at='2020-01-01T00:00:00Z', reported_at='2020-01-01T00:00:00Z'");
+ assertThatThrownBy(() -> sync(first, 11, 200, SECRET))
+ .isInstanceOfSatisfying(
+ ServerLicenseRegistrationStore.SequenceConflictException.class,
+ e ->
+ assertThat(e.conflict())
+ .isEqualTo(
+ new SequenceConflict(first.registrationId(), 100)));
+ assertThatThrownBy(() -> register(11, 200, SECRET))
+ .isInstanceOfSatisfying(
+ ServerLicenseRegistrationStore.SequenceConflictException.class,
+ e ->
+ assertThat(e.conflict())
+ .isEqualTo(
+ new SequenceConflict(first.registrationId(), 100)));
+ assertStatus(HttpStatus.UNAUTHORIZED, () -> sync(first, 11, 200, "b".repeat(43)));
+ assertStatus(HttpStatus.UNAUTHORIZED, () -> register(11, 200, "b".repeat(43)));
+ assertThat(
+ jdbc.queryForObject(
+ "SELECT reported_user_count FROM public.server_license_registrations",
+ Long.class))
+ .isEqualTo(147);
+ assertThat(
+ jdbc.queryForObject(
+ "SELECT last_seen_at FROM public.server_license_registrations",
+ java.sql.Timestamp.class)
+ .toInstant())
+ .isEqualTo(Instant.parse("2020-01-01T00:00:00Z"));
+ assertThat(sync(first, 101, 201, SECRET).registrationId())
+ .isEqualTo(first.registrationId());
+ assertThat(
+ jdbc.queryForObject(
+ "SELECT reported_user_count FROM public.server_license_registrations",
+ Long.class))
+ .isEqualTo(201);
+ assertThat(
+ jdbc.queryForObject(
+ "SELECT count(*) FROM public.server_license_registrations",
+ Integer.class))
+ .isEqualTo(1);
+ }
+
+ @Test
+ void ambiguousOrBlankPurchasesStayUnresolvedAndCanBeReconciledOnBootstrap() {
+ jdbc.update("UPDATE public.license_keys SET server_subscription_id=' '");
+ Receipt first = register(1, 147, SECRET);
+ assertThat(first.purchaseMapping()).isEqualTo(PurchaseMapping.UNRESOLVED);
+ jdbc.update("UPDATE public.license_keys SET server_subscription_id='sub_fixed'");
+ Receipt resolved = register(2, 147, SECRET);
+ assertThat(resolved.registrationId()).isEqualTo(first.registrationId());
+ assertThat(resolved.purchaseMapping()).isEqualTo(PurchaseMapping.RESOLVED);
+ jdbc.update(
+ "INSERT INTO public.license_keys VALUES (?, ?, 'server', 'sub_duplicate', NULL)",
+ UUID.randomUUID(),
+ license.key());
+ assertThat(register(3, 147, SECRET).purchaseMapping())
+ .isEqualTo(PurchaseMapping.UNRESOLVED);
+ }
+
+ @Test
+ void syncRefreshesThePurchaseAssociationAndDropsInvalidMappings() {
+ Receipt first = register(1, 147, SECRET);
+ jdbc.update("UPDATE public.license_keys SET server_subscription_id='sub_corrected'");
+ assertThat(sync(first, 2, 200, SECRET).purchaseMapping())
+ .isEqualTo(PurchaseMapping.RESOLVED);
+ assertThat(
+ jdbc.queryForObject(
+ "SELECT server_subscription_id FROM public.server_license_registrations",
+ String.class))
+ .isEqualTo("sub_corrected");
+ jdbc.update(
+ "UPDATE public.license_keys SET enterprise_seat_subscription_id='sub_enterprise'");
+ assertThat(sync(first, 3, 201, SECRET).purchaseMapping())
+ .isEqualTo(PurchaseMapping.UNRESOLVED);
+ assertThat(
+ jdbc.queryForObject(
+ "SELECT server_subscription_id FROM public.server_license_registrations",
+ String.class))
+ .isNull();
+ jdbc.update("UPDATE public.license_keys SET enterprise_seat_subscription_id=NULL");
+ assertThat(register(4, 202, SECRET).registrationId()).isEqualTo(first.registrationId());
+ jdbc.update("DELETE FROM public.license_keys");
+ assertThat(sync(first, 5, 203, SECRET).purchaseMapping())
+ .isEqualTo(PurchaseMapping.UNRESOLVED);
+ }
+
+ @Test
+ void ambiguousPurchaseIntroducedAfterRegistrationIsNotKeptOnSync() {
+ Receipt first = register(1, 147, SECRET);
+ jdbc.update(
+ "INSERT INTO public.license_keys VALUES (?, ?, 'server', 'sub_other', NULL)",
+ UUID.randomUUID(),
+ license.key());
+ assertThat(sync(first, 2, 200, SECRET).purchaseMapping())
+ .isEqualTo(PurchaseMapping.UNRESOLVED);
+ assertThat(
+ jdbc.queryForObject(
+ "SELECT license_record_id FROM public.server_license_registrations",
+ UUID.class))
+ .isNull();
+ }
+
+ @Test
+ void concurrentLostReplyRetriesReturnTheSameRegistration() throws Exception {
+ CountDownLatch ready = new CountDownLatch(2);
+ CountDownLatch start = new CountDownLatch(1);
+ try (var executor = Executors.newFixedThreadPool(2)) {
+ var task =
+ (java.util.concurrent.Callable<Receipt>)
+ () -> {
+ ready.countDown();
+ assertThat(start.await(10, TimeUnit.SECONDS)).isTrue();
+ return register(1, 147, SECRET);
+ };
+ var one = executor.submit(task);
+ var two = executor.submit(task);
+ assertThat(ready.await(10, TimeUnit.SECONDS)).isTrue();
+ start.countDown();
+ assertThat(one.get(20, TimeUnit.SECONDS)).isEqualTo(two.get(20, TimeUnit.SECONDS));
+ }
+ assertThat(
+ jdbc.queryForObject(
+ "SELECT count(*) FROM public.server_license_registrations",
+ Long.class))
+ .isEqualTo(1);
+ }
+
+ private Receipt register(long sequence, long count, String secret) {
+ return transactions.execute(
+ status ->
+ store.register(
+ new RegistrationRequest(
+ installation,
+ "proof",
+ "machine",
+ secret,
+ new Report(sequence, count, "test", 1)),
+ license));
+ }
+
+ private Receipt sync(Receipt registration, long sequence, long count, String secret) {
+ return transactions.execute(
+ status ->
+ store.sync(
+ new SyncRequest(
+ registration.registrationId(),
+ secret,
+ new Report(sequence, count, "test", 1))));
+ }
+
+ private void assertStatus(HttpStatus expected, Supplier<?> action) {
+ assertThatThrownBy(action::get)
+ .isInstanceOfSatisfying(
+ ResponseStatusException.class,
+ e -> assertThat(e.getStatusCode()).isEqualTo(expected));
+ }
+}