Skip to content

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

Run a linked server's AI on Stirling Cloud (#8101)

Anthony Stirling65a7e223b8a3
diff --git a/.github/workflows/Saas-Dev-Deploy.yml b/.github/workflows/Saas-Dev-Deploy.yml
index 9134a5f1e9..a4221f7636 100644
--- a/.github/workflows/Saas-Dev-Deploy.yml
+++ b/.github/workflows/Saas-Dev-Deploy.yml
@@ -150,9 +150,10 @@ jobs:
ENGINE_SECRET="$(openssl rand -hex 32)"
AI_BACKEND_VARS="
- SYSTEM_AIENGINE_ENABLED: \"true\"
- SYSTEM_AIENGINE_URL: \"http://saas-engine:5001\"
+ AIENGINE_ENABLED: \"true\"
+ AIENGINE_URL: \"http://saas-engine:5001\"
APP_AI_SERVICEBASEURL: \"http://saas-engine:5001\"
+ STIRLING_CLOUD_AI_SHARING_ENABLED: \"true\"
STIRLING_ENGINE_SHARED_SECRET: $(yaml "$ENGINE_SECRET")"
AI_SERVICE="
diff --git a/app/common/src/main/java/stirling/software/common/model/ApplicationProperties.java b/app/common/src/main/java/stirling/software/common/model/ApplicationProperties.java
index c6a5842af7..73d67a3f63 100644
--- a/app/common/src/main/java/stirling/software/common/model/ApplicationProperties.java
+++ b/app/common/src/main/java/stirling/software/common/model/ApplicationProperties.java
@@ -373,6 +373,10 @@ public class ApplicationProperties {
@Data
public static class AiEngine {
private boolean enabled = false;
+
+ /** {@code SELF_HOSTED} calls {@link #url}; {@code CLOUD} runs AI on Stirling Cloud. */
+ private AiEngineMode mode = AiEngineMode.SELF_HOSTED;
+
private String url = "http://localhost:5001";
private int timeoutSeconds = 120;
@@ -404,6 +408,23 @@ public class ApplicationProperties {
/** Per-capability on/off switches so an admin can disable individual AI tools. */
private Features features = new Features();
+ /**
+ * Cloud mode only: whether Stirling Cloud may keep document text for later questions. AI
+ * tools send page text either way, so this controls retention, not what leaves the server.
+ */
+ private boolean cloudDocumentIndexing = false;
+
+ /**
+ * Stirling Cloud's API host; blank uses the account-link host, the only one the device
+ * credential is valid for. Not in settings.yml: set it via env or custom_settings.yml.
+ */
+ private String cloudBaseUrl = "";
+
+ public enum AiEngineMode {
+ SELF_HOSTED,
+ CLOUD
+ }
+
@Data
public static class Models {
/** Provider driving the model strings: 'anthropic', 'openai', 'ollama', or 'custom'. */
diff --git a/app/core/src/main/resources/settings.yml.template b/app/core/src/main/resources/settings.yml.template
index 2b7b3ab8c7..dc4588a529 100644
--- a/app/core/src/main/resources/settings.yml.template
+++ b/app/core/src/main/resources/settings.yml.template
@@ -382,11 +382,13 @@ processExecutor:
aiEngine:
enabled: false # Set to 'true' to enable the AI engine integration
- url: http://localhost:5001 # URL of the Python AI engine
+ mode: SELF_HOSTED # 'SELF_HOSTED' uses the url below; 'CLOUD' runs AI on Stirling Cloud via the account link
+ url: http://localhost:5001 # URL of the Python AI engine (SELF_HOSTED only)
timeoutSeconds: 120 # Timeout in seconds for AI engine requests
longRunningTimeoutSeconds: 600 # Timeout (seconds) for heavy operations like RAG ingestion of large documents
streamTimeoutSeconds: 1800 # SSE stream timeout (seconds) for long-running orchestrator runs
pushConfigToEngine: true # Push admin AI config to the engine on startup + save; false = engine stays fully env-controlled
+ cloudDocumentIndexing: false # CLOUD only: let Stirling Cloud keep document text so document questions work
models:
provider: anthropic # Model provider: 'anthropic', 'openai', 'ollama', or 'custom' (OpenAI-compatible)
smartModel: claude-haiku-4-5 # High-quality tier model name (no provider prefix)
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/InstanceEntitlementInterceptor.java b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/InstanceEntitlementInterceptor.java
index 4cc502b2c8..c296475363 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/InstanceEntitlementInterceptor.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/InstanceEntitlementInterceptor.java
@@ -31,6 +31,7 @@ import stirling.software.common.service.InternalApiClient;
import stirling.software.common.util.TempFile;
import stirling.software.common.util.TempFileManager;
import stirling.software.jpdfium.PdfDocument;
+import stirling.software.proprietary.billing.AiCallRecord;
import stirling.software.proprietary.billing.BillingCategory;
import stirling.software.proprietary.billing.DocumentUnitCalculator;
import stirling.software.proprietary.billing.DocumentUnitCalculator.FileSize;
@@ -186,6 +187,12 @@ public class InstanceEntitlementInterceptor implements HandlerInterceptor {
|| category == BillingCategory.BYPASSED) {
return;
}
+ // Bill AI only when this server's own engine ran: Stirling Cloud bills its own work, and a
+ // route that never reached an engine did none.
+ if (category == BillingCategory.AI
+ && !AiCallRecord.ranLocally(request.getAttribute(AiCallRecord.attributeName()))) {
+ return;
+ }
try {
Object reason = request.getAttribute(ATTR_REASON);
if (reason == GateDecision.Reason.SERVER_LICENSE) {
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/billing/AiCallRecord.java b/app/proprietary/src/main/java/stirling/software/proprietary/billing/AiCallRecord.java
new file mode 100644
index 0000000000..880c6e155e
--- /dev/null
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/billing/AiCallRecord.java
@@ -0,0 +1,39 @@
+package stirling.software.proprietary.billing;
+
+import org.springframework.web.context.request.RequestAttributes;
+import org.springframework.web.context.request.RequestContextHolder;
+
+/**
+ * Where a request's AI work actually ran, set by the engine client and read by the meter. Records
+ * the call made rather than the configured mode, which an admin can change mid-request.
+ */
+public final class AiCallRecord {
+
+ private static final String ATTR = AiCallRecord.class.getName() + ".where";
+
+ private AiCallRecord() {}
+
+ /** Where the engine call went; absent when no call was made. */
+ public enum Where {
+ /** This server's own engine, so only the local meter bills it. */
+ LOCAL,
+ /** Stirling Cloud, which bills it on success. */
+ REMOTE
+ }
+
+ /** No-op off the request thread, so engine calls made on an executor go unrecorded. */
+ public static void record(Where where) {
+ RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
+ if (attributes != null) {
+ attributes.setAttribute(ATTR, where, RequestAttributes.SCOPE_REQUEST);
+ }
+ }
+
+ public static boolean ranLocally(Object attributeValue) {
+ return attributeValue == Where.LOCAL;
+ }
+
+ public static String attributeName() {
+ return ATTR;
+ }
+}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/controller/api/AiEngineController.java b/app/proprietary/src/main/java/stirling/software/proprietary/controller/api/AiEngineController.java
index f50d53e542..ff2bcd2b74 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/controller/api/AiEngineController.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/controller/api/AiEngineController.java
@@ -1,6 +1,7 @@
package stirling.software.proprietary.controller.api;
import java.io.IOException;
+import java.time.Duration;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executor;
@@ -32,14 +33,17 @@ import stirling.software.common.model.job.ResultFile;
import stirling.software.common.service.JobOwnershipService;
import stirling.software.common.service.TaskManager;
import stirling.software.common.service.UserServiceInterface;
+import stirling.software.proprietary.model.api.ai.AiEngineStatus;
import stirling.software.proprietary.model.api.ai.AiWorkflowProgressEvent;
import stirling.software.proprietary.model.api.ai.AiWorkflowRequest;
import stirling.software.proprietary.model.api.ai.AiWorkflowResponse;
import stirling.software.proprietary.model.api.ai.AiWorkflowResultFile;
import stirling.software.proprietary.service.AiEngineClient;
import stirling.software.proprietary.service.AiEngineEndpointResolver;
+import stirling.software.proprietary.service.AiEngineRouter;
import stirling.software.proprietary.service.AiFeatureGate;
import stirling.software.proprietary.service.AiWorkflowService;
+import stirling.software.proprietary.service.CloudStatusProbe;
import tools.jackson.core.JacksonException;
import tools.jackson.databind.JsonNode;
@@ -63,6 +67,9 @@ public class AiEngineController {
private final AiEngineEndpointResolver endpointResolver;
private final AiFeatureGate aiFeatureGate;
private final UserServiceInterface userService;
+ private final ApplicationProperties applicationProperties;
+ private final AiEngineRouter aiEngineRouter;
+ private final CloudStatusProbe cloudStatusProbe;
/**
* SSE emitter timeout (ms), long enough for multi-gigabyte PDF workflows without completing out
@@ -80,6 +87,8 @@ public class AiEngineController {
AiEngineEndpointResolver endpointResolver,
AiFeatureGate aiFeatureGate,
ApplicationProperties applicationProperties,
+ AiEngineRouter aiEngineRouter,
+ CloudStatusProbe cloudStatusProbe,
@Autowired(required = false) UserServiceInterface userService) {
this.aiEngineClient = aiEngineClient;
this.aiWorkflowService = aiWorkflowService;
@@ -90,6 +99,9 @@ public class AiEngineController {
this.endpointResolver = endpointResolver;
this.aiFeatureGate = aiFeatureGate;
this.userService = userService;
+ this.applicationProperties = applicationProperties;
+ this.aiEngineRouter = aiEngineRouter;
+ this.cloudStatusProbe = cloudStatusProbe;
this.streamTimeoutMs =
applicationProperties.getAiEngine().getStreamTimeoutSeconds() * 1000L;
}
@@ -107,6 +119,124 @@ public class AiEngineController {
return ResponseEntity.ok().contentType(MediaType.APPLICATION_JSON).body(response);
}
+ /**
+ * Also probes a secret-gated route: the engine's {@code /health} skips the shared-secret check,
+ * so it stays green while real calls get 401.
+ */
+ @GetMapping("/status")
+ @Operation(
+ summary = "AI engine status",
+ description =
+ "Reachability, round-trip time, the models in use, and whether the engine"
+ + " accepted this server's shared secret.")
+ public AiEngineStatus status() {
+ ApplicationProperties.AiEngine config = applicationProperties.getAiEngine();
+ if (!config.isEnabled()) {
+ return AiEngineStatus.builder().enabled(false).reachable(false).build();
+ }
+
+ AiEngineStatus.AiEngineStatusBuilder status = AiEngineStatus.builder().enabled(true);
+ String userId = currentUserId();
+
+ // Asked first: a cloud outage or sharing being off explains any failure that follows.
+ if (aiEngineRouter.isCloudMode()) {
+ boolean cloudUp = cloudStatusProbe.isUp();
+ status.cloudUp(cloudUp);
+ if (!cloudUp) {
+ return status.reachable(false)
+ .cloudSharingEnabled(null)
+ .error("Stirling Cloud is not responding.")
+ .build();
+ }
+ Boolean sharing = probeCloudSharing(userId);
+ status.cloudSharingEnabled(sharing);
+ if (Boolean.FALSE.equals(sharing)) {
+ return status.reachable(false)
+ .error("Stirling Cloud AI sharing is switched off for linked servers.")
+ .build();
+ }
+ }
+
+ long startedAt = System.nanoTime();
+ String health;
+ try {
+ health = aiEngineClient.get("/health", userId);
+ } catch (IOException | RuntimeException e) {
+ return status.reachable(false).error(describeFailure(e)).build();
+ }
+ status.reachable(true)
+ .latencyMs(Duration.ofNanos(System.nanoTime() - startedAt).toMillis());
+
+ try {
+ JsonNode body = objectMapper.readTree(health);
+ status.smartModel(textOrNull(body, "smartModel"))
+ .fastModel(textOrNull(body, "fastModel"));
+ } catch (JacksonException e) {
+ log.debug("AI engine health returned a body we could not parse", e);
+ }
+
+ status.authenticated(probeAuthentication(userId, status));
+ return status.build();
+ }
+
+ /**
+ * @return false only when the gateway said so; null when it could not be asked
+ */
+ private Boolean probeCloudSharing(String userId) {
+ try {
+ JsonNode body = objectMapper.readTree(aiEngineClient.get("/status", userId));
+ JsonNode enabled = body.path("sharingEnabled");
+ return enabled.isBoolean() ? enabled.asBoolean() : null;
+ } catch (IOException | RuntimeException e) {
+ log.debug("Cloud AI sharing probe failed", e);
+ return null;
+ }
+ }
+
+ /**
+ * @return true if accepted, false if rejected, null if the probe failed for another reason
+ */
+ private Boolean probeAuthentication(
+ String userId, AiEngineStatus.AiEngineStatusBuilder status) {
+ try {
+ aiEngineClient.get("/api/v1/agents/capabilities", userId);
+ return true;
+ } catch (AiEngineClient.EngineRejectedCredentials e) {
+ status.error(
+ aiEngineRouter.isCloudMode()
+ ? "Stirling Cloud rejected this server's link credential."
+ : "The engine rejected this server's shared secret.");
+ return false;
+ } catch (ResponseStatusException e) {
+ int code = e.getStatusCode().value();
+ String reason = e.getReason();
+ // Engine 5xx arrive as 502, so its fail-closed 503 survives only in the message.
+ if (code == HttpStatus.BAD_GATEWAY.value()
+ && reason != null
+ && reason.endsWith("503")) {
+ status.error("The engine requires a shared secret but none is configured on it.");
+ return false;
+ }
+ log.debug("AI engine capabilities probe returned {}", code);
+ return null;
+ } catch (IOException | RuntimeException e) {
+ log.debug("AI engine capabilities probe failed", e);
+ return null;
+ }
+ }
+
+ private static String textOrNull(JsonNode body, String field) {
+ JsonNode value = body.path(field);
+ return value.isTextual() ? value.asText() : null;
+ }
+
+ private static String describeFailure(Exception e) {
+ if (e instanceof ResponseStatusException rse && rse.getReason() != null) {
+ return rse.getReason();
+ }
+ return e.getMessage();
+ }
+
@PostMapping(value = "/orchestrate", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
@Operation(
summary = "Run an AI workflow against a PDF",
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/mcp/engine/EngineCapabilityClient.java b/app/proprietary/src/main/java/stirling/software/proprietary/mcp/engine/EngineCapabilityClient.java
index ed023bd25b..16453a38f4 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/mcp/engine/EngineCapabilityClient.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/mcp/engine/EngineCapabilityClient.java
@@ -26,6 +26,8 @@ import stirling.software.common.model.ApplicationProperties;
import stirling.software.proprietary.mcp.catalog.McpToolCatalog;
import stirling.software.proprietary.mcp.catalog.OperationCategory;
import stirling.software.proprietary.mcp.catalog.OperationMeta;
+import stirling.software.proprietary.service.AiEngineRouter;
+import stirling.software.proprietary.service.AiEngineTarget;
import tools.jackson.databind.JsonNode;
import tools.jackson.databind.ObjectMapper;
@@ -44,19 +46,20 @@ public class EngineCapabilityClient {
private final McpToolCatalog catalog;
private final ObjectMapper mapper;
private final HttpClient httpClient;
- private final String sharedSecret;
+ private final AiEngineRouter router;
private ScheduledExecutorService scheduler;
public EngineCapabilityClient(
ApplicationProperties applicationProperties,
McpToolCatalog catalog,
- ObjectMapper mapper) {
+ ObjectMapper mapper,
+ AiEngineRouter router) {
this.applicationProperties = applicationProperties;
this.catalog = catalog;
this.mapper = mapper;
this.httpClient = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(5)).build();
- this.sharedSecret = System.getenv("STIRLING_ENGINE_SHARED_SECRET");
+ this.router = router;
}
@PostConstruct
@@ -105,18 +108,15 @@ public class EngineCapabilityClient {
catalog.replaceAiCapabilities(Map.of());
return;
}
- // Trim whitespace and any trailing slash to avoid a malformed URI.
- String base = applicationProperties.getAiEngine().getUrl().strip().replaceAll("/+$", "");
- URI uri = URI.create(base + "/api/v1/agents/capabilities");
+ AiEngineTarget target = router.resolve();
+ URI uri = URI.create(target.urlFor("/api/v1/agents/capabilities"));
HttpRequest.Builder reqBuilder =
HttpRequest.newBuilder()
.uri(uri)
.timeout(Duration.ofSeconds(10))
.header("Accept", "application/json")
.GET();
- if (sharedSecret != null && !sharedSecret.isBlank()) {
- reqBuilder.header("X-Engine-Auth", sharedSecret);
- }
+ target.headers().forEach(reqBuilder::header);
HttpResponse<String> response =
httpClient.send(reqBuilder.build(), HttpResponse.BodyHandlers.ofString());
if (response.statusCode() != 200) {
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/model/api/ai/AiEngineStatus.java b/app/proprietary/src/main/java/stirling/software/proprietary/model/api/ai/AiEngineStatus.java
new file mode 100644
index 0000000000..dd4a649f4f
--- /dev/null
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/model/api/ai/AiEngineStatus.java
@@ -0,0 +1,50 @@
+package stirling.software.proprietary.model.api.ai;
+
+import io.swagger.v3.oas.annotations.media.Schema;
+
+import lombok.AllArgsConstructor;
+import lombok.Builder;
+import lombok.Data;
+import lombok.NoArgsConstructor;
+
+/** What the admin AI page shows about the engine. */
+@Data
+@Builder
+@NoArgsConstructor
+@AllArgsConstructor
+@Schema(description = "Reachability and authentication status of the configured AI engine")
+public class AiEngineStatus {
+
+ @Schema(description = "Whether AI is switched on. When false nothing else was probed")
+ private boolean enabled;
+
+ @Schema(description = "Whether the engine answered its health check")
+ private boolean reachable;
+
+ @Schema(description = "Health check round-trip in milliseconds, null when unreachable")
+ private Long latencyMs;
+
+ @Schema(
+ description =
+ "Whether the engine accepted this server's credentials. Null when it could not"
+ + " be determined")
+ private Boolean authenticated;
+
+ @Schema(description = "Smart model the engine reports it is using", example = "claude-sonnet-5")
+ private String smartModel;
+
+ @Schema(description = "Fast model the engine reports it is using", example = "claude-haiku-4-5")
+ private String fastModel;
+
+ @Schema(description = "Why the probe failed, for display next to a red status")
+ private String error;
+
+ @Schema(description = "Cloud mode only: whether the Stirling Cloud host answered")
+ private Boolean cloudUp;
+
+ @Schema(
+ description =
+ "Cloud mode only: whether Stirling Cloud shares its AI with linked servers."
+ + " Null when it could not be determined")
+ private Boolean cloudSharingEnabled;
+}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/service/AiEngineClient.java b/app/proprietary/src/main/java/stirling/software/proprietary/service/AiEngineClient.java
index b0d726ceca..d1fd6ab258 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/service/AiEngineClient.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/service/AiEngineClient.java
@@ -18,39 +18,52 @@ import org.springframework.web.server.ResponseStatusException;
import lombok.extern.slf4j.Slf4j;
import stirling.software.common.model.ApplicationProperties;
+import stirling.software.proprietary.billing.AiCallRecord;
@Slf4j
@Service
public class AiEngineClient {
+ /** The one route that makes Stirling Cloud keep a document past the request. */
+ private static final String DOCUMENT_INGEST_PATH = "/api/v1/documents";
+
private final ApplicationProperties applicationProperties;
private final HttpClient httpClient;
- private final String engineSharedSecret;
+ private final AiEngineRouter router;
@Autowired
- public AiEngineClient(ApplicationProperties applicationProperties) {
+ public AiEngineClient(ApplicationProperties applicationProperties, AiEngineRouter router) {
this(
applicationProperties,
HttpClient.newBuilder()
.connectTimeout(
Duration.ofSeconds(
applicationProperties.getAiEngine().getTimeoutSeconds()))
- .build());
- }
-
- /** Package-private constructor that accepts an HttpClient directly; intended for tests. */
- AiEngineClient(ApplicationProperties applicationProperties, HttpClient httpClient) {
- this(applicationProperties, httpClient, System.getenv("STIRLING_ENGINE_SHARED_SECRET"));
+ .build(),
+ router);
}
- /** Package-private constructor that also injects the engine shared secret; for tests. */
- AiEngineClient(
+ public AiEngineClient(
ApplicationProperties applicationProperties,
HttpClient httpClient,
- String engineSharedSecret) {
+ AiEngineRouter router) {
this.applicationProperties = applicationProperties;
this.httpClient = httpClient;
- this.engineSharedSecret = engineSharedSecret;
+ this.router = router;
+ }
+
+ // The cloud retention check lives here so every engine call, new ones included, passes it.
+ private AiEngineTarget resolveTarget(String path) {
+ AiEngineTarget target = router.resolve();
+ if (target.cloud()
+ && DOCUMENT_INGEST_PATH.equals(path)
+ && !router.documentIndexingAllowed()) {
+ throw new ResponseStatusException(
+ HttpStatus.FORBIDDEN,
+ "Storing documents on Stirling Cloud is turned off on this server, so"
+ + " document questions are unavailable in cloud AI mode.");
+ }
+ return target;
}
public String post(String path, String jsonBody, String userId) throws IOException {
@@ -77,7 +90,8 @@ public class AiEngineClient {
HttpStatus.SERVICE_UNAVAILABLE, "AI engine is not enabled");
}
- String url = config.getUrl().stripTrailing() + path;
+ AiEngineTarget target = resolveTarget(path);
+ String url = target.urlFor(path);
log.debug("Proxying AI engine request to {} (timeout {}s)", url, timeout.toSeconds());
HttpRequest.Builder builder =
@@ -88,22 +102,16 @@ public class AiEngineClient {
.timeout(timeout)
.POST(HttpRequest.BodyPublishers.ofString(jsonBody));
addUserHeader(builder, userId);
- addEngineAuthHeader(builder);
- HttpResponse<String> response = sendRequest(builder.build());
+ addEngineAuthHeader(builder, target);
+ HttpResponse<String> response = sendRequest(builder.build(), target);
log.debug("AI engine responded with status {}", response.statusCode());
checkResponseStatus(response);
return response.body();
}
- /**
- * Attach the {@code X-Engine-Auth} shared secret when configured so the engine trusts this
- * backend request.
- */
- private void addEngineAuthHeader(HttpRequest.Builder builder) {
- if (engineSharedSecret != null && !engineSharedSecret.isBlank()) {
- builder.header("X-Engine-Auth", engineSharedSecret);
- }
+ private static void addEngineAuthHeader(HttpRequest.Builder builder, AiEngineTarget target) {
+ target.headers().forEach(builder::header);
}
private static void addUserHeader(HttpRequest.Builder builder, String userId) {
@@ -130,7 +138,8 @@ public class AiEngineClient {
HttpStatus.SERVICE_UNAVAILABLE, "AI engine is not enabled");
}
- String url = config.getUrl().stripTrailing() + path;
+ AiEngineTarget target = resolveTarget(path);
+ String url = target.urlFor(path);
Duration timeout = Duration.ofSeconds(config.getLongRunningTimeoutSeconds());
log.debug(
"Proxying AI engine streaming request to {} (timeout {}s)",
@@ -145,17 +154,18 @@ public class AiEngineClient {
.timeout(timeout)
.POST(HttpRequest.BodyPublishers.ofString(jsonBody));
addUserHeader(builder, userId);
- addEngineAuthHeader(builder);
+ addEngineAuthHeader(builder, target);
HttpRequest request = builder.build();
HttpResponse<Stream<String>> response;
try {
response = httpClient.send(request, HttpResponse.BodyHandlers.ofLines());
+ recordWhereItRan(target);
} catch (HttpTimeoutException e) {
throw new ResponseStatusException(HttpStatus.GATEWAY_TIMEOUT, "AI engine timed out", e);
} catch (IOException e) {
throw new ResponseStatusException(
- HttpStatus.SERVICE_UNAVAILABLE, "AI engine unreachable: " + e.getMessage(), e);
+ HttpStatus.SERVICE_UNAVAILABLE, "AI engine unreachable: " + describe(e), e);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new ResponseStatusException(
@@ -164,9 +174,7 @@ public class AiEngineClient {
int status = response.statusCode();
if (status >= 400) {
- throw new ResponseStatusException(
- HttpStatus.valueOf(status >= 500 ? 502 : status),
- "AI engine returned error: " + status);
+ throw failureFor(status, null);
}
try (Stream<String> lines = response.body()) {
@@ -191,7 +199,8 @@ public class AiEngineClient {
HttpStatus.SERVICE_UNAVAILABLE, "AI engine is not enabled");
}
- String url = config.getUrl().stripTrailing() + path;
+ AiEngineTarget target = resolveTarget(path);
+ String url = target.urlFor(path);
log.debug("Proxying AI engine DELETE request to {}", url);
HttpRequest.Builder builder =
@@ -201,8 +210,8 @@ public class AiEngineClient {
.timeout(Duration.ofSeconds(config.getTimeoutSeconds()))
.DELETE();
addUserHeader(builder, userId);
- addEngineAuthHeader(builder);
- HttpResponse<String> response = sendRequest(builder.build());
+ addEngineAuthHeader(builder, target);
+ HttpResponse<String> response = sendRequest(builder.build(), target);
log.debug("AI engine responded with status {}", response.statusCode());
checkResponseStatus(response);
@@ -216,7 +225,8 @@ public class AiEngineClient {
HttpStatus.SERVICE_UNAVAILABLE, "AI engine is not enabled");
}
- String url = config.getUrl().stripTrailing() + path;
+ AiEngineTarget target = resolveTarget(path);
+ String url = target.urlFor(path);
log.debug("Proxying AI engine GET request to {}", url);
HttpRequest.Builder builder =
@@ -226,17 +236,34 @@ public class AiEngineClient {
.timeout(Duration.ofSeconds(config.getTimeoutSeconds()))
.GET();
addUserHeader(builder, userId);
- addEngineAuthHeader(builder);
- HttpResponse<String> response = sendRequest(builder.build());
+ addEngineAuthHeader(builder, target);
+ HttpResponse<String> response = sendRequest(builder.build(), target);
log.debug("AI engine responded with status {}", response.statusCode());
checkResponseStatus(response);
return response.body();
}
- private HttpResponse<String> sendRequest(HttpRequest request) throws IOException {
+ /** The JDK's ConnectException has no message, which would render as "unreachable: null". */
+ private static String describe(Exception e) {
+ String message = e.getMessage();
+ return message != null && !message.isBlank()
+ ? message
+ : e.getClass().getSimpleName() + " (nothing listening on the configured URL?)";
+ }
+
+ // Any answer counts, failures included: the meter skips failed requests on their status.
+ private static void recordWhereItRan(AiEngineTarget target) {
+ AiCallRecord.record(target.cloud() ? AiCallRecord.Where.REMOTE : AiCallRecord.Where.LOCAL);
+ }
+
+ private HttpResponse<String> sendRequest(HttpRequest request, AiEngineTarget target)
+ throws IOException {
try {
- return httpClient.send(request, HttpResponse.BodyHandlers.ofString());
+ HttpResponse<String> response =
+ httpClient.send(request, HttpResponse.BodyHandlers.ofString());
+ recordWhereItRan(target);
+ return response;
} catch (HttpTimeoutException e) {
throw new ResponseStatusException(HttpStatus.GATEWAY_TIMEOUT, "AI engine timed out", e);
} catch (IOException e) {
@@ -244,7 +271,7 @@ public class AiEngineClient {
// SERVICE_UNAVAILABLE so every caller of this client sees a structured
// status rather than a raw 500 from an unhandled IOException.
throw new ResponseStatusException(
- HttpStatus.SERVICE_UNAVAILABLE, "AI engine unreachable: " + e.getMessage(), e);
+ HttpStatus.SERVICE_UNAVAILABLE, "AI engine unreachable: " + describe(e), e);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new ResponseStatusException(
@@ -254,14 +281,42 @@ public class AiEngineClient {
private void checkResponseStatus(HttpResponse<String> response) {
int status = response.statusCode();
+ if (status >= 400) {
+ throw failureFor(status, response.body());
+ }
+ }
+
+ /**
+ * An upstream 401/403 is about this server's credentials; relayed as-is, the frontend would
+ * treat it as its own session expiring and reload mid-flow.
+ */
+ private static ResponseStatusException failureFor(int status, String body) {
+ if (status == 401 || status == 403) {
+ return new EngineRejectedCredentials(status);
+ }
if (status >= 500) {
- throw new ResponseStatusException(
+ return new ResponseStatusException(
HttpStatus.BAD_GATEWAY, "AI engine returned error: " + status);
}
- if (status >= 400) {
- throw new ResponseStatusException(
- HttpStatus.valueOf(status),
- "AI engine returned client error: " + response.body());
+ String detail = body == null || body.isBlank() ? "" : ": " + body;
+ return new ResponseStatusException(
+ HttpStatus.valueOf(status),
+ "AI engine returned client error (HTTP " + status + ")" + detail);
+ }
+
+ /** The engine, or the cloud gateway in front of it, refused this server's own credentials. */
+ public static final class EngineRejectedCredentials extends ResponseStatusException {
+ private final int upstreamStatus;
+
+ EngineRejectedCredentials(int upstreamStatus) {
+ super(
+ HttpStatus.BAD_GATEWAY,
+ "AI engine rejected this server's credentials (HTTP " + upstreamStatus + ")");
+ this.upstreamStatus = upstreamStatus;
+ }
+
+ public int upstreamStatus() {
+ return upstreamStatus;
}
}
}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/service/AiEngineConfigSync.java b/app/proprietary/src/main/java/stirling/software/proprietary/service/AiEngineConfigSync.java
index 99f5f025ef..e1d5373d45 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/service/AiEngineConfigSync.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/service/AiEngineConfigSync.java
@@ -37,6 +37,7 @@ public class AiEngineConfigSync {
private final ApplicationProperties applicationProperties;
private final AiEngineClient aiEngineClient;
private final ObjectMapper objectMapper;
+ private final AiEngineRouter router;
// Single worker keeps pushes strictly ordered; virtual (daemon) thread never blocks shutdown.
private final ExecutorService pushExecutor =
@@ -60,6 +61,11 @@ public class AiEngineConfigSync {
+ " (the engine is configured from its own environment)");
return;
}
+ if (router.isCloudMode()) {
+ // Stirling Cloud picks its own models, and its gateway refuses the config route.
+ log.debug("Skipping AI engine config push: this server is using Stirling Cloud AI");
+ return;
+ }
// Engine may still be booting; push off-thread with retries so startup never blocks.
submit(() -> pushWithRetries(cfg));
}
@@ -77,7 +83,8 @@ public class AiEngineConfigSync {
if (pendingAiEngine == null
|| pendingAiEngine.isEmpty()
|| !cfg.isPushConfigToEngine()
- || !cfg.isEnabled()) {
+ || !cfg.isEnabled()
+ || router.isCloudMode()) {
return;
}
Set<String> engineKeys =
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/service/AiEngineRouter.java b/app/proprietary/src/main/java/stirling/software/proprietary/service/AiEngineRouter.java
new file mode 100644
index 0000000000..da92effefa
--- /dev/null
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/service/AiEngineRouter.java
@@ -0,0 +1,174 @@
+package stirling.software.proprietary.service;
+
+import java.net.URI;
+import java.util.Map;
+import java.util.Optional;
+import java.util.stream.Stream;
+
+import org.springframework.beans.factory.ObjectProvider;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.http.HttpStatus;
+import org.springframework.stereotype.Service;
+import org.springframework.web.server.ResponseStatusException;
+
+import stirling.software.common.model.ApplicationProperties;
+import stirling.software.common.model.ApplicationProperties.AiEngine.AiEngineMode;
+import stirling.software.proprietary.accountlink.AccountLinkProperties;
+import stirling.software.proprietary.accountlink.DeviceCredential;
+import stirling.software.proprietary.accountlink.DeviceCredentialStore;
+
+/**
+ * Picks where an AI engine call goes: the configured engine with the shared secret, or Stirling
+ * Cloud's gateway with this server's account-link device credential.
+ */
+@Service
+public class AiEngineRouter {
+
+ /** Under {@code /api/v1/instance}, the only prefix the device credential authenticates on. */
+ static final String CLOUD_GATEWAY_PATH = "/api/v1/instance/ai";
+
+ static final String HEADER_ENGINE_AUTH = "X-Engine-Auth";
+ static final String HEADER_DEVICE_ID = "X-Device-Id";
+ static final String HEADER_DEVICE_SECRET = "X-Device-Secret";
+
+ private final ApplicationProperties applicationProperties;
+ private final ObjectProvider<DeviceCredentialStore> credentialStore;
+ private final ObjectProvider<AccountLinkProperties> accountLinkProperties;
+ private final String engineSharedSecret;
+
+ @Autowired
+ public AiEngineRouter(
+ ApplicationProperties applicationProperties,
+ ObjectProvider<DeviceCredentialStore> credentialStore,
+ ObjectProvider<AccountLinkProperties> accountLinkProperties) {
+ this(
+ applicationProperties,
+ credentialStore,
+ accountLinkProperties,
+ System.getenv("STIRLING_ENGINE_SHARED_SECRET"));
+ }
+
+ public AiEngineRouter(
+ ApplicationProperties applicationProperties,
+ ObjectProvider<DeviceCredentialStore> credentialStore,
+ ObjectProvider<AccountLinkProperties> accountLinkProperties,
+ String engineSharedSecret) {
+ this.applicationProperties = applicationProperties;
+ this.credentialStore = credentialStore;
+ this.accountLinkProperties = accountLinkProperties;
+ this.engineSharedSecret = engineSharedSecret;
+ }
+
+ /** A router without account-link beans, so cloud mode always fails to resolve. */
+ public static AiEngineRouter selfHosted(
+ ApplicationProperties applicationProperties, String engineSharedSecret) {
+ return new AiEngineRouter(applicationProperties, absent(), absent(), engineSharedSecret);
+ }
+
+ private static <T> ObjectProvider<T> absent() {
+ return new ObjectProvider<>() {
+ @Override
+ public Stream<T> stream() {
+ return Stream.empty();
+ }
+ };
+ }
+
+ public boolean isCloudMode() {
+ return applicationProperties.getAiEngine().getMode() == AiEngineMode.CLOUD;
+ }
+
+ /** Always true self-hosted; in cloud mode only when the admin lets Stirling Cloud keep text. */
+ public boolean documentIndexingAllowed() {
+ return !isCloudMode() || applicationProperties.getAiEngine().isCloudDocumentIndexing();
+ }
+
+ /**
+ * @throws ResponseStatusException 503 in cloud mode when this server is not linked or has no
+ * usable Stirling Cloud address
+ */
+ public AiEngineTarget resolve() {
+ if (!isCloudMode()) {
+ return selfHostedTarget();
+ }
+ DeviceCredential credential =
+ Optional.ofNullable(credentialStore.getIfAvailable())
+ .flatMap(DeviceCredentialStore::get)
+ .orElseThrow(
+ () ->
+ new ResponseStatusException(
+ HttpStatus.SERVICE_UNAVAILABLE,
+ "Stirling Cloud AI is selected but this server is"
+ + " not linked to a Stirling account."));
+ String host = cloudHost();
+ if (host.isEmpty()) {
+ throw new ResponseStatusException(
+ HttpStatus.SERVICE_UNAVAILABLE,
+ "Stirling Cloud AI is selected but no Stirling Cloud address is configured.");
+ }
+ return new AiEngineTarget(
+ host + CLOUD_GATEWAY_PATH,
+ Map.of(
+ HEADER_DEVICE_ID, credential.getDeviceId(),
+ HEADER_DEVICE_SECRET, credential.getDeviceSecret()),
+ true);
+ }
+
+ /** The configured engine regardless of mode, which is what Stirling Cloud's gateway calls. */
+ public AiEngineTarget selfHostedTarget() {
+ return new AiEngineTarget(
+ trimTrailingSlashes(applicationProperties.getAiEngine().getUrl()),
+ engineSharedSecret == null || engineSharedSecret.isBlank()
+ ? Map.of()
+ : Map.of(HEADER_ENGINE_AUTH, engineSharedSecret),
+ false);
+ }
+
+ /**
+ * {@code aiEngine.cloudBaseUrl}, else the account-link host, with no gateway path; empty when
+ * neither is set.
+ *
+ * @throws ResponseStatusException when the URL is not safe to send the device credential to
+ */
+ public String cloudHost() {
+ String host = trimTrailingSlashes(applicationProperties.getAiEngine().getCloudBaseUrl());
+ if (host.isEmpty()) {
+ AccountLinkProperties linkProperties = accountLinkProperties.getIfAvailable();
+ host =
+ linkProperties == null
+ ? ""
+ : trimTrailingSlashes(linkProperties.getSaasBaseUrl());
+ }
+ return host.isEmpty() ? host : requireCredentialSafe(host);
+ }
+
+ private static String requireCredentialSafe(String base) {
+ try {
+ URI uri = URI.create(base);
+ String host = uri.getHost();
+ boolean loopback =
+ "localhost".equalsIgnoreCase(host)
+ || "127.0.0.1".equals(host)
+ || "[::1]".equals(host);
+ if (host != null
+ && uri.getRawUserInfo() == null
+ && uri.getRawQuery() == null
+ && uri.getRawFragment() == null
+ && (uri.getPort() == -1 || (uri.getPort() > 0 && uri.getPort() <= 65535))
+ && ("https".equalsIgnoreCase(uri.getScheme())
+ || ("http".equalsIgnoreCase(uri.getScheme()) && loopback))) {
+ return base;
+ }
+ } catch (IllegalArgumentException ignored) {
+ // Malformed URLs get the same error as unsafe ones.
+ }
+ throw new ResponseStatusException(
+ HttpStatus.SERVICE_UNAVAILABLE,
+ "Stirling Cloud AI requires a valid HTTPS base URL without user info, query or"
+ + " fragment. HTTP is allowed only for localhost, 127.0.0.1 or [::1].");
+ }
+
+ private static String trimTrailingSlashes(String value) {
+ return value == null ? "" : value.strip().replaceAll("/+$", "");
+ }
+}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/service/AiEngineTarget.java b/app/proprietary/src/main/java/stirling/software/proprietary/service/AiEngineTarget.java
new file mode 100644
index 0000000000..039530bad6
--- /dev/null
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/service/AiEngineTarget.java
@@ -0,0 +1,15 @@
+package stirling.software.proprietary.service;
+
+import java.util.Map;
+
+/** Where one AI engine call goes and the auth headers it carries; baseUrl has no trailing slash. */
+public record AiEngineTarget(String baseUrl, Map<String, String> headers, boolean cloud) {
+
+ public AiEngineTarget {
+ headers = Map.copyOf(headers);
+ }
+
+ public String urlFor(String path) {
+ return baseUrl + path;
+ }
+}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/service/CloudStatusProbe.java b/app/proprietary/src/main/java/stirling/software/proprietary/service/CloudStatusProbe.java
new file mode 100644
index 0000000000..aaa0f2c10f
--- /dev/null
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/service/CloudStatusProbe.java
@@ -0,0 +1,68 @@
+package stirling.software.proprietary.service;
+
+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.stereotype.Service;
+
+import lombok.extern.slf4j.Slf4j;
+
+/**
+ * Whether the Stirling Cloud host is up at all, via its unauthenticated status endpoint. Tells a
+ * Stirling outage apart from a broken link, which look the same from the gateway.
+ */
+@Slf4j
+@Service
+public class CloudStatusProbe {
+
+ static final String STATUS_PATH = "/api/v1/info/status";
+
+ private final HttpClient httpClient;
+ private final AiEngineRouter router;
+
+ @Autowired
+ public CloudStatusProbe(AiEngineRouter router) {
+ this(
+ HttpClient.newBuilder()
+ .connectTimeout(Duration.ofSeconds(5))
+ .followRedirects(HttpClient.Redirect.NEVER)
+ .build(),
+ router);
+ }
+
+ /** Package-private: lets tests point at a stub host. */
+ CloudStatusProbe(HttpClient httpClient, AiEngineRouter router) {
+ this.httpClient = httpClient;
+ this.router = router;
+ }
+
+ /** Probes only the validated configured host, without following redirects. Never throws. */
+ public boolean isUp() {
+ try {
+ String baseUrl = router.cloudHost();
+ if (baseUrl.isEmpty()) {
+ return false;
+ }
+ HttpRequest request =
+ HttpRequest.newBuilder()
+ .uri(URI.create(baseUrl + STATUS_PATH))
+ .timeout(Duration.ofSeconds(5))
+ .GET()
+ .build();
+ int code =
+ httpClient.send(request, HttpResponse.BodyHandlers.discarding()).statusCode();
+ return code >= 200 && code < 300;
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ return false;
+ } catch (IOException | RuntimeException e) {
+ log.debug("Stirling Cloud status probe failed", e);
+ return false;
+ }
+ }
+}
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/EnterpriseProcessingHttpIntegrationTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/EnterpriseProcessingHttpIntegrationTest.java
index 5ae9bf98c1..56e95624ca 100644
--- a/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/EnterpriseProcessingHttpIntegrationTest.java
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/EnterpriseProcessingHttpIntegrationTest.java
@@ -62,6 +62,7 @@ import stirling.software.proprietary.controller.api.converters.ConvertPdfToPdfUa
import stirling.software.proprietary.security.configuration.ee.DynamicLicenseService;
import stirling.software.proprietary.security.configuration.ee.KeygenLicenseVerifier.License;
import stirling.software.proprietary.security.configuration.ee.LicenseKeyChecker;
+import stirling.software.proprietary.service.AiEngineRouter;
import stirling.software.proprietary.service.ua.FontEmbeddingService;
import stirling.software.proprietary.service.ua.PdfUaConversionService;
import stirling.software.proprietary.service.ua.PdfUaValidationService;
@@ -306,7 +307,7 @@ class EnterpriseProcessingHttpIntegrationTest {
UsageMeterService.class, UsageSyncService.class, DeviceCredentialStore.class,
EntitlementCache.class, DynamicLicenseService.class, TempFileManager.class,
TempFileRegistry.class, ConvertPdfToPdfUa.class, PdfUaConversionService.class,
- PdfUaValidationService.class, FontEmbeddingService.class
+ PdfUaValidationService.class, FontEmbeddingService.class, AiEngineRouter.class
})
static class TestApp {
@Bean
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/InstanceEntitlementInterceptorTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/InstanceEntitlementInterceptorTest.java
index f68fd12d26..bccd0c7972 100644
--- a/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/InstanceEntitlementInterceptorTest.java
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/InstanceEntitlementInterceptorTest.java
@@ -41,11 +41,14 @@ import org.springframework.mock.web.MockMultipartFile;
import org.springframework.mock.web.MockMultipartHttpServletRequest;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
+import org.springframework.web.context.request.RequestContextHolder;
+import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.method.HandlerMethod;
import stirling.software.common.annotations.AutoJobPostMapping;
import stirling.software.common.util.TempFile;
import stirling.software.common.util.TempFileManager;
+import stirling.software.proprietary.billing.AiCallRecord;
import stirling.software.proprietary.billing.BillingCategory;
import stirling.software.proprietary.billing.UnitCalcPolicy;
import stirling.software.proprietary.security.model.ApiKeyAuthenticationToken;
@@ -78,6 +81,17 @@ class InstanceEntitlementInterceptorTest {
new Object());
}
+ /** Records an engine call as AiEngineClient does; AI metering keys off it, not the mode. */
+ private static void engineCalled(
+ jakarta.servlet.http.HttpServletRequest request, AiCallRecord.Where where) {
+ RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(request));
+ try {
+ AiCallRecord.record(where);
+ } finally {
+ RequestContextHolder.resetRequestAttributes();
+ }
+ }
+
@Test
void includedServerApiSkipsBothCreditLedgers() throws Exception {
when(gate.evaluate(true, true))
@@ -173,6 +187,7 @@ class InstanceEntitlementInterceptorTest {
MockMultipartHttpServletRequest req = fileRequest("/api/v1/ai/tools/x");
MockHttpServletResponse resp = new MockHttpServletResponse();
interceptor.preHandle(req, resp, new Object());
+ engineCalled(req, AiCallRecord.Where.LOCAL);
interceptor.afterCompletion(req, resp, new Object(), null);
verify(freeTierUsageService).accrue(eq(BillingCategory.AI), eq(1L), isNull());
@@ -264,12 +279,47 @@ class InstanceEntitlementInterceptorTest {
MockMultipartHttpServletRequest req = fileRequest("/api/v1/ai/tools/x");
MockHttpServletResponse resp = new MockHttpServletResponse();
interceptor.preHandle(req, resp, new Object()); // stashes AI category
+ engineCalled(req, AiCallRecord.Where.LOCAL);
interceptor.afterCompletion(req, resp, new Object(), null);
// A tiny non-PDF input bills the 1-unit byte floor; a standalone op has a null key.
verify(meter).accrue(eq(period), eq(BillingCategory.AI), eq(1L), isNull(), eq(10));
}
+ @Test
+ void doesNotMeterAiThatStirlingCloudAlreadyBilled() throws Exception {
+ // Stirling Cloud billed this on success; metering it here too would charge twice.
+ when(gate.evaluate(anyBoolean(), anyBoolean()))
+ .thenReturn(GateDecision.allow(GateDecision.Reason.ENTITLED));
+ InstanceEntitlementInterceptor interceptor = interceptor();
+ MockMultipartHttpServletRequest req = fileRequest("/api/v1/ai/tools/x");
+ MockHttpServletResponse resp = new MockHttpServletResponse();
+ interceptor.preHandle(req, resp, new Object());
+ engineCalled(req, AiCallRecord.Where.REMOTE);
+ interceptor.afterCompletion(req, resp, new Object(), null);
+
+ // Nothing downstream is even consulted: the skip happens before any meter is resolved.
+ verify(meterProvider, never()).getIfAvailable();
+ verifyNoInteractions(freeTierUsageService);
+ }
+
+ @Test
+ void doesNotMeterAnAiRouteThatNeverCalledTheEngine() throws Exception {
+ // e.g. a document that already carries a verdict: no engine call, so nothing to bill.
+ when(gate.evaluate(anyBoolean(), anyBoolean()))
+ .thenReturn(GateDecision.allow(GateDecision.Reason.ENTITLED));
+ InstanceEntitlementInterceptor interceptor = interceptor();
+ MockMultipartHttpServletRequest req = fileRequest("/api/v1/ai/tools/x");
+ MockHttpServletResponse resp = new MockHttpServletResponse();
+ interceptor.preHandle(req, resp, new Object());
+ // No engineCalled(...) on purpose: the route returned without reaching the engine.
+ interceptor.afterCompletion(req, resp, new Object(), null);
+
+ // Nothing downstream is even consulted: the skip happens before any meter is resolved.
+ verify(meterProvider, never()).getIfAvailable();
+ verifyNoInteractions(freeTierUsageService);
+ }
+
@Test
void doesNotMeterFilelessBillableOp() throws Exception {
// A billable op with no document (no multipart file) is not metered - matching SaaS, which
@@ -286,6 +336,7 @@ class InstanceEntitlementInterceptorTest {
MockHttpServletRequest req = new MockHttpServletRequest("POST", "/api/v1/ai/tools/x");
MockHttpServletResponse resp = new MockHttpServletResponse();
interceptor.preHandle(req, resp, new Object());
+ engineCalled(req, AiCallRecord.Where.LOCAL);
interceptor.afterCompletion(req, resp, new Object(), null);
verify(meter, never()).accrue(any(), any(), anyLong(), any(), eq(10));
@@ -314,6 +365,7 @@ class InstanceEntitlementInterceptorTest {
req.addFile(new MockMultipartFile("file", "doc.pdf", "application/pdf", fivePagePdf()));
MockHttpServletResponse resp = new MockHttpServletResponse();
interceptor.preHandle(req, resp, new Object());
+ engineCalled(req, AiCallRecord.Where.LOCAL);
interceptor.afterCompletion(req, resp, new Object(), null);
// 5 pages, and a null key: a standalone op (no run) is its own charge - never deduped.
@@ -356,6 +408,7 @@ class InstanceEntitlementInterceptorTest {
MockHttpServletRequest req = new MockHttpServletRequest("POST", "/api/v1/ai/tools/x");
MockHttpServletResponse resp = new MockHttpServletResponse();
interceptor.preHandle(req, resp, new Object());
+ engineCalled(req, AiCallRecord.Where.LOCAL);
interceptor.afterCompletion(req, resp, new Object(), null);
// Meter absent → no entitlement lookup, no accrual.
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/mcp/engine/EngineCapabilityParseTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/mcp/engine/EngineCapabilityParseTest.java
index 9be2d9908d..b83e09b271 100644
--- a/app/proprietary/src/test/java/stirling/software/proprietary/mcp/engine/EngineCapabilityParseTest.java
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/mcp/engine/EngineCapabilityParseTest.java
@@ -11,6 +11,7 @@ import stirling.software.common.model.ApplicationProperties;
import stirling.software.proprietary.mcp.catalog.McpToolCatalog;
import stirling.software.proprietary.mcp.catalog.OperationCategory;
import stirling.software.proprietary.mcp.catalog.OperationMeta;
+import stirling.software.proprietary.service.AiEngineRouter;
import tools.jackson.databind.ObjectMapper;
@@ -24,8 +25,7 @@ class EngineCapabilityParseTest {
ObjectMapper mapper = new ObjectMapper();
ApplicationProperties props = new ApplicationProperties();
// parseManifest doesn't touch the catalog, so a null catalog is fine.
- EngineCapabilityClient client =
- new EngineCapabilityClient(props, (McpToolCatalog) null, mapper);
+ EngineCapabilityClient client = newClient(props, mapper);
String body =
"""
@@ -77,9 +77,7 @@ class EngineCapabilityParseTest {
@Test
void missing_capabilities_array_throws() {
ObjectMapper mapper = new ObjectMapper();
- EngineCapabilityClient client =
- new EngineCapabilityClient(
- new ApplicationProperties(), (McpToolCatalog) null, mapper);
+ EngineCapabilityClient client = newClient(new ApplicationProperties(), mapper);
try {
Method parse =
@@ -97,9 +95,7 @@ class EngineCapabilityParseTest {
@Test
void unsafe_routes_are_skipped_and_blank_scope_fails_safe() throws Exception {
ObjectMapper mapper = new ObjectMapper();
- EngineCapabilityClient client =
- new EngineCapabilityClient(
- new ApplicationProperties(), (McpToolCatalog) null, mapper);
+ EngineCapabilityClient client = newClient(new ApplicationProperties(), mapper);
String body =
"""
@@ -135,4 +131,11 @@ class EngineCapabilityParseTest {
assertThat(EngineCapabilityClient.isSafeRelativeRoute("/admin/x")).isFalse();
assertThat(EngineCapabilityClient.isSafeRelativeRoute("/api/v1/x y")).isFalse();
}
+
+ /** parseManifest never touches the catalog or the network, so both can be absent. */
+ private static EngineCapabilityClient newClient(
+ ApplicationProperties props, ObjectMapper mapper) {
+ return new EngineCapabilityClient(
+ props, (McpToolCatalog) null, mapper, AiEngineRouter.selfHosted(props, null));
+ }
}
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/service/AiEngineClientTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/service/AiEngineClientTest.java
index 259ae55a0b..d309020a02 100644
--- a/app/proprietary/src/test/java/stirling/software/proprietary/service/AiEngineClientTest.java
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/service/AiEngineClientTest.java
@@ -3,6 +3,7 @@ package stirling.software.proprietary.service;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@@ -12,13 +13,18 @@ import java.net.ConnectException;
import java.net.http.HttpClient;
import java.net.http.HttpResponse;
import java.net.http.HttpTimeoutException;
+import java.util.stream.Stream;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.http.HttpStatus;
+import org.springframework.mock.web.MockHttpServletRequest;
+import org.springframework.web.context.request.RequestContextHolder;
+import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.server.ResponseStatusException;
import stirling.software.common.model.ApplicationProperties;
+import stirling.software.proprietary.billing.AiCallRecord;
/**
* Verifies that AiEngineClient surfaces network-layer failures as structured HTTP statuses so every
@@ -37,7 +43,11 @@ class AiEngineClientTest {
applicationProperties.getAiEngine().setUrl("http://localhost:5001");
applicationProperties.getAiEngine().setTimeoutSeconds(5);
httpClient = mock(HttpClient.class);
- client = new AiEngineClient(applicationProperties, httpClient);
+ client =
+ new AiEngineClient(
+ applicationProperties,
+ httpClient,
+ AiEngineRouter.selfHosted(applicationProperties, null));
}
@Test
@@ -85,6 +95,56 @@ class AiEngineClientTest {
assertEquals(HttpStatus.SERVICE_UNAVAILABLE, ex.getStatusCode());
}
+ @Test
+ @SuppressWarnings("unchecked")
+ void anUpstreamUnauthorizedIsAboutOurCredentialsNotTheCallers() throws Exception {
+ // Relayed as a 401 the frontend treats it as its own session expiring and reloads.
+ HttpResponse<String> rejected = mock(HttpResponse.class);
+ when(rejected.statusCode()).thenReturn(401);
+ when(rejected.body()).thenReturn("");
+ when(httpClient.send(any(), any(HttpResponse.BodyHandler.class))).thenReturn(rejected);
+
+ ResponseStatusException ex =
+ assertThrows(ResponseStatusException.class, () -> client.get("/x", null));
+
+ assertEquals(HttpStatus.BAD_GATEWAY, ex.getStatusCode());
+ assertEquals(401, ((AiEngineClient.EngineRejectedCredentials) ex).upstreamStatus());
+ assertEquals("AI engine rejected this server's credentials (HTTP 401)", ex.getReason());
+ }
+
+ @Test
+ @SuppressWarnings("unchecked")
+ void aStreamedCallRecordsWhereItRanForTheMeter() throws Exception {
+ HttpResponse<Stream<String>> streamed = mock(HttpResponse.class);
+ when(streamed.statusCode()).thenReturn(200);
+ when(streamed.body()).thenReturn(Stream.of("{\"event\":\"result\"}"));
+ when(httpClient.send(any(), any(HttpResponse.BodyHandler.class))).thenReturn(streamed);
+ MockHttpServletRequest request = new MockHttpServletRequest();
+ RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(request));
+ try {
+ client.streamPost("/api/v1/orchestrator", "{}", null, line -> {});
+ } finally {
+ RequestContextHolder.resetRequestAttributes();
+ }
+
+ assertTrue(AiCallRecord.ranLocally(request.getAttribute(AiCallRecord.attributeName())));
+ }
+
+ @Test
+ @SuppressWarnings("unchecked")
+ void aClientErrorNamesItsStatusEvenWithAnEmptyBody() throws Exception {
+ HttpResponse<String> unprocessable = mock(HttpResponse.class);
+ when(unprocessable.statusCode()).thenReturn(422);
+ when(unprocessable.body()).thenReturn("");
+ when(httpClient.send(any(), any(HttpResponse.BodyHandler.class))).thenReturn(unprocessable);
+
+ ResponseStatusException ex =
+ assertThrows(ResponseStatusException.class, () -> client.post("/x", "{}", null));
+
+ assertEquals(HttpStatus.UNPROCESSABLE_CONTENT, ex.getStatusCode());
+ assertEquals("AI engine returned client error (HTTP 422)", ex.getReason());
+ }
+
@Test
@SuppressWarnings("unchecked")
void allVerbsSendEngineAuthHeaderWhenSecretConfigured() throws Exception {
@@ -92,7 +152,10 @@ class AiEngineClientTest {
// engine route (post/delete/get) must present X-Engine-Auth, or the route 401s once the
// secret is set. delete() backs the logout-time RAG purge, so a miss silently leaks data.
AiEngineClient secured =
- new AiEngineClient(applicationProperties, httpClient, "top-secret");
+ new AiEngineClient(
+ applicationProperties,
+ httpClient,
+ AiEngineRouter.selfHosted(applicationProperties, "top-secret"));
HttpResponse<String> ok = mock(HttpResponse.class);
when(ok.statusCode()).thenReturn(200);
when(ok.body()).thenReturn("{}");
@@ -115,7 +178,11 @@ class AiEngineClientTest {
@Test
@SuppressWarnings("unchecked")
void noEngineAuthHeaderWhenSecretUnset() throws Exception {
- AiEngineClient noSecret = new AiEngineClient(applicationProperties, httpClient, null);
+ AiEngineClient noSecret =
+ new AiEngineClient(
+ applicationProperties,
+ httpClient,
+ AiEngineRouter.selfHosted(applicationProperties, null));
HttpResponse<String> ok = mock(HttpResponse.class);
when(ok.statusCode()).thenReturn(200);
when(ok.body()).thenReturn("{}");
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/service/AiEngineConfigSyncTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/service/AiEngineConfigSyncTest.java
index 41f35c9daf..4af92f86fe 100644
--- a/app/proprietary/src/test/java/stirling/software/proprietary/service/AiEngineConfigSyncTest.java
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/service/AiEngineConfigSyncTest.java
@@ -3,6 +3,7 @@ package stirling.software.proprietary.service;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
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.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.isNull;
@@ -42,7 +43,12 @@ class AiEngineConfigSyncTest {
applicationProperties.getAiEngine().setPushConfigToEngine(true);
aiEngineClient = mock(AiEngineClient.class);
ObjectMapper objectMapper = JsonMapper.builder().build();
- sync = new AiEngineConfigSync(applicationProperties, aiEngineClient, objectMapper);
+ sync =
+ new AiEngineConfigSync(
+ applicationProperties,
+ aiEngineClient,
+ objectMapper,
+ AiEngineRouter.selfHosted(applicationProperties, null));
}
@Test
@@ -248,4 +254,16 @@ class AiEngineConfigSyncTest {
map.put(key, value);
return map;
}
+
+ @Test
+ void startupPushSkippedInCloudMode() throws Exception {
+ applicationProperties
+ .getAiEngine()
+ .setMode(ApplicationProperties.AiEngine.AiEngineMode.CLOUD);
+
+ sync.pushConfigOnStartup();
+
+ // Stirling Cloud chooses its own models, and its gateway does not forward /api/v1/config.
+ verify(aiEngineClient, never()).post(eq("/api/v1/config"), anyString(), any());
+ }
}
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/service/AiEngineRouterTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/service/AiEngineRouterTest.java
new file mode 100644
index 0000000000..035c46852c
--- /dev/null
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/service/AiEngineRouterTest.java
@@ -0,0 +1,260 @@
+package stirling.software.proprietary.service;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+import java.util.Optional;
+
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
+import org.springframework.beans.factory.ObjectProvider;
+import org.springframework.web.server.ResponseStatusException;
+
+import stirling.software.common.model.ApplicationProperties;
+import stirling.software.common.model.ApplicationProperties.AiEngine.AiEngineMode;
+import stirling.software.proprietary.accountlink.AccountLinkProperties;
+import stirling.software.proprietary.accountlink.DeviceCredential;
+import stirling.software.proprietary.accountlink.DeviceCredentialStore;
+
+/** Where an AI call goes, and what it carries to be trusted there. */
+class AiEngineRouterTest {
+
+ private static ApplicationProperties props(AiEngineMode mode) {
+ ApplicationProperties props = new ApplicationProperties();
+ props.getAiEngine().setEnabled(true);
+ props.getAiEngine().setMode(mode);
+ props.getAiEngine().setUrl("http://stirling-engine:5001/");
+ return props;
+ }
+
+ @SuppressWarnings("unchecked")
+ private static <T> ObjectProvider<T> providing(T value) {
+ ObjectProvider<T> provider = mock(ObjectProvider.class);
+ when(provider.getIfAvailable()).thenReturn(value);
+ return provider;
+ }
+
+ private static DeviceCredentialStore linkedStore() {
+ DeviceCredential credential = new DeviceCredential();
+ credential.setDeviceId("dev-1");
+ credential.setDeviceSecret("sec-1");
+ DeviceCredentialStore store = mock(DeviceCredentialStore.class);
+ when(store.get()).thenReturn(Optional.of(credential));
+ return store;
+ }
+
+ private static AccountLinkProperties saasAt(String baseUrl) {
+ AccountLinkProperties linkProps = new AccountLinkProperties();
+ linkProps.setSaasBaseUrl(baseUrl);
+ return linkProps;
+ }
+
+ @Test
+ void selfHostedGoesToTheConfiguredUrlWithTheSharedSecret() {
+ AiEngineRouter router = AiEngineRouter.selfHosted(props(AiEngineMode.SELF_HOSTED), "shh");
+
+ AiEngineTarget target = router.resolve();
+
+ assertThat(target.cloud()).isFalse();
+ // The trailing slash in the configured URL must not survive into the request line.
+ assertThat(target.urlFor("/health")).isEqualTo("http://stirling-engine:5001/health");
+ assertThat(target.headers()).containsExactly(java.util.Map.entry("X-Engine-Auth", "shh"));
+ }
+
+ @Test
+ void theSelfHostedTargetIsTheConfiguredEngineEvenInCloudMode() {
+ // Stirling Cloud's gateway forwards to its own engine whatever the mode says.
+ AiEngineRouter router = AiEngineRouter.selfHosted(props(AiEngineMode.CLOUD), "shh");
+
+ AiEngineTarget target = router.selfHostedTarget();
+
+ assertThat(target.cloud()).isFalse();
+ assertThat(target.urlFor("/health")).isEqualTo("http://stirling-engine:5001/health");
+ assertThat(target.headers()).containsExactly(java.util.Map.entry("X-Engine-Auth", "shh"));
+ }
+
+ @Test
+ void selfHostedWithNoSecretSendsNoAuthHeader() {
+ AiEngineRouter router = AiEngineRouter.selfHosted(props(AiEngineMode.SELF_HOSTED), " ");
+
+ assertThat(router.resolve().headers()).isEmpty();
+ }
+
+ @Test
+ void cloudModeGoesToTheInstanceGatewayOnTheAccountLinkHostByDefault() {
+ AiEngineRouter router =
+ new AiEngineRouter(
+ props(AiEngineMode.CLOUD),
+ providing(linkedStore()),
+ providing(saasAt("https://stirling.com/app/")),
+ "shh");
+
+ AiEngineTarget target = router.resolve();
+
+ assertThat(target.cloud()).isTrue();
+ // No API host configured: the credential was issued by the deployment this server linked
+ // to, so that is where it goes. A fixed default sent staging servers' credentials to prod.
+ assertThat(target.urlFor("/api/v1/orchestrator"))
+ .isEqualTo("https://stirling.com/app/api/v1/instance/ai/api/v1/orchestrator");
+ // The engine shared secret is this server's, and means nothing to Stirling Cloud.
+ assertThat(target.headers())
+ .containsOnly(
+ java.util.Map.entry("X-Device-Id", "dev-1"),
+ java.util.Map.entry("X-Device-Secret", "sec-1"));
+ }
+
+ @Test
+ void cloudModeUsesTheConfiguredApiHostOverTheAccountLinkHost() {
+ ApplicationProperties cloud = props(AiEngineMode.CLOUD);
+ cloud.getAiEngine().setCloudBaseUrl("https://api.stirling.com/");
+ AiEngineRouter router =
+ new AiEngineRouter(
+ cloud,
+ providing(linkedStore()),
+ providing(saasAt("https://stirling.com/app")),
+ null);
+
+ assertThat(router.resolve().urlFor("/health"))
+ .isEqualTo("https://api.stirling.com/api/v1/instance/ai/health");
+ }
+
+ @Test
+ void aBlankApiHostFallsBackToTheAccountLinkHost() {
+ // One host serves both in a single-origin deployment.
+ ApplicationProperties cloud = props(AiEngineMode.CLOUD);
+ cloud.getAiEngine().setCloudBaseUrl(" ");
+ AiEngineRouter router =
+ new AiEngineRouter(
+ cloud,
+ providing(linkedStore()),
+ providing(saasAt("https://stirling.com/app")),
+ null);
+
+ assertThat(router.resolve().urlFor("/health"))
+ .isEqualTo("https://stirling.com/app/api/v1/instance/ai/health");
+ }
+
+ @Test
+ void theCloudHostIsExposedWithoutTheGatewayPathOnIt() {
+ // The public status endpoint sits outside the gateway, so the probe needs the bare host.
+ ApplicationProperties cloud = props(AiEngineMode.CLOUD);
+ cloud.getAiEngine().setCloudBaseUrl("https://api.stirling.com/");
+ AiEngineRouter router =
+ new AiEngineRouter(
+ cloud,
+ providing(linkedStore()),
+ providing(saasAt("https://stirling.com/app")),
+ null);
+
+ assertThat(router.cloudHost()).isEqualTo("https://api.stirling.com");
+ assertThat(router.resolve().baseUrl())
+ .isEqualTo("https://api.stirling.com/api/v1/instance/ai");
+ }
+
+ @ParameterizedTest
+ @ValueSource(
+ strings = {
+ "http://api.stirling.com",
+ "http://localhost.attacker.example",
+ "http://127.0.0.1.attacker.example",
+ "http://[email protected]",
+ "http://[::ffff:127.0.0.1]",
+ "https:///missing-host",
+ "https:opaque",
+ "api.stirling.com",
+ "//api.stirling.com",
+ "ftp://api.stirling.com",
+ "https://user:[email protected]",
+ "https://api.stirling.com?redirect=elsewhere",
+ "https://api.stirling.com#fragment",
+ "https://api.stirling.com:65536",
+ "https://api.stirling.com:0",
+ "https://bad host"
+ })
+ void unsafeCloudUrlsAreRejectedForBothConfigurationSources(String baseUrl) {
+ ApplicationProperties cloud = props(AiEngineMode.CLOUD);
+ AiEngineRouter router =
+ new AiEngineRouter(
+ cloud, providing(linkedStore()), providing(saasAt(baseUrl)), null);
+
+ cloud.getAiEngine().setCloudBaseUrl(baseUrl);
+ assertThatThrownBy(router::resolve)
+ .isInstanceOf(ResponseStatusException.class)
+ .hasMessageContaining("503")
+ .hasMessageContaining("HTTPS");
+ assertThatThrownBy(router::cloudHost).isInstanceOf(ResponseStatusException.class);
+
+ cloud.getAiEngine().setCloudBaseUrl("");
+ assertThatThrownBy(router::resolve).isInstanceOf(ResponseStatusException.class);
+ assertThatThrownBy(router::cloudHost).isInstanceOf(ResponseStatusException.class);
+ }
+
+ @ParameterizedTest
+ @ValueSource(
+ strings = {
+ "https://api.stirling.com",
+ "https://custom.example/app",
+ "HTTPS://api.stirling.com:443",
+ "http://localhost:8081",
+ "http://LOCALHOST:8081",
+ "http://127.0.0.1:8081",
+ "http://[::1]:8081"
+ })
+ void secureCloudAndExactLoopbackUrlsCanCarryTheDeviceCredential(String baseUrl) {
+ ApplicationProperties cloud = props(AiEngineMode.CLOUD);
+ cloud.getAiEngine().setCloudBaseUrl(baseUrl);
+ AiEngineRouter router =
+ new AiEngineRouter(cloud, providing(linkedStore()), providing(null), null);
+
+ assertThat(router.resolve().baseUrl()).isEqualTo(baseUrl + "/api/v1/instance/ai");
+ assertThat(router.resolve().headers()).containsEntry("X-Device-Secret", "sec-1");
+ assertThat(router.cloudHost()).isEqualTo(baseUrl);
+ }
+
+ @Test
+ void cloudModeWithoutALinkFailsLoudlyRatherThanCallingLocalhost() {
+ DeviceCredentialStore unlinked = mock(DeviceCredentialStore.class);
+ when(unlinked.get()).thenReturn(Optional.empty());
+ AiEngineRouter router =
+ new AiEngineRouter(
+ props(AiEngineMode.CLOUD),
+ providing(unlinked),
+ providing(saasAt("https://stirling.com/app")),
+ null);
+
+ assertThatThrownBy(router::resolve)
+ .isInstanceOf(ResponseStatusException.class)
+ .hasMessageContaining("not linked");
+ }
+
+ @Test
+ void cloudModeWithNoAccountLinkBeansFailsLoudly() {
+ AiEngineRouter router = AiEngineRouter.selfHosted(props(AiEngineMode.CLOUD), null);
+
+ assertThatThrownBy(router::resolve).isInstanceOf(ResponseStatusException.class);
+ }
+
+ @Test
+ void documentUploadIsAlwaysAllowedAgainstAnEngineTheCustomerRuns() {
+ ApplicationProperties selfHosted = props(AiEngineMode.SELF_HOSTED);
+ selfHosted.getAiEngine().setCloudDocumentIndexing(false);
+
+ assertThat(AiEngineRouter.selfHosted(selfHosted, null).documentIndexingAllowed()).isTrue();
+ }
+
+ @Test
+ void cloudDocumentUploadIsOffUntilAnAdminTurnsItOn() {
+ ApplicationProperties cloud = props(AiEngineMode.CLOUD);
+ AiEngineRouter router =
+ new AiEngineRouter(
+ cloud, providing(linkedStore()), providing(saasAt("https://x/app")), null);
+
+ assertThat(router.documentIndexingAllowed()).isFalse();
+
+ cloud.getAiEngine().setCloudDocumentIndexing(true);
+ assertThat(router.documentIndexingAllowed()).isTrue();
+ }
+}
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/service/CloudStatusProbeTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/service/CloudStatusProbeTest.java
new file mode 100644
index 0000000000..063756c923
--- /dev/null
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/service/CloudStatusProbeTest.java
@@ -0,0 +1,127 @@
+package stirling.software.proprietary.service;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import java.io.IOException;
+import java.net.InetSocketAddress;
+import java.util.concurrent.atomic.AtomicReference;
+
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
+
+import com.sun.net.httpserver.HttpServer;
+
+import stirling.software.common.model.ApplicationProperties;
+
+/** Whether Stirling Cloud is up, asked over a real socket rather than a mocked client. */
+class CloudStatusProbeTest {
+
+ private HttpServer server;
+ private final AtomicReference<String> lastPath = new AtomicReference<>();
+ private volatile int responseCode = 200;
+ private volatile String redirectTo;
+
+ @BeforeEach
+ void startHost() throws IOException {
+ server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
+ server.createContext(
+ "/",
+ exchange -> {
+ lastPath.set(exchange.getRequestURI().getPath());
+ if (redirectTo != null) {
+ exchange.getResponseHeaders().add("Location", redirectTo);
+ }
+ byte[] body = "{\"status\":\"UP\"}".getBytes();
+ exchange.sendResponseHeaders(responseCode, body.length);
+ exchange.getResponseBody().write(body);
+ exchange.close();
+ });
+ server.start();
+ }
+
+ @AfterEach
+ void stopHost() {
+ server.stop(0);
+ }
+
+ private String baseUrl() {
+ return "http://127.0.0.1:" + server.getAddress().getPort();
+ }
+
+ private CloudStatusProbe probe(String baseUrl) {
+ ApplicationProperties properties = new ApplicationProperties();
+ properties.getAiEngine().setCloudBaseUrl(baseUrl);
+ return new CloudStatusProbe(AiEngineRouter.selfHosted(properties, null));
+ }
+
+ @Test
+ void aHostThatAnswersIsUp() {
+ assertThat(probe(baseUrl()).isUp()).isTrue();
+ assertThat(lastPath.get()).isEqualTo("/api/v1/info/status");
+ }
+
+ @Test
+ void aTrailingSlashDoesNotDoubleUpInThePath() {
+ assertThat(probe(baseUrl() + "/").isUp()).isTrue();
+ assertThat(lastPath.get()).isEqualTo("/api/v1/info/status");
+ }
+
+ @Test
+ void aHostThatErrorsIsDown() {
+ responseCode = 503;
+ assertThat(probe(baseUrl()).isUp()).isFalse();
+ }
+
+ @Test
+ void nothingListeningIsDownRatherThanAThrow() {
+ // Port 1 is reserved and never serves; the probe must answer, not propagate.
+ assertThat(probe("http://127.0.0.1:1").isUp()).isFalse();
+ }
+
+ @Test
+ void noConfiguredHostIsDownAndIsNeverDialled() {
+ assertThat(probe(null).isUp()).isFalse();
+ assertThat(probe(" ").isUp()).isFalse();
+ assertThat(lastPath.get()).isNull();
+ }
+
+ @ParameterizedTest
+ @ValueSource(
+ strings = {
+ "http://169.254.169.254",
+ "http://localhost.attacker.example",
+ "https:///missing-host",
+ "file:///etc/passwd"
+ })
+ void unsafeConfiguredHostsAreDownWithoutThrowing(String baseUrl) {
+ assertThat(probe(baseUrl).isUp()).isFalse();
+ assertThat(lastPath.get()).isNull();
+ }
+
+ @Test
+ void aRedirectCannotSendTheProbeToAnotherDestination() throws IOException {
+ AtomicReference<String> redirectedPath = new AtomicReference<>();
+ HttpServer destination = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
+ destination.createContext(
+ "/",
+ exchange -> {
+ redirectedPath.set(exchange.getRequestURI().getPath());
+ exchange.sendResponseHeaders(200, -1);
+ exchange.close();
+ });
+ destination.start();
+ try {
+ redirectTo = "http://127.0.0.1:" + destination.getAddress().getPort() + "/private";
+ responseCode = 302;
+
+ assertThat(probe(baseUrl()).isUp()).isFalse();
+ assertThat(lastPath.get()).isEqualTo("/api/v1/info/status");
+ assertThat(redirectedPath.get()).isNull();
+ } finally {
+ destination.stop(0);
+ }
+ }
+}
diff --git a/app/saas/src/main/java/stirling/software/saas/accountlink/InstanceAiController.java b/app/saas/src/main/java/stirling/software/saas/accountlink/InstanceAiController.java
new file mode 100644
index 0000000000..dbe3725a77
--- /dev/null
+++ b/app/saas/src/main/java/stirling/software/saas/accountlink/InstanceAiController.java
@@ -0,0 +1,181 @@
+package stirling.software.saas.accountlink;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.nio.charset.StandardCharsets;
+
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
+import org.springframework.context.annotation.Profile;
+import org.springframework.http.HttpHeaders;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.MediaType;
+import org.springframework.http.ResponseEntity;
+import org.springframework.security.access.prepost.PreAuthorize;
+import org.springframework.security.core.Authentication;
+import org.springframework.web.bind.annotation.DeleteMapping;
+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.RequestHeader;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody;
+
+import io.swagger.v3.oas.annotations.Hidden;
+import io.swagger.v3.oas.annotations.tags.Tag;
+
+import jakarta.servlet.http.HttpServletRequest;
+
+import lombok.extern.slf4j.Slf4j;
+
+import stirling.software.saas.accountlink.InstanceAiGatewayService.EngineReply;
+import stirling.software.saas.payg.cap.RequiresFeature;
+import stirling.software.saas.payg.model.FeatureGate;
+
+/**
+ * The AI engine as a linked self-hosted server sees it. Mounted under {@code /api/v1/instance}, the
+ * only prefix the device credential authenticates on, so a leaked one reaches nothing user-facing.
+ */
+@Slf4j
+@RestController
+@RequestMapping(InstanceAiController.PREFIX)
+@Profile("saas")
+@ConditionalOnProperty(name = "stirling.billing.account-link.enabled", havingValue = "true")
+@Hidden
+@Tag(name = "Instance AI")
+// Same plan gate as SaaS AI. The charge interceptor skips routes without multipart input, so
+// InstanceAiUsageService stays the only meter.
+@RequiresFeature(FeatureGate.AI_SUPPORT)
+public class InstanceAiController {
+
+ static final String PREFIX = "/api/v1/instance/ai";
+
+ private final InstanceAiGatewayService gateway;
+ private final InstanceAiUsageService usageService;
+ private final boolean sharingEnabled;
+
+ public InstanceAiController(
+ InstanceAiGatewayService gateway,
+ InstanceAiUsageService usageService,
+ @Value("${stirling.cloud-ai.sharing-enabled:false}") boolean sharingEnabled) {
+ this.gateway = gateway;
+ this.usageService = usageService;
+ this.sharingEnabled = sharingEnabled;
+ }
+
+ /** Answers even with sharing off, so an instance can tell switched off from down. */
+ @GetMapping("/status")
+ @PreAuthorize("hasRole('LINKED_INSTANCE')")
+ public InstanceAiStatus status() {
+ return new InstanceAiStatus(sharingEnabled, sharingEnabled && gateway.engineReachable());
+ }
+
+ public record InstanceAiStatus(boolean sharingEnabled, boolean engineReachable) {}
+
+ @GetMapping("/**")
+ @PreAuthorize("hasRole('LINKED_INSTANCE')")
+ public ResponseEntity<StreamingResponseBody> get(
+ HttpServletRequest request,
+ Authentication auth,
+ @RequestHeader(value = "X-User-Id", required = false) String instanceUserId)
+ throws IOException, InterruptedException {
+ return proxy("GET", request, auth, instanceUserId, null);
+ }
+
+ @PostMapping("/**")
+ @PreAuthorize("hasRole('LINKED_INSTANCE')")
+ public ResponseEntity<StreamingResponseBody> post(
+ HttpServletRequest request,
+ Authentication auth,
+ @RequestHeader(value = "X-User-Id", required = false) String instanceUserId,
+ @RequestBody(required = false) String body)
+ throws IOException, InterruptedException {
+ return proxy("POST", request, auth, instanceUserId, body);
+ }
+
+ @DeleteMapping("/**")
+ @PreAuthorize("hasRole('LINKED_INSTANCE')")
+ public ResponseEntity<StreamingResponseBody> delete(
+ HttpServletRequest request,
+ Authentication auth,
+ @RequestHeader(value = "X-User-Id", required = false) String instanceUserId)
+ throws IOException, InterruptedException {
+ return proxy("DELETE", request, auth, instanceUserId, null);
+ }
+
+ // Declared as StreamingResponseBody because Spring picks the writer from the declared type;
+ // behind ResponseEntity<?> a streamed reply fell through to the converters and answered 500.
+ private ResponseEntity<StreamingResponseBody> proxy(
+ String method,
+ HttpServletRequest request,
+ Authentication auth,
+ String instanceUserId,
+ String body)
+ throws IOException, InterruptedException {
+ if (!(auth instanceof LinkedInstanceAuthenticationToken token)) {
+ // hasRole already guarantees this; never leak a non-instance principal into the owner.
+ return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
+ }
+ if (!sharingEnabled) {
+ byte[] message =
+ "Stirling Cloud AI sharing is not enabled on this deployment."
+ .getBytes(StandardCharsets.UTF_8);
+ return ResponseEntity.status(HttpStatus.SERVICE_UNAVAILABLE)
+ .contentType(MediaType.TEXT_PLAIN)
+ .body(out -> out.write(message));
+ }
+ String enginePath = enginePathOf(request);
+ EngineReply reply =
+ gateway.forward(
+ method,
+ enginePath,
+ request.getQueryString(),
+ body,
+ token.getInstanceId(),
+ instanceUserId);
+ // Billed on the status, before the body, so a client leaving mid-stream is still charged.
+ if (reply.status() < 400) {
+ recordCallQuietly(token, enginePath);
+ }
+ return ResponseEntity.status(reply.status())
+ .header(HttpHeaders.CONTENT_TYPE, reply.contentType())
+ .body(out -> copy(reply.body(), out));
+ }
+
+ // Flushed per chunk so orchestrator progress frames arrive as the engine emits them.
+ private static void copy(InputStream in, OutputStream out) throws IOException {
+ try (in) {
+ byte[] buffer = new byte[8192];
+ int read;
+ while ((read = in.read(buffer)) != -1) {
+ out.write(buffer, 0, read);
+ out.flush();
+ }
+ }
+ }
+
+ /** Never fails the call: the engine already did the work, so a lost row is a billing gap. */
+ private void recordCallQuietly(LinkedInstanceAuthenticationToken token, String enginePath) {
+ try {
+ usageService.recordCall(token.getTeamId(), token.getInstanceId(), enginePath);
+ } catch (RuntimeException e) {
+ log.warn(
+ "Cloud AI usage not recorded for instance {} on {}",
+ token.getInstanceId(),
+ enginePath,
+ e);
+ }
+ }
+
+ private static String enginePathOf(HttpServletRequest request) {
+ String uri = request.getRequestURI();
+ String context = request.getContextPath();
+ String path =
+ context != null && !context.isEmpty() && uri.startsWith(context)
+ ? uri.substring(context.length())
+ : uri;
+ return path.substring(PREFIX.length());
+ }
+}
diff --git a/app/saas/src/main/java/stirling/software/saas/accountlink/InstanceAiGatewayService.java b/app/saas/src/main/java/stirling/software/saas/accountlink/InstanceAiGatewayService.java
new file mode 100644
index 0000000000..22b6d382b9
--- /dev/null
+++ b/app/saas/src/main/java/stirling/software/saas/accountlink/InstanceAiGatewayService.java
@@ -0,0 +1,240 @@
+package stirling.software.saas.accountlink;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.URI;
+import java.net.http.HttpClient;
+import java.net.http.HttpRequest;
+import java.net.http.HttpResponse;
+import java.time.Duration;
+import java.time.Instant;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.regex.Pattern;
+
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
+import org.springframework.context.annotation.Profile;
+import org.springframework.http.HttpStatus;
+import org.springframework.stereotype.Service;
+import org.springframework.web.server.ResponseStatusException;
+
+import lombok.extern.slf4j.Slf4j;
+
+import stirling.software.common.model.ApplicationProperties;
+import stirling.software.proprietary.service.AiEngineRouter;
+import stirling.software.proprietary.service.AiEngineTarget;
+
+import tools.jackson.core.JacksonException;
+import tools.jackson.databind.JsonNode;
+import tools.jackson.databind.ObjectMapper;
+import tools.jackson.databind.node.ObjectNode;
+
+/**
+ * Forwards a linked instance's AI call to this deployment's engine as {@code instance:<id>:<user>}.
+ * The engine treats owners as opaque, so that prefix keeps tenants apart.
+ */
+@Slf4j
+@Service
+@Profile("saas")
+@ConditionalOnProperty(name = "stirling.billing.account-link.enabled", havingValue = "true")
+public class InstanceAiGatewayService {
+
+ /** OpenAPI extension the engine puts on each route a linked instance may call. */
+ static final String LINKED_INSTANCE_MARKER = "x-linked-instance";
+
+ private static final Duration ROUTES_TTL = Duration.ofMinutes(5);
+ private static final List<String> OWNER_FIELDS =
+ List.of("ownerId", "owner_id", "readPrincipals", "read_principals");
+ private static final ObjectMapper JSON = new ObjectMapper();
+
+ private final ApplicationProperties applicationProperties;
+ private final AiEngineRouter router;
+ private final HttpClient httpClient;
+ private volatile Routes routes = new Routes(List.of(), Instant.MIN);
+
+ @Autowired
+ public InstanceAiGatewayService(
+ ApplicationProperties applicationProperties, AiEngineRouter router) {
+ this(
+ applicationProperties,
+ router,
+ HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(10)).build());
+ }
+
+ InstanceAiGatewayService(
+ ApplicationProperties applicationProperties,
+ AiEngineRouter router,
+ HttpClient httpClient) {
+ this.applicationProperties = applicationProperties;
+ this.router = router;
+ this.httpClient = httpClient;
+ }
+
+ /** The owner the engine sees; the prefix comes from the credential, never the instance. */
+ public static String namespacedOwner(Long instanceId, String instanceUserId) {
+ String user =
+ instanceUserId == null || instanceUserId.isBlank() ? "anonymous" : instanceUserId;
+ return "instance:" + instanceId + ":" + user;
+ }
+
+ /** Whether the engine answers its health check: enough to tell switched off from broken. */
+ public boolean engineReachable() {
+ try {
+ HttpRequest request = engineRequest("/health", Duration.ofSeconds(5)).GET().build();
+ return httpClient.send(request, HttpResponse.BodyHandlers.discarding()).statusCode()
+ < 400;
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ return false;
+ } catch (IOException | RuntimeException e) {
+ log.debug("Cloud AI engine health probe failed", e);
+ return false;
+ }
+ }
+
+ /** Forwards one call as the instance's owner; 404 unless the engine marks the route. */
+ public EngineReply forward(
+ String method,
+ String path,
+ String query,
+ String body,
+ Long instanceId,
+ String instanceUserId)
+ throws IOException, InterruptedException {
+ if (currentRoutes().stream().noneMatch(route -> route.matches(method, path))) {
+ throw new ResponseStatusException(
+ HttpStatus.NOT_FOUND,
+ "Not an AI engine route this gateway forwards: " + method + " " + path);
+ }
+ String owner = namespacedOwner(instanceId, instanceUserId);
+ String target = path + (query == null || query.isBlank() ? "" : "?" + query);
+ // One long timeout for all calls: it only lasts until headers arrive, and the instance
+ // times each call itself.
+ Duration timeout =
+ Duration.ofSeconds(
+ applicationProperties.getAiEngine().getLongRunningTimeoutSeconds());
+ HttpRequest.Builder builder = engineRequest(target, timeout).header("X-User-Id", owner);
+ switch (method) {
+ case "POST" ->
+ builder.header("Content-Type", "application/json")
+ .POST(HttpRequest.BodyPublishers.ofString(stampOwner(body, owner)));
+ case "DELETE" -> builder.DELETE();
+ default -> builder.GET();
+ }
+ HttpResponse<InputStream> response =
+ httpClient.send(builder.build(), HttpResponse.BodyHandlers.ofInputStream());
+ log.debug(
+ "Cloud AI gateway forwarded {} {} for instance {} -> {}",
+ method,
+ path,
+ instanceId,
+ response.statusCode());
+ return new EngineReply(
+ response.statusCode(),
+ response.headers().firstValue("Content-Type").orElse("application/json"),
+ response.body());
+ }
+
+ /**
+ * Replaces any owner fields in a JSON body with {@code owner}. Document ingest stores under the
+ * body's owner, not {@code X-User-Id}, so a forged one could overwrite another tenant.
+ */
+ static String stampOwner(String body, String owner) {
+ if (body == null || body.isBlank()) {
+ return "{}";
+ }
+ JsonNode parsed;
+ try {
+ parsed = JSON.readTree(body);
+ } catch (JacksonException e) {
+ throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Malformed JSON body");
+ }
+ if (!(parsed instanceof ObjectNode node) || OWNER_FIELDS.stream().noneMatch(node::has)) {
+ return body;
+ }
+ node.remove(OWNER_FIELDS);
+ node.put("ownerId", owner);
+ node.putArray("readPrincipals").add(owner);
+ return JSON.writeValueAsString(node);
+ }
+
+ /** The marked operations in an engine OpenAPI document. */
+ static List<EngineRoute> parseRoutes(JsonNode openApi) {
+ List<EngineRoute> found = new ArrayList<>();
+ for (Map.Entry<String, JsonNode> path : openApi.path("paths").properties()) {
+ for (Map.Entry<String, JsonNode> operation : path.getValue().properties()) {
+ if (operation.getValue().path(LINKED_INSTANCE_MARKER).asBoolean(false)) {
+ found.add(EngineRoute.of(operation.getKey(), path.getKey()));
+ }
+ }
+ }
+ return List.copyOf(found);
+ }
+
+ // Unlocked on purpose: a slow engine would otherwise queue every call behind one fetch.
+ private List<EngineRoute> currentRoutes() throws IOException, InterruptedException {
+ Routes cached = routes;
+ if (cached.isFresh()) {
+ return cached.list();
+ }
+ try {
+ routes = new Routes(fetchRoutes(), Instant.now());
+ } catch (IOException | JacksonException e) {
+ if (cached.list().isEmpty()) {
+ throw e;
+ }
+ log.warn("Engine route refresh failed; keeping the previous list", e);
+ routes = new Routes(cached.list(), Instant.now());
+ }
+ return routes.list();
+ }
+
+ private List<EngineRoute> fetchRoutes() throws IOException, InterruptedException {
+ HttpRequest request = engineRequest("/openapi.json", Duration.ofSeconds(10)).GET().build();
+ HttpResponse<String> response =
+ httpClient.send(request, HttpResponse.BodyHandlers.ofString());
+ if (response.statusCode() != 200) {
+ throw new IOException("Engine OpenAPI document returned HTTP " + response.statusCode());
+ }
+ return parseRoutes(JSON.readTree(response.body()));
+ }
+
+ private HttpRequest.Builder engineRequest(String pathAndQuery, Duration timeout) {
+ AiEngineTarget engine = router.selfHostedTarget();
+ HttpRequest.Builder builder =
+ HttpRequest.newBuilder()
+ .uri(URI.create(engine.urlFor(pathAndQuery)))
+ .timeout(timeout);
+ engine.headers().forEach(builder::header);
+ return builder;
+ }
+
+ public record EngineReply(int status, String contentType, InputStream body) {}
+
+ /** A marked engine operation; each {@code {param}} matches one segment other than . or .. */
+ record EngineRoute(String method, Pattern path) {
+
+ static EngineRoute of(String method, String template) {
+ StringBuilder regex = new StringBuilder();
+ for (String part : template.split("(?=\\{)|(?<=\\})")) {
+ regex.append(
+ part.startsWith("{") ? "(?!\\.\\.?(?:/|$))[^/]+" : Pattern.quote(part));
+ }
+ return new EngineRoute(
+ method.toUpperCase(Locale.ROOT), Pattern.compile(regex.toString()));
+ }
+
+ boolean matches(String requestMethod, String requestPath) {
+ return method.equals(requestMethod) && path.matcher(requestPath).matches();
+ }
+ }
+
+ private record Routes(List<EngineRoute> list, Instant fetchedAt) {
+ boolean isFresh() {
+ return Instant.now().isBefore(fetchedAt.plus(ROUTES_TTL));
+ }
+ }
+}
diff --git a/app/saas/src/main/java/stirling/software/saas/accountlink/InstanceAiUsageService.java b/app/saas/src/main/java/stirling/software/saas/accountlink/InstanceAiUsageService.java
new file mode 100644
index 0000000000..547773496d
--- /dev/null
+++ b/app/saas/src/main/java/stirling/software/saas/accountlink/InstanceAiUsageService.java
@@ -0,0 +1,69 @@
+package stirling.software.saas.accountlink;
+
+import java.util.Set;
+
+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;
+
+import stirling.software.saas.payg.charge.ChargeContext;
+import stirling.software.saas.payg.charge.JobChargeService;
+import stirling.software.saas.payg.model.BillingCategory;
+import stirling.software.saas.payg.model.JobSource;
+import stirling.software.saas.payg.model.ProcessType;
+
+/**
+ * The only meter for a linked instance's cloud AI, since the instance skips its own for cloud work.
+ * Billed flat per call: the gateway never parses a page or byte count out of the body.
+ */
+@Slf4j
+@Service
+@Profile("saas")
+@ConditionalOnProperty(name = "stirling.billing.account-link.enabled", havingValue = "true")
+public class InstanceAiUsageService {
+
+ /** Bookkeeping routes that run no model, so cost nothing. */
+ private static final Set<String> FREE_PATHS =
+ Set.of("/health", "/api/v1/agents/capabilities", "/api/v1/documents/by-owner");
+
+ private final JobChargeService chargeService;
+ private final LinkedInstanceRepository linkedInstanceRepository;
+
+ public InstanceAiUsageService(
+ JobChargeService chargeService, LinkedInstanceRepository linkedInstanceRepository) {
+ this.chargeService = chargeService;
+ this.linkedInstanceRepository = linkedInstanceRepository;
+ }
+
+ @Transactional
+ public void recordCall(Long teamId, Long instanceId, String enginePath) {
+ if (teamId == null || instanceId == null || FREE_PATHS.contains(enginePath)) {
+ return;
+ }
+ Long actorUserId =
+ linkedInstanceRepository
+ .findById(instanceId)
+ .map(LinkedInstance::getCreatedByUserId)
+ .orElse(null);
+ if (actorUserId == null) {
+ // Same as the nightly sync: a charge with no actor cannot be attributed, so skip it.
+ log.warn(
+ "Cloud AI call for instance {} has no linking admin; not billing {}",
+ instanceId,
+ enginePath);
+ return;
+ }
+ chargeService.chargeStandalone(
+ new ChargeContext(
+ actorUserId,
+ teamId,
+ JobSource.LINKED_INSTANCE,
+ ProcessType.SINGLE_TOOL,
+ BillingCategory.AI,
+ null),
+ 1);
+ }
+}
diff --git a/app/saas/src/main/java/stirling/software/saas/payg/entitlement/EntitlementGuard.java b/app/saas/src/main/java/stirling/software/saas/payg/entitlement/EntitlementGuard.java
index d4be0aef56..2959a6e423 100644
--- a/app/saas/src/main/java/stirling/software/saas/payg/entitlement/EntitlementGuard.java
+++ b/app/saas/src/main/java/stirling/software/saas/payg/entitlement/EntitlementGuard.java
@@ -23,6 +23,7 @@ import org.springframework.web.servlet.HandlerInterceptor;
import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.MeterRegistry;
+import jakarta.servlet.DispatcherType;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
@@ -35,6 +36,7 @@ import stirling.software.proprietary.security.controller.api.UserController;
import stirling.software.proprietary.security.database.repository.UserRepository;
import stirling.software.proprietary.security.model.ApiKeyAuthenticationToken;
import stirling.software.proprietary.security.model.User;
+import stirling.software.saas.accountlink.LinkedInstanceAuthenticationToken;
import stirling.software.saas.payg.cap.AiToolRoutes;
import stirling.software.saas.payg.cap.RequiresFeature;
import stirling.software.saas.payg.model.FeatureGate;
@@ -126,6 +128,11 @@ public class EntitlementGuard implements HandlerInterceptor {
if (!(handler instanceof HandlerMethod hm)) {
return true;
}
+ // The REQUEST dispatch already decided. Security filters skip ASYNC dispatches, so the
+ // empty context here would 401 a streamed response that has already started.
+ if (request.getDispatcherType() == DispatcherType.ASYNC) {
+ return true;
+ }
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
boolean keyManagement =
PortalApiKeysController.class.isAssignableFrom(hm.getBeanType())
@@ -250,6 +257,10 @@ public class EntitlementGuard implements HandlerInterceptor {
}
private Long resolveTeamId(Authentication auth) {
+ // A linked instance has no Supabase id, so the user lookup below would fail open.
+ if (auth instanceof LinkedInstanceAuthenticationToken instance) {
+ return instance.getTeamId();
+ }
if (auth instanceof ApiKeyAuthenticationToken
&& auth.getPrincipal() instanceof User apiUser) {
return apiUser.getTeam() == null ? null : apiUser.getTeam().getId();
diff --git a/app/saas/src/main/java/stirling/software/saas/payg/filter/PaygChargeInterceptor.java b/app/saas/src/main/java/stirling/software/saas/payg/filter/PaygChargeInterceptor.java
index 3375d91a88..2ecc7baeb1 100644
--- a/app/saas/src/main/java/stirling/software/saas/payg/filter/PaygChargeInterceptor.java
+++ b/app/saas/src/main/java/stirling/software/saas/payg/filter/PaygChargeInterceptor.java
@@ -39,6 +39,7 @@ import stirling.software.common.util.TempFileManager;
import stirling.software.proprietary.security.database.repository.UserRepository;
import stirling.software.proprietary.security.model.ApiKeyAuthenticationToken;
import stirling.software.proprietary.security.model.User;
+import stirling.software.saas.accountlink.LinkedInstanceAuthenticationToken;
import stirling.software.saas.payg.cap.AiToolRoutes;
import stirling.software.saas.payg.cap.RequiresFeature;
import stirling.software.saas.payg.charge.ChargeContext;
@@ -510,6 +511,11 @@ public class PaygChargeInterceptor implements AsyncHandlerInterceptor {
if (auth instanceof ApiKeyAuthenticationToken && auth.getPrincipal() instanceof User u) {
return u;
}
+ // InstanceAiUsageService meters linked instances; their instance-id principal would only
+ // fail the UUID parse below and log a spurious error per call.
+ if (auth instanceof LinkedInstanceAuthenticationToken) {
+ return null;
+ }
try {
String supabaseId = AuthenticationUtils.extractSupabaseId(auth);
if (supabaseId == null) {
diff --git a/app/saas/src/main/resources/application-saas.properties b/app/saas/src/main/resources/application-saas.properties
index e3c32c429e..85745ff2e3 100644
--- a/app/saas/src/main/resources/application-saas.properties
+++ b/app/saas/src/main/resources/application-saas.properties
@@ -5,6 +5,8 @@
# SaaS AI backend is env-driven (reached via AiProxyController); never push settings-derived
# config to it, so pin the config-push off.
aiEngine.pushConfigToEngine=false
+# Lend this engine to linked self-hosted servers; it spends this cluster's inference budget.
+stirling.cloud-ai.sharing-enabled=false
# ---------- Datasource ----------
system.datasource.enableCustomDatabase=true
diff --git a/app/saas/src/test/java/stirling/software/saas/accountlink/CloudAiEndToEndTest.java b/app/saas/src/test/java/stirling/software/saas/accountlink/CloudAiEndToEndTest.java
new file mode 100644
index 0000000000..5c909d35a8
--- /dev/null
+++ b/app/saas/src/test/java/stirling/software/saas/accountlink/CloudAiEndToEndTest.java
@@ -0,0 +1,343 @@
+package stirling.software.saas.accountlink;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.OutputStream;
+import java.net.InetSocketAddress;
+import java.net.http.HttpClient;
+import java.nio.charset.StandardCharsets;
+import java.util.List;
+import java.util.Optional;
+import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.concurrent.atomic.AtomicReference;
+
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.springframework.beans.factory.ObjectProvider;
+import org.springframework.http.ResponseEntity;
+import org.springframework.mock.web.MockHttpServletRequest;
+import org.springframework.web.server.ResponseStatusException;
+import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody;
+
+import com.sun.net.httpserver.HttpExchange;
+import com.sun.net.httpserver.HttpServer;
+
+import stirling.software.common.model.ApplicationProperties;
+import stirling.software.common.model.ApplicationProperties.AiEngine.AiEngineMode;
+import stirling.software.proprietary.accountlink.AccountLinkProperties;
+import stirling.software.proprietary.accountlink.DeviceCredential;
+import stirling.software.proprietary.accountlink.DeviceCredentialStore;
+import stirling.software.proprietary.service.AiEngineClient;
+import stirling.software.proprietary.service.AiEngineRouter;
+
+/**
+ * A self-hosted server's {@link AiEngineClient} through {@link InstanceAiController} to a stub
+ * engine, over real sockets. The controller is called directly, as the credential filter would.
+ */
+class CloudAiEndToEndTest {
+
+ private record EngineCall(
+ String method, String path, String userId, String engineAuth, String body) {}
+
+ private static final String ENGINE_SECRET = "cloud-engine-secret";
+ private static final String DEVICE_ID = "device-abc";
+ private static final String DEVICE_SECRET = "device-secret-xyz";
+ private static final String OPEN_API =
+ """
+ {"paths": {
+ "/health": {"get": {"x-linked-instance": true}},
+ "/api/v1/orchestrator": {"post": {"x-linked-instance": true}},
+ "/api/v1/documents": {"post": {"x-linked-instance": true}},
+ "/api/v1/documents/by-owner": {"delete": {"x-linked-instance": true}},
+ "/api/v1/config": {"post": {}}
+ }}
+ """;
+
+ private HttpServer cloud;
+ private HttpServer engine;
+ private final List<EngineCall> engineCalls = new CopyOnWriteArrayList<>();
+ private final AtomicReference<Exception> cloudFailure = new AtomicReference<>();
+ private InstanceAiUsageService usageService;
+ private ApplicationProperties instanceProps;
+
+ @BeforeEach
+ void startServers() throws IOException {
+ engine = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
+ // Public, like the real engine's, and not an engine call worth recording.
+ engine.createContext("/openapi.json", exchange -> respond(exchange, 200, OPEN_API));
+ engine.createContext(
+ "/",
+ exchange -> {
+ engineCalls.add(
+ new EngineCall(
+ exchange.getRequestMethod(),
+ exchange.getRequestURI().getPath(),
+ exchange.getRequestHeaders().getFirst("X-User-Id"),
+ exchange.getRequestHeaders().getFirst("X-Engine-Auth"),
+ bodyOf(exchange)));
+ if (!ENGINE_SECRET.equals(
+ exchange.getRequestHeaders().getFirst("X-Engine-Auth"))) {
+ respond(exchange, 401, "{\"detail\":\"bad secret\"}");
+ return;
+ }
+ respond(
+ exchange,
+ 200,
+ "{\"status\":\"ok\",\"smartModel\":\"demo-smart\",\"fastModel\":\"demo-fast\"}");
+ });
+ engine.start();
+
+ ApplicationProperties cloudProps = new ApplicationProperties();
+ cloudProps.getAiEngine().setUrl("http://127.0.0.1:" + engine.getAddress().getPort());
+ cloudProps.getAiEngine().setLongRunningTimeoutSeconds(30);
+ InstanceAiGatewayService gateway =
+ new InstanceAiGatewayService(
+ cloudProps,
+ AiEngineRouter.selfHosted(cloudProps, ENGINE_SECRET),
+ HttpClient.newHttpClient());
+ usageService = mock(InstanceAiUsageService.class);
+ InstanceAiController controller = new InstanceAiController(gateway, usageService, true);
+
+ cloud = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
+ cloud.createContext(
+ "/api/v1/instance/ai",
+ exchange -> {
+ try {
+ // Stands in for the device-credential filter.
+ String deviceId = exchange.getRequestHeaders().getFirst("X-Device-Id");
+ String deviceSecret =
+ exchange.getRequestHeaders().getFirst("X-Device-Secret");
+ if (!DEVICE_ID.equals(deviceId) || !DEVICE_SECRET.equals(deviceSecret)) {
+ respond(exchange, 401, "{\"detail\":\"unknown device\"}");
+ return;
+ }
+ String path = exchange.getRequestURI().getPath();
+ if ("GET".equals(exchange.getRequestMethod())
+ && path.endsWith("/api/v1/instance/ai/status")) {
+ InstanceAiController.InstanceAiStatus body = controller.status();
+ respond(
+ exchange,
+ 200,
+ "{\"sharingEnabled\":"
+ + body.sharingEnabled()
+ + ",\"engineReachable\":"
+ + body.engineReachable()
+ + "}");
+ return;
+ }
+ MockHttpServletRequest request =
+ new MockHttpServletRequest(exchange.getRequestMethod(), path);
+ request.setQueryString(exchange.getRequestURI().getRawQuery());
+ LinkedInstanceAuthenticationToken auth =
+ new LinkedInstanceAuthenticationToken(42L, 99L);
+ String userId = exchange.getRequestHeaders().getFirst("X-User-Id");
+ ResponseEntity<StreamingResponseBody> reply =
+ switch (exchange.getRequestMethod()) {
+ case "GET" -> controller.get(request, auth, userId);
+ case "DELETE" -> controller.delete(request, auth, userId);
+ default ->
+ controller.post(
+ request, auth, userId, bodyOf(exchange));
+ };
+ ByteArrayOutputStream drained = new ByteArrayOutputStream();
+ if (reply.getBody() != null) {
+ reply.getBody().writeTo(drained);
+ }
+ respond(
+ exchange,
+ reply.getStatusCode().value(),
+ drained.toString(StandardCharsets.UTF_8));
+ } catch (ResponseStatusException e) {
+ respond(exchange, e.getStatusCode().value(), "{\"detail\":\"refused\"}");
+ } catch (Exception e) {
+ cloudFailure.set(e);
+ respond(exchange, 500, "{\"detail\":\"boom\"}");
+ }
+ });
+ cloud.start();
+
+ instanceProps = new ApplicationProperties();
+ instanceProps.getAiEngine().setEnabled(true);
+ instanceProps.getAiEngine().setMode(AiEngineMode.CLOUD);
+ instanceProps.getAiEngine().setTimeoutSeconds(10);
+ instanceProps.getAiEngine().setCloudBaseUrl(cloudUrl());
+ }
+
+ @AfterEach
+ void stopServers() {
+ engine.stop(0);
+ cloud.stop(0);
+ }
+
+ private String cloudUrl() {
+ return "http://127.0.0.1:" + cloud.getAddress().getPort();
+ }
+
+ private static String bodyOf(HttpExchange exchange) throws IOException {
+ return new String(exchange.getRequestBody().readAllBytes(), StandardCharsets.UTF_8);
+ }
+
+ private static void respond(HttpExchange exchange, int status, String body) throws IOException {
+ byte[] bytes = body.getBytes(StandardCharsets.UTF_8);
+ exchange.getResponseHeaders().add("Content-Type", "application/json");
+ exchange.sendResponseHeaders(status, bytes.length);
+ try (OutputStream out = exchange.getResponseBody()) {
+ out.write(bytes);
+ }
+ }
+
+ @SuppressWarnings("unchecked")
+ private static <T> ObjectProvider<T> providing(T value) {
+ ObjectProvider<T> provider = mock(ObjectProvider.class);
+ when(provider.getIfAvailable()).thenReturn(value);
+ return provider;
+ }
+
+ private AiEngineClient clientWith(DeviceCredentialStore store) {
+ AccountLinkProperties linkProps = new AccountLinkProperties();
+ linkProps.setSaasBaseUrl(cloudUrl());
+ AiEngineRouter router =
+ new AiEngineRouter(
+ instanceProps, providing(store), providing(linkProps), "local-secret");
+ return new AiEngineClient(instanceProps, HttpClient.newHttpClient(), router);
+ }
+
+ /** A self-hosted server's engine client, linked and pointed at the cloud under test. */
+ private AiEngineClient linkedInstanceClient() {
+ DeviceCredential credential = new DeviceCredential();
+ credential.setDeviceId(DEVICE_ID);
+ credential.setDeviceSecret(DEVICE_SECRET);
+ DeviceCredentialStore store = mock(DeviceCredentialStore.class);
+ when(store.get()).thenReturn(Optional.of(credential));
+ return clientWith(store);
+ }
+
+ @Test
+ void aLinkedInstancesAiCallReachesTheCloudEngineAndComesBack() throws Exception {
+ String body = linkedInstanceClient().get("/health", "alice");
+
+ assertThat(cloudFailure.get()).isNull();
+ assertThat(body).contains("demo-smart");
+ assertThat(engineCalls).hasSize(1);
+ assertThat(engineCalls.get(0).path()).isEqualTo("/health");
+ // The instance's own shared secret never leaves it; the cloud presents its own.
+ assertThat(engineCalls.get(0).engineAuth()).isEqualTo(ENGINE_SECRET);
+ }
+
+ @Test
+ void theEngineSeesAnOwnerNamespacedToTheCallingInstance() throws Exception {
+ linkedInstanceClient().post("/api/v1/orchestrator", "{}", "alice");
+
+ assertThat(cloudFailure.get()).isNull();
+ assertThat(engineCalls).hasSize(1);
+ assertThat(engineCalls.get(0).userId()).isEqualTo("instance:42:alice");
+ }
+
+ @Test
+ void successfulCloudWorkIsBilledOnceByTheCloud() throws Exception {
+ linkedInstanceClient().post("/api/v1/orchestrator", "{}", "alice");
+
+ verify(usageService).recordCall(99L, 42L, "/api/v1/orchestrator");
+ }
+
+ @Test
+ void healthChecksAreNotBilledAsReasoning() throws Exception {
+ linkedInstanceClient().get("/health", "alice");
+
+ // recordCall decides that /health is free; its own test covers that.
+ verify(usageService).recordCall(99L, 42L, "/health");
+ verify(usageService, never()).recordCall(any(), any(), eq("/api/v1/orchestrator"));
+ }
+
+ @Test
+ void anUnlinkedServerInCloudModeRefusesBeforeItCallsAnything() {
+ DeviceCredentialStore unlinked = mock(DeviceCredentialStore.class);
+ when(unlinked.get()).thenReturn(Optional.empty());
+
+ assertThatThrownBy(() -> clientWith(unlinked).get("/health", "alice"))
+ .isInstanceOf(ResponseStatusException.class)
+ .hasMessageContaining("not linked");
+ assertThat(engineCalls).isEmpty();
+ }
+
+ @Test
+ void documentUploadIsRefusedLocallyWhenCloudIndexingIsOff() {
+ assertThatThrownBy(() -> linkedInstanceClient().post("/api/v1/documents", "{}", "alice"))
+ .isInstanceOf(ResponseStatusException.class)
+ .hasMessageContaining("turned off");
+ assertThat(engineCalls).isEmpty();
+ }
+
+ @Test
+ void anUploadReachesTheEngineUnderTheInstanceOwnerOnceIndexingIsOn() throws Exception {
+ instanceProps.getAiEngine().setCloudDocumentIndexing(true);
+
+ linkedInstanceClient()
+ .post(
+ "/api/v1/documents",
+ "{\"documentId\":\"d1\",\"ownerId\":\"alice\",\"readPrincipals\":[\"alice\"]}",
+ "alice");
+
+ assertThat(cloudFailure.get()).isNull();
+ assertThat(engineCalls).hasSize(1);
+ assertThat(engineCalls.get(0).path()).isEqualTo("/api/v1/documents");
+ assertThat(engineCalls.get(0).body()).contains("\"ownerId\":\"instance:42:alice\"");
+ }
+
+ @Test
+ void selfHostedModeStillGoesStraightToTheLocalEngine() throws Exception {
+ instanceProps.getAiEngine().setMode(AiEngineMode.SELF_HOSTED);
+ instanceProps.getAiEngine().setUrl("http://127.0.0.1:" + engine.getAddress().getPort());
+ AiEngineClient client =
+ new AiEngineClient(
+ instanceProps,
+ HttpClient.newHttpClient(),
+ AiEngineRouter.selfHosted(instanceProps, ENGINE_SECRET));
+
+ client.get("/health", "alice");
+
+ assertThat(engineCalls).hasSize(1);
+ assertThat(engineCalls.get(0).userId()).isEqualTo("alice");
+ verify(usageService, never()).recordCall(any(), any(), any());
+ }
+
+ @Test
+ void aRouteTheEngineDoesNotMarkNeverReachesIt() {
+ // Config push would let one tenant repoint the models every tenant shares.
+ assertThatThrownBy(() -> linkedInstanceClient().post("/api/v1/config", "{}", null))
+ .isInstanceOf(ResponseStatusException.class)
+ .hasMessageContaining("404");
+ assertThat(engineCalls).isEmpty();
+ }
+
+ @Test
+ void theLogoutPurgeReachesTheCloudEngineInTheInstanceNamespace() throws Exception {
+ linkedInstanceClient().delete("/api/v1/documents/by-owner", "alice");
+
+ assertThat(cloudFailure.get()).isNull();
+ assertThat(engineCalls).hasSize(1);
+ EngineCall call = engineCalls.get(0);
+ assertThat(call.method()).isEqualTo("DELETE");
+ assertThat(call.path()).isEqualTo("/api/v1/documents/by-owner");
+ assertThat(call.userId()).isEqualTo("instance:42:alice");
+ }
+
+ @Test
+ void aLinkedInstanceCanAskWhetherTheCloudSharesItsAi() throws Exception {
+ String body = linkedInstanceClient().get("/status", "alice");
+
+ assertThat(body).contains("\"sharingEnabled\":true");
+ assertThat(body).contains("\"engineReachable\":true");
+ assertThat(cloudFailure.get()).isNull();
+ }
+}
diff --git a/app/saas/src/test/java/stirling/software/saas/accountlink/InstanceAiControllerDispatchTest.java b/app/saas/src/test/java/stirling/software/saas/accountlink/InstanceAiControllerDispatchTest.java
new file mode 100644
index 0000000000..08613f9b63
--- /dev/null
+++ b/app/saas/src/test/java/stirling/software/saas/accountlink/InstanceAiControllerDispatchTest.java
@@ -0,0 +1,181 @@
+package stirling.software.saas.accountlink;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.ArgumentMatchers.isNull;
+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 static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.asyncDispatch;
+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.request;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
+
+import java.io.ByteArrayInputStream;
+import java.nio.charset.StandardCharsets;
+
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.springframework.http.MediaType;
+import org.springframework.test.web.servlet.MockMvc;
+import org.springframework.test.web.servlet.MvcResult;
+import org.springframework.test.web.servlet.setup.MockMvcBuilders;
+
+import stirling.software.saas.accountlink.InstanceAiGatewayService.EngineReply;
+
+/**
+ * The gateway through Spring's own dispatch, which picks the response writer from the declared
+ * return type; calling the controller directly cannot catch a wrong choice there.
+ */
+class InstanceAiControllerDispatchTest {
+
+ private InstanceAiGatewayService gateway;
+ private InstanceAiUsageService usageService;
+ private MockMvc mvc;
+
+ @BeforeEach
+ void setUp() {
+ gateway = mock(InstanceAiGatewayService.class);
+ usageService = mock(InstanceAiUsageService.class);
+ mvc =
+ MockMvcBuilders.standaloneSetup(
+ new InstanceAiController(gateway, usageService, true))
+ .build();
+ }
+
+ private static LinkedInstanceAuthenticationToken instance() {
+ return new LinkedInstanceAuthenticationToken(42L, 99L);
+ }
+
+ private static EngineReply reply(int status, String contentType, String body) {
+ return new EngineReply(
+ status,
+ contentType,
+ new ByteArrayInputStream(body.getBytes(StandardCharsets.UTF_8)));
+ }
+
+ @Test
+ void theOrchestratorStreamReachesTheInstanceAsNdjson() throws Exception {
+ String frames = "{\"event\":\"progress\"}\n{\"event\":\"result\"}\n";
+ when(gateway.forward(
+ eq("POST"),
+ eq("/api/v1/orchestrator"),
+ isNull(),
+ anyString(),
+ eq(42L),
+ eq("alice")))
+ .thenReturn(reply(200, "application/x-ndjson", frames));
+
+ MvcResult started =
+ mvc.perform(
+ post("/api/v1/instance/ai/api/v1/orchestrator")
+ .principal(instance())
+ .header("X-User-Id", "alice")
+ .contentType(MediaType.APPLICATION_JSON)
+ .content("{}"))
+ .andExpect(request().asyncStarted())
+ .andReturn();
+
+ mvc.perform(asyncDispatch(started))
+ .andExpect(status().isOk())
+ .andExpect(content().contentType(MediaType.APPLICATION_NDJSON))
+ .andExpect(content().string(frames));
+
+ verify(usageService).recordCall(99L, 42L, "/api/v1/orchestrator");
+ }
+
+ @Test
+ void aJsonReplyIsPassedThroughAsJson() throws Exception {
+ when(gateway.forward(eq("GET"), eq("/health"), isNull(), isNull(), eq(42L), eq("alice")))
+ .thenReturn(reply(200, "application/json", "{\"status\":\"ok\"}"));
+
+ MvcResult started =
+ mvc.perform(
+ get("/api/v1/instance/ai/health")
+ .principal(instance())
+ .header("X-User-Id", "alice"))
+ .andExpect(request().asyncStarted())
+ .andReturn();
+
+ mvc.perform(asyncDispatch(started))
+ .andExpect(status().isOk())
+ .andExpect(content().contentType(MediaType.APPLICATION_JSON))
+ .andExpect(content().json("{\"status\":\"ok\"}"));
+ }
+
+ @Test
+ void anEngineErrorKeepsItsStatusAndIsNotBilled() throws Exception {
+ when(gateway.forward(
+ eq("POST"), eq("/api/v1/pdf/edit"), isNull(), anyString(), eq(42L), any()))
+ .thenReturn(reply(422, "application/json", "{\"detail\":\"bad plan\"}"));
+
+ MvcResult started =
+ mvc.perform(
+ post("/api/v1/instance/ai/api/v1/pdf/edit")
+ .principal(instance())
+ .contentType(MediaType.APPLICATION_JSON)
+ .content("{}"))
+ .andExpect(request().asyncStarted())
+ .andReturn();
+
+ mvc.perform(asyncDispatch(started))
+ .andExpect(status().isUnprocessableContent())
+ .andExpect(content().json("{\"detail\":\"bad plan\"}"));
+
+ verify(usageService, never()).recordCall(any(), any(), any());
+ }
+
+ @Test
+ void queryParametersReachTheGatewayWithThePath() throws Exception {
+ // The math auditor sends its tolerance as a query parameter; dropping it ran defaults.
+ when(gateway.forward(
+ eq("POST"),
+ eq("/api/v1/ai/math-auditor-agent/deliberate"),
+ eq("tolerance=0.01"),
+ anyString(),
+ eq(42L),
+ any()))
+ .thenReturn(reply(200, "application/json", "{\"verdict\":\"ok\"}"));
+
+ MvcResult started =
+ mvc.perform(
+ post("/api/v1/instance/ai/api/v1/ai/math-auditor-agent/deliberate?tolerance=0.01")
+ .principal(instance())
+ .contentType(MediaType.APPLICATION_JSON)
+ .content("{}"))
+ .andExpect(request().asyncStarted())
+ .andReturn();
+
+ mvc.perform(asyncDispatch(started))
+ .andExpect(status().isOk())
+ .andExpect(content().json("{\"verdict\":\"ok\"}"));
+
+ verify(usageService).recordCall(99L, 42L, "/api/v1/ai/math-auditor-agent/deliberate");
+ }
+
+ @Test
+ void sharingOffAnswersPlainlyWithoutDiallingTheEngine() throws Exception {
+ MockMvc off =
+ MockMvcBuilders.standaloneSetup(
+ new InstanceAiController(gateway, usageService, false))
+ .build();
+
+ MvcResult started =
+ off.perform(get("/api/v1/instance/ai/health").principal(instance()))
+ .andExpect(request().asyncStarted())
+ .andReturn();
+
+ MvcResult done =
+ off.perform(asyncDispatch(started))
+ .andExpect(status().isServiceUnavailable())
+ .andReturn();
+
+ assertThat(done.getResponse().getContentAsString()).contains("sharing is not enabled");
+ verify(gateway, never()).forward(any(), any(), any(), any(), any(), any());
+ }
+}
diff --git a/app/saas/src/test/java/stirling/software/saas/accountlink/InstanceAiGatewayServiceTest.java b/app/saas/src/test/java/stirling/software/saas/accountlink/InstanceAiGatewayServiceTest.java
new file mode 100644
index 0000000000..a7c0e11bfd
--- /dev/null
+++ b/app/saas/src/test/java/stirling/software/saas/accountlink/InstanceAiGatewayServiceTest.java
@@ -0,0 +1,310 @@
+package stirling.software.saas.accountlink;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.argThat;
+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.io.ByteArrayInputStream;
+import java.net.http.HttpClient;
+import java.net.http.HttpHeaders;
+import java.net.http.HttpRequest;
+import java.net.http.HttpResponse;
+import java.nio.ByteBuffer;
+import java.nio.charset.StandardCharsets;
+import java.time.Duration;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.Flow;
+import java.util.concurrent.TimeUnit;
+
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.CsvSource;
+import org.springframework.web.server.ResponseStatusException;
+
+import stirling.software.common.model.ApplicationProperties;
+import stirling.software.proprietary.service.AiEngineRouter;
+import stirling.software.saas.accountlink.InstanceAiGatewayService.EngineReply;
+import stirling.software.saas.accountlink.InstanceAiGatewayService.EngineRoute;
+
+import tools.jackson.databind.JsonNode;
+import tools.jackson.databind.ObjectMapper;
+
+/** What a linked instance's AI call becomes by the time the cloud engine sees it. */
+class InstanceAiGatewayServiceTest {
+
+ private static final ObjectMapper MAPPER = new ObjectMapper();
+
+ /** The engine's OpenAPI document, trimmed to a few marked and unmarked operations. */
+ private static final String OPEN_API =
+ """
+ {"paths": {
+ "/health": {"get": {"x-linked-instance": true}},
+ "/api/v1/orchestrator": {"post": {"x-linked-instance": true}},
+ "/api/v1/pdf/questions": {"post": {"x-linked-instance": true}},
+ "/api/v1/documents": {"post": {"x-linked-instance": true}},
+ "/api/v1/documents/by-owner": {"delete": {"x-linked-instance": true}},
+ "/api/v1/documents/by-id/{document_id}": {"delete": {}},
+ "/api/v1/ai/math-auditor-agent/deliberate": {"post": {"x-linked-instance": true}},
+ "/api/v1/config": {"post": {}, "parameters": []}
+ }}
+ """;
+
+ private HttpClient httpClient;
+ private InstanceAiGatewayService gateway;
+ private final List<HttpRequest> sent = new ArrayList<>();
+
+ @BeforeEach
+ @SuppressWarnings("unchecked")
+ void setUp() throws Exception {
+ ApplicationProperties props = new ApplicationProperties();
+ props.getAiEngine().setUrl("http://cloud-engine:5001/");
+ props.getAiEngine().setLongRunningTimeoutSeconds(600);
+ httpClient = mock(HttpClient.class);
+ gateway =
+ new InstanceAiGatewayService(
+ props, AiEngineRouter.selfHosted(props, "cloud-secret"), httpClient);
+
+ HttpResponse<String> openApi = mock(HttpResponse.class);
+ when(openApi.statusCode()).thenReturn(200);
+ when(openApi.body()).thenReturn(OPEN_API);
+ when(httpClient.send(any(), any(HttpResponse.BodyHandler.class)))
+ .thenAnswer(
+ invocation -> {
+ HttpRequest request = invocation.getArgument(0);
+ if (request.uri().getPath().equals("/openapi.json")) {
+ return openApi;
+ }
+ sent.add(request);
+ return engineReply();
+ });
+ }
+
+ @SuppressWarnings("unchecked")
+ private static HttpResponse<Object> engineReply() {
+ HttpResponse<Object> reply = mock(HttpResponse.class);
+ when(reply.statusCode()).thenReturn(200);
+ when(reply.headers())
+ .thenReturn(
+ HttpHeaders.of(
+ Map.of("Content-Type", List.of("application/x-ndjson")),
+ (name, value) -> true));
+ when(reply.body())
+ .thenReturn(
+ new ByteArrayInputStream(
+ "{\"status\":\"ok\"}".getBytes(StandardCharsets.UTF_8)));
+ return reply;
+ }
+
+ private HttpRequest lastSent() {
+ return sent.get(sent.size() - 1);
+ }
+
+ @Test
+ void theOwnerTheEngineSeesIsNamespacedByInstance() throws Exception {
+ gateway.forward("POST", "/api/v1/orchestrator", null, "{}", 7L, "admin");
+
+ assertThat(lastSent().headers().firstValue("X-User-Id")).contains("instance:7:admin");
+ }
+
+ @Test
+ void twoInstancesWithTheSameUsernameDoNotCollide() {
+ assertThat(InstanceAiGatewayService.namespacedOwner(1L, "admin"))
+ .isNotEqualTo(InstanceAiGatewayService.namespacedOwner(2L, "admin"));
+ }
+
+ @Test
+ void anInstanceCannotClaimAnotherTenantByForgingTheUserHeader() throws Exception {
+ gateway.forward("POST", "/api/v1/orchestrator", null, "{}", 7L, "instance:9:admin");
+
+ // The forged value only ever becomes a suffix inside the caller's own namespace.
+ assertThat(lastSent().headers().firstValue("X-User-Id"))
+ .contains("instance:7:instance:9:admin");
+ }
+
+ @Test
+ void aMissingUserHeaderStillLandsInsideTheInstanceNamespace() throws Exception {
+ gateway.forward("POST", "/api/v1/orchestrator", null, "{}", 7L, null);
+
+ assertThat(lastSent().headers().firstValue("X-User-Id")).contains("instance:7:anonymous");
+ }
+
+ @Test
+ void theEngineSecretIsAttachedAndTheBaseUrlIsNotDoubleSlashed() throws Exception {
+ gateway.forward("GET", "/health", null, null, 7L, "admin");
+
+ assertThat(lastSent().uri().toString()).isEqualTo("http://cloud-engine:5001/health");
+ assertThat(lastSent().headers().firstValue("X-Engine-Auth")).contains("cloud-secret");
+ }
+
+ @Test
+ void theQueryStringTravelsWithAnAllowedPath() throws Exception {
+ gateway.forward(
+ "POST",
+ "/api/v1/ai/math-auditor-agent/deliberate",
+ "tolerance=0.01",
+ "{}",
+ 7L,
+ "admin");
+
+ assertThat(lastSent().uri().toString())
+ .isEqualTo(
+ "http://cloud-engine:5001/api/v1/ai/math-auditor-agent/deliberate?tolerance=0.01");
+ }
+
+ @Test
+ void theReplyIsPassedBackWithItsContentType() throws Exception {
+ EngineReply reply = gateway.forward("GET", "/health", null, null, 7L, "admin");
+
+ assertThat(reply.status()).isEqualTo(200);
+ assertThat(reply.contentType()).isEqualTo("application/x-ndjson");
+ assertThat(new String(reply.body().readAllBytes(), StandardCharsets.UTF_8))
+ .isEqualTo("{\"status\":\"ok\"}");
+ }
+
+ @ParameterizedTest
+ @CsvSource({
+ // Would let an instance repoint the models Stirling Cloud runs for everyone.
+ "POST, /api/v1/config",
+ "DELETE, /api/v1/documents/by-id/abc",
+ "POST, /api/v1/admin/settings",
+ "POST, /../api/v1/config",
+ // A marked route is forwarded only for the method the engine marked.
+ "GET, /api/v1/orchestrator"
+ })
+ void operationsTheEngineDoesNotMarkAreRefused(String method, String path) {
+ assertThatThrownBy(() -> gateway.forward(method, path, null, "{}", 7L, "admin"))
+ .isInstanceOf(ResponseStatusException.class)
+ .hasMessageContaining("404");
+ assertThat(sent).isEmpty();
+ }
+
+ @Test
+ void theEngineRouteListIsFetchedOnceAndReused() throws Exception {
+ gateway.forward("GET", "/health", null, null, 7L, "admin");
+ gateway.forward("POST", "/api/v1/orchestrator", null, "{}", 7L, "admin");
+
+ verify(httpClient, times(1))
+ .send(
+ argThat(request -> request.uri().getPath().equals("/openapi.json")),
+ any(HttpResponse.BodyHandler.class));
+ }
+
+ @Test
+ void aTemplatedRouteMatchesExactlyOneRealSegment() {
+ EngineRoute route = EngineRoute.of("delete", "/api/v1/documents/by-id/{document_id}");
+
+ assertThat(route.matches("DELETE", "/api/v1/documents/by-id/abc")).isTrue();
+ assertThat(route.matches("DELETE", "/api/v1/documents/by-id/a/b")).isFalse();
+ assertThat(route.matches("DELETE", "/api/v1/documents/by-id/..")).isFalse();
+ assertThat(route.matches("GET", "/api/v1/documents/by-id/abc")).isFalse();
+ }
+
+ @Test
+ void onlyMarkedOperationsAreParsedFromTheOpenApiDocument() {
+ List<EngineRoute> routes = InstanceAiGatewayService.parseRoutes(MAPPER.readTree(OPEN_API));
+
+ assertThat(routes).hasSize(6);
+ assertThat(routes).noneMatch(route -> route.matches("POST", "/api/v1/config"));
+ }
+
+ @Test
+ void theLogoutPurgeIsForwardedAsADelete() throws Exception {
+ gateway.forward("DELETE", "/api/v1/documents/by-owner", null, null, 7L, "alice");
+
+ assertThat(lastSent().method()).isEqualTo("DELETE");
+ assertThat(lastSent().headers().firstValue("X-User-Id")).contains("instance:7:alice");
+ }
+
+ @Test
+ void everyCallGetsTheLongRunningTimeout() throws Exception {
+ gateway.forward("POST", "/api/v1/pdf/questions", null, "{}", 7L, "alice");
+
+ assertThat(lastSent().timeout()).contains(Duration.ofSeconds(600));
+ }
+
+ @Test
+ void aDocumentUploadIsReownedToTheInstanceRegardlessOfWhatItAsksFor() throws Exception {
+ // Ingest stores under the body's owner, so both spellings the engine accepts must lose.
+ String forged =
+ "{\"documentId\":\"d1\",\"ownerId\":\"instance:9:victim\","
+ + "\"read_principals\":[\"instance:9:victim\"],\"pageText\":\"hi\"}";
+
+ gateway.forward("POST", "/api/v1/documents", null, forged, 7L, "alice");
+
+ JsonNode body = MAPPER.readTree(bodyOf(lastSent()));
+ assertThat(body.get("ownerId").asText()).isEqualTo("instance:7:alice");
+ assertThat(body.get("readPrincipals")).hasSize(1);
+ assertThat(body.get("readPrincipals").get(0).asText()).isEqualTo("instance:7:alice");
+ assertThat(body.has("owner_id")).isFalse();
+ assertThat(body.has("read_principals")).isFalse();
+ assertThat(body.get("documentId").asText()).isEqualTo("d1");
+ assertThat(body.get("pageText").asText()).isEqualTo("hi");
+ }
+
+ @Test
+ void aBodyWithoutOwnerFieldsIsForwardedUntouched() throws Exception {
+ String question = "{\"documentId\":\"d1\",\"question\":\"what changed?\"}";
+
+ gateway.forward("POST", "/api/v1/pdf/questions", null, question, 7L, "alice");
+
+ assertThat(bodyOf(lastSent())).isEqualTo(question);
+ }
+
+ @Test
+ void anEmptyBodyIsSentAsAnEmptyObject() throws Exception {
+ gateway.forward("POST", "/api/v1/documents", null, null, 7L, "alice");
+
+ assertThat(bodyOf(lastSent())).isEqualTo("{}");
+ }
+
+ @Test
+ void aMalformedBodyIsRefusedRatherThanForwarded() {
+ assertThatThrownBy(
+ () ->
+ gateway.forward(
+ "POST", "/api/v1/documents", null, "not json", 7L, "a"))
+ .isInstanceOf(ResponseStatusException.class)
+ .hasMessageContaining("400");
+ assertThat(sent).isEmpty();
+ }
+
+ /** Drains a captured request's body publisher, which {@code ofString} emits synchronously. */
+ private static String bodyOf(HttpRequest request) throws InterruptedException {
+ Flow.Publisher<ByteBuffer> publisher = request.bodyPublisher().orElseThrow();
+ StringBuilder out = new StringBuilder();
+ CountDownLatch done = new CountDownLatch(1);
+ publisher.subscribe(
+ new Flow.Subscriber<>() {
+ @Override
+ public void onSubscribe(Flow.Subscription subscription) {
+ subscription.request(Long.MAX_VALUE);
+ }
+
+ @Override
+ public void onNext(ByteBuffer item) {
+ out.append(StandardCharsets.UTF_8.decode(item));
+ }
+
+ @Override
+ public void onError(Throwable throwable) {
+ done.countDown();
+ }
+
+ @Override
+ public void onComplete() {
+ done.countDown();
+ }
+ });
+ done.await(5, TimeUnit.SECONDS);
+ return out.toString();
+ }
+}
diff --git a/app/saas/src/test/java/stirling/software/saas/accountlink/InstanceAiSharingTest.java b/app/saas/src/test/java/stirling/software/saas/accountlink/InstanceAiSharingTest.java
new file mode 100644
index 0000000000..6f54066776
--- /dev/null
+++ b/app/saas/src/test/java/stirling/software/saas/accountlink/InstanceAiSharingTest.java
@@ -0,0 +1,163 @@
+package stirling.software.saas.accountlink;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.ArgumentMatchers.anyLong;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.Mockito.doThrow;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verifyNoInteractions;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.net.InetSocketAddress;
+import java.net.http.HttpClient;
+import java.nio.charset.StandardCharsets;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.ResponseEntity;
+import org.springframework.mock.web.MockHttpServletRequest;
+import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody;
+
+import com.sun.net.httpserver.HttpServer;
+
+import stirling.software.common.model.ApplicationProperties;
+import stirling.software.proprietary.service.AiEngineRouter;
+
+/** The sharing switch: off is not an outage, so status still answers while forwarding refuses. */
+class InstanceAiSharingTest {
+
+ private HttpServer engine;
+ private final AtomicInteger engineCalls = new AtomicInteger();
+ private InstanceAiUsageService usageService;
+
+ @BeforeEach
+ void startEngine() throws IOException {
+ engine = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
+ engine.createContext(
+ "/openapi.json",
+ exchange -> {
+ byte[] body =
+ ("{\"paths\": {\"/api/v1/agents/capabilities\":"
+ + " {\"get\": {\"x-linked-instance\": true}}}}")
+ .getBytes();
+ exchange.sendResponseHeaders(200, body.length);
+ exchange.getResponseBody().write(body);
+ exchange.close();
+ });
+ engine.createContext(
+ "/",
+ exchange -> {
+ engineCalls.incrementAndGet();
+ byte[] body = "{\"status\":\"ok\"}".getBytes();
+ exchange.sendResponseHeaders(200, body.length);
+ exchange.getResponseBody().write(body);
+ exchange.close();
+ });
+ engine.start();
+ usageService = mock(InstanceAiUsageService.class);
+ }
+
+ @AfterEach
+ void stopEngine() {
+ engine.stop(0);
+ }
+
+ private static InstanceAiGatewayService gatewayTo(String engineUrl) {
+ ApplicationProperties props = new ApplicationProperties();
+ props.getAiEngine().setUrl(engineUrl);
+ return new InstanceAiGatewayService(
+ props, AiEngineRouter.selfHosted(props, null), HttpClient.newHttpClient());
+ }
+
+ private InstanceAiController controller(boolean sharingEnabled) {
+ InstanceAiGatewayService gateway =
+ gatewayTo("http://127.0.0.1:" + engine.getAddress().getPort());
+ return new InstanceAiController(gateway, usageService, sharingEnabled);
+ }
+
+ private static MockHttpServletRequest capabilitiesRequest() {
+ MockHttpServletRequest request =
+ new MockHttpServletRequest("GET", "/api/v1/instance/ai/api/v1/agents/capabilities");
+ request.setRequestURI("/api/v1/instance/ai/api/v1/agents/capabilities");
+ return request;
+ }
+
+ private static LinkedInstanceAuthenticationToken instance() {
+ return new LinkedInstanceAuthenticationToken(42L, 99L);
+ }
+
+ /** Drains the streamed body the way Spring's writer would. */
+ private static String bodyText(ResponseEntity<StreamingResponseBody> reply) throws IOException {
+ ByteArrayOutputStream drained = new ByteArrayOutputStream();
+ if (reply.getBody() != null) {
+ reply.getBody().writeTo(drained);
+ }
+ return drained.toString(StandardCharsets.UTF_8);
+ }
+
+ @Test
+ void sharingOffRefusesBeforeTheEngineIsEverDialled() throws Exception {
+ ResponseEntity<StreamingResponseBody> reply =
+ controller(false).get(capabilitiesRequest(), instance(), "user-1");
+
+ assertThat(reply.getStatusCode()).isEqualTo(HttpStatus.SERVICE_UNAVAILABLE);
+ assertThat(bodyText(reply)).contains("sharing is not enabled");
+ // Gated before the engine: no cluster work and no charge.
+ assertThat(engineCalls.get()).isZero();
+ verifyNoInteractions(usageService);
+ }
+
+ @Test
+ void sharingOnForwardsAsBefore() throws Exception {
+ ResponseEntity<?> reply = controller(true).get(capabilitiesRequest(), instance(), "user-1");
+
+ assertThat(reply.getStatusCode().value()).isEqualTo(200);
+ assertThat(engineCalls.get()).isEqualTo(1);
+ }
+
+ @Test
+ void aMeteringFailureDoesNotFailWorkTheEngineAlreadyDid() throws Exception {
+ // The engine already answered, so a usage-store outage must not turn success into a 500.
+ doThrow(new RuntimeException("usage store unavailable"))
+ .when(usageService)
+ .recordCall(anyLong(), anyLong(), anyString());
+
+ ResponseEntity<?> reply = controller(true).get(capabilitiesRequest(), instance(), "user-1");
+
+ assertThat(reply.getStatusCode().value()).isEqualTo(200);
+ assertThat(engineCalls.get()).isEqualTo(1);
+ }
+
+ @Test
+ void statusAnswersEvenWhileSharingIsOff() {
+ InstanceAiController.InstanceAiStatus status = controller(false).status();
+
+ assertThat(status.sharingEnabled()).isFalse();
+ assertThat(status.engineReachable()).isFalse();
+ assertThat(engineCalls.get()).isZero();
+ }
+
+ @Test
+ void statusReportsTheEngineWhenSharingIsOn() {
+ InstanceAiController.InstanceAiStatus status = controller(true).status();
+
+ assertThat(status.sharingEnabled()).isTrue();
+ assertThat(status.engineReachable()).isTrue();
+ }
+
+ @Test
+ void statusReportsAnUnreachableEngineWithoutFailing() throws IOException {
+ engine.stop(0);
+ // Port 1 is reserved and never serves, so this is a real connection refusal.
+ InstanceAiController.InstanceAiStatus status =
+ new InstanceAiController(gatewayTo("http://127.0.0.1:1"), usageService, true)
+ .status();
+
+ assertThat(status.sharingEnabled()).isTrue();
+ assertThat(status.engineReachable()).isFalse();
+ }
+}
diff --git a/app/saas/src/test/java/stirling/software/saas/accountlink/InstanceAiUsageServiceTest.java b/app/saas/src/test/java/stirling/software/saas/accountlink/InstanceAiUsageServiceTest.java
new file mode 100644
index 0000000000..26ac85d695
--- /dev/null
+++ b/app/saas/src/test/java/stirling/software/saas/accountlink/InstanceAiUsageServiceTest.java
@@ -0,0 +1,53 @@
+package stirling.software.saas.accountlink;
+
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.verifyNoInteractions;
+import static org.mockito.Mockito.when;
+
+import java.util.Optional;
+
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
+
+import stirling.software.saas.payg.charge.ChargeContext;
+import stirling.software.saas.payg.charge.JobChargeService;
+import stirling.software.saas.payg.model.BillingCategory;
+import stirling.software.saas.payg.model.JobSource;
+import stirling.software.saas.payg.model.ProcessType;
+
+class InstanceAiUsageServiceTest {
+
+ private final JobChargeService charges = mock(JobChargeService.class);
+ private final LinkedInstanceRepository instances = mock(LinkedInstanceRepository.class);
+ private final InstanceAiUsageService usage = new InstanceAiUsageService(charges, instances);
+
+ @ParameterizedTest
+ @ValueSource(strings = {"/health", "/api/v1/agents/capabilities", "/api/v1/documents/by-owner"})
+ void healthAndLogoutCleanupNeverCharge(String path) {
+ usage.recordCall(99L, 42L, path);
+
+ verifyNoInteractions(charges, instances);
+ }
+
+ @Test
+ void reasoningChargesTheLinkedTeamOnce() {
+ LinkedInstance instance = new LinkedInstance();
+ instance.setCreatedByUserId(7L);
+ when(instances.findById(42L)).thenReturn(Optional.of(instance));
+
+ usage.recordCall(99L, 42L, "/api/v1/pdf/questions");
+
+ verify(charges)
+ .chargeStandalone(
+ new ChargeContext(
+ 7L,
+ 99L,
+ JobSource.LINKED_INSTANCE,
+ ProcessType.SINGLE_TOOL,
+ BillingCategory.AI,
+ null),
+ 1);
+ }
+}
diff --git a/app/saas/src/test/java/stirling/software/saas/payg/entitlement/EntitlementGuardTest.java b/app/saas/src/test/java/stirling/software/saas/payg/entitlement/EntitlementGuardTest.java
index 31024e5252..7e53f539e7 100644
--- a/app/saas/src/test/java/stirling/software/saas/payg/entitlement/EntitlementGuardTest.java
+++ b/app/saas/src/test/java/stirling/software/saas/payg/entitlement/EntitlementGuardTest.java
@@ -31,11 +31,14 @@ import org.springframework.web.method.HandlerMethod;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.simple.SimpleMeterRegistry;
+import jakarta.servlet.DispatcherType;
+
import stirling.software.common.annotations.AutoJobPostMapping;
import stirling.software.proprietary.model.Team;
import stirling.software.proprietary.security.database.repository.UserRepository;
import stirling.software.proprietary.security.model.ApiKeyAuthenticationToken;
import stirling.software.proprietary.security.model.User;
+import stirling.software.saas.accountlink.LinkedInstanceAuthenticationToken;
import stirling.software.saas.payg.cap.RequiresFeature;
import stirling.software.saas.payg.model.EntitlementState;
import stirling.software.saas.payg.model.FeatureGate;
@@ -175,6 +178,23 @@ class EntitlementGuardTest {
verify(entitlementService).getSnapshot(42L);
}
+ @Test
+ void asyncDispatch_isNotGuardedAgain() throws Exception {
+ // Security filters skip ASYNC dispatches, so re-gating would 401 a response already sent.
+ HandlerMethod hm = handlerFor("plainEndpoint");
+ MockHttpServletRequest req = new MockHttpServletRequest();
+ req.setRequestURI("/api/v1/ai/tools/math-auditor-agent");
+ req.setDispatcherType(DispatcherType.ASYNC);
+ MockHttpServletResponse res = new MockHttpServletResponse();
+
+ boolean proceed = guard.preHandle(req, res, hm);
+
+ assertThat(proceed).isTrue();
+ assertThat(res.getStatus()).isEqualTo(200);
+ assertThat(res.getContentAsString()).isEmpty();
+ Mockito.verifyNoInteractions(entitlementService, userRepository);
+ }
+
@Test
void aiToolRoute_anonymous_returns401WithAiCategory() throws Exception {
SecurityContextHolder.getContext()
@@ -447,6 +467,36 @@ class EntitlementGuardTest {
assertThat(body.get("missingGates").get(0).asText()).isEqualTo("AI_SUPPORT");
}
+ @Test
+ void linkedInstance_aiRouteDegraded_returns402() throws Exception {
+ // Its principal is an instance id, so a user lookup would fail open for an unentitled team.
+ SecurityContextHolder.getContext()
+ .setAuthentication(new LinkedInstanceAuthenticationToken(9L, 42L));
+ when(entitlementService.getSnapshot(42L)).thenReturn(degradedSnapshot());
+
+ MockHttpServletResponse res = new MockHttpServletResponse();
+ boolean proceed = guard.preHandle(new MockHttpServletRequest(), res, handlerFor("aiOnly"));
+
+ assertThat(proceed).isFalse();
+ assertThat(res.getStatus()).isEqualTo(402);
+ JsonNode body = json.readTree(res.getContentAsByteArray());
+ assertThat(body.get("missingGates").get(0).asText()).isEqualTo("AI_SUPPORT");
+ Mockito.verifyNoInteractions(userRepository);
+ }
+
+ @Test
+ void linkedInstance_aiRouteEntitled_passesThrough() throws Exception {
+ SecurityContextHolder.getContext()
+ .setAuthentication(new LinkedInstanceAuthenticationToken(9L, 42L));
+ when(entitlementService.getSnapshot(42L)).thenReturn(fullSnapshot());
+
+ MockHttpServletResponse res = new MockHttpServletResponse();
+ boolean proceed = guard.preHandle(new MockHttpServletRequest(), res, handlerFor("aiOnly"));
+
+ assertThat(proceed).isTrue();
+ assertThat(res.getStatus()).isEqualTo(200);
+ }
+
// ---------------------------------------------------------------------------------------
// API-key calls: billable, hard-stop when degraded (allowance/cap reached)
// ---------------------------------------------------------------------------------------
diff --git a/app/saas/src/test/java/stirling/software/saas/payg/filter/AiCloudDoubleChargeTest.java b/app/saas/src/test/java/stirling/software/saas/payg/filter/AiCloudDoubleChargeTest.java
new file mode 100644
index 0000000000..3af72b78ba
--- /dev/null
+++ b/app/saas/src/test/java/stirling/software/saas/payg/filter/AiCloudDoubleChargeTest.java
@@ -0,0 +1,84 @@
+package stirling.software.saas.payg.filter;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import java.util.stream.Stream;
+
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.springframework.mock.web.MockHttpServletRequest;
+
+import stirling.software.proprietary.accountlink.BillableOperationClassifier;
+import stirling.software.proprietary.billing.BillingCategory;
+import stirling.software.saas.payg.cap.AiToolRoutes;
+
+/**
+ * AI paths both the self-hosted and cloud meters classify as billable, where one action could debit
+ * the same wallet twice. Pinned so a prefix widened on either side fails here first.
+ */
+class AiCloudDoubleChargeTest {
+
+ /** {@code doubleCharges} = both meters bill it, so one action would cost two charges. */
+ private record AiPath(String name, String uri, boolean doubleCharges) {
+ @Override
+ public String toString() {
+ return name;
+ }
+ }
+
+ private static Stream<AiPath> aiPaths() {
+ return Stream.of(
+ // The document-tool namespace is the whole exposure.
+ new AiPath("pdf comment agent", "/api/v1/ai/tools/pdf-comment-agent", true),
+ new AiPath("math auditor", "/api/v1/ai/tools/math-auditor-agent", true),
+ // Reasoning and health routes are outside both billing classifiers.
+ new AiPath("orchestrate", "/api/v1/ai/orchestrate", false),
+ new AiPath("orchestrate stream", "/api/v1/ai/orchestrate/stream", false),
+ new AiPath("engine pdf edit", "/api/v1/ai/pdf/edit", false),
+ new AiPath("engine health", "/api/v1/ai/health", false),
+ new AiPath("engine status", "/api/v1/ai/status", false),
+ // Not AI at all; here so a prefix widened by accident fails loudly.
+ new AiPath("ordinary tool", "/api/v1/security/add-password", false));
+ }
+
+ @ParameterizedTest(name = "{0}")
+ @MethodSource("aiPaths")
+ void bothMetersAgreeOnWhichAiPathsWouldBeChargedTwice(AiPath path) {
+ MockHttpServletRequest request = new MockHttpServletRequest("POST", path.uri());
+ request.setRequestURI(path.uri());
+
+ // Self-hosted: an interactive call with no API key and no automation header.
+ BillingCategory selfHosted = BillableOperationClassifier.categorize(request, false);
+ boolean selfHostedBills = selfHosted == BillingCategory.AI;
+
+ // Cloud: the same request, as the charge interceptor and entitlement guard scope it.
+ boolean cloudBills = AiToolRoutes.matches(request);
+
+ assertThat(selfHostedBills)
+ .as("self-hosted meter bills %s as AI", path.uri())
+ .isEqualTo(path.doubleCharges());
+ assertThat(cloudBills)
+ .as("cloud meter bills %s as AI", path.uri())
+ .isEqualTo(path.doubleCharges());
+ assertThat(selfHostedBills && cloudBills)
+ .as("%s would be charged on both ledgers for one user action", path.uri())
+ .isEqualTo(path.doubleCharges());
+ }
+
+ /**
+ * The self-hosted classifier keys off the raw URI, so a deployment context path must not change
+ * the answer - otherwise the exposure would differ between a root and a sub-path install.
+ */
+ @ParameterizedTest(name = "{0}")
+ @MethodSource("aiPaths")
+ void aContextPathDoesNotChangeTheExposure(AiPath path) {
+ MockHttpServletRequest request =
+ new MockHttpServletRequest("POST", "/stirling" + path.uri());
+ request.setRequestURI("/stirling" + path.uri());
+ request.setContextPath("/stirling");
+
+ assertThat(BillableOperationClassifier.categorize(request, false) == BillingCategory.AI)
+ .as("self-hosted meter, behind a context path")
+ .isEqualTo(path.doubleCharges());
+ }
+}
diff --git a/app/saas/src/test/java/stirling/software/saas/payg/filter/PaygBillingParityTest.java b/app/saas/src/test/java/stirling/software/saas/payg/filter/PaygBillingParityTest.java
index ed93b5ea3a..99fbd7714a 100644
--- a/app/saas/src/test/java/stirling/software/saas/payg/filter/PaygBillingParityTest.java
+++ b/app/saas/src/test/java/stirling/software/saas/payg/filter/PaygBillingParityTest.java
@@ -30,6 +30,8 @@ import org.springframework.mock.web.MockMultipartHttpServletRequest;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
+import org.springframework.web.context.request.RequestContextHolder;
+import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.method.HandlerMethod;
import io.micrometer.core.instrument.simple.SimpleMeterRegistry;
@@ -46,6 +48,7 @@ import stirling.software.proprietary.accountlink.InstanceEntitlement;
import stirling.software.proprietary.accountlink.InstanceEntitlementGate;
import stirling.software.proprietary.accountlink.InstanceEntitlementInterceptor;
import stirling.software.proprietary.accountlink.UsageMeterService;
+import stirling.software.proprietary.billing.AiCallRecord;
import stirling.software.proprietary.billing.UnitCalcPolicy;
import stirling.software.proprietary.security.database.repository.UserRepository;
import stirling.software.proprietary.security.model.ApiKeyAuthenticationToken;
@@ -342,6 +345,13 @@ class PaygBillingParityTest {
}
MockHttpServletResponse resp = new MockHttpServletResponse();
interceptor.preHandle(req, resp, handler(op.handler()));
+ // The self-hosted meter bills AI only after an engine call, so record one like a real op.
+ RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(req));
+ try {
+ AiCallRecord.record(AiCallRecord.Where.LOCAL);
+ } finally {
+ RequestContextHolder.resetRequestAttributes();
+ }
interceptor.afterCompletion(req, resp, handler(op.handler()), null);
if ("BYPASSED".equals(op.expected())) {
diff --git a/engine/src/stirling/api/app.py b/engine/src/stirling/api/app.py
index a5f1cb716f..20298acda2 100644
--- a/engine/src/stirling/api/app.py
+++ b/engine/src/stirling/api/app.py
@@ -12,6 +12,7 @@ from pydantic_ai.models.instrumented import InstrumentationSettings
from stirling.api.bootstrap import apply_app_state, build_app_state
from stirling.api.dependencies import enforce_required_user_id
from stirling.api.engine_auth import EngineSharedSecretMiddleware
+from stirling.api.linked_instance import LINKED_INSTANCE
from stirling.api.middleware import UserIdMiddleware
from stirling.api.routes import (
agent_capabilities_router,
@@ -224,7 +225,7 @@ app.include_router(docparse_router, dependencies=_user_gate)
app.include_router(config_router)
[email protected]("/health", response_model=HealthResponse)
[email protected]("/health", response_model=HealthResponse, openapi_extra=LINKED_INSTANCE)
async def healthcheck(http_request: Request) -> HealthResponse:
# Report the LIVE config on app.state, not the boot-time env cache, so an admin
# "Test connection" shows the model actually in use after a push. Falls back to env.
diff --git a/engine/src/stirling/api/linked_instance.py b/engine/src/stirling/api/linked_instance.py
new file mode 100644
index 0000000000..6fef37837a
--- /dev/null
+++ b/engine/src/stirling/api/linked_instance.py
@@ -0,0 +1,8 @@
+"""OpenAPI marker for the routes a linked self-hosted server may call through Stirling Cloud."""
+
+from __future__ import annotations
+
+from typing import Any
+
+# Stirling Cloud's gateway reads this from /openapi.json and refuses every unmarked route.
+LINKED_INSTANCE: dict[str, Any] = {"x-linked-instance": True}
diff --git a/engine/src/stirling/api/routes/agent_capabilities.py b/engine/src/stirling/api/routes/agent_capabilities.py
index 75f1d0f823..e3e24348a8 100644
--- a/engine/src/stirling/api/routes/agent_capabilities.py
+++ b/engine/src/stirling/api/routes/agent_capabilities.py
@@ -7,11 +7,12 @@ from typing import Any
from fastapi import APIRouter
from stirling.api.agent_capabilities import manifest_payload
+from stirling.api.linked_instance import LINKED_INSTANCE
router = APIRouter(prefix="/api/v1/agents", tags=["agents"])
[email protected]("/capabilities")
[email protected]("/capabilities", openapi_extra=LINKED_INSTANCE)
def get_capabilities() -> dict[str, Any]:
"""Return the curated agent capabilities manifest.
diff --git a/engine/src/stirling/api/routes/agent_drafts.py b/engine/src/stirling/api/routes/agent_drafts.py
index f5cf003c41..43200815dc 100644
--- a/engine/src/stirling/api/routes/agent_drafts.py
+++ b/engine/src/stirling/api/routes/agent_drafts.py
@@ -6,6 +6,7 @@ from fastapi import APIRouter, Depends
from stirling.agents import UserSpecAgent
from stirling.api.dependencies import get_user_spec_agent
+from stirling.api.linked_instance import LINKED_INSTANCE
from stirling.contracts import (
AgentDraftRequest,
AgentDraftWorkflowResponse,
@@ -16,7 +17,7 @@ from stirling.contracts import (
router = APIRouter(prefix="/api/v1/agents", tags=["agents"])
[email protected]("/draft", response_model=AgentDraftWorkflowResponse)
[email protected]("/draft", response_model=AgentDraftWorkflowResponse, openapi_extra=LINKED_INSTANCE)
async def draft_agent(
request: AgentDraftRequest,
agent: Annotated[UserSpecAgent, Depends(get_user_spec_agent)],
@@ -24,7 +25,7 @@ async def draft_agent(
return await agent.draft(request)
[email protected]("/revise", response_model=AgentRevisionWorkflowResponse)
[email protected]("/revise", response_model=AgentRevisionWorkflowResponse, openapi_extra=LINKED_INSTANCE)
async def revise_agent(
request: AgentRevisionRequest,
agent: Annotated[UserSpecAgent, Depends(get_user_spec_agent)],
diff --git a/engine/src/stirling/api/routes/document_classifier.py b/engine/src/stirling/api/routes/document_classifier.py
index 649c0f4e9e..77f528d32b 100644
--- a/engine/src/stirling/api/routes/document_classifier.py
+++ b/engine/src/stirling/api/routes/document_classifier.py
@@ -6,12 +6,13 @@ from fastapi import APIRouter, Depends
from stirling.agents import DocumentClassifierAgent
from stirling.api.dependencies import get_document_classifier_agent
+from stirling.api.linked_instance import LINKED_INSTANCE
from stirling.contracts import ClassifyDocumentRequest, ClassifyDocumentResponse
router = APIRouter(prefix="/api/v1/documents/classify", tags=["document-classifier"])
[email protected]("", response_model=ClassifyDocumentResponse)
[email protected]("", response_model=ClassifyDocumentResponse, openapi_extra=LINKED_INSTANCE)
async def classify_document(
request: ClassifyDocumentRequest,
agent: Annotated[DocumentClassifierAgent, Depends(get_document_classifier_agent)],
diff --git a/engine/src/stirling/api/routes/documents.py b/engine/src/stirling/api/routes/documents.py
index a9c863d128..fda7dbf4ea 100644
--- a/engine/src/stirling/api/routes/documents.py
+++ b/engine/src/stirling/api/routes/documents.py
@@ -6,6 +6,7 @@ from typing import Annotated
from fastapi import APIRouter, Depends
from stirling.api.dependencies import get_document_service, require_user_id
+from stirling.api.linked_instance import LINKED_INSTANCE
from stirling.contracts import (
DeleteDocumentResponse,
IngestDocumentRequest,
@@ -19,7 +20,7 @@ router = APIRouter(prefix="/api/v1/documents", tags=["documents"])
logger = logging.getLogger(__name__)
[email protected]("", response_model=IngestDocumentResponse)
[email protected]("", response_model=IngestDocumentResponse, openapi_extra=LINKED_INSTANCE)
async def ingest_document(
request: IngestDocumentRequest,
documents: Annotated[DocumentService, Depends(get_document_service)],
@@ -66,7 +67,7 @@ async def delete_document(
return DeleteDocumentResponse(document_id=document_id, deleted=existed)
[email protected]("/by-owner", response_model=PurgeOwnerResponse)
[email protected]("/by-owner", response_model=PurgeOwnerResponse, openapi_extra=LINKED_INSTANCE)
async def purge_caller_documents(
documents: Annotated[DocumentService, Depends(get_document_service)],
user_id: Annotated[UserId, Depends(require_user_id)],
diff --git a/engine/src/stirling/api/routes/execution.py b/engine/src/stirling/api/routes/execution.py
index e7482326fb..d3b92d2946 100644
--- a/engine/src/stirling/api/routes/execution.py
+++ b/engine/src/stirling/api/routes/execution.py
@@ -6,12 +6,13 @@ from fastapi import APIRouter, Depends
from stirling.agents import ExecutionPlanningAgent
from stirling.api.dependencies import get_execution_planning_agent
+from stirling.api.linked_instance import LINKED_INSTANCE
from stirling.contracts import AgentExecutionRequest, NextExecutionAction
router = APIRouter(prefix="/api/v1/agents", tags=["agents"])
[email protected]("/next-action", response_model=NextExecutionAction)
[email protected]("/next-action", response_model=NextExecutionAction, openapi_extra=LINKED_INSTANCE)
async def next_action(
request: AgentExecutionRequest,
agent: Annotated[ExecutionPlanningAgent, Depends(get_execution_planning_agent)],
diff --git a/engine/src/stirling/api/routes/ledger.py b/engine/src/stirling/api/routes/ledger.py
index 82e220fbf6..5faf4bde11 100644
--- a/engine/src/stirling/api/routes/ledger.py
+++ b/engine/src/stirling/api/routes/ledger.py
@@ -22,6 +22,7 @@ from fastapi import APIRouter, Depends, HTTPException, Query
from stirling.agents.ledger import MathAuditorAgent
from stirling.api.dependencies import get_math_auditor_agent
+from stirling.api.linked_instance import LINKED_INSTANCE
from stirling.contracts.ledger import (
Evidence,
FolioManifest,
@@ -34,7 +35,7 @@ logger = logging.getLogger(__name__)
router = APIRouter(prefix="/api/v1/ai/math-auditor-agent", tags=["math-auditor-agent"])
[email protected]("/examine", response_model=Requisition)
[email protected]("/examine", response_model=Requisition, openapi_extra=LINKED_INSTANCE)
async def examine_endpoint(
manifest: FolioManifest,
agent: Annotated[MathAuditorAgent, Depends(get_math_auditor_agent)],
@@ -43,7 +44,7 @@ async def examine_endpoint(
return await agent.examine(manifest)
[email protected]("/deliberate", response_model=Verdict)
[email protected]("/deliberate", response_model=Verdict, openapi_extra=LINKED_INSTANCE)
async def deliberate_endpoint(
evidence: Evidence,
agent: Annotated[MathAuditorAgent, Depends(get_math_auditor_agent)],
diff --git a/engine/src/stirling/api/routes/orchestrator.py b/engine/src/stirling/api/routes/orchestrator.py
index b015c2bcf4..7f688db456 100644
--- a/engine/src/stirling/api/routes/orchestrator.py
+++ b/engine/src/stirling/api/routes/orchestrator.py
@@ -12,6 +12,7 @@ from fastapi.responses import StreamingResponse
from stirling.agents import OrchestratorAgent
from stirling.api.dependencies import get_orchestrator_agent
+from stirling.api.linked_instance import LINKED_INSTANCE
from stirling.contracts import OrchestratorRequest, OrchestratorResponse, ProgressEvent
from stirling.services import reset_progress_emitter, set_progress_emitter
@@ -26,7 +27,7 @@ HEARTBEAT_INTERVAL_SECONDS = 10.0
router = APIRouter(prefix="/api/v1/orchestrator", tags=["orchestrator"])
[email protected]("", openapi_extra=LINKED_INSTANCE)
async def orchestrate(
request: OrchestratorRequest,
agent: Annotated[OrchestratorAgent, Depends(get_orchestrator_agent)],
diff --git a/engine/src/stirling/api/routes/pdf_comments.py b/engine/src/stirling/api/routes/pdf_comments.py
index 45503f152a..2daf34bbc9 100644
--- a/engine/src/stirling/api/routes/pdf_comments.py
+++ b/engine/src/stirling/api/routes/pdf_comments.py
@@ -17,6 +17,7 @@ from fastapi import APIRouter, Depends
from stirling.agents.pdf_comment import PdfCommentAgent
from stirling.api.dependencies import get_pdf_comment_agent
+from stirling.api.linked_instance import LINKED_INSTANCE
from stirling.contracts.pdf_comments import PdfCommentRequest, PdfCommentResponse
logger = logging.getLogger(__name__)
@@ -24,7 +25,7 @@ logger = logging.getLogger(__name__)
router = APIRouter(prefix="/api/v1/ai/pdf-comment-agent", tags=["pdf-comment-agent"])
[email protected]("/generate", response_model=PdfCommentResponse)
[email protected]("/generate", response_model=PdfCommentResponse, openapi_extra=LINKED_INSTANCE)
async def generate_endpoint(
request: PdfCommentRequest,
agent: Annotated[PdfCommentAgent, Depends(get_pdf_comment_agent)],
diff --git a/engine/src/stirling/api/routes/pdf_edit.py b/engine/src/stirling/api/routes/pdf_edit.py
index 54601bb5ac..cc86266163 100644
--- a/engine/src/stirling/api/routes/pdf_edit.py
+++ b/engine/src/stirling/api/routes/pdf_edit.py
@@ -6,12 +6,13 @@ from fastapi import APIRouter, Depends
from stirling.agents import PdfEditAgent
from stirling.api.dependencies import get_pdf_edit_agent
+from stirling.api.linked_instance import LINKED_INSTANCE
from stirling.contracts import PdfEditRequest, PdfEditResponse
router = APIRouter(prefix="/api/v1/pdf/edit", tags=["pdf-edit"])
[email protected]("", response_model=PdfEditResponse)
[email protected]("", response_model=PdfEditResponse, openapi_extra=LINKED_INSTANCE)
async def pdf_edit(
request: PdfEditRequest,
agent: Annotated[PdfEditAgent, Depends(get_pdf_edit_agent)],
diff --git a/engine/src/stirling/api/routes/pdf_questions.py b/engine/src/stirling/api/routes/pdf_questions.py
index d875b838cf..405b941fa7 100644
--- a/engine/src/stirling/api/routes/pdf_questions.py
+++ b/engine/src/stirling/api/routes/pdf_questions.py
@@ -6,12 +6,13 @@ from fastapi import APIRouter, Depends
from stirling.agents import PdfQuestionAgent
from stirling.api.dependencies import get_pdf_question_agent
+from stirling.api.linked_instance import LINKED_INSTANCE
from stirling.contracts import PdfQuestionRequest, PdfQuestionResponse
router = APIRouter(prefix="/api/v1/pdf/questions", tags=["pdf-questions"])
[email protected]("", response_model=PdfQuestionResponse)
[email protected]("", response_model=PdfQuestionResponse, openapi_extra=LINKED_INSTANCE)
async def pdf_questions(
request: PdfQuestionRequest,
agent: Annotated[PdfQuestionAgent, Depends(get_pdf_question_agent)],
diff --git a/engine/tests/test_linked_instance_routes.py b/engine/tests/test_linked_instance_routes.py
new file mode 100644
index 0000000000..485b7a0f54
--- /dev/null
+++ b/engine/tests/test_linked_instance_routes.py
@@ -0,0 +1,42 @@
+"""Which engine routes Stirling Cloud's gateway may forward for a linked self-hosted server."""
+
+from __future__ import annotations
+
+from fastapi.routing import APIRoute
+
+from stirling.api import app
+from stirling.api.dependencies import enforce_required_user_id
+from stirling.api.linked_instance import LINKED_INSTANCE
+
+
+def _marked_routes() -> list[APIRoute]:
+ return [
+ route
+ for route in app.routes
+ if isinstance(route, APIRoute) and (route.openapi_extra or {}).items() >= LINKED_INSTANCE.items()
+ ]
+
+
+def test_marked_routes_are_published_in_openapi():
+ paths = app.openapi()["paths"]
+ routes = _marked_routes()
+ assert routes
+ for route in routes:
+ for method in route.methods or ():
+ assert paths[route.path][method.lower()]["x-linked-instance"] is True
+
+
+def test_config_push_is_never_forwarded():
+ # It would let one linked server repoint the models every tenant shares.
+ assert [route.path for route in _marked_routes() if route.path.startswith("/api/v1/config")] == []
+
+
+def test_every_marked_route_but_health_is_behind_the_user_gate():
+ # The gateway namespaces X-User-Id per instance, which only isolates routes that read it.
+ ungated = [
+ route.path
+ for route in _marked_routes()
+ if route.path != "/health"
+ and not any(dependency.dependency is enforce_required_user_id for dependency in route.dependencies)
+ ]
+ assert ungated == []