Skip to content

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

Cleanup server.middleware.session (#84689)

Eric Normandc6020b521ade
diff --git a/src/metabase/analytics/core.clj b/src/metabase/analytics/core.clj
index 1fc7818293b..608a2d80aaa 100644
--- a/src/metabase/analytics/core.clj
+++ b/src/metabase/analytics/core.clj
@@ -46,9 +46,8 @@
include-sdk-info
pii-fields-from
pii-request-info
- with-auth-method! get-auth-method
+ with-auth-method!
with-client! get-client
- get-route
with-version! get-version]
[metabase.analytics.settings
anon-tracking-enabled
diff --git a/src/metabase/analytics/sdk.clj b/src/metabase/analytics/sdk.clj
index 2aad6a73f76..428124e55c8 100644
--- a/src/metabase/analytics/sdk.clj
+++ b/src/metabase/analytics/sdk.clj
@@ -54,8 +54,6 @@
#_{:clj-kondo/ignore [:metabase/discourage-dynamic-vars]}
(def ^:dynamic *route* "Used to track the API route for the current request (e.g. \"public\", \"guest-embed\")." nil)
-(defn get-route "Returns [[*route*]]." [] *route*)
-
#_{:clj-kondo/ignore [:metabase/discourage-dynamic-vars]}
(def ^:dynamic *auth-method* "Used to track the authentication method for the current request (e.g. \"password\", \"jwt\", \"api-key\")." nil)
@@ -64,8 +62,6 @@
`(binding [*auth-method* ~value]
~@body))
-(defn get-auth-method "Returns [[*auth-method*]]." [] *auth-method*)
-
(defn extract-hostname
"Extracts the hostname from a URL string. Returns nil if the URL is nil or unparseable."
[url]
@@ -175,15 +171,16 @@
[:sandbox_details {:optional true} [:maybe [:sequential [:map {::mr/deliberately-open true}]]]]])
(mu/defn include-sdk-info :- :map
- "Adds the currently bound, or existing `*client*` and `*version*` to the given map, which is usually a row going
- into the `view_log` or `query_execution` table. Falls back to the original value."
+ "Embeds the sdk information into the map for usage analytics."
[m :- sdk-info-row]
(-> m
(update :embedding_client (fn [client] (or *client* client)))
(update :embedding_client_identifier (fn [identifier] (or *client-identifier* identifier)))
(update :embedding_route (fn [route] (or *route* route)))
(update :embedding_sdk_version (fn [version] (or *version* version)))
- (update :auth_method (fn [method] (or *auth-method* method)))
+ (update :auth_method (fn [method] (if (= "guest-embed" *route*)
+ "guest"
+ (or *route* *auth-method* method))))
(assoc :metabase_version (:tag config/mb-version-info))
(merge (hostname-fields) (pii-fields))))
diff --git a/src/metabase/request/schema.clj b/src/metabase/request/schema.clj
index 16930312088..97b3beb6e90 100644
--- a/src/metabase/request/schema.clj
+++ b/src/metabase/request/schema.clj
@@ -13,12 +13,12 @@
[:user-locale {:optional true} [:maybe string?]]
[:is-group-manager? {:optional true} :boolean]
[:permissions-set {:optional true} [:set :string]]
- [:auth-provider {:optional true} [:maybe :string]]
[:settings {:optional true} [:maybe [:or ms/UserSettings :string]]]
[:token-scopes {:optional true} [:maybe [:set [:or :keyword :string]]]]
[:token-scopes-checked {:optional true} :boolean]
[:data-app-scoped? {:optional true} :boolean]
[:authenticated-via-oauth? {:optional true} :boolean]
+ [:embedding/auth-method {:optional true} :string]
;; only API-key auth resolves these two: `:api-key-id` identifies the key itself (for per-key usage analytics),
;; and `:api-key-creator-id` is the real human who created the key (distinct from `:metabase-user-id`, the key's
;; own synthetic service-account user) — both read off the same auth query rather than looked up again later.
diff --git a/src/metabase/server/middleware/log.clj b/src/metabase/server/middleware/log.clj
index 3ff57c68258..00e5be3da9f 100644
--- a/src/metabase/server/middleware/log.clj
+++ b/src/metabase/server/middleware/log.clj
@@ -203,12 +203,9 @@
(defn- api-key-request?
"Whether `request` authenticated with an API key — the only kind of request that gets recorded. Resolved well
outside this middleware by `metabase.server.middleware.session/wrap-current-user-info`, so it is already on the
- request we closed over. Everything else pays this one keyword lookup and nothing more.
-
- Checks `:api-key-id` rather than `:embedding/auth-method` — that key is stamped `agent-api`/`metabot`/`public`/
- `guest` etc. for those routes even when the request authenticated with an API key, so matching on `\"api-key\"`
- missed all of them. `:api-key-id` is only ever set by API-key auth, on every route."
+ request we closed over. Everything else pays this one keyword lookup and nothing more."
[request]
+ ;; `:api-key-id` is always and only set by API-key auth
(some? (:api-key-id request)))
(defn- record-api-key-usage!
diff --git a/src/metabase/server/middleware/session.clj b/src/metabase/server/middleware/session.clj
index 6df280839c5..1b8f373ff03 100644
--- a/src/metabase/server/middleware/session.clj
+++ b/src/metabase/server/middleware/session.clj
@@ -104,25 +104,28 @@
(mu/defn- current-user-info-for-session :- [:maybe [:merge
::request.schema/current-user-info
[:map {:closed true}
- [:session-key-hash :string]]]]
+ [:metabase/authed-session-key-hash :string]]]]
"Return User ID and superuser status for Session with `session-key` if it is valid and not expired, plus
- `:session-key-hash`, the `key_hashed` value the row was matched on."
+ `:metabase/authed-session-key-hash`, the `key_hashed` value the row was matched on."
[session-key :- [:maybe :string]
anti-csrf-token :- [:maybe :string]]
(when (and session-key (valid-session-key? session-key) (init-status/complete?))
(let [session-key-hash (session/hash-session-key session-key)]
- (some-> (server.db/session-user-info session-key-hash
- anti-csrf-token
- (config/config-int :max-session-age)
- (premium-features/enable-advanced-permissions?)
- (and (premium-features/enable-tenants?)
- (setting/get :use-tenants))
- (request/enabled-session-timeout-seconds)
- (session/mfa-required?))
- ;; is-group-manager? could return `nil, convert it to boolean so it's guaranteed to be only true/false
- (update :is-group-manager? boolean)
- ;; so that whatever refers to this session later can do so by the hash without handling the key again
- (assoc :session-key-hash session-key-hash)))))
+ (when-let [{:keys [auth-provider] :as user-info}
+ (server.db/session-user-info session-key-hash
+ anti-csrf-token
+ (config/config-int :max-session-age)
+ (premium-features/enable-advanced-permissions?)
+ (and (premium-features/enable-tenants?)
+ (setting/get :use-tenants))
+ (request/enabled-session-timeout-seconds)
+ (session/mfa-required?))]
+ (-> user-info
+ (dissoc :auth-provider)
+ ;; is-group-manager? could return `nil, convert it to boolean so it's guaranteed to be only true/false
+ (update :is-group-manager? boolean)
+ (assoc :metabase/authed-session-key-hash session-key-hash
+ :embedding/auth-method (or auth-provider "session")))))))
(def ^:private api-key-that-should-never-match (str (random-uuid)))
(def ^:private hash-that-should-never-match (u.password/hash-bcrypt "password"))
@@ -166,7 +169,8 @@
(m/update-existing :is-group-manager? boolean))]
(when (matching-api-key? user-info api-key)
(-> user-info
- (dissoc :api-key)))))))
+ (dissoc :api-key)
+ (assoc :embedding/auth-method "api-key")))))))
(mr/def ::oauth-bearer
"Fns that authenticate a request by its OAuth bearer token, and the scope that grants full access."
@@ -223,7 +227,8 @@
(some-> (server.db/oauth-user-info user-id (premium-features/enable-advanced-permissions?))
(m/update-existing :is-group-manager? boolean)
(assoc :token-scopes (oauth-token->token-scopes full-access-scope scopes)
- :authenticated-via-oauth? true)))))))
+ :authenticated-via-oauth? true
+ :embedding/auth-method "oauth")))))))
(defn- current-user-info-for-mcp-ui-credential
"Resolve the short-lived credential from an MCP App tool result.
@@ -258,44 +263,23 @@
(assoc :token-scopes #{::scope/mcp-ui}
:token-scopes-checked (scope-satisfied? (:request-method request) (:uri request) claims)
:mcp-ui-session-id sid
- :mcp-ui-credential claims)))))
-
-(defn- auth-method
- [session-info api-key-info oauth-info mcp-ui-info embedding-route]
- (or ({"guest-embed" "guest"} embedding-route embedding-route)
- (cond session-info (or (:auth-provider session-info) "session")
- api-key-info "api-key"
- oauth-info "oauth"
- mcp-ui-info "mcp-ui")))
+ :mcp-ui-credential claims
+ :embedding/auth-method "mcp-ui")))))
(defn- merge-current-user-info
[{:keys [oauth-bearer mcp-ui-credentials]}
{:keys [metabase-session-key anti-csrf-token], {:strs [x-metabase-locale x-api-key]} :headers, :as request}]
- (let [session-info (current-user-info-for-session metabase-session-key anti-csrf-token)
- api-key-info (when-not session-info (current-user-info-for-api-key x-api-key))
- ;; Bearer and MCP UI credentials are consulted only when no normal session/API key authenticated.
- oauth-info (when-not (or session-info api-key-info)
- (current-user-info-for-oauth-token oauth-bearer request))
- mcp-ui-info (when-not (or session-info api-key-info oauth-info)
- (current-user-info-for-mcp-ui-credential mcp-ui-credentials request))
- embedding-route (analytics/get-route)
- auth-method (auth-method session-info api-key-info oauth-info mcp-ui-info embedding-route)]
- (merge
- request
- ;; oauth-info carries `:token-scopes` in addition to the standard current-user-info keys, so
- ;; merging it whole both authenticates the request and records the granted scopes.
- (dissoc (or session-info api-key-info oauth-info mcp-ui-info) :auth-provider :session-key-hash)
- ;; `:metabase-session-key` is attached by [[wrap-session-key]] from an unvalidated cookie or header, so its
- ;; presence says nothing about whether the session is the credential that authenticated this request.
- ;; `:metabase/authed-session-key-hash` identifies the session that did, and being namespaced it cannot arrive
- ;; from anywhere a request has been: Ring keys are unqualified, so only this function can set it. It carries the
- ;; `key_hashed` value rather than the key itself, since that is all anything downstream needs and the key is
- ;; the credential.
- (when session-info {:metabase/authed-session-key-hash (:session-key-hash session-info)})
- (when auth-method {:embedding/auth-method auth-method})
- (when x-metabase-locale
- (log/tracef "Found X-Metabase-Locale header: using %s as user locale" (pr-str x-metabase-locale))
- {:user-locale (i18n/normalized-locale-string x-metabase-locale)}))))
+ (merge
+ request
+ ;; order of authentication sources is important, bearer and mcp ui credentials last
+ (or (current-user-info-for-session metabase-session-key anti-csrf-token)
+ (current-user-info-for-api-key x-api-key)
+ ;; bearer tokens below also carry `:token-scopes`
+ (current-user-info-for-oauth-token oauth-bearer request)
+ (current-user-info-for-mcp-ui-credential mcp-ui-credentials request))
+ (when x-metabase-locale
+ (log/tracef "Found X-Metabase-Locale header: using %s as user locale" (pr-str x-metabase-locale))
+ {:user-locale (i18n/normalized-locale-string x-metabase-locale)})))
(defn wrap-current-user-info
"Add `:metabase-user-id`, `:is-superuser?`, `:is-group-manager?` and `:user-locale` to the request if a valid session
diff --git a/test/metabase/mcp/ui_surface_test.clj b/test/metabase/mcp/ui_surface_test.clj
index ee02a152106..198c03f0bde 100644
--- a/test/metabase/mcp/ui_surface_test.clj
+++ b/test/metabase/mcp/ui_surface_test.clj
@@ -3,8 +3,11 @@
[clojure.string :as str]
[clojure.test :refer :all]
[metabase.api.macros.scope :as scope]
+ [metabase.initialization-status.core :as init-status]
+ [metabase.mcp.http-handler :as mcp.http-handler]
[metabase.mcp.session :as mcp.session]
[metabase.mcp.ui-surface :as mcp.ui-surface]
+ [metabase.server.middleware.session :as mw.session]
[metabase.test :as mt]
[metabase.test.fixtures :as fixtures]
[metabase.test.http-client :as client]))
@@ -74,6 +77,20 @@
{:request-options {:headers {"x-metabase-mcp-ui-auth" credential
"mcp-session-id" session-id}}}))
+(deftest ui-credential-authenticates-with-auth-method-mcp-ui-test
+ (init-status/set-complete!)
+ (testing "a resolvable credential on the surface authenticates its user with auth method \"mcp-ui\""
+ (let [user-id (mt/user->id :crowberto)
+ session-id (mcp.session/create! user-id)
+ credential (mcp.session/issue-ui-credential session-id user-id #{"agent:query:run"})]
+ (is (=? {:metabase-user-id user-id
+ :embedding/auth-method "mcp-ui"}
+ (#'mw.session/merge-current-user-info
+ mcp.http-handler/options
+ {:request-method :get
+ :uri "/api/embed-mcp/bootstrap"
+ :headers {"x-metabase-mcp-ui-auth" credential}}))))))
+
(deftest ui-credential-cannot-read-the-profile-test
(testing "GHY-4400: `refresh_ui_credential` is not a scope-escalation primitive — the credential cannot read
the endpoints a narrow agent token is refused"
diff --git a/test/metabase/server/middleware/sdk_test.clj b/test/metabase/server/middleware/sdk_test.clj
index ae73797f707..2d6c5ccd8b2 100644
--- a/test/metabase/server/middleware/sdk_test.clj
+++ b/test/metabase/server/middleware/sdk_test.clj
@@ -68,6 +68,22 @@
(is (=? {:embedding_client_identifier "my-data-app"}
(analytics.core/include-sdk-info {:embedding_client_identifier "my-data-app"})))))
+(deftest include-sdk-info-auth-method-test
+ (testing "A special route's auth method wins over the credential's, which wins over the row's existing value"
+ (are [route bound-method row-method expected]
+ (= expected (:auth_method (binding [sdk/*route* route
+ sdk/*auth-method* bound-method]
+ (analytics.core/include-sdk-info {:auth_method row-method}))))
+ nil "api-key" nil "api-key"
+ nil "api-key" "jwt" "api-key"
+ "guest-embed" "api-key" nil "guest"
+ "public" "session" nil "public"
+ "agent-api" "api-key" nil "agent-api"
+ "guest-embed" nil nil "guest"
+ "metabot" nil nil "metabot"
+ nil nil "jwt" "jwt"
+ nil nil nil nil)))
+
(deftest embeding-mw-bumps-metrics-with-react-sdk-client-header
(mt/with-prometheus-system! [_ system]
;; X-Metabase-Client header == "embedding-sdk-react" => SDK context
@@ -265,10 +281,10 @@
(:body (handler request identity identity))))
(defn- route-from-mw
- "Runs a request through embedding-mw and returns the *route* value bound inside the handler."
+ "Runs a request through embedding-mw and returns the route bound inside the handler."
[request]
(let [handler (analytics.core/embedding-mw
- (fn [_ respond _] (respond {:status 200 :body (sdk/get-route)})))]
+ (fn [_ respond _] (respond {:status 200 :body sdk/*route*})))]
(:body (handler request identity identity))))
(deftest route-based-client-derivation-test
diff --git a/test/metabase/server/middleware/session_oauth_test.clj b/test/metabase/server/middleware/session_oauth_test.clj
index daf708a18dd..52d59ed056c 100644
--- a/test/metabase/server/middleware/session_oauth_test.clj
+++ b/test/metabase/server/middleware/session_oauth_test.clj
@@ -171,13 +171,11 @@
(testing "a session request"
(mt/with-dynamic-fn-redefs [mw.session/current-user-info-for-session (fn [_ _] user-info)]
(let [req (merge-current-user-info {:metabase-session-key "session-key"})]
- (is (= "session" (:embedding/auth-method req)))
(is (nil? (:authenticated-via-oauth? req)))
(is (passes-scope-middleware? req)))))
(testing "an API-key request"
(mt/with-dynamic-fn-redefs [mw.session/current-user-info-for-api-key (fn [_] user-info)]
(let [req (merge-current-user-info {:headers {"x-api-key" "mb_whatever"}})]
- (is (= "api-key" (:embedding/auth-method req)))
(is (nil? (:authenticated-via-oauth? req)))
(is (passes-scope-middleware? req)))))
(testing "a session request carrying a stray bearer header"
@@ -188,7 +186,6 @@
(mt/with-dynamic-fn-redefs [mw.session/current-user-info-for-session (fn [_ _] user-info)]
(let [req (merge-current-user-info (assoc (bearer-request token) :metabase-session-key "session-key"))]
(is (= (mt/user->id :rasta) (:metabase-user-id req)))
- (is (= "session" (:embedding/auth-method req)))
(is (nil? (:authenticated-via-oauth? req)))
(is (passes-scope-middleware? req))))
(testing "and over HTTP"
@@ -303,6 +300,5 @@
(let [req (merge-current-user-info {:headers {"authorization" "Bearer anything"
"x-api-key" "mb_whatever"}})]
(is (= 99 (:metabase-user-id req)))
- (is (= "api-key" (:embedding/auth-method req)))
(is (nil? (:token-scopes req)) "api-key auth must not set token-scopes")
(is (false? @called?) "bearer token store must not be consulted when api-key already authenticated"))))))
diff --git a/test/metabase/server/middleware/session_test.clj b/test/metabase/server/middleware/session_test.clj
index 0cfaa78c75a..2669e8d2d0c 100644
--- a/test/metabase/server/middleware/session_test.clj
+++ b/test/metabase/server/middleware/session_test.clj
@@ -444,8 +444,8 @@
:is-group-manager? false,
:user-locale nil
:is-data-analyst? false
- :auth-provider nil
- :session-key-hash test-session-key-hashed}
+ :metabase/authed-session-key-hash test-session-key-hashed
+ :embedding/auth-method "session"}
(#'mw.session/current-user-info-for-session test-session-key nil)))
(finally
(t2/delete! :model/Session :id test-session-id))))))
@@ -462,8 +462,8 @@
:is-group-manager? false,
:user-locale nil
:is-data-analyst? false
- :auth-provider nil
- :session-key-hash test-session-key-hashed}
+ :metabase/authed-session-key-hash test-session-key-hashed
+ :embedding/auth-method "session"}
(#'mw.session/current-user-info-for-session test-session-key nil)))
(finally
(t2/delete! :model/Session :id test-session-id))))))
@@ -516,8 +516,8 @@
:is-group-manager? false,
:user-locale nil
:is-data-analyst? false
- :auth-provider nil
- :session-key-hash test-session-key-hashed}
+ :metabase/authed-session-key-hash test-session-key-hashed
+ :embedding/auth-method "session"}
(#'mw.session/current-user-info-for-session test-session-key test-anti-csrf-token)))
(finally
(t2/delete! :model/Session :id test-session-id)))
@@ -568,21 +568,21 @@
(t2/delete! :model/Session :id test-session-id))))))
(deftest auth-provider-via-left-join-test
- (testing "session LEFT JOIN on auth_identity returns correct provider for each auth method"
+ (testing "a session's auth method is its auth_identity provider, or \"session\" without one"
(mt/with-temporary-setting-values [mfa-enforcement :off]
(mt/with-temp [:model/User {user-id :id} {}]
- ;; "password" is excluded - its before-insert hook requires credentials, and it's already
- ;; tested via auth-method-test in view_log_test.clj. "api-key" is tested above in
- ;; current-user-info-for-api-key-test (different code path, no auth_identity).
- (doseq [provider ["jwt" "saml" "google" "ldap" "oidc"
- "custom-oidc" "slack-connect" "support-access-grant"]]
- (testing (str "provider: " provider)
- (let [ai (first (t2/insert-returning-instances! (t2/table-name :model/AuthIdentity)
- {:user_id user-id
- :provider provider
- :provider_id (str user-id "-" provider)
- :created_at :%now
- :updated_at :%now}))
+ ;; table inserts skip the AuthIdentity before-insert hook, which requires credentials for "password".
+ ;; "api-key" is tested above in current-user-info-for-api-key-test (no auth_identity).
+ (doseq [provider ["password" "jwt" "saml" "google" "ldap" "oidc"
+ "custom-oidc" "slack-connect" "support-access-grant" nil]]
+ (testing (str "provider: " (or provider "none"))
+ (let [ai (when provider
+ (first (t2/insert-returning-instances! (t2/table-name :model/AuthIdentity)
+ {:user_id user-id
+ :provider provider
+ :provider_id (str user-id "-" provider)
+ :created_at :%now
+ :updated_at :%now})))
session-key (session/generate-session-key)
session-id (session/generate-session-id)]
(try
@@ -592,11 +592,12 @@
:user_id user-id
:auth_identity_id (:id ai)
:created_at :%now})
- (is (= provider
- (:auth-provider (#'mw.session/current-user-info-for-session session-key nil))))
+ (is (= (or provider "session")
+ (:embedding/auth-method (#'mw.session/current-user-info-for-session session-key nil))))
(finally
(t2/delete! :model/Session :id session-id)
- (t2/delete! :model/AuthIdentity :id (:id ai)))))))))))
+ (when ai
+ (t2/delete! :model/AuthIdentity :id (:id ai))))))))))))
;; create a simple example of our middleware wrapped around a handler that simply returns our bound variables for users
(defn- user-bound-handler [request]
@@ -731,32 +732,6 @@
:last_active_at (h2x/add-interval-honeysql-form (mdb/db-type) :%now -600 :second)})
(is (some? (#'mw.session/current-user-info-for-session session-key nil))))))))
-(deftest auth-method-test
- (testing "auth-method prefers route-based override on special routes"
- (let [f #'mw.session/auth-method]
- (are [session-info api-key-info oauth-info mcp-ui-info embedding-route expected]
- (= expected (f session-info api-key-info oauth-info mcp-ui-info embedding-route))
- ;; session-based auth on non-special routes
- {:auth-provider "password"} nil nil nil nil "password"
- {:auth-provider "saml"} nil nil nil nil "saml"
- {:auth-provider "jwt"} nil nil nil nil "jwt"
- {:auth-provider "ldap"} nil nil nil nil "ldap"
- {} nil nil nil nil "session"
- ;; api-key on non-special route
- nil {} nil nil nil "api-key"
- ;; oauth bearer on non-special route
- nil nil {:metabase-user-id 1} nil nil "oauth"
- ;; mcp-ui credential on non-special route
- nil nil nil {:metabase-user-id 1} nil "mcp-ui"
- ;; route override: special routes win over credentials
- nil {} nil nil "guest-embed" "guest" ; api-key + embed -> guest
- nil nil nil nil "guest-embed" "guest" ; anon guest embed
- nil nil nil nil "public" "public"
- nil nil nil nil "metabot" "metabot"
- nil nil nil nil "agent-api" "agent-api"
- ;; fully anonymous, non-special route
- nil nil nil nil nil nil))))
-
(defn session-valid?
[session-key]
(boolean (#'mw.session/current-user-info-for-session session-key nil)))