Skip to content

The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:

fix(sdk): send CORS headers for error messages when embedding is disabled (#61808)

Phoomparin Manob46048533c39
diff --git a/e2e/test/scenarios/embedding-sdk/static-dashboard-cors.cy.spec.js b/e2e/test/scenarios/embedding-sdk/static-dashboard-cors.cy.spec.js
index 43a9a2818b5..6c532db9551 100644
--- a/e2e/test/scenarios/embedding-sdk/static-dashboard-cors.cy.spec.js
+++ b/e2e/test/scenarios/embedding-sdk/static-dashboard-cors.cy.spec.js
@@ -83,7 +83,7 @@ describe("scenarios > embedding-sdk > static-dashboard", () => {
getStorybookSdkRoot().within(() => {
cy.findByText(
- "Unable to connect to instance at http://localhost:4000",
+ "Embedding SDK for React is disabled. Enable it in the embedding settings.",
).should("be.visible");
});
});
diff --git a/e2e/test/scenarios/embedding/sdk-iframe-embedding/authentication.cy.spec.ts b/e2e/test/scenarios/embedding/sdk-iframe-embedding/authentication.cy.spec.ts
index 6872121caea..6bb5b5d2716 100644
--- a/e2e/test/scenarios/embedding/sdk-iframe-embedding/authentication.cy.spec.ts
+++ b/e2e/test/scenarios/embedding/sdk-iframe-embedding/authentication.cy.spec.ts
@@ -17,7 +17,7 @@ describe("scenarios > embedding > sdk iframe embedding > authentication", () =>
frame.within(() => {
cy.findByTestId("sdk-error-container")
.should("be.visible")
- .and("contain", "Backend returned an error when refreshing the token.");
+ .and("contain", "SSO has not been enabled and/or configured");
});
});
@@ -47,7 +47,7 @@ describe("scenarios > embedding > sdk iframe embedding > authentication", () =>
frame.within(() => {
cy.findByTestId("sdk-error-container")
.should("be.visible")
- .and("contain", "Backend returned an error when refreshing the token");
+ .and("contain", "SSO has not been enabled and/or configured");
});
});
@@ -192,11 +192,19 @@ describe("scenarios > embedding > sdk iframe embedding > authentication", () =>
});
cy.log("must fail to login via SAML as the SAML endpoint does not exist");
+
+ // If the error message returns a 500 (internal server error) status code,
+ // we should show a generic error message.
+ // This happens because the SAML endpoint is not mocked in this test.
cy.wait("@authSso").its("response.statusCode").should("eq", 500);
+
frame.within(() => {
cy.findByTestId("sdk-error-container")
.should("be.visible")
- .and("contain", "Backend returned an error when refreshing the token.");
+ .and(
+ "contain",
+ "Unable to connect to instance at http://localhost:4000 (status: 500)",
+ );
});
});
});
diff --git a/enterprise/backend/src/metabase_enterprise/sso/integrations/jwt.clj b/enterprise/backend/src/metabase_enterprise/sso/integrations/jwt.clj
index fb37e41ac24..ebb75e300e2 100644
--- a/enterprise/backend/src/metabase_enterprise/sso/integrations/jwt.clj
+++ b/enterprise/backend/src/metabase_enterprise/sso/integrations/jwt.clj
@@ -131,7 +131,7 @@
(defn- throw-simple-embedding-disabled
[]
(throw
- (ex-info (tru "Simple Embedding is disabled. Enable it in the embedding settings.")
+ (ex-info (tru "Embedded Analytics JS is disabled. Enable it in the embedding settings.")
{:status "error-embedding-simple-disabled"
:status-code 402})))
diff --git a/enterprise/frontend/src/embedding-sdk/errors/generic.ts b/enterprise/frontend/src/embedding-sdk/errors/generic.ts
index b51ee7c96fb..e3c1773a837 100644
--- a/enterprise/frontend/src/embedding-sdk/errors/generic.ts
+++ b/enterprise/frontend/src/embedding-sdk/errors/generic.ts
@@ -10,15 +10,22 @@ export function USER_FETCH_FAILED() {
export function CANNOT_CONNECT_TO_INSTANCE({
instanceUrl,
status,
+ message,
}: {
instanceUrl: string;
status?: number;
+ message?: string;
}) {
- return new MetabaseError(
- "CANNOT_CONNECT_TO_INSTANCE",
- `Unable to connect to instance at ${instanceUrl}${status ? ` (status: ${status})` : ""}`,
- { status },
- );
+ // If error status is 500 (internal server error) or no message is provided,
+ // we provide a generic error message.
+ const errorMessage =
+ !message || status === 500
+ ? `Unable to connect to instance at ${instanceUrl}${status ? ` (status: ${status})` : ""}`
+ : message;
+
+ return new MetabaseError("CANNOT_CONNECT_TO_INSTANCE", errorMessage, {
+ status,
+ });
}
export function INVALID_AUTH_METHOD({ method }: { method: string }) {
diff --git a/enterprise/frontend/src/embedding-sdk/errors/jwt.ts b/enterprise/frontend/src/embedding-sdk/errors/jwt.ts
index c490d3e88a5..91d0256b88a 100644
--- a/enterprise/frontend/src/embedding-sdk/errors/jwt.ts
+++ b/enterprise/frontend/src/embedding-sdk/errors/jwt.ts
@@ -26,11 +26,11 @@ export function REFRESH_TOKEN_BACKEND_ERROR(params: {
status?: string;
message?: string;
}) {
- return new MetabaseError(
- "BACKEND_ERROR_STATUS",
- `Backend returned an error when refreshing the token. Status: ${params.status ?? "unknown"}${params.message ? ", Message: " + params.message : ""}.`,
- params,
- );
+ const errorMessage =
+ params.message ||
+ `Backend returned an error when refreshing the token.${params.status ? ` Status: ${params.status}` : ""}`;
+
+ return new MetabaseError("BACKEND_ERROR_STATUS", errorMessage, params);
}
export function CUSTOM_FETCH_REQUEST_TOKEN_ERROR(params: {
diff --git a/enterprise/frontend/src/embedding/auth-common/connect-to-instance-auth-sso.ts b/enterprise/frontend/src/embedding/auth-common/connect-to-instance-auth-sso.ts
index d41c32fcf5c..cf0e7259a78 100644
--- a/enterprise/frontend/src/embedding/auth-common/connect-to-instance-auth-sso.ts
+++ b/enterprise/frontend/src/embedding/auth-common/connect-to-instance-auth-sso.ts
@@ -29,10 +29,18 @@ export async function connectToInstanceAuthSso(
try {
const urlResponse = await fetch(ssoUrl, { headers });
+
if (!urlResponse.ok) {
+ let errorData;
+
+ try {
+ errorData = await urlResponse.json();
+ } catch {}
+
throw MetabaseError.CANNOT_CONNECT_TO_INSTANCE({
instanceUrl: url,
status: urlResponse.status,
+ message: errorData?.message,
});
}
return await urlResponse.json();
diff --git a/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk/embed.ts b/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk/embed.ts
index 3251bd15442..84c6b5e5997 100644
--- a/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk/embed.ts
+++ b/enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk/embed.ts
@@ -383,8 +383,6 @@ class MetabaseEmbed {
error,
});
}
-
- throw error;
}
}
diff --git a/src/metabase/server/middleware/security.clj b/src/metabase/server/middleware/security.clj
index cdcbf78d57d..52a117e31c2 100644
--- a/src/metabase/server/middleware/security.clj
+++ b/src/metabase/server/middleware/security.clj
@@ -263,13 +263,26 @@
;; Tell browser not to use MIME sniffing to guess types of files -- protect against MIME type confusion attacks
"X-Content-Type-Options" "nosniff"}))
+(defn- always-allow-cors?
+ "Returns true if the request/response should have CORS headers added."
+ [request response]
+ ;; Needed for showing errors in the SDK when embedding or SSO is disabled.
+ (and (= (:uri request) "/auth/sso")
+ (or (= (:request-method request) :options)
+ (contains? #{400 402} (:status response)))))
+
(defn- add-security-headers* [request response]
;; merge is other way around so that handler can override headers
- (update response :headers #(merge %2 %1) (security-headers
- :origin (get (:headers request) "origin")
- :nonce (:nonce request)
- :allow-iframes? ((some-fn request/public? request/embed?) request)
- :allow-cache? (request/cacheable? request))))
+ (let [headers (security-headers
+ :origin (get (:headers request) "origin")
+ :nonce (:nonce request)
+ :allow-iframes? ((some-fn request/public? request/embed?) request)
+ :allow-cache? (request/cacheable? request))
+ cors-headers (when (always-allow-cors? request response)
+ {"Access-Control-Allow-Origin" "*"
+ "Access-Control-Allow-Headers" "*"
+ "Access-Control-Allow-Methods" "*"})]
+ (update response :headers #(merge %2 %1 cors-headers) headers)))
(defn add-security-headers
"Middleware that adds HTTP security and cache-busting headers."
diff --git a/src/metabase/server/routes.clj b/src/metabase/server/routes.clj
index 8d8795503f0..a7dc3e73ef8 100644
--- a/src/metabase/server/routes.clj
+++ b/src/metabase/server/routes.clj
@@ -82,6 +82,8 @@
;; ^/api/health -> Health Check Endpoint
(GET "/api/health" [] health-handler)
+ ;; Handle CORS preflight requests for auth routes
+ (OPTIONS "/auth/*" [] {:status 200 :body ""})
(OPTIONS "/api/*" [] {:status 200 :body ""})
;; ^/api/ -> All other API routes
diff --git a/test/metabase/server/middleware/security_test.clj b/test/metabase/server/middleware/security_test.clj
index d6d9ffa56e1..8c202fcf0f7 100644
--- a/test/metabase/server/middleware/security_test.clj
+++ b/test/metabase/server/middleware/security_test.clj
@@ -407,3 +407,67 @@
(respond {:status 200 :headers {"Response-Header" "ok"} :body "ok"})))
response (wrapped-handler {:headers {"origin" request-origin} :uri request-uri} identity identity)]
[enable-embedding-sdk embedding-app-origins-sdk request-origin request-uri (-> response :headers (get "Access-Control-Allow-Origin"))])))))
+
+(deftest ^:parallel add-cors-headers-for-auth-sso-test
+ (testing "Should add CORS headers for /auth/sso endpoint with 402 status (embedding disabled errors)"
+ (let [wrapped-handler (mw.security/add-security-headers
+ (fn [_request respond _raise]
+ (respond {:status 402
+ :headers {"Content-Type" "application/json"}
+ :body "{\"status\": \"error-embedding-sdk-disabled\"}"})))
+ response (wrapped-handler {:uri "/auth/sso" :headers {"origin" "https://example.com"}}
+ identity
+ identity)]
+ (is (= "*" (get-in response [:headers "Access-Control-Allow-Origin"]))
+ "Should set Access-Control-Allow-Origin to * for /auth/sso with 402 status")
+ (is (= "*" (get-in response [:headers "Access-Control-Allow-Headers"]))
+ "Should set Access-Control-Allow-Headers to * for /auth/sso with 402 status")
+ (is (= "*" (get-in response [:headers "Access-Control-Allow-Methods"]))
+ "Should set Access-Control-Allow-Methods to * for /auth/sso with 402 status")))
+
+ (testing "Should add CORS headers for /auth/sso endpoint with 400 status (client errors)"
+ (let [wrapped-handler (mw.security/add-security-headers
+ (fn [_request respond _raise]
+ (respond {:status 400
+ :headers {"Content-Type" "application/json"}
+ :body "{\"status\": \"error-sso-disabled\"}"})))
+ response (wrapped-handler {:uri "/auth/sso" :headers {"origin" "https://example.com"}}
+ identity
+ identity)]
+ (is (= "*" (get-in response [:headers "Access-Control-Allow-Origin"]))
+ "Should set Access-Control-Allow-Origin to * for /auth/sso with 400 status")
+ (is (= "*" (get-in response [:headers "Access-Control-Allow-Headers"]))
+ "Should set Access-Control-Allow-Headers to * for /auth/sso with 400 status")
+ (is (= "*" (get-in response [:headers "Access-Control-Allow-Methods"]))
+ "Should set Access-Control-Allow-Methods to * for /auth/sso with 400 status")))
+
+ (testing "Should add CORS headers for /auth/sso OPTIONS requests (preflight)"
+ (let [wrapped-handler (mw.security/add-security-headers
+ (fn [_request respond _raise]
+ (respond {:status 200
+ :headers {}
+ :body ""})))
+ response (wrapped-handler {:request-method :options
+ :uri "/auth/sso"
+ :headers {"origin" "https://example.com"}}
+ identity
+ identity)]
+ (is (= "*" (get-in response [:headers "Access-Control-Allow-Origin"]))
+ "Should set Access-Control-Allow-Origin to * for OPTIONS /auth/sso")
+ (is (= "*" (get-in response [:headers "Access-Control-Allow-Headers"]))
+ "Should set Access-Control-Allow-Headers to * for OPTIONS /auth/sso")
+ (is (= "*" (get-in response [:headers "Access-Control-Allow-Methods"]))
+ "Should set Access-Control-Allow-Methods to * for OPTIONS /auth/sso")))
+
+ (testing "Should not add CORS headers for /auth/sso endpoint with other status codes"
+ (doseq [status [200 201 500 503]]
+ (let [wrapped-handler (mw.security/add-security-headers
+ (fn [_request respond _raise]
+ (respond {:status status
+ :headers {"Content-Type" "application/json"}
+ :body "{\"status\": \"ok\"}"})))
+ response (wrapped-handler {:uri "/auth/sso" :headers {"origin" "https://example.com"}}
+ identity
+ identity)]
+ (is (nil? (get-in response [:headers "Access-Control-Allow-Origin"]))
+ (format "Should not set CORS headers for /auth/sso with %d status" status))))))