Skip to content

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

Let a linked self-hosted instance read its own SaaS data (#7798)

ConnorYoh64edee29d312
diff --git a/app/saas/src/main/java/stirling/software/saas/security/SupabaseSecurityConfig.java b/app/saas/src/main/java/stirling/software/saas/security/SupabaseSecurityConfig.java
index ea1c9bca9b..57e55beb00 100644
--- a/app/saas/src/main/java/stirling/software/saas/security/SupabaseSecurityConfig.java
+++ b/app/saas/src/main/java/stirling/software/saas/security/SupabaseSecurityConfig.java
@@ -85,6 +85,9 @@ public class SupabaseSecurityConfig {
@Value("${app.supabase.clock-skew-seconds:120}")
private long clockSkewSeconds;
+ @Value("${stirling.billing.account-link.enabled:false}")
+ private boolean accountLinkEnabled;
+
@Bean
SecurityFilterChain saasSecurityFilterChain(
HttpSecurity http,
@@ -288,6 +291,28 @@ public class SupabaseSecurityConfig {
private static final List<String> LOOPBACK_ANY_PORT =
List.of("http://localhost:[*]", "http://127.0.0.1:[*]");
+ /**
+ * The surface a linked self-hosted instance calls from its own browser with the signed-in
+ * admin's Supabase JWT, mirroring the frontend's {@code apiClient.saas}. Its origin is whatever
+ * the customer deployed on, so these cannot be served by an allow-list. See {@link
+ * #linkedInstanceCors()}.
+ *
+ * <p>Each hosts cloud-only endpoints, which is what makes a prefix safe here: billing,
+ * procurement, legal documents and the team's roster of linked instances have no self-hosted
+ * equivalent. Anything the instance also serves itself belongs on {@code apiClient.local}
+ * instead of here.
+ *
+ * <p>Only the {@code instances} half of account-link is listed. The {@code connect/*} handshake
+ * never reaches a browser on the customer's origin: the instance backend calls {@code request}
+ * and {@code claim} server-side, and the approval page is served by us.
+ */
+ private static final List<String> LINKED_INSTANCE_PATHS =
+ List.of(
+ "/api/v1/payg/**",
+ "/api/v1/procurement/**",
+ "/api/v1/legal/**",
+ "/api/v1/account-link/instances/**");
+
/**
* Profiles that mean "a developer's machine or a preview environment", never the production
* deployment. Production runs the bare {@code saas} profile.
@@ -375,10 +400,37 @@ public class SupabaseSecurityConfig {
cfg.setAllowCredentials(true);
cfg.setMaxAge(3600L);
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
+ // Registered ahead of "/**": the source returns the first pattern that matches, not the
+ // most specific one.
+ if (accountLinkEnabled) {
+ CorsConfiguration linked = linkedInstanceCors();
+ for (String path : LINKED_INSTANCE_PATHS) {
+ source.registerCorsConfiguration(path, linked);
+ }
+ }
source.registerCorsConfiguration("/**", cfg);
return source;
}
+ /**
+ * Any-origin CORS for the reads a linked self-hosted instance makes from its own browser, whose
+ * origin cannot be known in advance.
+ *
+ * <p>Safe only because it carries no credentials: this chain is bearer-token only and nothing
+ * in the SaaS module reads a cookie, so the browser attaches no ambient authority and a hostile
+ * page has nothing to ride on. The same reasoning already justifies disabling CSRF here.
+ * Authorisation is unchanged; this decides only who may read the response.
+ */
+ private static CorsConfiguration linkedInstanceCors() {
+ CorsConfiguration cfg = new CorsConfiguration();
+ cfg.setAllowedOrigins(List.of(CorsConfiguration.ALL));
+ cfg.setAllowedMethods(List.of("GET", "POST", "PATCH", "OPTIONS"));
+ cfg.setAllowedHeaders(List.of("Authorization", "Content-Type", "Accept"));
+ cfg.setAllowCredentials(false);
+ cfg.setMaxAge(3600L);
+ return cfg;
+ }
+
/**
* Maps Supabase JWT claims onto Spring Security authorities. Package-private static so unit
* tests can call it directly without instantiating the full security config.
diff --git a/app/saas/src/test/java/stirling/software/saas/security/SupabaseSecurityConfigMoreTest.java b/app/saas/src/test/java/stirling/software/saas/security/SupabaseSecurityConfigMoreTest.java
index 4727d78463..255e70c72d 100644
--- a/app/saas/src/test/java/stirling/software/saas/security/SupabaseSecurityConfigMoreTest.java
+++ b/app/saas/src/test/java/stirling/software/saas/security/SupabaseSecurityConfigMoreTest.java
@@ -12,10 +12,14 @@ import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.core.env.Environment;
+import org.springframework.http.HttpMethod;
import org.springframework.mock.env.MockEnvironment;
+import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.security.oauth2.jwt.JwtDecoder;
@@ -352,4 +356,86 @@ class SupabaseSecurityConfigMoreTest {
.contains("ROLE_LIMITED_API_USER");
}
}
+
+ @Nested
+ @DisplayName("linked-instance CORS")
+ class LinkedInstanceCors {
+
+ /** An origin no allow-list could ever contain: a customer's own deployment. */
+ private static final String SELF_HOSTED = "http://54.175.155.236:7779";
+
+ private CorsConfigurationSource source(boolean accountLinkEnabled) {
+ SupabaseSecurityConfig cfg = config(new ApplicationProperties());
+ ReflectionTestUtils.setField(cfg, "accountLinkEnabled", accountLinkEnabled);
+ return cfg.corsConfigurationSource();
+ }
+
+ private CorsConfiguration resolve(CorsConfigurationSource source, String path) {
+ return source.getCorsConfiguration(new MockHttpServletRequest("GET", path));
+ }
+
+ @ParameterizedTest
+ @ValueSource(
+ strings = {
+ "/api/v1/payg/wallet",
+ "/api/v1/payg/wallet/refresh",
+ "/api/v1/payg/invoices",
+ "/api/v1/payg/cap",
+ "/api/v1/procurement/quote",
+ "/api/v1/legal/consent",
+ // The Settings page's "who is linked" table, and its revoke button.
+ "/api/v1/account-link/instances",
+ "/api/v1/account-link/instances/42/revoke"
+ })
+ @DisplayName("every apiClient.saas path is readable from any origin")
+ void portalReadsAllowAnyOrigin(String path) {
+ CorsConfiguration cfg = resolve(source(true), path);
+
+ assertThat(cfg.checkOrigin(SELF_HOSTED)).isEqualTo("*");
+ // The wildcard is only defensible without credentials. These must never both be set:
+ // the browser rejects the pair outright, and it would be an open credentialed API.
+ assertThat(cfg.getAllowCredentials()).isNotEqualTo(Boolean.TRUE);
+ }
+
+ @Test
+ @DisplayName("PATCH is allowed; the cap endpoint needs it")
+ void patchAllowed() {
+ CorsConfiguration cfg = resolve(source(true), "/api/v1/payg/cap");
+
+ assertThat(cfg.checkHttpMethod(HttpMethod.PATCH)).isNotNull();
+ }
+
+ @ParameterizedTest
+ @ValueSource(
+ strings = {
+ "/api/v1/instance/sync",
+ // The instance serves its own audit trail and Documents feed, so the portal
+ // reads these from apiClient.local. They must never need cross-origin access.
+ "/api/v1/proprietary/ui-data/documents",
+ "/api/v1/proprietary/ui-data/audit-export",
+ "/api/v1/proprietary/ui-data/infrastructure/audit-log",
+ "/api/v1/proprietary/ui-data/admin-settings",
+ "/api/v1/proprietary/ui-data/database",
+ // The handshake is server-side plus our own approval page, never the
+ // customer's origin.
+ "/api/v1/account-link/connect/request",
+ "/api/v1/account-link/connect/claim"
+ })
+ @DisplayName("every other path keeps the credentialed allow-list")
+ void otherPathsUnchanged(String path) {
+ CorsConfiguration cfg = resolve(source(true), path);
+
+ assertThat(cfg.getAllowCredentials()).isTrue();
+ assertThat(cfg.checkOrigin(SELF_HOSTED)).isNull();
+ }
+
+ @Test
+ @DisplayName("no wildcard at all when account linking is off")
+ void flagOffKeepsAllowList() {
+ CorsConfiguration cfg = resolve(source(false), "/api/v1/payg/wallet");
+
+ assertThat(cfg.getAllowCredentials()).isTrue();
+ assertThat(cfg.checkOrigin(SELF_HOSTED)).isNull();
+ }
+ }
}
diff --git a/frontend/editor/src/portal/api/documents.ts b/frontend/editor/src/portal/api/documents.ts
index 6339f25222..3a3ce1aa03 100644
--- a/frontend/editor/src/portal/api/documents.ts
+++ b/frontend/editor/src/portal/api/documents.ts
@@ -123,10 +123,8 @@ export const DOC_AUDIT_TONE: Record<DocAuditKind, StatusTone> = {
elevation: "purple",
};
-/** GET the audit-derived Documents feed; SaaS or local, scoped server-side. `tier` ignored. */
+/** GET the audit-derived Documents feed, scoped server-side. `tier` ignored. */
export async function fetchDocuments(tier: Tier): Promise<DocumentsResponse> {
const path = `/api/v1/proprietary/ui-data/documents?tier=${encodeURIComponent(tier)}`;
- return apiClient.saas.isConfigured()
- ? apiClient.saas.json<DocumentsResponse>(path)
- : apiClient.local.json<DocumentsResponse>(path);
+ return apiClient.local.json<DocumentsResponse>(path);
}
diff --git a/frontend/editor/src/portal/api/http.ts b/frontend/editor/src/portal/api/http.ts
index 2ec00e9818..fb4f62cb8e 100644
--- a/frontend/editor/src/portal/api/http.ts
+++ b/frontend/editor/src/portal/api/http.ts
@@ -324,7 +324,5 @@ export const apiClient = {
json: saasJson,
text: saasText,
blob: saasBlob,
- /** True when a SaaS base URL is resolvable. Doesn't check session liveness. */
- isConfigured: (): boolean => saasBaseUrl() !== null,
},
} as const;
diff --git a/frontend/editor/src/portal/api/infrastructure.ts b/frontend/editor/src/portal/api/infrastructure.ts
index afd059a1ef..05fb5ad4eb 100644
--- a/frontend/editor/src/portal/api/infrastructure.ts
+++ b/frontend/editor/src/portal/api/infrastructure.ts
@@ -106,15 +106,13 @@ export async function revokeApiKey(id: string): Promise<void> {
await apiClient.local.json<void>(path, { method: "DELETE" });
}
-/** GET the audit log; SaaS or local, backend-scoped (admin → server, SaaS lead → team). */
+/** GET the audit log, backend-scoped (admin → server, SaaS lead → team). */
export async function fetchAuditLog(tier: Tier): Promise<AuditLogResponse> {
const path = `/api/v1/proprietary/ui-data/infrastructure/audit-log${q(tier)}`;
- return apiClient.saas.isConfigured()
- ? apiClient.saas.json<AuditLogResponse>(path)
- : apiClient.local.json<AuditLogResponse>(path);
+ return apiClient.local.json<AuditLogResponse>(path);
}
-/** Download the audit log as a CSV/JSON blob (admin-only, whole-server); SaaS or local. */
+/** Download the audit log as a CSV/JSON blob (admin-only, whole-server). */
export async function exportAuditLog(
format: "csv" | "json",
fields: string,
@@ -122,7 +120,5 @@ export async function exportAuditLog(
const path = `/api/v1/proprietary/ui-data/audit-export?format=${format}&fields=${encodeURIComponent(
fields,
)}`;
- return apiClient.saas.isConfigured()
- ? apiClient.saas.blob(path)
- : apiClient.local.blob(path);
+ return apiClient.local.blob(path);
}