diff --git a/.taskfiles/backend.yml b/.taskfiles/backend.yml index 2be287bd0f..77c9645476 100644 --- a/.taskfiles/backend.yml +++ b/.taskfiles/backend.yml @@ -30,6 +30,10 @@ tasks: dev:proprietary: desc: "Start backend dev server in proprietary mode" + # `dotenv:` reads from the root Taskfile's directory (".") because this + # subtaskfile is included with `dir: .`. Local overrides in + # .env.proprietary.local win over the committed .env.proprietary defaults. + dotenv: ['app/.env.proprietary.local', 'app/.env.proprietary'] ignore_error: true vars: PORT: '{{.PORT | default "8080"}}' diff --git a/app/.env.proprietary b/app/.env.proprietary new file mode 100644 index 0000000000..4e30318e57 --- /dev/null +++ b/app/.env.proprietary @@ -0,0 +1,8 @@ +# Committed defaults for `task backend:dev:proprietary` (self-hosted / proprietary +# flavor). Local overrides + secrets live in app/.env.proprietary.local (ignored). + +# Combined-billing account link (Mode A). Feature-flagged: OFF until release. +# Flip to true in app/.env.proprietary.local to test linking locally. +STIRLING_BILLING_ACCOUNT_LINK_ENABLED=false +# SaaS base URL the linked instance calls (register + entitlement). +STIRLING_BILLING_ACCOUNT_LINK_SAAS_BASE_URL=https://stirling.com/app diff --git a/app/.gitignore b/app/.gitignore index e2a86ce4cf..f7e1a1575a 100644 --- a/app/.gitignore +++ b/app/.gitignore @@ -1,3 +1,4 @@ # Whitelist committed env defaults. `.env.saas.local` (and any other .env*) # stays ignored via the root .gitignore. !.env.saas +!.env.proprietary diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/AccountLinkClient.java b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/AccountLinkClient.java new file mode 100644 index 0000000000..a77f67f8a8 --- /dev/null +++ b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/AccountLinkClient.java @@ -0,0 +1,265 @@ +package stirling.software.proprietary.accountlink; + +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.Duration; + +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 lombok.extern.slf4j.Slf4j; + +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.ObjectMapper; + +/** + * Outbound calls from a self-hosted instance to its linked SaaS backend (combined-billing "Mode + * A"). + * + *

Two calls: + * + *

+ * + *

Uses {@code java.net.http.HttpClient} (the established self-hosted outbound pattern, see + * {@code AiEngineClient}). The base URL + client are injectable so tests can stub the SaaS + * endpoint. + */ +@Slf4j +@Service +@Profile("!saas") +@ConditionalOnProperty(name = "stirling.billing.account-link.enabled", havingValue = "true") +public class AccountLinkClient { + + static final String HEADER_DEVICE_ID = "X-Device-Id"; + static final String HEADER_DEVICE_SECRET = "X-Device-Secret"; + + private final AccountLinkProperties properties; + private final ObjectMapper mapper; + private final HttpClient httpClient; + + @Autowired + public AccountLinkClient(AccountLinkProperties properties, ObjectMapper mapper) { + this( + properties, + mapper, + HttpClient.newBuilder() + .connectTimeout(Duration.ofSeconds(properties.getRequestTimeoutSeconds())) + .build()); + } + + /** Package-private: lets tests inject a stub {@link HttpClient}. */ + AccountLinkClient( + AccountLinkProperties properties, ObjectMapper mapper, HttpClient httpClient) { + this.properties = properties; + this.mapper = mapper; + this.httpClient = httpClient; + } + + /** The device credential a successful {@link #register} returns. */ + public record RegisterResult(String deviceId, String deviceSecret, Long teamId) {} + + /** + * A non-2xx reply from the SaaS account-link API. Carries the upstream status so the caller can + * map auth failures (401/403) through rather than masking everything as a 502. + */ + public static class UpstreamException extends IOException { + private final int status; + + public UpstreamException(int status, String body) { + super("SaaS account-link returned HTTP " + status + ": " + body); + this.status = status; + } + + public int status() { + return status; + } + } + + /** + * Authoritative deny (401/403) from the entitlement endpoint — the device credential is revoked + * or invalid. Distinct from a transport/server failure (which returns {@code null} and fails + * open): the cache must BLOCK billable work on this rather than serve a stale entitled + * snapshot. Unchecked so it propagates cleanly through {@link #fetchEntitlement}'s transport + * try/catch. + */ + public static final class RevokedException extends RuntimeException { + private final int status; + + public RevokedException(int status) { + super("SaaS entitlement denied (credential revoked/invalid): HTTP " + status); + this.status = status; + } + + public int status() { + return status; + } + } + + /** + * Relays the admin Supabase JWT to the SaaS register endpoint and returns the minted + * credential. + * + * @throws IOException on transport failure or a non-2xx response (caller surfaces to the + * admin). + */ + public RegisterResult register(String supabaseJwt, String instanceName) throws IOException { + String body = + instanceName == null || instanceName.isBlank() + ? "{}" + : "{\"name\":" + mapper.writeValueAsString(instanceName) + "}"; + HttpRequest request = + HttpRequest.newBuilder() + .uri(uri("/api/v1/account-link/register")) + .header("Authorization", "Bearer " + supabaseJwt) + .header("Content-Type", "application/json") + .header("Accept", "application/json") + .timeout(timeout()) + .POST(HttpRequest.BodyPublishers.ofString(body)) + .build(); + + HttpResponse response = send(request); + if (response.statusCode() / 100 != 2) { + throw new UpstreamException(response.statusCode(), response.body()); + } + JsonNode root = mapper.readTree(response.body()); + String deviceId = text(root, "deviceId"); + String deviceSecret = text(root, "deviceSecret"); + if (deviceId == null || deviceSecret == null) { + throw new IOException("SaaS register response missing deviceId/deviceSecret"); + } + Long teamId = root.hasNonNull("teamId") ? root.get("teamId").asLong() : null; + return new RegisterResult(deviceId, deviceSecret, teamId); + } + + /** + * Revokes this instance's own credential on the SaaS side ({@code POST + * /api/v1/instance/revoke-self}), authenticated by the device credential — a credential is + * allowed to revoke its own identity. Best-effort: returns {@code false} if SaaS is unreachable + * or rejects the call, so the caller (local unlink) can still clear locally and log the orphan + * row for follow-up. Idempotent on SaaS (already-revoked → still 204). + */ + public boolean revokeSelf(String deviceId, String deviceSecret) { + try { + HttpRequest request = + HttpRequest.newBuilder() + .uri(uri("/api/v1/instance/revoke-self")) + .header(HEADER_DEVICE_ID, deviceId) + .header(HEADER_DEVICE_SECRET, deviceSecret) + .header("Accept", "application/json") + .timeout(timeout()) + .POST(HttpRequest.BodyPublishers.noBody()) + .build(); + HttpResponse response = send(request); + if (response.statusCode() / 100 != 2) { + log.debug("Self-revoke returned HTTP {}", response.statusCode()); + return false; + } + return true; + } catch (Exception e) { + log.debug("Self-revoke failed: {}", e.getMessage()); + return false; + } + } + + /** + * Fetches the current entitlement using the stored device credential. Three outcomes: + * + *

+ */ + public InstanceEntitlement fetchEntitlement(String deviceId, String deviceSecret) { + HttpResponse response; + try { + HttpRequest request = + HttpRequest.newBuilder() + .uri(uri("/api/v1/instance/entitlement")) + .header(HEADER_DEVICE_ID, deviceId) + .header(HEADER_DEVICE_SECRET, deviceSecret) + .header("Accept", "application/json") + .timeout(timeout()) + .GET() + .build(); + response = send(request); + } catch (Exception e) { + // Transport failure (timeout / connection refused / interrupted) → unknown, fail open. + log.debug("Entitlement fetch failed: {}", e.getMessage()); + return null; + } + int status = response.statusCode(); + if (status == 401 || status == 403) { + // Authoritative deny — the SaaS side rejected the credential (revoked/invalid). + throw new RevokedException(status); + } + if (status / 100 != 2) { + // Server / transient error → unknown, fail open (do NOT treat as a deny). + log.debug("Entitlement fetch returned HTTP {}", status); + return null; + } + try { + return parseEntitlement(response.body()); + } catch (IOException e) { + log.debug("Entitlement parse failed: {}", e.getMessage()); + return null; + } + } + + private InstanceEntitlement parseEntitlement(String body) throws IOException { + JsonNode root = mapper.readTree(body); + boolean subscribed = root.path("subscribed").asBoolean(false); + long freeRemaining = root.path("freeRemainingUnits").asLong(0); + long periodSpend = root.path("periodSpendUnits").asLong(0); + Long periodCap = + root.hasNonNull("periodCapUnits") ? root.get("periodCapUnits").asLong() : null; + EntitlementState state = mapState(root.path("state").asText(null)); + return new InstanceEntitlement(subscribed, freeRemaining, periodSpend, periodCap, state); + } + + /** Maps the SaaS state string to our coarse enum; unrecognised → UNKNOWN. */ + private static EntitlementState mapState(String raw) { + if (raw == null) { + return EntitlementState.UNKNOWN; + } + return switch (raw) { + case "OK", "ACTIVE", "SUBSCRIBED", "FREE" -> EntitlementState.OK; + case "OVER_LIMIT", "PAYG_LIMIT_REACHED", "BLOCKED" -> EntitlementState.OVER_LIMIT; + default -> EntitlementState.UNKNOWN; + }; + } + + private HttpResponse send(HttpRequest request) throws IOException { + try { + return httpClient.send(request, HttpResponse.BodyHandlers.ofString()); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new IOException("Interrupted calling SaaS account-link", e); + } + } + + private URI uri(String path) { + String base = properties.getSaasBaseUrl().strip().replaceAll("/+$", ""); + return URI.create(base + path); + } + + private Duration timeout() { + return Duration.ofSeconds(properties.getRequestTimeoutSeconds()); + } + + private static String text(JsonNode node, String field) { + return node.hasNonNull(field) ? node.get(field).asText() : null; + } +} diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/AccountLinkController.java b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/AccountLinkController.java new file mode 100644 index 0000000000..1d1a8aa77d --- /dev/null +++ b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/AccountLinkController.java @@ -0,0 +1,88 @@ +package stirling.software.proprietary.accountlink; + +import java.io.IOException; + +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.context.annotation.Profile; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.GetMapping; +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 io.swagger.v3.oas.annotations.Hidden; + +import lombok.extern.slf4j.Slf4j; + +/** + * Same-origin account-link surface on the self-hosted instance (combined-billing "Mode A"). + * + *

The portal (served from this same origin, admin authenticated by the existing self-hosted + * security chain) calls these. {@code POST /link} relays the admin's Supabase JWT to the SaaS + * backend, which mints + returns a device credential we store locally. {@code GET /status} backs + * the portal's link card. + * + *

Admin-only, {@code @Profile("!saas")}, gated behind {@code + * stirling.billing.account-link.enabled} — off → bean absent → 404. + */ +@Slf4j +@Hidden +@RestController +@RequestMapping("/api/v1/account-link") +@Profile("!saas") +@PreAuthorize("hasRole('ADMIN')") +@ConditionalOnProperty(name = "stirling.billing.account-link.enabled", havingValue = "true") +public class AccountLinkController { + + private final AccountLinkService service; + + public AccountLinkController(AccountLinkService service) { + this.service = service; + } + + /** {@code supabaseJwt} is the admin's short-lived token the portal already holds. */ + public record LinkRequest(String supabaseJwt, String name) {} + + @PostMapping("/link") + public ResponseEntity link(@RequestBody LinkRequest req) { + if (req == null || req.supabaseJwt() == null || req.supabaseJwt().isBlank()) { + return ResponseEntity.badRequest() + .body(java.util.Map.of("error", "supabaseJwt is required")); + } + try { + return ResponseEntity.ok(service.link(req.supabaseJwt(), req.name())); + } catch (AccountLinkClient.UpstreamException e) { + // Auth failures are the admin's token, not a gateway fault: surface 401/403 as-is so + // the portal can prompt a re-sign-in. Anything else upstream → 502. Don't echo the + // raw upstream body back to the browser. + HttpStatus status = + e.status() == HttpStatus.UNAUTHORIZED.value() + || e.status() == HttpStatus.FORBIDDEN.value() + ? HttpStatus.valueOf(e.status()) + : HttpStatus.BAD_GATEWAY; + log.warn("Account-link register rejected upstream: HTTP {}", e.status()); + return ResponseEntity.status(status).body(java.util.Map.of("error", "LINK_FAILED")); + } catch (IOException e) { + // Don't echo e.getMessage() to the browser: a DNS/connection/TLS failure can carry the + // configured SaaS host/IP. Log it server-side; return the same opaque body the + // UpstreamException branch does. + log.warn("Account-link failed (transport): {}", e.getMessage()); + return ResponseEntity.status(HttpStatus.BAD_GATEWAY) + .body(java.util.Map.of("error", "LINK_FAILED")); + } + } + + @GetMapping("/status") + public ResponseEntity status() { + return ResponseEntity.ok(service.status()); + } + + @PostMapping("/unlink") + public ResponseEntity unlink() { + service.unlink(); + return ResponseEntity.noContent().build(); + } +} diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/AccountLinkProperties.java b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/AccountLinkProperties.java new file mode 100644 index 0000000000..c12e56f06d --- /dev/null +++ b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/AccountLinkProperties.java @@ -0,0 +1,39 @@ +package stirling.software.proprietary.accountlink; + +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.stereotype.Component; + +import lombok.Getter; +import lombok.Setter; + +/** + * Self-hosted side of combined-billing "Mode A" (connected self-hosted). + * + *

Binds the {@code stirling.billing.account-link.*} keys. {@link #enabled} mirrors the same flag + * the gated beans test with {@code @ConditionalOnProperty}; it is kept here only so non-conditional + * code (e.g. the gate's flag-off short-circuit, exposed status) can read it. The whole feature is + * off by default and dark — when off nothing gates and the link endpoints 404. + */ +@Getter +@Setter +@Component +@ConfigurationProperties(prefix = "stirling.billing.account-link") +public class AccountLinkProperties { + + /** Master switch. When {@code false} (default) the feature is fully inert. */ + private boolean enabled = false; + + /** + * Base URL of the SaaS backend this instance links to (register + entitlement live there). + * + *

STUB: defaults to the public cloud host; an operator overrides it for staging. There is no + * existing SaaS-base-url property in the self-hosted profile, so this is introduced here. + */ + private String saasBaseUrl = "https://stirling.com/app"; + + /** Cached entitlement is reused for this long before a refresh is attempted. */ + private long entitlementCacheSeconds = 300; + + /** Connect/read timeout for the outbound SaaS calls. */ + private int requestTimeoutSeconds = 10; +} diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/AccountLinkService.java b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/AccountLinkService.java new file mode 100644 index 0000000000..1bb27d9cd6 --- /dev/null +++ b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/AccountLinkService.java @@ -0,0 +1,92 @@ +package stirling.software.proprietary.accountlink; + +import java.io.IOException; +import java.util.Optional; + +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.context.annotation.Profile; +import org.springframework.stereotype.Service; + +import lombok.extern.slf4j.Slf4j; + +/** + * Linking orchestrator (self-hosted side of combined-billing "Mode A"). + * + *

{@link #link} is the same-origin action the portal triggers: it relays the admin's Supabase + * JWT to the SaaS register endpoint, then persists the returned device credential secure-at-rest. + * The credential — not the JWT — authenticates all later unattended entitlement calls. + */ +@Slf4j +@Service +@Profile("!saas") +@ConditionalOnProperty(name = "stirling.billing.account-link.enabled", havingValue = "true") +public class AccountLinkService { + + private final AccountLinkClient client; + private final DeviceCredentialStore credentialStore; + private final EntitlementCache entitlementCache; + + public AccountLinkService( + AccountLinkClient client, + DeviceCredentialStore credentialStore, + EntitlementCache entitlementCache) { + this.client = client; + this.credentialStore = credentialStore; + this.entitlementCache = entitlementCache; + } + + /** Status of this instance's link, for the portal's "Account link" card. */ + public record LinkStatus(boolean linked, String deviceId, Long teamId, String linkedAt) {} + + /** + * Registers this instance with the SaaS team behind {@code supabaseJwt} and stores the + * credential. + * + * @throws IOException if the SaaS register call fails (surfaced to the admin as a link error). + */ + public LinkStatus link(String supabaseJwt, String instanceName) throws IOException { + AccountLinkClient.RegisterResult result = client.register(supabaseJwt, instanceName); + credentialStore.save(result.deviceId(), result.deviceSecret(), result.teamId()); + entitlementCache.invalidate(); + log.info("Account-link: instance linked to team {}", result.teamId()); + return status(); + } + + /** + * Unlinks this instance — best-effort tells SaaS to revoke first (so the row gets {@code + * revoked_at} set), then clears locally regardless. If SaaS is unreachable the local clear + * still proceeds (admin's intent must win); the orphan row can be revoked from the portal. + */ + public void unlink() { + credentialStore + .get() + .ifPresent( + c -> { + boolean ok = client.revokeSelf(c.getDeviceId(), c.getDeviceSecret()); + if (!ok) { + log.warn( + "Account-link: SaaS self-revoke failed for device {};" + + " clearing locally anyway (admin can revoke" + + " from the portal).", + c.getDeviceId()); + } + }); + credentialStore.clear(); + entitlementCache.invalidate(); + log.info("Account-link: instance unlinked"); + } + + public LinkStatus status() { + Optional cred = credentialStore.get(); + return cred.map( + c -> + new LinkStatus( + true, + c.getDeviceId(), + c.getTeamId(), + c.getLinkedAt() != null + ? c.getLinkedAt().toString() + : null)) + .orElseGet(() -> new LinkStatus(false, null, null, null)); + } +} diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/AccountLinkWebMvcConfig.java b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/AccountLinkWebMvcConfig.java new file mode 100644 index 0000000000..8c20abfa11 --- /dev/null +++ b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/AccountLinkWebMvcConfig.java @@ -0,0 +1,36 @@ +package stirling.software.proprietary.accountlink; + +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Profile; +import org.springframework.web.servlet.config.annotation.InterceptorRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; + +/** + * Registers the account-link entitlement gate. Path patterns cover the billable API surface; the + * interceptor itself re-checks billability (and short-circuits manual tools), but scoping here + * keeps the gate off the bulk of interactive endpoints entirely. + * + *

Whole config is gated behind {@code stirling.billing.account-link.enabled} + + * {@code @Profile("!saas")}; absent when off, so no interceptor is registered. + */ +@Configuration +@Profile("!saas") +@ConditionalOnProperty(name = "stirling.billing.account-link.enabled", havingValue = "true") +public class AccountLinkWebMvcConfig implements WebMvcConfigurer { + + private final InstanceEntitlementInterceptor gateInterceptor; + + public AccountLinkWebMvcConfig(InstanceEntitlementInterceptor gateInterceptor) { + this.gateInterceptor = gateInterceptor; + } + + @Override + public void addInterceptors(InterceptorRegistry registry) { + // AI surface is always billable; the broad /api/v1/** catch lets automation-marked manual + // calls be gated too, while the interceptor lets genuine manual tools through. + registry.addInterceptor(gateInterceptor) + .addPathPatterns("/api/v1/**") + .excludePathPatterns("/api/v1/account-link/**"); + } +} diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/BillableOperationClassifier.java b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/BillableOperationClassifier.java new file mode 100644 index 0000000000..136e4c3214 --- /dev/null +++ b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/BillableOperationClassifier.java @@ -0,0 +1,38 @@ +package stirling.software.proprietary.accountlink; + +import jakarta.servlet.http.HttpServletRequest; + +import stirling.software.common.service.InternalApiClient; + +/** + * Classifies a request as billable (AI / automation) or free (a manual tool). + * + *

Mirrors the saas billing categorisation at a coarse level, without depending on the saas + * module: billable = the AI surface ({@code /api/v1/ai/**}) or any request carrying the automation + * marker header ({@link InternalApiClient#AUTOMATION_HEADER}, set on pipeline / workflow / policy + * sub-steps). Everything else — interactive manual PDF tools — is always free. + */ +public final class BillableOperationClassifier { + + private static final String AI_PATH_PREFIX = "/api/v1/ai/"; + + private BillableOperationClassifier() {} + + public static boolean isBillable(HttpServletRequest request) { + if (request.getHeader(InternalApiClient.AUTOMATION_HEADER) != null) { + return true; + } + String uri = request.getRequestURI(); + if (uri == null) { + return false; + } + // Prefix-match the AI surface (not a loose substring contains), stripping a deployment + // context path so //api/v1/ai/** still classifies as billable. + String ctx = request.getContextPath(); + String path = + ctx != null && !ctx.isEmpty() && uri.startsWith(ctx) + ? uri.substring(ctx.length()) + : uri; + return path.startsWith(AI_PATH_PREFIX); + } +} diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/DeviceCredential.java b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/DeviceCredential.java new file mode 100644 index 0000000000..4625572310 --- /dev/null +++ b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/DeviceCredential.java @@ -0,0 +1,53 @@ +package stirling.software.proprietary.accountlink; + +import java.io.Serializable; +import java.time.LocalDateTime; + +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.Id; +import jakarta.persistence.Table; + +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; + +/** + * The device credential this self-hosted instance received when it linked a SaaS account + * (combined-billing "Mode A"). Singleton — one instance links to exactly one SaaS team. + * + *

Unlike the SaaS side (which stores only a hash), the instance must keep the plaintext {@code + * deviceSecret} so it can present it on every unattended entitlement call. It lives in the local + * database (the same store that already holds API-key material and the license signature), so it is + * as secure-at-rest as the rest of the instance's secrets. + */ +@Entity +@Table(name = "account_link_device_credential") +@NoArgsConstructor +@Getter +@Setter +public class DeviceCredential implements Serializable { + + private static final long serialVersionUID = 1L; + + public static final Long SINGLETON_ID = 1L; + + @Id + @Column(name = "id") + private Long id = SINGLETON_ID; + + /** Public identifier minted by the SaaS register call; sent as {@code X-Device-Id}. */ + @Column(name = "device_id", nullable = false, length = 64) + private String deviceId; + + /** High-entropy secret returned once by register; sent as {@code X-Device-Secret}. */ + @Column(name = "device_secret", nullable = false, length = 128) + private String deviceSecret; + + /** SaaS team this instance is linked to; informational on the instance side. */ + @Column(name = "team_id") + private Long teamId; + + @Column(name = "linked_at", nullable = false) + private LocalDateTime linkedAt; +} diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/DeviceCredentialRepository.java b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/DeviceCredentialRepository.java new file mode 100644 index 0000000000..792731e589 --- /dev/null +++ b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/DeviceCredentialRepository.java @@ -0,0 +1,15 @@ +package stirling.software.proprietary.accountlink; + +import java.util.Optional; + +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface DeviceCredentialRepository extends JpaRepository { + + /** The singleton credential, if this instance has linked. */ + default Optional findCredential() { + return findById(DeviceCredential.SINGLETON_ID); + } +} diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/DeviceCredentialStore.java b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/DeviceCredentialStore.java new file mode 100644 index 0000000000..33658a48c6 --- /dev/null +++ b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/DeviceCredentialStore.java @@ -0,0 +1,55 @@ +package stirling.software.proprietary.accountlink; + +import java.time.LocalDateTime; +import java.util.Optional; + +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.context.annotation.Profile; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +/** + * Secure-at-rest persistence for this instance's device credential. Thin wrapper over the + * singleton-row repository so the rest of the feature never touches JPA directly. + * + *

Gated + {@code @Profile("!saas")}: only the self-hosted profile links outward to a SaaS team. + */ +@Service +@Profile("!saas") +@ConditionalOnProperty(name = "stirling.billing.account-link.enabled", havingValue = "true") +public class DeviceCredentialStore { + + private final DeviceCredentialRepository repo; + + public DeviceCredentialStore(DeviceCredentialRepository repo) { + this.repo = repo; + } + + @Transactional(readOnly = true) + public Optional get() { + return repo.findCredential(); + } + + @Transactional(readOnly = true) + public boolean isLinked() { + return repo.findCredential().isPresent(); + } + + /** Persists (or replaces) the credential returned by a SaaS register call. */ + @Transactional + public void save(String deviceId, String deviceSecret, Long teamId) { + DeviceCredential cred = repo.findCredential().orElseGet(DeviceCredential::new); + cred.setId(DeviceCredential.SINGLETON_ID); + cred.setDeviceId(deviceId); + cred.setDeviceSecret(deviceSecret); + cred.setTeamId(teamId); + cred.setLinkedAt(LocalDateTime.now()); + repo.save(cred); + } + + /** Unlinks this instance locally (idempotent). */ + @Transactional + public void clear() { + repo.findCredential().ifPresent(repo::delete); + } +} diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/EntitlementCache.java b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/EntitlementCache.java new file mode 100644 index 0000000000..63818c1f98 --- /dev/null +++ b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/EntitlementCache.java @@ -0,0 +1,124 @@ +package stirling.software.proprietary.accountlink; + +import java.time.Duration; +import java.time.Instant; +import java.util.Optional; +import java.util.concurrent.atomic.AtomicBoolean; + +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.context.annotation.Profile; +import org.springframework.stereotype.Service; + +import lombok.extern.slf4j.Slf4j; + +/** + * Caches the linked team's entitlement so the request-time gate does not call the SaaS backend on + * every billable request. Single-slot (one instance = one linked team), TTL-based. + * + *

Fail-open friendly for TRANSPORT failures: {@link #current()} returns the freshest snapshot it + * has, even if a refresh just failed; it returns {@link Optional#empty()} only when nothing has + * ever been fetched and the latest refresh failed (the gate treats empty as "unknown → + * allow"). + * + *

But an AUTHORITATIVE deny (revoked/invalid credential → {@link + * AccountLinkClient.RevokedException}) is NOT a transport failure: the snapshot is replaced with a + * {@link EntitlementState#REVOKED} blocked entitlement so the gate stops billable work immediately + * rather than serving a stale entitled snapshot. + */ +@Slf4j +@Service +@Profile("!saas") +@ConditionalOnProperty(name = "stirling.billing.account-link.enabled", havingValue = "true") +public class EntitlementCache { + + private final DeviceCredentialStore credentialStore; + private final AccountLinkClient client; + private final Duration ttl; + + /** Entitlement + fetch time, swapped atomically as one value so readers never tear. */ + private record Snapshot(InstanceEntitlement entitlement, Instant fetchedAt) {} + + private static final Snapshot EMPTY = new Snapshot(null, Instant.EPOCH); + + /** Blocked entitlement synthesised on an authoritative deny (revoked/invalid credential). */ + private static final InstanceEntitlement REVOKED = + new InstanceEntitlement(false, 0, 0, null, EntitlementState.REVOKED); + + private volatile Snapshot snapshot = EMPTY; + + /** Single-flight guard: one thread refreshes while others serve the current snapshot. */ + private final AtomicBoolean refreshing = new AtomicBoolean(false); + + public EntitlementCache( + DeviceCredentialStore credentialStore, + AccountLinkClient client, + AccountLinkProperties properties) { + this.credentialStore = credentialStore; + this.client = client; + this.ttl = Duration.ofSeconds(properties.getEntitlementCacheSeconds()); + } + + /** + * Current entitlement, refreshing if stale. {@link Optional#empty()} means "unknown" — either + * not linked or the SaaS side is unreachable and we have no prior snapshot. + */ + public Optional current() { + // Single-flight: when stale, exactly one thread refreshes (blocking on the SaaS + // call) while concurrent callers serve the last snapshot — no thundering herd of + // synchronous round-trips on the billable hot path. Safe because the gate fails open. + if (isStale(snapshot) && refreshing.compareAndSet(false, true)) { + try { + refresh(); + } finally { + refreshing.set(false); + } + } + return Optional.ofNullable(snapshot.entitlement()); + } + + private boolean isStale(Snapshot snap) { + // fetchedAt is the last *attempt* time (stamped on success AND failure), so a failed + // fetch backs off for a full TTL instead of every billable request re-triggering a + // blocking round-trip against a dead/slow SaaS endpoint. + return Duration.between(snap.fetchedAt(), Instant.now()).compareTo(ttl) >= 0; + } + + /** + * Pulls a fresh snapshot. Keeps the previous entitlement on a TRANSPORT failure (fail-open) but + * still stamps the attempt time so re-fetches throttle to the TTL; on an AUTHORITATIVE deny + * (revoked credential) replaces it with a blocked snapshot so the gate stops billable work. + */ + void refresh() { + Optional cred = credentialStore.get(); + if (cred.isEmpty()) { + // Unlinked: clear any stale snapshot so the gate sees "not linked". + snapshot = new Snapshot(null, Instant.now()); + return; + } + try { + InstanceEntitlement fresh = + client.fetchEntitlement(cred.get().getDeviceId(), cred.get().getDeviceSecret()); + if (fresh != null) { + snapshot = new Snapshot(fresh, Instant.now()); + } else { + // Unreachable / server error: keep the last known entitlement (may be null) but + // stamp the attempt so we don't hammer SaaS; the gate fails open in the meantime. + log.debug( + "Entitlement refresh failed; reusing last known snapshot, backing off a TTL"); + snapshot = new Snapshot(snapshot.entitlement(), Instant.now()); + } + } catch (AccountLinkClient.RevokedException e) { + // Authoritative deny — credential revoked/invalid. Do NOT fail open: block immediately + // rather than serving the stale entitled snapshot until the next unlink. + log.info( + "Entitlement denied (HTTP {}); blocking billable work for the revoked credential", + e.status()); + snapshot = new Snapshot(REVOKED, Instant.now()); + } + } + + /** Forces a refresh on the next {@link #current()} (e.g. right after linking). */ + public void invalidate() { + snapshot = new Snapshot(snapshot.entitlement(), Instant.EPOCH); + } +} diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/EntitlementState.java b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/EntitlementState.java new file mode 100644 index 0000000000..1cca34cb69 --- /dev/null +++ b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/EntitlementState.java @@ -0,0 +1,19 @@ +package stirling.software.proprietary.accountlink; + +/** + * Coarse entitlement state the local gate enforces against. Proprietary-local (no coupling to the + * saas billing module): the SaaS entitlement response is parsed into this minimal shape. + */ +public enum EntitlementState { + /** Within free pool or covered by an active subscription — billable work allowed. */ + OK, + /** Free pool exhausted and no subscription / over the period cap — billable work blocked. */ + OVER_LIMIT, + /** + * Device credential revoked/invalid on the SaaS side (authoritative 401/403 deny) — billable + * work blocked. Synthesised locally by {@code EntitlementCache}, never sent by SaaS. + */ + REVOKED, + /** Unrecognised/malformed reply — the gate falls back to its numeric checks, not this flag. */ + UNKNOWN +} diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/GateDecision.java b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/GateDecision.java new file mode 100644 index 0000000000..677183278b --- /dev/null +++ b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/GateDecision.java @@ -0,0 +1,34 @@ +package stirling.software.proprietary.accountlink; + +/** + * Outcome of {@link InstanceEntitlementGate}. {@link #allowed} is what the interceptor enforces; + * {@link #reason} carries the machine-readable signal the FE maps to a prompt (e.g. "link to + * activate"). Manual-tool and fail-open allows carry an informational reason but never block. + */ +public record GateDecision(boolean allowed, Reason reason) { + + public enum Reason { + /** Feature flag is off — gate is fully inert. */ + FLAG_OFF, + /** Operation is a manual tool — always free, never gated. */ + MANUAL_FREE, + /** Linked + within entitlement — billable work allowed. */ + ENTITLED, + /** Entitlement source unreachable — fail open, allow. */ + FAIL_OPEN, + /** Not linked — block billable work; FE should prompt to link. */ + NOT_LINKED, + /** Linked but over the limit / no subscription — block billable work. */ + OVER_LIMIT, + /** Credential revoked/invalid on the SaaS side — block billable work. */ + REVOKED + } + + public static GateDecision allow(Reason reason) { + return new GateDecision(true, reason); + } + + public static GateDecision block(Reason reason) { + return new GateDecision(false, reason); + } +} diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/InstanceEntitlement.java b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/InstanceEntitlement.java new file mode 100644 index 0000000000..6445d886e9 --- /dev/null +++ b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/InstanceEntitlement.java @@ -0,0 +1,19 @@ +package stirling.software.proprietary.accountlink; + +/** + * Cached, proprietary-local view of the SaaS {@code GET /api/v1/instance/entitlement} response — + * just the fields the gate needs. Mirrors the saas {@code EntitlementResponse} shape but carries no + * saas types. + * + * @param subscribed team has an active subscription + * @param freeRemainingUnits remaining free-pool units (>0 means free work is available) + * @param periodSpendUnits paid units spent this period + * @param periodCapUnits paid cap for the period; {@code null} = uncapped + * @param state coarse state classification (see {@link EntitlementState}) + */ +public record InstanceEntitlement( + boolean subscribed, + long freeRemainingUnits, + long periodSpendUnits, + Long periodCapUnits, + EntitlementState state) {} diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/InstanceEntitlementGate.java b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/InstanceEntitlementGate.java new file mode 100644 index 0000000000..c975bad055 --- /dev/null +++ b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/InstanceEntitlementGate.java @@ -0,0 +1,104 @@ +package stirling.software.proprietary.accountlink; + +import java.util.Optional; + +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.context.annotation.Profile; +import org.springframework.stereotype.Service; + +/** + * Decides whether a request may proceed under combined-billing "Mode A" on a self-hosted instance. + * + *

Rules (in order): + * + *

    + *
  1. Flag off → always allow (feature inert). + *
  2. Manual tool → always allow (manual tools are free, never metered). + *
  3. Billable + not linked → block with {@code NOT_LINKED} ("link to activate"). + *
  4. Billable + linked + entitlement unknown (unreachable) → fail open, allow. + *
  5. Billable + linked + entitled → allow. + *
  6. Billable + linked + credential revoked → block with {@code REVOKED}. + *
  7. Billable + linked + over limit → block with {@code OVER_LIMIT}. + *
+ * + *

The decision logic is the pure static {@link #decide}; the Spring wrapper just supplies the + * live flag / linked-state / entitlement. This is the unit-tested core. + */ +@Service +@Profile("!saas") +@ConditionalOnProperty(name = "stirling.billing.account-link.enabled", havingValue = "true") +public class InstanceEntitlementGate { + + private final AccountLinkProperties properties; + private final DeviceCredentialStore credentialStore; + private final EntitlementCache entitlementCache; + + public InstanceEntitlementGate( + AccountLinkProperties properties, + DeviceCredentialStore credentialStore, + EntitlementCache entitlementCache) { + this.properties = properties; + this.credentialStore = credentialStore; + this.entitlementCache = entitlementCache; + } + + /** Evaluates the gate for a request, resolving live state from the store + cache. */ + public GateDecision evaluate(boolean billable) { + if (!properties.isEnabled()) { + return GateDecision.allow(GateDecision.Reason.FLAG_OFF); + } + if (!billable) { + return GateDecision.allow(GateDecision.Reason.MANUAL_FREE); + } + boolean linked = credentialStore.isLinked(); + Optional entitlement = + linked ? entitlementCache.current() : Optional.empty(); + return decide(true, true, linked, entitlement); + } + + /** + * Pure decision function — no Spring, no I/O. {@code entitlement} empty means "unknown" + * (unreachable): when linked, that fails open. + */ + public static GateDecision decide( + boolean flagEnabled, + boolean billable, + boolean linked, + Optional entitlement) { + if (!flagEnabled) { + return GateDecision.allow(GateDecision.Reason.FLAG_OFF); + } + if (!billable) { + return GateDecision.allow(GateDecision.Reason.MANUAL_FREE); + } + if (!linked) { + return GateDecision.block(GateDecision.Reason.NOT_LINKED); + } + if (entitlement.isEmpty()) { + // Linked but entitlement source unreachable — never hard-block billable work on our + // inability to reach billing. + return GateDecision.allow(GateDecision.Reason.FAIL_OPEN); + } + InstanceEntitlement e = entitlement.get(); + if (e.state() == EntitlementState.REVOKED) { + // Credential revoked/invalid (authoritative deny) — block, distinct from over-limit. + return GateDecision.block(GateDecision.Reason.REVOKED); + } + return entitled(e) + ? GateDecision.allow(GateDecision.Reason.ENTITLED) + : GateDecision.block(GateDecision.Reason.OVER_LIMIT); + } + + /** True when the snapshot permits billable work (subscribed, free pool left, or within cap). */ + private static boolean entitled(InstanceEntitlement e) { + if (e.state() == EntitlementState.OVER_LIMIT || e.state() == EntitlementState.REVOKED) { + return false; + } + if (e.subscribed()) { + // Subscribed: allowed unless a period cap is set and exceeded. + return e.periodCapUnits() == null || e.periodSpendUnits() < e.periodCapUnits(); + } + // Unsubscribed: only the free pool covers billable work. + return e.freeRemainingUnits() > 0; + } +} diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/InstanceEntitlementInterceptor.java b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/InstanceEntitlementInterceptor.java new file mode 100644 index 0000000000..8597813a85 --- /dev/null +++ b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/InstanceEntitlementInterceptor.java @@ -0,0 +1,65 @@ +package stirling.software.proprietary.accountlink; + +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.context.annotation.Profile; +import org.springframework.http.HttpStatus; +import org.springframework.stereotype.Component; +import org.springframework.web.servlet.HandlerInterceptor; + +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; + +import lombok.extern.slf4j.Slf4j; + +/** + * Request-time gate for combined-billing "Mode A". Runs before billable (AI / automation) work and + * blocks it when the instance is unlinked or over its limit; manual tools pass straight through. + * + *

Blocking responds {@code 402 Payment Required} with a small machine-readable body — {@code + * {"error":"ACCOUNT_LINK_REQUIRED","reason":"NOT_LINKED"}} — that the FE maps to a "link to + * activate" prompt (the same DownstreamEntitlementError-style envelope already used for saas limit + * responses). Fail-open and flag-off both let the request continue. + * + *

Gated + {@code @Profile("!saas")}; when the flag is off the bean is absent and the {@link + * AccountLinkWebMvcConfig} never registers it, so there is no per-request cost. + */ +@Slf4j +@Component +@Profile("!saas") +@ConditionalOnProperty(name = "stirling.billing.account-link.enabled", havingValue = "true") +public class InstanceEntitlementInterceptor implements HandlerInterceptor { + + private final InstanceEntitlementGate gate; + + public InstanceEntitlementInterceptor(InstanceEntitlementGate gate) { + this.gate = gate; + } + + @Override + public boolean preHandle( + HttpServletRequest request, HttpServletResponse response, Object handler) + throws Exception { + GateDecision decision; + try { + decision = gate.evaluate(BillableOperationClassifier.isBillable(request)); + } catch (RuntimeException e) { + // Fail open: an inability to resolve entitlement (e.g. a DB or SaaS blip) must never + // turn into a hard block on billable work. + log.debug("Account-link gate evaluation failed; allowing request", e); + return true; + } + if (decision.allowed()) { + return true; + } + + log.debug("Account-link gate blocked {} ({})", request.getRequestURI(), decision.reason()); + response.setStatus(HttpStatus.PAYMENT_REQUIRED.value()); + response.setContentType("application/json"); + response.getWriter() + .write( + "{\"error\":\"ACCOUNT_LINK_REQUIRED\",\"reason\":\"" + + decision.reason().name() + + "\"}"); + return false; + } +} 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 3c713206de..ee449b31f2 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 @@ -33,6 +33,7 @@ import stirling.software.common.model.exception.UnsupportedProviderException; "stirling.software.proprietary.storage.repository", "stirling.software.proprietary.workflow.repository", "stirling.software.proprietary.policy.store", + "stirling.software.proprietary.accountlink", "stirling.software.proprietary.policy.source" }) @EntityScan({ @@ -41,6 +42,7 @@ import stirling.software.common.model.exception.UnsupportedProviderException; "stirling.software.proprietary.storage.model", "stirling.software.proprietary.workflow.model", "stirling.software.proprietary.policy.store", + "stirling.software.proprietary.accountlink", "stirling.software.proprietary.policy.source" }) public class DatabaseConfig { diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/AccountLinkClientTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/AccountLinkClientTest.java new file mode 100644 index 0000000000..7d954a4398 --- /dev/null +++ b/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/AccountLinkClientTest.java @@ -0,0 +1,192 @@ +package stirling.software.proprietary.accountlink; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.net.ConnectException; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; + +import tools.jackson.databind.ObjectMapper; + +/** + * Stubs the {@link HttpClient} so the SaaS endpoint is never actually called. Confirms register + * relays the JWT and parses the credential, and that entitlement parsing + the fail-open (null on + * unreachable) behaviour hold. + */ +class AccountLinkClientTest { + + private AccountLinkProperties properties; + private HttpClient httpClient; + private AccountLinkClient client; + + @BeforeEach + void setUp() { + properties = new AccountLinkProperties(); + properties.setEnabled(true); + properties.setSaasBaseUrl("https://saas.example.com"); + httpClient = mock(HttpClient.class); + client = new AccountLinkClient(properties, new ObjectMapper(), httpClient); + } + + @SuppressWarnings("unchecked") + private HttpResponse response(int status, String body) { + HttpResponse resp = mock(HttpResponse.class); + when(resp.statusCode()).thenReturn(status); + when(resp.body()).thenReturn(body); + return resp; + } + + @Test + @SuppressWarnings("unchecked") + void registerRelaysJwtAndParsesCredential() throws Exception { + // Build the stub response first: nesting response() inside when() trips Mockito's + // unfinished-stubbing check (inner when() runs mid outer when()). + HttpResponse resp = + response(201, "{\"deviceId\":\"dev-1\",\"deviceSecret\":\"sec-1\",\"teamId\":42}"); + ArgumentCaptor captor = ArgumentCaptor.forClass(HttpRequest.class); + when(httpClient.send(captor.capture(), any(HttpResponse.BodyHandler.class))) + .thenReturn(resp); + + AccountLinkClient.RegisterResult result = client.register("jwt-token", "My Server"); + + assertEquals("dev-1", result.deviceId()); + assertEquals("sec-1", result.deviceSecret()); + assertEquals(42L, result.teamId()); + + HttpRequest sent = captor.getValue(); + assertEquals("Bearer jwt-token", sent.headers().firstValue("Authorization").orElse(null)); + assertEquals( + "https://saas.example.com/api/v1/account-link/register", sent.uri().toString()); + } + + @Test + @SuppressWarnings("unchecked") + void registerThrowsUpstreamExceptionWithStatusOnNon2xx() throws Exception { + HttpResponse resp = response(401, "{\"error\":\"unauthorized\"}"); + when(httpClient.send(any(), any(HttpResponse.BodyHandler.class))).thenReturn(resp); + AccountLinkClient.UpstreamException ex = + assertThrows( + AccountLinkClient.UpstreamException.class, + () -> client.register("jwt", null)); + assertEquals(401, ex.status()); + } + + @Test + @SuppressWarnings("unchecked") + void fetchEntitlementParsesSnapshotAndSendsDeviceHeaders() throws Exception { + HttpResponse resp = + response( + 200, + "{\"subscribed\":true,\"freeRemainingUnits\":0,\"periodSpendUnits\":10,\"periodCapUnits\":100,\"state\":\"OK\"}"); + ArgumentCaptor captor = ArgumentCaptor.forClass(HttpRequest.class); + when(httpClient.send(captor.capture(), any(HttpResponse.BodyHandler.class))) + .thenReturn(resp); + + InstanceEntitlement e = client.fetchEntitlement("dev-1", "sec-1"); + + assertNotNull(e); + assertEquals(true, e.subscribed()); + assertEquals(10, e.periodSpendUnits()); + assertEquals(100L, e.periodCapUnits()); + assertEquals(EntitlementState.OK, e.state()); + + HttpRequest sent = captor.getValue(); + assertEquals("dev-1", sent.headers().firstValue("X-Device-Id").orElse(null)); + assertEquals("sec-1", sent.headers().firstValue("X-Device-Secret").orElse(null)); + } + + @Test + @SuppressWarnings("unchecked") + void fetchEntitlementMapsOverLimitState() throws Exception { + // Pins the consume side of the wire contract: InstanceController emits "OVER_LIMIT" (for a + // DEGRADED team) and the client must map it to the gate-blocking state. + HttpResponse resp = + response( + 200, + "{\"subscribed\":true,\"freeRemainingUnits\":0,\"periodSpendUnits\":1300,\"periodCapUnits\":1250,\"state\":\"OVER_LIMIT\"}"); + when(httpClient.send(any(), any(HttpResponse.BodyHandler.class))).thenReturn(resp); + + InstanceEntitlement e = client.fetchEntitlement("dev-1", "sec-1"); + + assertNotNull(e); + assertEquals(EntitlementState.OVER_LIMIT, e.state()); + } + + @Test + @SuppressWarnings("unchecked") + void fetchEntitlementReturnsNullWhenUnreachable() throws Exception { + when(httpClient.send(any(), any(HttpResponse.BodyHandler.class))) + .thenThrow(new ConnectException("refused")); + // Null = unknown → the cache/gate fail open. + assertNull(client.fetchEntitlement("dev-1", "sec-1")); + } + + @Test + @SuppressWarnings("unchecked") + void fetchEntitlementReturnsNullOnServerError() throws Exception { + // 5xx is a transient/server failure, not a credential deny → null, the cache fails open. + HttpResponse resp = response(503, "{}"); + when(httpClient.send(any(), any(HttpResponse.BodyHandler.class))).thenReturn(resp); + assertNull(client.fetchEntitlement("dev-1", "sec-1")); + } + + @Test + @SuppressWarnings("unchecked") + void fetchEntitlementThrowsRevokedOnDeny() throws Exception { + // 401/403 = authoritative deny (revoked/invalid credential) → RevokedException, NOT null: + // the cache must block billable work rather than fail open on a stale snapshot. + for (int status : new int[] {401, 403}) { + HttpResponse resp = response(status, "{}"); + when(httpClient.send(any(), any(HttpResponse.BodyHandler.class))).thenReturn(resp); + AccountLinkClient.RevokedException ex = + assertThrows( + AccountLinkClient.RevokedException.class, + () -> client.fetchEntitlement("dev-1", "sec-1")); + assertEquals(status, ex.status()); + } + } + + @Test + @SuppressWarnings("unchecked") + void revokeSelfSendsDeviceHeadersAndReturnsTrueOn2xx() throws Exception { + HttpResponse resp = response(204, ""); + ArgumentCaptor captor = ArgumentCaptor.forClass(HttpRequest.class); + when(httpClient.send(captor.capture(), any(HttpResponse.BodyHandler.class))) + .thenReturn(resp); + + assertEquals(true, client.revokeSelf("dev-1", "sec-1")); + + HttpRequest sent = captor.getValue(); + assertEquals("https://saas.example.com/api/v1/instance/revoke-self", sent.uri().toString()); + assertEquals("dev-1", sent.headers().firstValue("X-Device-Id").orElse(null)); + assertEquals("sec-1", sent.headers().firstValue("X-Device-Secret").orElse(null)); + assertEquals("POST", sent.method()); + } + + @Test + @SuppressWarnings("unchecked") + void revokeSelfReturnsFalseOnErrorStatus() throws Exception { + HttpResponse resp = response(403, "{}"); + when(httpClient.send(any(), any(HttpResponse.BodyHandler.class))).thenReturn(resp); + assertEquals(false, client.revokeSelf("dev-1", "sec-1")); + } + + @Test + @SuppressWarnings("unchecked") + void revokeSelfReturnsFalseWhenUnreachable() throws Exception { + when(httpClient.send(any(), any(HttpResponse.BodyHandler.class))) + .thenThrow(new ConnectException("refused")); + assertEquals(false, client.revokeSelf("dev-1", "sec-1")); + } +} diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/AccountLinkControllerTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/AccountLinkControllerTest.java new file mode 100644 index 0000000000..6e4a816bb0 --- /dev/null +++ b/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/AccountLinkControllerTest.java @@ -0,0 +1,68 @@ +package stirling.software.proprietary.accountlink; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.io.IOException; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; + +import stirling.software.proprietary.accountlink.AccountLinkController.LinkRequest; + +/** + * The local (self-hosted) account-link controller's error mapping: an upstream auth rejection + * surfaces as 401/403 (so the portal can prompt a re-sign-in) while other upstream / transport + * faults are a 502. + */ +class AccountLinkControllerTest { + + private AccountLinkService service; + private AccountLinkController controller; + + @BeforeEach + void setUp() { + service = mock(AccountLinkService.class); + controller = new AccountLinkController(service); + } + + @Test + void link_missingJwt_returns400() { + ResponseEntity resp = controller.link(new LinkRequest(" ", null)); + assertThat(resp.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST); + } + + @Test + void link_upstreamUnauthorized_maps401() throws Exception { + when(service.link("jwt", null)) + .thenThrow(new AccountLinkClient.UpstreamException(401, "bad token")); + ResponseEntity resp = controller.link(new LinkRequest("jwt", null)); + assertThat(resp.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED); + } + + @Test + void link_upstreamForbidden_maps403() throws Exception { + when(service.link("jwt", null)) + .thenThrow(new AccountLinkClient.UpstreamException(403, "forbidden")); + ResponseEntity resp = controller.link(new LinkRequest("jwt", null)); + assertThat(resp.getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN); + } + + @Test + void link_upstreamServerError_maps502() throws Exception { + when(service.link("jwt", null)) + .thenThrow(new AccountLinkClient.UpstreamException(500, "boom")); + ResponseEntity resp = controller.link(new LinkRequest("jwt", null)); + assertThat(resp.getStatusCode()).isEqualTo(HttpStatus.BAD_GATEWAY); + } + + @Test + void link_transportFailure_maps502() throws Exception { + when(service.link("jwt", null)).thenThrow(new IOException("connection refused")); + ResponseEntity resp = controller.link(new LinkRequest("jwt", null)); + assertThat(resp.getStatusCode()).isEqualTo(HttpStatus.BAD_GATEWAY); + } +} diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/AccountLinkServiceTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/AccountLinkServiceTest.java new file mode 100644 index 0000000000..b909fb37a0 --- /dev/null +++ b/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/AccountLinkServiceTest.java @@ -0,0 +1,111 @@ +package stirling.software.proprietary.accountlink; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.io.IOException; +import java.time.LocalDateTime; +import java.util.Optional; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +class AccountLinkServiceTest { + + private AccountLinkClient client; + private DeviceCredentialStore store; + private EntitlementCache cache; + private AccountLinkService service; + + @BeforeEach + void setUp() { + client = mock(AccountLinkClient.class); + store = mock(DeviceCredentialStore.class); + cache = mock(EntitlementCache.class); + service = new AccountLinkService(client, store, cache); + } + + @Test + void link_storesCredentialAndInvalidatesCache() throws IOException { + when(client.register("jwt", "name")) + .thenReturn(new AccountLinkClient.RegisterResult("dev-1", "sec-1", 7L)); + DeviceCredential stored = new DeviceCredential(); + stored.setDeviceId("dev-1"); + stored.setTeamId(7L); + stored.setLinkedAt(LocalDateTime.now()); + when(store.get()).thenReturn(Optional.of(stored)); + + AccountLinkService.LinkStatus status = service.link("jwt", "name"); + + verify(store).save("dev-1", "sec-1", 7L); + verify(cache).invalidate(); + assertTrue(status.linked()); + assertEquals("dev-1", status.deviceId()); + assertEquals(7L, status.teamId()); + } + + @Test + void link_propagatesRegisterFailure() throws IOException { + when(client.register(any(), any())).thenThrow(new IOException("boom")); + org.junit.jupiter.api.Assertions.assertThrows( + IOException.class, () -> service.link("jwt", null)); + verify(cache, org.mockito.Mockito.never()).invalidate(); + } + + @Test + void status_unlinkedWhenNoCredential() { + when(store.get()).thenReturn(Optional.empty()); + AccountLinkService.LinkStatus status = service.status(); + assertFalse(status.linked()); + } + + @Test + void unlink_callsSaasRevokeBeforeClearingLocally() { + DeviceCredential cred = new DeviceCredential(); + cred.setDeviceId("dev-1"); + cred.setDeviceSecret("sec-1"); + cred.setTeamId(7L); + cred.setLinkedAt(LocalDateTime.now()); + when(store.get()).thenReturn(Optional.of(cred)); + when(client.revokeSelf("dev-1", "sec-1")).thenReturn(true); + + service.unlink(); + + verify(client).revokeSelf("dev-1", "sec-1"); + verify(store).clear(); + verify(cache).invalidate(); + } + + @Test + void unlink_clearsLocallyEvenWhenSaasRevokeFails() { + DeviceCredential cred = new DeviceCredential(); + cred.setDeviceId("dev-1"); + cred.setDeviceSecret("sec-1"); + cred.setLinkedAt(LocalDateTime.now()); + when(store.get()).thenReturn(Optional.of(cred)); + // SaaS unreachable / returns non-2xx. + when(client.revokeSelf("dev-1", "sec-1")).thenReturn(false); + + service.unlink(); + + // Local clear MUST still happen — admin's intent wins; orphan row is a follow-up. + verify(store).clear(); + verify(cache).invalidate(); + } + + @Test + void unlink_whenAlreadyUnlinked_skipsSaasRevoke() { + when(store.get()).thenReturn(Optional.empty()); + + service.unlink(); + + org.mockito.Mockito.verifyNoInteractions(client); + verify(store).clear(); + verify(cache).invalidate(); + } +} diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/BillableOperationClassifierTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/BillableOperationClassifierTest.java new file mode 100644 index 0000000000..275026794a --- /dev/null +++ b/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/BillableOperationClassifierTest.java @@ -0,0 +1,49 @@ +package stirling.software.proprietary.accountlink; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.junit.jupiter.api.Test; +import org.springframework.mock.web.MockHttpServletRequest; + +import stirling.software.common.service.InternalApiClient; + +class BillableOperationClassifierTest { + + @Test + void aiPathIsBillable() { + MockHttpServletRequest req = new MockHttpServletRequest("POST", "/api/v1/ai/tools/foo"); + assertTrue(BillableOperationClassifier.isBillable(req)); + } + + @Test + void automationHeaderIsBillable() { + MockHttpServletRequest req = new MockHttpServletRequest("POST", "/api/v1/general/merge"); + req.addHeader(InternalApiClient.AUTOMATION_HEADER, "1"); + assertTrue(BillableOperationClassifier.isBillable(req)); + } + + @Test + void plainManualToolIsFree() { + MockHttpServletRequest req = new MockHttpServletRequest("POST", "/api/v1/general/merge"); + assertFalse(BillableOperationClassifier.isBillable(req)); + } + + @Test + void aiSegmentNotAtPathStartIsFree() { + // Tightened from substring to prefix: the AI segment appearing mid-path (e.g. behind a + // proxy prefix) must NOT classify a manual tool as billable. + MockHttpServletRequest req = + new MockHttpServletRequest("POST", "/proxy/api/v1/ai/tools/foo"); + assertFalse(BillableOperationClassifier.isBillable(req)); + } + + @Test + void aiPathUnderContextPathIsBillable() { + // A real context-path deployment still classifies: //api/v1/ai/** is billable. + MockHttpServletRequest req = + new MockHttpServletRequest("POST", "/stirling/api/v1/ai/tools/foo"); + req.setContextPath("/stirling"); + assertTrue(BillableOperationClassifier.isBillable(req)); + } +} diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/EntitlementCacheTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/EntitlementCacheTest.java new file mode 100644 index 0000000000..3dbeb1ef5c --- /dev/null +++ b/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/EntitlementCacheTest.java @@ -0,0 +1,114 @@ +package stirling.software.proprietary.accountlink; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.time.LocalDateTime; +import java.util.Optional; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +class EntitlementCacheTest { + + private DeviceCredentialStore store; + private AccountLinkClient client; + private AccountLinkProperties properties; + private EntitlementCache cache; + + @BeforeEach + void setUp() { + store = mock(DeviceCredentialStore.class); + client = mock(AccountLinkClient.class); + properties = new AccountLinkProperties(); + properties.setEntitlementCacheSeconds(300); + cache = new EntitlementCache(store, client, properties); + } + + private DeviceCredential cred() { + DeviceCredential c = new DeviceCredential(); + c.setDeviceId("dev-1"); + c.setDeviceSecret("sec-1"); + c.setTeamId(1L); + c.setLinkedAt(LocalDateTime.now()); + return c; + } + + @Test + void unlinked_returnsEmpty() { + when(store.get()).thenReturn(Optional.empty()); + assertTrue(cache.current().isEmpty()); + } + + @Test + void linked_fetchesAndCachesWithinTtl() { + InstanceEntitlement snap = new InstanceEntitlement(false, 10, 0, null, EntitlementState.OK); + when(store.get()).thenReturn(Optional.of(cred())); + when(client.fetchEntitlement(anyString(), anyString())).thenReturn(snap); + + assertEquals(snap, cache.current().orElseThrow()); + // Second read within TTL must not re-fetch. + assertEquals(snap, cache.current().orElseThrow()); + verify(client, times(1)).fetchEntitlement(any(), any()); + } + + @Test + void linked_unreachable_keepsLastKnownSnapshot_failOpenFriendly() { + InstanceEntitlement snap = new InstanceEntitlement(true, 0, 1, 100L, EntitlementState.OK); + when(store.get()).thenReturn(Optional.of(cred())); + when(client.fetchEntitlement(anyString(), anyString())).thenReturn(snap); + assertEquals(snap, cache.current().orElseThrow()); + + // TTL elapsed → refresh attempted, but the SaaS side is now unreachable (null). + cache.invalidate(); + when(client.fetchEntitlement(anyString(), anyString())).thenReturn(null); + assertEquals(snap, cache.current().orElseThrow(), "stale snapshot retained on failure"); + } + + @Test + void linked_neverFetched_unreachable_backsOffWithinTtl() { + // No prior snapshot + SaaS unreachable: the gate fails open (empty), but a failed + // attempt stamps the TTL so a second read within the window does NOT re-fetch — + // no sustained hammer of blocking round-trips against a dead endpoint. + when(store.get()).thenReturn(Optional.of(cred())); + when(client.fetchEntitlement(anyString(), anyString())).thenReturn(null); + + assertTrue(cache.current().isEmpty()); + assertTrue(cache.current().isEmpty()); + verify(client, times(1)).fetchEntitlement(any(), any()); + } + + @Test + void linked_revoked_blocksAndDropsStaleEntitlement() { + InstanceEntitlement entitled = + new InstanceEntitlement(true, 0, 1, 100L, EntitlementState.OK); + when(store.get()).thenReturn(Optional.of(cred())); + when(client.fetchEntitlement(anyString(), anyString())).thenReturn(entitled); + assertEquals(entitled, cache.current().orElseThrow()); + + // Credential revoked: the next refresh is an authoritative deny. The cache must NOT keep + // serving the stale entitled snapshot — it replaces it with a blocked REVOKED one. + cache.invalidate(); + when(client.fetchEntitlement(anyString(), anyString())) + .thenThrow(new AccountLinkClient.RevokedException(401)); + assertEquals(EntitlementState.REVOKED, cache.current().orElseThrow().state()); + } + + @Test + void invalidate_forcesRefetch() { + InstanceEntitlement snap = new InstanceEntitlement(false, 10, 0, null, EntitlementState.OK); + when(store.get()).thenReturn(Optional.of(cred())); + when(client.fetchEntitlement(anyString(), anyString())).thenReturn(snap); + + cache.current(); + cache.invalidate(); + cache.current(); + verify(client, times(2)).fetchEntitlement(any(), any()); + } +} diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/InstanceEntitlementGateTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/InstanceEntitlementGateTest.java new file mode 100644 index 0000000000..0c250fd3e9 --- /dev/null +++ b/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/InstanceEntitlementGateTest.java @@ -0,0 +1,117 @@ +package stirling.software.proprietary.accountlink; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.Optional; + +import org.junit.jupiter.api.Test; + +import stirling.software.proprietary.accountlink.GateDecision.Reason; + +/** + * Covers the gate decision matrix: flag-off, manual-free, unlinked, fail-open, linked-free, and + * over-limit. Exercises the pure {@link InstanceEntitlementGate#decide} so no Spring / I/O is + * needed. + */ +class InstanceEntitlementGateTest { + + private static InstanceEntitlement free() { + return new InstanceEntitlement(false, 100, 0, null, EntitlementState.OK); + } + + private static InstanceEntitlement exhaustedUnsubscribed() { + return new InstanceEntitlement(false, 0, 0, null, EntitlementState.OVER_LIMIT); + } + + private static InstanceEntitlement subscribedWithinCap() { + return new InstanceEntitlement(true, 0, 10, 100L, EntitlementState.OK); + } + + private static InstanceEntitlement subscribedOverCap() { + return new InstanceEntitlement(true, 0, 100, 100L, EntitlementState.OK); + } + + @Test + void flagOff_allowsEverything_evenBillableUnlinked() { + GateDecision d = InstanceEntitlementGate.decide(false, true, false, Optional.empty()); + assertTrue(d.allowed()); + assertEquals(Reason.FLAG_OFF, d.reason()); + } + + @Test + void manualTool_alwaysFree_evenUnlinked() { + GateDecision d = InstanceEntitlementGate.decide(true, false, false, Optional.empty()); + assertTrue(d.allowed()); + assertEquals(Reason.MANUAL_FREE, d.reason()); + } + + @Test + void billable_notLinked_blocksWithLinkSignal() { + GateDecision d = InstanceEntitlementGate.decide(true, true, false, Optional.empty()); + assertFalse(d.allowed()); + assertEquals(Reason.NOT_LINKED, d.reason()); + } + + @Test + void billable_linked_entitlementUnreachable_failsOpen() { + GateDecision d = InstanceEntitlementGate.decide(true, true, true, Optional.empty()); + assertTrue(d.allowed()); + assertEquals(Reason.FAIL_OPEN, d.reason()); + } + + @Test + void billable_linked_freePoolAvailable_allows() { + GateDecision d = InstanceEntitlementGate.decide(true, true, true, Optional.of(free())); + assertTrue(d.allowed()); + assertEquals(Reason.ENTITLED, d.reason()); + } + + @Test + void billable_linked_unsubscribedAndExhausted_blocksOverLimit() { + GateDecision d = + InstanceEntitlementGate.decide( + true, true, true, Optional.of(exhaustedUnsubscribed())); + assertFalse(d.allowed()); + assertEquals(Reason.OVER_LIMIT, d.reason()); + } + + @Test + void billable_linked_subscribedWithinCap_allows() { + GateDecision d = + InstanceEntitlementGate.decide( + true, true, true, Optional.of(subscribedWithinCap())); + assertTrue(d.allowed()); + assertEquals(Reason.ENTITLED, d.reason()); + } + + @Test + void billable_linked_subscribedOverCap_blocks() { + GateDecision d = + InstanceEntitlementGate.decide(true, true, true, Optional.of(subscribedOverCap())); + assertFalse(d.allowed()); + assertEquals(Reason.OVER_LIMIT, d.reason()); + } + + @Test + void billable_linked_revoked_blocksWithRevokedSignal() { + // Authoritative deny (revoked/invalid credential) surfaced by the cache as REVOKED — + // blocks distinctly from over-limit, even though the snapshot is "present". + InstanceEntitlement revoked = + new InstanceEntitlement(false, 0, 0, null, EntitlementState.REVOKED); + GateDecision d = InstanceEntitlementGate.decide(true, true, true, Optional.of(revoked)); + assertFalse(d.allowed()); + assertEquals(Reason.REVOKED, d.reason()); + } + + @Test + void billable_linked_unsubscribedWithFreePool_overLimitStateStillBlocks() { + // Defensive: an explicit OVER_LIMIT state blocks even if a stale free count looks positive. + InstanceEntitlement conflicting = + new InstanceEntitlement(false, 5, 0, null, EntitlementState.OVER_LIMIT); + GateDecision d = InstanceEntitlementGate.decide(true, true, true, Optional.of(conflicting)); + assertFalse(d.allowed()); + assertEquals(Reason.OVER_LIMIT, d.reason()); + } +} diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/InstanceEntitlementGateWiringTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/InstanceEntitlementGateWiringTest.java new file mode 100644 index 0000000000..f764f5e836 --- /dev/null +++ b/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/InstanceEntitlementGateWiringTest.java @@ -0,0 +1,71 @@ +package stirling.software.proprietary.accountlink; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.util.Optional; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +/** Verifies {@link InstanceEntitlementGate#evaluate} resolves live state from store + cache. */ +class InstanceEntitlementGateWiringTest { + + private AccountLinkProperties properties; + private DeviceCredentialStore store; + private EntitlementCache cache; + private InstanceEntitlementGate gate; + + @BeforeEach + void setUp() { + properties = new AccountLinkProperties(); + properties.setEnabled(true); + store = mock(DeviceCredentialStore.class); + cache = mock(EntitlementCache.class); + gate = new InstanceEntitlementGate(properties, store, cache); + } + + @Test + void manualNeverConsultsStoreOrCache() { + GateDecision d = gate.evaluate(false); + assertTrue(d.allowed()); + assertEquals(GateDecision.Reason.MANUAL_FREE, d.reason()); + verify(store, never()).isLinked(); + verify(cache, never()).current(); + } + + @Test + void billableUnlinkedDoesNotHitCache() { + when(store.isLinked()).thenReturn(false); + GateDecision d = gate.evaluate(true); + assertFalse(d.allowed()); + assertEquals(GateDecision.Reason.NOT_LINKED, d.reason()); + verify(cache, never()).current(); + } + + @Test + void billableLinkedConsultsCache() { + when(store.isLinked()).thenReturn(true); + when(cache.current()) + .thenReturn( + Optional.of( + new InstanceEntitlement(false, 5, 0, null, EntitlementState.OK))); + GateDecision d = gate.evaluate(true); + assertTrue(d.allowed()); + assertEquals(GateDecision.Reason.ENTITLED, d.reason()); + } + + @Test + void flagOffShortCircuits() { + properties.setEnabled(false); + GateDecision d = gate.evaluate(true); + assertTrue(d.allowed()); + assertEquals(GateDecision.Reason.FLAG_OFF, d.reason()); + verify(store, never()).isLinked(); + } +} diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/InstanceEntitlementInterceptorTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/InstanceEntitlementInterceptorTest.java new file mode 100644 index 0000000000..709e3c0866 --- /dev/null +++ b/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/InstanceEntitlementInterceptorTest.java @@ -0,0 +1,61 @@ +package stirling.software.proprietary.accountlink; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.anyBoolean; +import static org.mockito.Mockito.when; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.http.HttpStatus; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.mock.web.MockHttpServletResponse; + +@ExtendWith(MockitoExtension.class) +class InstanceEntitlementInterceptorTest { + + @Mock private InstanceEntitlementGate gate; + + private boolean preHandle(MockHttpServletResponse response) throws Exception { + return new InstanceEntitlementInterceptor(gate) + .preHandle( + new MockHttpServletRequest("GET", "/api/v1/ai/x"), response, new Object()); + } + + @Test + void allowsWhenGateAllows() throws Exception { + when(gate.evaluate(anyBoolean())) + .thenReturn(GateDecision.allow(GateDecision.Reason.ENTITLED)); + MockHttpServletResponse response = new MockHttpServletResponse(); + + assertTrue(preHandle(response)); + assertEquals(200, response.getStatus()); + } + + @Test + void blocksWith402AndLinkSignalWhenGateBlocks() throws Exception { + when(gate.evaluate(anyBoolean())) + .thenReturn(GateDecision.block(GateDecision.Reason.NOT_LINKED)); + MockHttpServletResponse response = new MockHttpServletResponse(); + + assertFalse(preHandle(response)); + assertEquals(HttpStatus.PAYMENT_REQUIRED.value(), response.getStatus()); + assertEquals("application/json", response.getContentType()); + assertTrue(response.getContentAsString().contains("ACCOUNT_LINK_REQUIRED")); + assertTrue(response.getContentAsString().contains("NOT_LINKED")); + } + + @Test + void failsOpenWhenGateThrows() throws Exception { + // A DB / SaaS blip while resolving entitlement must never hard-block billable work. + when(gate.evaluate(anyBoolean())) + .thenThrow(new RuntimeException("entitlement source down")); + MockHttpServletResponse response = new MockHttpServletResponse(); + + assertTrue(preHandle(response)); + assertEquals(200, response.getStatus()); + } +} diff --git a/app/saas/src/main/java/stirling/software/saas/accountlink/AccountLinkController.java b/app/saas/src/main/java/stirling/software/saas/accountlink/AccountLinkController.java new file mode 100644 index 0000000000..91974a6d04 --- /dev/null +++ b/app/saas/src/main/java/stirling/software/saas/accountlink/AccountLinkController.java @@ -0,0 +1,161 @@ +package stirling.software.saas.accountlink; + +import java.util.List; + +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.context.annotation.Profile; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.security.core.Authentication; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import io.swagger.v3.oas.annotations.Hidden; + +import lombok.extern.slf4j.Slf4j; + +import stirling.software.common.model.enumeration.TeamRole; +import stirling.software.proprietary.security.database.repository.UserRepository; +import stirling.software.proprietary.security.model.User; +import stirling.software.saas.model.TeamMembership; +import stirling.software.saas.repository.TeamMembershipRepository; +import stirling.software.saas.util.AuthenticationUtils; + +/** + * Account-link registration surface (combined-billing "Mode A"). + * + *

A self-hosted instance's local backend calls {@code POST /register} with the admin's + * short-lived Supabase JWT (validated by the existing {@code SupabaseSecurityConfig} chain — no new + * auth here). We resolve the caller's team, mint a device credential bound to it, and return the + * secret exactly once. Ongoing entitlement reads authenticate with that device credential, not this + * JWT. + * + *

Whole surface gated behind {@code stirling.billing.account-link.enabled}: off → beans absent → + * 404. Leader-only, and the team is always derived from the caller (never the request body). + */ +@Slf4j +@Hidden +@RestController +@RequestMapping("/api/v1/account-link") +@Profile("saas") +@ConditionalOnProperty(name = "stirling.billing.account-link.enabled", havingValue = "true") +public class AccountLinkController { + + private final AccountLinkService service; + private final TeamMembershipRepository memberRepo; + private final UserRepository userRepository; + + public AccountLinkController( + AccountLinkService service, + TeamMembershipRepository memberRepo, + UserRepository userRepository) { + this.service = service; + this.memberRepo = memberRepo; + this.userRepository = userRepository; + } + + /** Optional display name for the instance (hostname / label). */ + public record RegisterRequest(String name) {} + + /** {@code deviceSecret} is plaintext and returned exactly once — the caller must store it. */ + public record RegisterResponse( + Long instanceId, Long teamId, String deviceId, String deviceSecret, String name) {} + + public record InstanceRow( + Long instanceId, + String deviceId, + String name, + String createdAt, + String lastSeenAt, + boolean revoked) {} + + @PostMapping("/register") + @PreAuthorize("isAuthenticated()") + public ResponseEntity register( + @RequestBody(required = false) RegisterRequest req, Authentication auth) { + LeaderTeam lt = resolveLeaderTeam(auth); + if (lt.error() != null) { + return ResponseEntity.status(lt.error()).build(); + } + String name = req != null ? req.name() : null; + AccountLinkService.RegisteredInstance reg = + service.register(lt.teamId(), lt.userId(), name); + return ResponseEntity.status(HttpStatus.CREATED) + .body( + new RegisterResponse( + reg.instanceId(), + lt.teamId(), + reg.deviceId(), + reg.deviceSecret(), + reg.name())); + } + + @GetMapping("/instances") + @PreAuthorize("isAuthenticated()") + public ResponseEntity> list(Authentication auth) { + LeaderTeam lt = resolveLeaderTeam(auth); + if (lt.error() != null) { + return ResponseEntity.status(lt.error()).build(); + } + List rows = + service.list(lt.teamId()).stream() + .map( + i -> + new InstanceRow( + i.getInstanceId(), + i.getDeviceId(), + i.getName(), + i.getCreatedAt() != null + ? i.getCreatedAt().toString() + : null, + i.getLastSeenAt() != null + ? i.getLastSeenAt().toString() + : null, + i.getRevokedAt() != null)) + .toList(); + return ResponseEntity.ok(rows); + } + + @PostMapping("/instances/{instanceId}/revoke") + @PreAuthorize("isAuthenticated()") + public ResponseEntity revoke(@PathVariable Long instanceId, Authentication auth) { + LeaderTeam lt = resolveLeaderTeam(auth); + if (lt.error() != null) { + return ResponseEntity.status(lt.error()).build(); + } + boolean ok = service.revoke(lt.teamId(), instanceId); + return ok ? ResponseEntity.noContent().build() : ResponseEntity.notFound().build(); + } + + // --------------------------------------------------------------------------------------- + // Helpers — team always derived from the caller; instance linking is a leader (billing) action. + // --------------------------------------------------------------------------------------- + + /** + * Resolved caller team, or an {@code error} status to return (teamId/userId null when error). + */ + private record LeaderTeam(Long teamId, Long userId, HttpStatus error) {} + + private LeaderTeam resolveLeaderTeam(Authentication auth) { + User user; + try { + user = AuthenticationUtils.getCurrentUser(auth, userRepository); + } catch (SecurityException e) { + return new LeaderTeam(null, null, HttpStatus.UNAUTHORIZED); + } + List rows = memberRepo.findPrimaryMembership(user.getId()); + if (rows.isEmpty()) { + return new LeaderTeam(null, null, HttpStatus.FORBIDDEN); + } + TeamMembership m = rows.get(0); + if (m.getRole() != TeamRole.LEADER) { + return new LeaderTeam(null, null, HttpStatus.FORBIDDEN); + } + return new LeaderTeam(m.getTeam().getId(), user.getId(), null); + } +} diff --git a/app/saas/src/main/java/stirling/software/saas/accountlink/AccountLinkService.java b/app/saas/src/main/java/stirling/software/saas/accountlink/AccountLinkService.java new file mode 100644 index 0000000000..c31fc1b03e --- /dev/null +++ b/app/saas/src/main/java/stirling/software/saas/accountlink/AccountLinkService.java @@ -0,0 +1,117 @@ +package stirling.software.saas.accountlink; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.security.SecureRandom; +import java.time.LocalDateTime; +import java.util.Base64; +import java.util.HexFormat; +import java.util.List; +import java.util.Optional; +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.Transactional; + +import lombok.extern.slf4j.Slf4j; + +/** + * Account-link instance registration + lifecycle (combined-billing "Mode A"). + * + *

Mints a {@code device_id} (public) + {@code device_secret} (high-entropy, returned once) bound + * to a team, persisting only the SHA-256 hash of the secret. The instance authenticates its + * unattended entitlement reads with that credential. + * + *

Gated behind {@code stirling.billing.account-link.enabled}: when off the bean is absent, so + * {@link AccountLinkController} (which depends on it) drops out too and its endpoints 404. + */ +@Slf4j +@Service +@Profile("saas") +@ConditionalOnProperty(name = "stirling.billing.account-link.enabled", havingValue = "true") +public class AccountLinkService { + + /** 32 bytes of entropy → URL-safe secret; high enough that an unsalted SHA-256 hash is fine. */ + private static final int SECRET_BYTES = 32; + + private final LinkedInstanceRepository repo; + private final SecureRandom random = new SecureRandom(); + + public AccountLinkService(LinkedInstanceRepository repo) { + this.repo = repo; + } + + /** Result of {@link #register}; {@code deviceSecret} is plaintext and returned exactly once. */ + public record RegisteredInstance( + Long instanceId, String deviceId, String deviceSecret, String name) {} + + /** + * Creates a new linked instance for {@code teamId}, returning the one-time plaintext secret. + */ + @Transactional + public RegisteredInstance register(Long teamId, Long createdByUserId, String name) { + String deviceId = UUID.randomUUID().toString(); + String deviceSecret = randomSecret(); + + LinkedInstance instance = new LinkedInstance(); + instance.setTeamId(teamId); + instance.setCreatedByUserId(createdByUserId); + instance.setDeviceId(deviceId); + instance.setDeviceSecretHash(sha256Hex(deviceSecret)); + instance.setName(name); + repo.save(instance); + + log.info( + "Account-link: registered instance {} (device {}) for team {}", + instance.getInstanceId(), + deviceId, + teamId); + return new RegisteredInstance(instance.getInstanceId(), deviceId, deviceSecret, name); + } + + /** + * All instances for a team, newest first (includes revoked, for the "Linked instances" list). + */ + @Transactional(readOnly = true) + public List list(Long teamId) { + return repo.findByTeamIdOrderByCreatedAtDesc(teamId); + } + + /** + * Revokes an instance iff it belongs to {@code teamId}. Returns false if not found or owned by + * a different team (so a caller can never revoke another team's instance). Idempotent. + */ + @Transactional + public boolean revoke(Long teamId, Long instanceId) { + Optional found = repo.findById(instanceId); + if (found.isEmpty() || !found.get().getTeamId().equals(teamId)) { + return false; + } + LinkedInstance instance = found.get(); + if (instance.getRevokedAt() == null) { + instance.setRevokedAt(LocalDateTime.now()); + repo.save(instance); + log.info("Account-link: revoked instance {} for team {}", instanceId, teamId); + } + return true; + } + + private String randomSecret() { + byte[] buf = new byte[SECRET_BYTES]; + random.nextBytes(buf); + return Base64.getUrlEncoder().withoutPadding().encodeToString(buf); + } + + /** SHA-256 hex of a value. The device secret is high-entropy, so no salt is required. */ + static String sha256Hex(String value) { + try { + MessageDigest md = MessageDigest.getInstance("SHA-256"); + return HexFormat.of().formatHex(md.digest(value.getBytes(StandardCharsets.UTF_8))); + } catch (NoSuchAlgorithmException e) { + throw new IllegalStateException("SHA-256 unavailable", e); + } + } +} diff --git a/app/saas/src/main/java/stirling/software/saas/accountlink/DeviceCredentialAuthenticationFilter.java b/app/saas/src/main/java/stirling/software/saas/accountlink/DeviceCredentialAuthenticationFilter.java new file mode 100644 index 0000000000..a2fd13a095 --- /dev/null +++ b/app/saas/src/main/java/stirling/software/saas/accountlink/DeviceCredentialAuthenticationFilter.java @@ -0,0 +1,108 @@ +package stirling.software.saas.accountlink; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.time.LocalDateTime; + +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.context.annotation.Profile; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.stereotype.Component; +import org.springframework.web.filter.OncePerRequestFilter; + +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; + +import lombok.extern.slf4j.Slf4j; + +/** + * Authenticates a linked self-hosted instance by its device credential (combined-billing "Mode A"). + * + *

Reads {@code X-Device-Id} + {@code X-Device-Secret}, looks up the active {@link + * LinkedInstance}, and constant-time compares the SHA-256 of the presented secret against the + * stored hash. On a match it sets a {@link LinkedInstanceAuthenticationToken} (team-scoped, {@code + * ROLE_LINKED_INSTANCE}); otherwise it does nothing and lets the chain continue (→ 401 on a + * protected endpoint). + * + *

Read-only and path-scoped to {@code /api/v1/instance/**}: the device principal is never + * established for user-facing endpoints, so a leaked secret can only reach the instance surface. + * Gated behind {@code stirling.billing.account-link.enabled}; absent when the flag is off, so + * {@code SupabaseSecurityConfig} never wires it in. + */ +@Slf4j +@Component +@Profile("saas") +@ConditionalOnProperty(name = "stirling.billing.account-link.enabled", havingValue = "true") +public class DeviceCredentialAuthenticationFilter extends OncePerRequestFilter { + + static final String HEADER_DEVICE_ID = "X-Device-Id"; + static final String HEADER_DEVICE_SECRET = "X-Device-Secret"; + static final String INSTANCE_PATH_PREFIX = "/api/v1/instance/"; + + private final LinkedInstanceRepository repo; + + public DeviceCredentialAuthenticationFilter(LinkedInstanceRepository repo) { + this.repo = repo; + } + + /** Only the instance surface uses the device credential; everything else skips this filter. */ + @Override + protected boolean shouldNotFilter(HttpServletRequest request) { + return !request.getRequestURI().startsWith(INSTANCE_PATH_PREFIX); + } + + @Override + protected void doFilterInternal( + HttpServletRequest request, HttpServletResponse response, FilterChain chain) + throws ServletException, IOException { + String deviceId = request.getHeader(HEADER_DEVICE_ID); + String secret = request.getHeader(HEADER_DEVICE_SECRET); + + if (deviceId != null + && secret != null + && SecurityContextHolder.getContext().getAuthentication() == null) { + repo.findByDeviceIdAndRevokedAtIsNull(deviceId) + .ifPresent( + instance -> { + if (constantTimeEquals( + AccountLinkService.sha256Hex(secret), + instance.getDeviceSecretHash())) { + SecurityContextHolder.getContext() + .setAuthentication( + new LinkedInstanceAuthenticationToken( + instance.getInstanceId(), + instance.getTeamId())); + // Stamp liveness, best-effort. Auth is already set above; a + // transient write failure must NOT 500 an otherwise-valid + // request, so swallow it. Targeted single-column UPDATE (not a + // full save) so a concurrent revoke between the read above and + // this write can't be clobbered back to active. + try { + repo.touchLastSeen( + instance.getInstanceId(), LocalDateTime.now()); + } catch (RuntimeException e) { + log.debug( + "last_seen_at update failed for device {}: {}", + deviceId, + e.getMessage()); + } + } else { + log.debug("Device credential mismatch for device {}", deviceId); + } + }); + } + + chain.doFilter(request, response); + } + + private static boolean constantTimeEquals(String a, String b) { + if (a == null || b == null) { + return false; + } + return MessageDigest.isEqual( + a.getBytes(StandardCharsets.UTF_8), b.getBytes(StandardCharsets.UTF_8)); + } +} diff --git a/app/saas/src/main/java/stirling/software/saas/accountlink/InstanceController.java b/app/saas/src/main/java/stirling/software/saas/accountlink/InstanceController.java new file mode 100644 index 0000000000..7392eb928a --- /dev/null +++ b/app/saas/src/main/java/stirling/software/saas/accountlink/InstanceController.java @@ -0,0 +1,131 @@ +package stirling.software.saas.accountlink; + +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.context.annotation.Profile; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.security.core.Authentication; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import io.swagger.v3.oas.annotations.Hidden; + +import lombok.extern.slf4j.Slf4j; + +import stirling.software.saas.payg.billing.TeamBillingContext; +import stirling.software.saas.payg.billing.TeamBillingService; +import stirling.software.saas.payg.entitlement.EntitlementService; +import stirling.software.saas.payg.entitlement.EntitlementSnapshot; +import stirling.software.saas.payg.model.EntitlementState; + +/** + * Instance-facing surface (combined-billing "Mode A"), authenticated by the device + * credential — not a user JWT. Separate path prefix ({@code /api/v1/instance/**}) so the device + * credential is scoped here and nowhere else. + * + *

{@code GET /whoami} is the MVP round-trip proof: a registered instance presenting a valid + * device credential gets back its resolved {@code instanceId} + {@code teamId}. {@code GET + * /entitlement} is the read the local gate consumes — the same team-scoped snapshot the FE wallet + * sees, trimmed to the fields the gate needs (subscription, free pool, period spend/cap, state), + * and built on the same device-credential auth. + * + *

Gated behind {@code stirling.billing.account-link.enabled}: off → beans absent → 404. + */ +@Slf4j +@Hidden +@RestController +@RequestMapping("/api/v1/instance") +@Profile("saas") +@ConditionalOnProperty(name = "stirling.billing.account-link.enabled", havingValue = "true") +public class InstanceController { + + private final EntitlementService entitlementService; + private final TeamBillingService billingService; + private final AccountLinkService accountLinkService; + + public InstanceController( + EntitlementService entitlementService, + TeamBillingService billingService, + AccountLinkService accountLinkService) { + this.entitlementService = entitlementService; + this.billingService = billingService; + this.accountLinkService = accountLinkService; + } + + public record WhoAmIResponse(Long instanceId, Long teamId) {} + + /** + * Minimal entitlement view the local gate enforces against. {@code periodCapUnits} null = + * uncapped. {@code state} is the coarse OK / OVER_LIMIT vocabulary the instance gate parses + * (see {@link #coarseState}), not the SaaS feature-state enum. + */ + public record EntitlementResponse( + boolean subscribed, + long freeRemainingUnits, + long periodSpendUnits, + Long periodCapUnits, + String state) {} + + @GetMapping("/whoami") + @PreAuthorize("hasRole('LINKED_INSTANCE')") + public ResponseEntity whoami(Authentication auth) { + if (!(auth instanceof LinkedInstanceAuthenticationToken token)) { + // Belt-and-braces: hasRole already guarantees this, but never leak a non-instance + // principal. + return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build(); + } + return ResponseEntity.ok(new WhoAmIResponse(token.getInstanceId(), token.getTeamId())); + } + + /** + * Revokes this instance's own credential — a credential can mark itself revoked the same way a + * session logs itself out. Called by the proprietary backend on local unlink so the SaaS row + * gets {@code revoked_at} set; idempotent (already-revoked → still 204). + */ + @PostMapping("/revoke-self") + @PreAuthorize("hasRole('LINKED_INSTANCE')") + public ResponseEntity revokeSelf(Authentication auth) { + if (!(auth instanceof LinkedInstanceAuthenticationToken token)) { + return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build(); + } + accountLinkService.revoke(token.getTeamId(), token.getInstanceId()); + return ResponseEntity.noContent().build(); + } + + @GetMapping("/entitlement") + @PreAuthorize("hasRole('LINKED_INSTANCE')") + @Transactional(readOnly = true) + public ResponseEntity entitlement(Authentication auth) { + if (!(auth instanceof LinkedInstanceAuthenticationToken token)) { + return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build(); + } + Long teamId = token.getTeamId(); + + // Same composition the FE wallet uses: billing facts (subscription, free pool) from + // TeamBillingService, period spend/cap + state from the entitlement snapshot. + TeamBillingContext billing = billingService.forTeam(teamId); + EntitlementSnapshot snap = entitlementService.getSnapshot(teamId); + + return ResponseEntity.ok( + new EntitlementResponse( + billing.subscribed(), + billing.freeRemainingUnits(), + snap.periodSpendUnits(), + snap.periodCapUnits(), + coarseState(snap.state()))); + } + + /** + * Collapses the SaaS feature-state machine into the OK / OVER_LIMIT vocabulary the instance + * gate parses. DEGRADED means automation + AI are gated off — which, for a gate that governs + * only billable work (manual tools are free-pathed before it), is exactly OVER_LIMIT; FULL and + * WARNED are OK. + */ + private static String coarseState(EntitlementState state) { + return state == EntitlementState.DEGRADED ? "OVER_LIMIT" : "OK"; + } +} diff --git a/app/saas/src/main/java/stirling/software/saas/accountlink/LinkedInstance.java b/app/saas/src/main/java/stirling/software/saas/accountlink/LinkedInstance.java new file mode 100644 index 0000000000..ec92c97758 --- /dev/null +++ b/app/saas/src/main/java/stirling/software/saas/accountlink/LinkedInstance.java @@ -0,0 +1,77 @@ +package stirling.software.saas.accountlink; + +import java.time.LocalDateTime; + +import org.hibernate.annotations.CreationTimestamp; + +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.Table; + +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; + +/** + * One self-hosted instance that has linked a SaaS account (combined-billing "Mode A", {@code + * linked_instance}, V22). + * + *

Created by {@code POST /api/v1/account-link/register}, authenticated with the admin's + * short-lived Supabase JWT. Registration mints a {@code device_id} (public) plus a {@code + * device_secret} (high-entropy, returned once and stored only on the instance — we keep an unsalted + * SHA-256 hash, the same posture as API keys). The instance authenticates its unattended + * entitlement reads with that device credential, so no long-lived user JWT lives on the server + * side. + * + *

{@code revoked_at IS NULL} means active; revoking sets it and the credential stops + * authenticating. The whole surface is gated behind {@code stirling.billing.account-link.enabled}. + */ +@Entity +@Table(name = "linked_instance") +@Getter +@Setter +@NoArgsConstructor +public class LinkedInstance { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "instance_id") + private Long instanceId; + + @Column(name = "team_id", nullable = false) + private Long teamId; + + /** + * Admin who registered the instance; informational (no FK, so a user delete never offlines it). + */ + @Column(name = "created_by_user_id") + private Long createdByUserId; + + /** Public, non-secret identifier the instance presents on every request. */ + @Column(name = "device_id", nullable = false, unique = true, length = 64) + private String deviceId; + + /** SHA-256 hex of the device secret; the secret itself is never stored. */ + @Column(name = "device_secret_hash", nullable = false, length = 64) + private String deviceSecretHash; + + /** Operator-set display label (hostname etc.) for the "Linked instances" list. */ + @Column(name = "name", length = 255) + private String name; + + /** Insert time; Hibernate populates this on persist (DB DEFAULT is belt-and-braces). */ + @CreationTimestamp + @Column(name = "created_at", nullable = false, updatable = false) + private LocalDateTime createdAt; + + /** Stamped when the device credential last authenticated; powers staleness display. */ + @Column(name = "last_seen_at") + private LocalDateTime lastSeenAt; + + /** NULL = active. Set on unlink/revoke; a revoked credential fails authentication. */ + @Column(name = "revoked_at") + private LocalDateTime revokedAt; +} diff --git a/app/saas/src/main/java/stirling/software/saas/accountlink/LinkedInstanceAuthenticationToken.java b/app/saas/src/main/java/stirling/software/saas/accountlink/LinkedInstanceAuthenticationToken.java new file mode 100644 index 0000000000..af883bd66a --- /dev/null +++ b/app/saas/src/main/java/stirling/software/saas/accountlink/LinkedInstanceAuthenticationToken.java @@ -0,0 +1,45 @@ +package stirling.software.saas.accountlink; + +import java.util.List; + +import org.springframework.security.authentication.AbstractAuthenticationToken; +import org.springframework.security.core.authority.SimpleGrantedAuthority; + +/** + * Authentication for a linked self-hosted instance (combined-billing "Mode A"). + * + *

Deliberately not a user: the principal is the instance ({@code instanceId}) bound to + * a {@code teamId}, with the single authority {@code ROLE_LINKED_INSTANCE}. It carries no {@code + * User} and creates no user row — a device credential can never act as a person, only as its team's + * instance, and only on the instance-facing endpoints. + */ +public class LinkedInstanceAuthenticationToken extends AbstractAuthenticationToken { + + private final Long instanceId; + private final Long teamId; + + public LinkedInstanceAuthenticationToken(Long instanceId, Long teamId) { + super(List.of(new SimpleGrantedAuthority("ROLE_LINKED_INSTANCE"))); + this.instanceId = instanceId; + this.teamId = teamId; + setAuthenticated(true); + } + + @Override + public Object getCredentials() { + return null; // the secret is never retained on the authentication + } + + @Override + public Object getPrincipal() { + return instanceId; + } + + public Long getInstanceId() { + return instanceId; + } + + public Long getTeamId() { + return teamId; + } +} diff --git a/app/saas/src/main/java/stirling/software/saas/accountlink/LinkedInstanceRepository.java b/app/saas/src/main/java/stirling/software/saas/accountlink/LinkedInstanceRepository.java new file mode 100644 index 0000000000..dae6a2a69e --- /dev/null +++ b/app/saas/src/main/java/stirling/software/saas/accountlink/LinkedInstanceRepository.java @@ -0,0 +1,43 @@ +package stirling.software.saas.accountlink; + +import java.time.LocalDateTime; +import java.util.List; +import java.util.Optional; + +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Modifying; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; +import org.springframework.transaction.annotation.Transactional; + +/** + * Data access for {@link LinkedInstance}. Plain Spring Data JPA against {@code stirling_pdf} — + * native schema access, no RPC, consistent with the rest of the SaaS backend. + */ +public interface LinkedInstanceRepository extends JpaRepository { + + /** + * Active-credential lookup for the device-credential auth filter (revoked rows never match). + */ + Optional findByDeviceIdAndRevokedAtIsNull(String deviceId); + + /** Backs the portal "Linked instances" list (includes revoked, newest first). */ + List findByTeamIdOrderByCreatedAtDesc(Long teamId); + + /** Active (non-revoked) linked instances on a team — the orphan guard's count. */ + long countByTeamIdAndRevokedAtIsNull(Long teamId); + + /** + * Stamps liveness on a single instance. A targeted single-column UPDATE rather than a + * full-entity {@code save}: the auth filter loads the instance outside a transaction, so a full + * save would write back the stale (in-memory {@code null}) {@code revoked_at} and could + * silently un-revoke a credential that was revoked between the read and the write. The {@code + * revoked_at IS NULL} guard makes this a no-op once revoked. + */ + @Modifying + @Transactional + @Query( + "UPDATE LinkedInstance li SET li.lastSeenAt = :now " + + "WHERE li.instanceId = :instanceId AND li.revokedAt IS NULL") + int touchLastSeen(@Param("instanceId") Long instanceId, @Param("now") LocalDateTime now); +} diff --git a/app/saas/src/main/java/stirling/software/saas/config/SaasJpaConfig.java b/app/saas/src/main/java/stirling/software/saas/config/SaasJpaConfig.java index 3c6b0d14df..5e90df6bf5 100644 --- a/app/saas/src/main/java/stirling/software/saas/config/SaasJpaConfig.java +++ b/app/saas/src/main/java/stirling/software/saas/config/SaasJpaConfig.java @@ -14,12 +14,14 @@ import org.springframework.data.jpa.repository.config.EnableJpaRepositories; @Profile("saas") @EnableJpaRepositories( basePackages = { + "stirling.software.saas.accountlink", "stirling.software.saas.repository", "stirling.software.saas.billing.repository", "stirling.software.saas.ai.repository", "stirling.software.saas.payg.repository" }) @EntityScan({ + "stirling.software.saas.accountlink", "stirling.software.saas.model", "stirling.software.saas.billing.model", "stirling.software.saas.ai.model", diff --git a/app/saas/src/main/java/stirling/software/saas/payg/api/PaygInvoicesController.java b/app/saas/src/main/java/stirling/software/saas/payg/api/PaygInvoicesController.java new file mode 100644 index 0000000000..6b8bb2c883 --- /dev/null +++ b/app/saas/src/main/java/stirling/software/saas/payg/api/PaygInvoicesController.java @@ -0,0 +1,150 @@ +package stirling.software.saas.payg.api; + +import java.time.LocalDateTime; +import java.util.List; +import java.util.Objects; +import java.util.Optional; + +import org.springframework.context.annotation.Profile; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.security.core.Authentication; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +import io.swagger.v3.oas.annotations.Hidden; + +import lombok.extern.slf4j.Slf4j; + +import stirling.software.proprietary.security.database.repository.UserRepository; +import stirling.software.proprietary.security.model.User; +import stirling.software.saas.model.TeamMembership; +import stirling.software.saas.payg.policy.PaygTeamExtensions; +import stirling.software.saas.payg.repository.PaygTeamExtensionsRepository; +import stirling.software.saas.payg.stripe.StripeInvoiceDao; +import stirling.software.saas.repository.TeamMembershipRepository; +import stirling.software.saas.util.AuthenticationUtils; + +/** + * Read-only Stripe-invoices surface for the linked org's billing page. + * + *

{@code GET /api/v1/payg/invoices?limit=N} returns the team's most recent Stripe invoices, + * sourced from the {@code stripe.invoices} table the Sync Engine maintains. The caller's team is + * resolved from the authenticated principal (same pattern as {@link PaygWalletController}); we + * never trust a team id from the request. + * + *

Defensive: when the team has no {@code stripe_customer_id} (not subscribed, or pre-checkout) + * or the {@code stripe} schema isn't synced (H2 tests, sync engine off), we return {@code 200} with + * an empty list rather than 500 — the UI renders "no invoices yet". This keeps the page working + * through every link/subscription state. + * + *

{@code hostedInvoiceUrl} + {@code invoicePdf} are Stripe-hosted links the portal can deep-link + * from. We don't proxy the PDF ourselves; Stripe handles auth + caching. + */ +@Slf4j +@Hidden +@RestController +@RequestMapping("/api/v1/payg") +@Profile("saas") +public class PaygInvoicesController { + + private static final int DEFAULT_LIMIT = 20; + private static final int MAX_LIMIT = 100; + + private final StripeInvoiceDao invoiceDao; + private final PaygTeamExtensionsRepository extRepo; + private final TeamMembershipRepository memberRepo; + private final UserRepository userRepository; + + public PaygInvoicesController( + StripeInvoiceDao invoiceDao, + PaygTeamExtensionsRepository extRepo, + TeamMembershipRepository memberRepo, + UserRepository userRepository) { + this.invoiceDao = Objects.requireNonNull(invoiceDao, "invoiceDao"); + this.extRepo = Objects.requireNonNull(extRepo, "extRepo"); + this.memberRepo = Objects.requireNonNull(memberRepo, "memberRepo"); + this.userRepository = Objects.requireNonNull(userRepository, "userRepository"); + } + + /** The shape the portal renders. Trimmed; never echoes raw Stripe object fields verbatim. */ + public record InvoiceResponse( + String id, + String number, + String status, + Long totalMinor, + String currency, + String createdAt, + String periodStart, + String periodEnd, + String hostedInvoiceUrl, + String invoicePdf, + String description, + Long pdfsProcessed) {} + + @GetMapping("/invoices") + @PreAuthorize("isAuthenticated()") + @Transactional(readOnly = true) + public ResponseEntity> list( + @RequestParam(name = "limit", required = false) Integer limit, Authentication auth) { + + User user; + try { + user = AuthenticationUtils.getCurrentUser(auth, userRepository); + } catch (SecurityException e) { + return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build(); + } + + // Resolve the caller's team from their primary membership — same pattern as + // PaygWalletController. The team id NEVER comes from the request. + List rows = memberRepo.findPrimaryMembership(user.getId()); + if (rows.isEmpty()) { + return ResponseEntity.ok(List.of()); + } + Long teamId = rows.get(0).getTeam().getId(); + + // No PAYG extension row OR no Stripe customer id → team has never subscribed → no + // invoices. Empty list, not 404 — the UI distinguishes "no invoices yet" from a + // genuine error and we don't want to error a happy free team. + Optional ext = extRepo.findById(teamId); + if (ext.isEmpty() || ext.get().getStripeCustomerId() == null) { + return ResponseEntity.ok(List.of()); + } + + int safeLimit = clampLimit(limit); + List body = + invoiceDao.findRecentByCustomer(ext.get().getStripeCustomerId(), safeLimit).stream() + .map(PaygInvoicesController::toResponse) + .toList(); + return ResponseEntity.ok(body); + } + + private static int clampLimit(Integer requested) { + if (requested == null) return DEFAULT_LIMIT; + return Math.max(1, Math.min(requested, MAX_LIMIT)); + } + + private static InvoiceResponse toResponse(StripeInvoiceDao.InvoiceRow r) { + return new InvoiceResponse( + r.id(), + r.number(), + r.status(), + r.totalMinor(), + r.currency(), + iso(r.createdAt()), + iso(r.periodStart()), + iso(r.periodEnd()), + r.hostedInvoiceUrl(), + r.invoicePdf(), + r.description(), + r.pdfsProcessed()); + } + + private static String iso(LocalDateTime ldt) { + return ldt == null ? null : ldt.toString(); + } +} diff --git a/app/saas/src/main/java/stirling/software/saas/payg/api/PaygPaymentMethodController.java b/app/saas/src/main/java/stirling/software/saas/payg/api/PaygPaymentMethodController.java new file mode 100644 index 0000000000..724d6715d3 --- /dev/null +++ b/app/saas/src/main/java/stirling/software/saas/payg/api/PaygPaymentMethodController.java @@ -0,0 +1,108 @@ +package stirling.software.saas.payg.api; + +import java.util.List; +import java.util.Objects; +import java.util.Optional; + +import org.springframework.context.annotation.Profile; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.security.core.Authentication; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import io.swagger.v3.oas.annotations.Hidden; + +import lombok.extern.slf4j.Slf4j; + +import stirling.software.proprietary.security.database.repository.UserRepository; +import stirling.software.proprietary.security.model.User; +import stirling.software.saas.model.TeamMembership; +import stirling.software.saas.payg.policy.PaygTeamExtensions; +import stirling.software.saas.payg.repository.PaygTeamExtensionsRepository; +import stirling.software.saas.payg.stripe.StripePaymentMethodDao; +import stirling.software.saas.repository.TeamMembershipRepository; +import stirling.software.saas.util.AuthenticationUtils; + +/** + * Read-only default-payment-method surface for the subscribed billing page. + * + *

{@code GET /api/v1/payg/payment-method} returns the team's default card (brand / last4 / + * expiry), sourced from {@code stripe.payment_methods} (Sync Engine mirror). The caller's team is + * resolved from the authenticated principal — never trusted from the request — exactly as {@link + * PaygInvoicesController} does. + * + *

Defensive: no team, no {@code stripe_customer_id} (free / pre-checkout), or the card simply + * not in the mirror all degrade to {@code 200 present=false} rather than an error. Card edits never + * happen here; the portal deep-links to Stripe's hosted customer portal for that. + */ +@Slf4j +@Hidden +@RestController +@RequestMapping("/api/v1/payg") +@Profile("saas") +public class PaygPaymentMethodController { + + /** Trimmed default-card shape. {@code present=false} carries no card fields. */ + public record PaymentMethodResponse( + boolean present, String brand, String last4, Integer expMonth, Integer expYear) { + static PaymentMethodResponse absent() { + return new PaymentMethodResponse(false, null, null, null, null); + } + } + + private final StripePaymentMethodDao paymentMethodDao; + private final PaygTeamExtensionsRepository extRepo; + private final TeamMembershipRepository memberRepo; + private final UserRepository userRepository; + + public PaygPaymentMethodController( + StripePaymentMethodDao paymentMethodDao, + PaygTeamExtensionsRepository extRepo, + TeamMembershipRepository memberRepo, + UserRepository userRepository) { + this.paymentMethodDao = Objects.requireNonNull(paymentMethodDao, "paymentMethodDao"); + this.extRepo = Objects.requireNonNull(extRepo, "extRepo"); + this.memberRepo = Objects.requireNonNull(memberRepo, "memberRepo"); + this.userRepository = Objects.requireNonNull(userRepository, "userRepository"); + } + + @GetMapping("/payment-method") + @PreAuthorize("isAuthenticated()") + @Transactional(readOnly = true) + public ResponseEntity get(Authentication auth) { + User user; + try { + user = AuthenticationUtils.getCurrentUser(auth, userRepository); + } catch (SecurityException e) { + return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build(); + } + + List rows = memberRepo.findPrimaryMembership(user.getId()); + if (rows.isEmpty()) { + return ResponseEntity.ok(PaymentMethodResponse.absent()); + } + Long teamId = rows.get(0).getTeam().getId(); + + Optional ext = extRepo.findById(teamId); + if (ext.isEmpty() || ext.get().getStripeCustomerId() == null) { + return ResponseEntity.ok(PaymentMethodResponse.absent()); + } + + return ResponseEntity.ok( + paymentMethodDao + .findDefaultCard(ext.get().getStripeCustomerId()) + .map( + c -> + new PaymentMethodResponse( + true, + c.brand(), + c.last4(), + c.expMonth(), + c.expYear())) + .orElseGet(PaymentMethodResponse::absent)); + } +} diff --git a/app/saas/src/main/java/stirling/software/saas/payg/cap/CapEvaluator.java b/app/saas/src/main/java/stirling/software/saas/payg/cap/CapEvaluator.java index d47b6e7365..29148a5ddb 100644 --- a/app/saas/src/main/java/stirling/software/saas/payg/cap/CapEvaluator.java +++ b/app/saas/src/main/java/stirling/software/saas/payg/cap/CapEvaluator.java @@ -15,7 +15,9 @@ import stirling.software.saas.payg.model.FeatureSet; *

State transitions: * *