Skip to content

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

Store SAML relay state in db (#75887)

Nathan Voxland4b3ee24236c0
diff --git a/.clj-kondo/config/modules/config.edn b/.clj-kondo/config/modules/config.edn
index e68cfdd72b0..601f525b27c 100644
--- a/.clj-kondo/config/modules/config.edn
+++ b/.clj-kondo/config/modules/config.edn
@@ -3466,6 +3466,7 @@
settings
sso
system
+ task
util
enterprise/scim}
:model-imports #{:model/PermissionsGroup :model/Session}}
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 5974b8650be..2d874dff15f 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
@@ -443,7 +443,7 @@ describe("scenarios > embedding > sdk iframe embedding > authentication", () =>
signOut: true,
});
- const frame = H.loadSdkIframeEmbedTestPage({
+ H.loadSdkIframeEmbedTestPage({
elements: [
{
component: "metabase-dashboard",
@@ -455,22 +455,22 @@ describe("scenarios > embedding > sdk iframe embedding > authentication", () =>
metabaseConfig: {
preferredAuthMethod: "saml",
},
+ // Once SAML is chosen, the SDK opens the IdP AuthnRequest URL in a popup.
+ // The IdP isn't real here and we don't simulate the callback, so stub
+ // window.open to keep it from actually navigating — we only care that SAML
+ // (not JWT) was selected.
+ onVisitPage: () =>
+ cy.window().then((win) => {
+ cy.stub(win, "open").returns({ closed: false, close: () => {} });
+ }),
});
- 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",
- "Unable to connect to instance at http://localhost:4000 (status: 500)",
- );
+ // preferredAuthMethod: "saml" must route to the SAML initiate endpoint. It now
+ // returns a 200 with the AuthnRequest redirect (the RelayState is stored
+ // server-side and only a short key is sent to the IdP).
+ cy.wait("@authSso").then(({ response }) => {
+ expect(response?.statusCode).to.eq(200);
+ expect(response?.body?.method).to.eq("saml");
});
});
});
diff --git a/enterprise/backend/src/metabase_enterprise/serialization/v2/models.clj b/enterprise/backend/src/metabase_enterprise/serialization/v2/models.clj
index 638a068a410..17aa985bb26 100644
--- a/enterprise/backend/src/metabase_enterprise/serialization/v2/models.clj
+++ b/enterprise/backend/src/metabase_enterprise/serialization/v2/models.clj
@@ -141,6 +141,7 @@
"SourceMetricDaily"
"SourceSegmentCompositeDaily"
"SourceSegmentDaily"
+ "SsoRelayState"
"SupportAccessGrantLog"
"TableRemapping"
"TaskHistory"
diff --git a/enterprise/backend/src/metabase_enterprise/sso/init.clj b/enterprise/backend/src/metabase_enterprise/sso/init.clj
index 5335e09801f..b4504eff5f8 100644
--- a/enterprise/backend/src/metabase_enterprise/sso/init.clj
+++ b/enterprise/backend/src/metabase_enterprise/sso/init.clj
@@ -1,8 +1,10 @@
(ns metabase-enterprise.sso.init
(:require
[metabase-enterprise.sso.integrations.google] ; has a `define-multi-setting` impl
+ [metabase-enterprise.sso.models.relay-state]
[metabase-enterprise.sso.providers.jwt]
[metabase-enterprise.sso.providers.oidc]
[metabase-enterprise.sso.providers.saml]
[metabase-enterprise.sso.settings]
+ [metabase-enterprise.sso.task.delete-expired-relay-state]
[metabase.sso.providers.slack-connect]))
diff --git a/enterprise/backend/src/metabase_enterprise/sso/integrations/saml.clj b/enterprise/backend/src/metabase_enterprise/sso/integrations/saml.clj
index ccf3f01c1c5..9f38f5c20aa 100644
--- a/enterprise/backend/src/metabase_enterprise/sso/integrations/saml.clj
+++ b/enterprise/backend/src/metabase_enterprise/sso/integrations/saml.clj
@@ -35,6 +35,7 @@
[metabase-enterprise.sso.integrations.saml-utils :as saml-utils]
[metabase-enterprise.sso.integrations.sso-utils :as sso-utils]
[metabase-enterprise.sso.integrations.token-utils :as token-utils]
+ [metabase-enterprise.sso.models.relay-state :as relay-state]
[metabase-enterprise.sso.settings :as sso-settings]
[metabase.api.common :as api]
[metabase.auth-identity.core :as auth-identity]
@@ -75,33 +76,20 @@
(api/check (sso-settings/saml-enabled)
[400 (tru "SAML has not been enabled and/or configured")]))
-(defn construct-redirect-url
- "Constructs a redirect URL from request parameters.
- Parameters:
- - req: The request object containing params, headers, etc.
- Returns: The constructed redirect URL with appropriate query parameters"
- [req]
- (let [redirect (get-in req [:params :redirect])
- origin (get-in req [:headers "origin"])
- embedding-sdk-header? (embed.util/is-modular-embedding-request? req)]
+(defn- continue-url
+ "Where the user should end up after a successful login. For modular embedding this is the popup fallback
+ URL (used only when there is no opener window). Otherwise it comes from the `redirect` query param:
+ resolved against the site URL when relative, used as-is when absolute, or falling back to the site URL
+ (with a warning) when no `redirect` was provided."
+ [req embedding?]
+ (let [redirect (get-in req [:params :redirect])]
(cond
- ;; Case 1: Embedding SDK header is present - use ACS URL with token and origin
- embedding-sdk-header?
- (str (acs-url) "?token=" (token-utils/generate-token) "&origin=" (java.net.URLEncoder/encode ^String origin "UTF-8"))
-
- ;; Case 2: No redirect parameter
- (nil? redirect)
- (do
- (log/warn "Warning: expected `redirect` param, but none is present")
- (system/site-url))
-
- ;; Case 3: Redirect is a relative URI
- (sso-utils/relative-uri? redirect)
- (str (system/site-url) redirect)
-
- ;; Case 4: Redirect is an absolute URI
- :else
- redirect)))
+ embedding? (acs-url)
+ (nil? redirect) (do
+ (log/warn "Warning: expected `redirect` param, but none is present")
+ (system/site-url))
+ (sso-utils/relative-uri? redirect) (str (system/site-url) redirect)
+ :else redirect)))
(defmethod sso.i/sso-get :saml
;; Initial call that will result in a redirect to the IDP along with information about how the IDP can authenticate
@@ -109,62 +97,84 @@
[req]
(premium-features/assert-has-feature :sso-saml (tru "SAML-based authentication"))
(check-saml-enabled)
- (let [redirect (get-in req [:params :redirect])
- embedding-sdk-header? (embed.util/is-modular-embedding-request? req)
- redirect-url (construct-redirect-url req)]
+ (let [redirect (get-in req [:params :redirect])
+ embedding? (embed.util/is-modular-embedding-request? req)
+ continue (continue-url req embedding?)
+ ;; Generate the RelayState key up front (the AuthnRequest embeds it) but DON'T persist it yet — we
+ ;; only store the callback context once the AuthnRequest is successfully generated.
+ relay-key (relay-state/generate-key)]
+ ;; Validate the requested redirect before persisting it as the stored continue URL
(sso-utils/check-sso-redirect redirect)
;; Use provider/authenticate to generate SAML AuthnRequest
(let [auth-result (auth-identity/authenticate :provider/saml
- (assoc req :redirect-url redirect-url))]
+ (assoc req
+ :redirect-url continue
+ :relay-state relay-key))]
(cond
;; Need redirect to IdP
(= :redirect (:success? auth-result))
- (if embedding-sdk-header?
- {:status 200
- :body {:url (:redirect-url auth-result)
- :method "saml"}
- :headers {"Content-Type" "application/json"}}
- (response/redirect (:redirect-url auth-result)))
+ (do
+ (relay-state/persist! {:id relay-key
+ :continue-url continue
+ :origin (when embedding? (get-in req [:headers "origin"]))
+ :embedding? embedding?})
+ (if embedding?
+ {:status 200
+ :body {:url (:redirect-url auth-result)
+ :method "saml"}
+ :headers {"Content-Type" "application/json"}}
+ (response/redirect (:redirect-url auth-result))))
;; Error
:else
(throw (ex-info (or (:message auth-result) (trs "SAML request generation failed"))
{:status-code 500}))))))
-(defn- process-relay-state-params
- "Process the RelayState to extract continue URL and related parameters"
+(defn- legacy-token-relay-state
+ "Backwards compatibility: before the RelayState was stored server-side, the embedding flow Base64-encoded
+ a continue URL that carried `?token=<encrypted token>&origin=<origin>`. Logins started on an older version
+ may POST back to a newer one during an upgrade, so we still honor that format here. Returns an `:embedding`
+ (or `:expired`) result, mirroring [[process-relay-state]], or `nil` if `continue-url` carries no token."
+ [continue-url]
+ (when-let [token-value (and continue-url (second (re-find #"[?&]token=([^&]+)" continue-url)))]
+ (let [url-without-token (str/replace continue-url #"[?&]token=[^&]+(&|$)" "$1")
+ origin-param (second (re-find #"[?&]origin=([^&]+)" url-without-token))
+ origin (if origin-param
+ (try
+ (java.net.URLDecoder/decode ^String origin-param "UTF-8")
+ (catch Exception _
+ "*"))
+ "*")
+ clean-continue-url (if origin-param
+ (str/replace url-without-token #"[?&]origin=[^&]+(&|$)" "$1")
+ url-without-token)]
+ (if (token-utils/validate-token token-value)
+ {:mode :embedding, :continue-url clean-continue-url, :origin origin}
+ {:mode :expired}))))
+
+(defn- process-relay-state
+ "Resolve the RelayState returned by the IdP into the continue URL and (for embedding) the popup origin.
+
+ Returns a map with a `:mode`:
+ - `:embedding` - a modular-embedding popup login; `:continue-url` and `:origin` describe the callback.
+ - `:redirect` - a regular login; redirect to `:continue-url` with a session cookie.
+ - `:expired` - the login's proof (stored entry or legacy token) is missing, expired, or invalid."
[relay-state]
- (let [continue-url (u/ignore-exceptions
- (when-let [s (some-> relay-state u/decode-base64)]
- (when-not (str/blank? s)
- s)))
- ;; Extract token value from URL parameter
- token-value (when continue-url
- (second (re-find #"[?&]token=([^&]+)" continue-url)))
- ;; Check if token is valid using token-utils
- token-valid? (when token-value
- (token-utils/validate-token token-value))
- ;; Remove token parameter
- url-without-token (when continue-url
- (str/replace continue-url #"[?&]token=[^&]+(&|$)" "$1"))
- ;; Extract origin parameter
- origin-param (when url-without-token
- (second (re-find #"[?&]origin=([^&]+)" url-without-token)))
- origin (if origin-param
- (try
- (java.net.URLDecoder/decode ^String origin-param "UTF-8")
- (catch Exception _
- "*"))
- "*")
- ;; Remove origin parameter
- clean-continue-url (if (and url-without-token origin-param)
- (str/replace url-without-token #"[?&]origin=[^&]+(&|$)" "$1")
- url-without-token)]
- {:continue-url continue-url
- :token-value token-value
- :token-valid? token-valid?
- :clean-continue-url clean-continue-url
- :origin origin}))
+ (cond
+ (relay-state/relay-state-key? relay-state)
+ (if-let [{:keys [continue_url origin embedding]} (relay-state/find-unexpired relay-state)]
+ (if embedding
+ {:mode :embedding, :continue-url continue_url, :origin (or origin "*"), :relay-key relay-state}
+ {:mode :redirect, :continue-url continue_url, :relay-key relay-state})
+ {:mode :expired})
+
+ :else
+ (let [continue-url (u/ignore-exceptions
+ (when-let [s (some-> relay-state u/decode-base64)]
+ (when-not (str/blank? s)
+ s)))]
+ (or (legacy-token-relay-state continue-url)
+ {:mode :redirect, :continue-url continue-url}))))
(defmethod sso.i/sso-post :saml
;; Does the verification of the IDP's response and 'logs the user in'. The attributes are available in the response:
@@ -172,10 +182,10 @@
[{:keys [params], :as request}]
(premium-features/assert-has-feature :sso-saml (tru "SAML-based authentication"))
(check-saml-enabled)
- ;; Process continue URL and extract needed parameters
- (let [{:keys [continue-url token-value token-valid? clean-continue-url origin]} (process-relay-state-params (:RelayState params))]
- ;; Check if token is present but not valid
- (when (and token-value (not token-valid?))
+ ;; Resolve the RelayState into a continue URL (and popup origin for embedding)
+ (let [{:keys [mode continue-url origin relay-key]} (process-relay-state (:RelayState params))]
+ ;; A login whose RelayState entry is gone (expired, already used, or an invalid legacy token) can't be trusted
+ (when (= mode :expired)
(throw (ex-info (tru "Invalid authentication token")
{:status-code 401})))
(sso-utils/check-sso-redirect continue-url)
@@ -188,12 +198,16 @@
(cond
;; Login succeeded
(:success? login-result)
- (if token-value
- (saml-utils/create-token-response (:session login-result) origin clean-continue-url (:nonce request))
- (request/set-session-cookies request
- (response/redirect (:redirect-url login-result))
- (:session login-result)
- (t/zoned-date-time (t/zone-id "GMT"))))
+ (do
+ ;; Consume the single-use key only now that login succeeded — a failed or retried callback keeps
+ ;; the key alive so the user can complete login. (Legacy Base64 logins have no `:relay-key`.)
+ (when relay-key (relay-state/delete! relay-key))
+ (if (= mode :embedding)
+ (saml-utils/create-token-response (:session login-result) origin continue-url (:nonce request))
+ (request/set-session-cookies request
+ (response/redirect (:redirect-url login-result))
+ (:session login-result)
+ (t/zoned-date-time (t/zone-id "GMT")))))
;; Login failed
:else
diff --git a/enterprise/backend/src/metabase_enterprise/sso/models/relay_state.clj b/enterprise/backend/src/metabase_enterprise/sso/models/relay_state.clj
new file mode 100644
index 00000000000..85800660680
--- /dev/null
+++ b/enterprise/backend/src/metabase_enterprise/sso/models/relay_state.clj
@@ -0,0 +1,91 @@
+(ns metabase-enterprise.sso.models.relay-state
+ "Server-side store for the SAML SSO `RelayState` context.
+ The key itself is the single-use, expiring proof that the callback belongs to a login we started, so no
+ separate token is needed. Like session keys, the plaintext key lives only in the SAML `RelayState` that
+ round-trips through the IdP — the DB stores and is looked up by its SHA-512 hash, so a read of the table
+ can't reveal in-flight keys."
+ (:require
+ [buddy.core.codecs :as codecs]
+ [buddy.core.hash :as buddy-hash]
+ [clojure.string :as str]
+ [java-time.api :as t]
+ [metabase.util.random :as random]
+ [methodical.core :as methodical]
+ [toucan2.core :as t2])
+ (:import
+ (java.nio.charset StandardCharsets)))
+
+(set! *warn-on-reflection* true)
+
+(methodical/defmethod t2/table-name :model/SsoRelayState [_model] :sso_relay_state)
+
+(doto :model/SsoRelayState
+ (derive :metabase/model)
+ (derive :hook/created-at-timestamped?))
+
+(def ^:private key-prefix
+ "Prefix for generated RelayState keys. The trailing `_` is not part of the Base64 alphabet, so a stored
+ key can never be mistaken for a Base64-encoded continue URL (the legacy, non-embedding RelayState format)."
+ "mbsso_")
+
+(def ^:private ttl-seconds
+ "How long a RelayState entry is valid for — i.e. the maximum time allowed between starting a login
+ (redirect to the IdP) and the IdP posting back. Generous, since a user may spend a while authenticating
+ at their IdP; the SAML assertion's own validity window is the real freshness gate."
+ (* 30 60))
+
+(defn relay-state-key?
+ "Is `relay-state` one of our generated keys (vs. a legacy Base64-encoded continue URL)?"
+ [relay-state]
+ (boolean (and relay-state (str/starts-with? relay-state key-prefix))))
+
+(defn- hash-key
+ "One-way SHA-512 hash (hex) of a RelayState `key`, used as the stored/looked-up primary key. The plaintext
+ key is high-entropy random, so a fast hash is sufficient (cf. [[metabase.session.models.session]])."
+ ^String [^String key]
+ (codecs/bytes->hex (buddy-hash/sha512 (.getBytes key StandardCharsets/UTF_8))))
+
+(defn generate-key
+ "Generate a fresh opaque RelayState key — 16 bytes (128 bits) of cryptographically secure randomness behind
+ the [[key-prefix]]. The key is the unguessable proof that ties an IdP callback to a login we initiated. It
+ is generated before the SAML AuthnRequest (which embeds it) and only [[persist!]]ed once that succeeds."
+ ^String []
+ (str key-prefix (random/secure-hex 16)))
+
+(defn persist!
+ "Persist the SAML callback `context` under its already-generated `:id` (from [[generate-key]]). Returns the id.
+
+ `context` keys:
+ - `:id` - the RelayState key (see [[generate-key]]); stored hashed, never in plaintext
+ - `:continue-url` - where to send the user after login (redirect target, or popup fallback URL)
+ - `:origin` - postMessage target origin (embedding popup only)
+ - `:embedding?` - whether this is a modular-embedding popup login"
+ [{:keys [id continue-url origin embedding?]}]
+ (t2/insert! :model/SsoRelayState
+ {:id (hash-key id)
+ :continue_url continue-url
+ :origin origin
+ :embedding (boolean embedding?)
+ :expires_at (t/plus (t/offset-date-time) (t/seconds ttl-seconds))})
+ id)
+
+(defn find-unexpired
+ "Return the stored, unexpired RelayState row for the (plaintext) `key`, or `nil`. Look-up only — it does NOT
+ delete the entry. The entry is consumed via [[delete!]] only after the login succeeds, so a failed or
+ retried callback doesn't burn the key."
+ [key]
+ (when (relay-state-key? key)
+ (t2/select-one :model/SsoRelayState :id (hash-key key) :expires_at [:> (t/offset-date-time)])))
+
+(defn delete!
+ "Consume (delete) the RelayState entry for the (plaintext) `key`. Called after a successful login; the single
+ `DELETE` is atomic and idempotent (a concurrent or replayed callback that loses the race simply deletes
+ nothing)."
+ [key]
+ (when (relay-state-key? key)
+ (t2/delete! :model/SsoRelayState :id (hash-key key))))
+
+(defn delete-expired!
+ "Delete all expired RelayState entries (abandoned logins that never came back). Returns the number deleted."
+ []
+ (t2/delete! :model/SsoRelayState :expires_at [:<= (t/offset-date-time)]))
diff --git a/enterprise/backend/src/metabase_enterprise/sso/providers/saml.clj b/enterprise/backend/src/metabase_enterprise/sso/providers/saml.clj
index 3690b0f0cea..15fc53f50d1 100644
--- a/enterprise/backend/src/metabase_enterprise/sso/providers/saml.clj
+++ b/enterprise/backend/src/metabase_enterprise/sso/providers/saml.clj
@@ -65,7 +65,7 @@
attrs))
(methodical/defmethod auth-identity/authenticate :provider/saml
- [_provider {:keys [redirect-url] :as request}]
+ [_provider {:keys [redirect-url relay-state] :as request}]
(cond
(not (sso-settings/saml-enabled))
{:success? false
@@ -76,8 +76,11 @@
(= (:request-method request) :get)
(try
(let [idp-url (sso-settings/saml-identity-provider-uri)
- relay-state (when redirect-url
- (u/encode-base64 redirect-url))
+ ;; Callers may pass an explicit `:relay-state` (short server-side key);
+ ;; otherwise fall back to Base64-encoding the continue URL.
+ relay-state (or relay-state
+ (when redirect-url
+ (u/encode-base64 redirect-url)))
response (saml/idp-redirect-response {:request-id (str "id-" (random-uuid))
:sp-name (sso-settings/saml-application-name)
:issuer (sso-settings/saml-application-name)
diff --git a/enterprise/backend/src/metabase_enterprise/sso/task/delete_expired_relay_state.clj b/enterprise/backend/src/metabase_enterprise/sso/task/delete_expired_relay_state.clj
new file mode 100644
index 00000000000..4e3ef7d4bc6
--- /dev/null
+++ b/enterprise/backend/src/metabase_enterprise/sso/task/delete_expired_relay_state.clj
@@ -0,0 +1,38 @@
+(ns metabase-enterprise.sso.task.delete-expired-relay-state
+ "Periodically purge expired `sso_relay_state` rows left behind by SAML embedding logins that were started
+ but never completed (popup closed, IdP never posted back, etc.). Consumed entries are deleted on read; this
+ sweep only cleans up the abandoned ones."
+ (:require
+ [clojurewerkz.quartzite.jobs :as jobs]
+ [clojurewerkz.quartzite.schedule.cron :as cron]
+ [clojurewerkz.quartzite.triggers :as triggers]
+ [metabase-enterprise.sso.models.relay-state :as relay-state]
+ [metabase.task.core :as task]
+ [metabase.util.log :as log]))
+
+(set! *warn-on-reflection* true)
+
+(task/defjob ^{org.quartz.DisallowConcurrentExecution true
+ :doc "Delete expired SAML SSO RelayState entries"}
+ DeleteExpiredSsoRelayState [_ctx]
+ (let [deleted (relay-state/delete-expired!)]
+ (when (pos? deleted)
+ (log/debugf "Deleted %d expired SSO RelayState entries" deleted))))
+
+(def ^:private job
+ (jobs/build
+ (jobs/with-description "Delete expired SSO RelayState entries")
+ (jobs/of-type DeleteExpiredSsoRelayState)
+ (jobs/with-identity (jobs/key "metabase-enterprise.sso.delete-expired-relay-state.job"))
+ (jobs/store-durably)))
+
+(def ^:private trigger
+ (triggers/build
+ (triggers/with-identity (triggers/key "metabase-enterprise.sso.delete-expired-relay-state.trigger"))
+ (triggers/start-now)
+ (triggers/with-schedule
+ ;; once an hour, on the hour
+ (cron/cron-schedule "0 0 * * * ? *"))))
+
+(defmethod task/init! ::DeleteExpiredSsoRelayState [_]
+ (task/schedule-task! job trigger))
diff --git a/enterprise/backend/test/metabase_enterprise/serialization/models/entity_id_test.clj b/enterprise/backend/test/metabase_enterprise/serialization/models/entity_id_test.clj
index c790317e9c1..b421ecaa001 100644
--- a/enterprise/backend/test/metabase_enterprise/serialization/models/entity_id_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/serialization/models/entity_id_test.clj
@@ -117,6 +117,7 @@
:model/SourceMetricDaily
:model/SourceSegmentCompositeDaily
:model/SourceSegmentDaily
+ :model/SsoRelayState
:model/SupportAccessGrantLog
:model/TaskHistory
:model/TaskRun
diff --git a/enterprise/backend/test/metabase_enterprise/sso/integrations/saml_test.clj b/enterprise/backend/test/metabase_enterprise/sso/integrations/saml_test.clj
index 52c54c06d6c..f32020a0cc3 100644
--- a/enterprise/backend/test/metabase_enterprise/sso/integrations/saml_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/sso/integrations/saml_test.clj
@@ -4,6 +4,7 @@
[clojure.string :as str]
[clojure.test :refer :all]
[metabase-enterprise.sso.integrations.token-utils :as token-utils]
+ [metabase-enterprise.sso.models.relay-state :as relay-state]
[metabase-enterprise.sso.providers.saml :as saml.p]
[metabase-enterprise.sso.settings :as sso-settings]
[metabase-enterprise.sso.test-setup :as sso.test-setup]
@@ -240,14 +241,19 @@
(with-saml-default-setup!
(do-with-some-validators-disabled!
(fn []
- (let [result (client/client-real-response :get 302 "/auth/sso"
- {:request-options {:redirect-strategy :none}}
- :redirect default-redirect-uri)
- redirect-url (get-in result [:headers "Location"])]
+ (let [result (client/client-real-response :get 302 "/auth/sso"
+ {:request-options {:redirect-strategy :none}}
+ :redirect default-redirect-uri)
+ redirect-url (get-in result [:headers "Location"])
+ relay-key (:RelayState (uri->params-map redirect-url))]
(testing (format "result = %s" (pr-str result))
(is (string? redirect-url))
- (is (= default-redirect-uri
- (u/decode-base64 (:RelayState (uri->params-map redirect-url))))))))))))
+ (testing "RelayState is a short server-side key, not the encoded continue URL"
+ (is (relay-state/relay-state-key? relay-key))
+ (is (<= (count (.getBytes ^String relay-key "UTF-8")) 80)))
+ (testing "the continue URL is persisted server-side, keyed by the RelayState"
+ (is (= default-redirect-uri
+ (:continue_url (relay-state/find-unexpired relay-key))))))))))))
(defn- saml-response-from-file [filename]
(u/encode-base64 (slurp filename)))
@@ -296,11 +302,23 @@
(re-find #"<script nonce=\"([^\"]+)\">")
second))
-(defn- token-relay-state
- "Build a RelayState whose decoded continue URL carries a valid SDK token + origin."
- [continue-base origin]
- (let [token (token-utils/generate-token)]
- (str continue-base "?token=" token "&origin=" (codec/url-encode origin))))
+(defn- saml-post-request-options*
+ "POST options where the RelayState is a raw server-side relay-state key. The IdP echoes the RelayState
+ back verbatim, so unlike [[saml-post-request-options]] (which Base64-encodes a legacy continue URL) the
+ key must be sent as-is."
+ [saml-response relay-state-key]
+ {:request-options {:content-type :x-www-form-urlencoded
+ :redirect-strategy :none
+ :form-params {:SAMLResponse saml-response
+ :RelayState relay-state-key}}})
+
+(defn- embedding-relay-state-key!
+ "Persist a relay-state entry like the embedding GET flow does, returning its RelayState key."
+ [origin]
+ (relay-state/persist! {:id (relay-state/generate-key)
+ :continue-url (str (system/site-url) "/auth/sso")
+ :origin origin
+ :embedding? true}))
(defn- some-saml-attributes [user-nickname]
{"http://schemas.auth0.com/identities/default/provider" "auth0"
@@ -702,16 +720,15 @@
:redirect redirect-url)
location (get-in result [:headers "Location"])
_ (is (string? location))
- params-map (uri->params-map location)]
+ params-map (uri->params-map location)
+ relay-key (:RelayState params-map)]
(testing (format "\nresult =\n%s" (u/pprint-to-str params-map))
- (testing "\nRelay state URL should be base-64 encoded"
- (is (= redirect-url
- (u/decode-base64 (:RelayState params-map)))))
+ (testing "\nRelayState is a short server-side key"
+ (is (relay-state/relay-state-key? relay-key)))
(testing "\nPOST request should redirect to the original redirect URL"
(do-with-some-validators-disabled!
(fn []
- (let [req-options (saml-post-request-options (saml-test-response)
- (u/decode-base64 (:RelayState params-map)))
+ (let [req-options (saml-post-request-options* (saml-test-response) relay-key)
response (client/client-real-response :post 302 "/auth/sso" req-options)]
(is (successful-login? response))
(is (= redirect-url
@@ -731,13 +748,13 @@
:redirect redirect-url)
location (get-in result [:headers "Location"])
_ (is (string? location))
- params-map (uri->params-map location)]
+ params-map (uri->params-map location)
+ relay-key (:RelayState params-map)]
(testing (format "\nresult =\n%s" (u/pprint-to-str params-map))
(testing "\nPOST request should redirect to the original redirect URL with the correct site-url path"
(do-with-some-validators-disabled!
(fn []
- (let [req-options (saml-post-request-options (saml-test-response)
- (u/decode-base64 (:RelayState params-map)))
+ (let [req-options (saml-post-request-options* (saml-test-response) relay-key)
response (client/client-real-response :post 302 "/auth/sso" req-options)]
(is (successful-login? response))
(is (= (str "http://localhost:3001/path" redirect-url)
@@ -827,37 +844,33 @@
(is (str/starts-with? (-> result :body :url) default-idp-uri)))))))
(deftest saml-embedding-sdk-integration-includes-origin-tests
- (testing "should include origin in the redirect URL when embedding SDK header is present with origin"
+ (testing "should persist the popup origin server-side, referenced by the RelayState key"
(with-other-sso-types-disabled!
(with-saml-default-setup!
- (let [result (client/client-real-response
- :get 200 "/auth/sso"
- {:request-options {:headers {"x-metabase-client" "embedding-sdk-react"
- "origin" "https://app.example.com"}}})
- origin (-> (get-in result [:body :url])
- uri->params-map
- :RelayState
- u/decode-base64
- uri->params-map
- :origin)]
- (is (= "https://app.example.com" origin)))))))
-
-(deftest saml-embedding-sdk-integration-includes-token-tests
- (mt/with-temporary-setting-values [sdk-encryption-validation-key "1FlZMdousOLX9d3SSL+KuWq2+l1gfKoFM7O4ZHqKjTgabo7QdqP8US2bNPN+PqisP1QOKvesxkxOigIrvvd5OQ=="]
- (testing "should include token in the redirect URL when embedding SDK header is present with origin"
- (with-other-sso-types-disabled!
- (with-saml-default-setup!
- (let [result (client/client-real-response
- :get 200 "/auth/sso"
- {:request-options {:headers {"x-metabase-client" "embedding-sdk-react"
- "origin" "https://app.example.com"}}})
- token (-> (get-in result [:body :url])
- uri->params-map
- :RelayState
- u/decode-base64
- uri->params-map
- :token)]
- (is (not (nil? token)))))))))
+ (let [result (client/client-real-response
+ :get 200 "/auth/sso"
+ {:request-options {:headers {"x-metabase-client" "embedding-sdk-react"
+ "origin" "https://app.example.com"}}})
+ relay-key (-> (get-in result [:body :url])
+ uri->params-map
+ :RelayState)]
+ (is (relay-state/relay-state-key? relay-key))
+ (is (= "https://app.example.com"
+ (:origin (relay-state/find-unexpired relay-key)))))))))
+
+(deftest saml-embedding-relay-state-within-80-bytes-test
+ (testing "the embedding RelayState stays within the SAML 80-byte limit, so OpenSAML doesn't warn (UXW-4422)"
+ (with-other-sso-types-disabled!
+ (with-saml-default-setup!
+ (let [result (client/client-real-response
+ :get 200 "/auth/sso"
+ {:request-options {:headers {"x-metabase-client" "embedding-sdk-react"
+ "origin" "https://app.example.com"}}})
+ relay-key (-> (get-in result [:body :url])
+ uri->params-map
+ :RelayState)]
+ (is (relay-state/relay-state-key? relay-key))
+ (is (<= (count (.getBytes ^String relay-key "UTF-8")) 80)))))))
(deftest saml-embedding-sdk-integration-no-embedding-tests
(testing "should redirect to IdP when no embedding SDK header is present"
@@ -871,23 +884,85 @@
(is (str/starts-with? (get-in result [:headers "Location"]) default-idp-uri)))))))
(deftest saml-embedding-sdk-post-integration-tests
- (testing "should the token when it is included in relay state and embedding SDK header"
+ (testing "should return the popup token HTML when the RelayState resolves to a persisted embedding entry"
(with-other-sso-types-disabled!
(with-saml-default-setup!
(do-with-some-validators-disabled!
(fn []
- (let [relay-state (str "http://localhost:3000/"
- "?token=" (token-utils/generate-token)
- "&origin=https%3A%2F%2Fapp.example.com")
- req-options (saml-post-request-options
+ (let [relay-key (embedding-relay-state-key! "https://app.example.com")
+ req-options (saml-post-request-options*
(saml-test-response)
- relay-state)
+ relay-key)
response (client/client-real-response :post 200 "/auth/sso" req-options)]
(is (partial= {:status 200
:headers {"Content-Type" "text/html"}}
response))
(is (str/includes? (:body response) "SAML_AUTH_COMPLETE"))
- (is (str/includes? (:body response) "authData")))))))))
+ (is (str/includes? (:body response) "authData"))
+ (testing "popup posts back to the persisted origin"
+ (is (str/includes? (:body response) "https://app.example.com")))
+ (testing "the relay-state entry is consumed (single use)"
+ (is (nil? (relay-state/find-unexpired relay-key)))))))))))
+
+(deftest saml-stored-key-survives-failed-login-test
+ (testing "a stored RelayState key is consumed only on success — a failed login keeps it so the user can retry"
+ (with-other-sso-types-disabled!
+ (with-saml-default-setup!
+ (let [relay-key (embedding-relay-state-key! "https://app.example.com")]
+ (testing "login fails (validators enabled, so the sample assertion is rejected) → 401, key NOT consumed"
+ (let [resp (client/client-real-response :post 401 "/auth/sso"
+ (saml-post-request-options* (saml-test-response) relay-key))]
+ (is (not (successful-login? resp))))
+ (is (some? (relay-state/find-unexpired relay-key))))
+ (testing "retrying with the same key succeeds, and only then is the key consumed"
+ (do-with-some-validators-disabled!
+ (fn []
+ (let [resp (client/client-real-response :post 200 "/auth/sso"
+ (saml-post-request-options* (saml-test-response) relay-key))]
+ (is (str/includes? (:body resp) "SAML_AUTH_COMPLETE"))))))
+ (is (nil? (relay-state/find-unexpired relay-key))))))))
+
+(deftest saml-embedding-sdk-post-expired-relay-state-test
+ (testing "an embedding RelayState key with no live entry (expired or already used) is rejected"
+ (with-other-sso-types-disabled!
+ (with-saml-default-setup!
+ (do-with-some-validators-disabled!
+ (fn []
+ (let [req-options (saml-post-request-options*
+ (saml-test-response)
+ (str "mbsso_" (random-uuid)))
+ response (client/client-real-response :post 401 "/auth/sso" req-options)]
+ (is (not (successful-login? response))))))))))
+
+(deftest saml-embedding-legacy-token-relay-state-test
+ (testing "in-flight logins from a previous version that packed the token+origin into the RelayState still work (upgrade compatibility)"
+ (with-other-sso-types-disabled!
+ (with-saml-default-setup!
+ (do-with-some-validators-disabled!
+ (fn []
+ (let [relay-state (str "http://localhost:3000/"
+ "?token=" (token-utils/generate-token)
+ "&origin=" (codec/url-encode "https://app.example.com"))
+ req-options (saml-post-request-options (saml-test-response) relay-state)
+ response (client/client-real-response :post 200 "/auth/sso" req-options)]
+ (is (partial= {:status 200
+ :headers {"Content-Type" "text/html"}}
+ response))
+ (is (str/includes? (:body response) "SAML_AUTH_COMPLETE"))
+ (testing "popup posts back to the origin carried in the legacy RelayState"
+ (is (str/includes? (:body response) "https://app.example.com"))))))))))
+
+(deftest saml-embedding-legacy-invalid-token-relay-state-test
+ (testing "a legacy-format RelayState carrying an invalid token is rejected"
+ (with-other-sso-types-disabled!
+ (with-saml-default-setup!
+ (do-with-some-validators-disabled!
+ (fn []
+ (let [relay-state (str "http://localhost:3000/?token=not-a-valid-token"
+ "&origin=" (codec/url-encode "https://app.example.com"))
+ req-options (saml-post-request-options (saml-test-response) relay-state)
+ response (client/client-real-response :post 401 "/auth/sso" req-options)]
+ (is (not (successful-login? response))))))))))
(deftest non-string-saml-attributes-dropped-test
(testing "SAML attributes with non-string values are dropped"
@@ -1138,8 +1213,8 @@
(with-saml-default-setup!
(do-with-some-validators-disabled!
(fn []
- (let [relay-state (token-relay-state default-redirect-uri (system/site-url))
- req-options (saml-post-request-options (saml-test-response) relay-state)
+ (let [relay-key (embedding-relay-state-key! (system/site-url))
+ req-options (saml-post-request-options* (saml-test-response) relay-key)
response (client/client-real-response :post 200 "/auth/sso" req-options)
header-nonce (extract-csp-script-nonce (get-in response [:headers "Content-Security-Policy"]))
body-nonce (extract-script-tag-nonce (:body response))]
@@ -1158,14 +1233,14 @@
(fn []
(let [response-1 (client/client-real-response
:post 200 "/auth/sso"
- (saml-post-request-options
+ (saml-post-request-options*
(saml-test-response)
- (token-relay-state default-redirect-uri (system/site-url))))
+ (embedding-relay-state-key! (system/site-url))))
response-2 (client/client-real-response
:post 200 "/auth/sso"
- (saml-post-request-options
+ (saml-post-request-options*
(saml-test-response)
- (token-relay-state default-redirect-uri (system/site-url))))
+ (embedding-relay-state-key! (system/site-url))))
nonce-1 (extract-script-tag-nonce (:body response-1))
nonce-2 (extract-script-tag-nonce (:body response-2))]
(testing "Both responses have nonces"
diff --git a/enterprise/backend/test/metabase_enterprise/sso/models/relay_state_test.clj b/enterprise/backend/test/metabase_enterprise/sso/models/relay_state_test.clj
new file mode 100644
index 00000000000..185bbd57b57
--- /dev/null
+++ b/enterprise/backend/test/metabase_enterprise/sso/models/relay_state_test.clj
@@ -0,0 +1,98 @@
+(ns metabase-enterprise.sso.models.relay-state-test
+ (:require
+ [clojure.test :refer :all]
+ [java-time.api :as t]
+ [metabase-enterprise.sso.models.relay-state :as relay-state]
+ [metabase.test :as mt]
+ [toucan2.core :as t2]))
+
+(set! *warn-on-reflection* true)
+
+(defn- store!
+ "Generate a key and persist `context` under it, like the GET flow does. Returns the (plaintext) key."
+ [context]
+ (relay-state/persist! (assoc context :id (relay-state/generate-key))))
+
+(defn- stored-id
+ "The primary key actually written to the table for a (plaintext) `key` — i.e. its hash. Used by tests that
+ need to poke the raw row, since the table is keyed by the hash, never the plaintext key."
+ [key]
+ (#'relay-state/hash-key key))
+
+(deftest relay-state-key?-test
+ (testing "recognizes generated keys and rejects legacy Base64 continue URLs"
+ (is (true? (relay-state/relay-state-key? (str "mbsso_" (random-uuid)))))
+ (is (false? (relay-state/relay-state-key? "aHR0cDovL2xvY2FsaG9zdA==")))
+ (is (false? (relay-state/relay-state-key? nil)))
+ (is (false? (relay-state/relay-state-key? "")))))
+
+(deftest generate-key-test
+ (testing "generate-key returns a short, recognizable key within the SAML 80-byte RelayState limit"
+ (let [key (relay-state/generate-key)]
+ (is (relay-state/relay-state-key? key))
+ (is (<= (count (.getBytes ^String key "UTF-8")) 80))
+ (testing "and is unique per call"
+ (is (not= key (relay-state/generate-key)))))))
+
+(deftest persist!-test
+ (testing "persist! stores the context, keyed by the hash of the key (never the plaintext key)"
+ (mt/with-model-cleanup [:model/SsoRelayState]
+ (let [key (store! {:continue-url "http://localhost:3000/auth/sso"
+ :origin "https://app.example.com"
+ :embedding? true})]
+ (testing "the plaintext key is NOT stored; the row is keyed by its hash"
+ (is (false? (t2/exists? :model/SsoRelayState :id key)))
+ (is (true? (t2/exists? :model/SsoRelayState :id (stored-id key)))))
+ (let [row (t2/select-one :model/SsoRelayState :id (stored-id key))]
+ (is (= "http://localhost:3000/auth/sso" (:continue_url row)))
+ (is (= "https://app.example.com" (:origin row)))
+ (is (true? (:embedding row)))
+ (is (some? (:expires_at row)))
+ (is (some? (:created_at row)))))))
+ (testing "persist! defaults embedding to false for a regular login"
+ (mt/with-model-cleanup [:model/SsoRelayState]
+ (let [key (store! {:continue-url "http://localhost:3000/dashboard/1"})
+ row (t2/select-one :model/SsoRelayState :id (stored-id key))]
+ (is (= "http://localhost:3000/dashboard/1" (:continue_url row)))
+ (is (nil? (:origin row)))
+ (is (false? (:embedding row)))))))
+
+(deftest find-unexpired-test
+ (testing "find-unexpired returns the row WITHOUT deleting it (look-up only, so retries don't burn the key)"
+ (mt/with-model-cleanup [:model/SsoRelayState]
+ (let [key (store! {:continue-url "http://localhost:3000/auth/sso"
+ :origin "https://app.example.com"})]
+ (is (= "https://app.example.com" (:origin (relay-state/find-unexpired key))))
+ ;; a second look-up still finds it — it is not consumed on read
+ (is (some? (relay-state/find-unexpired key)))
+ (is (true? (t2/exists? :model/SsoRelayState :id (stored-id key)))))))
+ (testing "find-unexpired returns nil for an expired entry"
+ (mt/with-model-cleanup [:model/SsoRelayState]
+ (let [key (store! {:continue-url "http://localhost:3000/auth/sso"})]
+ ;; backdate so the entry is already expired
+ (t2/update! :model/SsoRelayState (stored-id key) {:expires_at (t/minus (t/offset-date-time) (t/seconds 1))})
+ (is (nil? (relay-state/find-unexpired key))))))
+ (testing "find-unexpired ignores values that aren't our keys (legacy Base64 RelayState)"
+ (is (nil? (relay-state/find-unexpired "aHR0cDovL2xvY2FsaG9zdA==")))))
+
+(deftest delete!-test
+ (testing "delete! consumes the entry (single use); a second delete is a harmless no-op"
+ (mt/with-model-cleanup [:model/SsoRelayState]
+ (let [key (store! {:continue-url "http://localhost:3000/auth/sso"})]
+ (is (= 1 (relay-state/delete! key)))
+ (is (false? (t2/exists? :model/SsoRelayState :id (stored-id key))))
+ (is (= 0 (relay-state/delete! key))))))
+ (testing "delete! ignores values that aren't our keys"
+ (is (nil? (relay-state/delete! "aHR0cDovL2xvY2FsaG9zdA==")))))
+
+(deftest delete-expired!-test
+ (testing "delete-expired! removes only expired entries"
+ (mt/with-model-cleanup [:model/SsoRelayState]
+ (let [live (store! {:continue-url "http://localhost:3000/auth/sso" :origin "*"})
+ expired (store! {:continue-url "http://localhost:3000/auth/sso" :origin "*"})]
+ (t2/update! :model/SsoRelayState (stored-id expired) {:expires_at (t/minus (t/offset-date-time) (t/seconds 1))})
+ ;; delete-expired! operates globally, so don't assert an exact count (other tests may leave rows) —
+ ;; just confirm our expired entry is purged and the live one survives.
+ (is (pos? (relay-state/delete-expired!)))
+ (is (true? (t2/exists? :model/SsoRelayState :id (stored-id live))))
+ (is (false? (t2/exists? :model/SsoRelayState :id (stored-id expired))))))))
diff --git a/resources/migrations/063/20260612_uxw_4422_sso_relay_state.yaml b/resources/migrations/063/20260612_uxw_4422_sso_relay_state.yaml
new file mode 100644
index 00000000000..a527486dab2
--- /dev/null
+++ b/resources/migrations/063/20260612_uxw_4422_sso_relay_state.yaml
@@ -0,0 +1,60 @@
+## Server-side store for the SAML SSO RelayState context.
+
+databaseChangeLog:
+ - changeSet:
+ id: v63.gu89weuix
+ author: nvoxland
+ comment: Create sso_relay_state table for SAML embedding popup callbacks
+ changes:
+ - createTable:
+ tableName: sso_relay_state
+ remarks: Server-side store for SAML SSO RelayState context
+ columns:
+ - column:
+ name: id
+ type: varchar(128)
+ remarks: SHA-512 hash of the RelayState key
+ constraints:
+ primaryKey: true
+ nullable: false
+ - column:
+ name: continue_url
+ type: ${text.type}
+ remarks: URL the popup falls back to when there is no opener window
+ constraints:
+ nullable: false
+ - column:
+ name: origin
+ type: varchar(254)
+ remarks: Origin used as the postMessage target when handing the session back to the opener (embedding only)
+ - column:
+ name: embedding
+ type: ${boolean.type}
+ defaultValueBoolean: false
+ remarks: Whether this is a modular-embedding popup login (postMessage handback) vs. a regular redirect login
+ constraints:
+ nullable: false
+ - column:
+ name: expires_at
+ type: ${timestamp_type}
+ remarks: When this RelayState entry expires and is no longer valid
+ constraints:
+ nullable: false
+ - column:
+ name: created_at
+ type: ${timestamp_type}
+ remarks: When this RelayState entry was created
+ constraints:
+ nullable: false
+
+ - changeSet:
+ id: v63.j98bawra
+ author: nvoxland
+ comment: Index sso_relay_state.expires_at for the expired-row cleanup sweep
+ changes:
+ - createIndex:
+ tableName: sso_relay_state
+ indexName: idx_sso_relay_state_expires_at
+ columns:
+ - column:
+ name: expires_at
diff --git a/src/metabase/models/resolution.clj b/src/metabase/models/resolution.clj
index 4ebefd1488e..0ef42e1e353 100644
--- a/src/metabase/models/resolution.clj
+++ b/src/metabase/models/resolution.clj
@@ -114,6 +114,7 @@
:model/SemanticSearchTokenTracking metabase-enterprise.semantic-search.models.token-tracking
:model/Session metabase.session.models.session
:model/Setting metabase.settings.models.setting
+ :model/SsoRelayState metabase-enterprise.sso.models.relay-state
:model/SupportAccessGrantLog metabase-enterprise.support-access-grants.models.support-access-grant-log
:model/Table metabase.warehouse-schema.models.table
:model/TableRemapping metabase-enterprise.workspaces.models.table-remapping
diff --git a/test/metabase/cmd/copy_test.clj b/test/metabase/cmd/copy_test.clj
index f32bf8fd1b0..b05e5e88a70 100644
--- a/test/metabase/cmd/copy_test.clj
+++ b/test/metabase/cmd/copy_test.clj
@@ -62,6 +62,7 @@
:model/SourceMetricDaily
:model/SourceSegmentCompositeDaily
:model/SourceSegmentDaily
+ :model/SsoRelayState
:model/SupportAccessGrantLog
:model/TaskHistory
:model/TaskRun