Skip to content

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

More clarity around revoking credentials when "base" entity is gone/deactivated (#80556)

John Swansonf2cef9e46c54
diff --git a/.clj-kondo/config.edn b/.clj-kondo/config.edn
index 09214e8e1f4..134b5495618 100644
--- a/.clj-kondo/config.edn
+++ b/.clj-kondo/config.edn
@@ -498,6 +498,7 @@
metabase.notification.test-util/with-card-notification clojure.core/let
metabase.notification.test-util/with-system-event-notification! clojure.core/let
metabase.notification.test-util/with-temp-notification clojure.core/let
+ metabase.oauth-server.test-util/with-oauth-client clojure.core/fn
metabase.osi.ai-context.api-test/with-test-entry clojure.core/let
metabase.premium-features.core/defenterprise-schema clj-kondo.lint-as/def-catch-all
metabase.premium-features.defenterprise/defenterprise-schema clj-kondo.lint-as/def-catch-all
diff --git a/.clj-kondo/config/modules/config.edn b/.clj-kondo/config/modules/config.edn
index 46d0480c488..cc5d8cccb71 100644
--- a/.clj-kondo/config/modules/config.edn
+++ b/.clj-kondo/config/modules/config.edn
@@ -1608,6 +1608,7 @@
:uses #{api
api-scope
appearance
+ events
mcp
models
request
diff --git a/src/metabase/events/schema.clj b/src/metabase/events/schema.clj
index 7d61a920ca3..62df2baae54 100644
--- a/src/metabase/events/schema.clj
+++ b/src/metabase/events/schema.clj
@@ -95,6 +95,8 @@
(mr/def :event/user-login ::user)
(mr/def :event/user-joined ::user)
+(mr/def :event/user-credentials-revoked ::user)
+
(mr/def :event/user-invited
[:map {:closed true}
[:object [:map
diff --git a/src/metabase/oauth_server/core.clj b/src/metabase/oauth_server/core.clj
index 9d28598872d..3fb9bb81c92 100644
--- a/src/metabase/oauth_server/core.clj
+++ b/src/metabase/oauth_server/core.clj
@@ -9,7 +9,8 @@
[metabase.system.core :as system]
[metabase.util :as u]
[oidc-provider.core :as oidc]
- [oidc-provider.store :as oidc.store]))
+ [oidc-provider.store :as oidc.store]
+ [toucan2.core :as t2]))
(set! *warn-on-reflection* true)
@@ -100,8 +101,10 @@
(when-let [provider (get-provider)]
(when-let [token-data (oidc.store/get-access-token (:token-store provider) token-string)]
(let [expiry (:expiry token-data)]
- (when (or (nil? expiry)
- (t/after? (t/instant expiry) (t/instant)))
+ (when (and (or (nil? expiry)
+ (t/after? (t/instant expiry) (t/instant)))
+ ;; Fail closed if the issuing client is gone (SEC-863).
+ (t2/exists? :model/OAuthClient :client_id (:client-id token-data)))
(when-let [user-id (some-> (:user-id token-data) parse-long)]
{:user-id user-id
:scopes (or (some->> (:scope token-data) (into #{})) #{})})))))))
diff --git a/src/metabase/oauth_server/events/revoke_on_deactivation.clj b/src/metabase/oauth_server/events/revoke_on_deactivation.clj
new file mode 100644
index 00000000000..833cad6635b
--- /dev/null
+++ b/src/metabase/oauth_server/events/revoke_on_deactivation.clj
@@ -0,0 +1,16 @@
+(ns metabase.oauth-server.events.revoke-on-deactivation
+ "Revoke a user's OAuth access and refresh tokens when they are deactivated, so a later reactivation
+ can't revive a pre-deactivation token. (SEC-863)"
+ (:require
+ [metabase.events.core :as events]
+ [methodical.core :as methodical]
+ [toucan2.core :as t2]))
+
+(events/derive! ::event :metabase/event)
+(events/derive! :event/user-credentials-revoked ::event)
+
+(methodical/defmethod events/publish-event! ::event
+ [_topic {:keys [user-id] :as _event}]
+ (t2/update! :model/OAuthAccessToken {:user_id user-id, :revoked_at nil} {:revoked_at :%now})
+ (t2/update! :model/OAuthRefreshToken {:user_id user-id, :revoked_at nil} {:revoked_at :%now})
+ (t2/delete! :model/OAuthAuthorizationCode :user_id user-id))
diff --git a/src/metabase/oauth_server/init.clj b/src/metabase/oauth_server/init.clj
index ea4bae4d905..37faabc02aa 100644
--- a/src/metabase/oauth_server/init.clj
+++ b/src/metabase/oauth_server/init.clj
@@ -1,4 +1,5 @@
(ns metabase.oauth-server.init
(:require
+ [metabase.oauth-server.events.revoke-on-deactivation]
[metabase.oauth-server.settings]
[metabase.oauth-server.task.cleanup-expired-tokens]))
diff --git a/src/metabase/session/events/revoke_on_deactivation.clj b/src/metabase/session/events/revoke_on_deactivation.clj
new file mode 100644
index 00000000000..35f6a23d601
--- /dev/null
+++ b/src/metabase/session/events/revoke_on_deactivation.clj
@@ -0,0 +1,14 @@
+(ns metabase.session.events.revoke-on-deactivation
+ "Delete a user's sessions when they are deactivated, so a later reactivation can't revive a
+ pre-deactivation session cookie. (SEC-863)"
+ (:require
+ [metabase.events.core :as events]
+ [methodical.core :as methodical]
+ [toucan2.core :as t2]))
+
+(events/derive! ::event :metabase/event)
+(events/derive! :event/user-credentials-revoked ::event)
+
+(methodical/defmethod events/publish-event! ::event
+ [_topic {:keys [user-id] :as _event}]
+ (t2/delete! :model/Session :user_id user-id))
diff --git a/src/metabase/session/init.clj b/src/metabase/session/init.clj
index f0038929401..9820403113d 100644
--- a/src/metabase/session/init.clj
+++ b/src/metabase/session/init.clj
@@ -1,4 +1,5 @@
(ns metabase.session.init
(:require
+ [metabase.session.events.revoke-on-deactivation]
[metabase.session.settings]
[metabase.session.task.session-cleanup]))
diff --git a/src/metabase/users/models/user.clj b/src/metabase/users/models/user.clj
index b64e27b4e89..47231b97ecd 100644
--- a/src/metabase/users/models/user.clj
+++ b/src/metabase/users/models/user.clj
@@ -206,6 +206,9 @@
(perms/without-is-superuser-sync-on-add-to-admin-group
(perms/add-user-to-groups! user-id (map u/the-id groups))))))))
+;; Declare the topic a valid event here in case subscribers are not loaded yet. (SEC-863)
+(events/derive! :event/user-credentials-revoked :metabase/event)
+
(t2/define-before-update :model/User
[{:keys [id] :as user}]
(let [changes (t2/changes user)
@@ -220,6 +223,8 @@
(when locale (validate-user-locale! locale))
(handle-superuser-toggle! id superuser? in-admin-group?)
(handle-user-archival! id active?)
+ (when (false? active?)
+ (events/publish-event! :event/user-credentials-revoked {:user-id id}))
(-> user
(merge (normalize-user-fields (t2/changes user))
(prepare-archival-timestamp active?))
diff --git a/test/metabase/mcp/api_test.clj b/test/metabase/mcp/api_test.clj
index cd3f05fa45d..b765640e28e 100644
--- a/test/metabase/mcp/api_test.clj
+++ b/test/metabase/mcp/api_test.clj
@@ -15,6 +15,7 @@
[metabase.mcp.settings :as mcp.settings]
[metabase.mcp.tools :as mcp.tools]
[metabase.oauth-server.core :as oauth-server]
+ [metabase.oauth-server.test-util :as oauth-server.tu]
[metabase.search.test-util :as search.tu]
[metabase.system.settings :as system.settings]
[metabase.test :as mt]
@@ -74,10 +75,11 @@
body))
(defn- save-access-token!
- "Persist an OAuth access token into the provider backing the MCP endpoint."
- [token user-id scopes]
+ "Persist an OAuth access token into the provider backing the MCP endpoint. `client-id` should come
+ from [[oauth-server.tu/with-oauth-client]]."
+ [token user-id client-id scopes]
(oidc.store/save-access-token (:token-store (oauth-server/get-provider))
- token (str user-id) "test-client" (vec scopes)
+ token (str user-id) client-id (vec scopes)
(+ (inst-ms (java.util.Date.)) 3600000) nil))
(defn- mcp-delete
@@ -1446,31 +1448,33 @@
(mt/with-temporary-setting-values [site-url "http://localhost:3000"]
(t2/with-transaction [_conn nil {:rollback-only true}]
(oauth-server/reset-provider!)
- (let [token (str (random-uuid))]
- (save-access-token! token (mt/user->id :crowberto) #{"agent:search"})
- (let [sid (-> (mcp-request-with-bearer token 200 (jsonrpc-request "initialize") {})
- (get-in [:headers "Mcp-Session-Id"]))
- response (mcp-request-with-bearer token 200 (jsonrpc-request "tools/list")
- {"mcp-session-id" sid})
- tool-names (set (map :name (get-in response [:body :result :tools])))]
- (is (contains? tool-names "search"))
- (is (not (contains? tool-names "update_question"))
- "Only matching tools should be available")))))))
+ (oauth-server.tu/with-oauth-client [client-id]
+ (let [token (str (random-uuid))]
+ (save-access-token! token (mt/user->id :crowberto) client-id #{"agent:search"})
+ (let [sid (-> (mcp-request-with-bearer token 200 (jsonrpc-request "initialize") {})
+ (get-in [:headers "Mcp-Session-Id"]))
+ response (mcp-request-with-bearer token 200 (jsonrpc-request "tools/list")
+ {"mcp-session-id" sid})
+ tool-names (set (map :name (get-in response [:body :result :tools])))]
+ (is (contains? tool-names "search"))
+ (is (not (contains? tool-names "update_question"))
+ "Only matching tools should be available"))))))))
(deftest full-access-token-scope-validation-test
(testing "an OAuth token with the full-access grant exposes all tools"
(mt/with-temporary-setting-values [site-url "http://localhost:3000"]
(t2/with-transaction [_conn nil {:rollback-only true}]
(oauth-server/reset-provider!)
- (let [token (str (random-uuid))]
- (save-access-token! token (mt/user->id :crowberto) #{oauth-server/full-access-scope})
- (let [sid (-> (mcp-request-with-bearer token 200 (jsonrpc-request "initialize") {})
- (get-in [:headers "Mcp-Session-Id"]))
- response (mcp-request-with-bearer token 200 (jsonrpc-request "tools/list")
- {"mcp-session-id" sid})
- tool-names (set (map :name (get-in response [:body :result :tools])))]
- (is (contains? tool-names "search"))
- (is (contains? tool-names "update_question"))))))))
+ (oauth-server.tu/with-oauth-client [client-id]
+ (let [token (str (random-uuid))]
+ (save-access-token! token (mt/user->id :crowberto) client-id #{oauth-server/full-access-scope})
+ (let [sid (-> (mcp-request-with-bearer token 200 (jsonrpc-request "initialize") {})
+ (get-in [:headers "Mcp-Session-Id"]))
+ response (mcp-request-with-bearer token 200 (jsonrpc-request "tools/list")
+ {"mcp-session-id" sid})
+ tool-names (set (map :name (get-in response [:body :result :tools])))]
+ (is (contains? tool-names "search"))
+ (is (contains? tool-names "update_question")))))))))
(deftest tools-call-token-scope-validation-test
(testing "an OAuth token with a limited scope cannot call a tool outside that scope"
@@ -1480,19 +1484,20 @@
(mt/with-temporary-setting-values [site-url "http://localhost:3000"]
(t2/with-transaction [_conn nil {:rollback-only true}]
(oauth-server/reset-provider!)
- (let [token (str (random-uuid))]
- (save-access-token! token (mt/user->id :crowberto) #{"agent:search"})
- (let [sid (-> (mcp-request-with-bearer token 200 (jsonrpc-request "initialize") {})
- (get-in [:headers "Mcp-Session-Id"]))
- response (mcp-request-with-bearer token 200
- (jsonrpc-request "tools/call"
- {:name "update_question"
- :arguments {:id card-id :name "Renamed by narrow token"}})
- {"mcp-session-id" sid})]
- (is (=? {:isError true} (get-in response [:body :result]))
- "update_question is outside agent:search and must be refused")
- (is (= "Scope Validation Card" (t2/select-one-fn :name :model/Card :id card-id))
- "the card must not have been renamed"))))))))
+ (oauth-server.tu/with-oauth-client [client-id]
+ (let [token (str (random-uuid))]
+ (save-access-token! token (mt/user->id :crowberto) client-id #{"agent:search"})
+ (let [sid (-> (mcp-request-with-bearer token 200 (jsonrpc-request "initialize") {})
+ (get-in [:headers "Mcp-Session-Id"]))
+ response (mcp-request-with-bearer token 200
+ (jsonrpc-request "tools/call"
+ {:name "update_question"
+ :arguments {:id card-id :name "Renamed by narrow token"}})
+ {"mcp-session-id" sid})]
+ (is (=? {:isError true} (get-in response [:body :result]))
+ "update_question is outside agent:search and must be refused")
+ (is (= "Scope Validation Card" (t2/select-one-fn :name :model/Card :id card-id))
+ "the card must not have been renamed")))))))))
(defn- insert-expired-oauth-token!
"Insert an OAuth access token into the DB with an expiry in the past.
@@ -1513,14 +1518,16 @@
(mt/with-temporary-setting-values [site-url "http://localhost:3000"]
(t2/with-transaction [_conn nil {:rollback-only true}]
(oauth-server/reset-provider!)
- (let [user-id (mt/user->id :crowberto)
- token (insert-expired-oauth-token! user-id (str (random-uuid)))
- response (mcp-request-with-bearer token 401
- (jsonrpc-request "initialize")
- {})]
- (is (=? {:status 401
- :headers {"WWW-Authenticate" #(str/includes? % "invalid_token")}}
- response)))))))
+ ;; register a live client so the expiry is the only thing rejecting the token
+ (oauth-server.tu/with-oauth-client [client-id]
+ (let [user-id (mt/user->id :crowberto)
+ token (insert-expired-oauth-token! user-id client-id)
+ response (mcp-request-with-bearer token 401
+ (jsonrpc-request "initialize")
+ {})]
+ (is (=? {:status 401
+ :headers {"WWW-Authenticate" #(str/includes? % "invalid_token")}}
+ response))))))))
(deftest tools-call-scope-enforcement-test
(mt/with-temp [:model/Card {card-id :id} {:name "Scope Test Card"
@@ -1654,21 +1661,22 @@
(mt/with-temporary-setting-values [site-url "http://localhost:3000"]
(t2/with-transaction [_conn nil {:rollback-only true}]
(oauth-server/reset-provider!)
- (let [token (str (random-uuid))
- _ (save-access-token! token (mt/user->id :crowberto) #{"agent:viz:mcp-ui:query"})
- initialize (mcp-request-with-bearer token 200 (jsonrpc-request "initialize" {:capabilities mcp-app-ui-capabilities}) {})
- session-id (get-in initialize [:headers "Mcp-Session-Id"])
- resource (mcp-request-with-bearer token 200
- (jsonrpc-request "resources/read" {:uri "ui://metabase/visualize-query.html"})
- {"mcp-session-id" session-id})
- html (-> resource :body :result :contents first :text)
- credential (second (re-find #"uiCredential:\s*\"([^\"]+)\"" html))
- headers {"x-metabase-mcp-ui-auth" credential}]
- (is (string? credential))
- (is (= 200 (:status (client/client-full-response :get 200 "user/current"
- {:request-options {:headers headers}}))))
- (is (= 401 (:status (client/client-full-response :get 401 "collection"
- {:request-options {:headers headers}})))))))))
+ (oauth-server.tu/with-oauth-client [client-id]
+ (let [token (str (random-uuid))
+ _ (save-access-token! token (mt/user->id :crowberto) client-id #{"agent:viz:mcp-ui:query"})
+ initialize (mcp-request-with-bearer token 200 (jsonrpc-request "initialize" {:capabilities mcp-app-ui-capabilities}) {})
+ session-id (get-in initialize [:headers "Mcp-Session-Id"])
+ resource (mcp-request-with-bearer token 200
+ (jsonrpc-request "resources/read" {:uri "ui://metabase/visualize-query.html"})
+ {"mcp-session-id" session-id})
+ html (-> resource :body :result :contents first :text)
+ credential (second (re-find #"uiCredential:\s*\"([^\"]+)\"" html))
+ headers {"x-metabase-mcp-ui-auth" credential}]
+ (is (string? credential))
+ (is (= 200 (:status (client/client-full-response :get 200 "user/current"
+ {:request-options {:headers headers}}))))
+ (is (= 401 (:status (client/client-full-response :get 401 "collection"
+ {:request-options {:headers headers}}))))))))))
(deftest batch-initialized-then-resources-read-test
(testing "batch containing notifications/initialized + resources/read succeeds"
diff --git a/test/metabase/oauth_server/core_test.clj b/test/metabase/oauth_server/core_test.clj
index 6262d5bf129..03ec9ebf041 100644
--- a/test/metabase/oauth_server/core_test.clj
+++ b/test/metabase/oauth_server/core_test.clj
@@ -1,8 +1,14 @@
(ns metabase.oauth-server.core-test
(:require
[clojure.test :refer [deftest is testing use-fixtures]]
+ ;; Loaded for its load-time side effects: it registers the agent API endpoints, from which
+ ;; `get-provider` derives the provider's supported scopes (see [[metabase.mcp.core/all-scopes]]).
+ [metabase.agent-api.api]
[metabase.oauth-server.core :as oauth-server]
- [metabase.test :as mt]))
+ [metabase.oauth-server.test-util :as oauth-server.tu]
+ [metabase.test :as mt]
+ [oidc-provider.store :as oidc.store]
+ [toucan2.core :as t2]))
(use-fixtures :each (fn [thunk]
(oauth-server/reset-provider!)
@@ -24,3 +30,21 @@
(is (= "http://localhost:3000" (:issuer config)))
(is (= "http://localhost:3000/oauth/authorize" (:authorization-endpoint config)))
(is (= "http://localhost:3000/oauth/token" (:token-endpoint config)))))))
+
+(deftest resolve-access-token-requires-existing-client-test
+ (testing "an access token stops authenticating once its oauth_client row is deleted (SEC-863)"
+ (mt/with-temporary-setting-values [site-url "http://localhost:3000"]
+ (t2/with-transaction [_conn nil {:rollback-only true}]
+ (oauth-server.tu/with-oauth-client [client-id]
+ (let [token (str (random-uuid))
+ user-id (mt/user->id :rasta)
+ expiry (+ (inst-ms (java.util.Date.)) 3600000)]
+ (oidc.store/save-access-token (:token-store (oauth-server/get-provider))
+ token (str user-id) client-id ["openid"] expiry nil)
+ (testing "resolves while the client exists"
+ (is (=? {:user-id user-id
+ :scopes #{"openid"}}
+ (oauth-server/resolve-access-token token))))
+ (testing "returns nil once the client row is gone — token must not outlive its client"
+ (t2/delete! :model/OAuthClient :client_id client-id)
+ (is (nil? (oauth-server/resolve-access-token token))))))))))
diff --git a/test/metabase/oauth_server/events/revoke_on_deactivation_test.clj b/test/metabase/oauth_server/events/revoke_on_deactivation_test.clj
new file mode 100644
index 00000000000..0fca4b856fd
--- /dev/null
+++ b/test/metabase/oauth_server/events/revoke_on_deactivation_test.clj
@@ -0,0 +1,79 @@
+(ns metabase.oauth-server.events.revoke-on-deactivation-test
+ (:require
+ [clojure.test :refer [deftest is testing]]
+ [metabase.events.core :as events]
+ [metabase.oauth-server.events.revoke-on-deactivation] ; for side effects: registers the event subscriber
+ [metabase.test :as mt]
+ [toucan2.core :as t2]))
+
+(defn- in-one-hour [] (+ (inst-ms (java.util.Date.)) 3600000))
+
+(defn- insert-access-token! [user-id]
+ (let [token (str (random-uuid))]
+ (t2/insert! :model/OAuthAccessToken {:token token
+ :user_id user-id
+ :client_id "test-client"
+ :scope ["openid"]
+ :expiry (in-one-hour)})
+ token))
+
+(defn- insert-refresh-token! [user-id]
+ (let [token (str (random-uuid))]
+ (t2/insert! :model/OAuthRefreshToken {:token token
+ :user_id user-id
+ :client_id "test-client"
+ :scope ["openid"]})
+ token))
+
+(defn- insert-auth-code! [user-id]
+ (let [code (str (random-uuid))]
+ (t2/insert! :model/OAuthAuthorizationCode {:code code
+ :user_id user-id
+ :client_id "test-client"
+ :redirect_uri "http://localhost/callback"
+ :scope ["openid"]
+ :expiry (in-one-hour)})
+ code))
+
+(defn- revoked? [model token]
+ (some? (t2/select-one-fn :revoked_at model :token token)))
+
+(deftest revoke-on-event-test
+ (testing ":event/user-credentials-revoked revokes the user's OAuth tokens, leaving other users' untouched"
+ (t2/with-transaction [_conn nil {:rollback-only true}]
+ (let [victim (mt/user->id :rasta)
+ bystander (mt/user->id :lucky)
+ victim-access (insert-access-token! victim)
+ victim-refresh (insert-refresh-token! victim)
+ victim-code (insert-auth-code! victim)
+ bystander-access (insert-access-token! bystander)
+ bystander-code (insert-auth-code! bystander)]
+ (events/publish-event! :event/user-credentials-revoked {:user-id victim})
+ (is (revoked? :model/OAuthAccessToken victim-access)
+ "victim's access token is revoked")
+ (is (revoked? :model/OAuthRefreshToken victim-refresh)
+ "victim's refresh token is revoked")
+ (is (not (t2/exists? :model/OAuthAuthorizationCode :code victim-code))
+ "victim's pending authorization code is deleted — it could otherwise mint fresh tokens")
+ (is (not (revoked? :model/OAuthAccessToken bystander-access))
+ "an unrelated user's token is untouched")
+ (is (t2/exists? :model/OAuthAuthorizationCode :code bystander-code)
+ "an unrelated user's pending authorization code is untouched")))))
+
+(deftest deactivation-revokes-and-reactivation-does-not-revive-test
+ (testing "deactivating a user revokes their OAuth tokens; reactivating does NOT un-revoke them (SEC-863)"
+ (t2/with-transaction [_conn nil {:rollback-only true}]
+ (let [user-id (mt/user->id :rasta)
+ access-token (insert-access-token! user-id)
+ auth-code (insert-auth-code! user-id)]
+ (is (not (revoked? :model/OAuthAccessToken access-token))
+ "token is live while the user is active")
+ (t2/update! :model/User user-id {:is_active false})
+ (is (revoked? :model/OAuthAccessToken access-token)
+ "deactivation revokes the token")
+ (is (not (t2/exists? :model/OAuthAuthorizationCode :code auth-code))
+ "deactivation deletes the pending authorization code")
+ (let [revoked-at (t2/select-one-fn :revoked_at :model/OAuthAccessToken :token access-token)]
+ (t2/update! :model/User user-id {:is_active true})
+ (is (= revoked-at (t2/select-one-fn :revoked_at :model/OAuthAccessToken :token access-token))
+ "reactivation does not un-revoke the pre-deactivation token"))))))
diff --git a/test/metabase/oauth_server/test_util.clj b/test/metabase/oauth_server/test_util.clj
new file mode 100644
index 00000000000..1f8712fd40d
--- /dev/null
+++ b/test/metabase/oauth_server/test_util.clj
@@ -0,0 +1,18 @@
+(ns metabase.oauth-server.test-util
+ "Helpers for tests that exercise the OAuth server."
+ (:require
+ [metabase.test :as mt]))
+
+(defmacro with-oauth-client
+ "Execute `body` with a freshly registered `oauth_client` row, binding `client-id-binding` to its
+ `client_id`, and delete the row when `body` exits. Save test tokens against this client id —
+ see [[metabase.oauth-server.core/resolve-access-token]] for why a token needs a live client."
+ [[client-id-binding] & body]
+ `(mt/with-temp [:model/OAuthClient {~client-id-binding :client_id}
+ {:client_id (str (random-uuid))
+ :redirect_uris ["https://example.com/callback"]
+ :grant_types ["authorization_code"]
+ :response_types ["code"]
+ :scopes ["openid"]
+ :registration_type "static"}]
+ ~@body))
diff --git a/test/metabase/server/middleware/session_oauth_test.clj b/test/metabase/server/middleware/session_oauth_test.clj
index e12fbc668ae..c8afe7b4e6c 100644
--- a/test/metabase/server/middleware/session_oauth_test.clj
+++ b/test/metabase/server/middleware/session_oauth_test.clj
@@ -4,14 +4,16 @@
OAuth scopes are mapped onto `:token-scopes` for the scope-enforcement middleware."
(:require
[clojure.test :refer [deftest is testing]]
- ;; Loaded for its load-time side effects: the OAuth provider's scopes-supported is derived by
- ;; reflecting over the agent API route table (see [[metabase.mcp.core/all-scopes]]), which in a
- ;; full server boot is loaded by [[metabase.api-routes.routes]]. The isolated test classpath does
- ;; not mount the routes, so require it here as that route ns does.
+ ;; Loaded for its load-time side effects: it registers the agent API endpoints, from which the
+ ;; OAuth provider derives its scopes-supported (see [[metabase.mcp.core/all-scopes]]). In a full
+ ;; server boot [[metabase.api-routes.routes]] loads it; the isolated test classpath does not
+ ;; mount the routes, so require it here as that route ns does.
[metabase.agent-api.api]
[metabase.api.macros.scope :as scope]
[metabase.initialization-status.core :as init-status]
[metabase.oauth-server.core :as oauth-server]
+ [metabase.oauth-server.events.revoke-on-deactivation] ; for side effects: revokes tokens on deactivation
+ [metabase.oauth-server.test-util :as oauth-server.tu]
[metabase.server.middleware.session :as mw.session]
[metabase.test :as mt]
[oidc-provider.store :as oidc.store]
@@ -31,10 +33,11 @@
(defn- save-access-token!
"Persist an OAuth access token into the live provider's token store (the one [[oauth-server/resolve-access-token]]
- reads from) for the given user, scopes, and expiry (epoch millis)."
- [token user-id scopes expiry]
+ reads from) for the given user, client, scopes, and expiry (epoch millis). `client-id` should come from
+ [[oauth-server.tu/with-oauth-client]]."
+ [token user-id client-id scopes expiry]
(oidc.store/save-access-token (:token-store (oauth-server/get-provider))
- token (str user-id) "test-client" (vec scopes) expiry nil))
+ token (str user-id) client-id (vec scopes) expiry nil))
(defn- revoke-access-token!
"Revoke a token in the live provider's token store, as the `/oauth/revoke` endpoint does on logout."
@@ -82,37 +85,40 @@
(deftest bearer-bridge-full-access-test
(mt/with-temporary-setting-values [site-url "http://localhost:3000"]
(t2/with-transaction [_conn nil {:rollback-only true}]
- (let [user-id (mt/user->id :rasta)
- token (str (random-uuid))]
- (save-access-token! token user-id [oauth-server/full-access-scope] (in-one-hour))
- (let [req (merge-current-user-info (bearer-request token))]
- (testing "resolves the bearer token to the user"
- (is (= user-id (:metabase-user-id req))))
- (testing "marks the request as oauth-authenticated"
- (is (= "oauth" (:embedding/auth-method req))))
- (testing "grants unrestricted token-scopes so the whole REST API is reachable"
- (is (= #{::scope/unrestricted} (:token-scopes req)))))))))
+ (oauth-server.tu/with-oauth-client [client-id]
+ (let [user-id (mt/user->id :rasta)
+ token (str (random-uuid))]
+ (save-access-token! token user-id client-id [oauth-server/full-access-scope] (in-one-hour))
+ (let [req (merge-current-user-info (bearer-request token))]
+ (testing "resolves the bearer token to the user"
+ (is (= user-id (:metabase-user-id req))))
+ (testing "marks the request as oauth-authenticated"
+ (is (= "oauth" (:embedding/auth-method req))))
+ (testing "grants unrestricted token-scopes so the whole REST API is reachable"
+ (is (= #{::scope/unrestricted} (:token-scopes req))))))))))
(deftest bearer-bridge-narrow-scope-test
(mt/with-temporary-setting-values [site-url "http://localhost:3000"]
(t2/with-transaction [_conn nil {:rollback-only true}]
- (let [user-id (mt/user->id :rasta)
- token (str (random-uuid))]
- (save-access-token! token user-id ["agent:query:execute"] (in-one-hour))
- (let [req (merge-current-user-info (bearer-request token))]
- (testing "resolves the user but only carries the narrow granted scopes"
- (is (= user-id (:metabase-user-id req)))
- (is (= #{"agent:query:execute"} (:token-scopes req)))))))))
+ (oauth-server.tu/with-oauth-client [client-id]
+ (let [user-id (mt/user->id :rasta)
+ token (str (random-uuid))]
+ (save-access-token! token user-id client-id ["agent:query:execute"] (in-one-hour))
+ (let [req (merge-current-user-info (bearer-request token))]
+ (testing "resolves the user but only carries the narrow granted scopes"
+ (is (= user-id (:metabase-user-id req)))
+ (is (= #{"agent:query:execute"} (:token-scopes req))))))))))
(deftest bearer-bridge-expired-token-test
(mt/with-temporary-setting-values [site-url "http://localhost:3000"]
(t2/with-transaction [_conn nil {:rollback-only true}]
- (let [token (str (random-uuid))]
- (save-access-token! token (mt/user->id :rasta) [oauth-server/full-access-scope] (one-hour-ago))
- (let [req (merge-current-user-info (bearer-request token))]
- (testing "an expired access token does not authenticate"
- (is (nil? (:metabase-user-id req)))
- (is (nil? (:token-scopes req)))))))))
+ (oauth-server.tu/with-oauth-client [client-id]
+ (let [token (str (random-uuid))]
+ (save-access-token! token (mt/user->id :rasta) client-id [oauth-server/full-access-scope] (one-hour-ago))
+ (let [req (merge-current-user-info (bearer-request token))]
+ (testing "an expired access token does not authenticate"
+ (is (nil? (:metabase-user-id req)))
+ (is (nil? (:token-scopes req))))))))))
(deftest bearer-bridge-unknown-token-test
(mt/with-temporary-setting-values [site-url "http://localhost:3000"]
@@ -124,16 +130,34 @@
(deftest bearer-bridge-revoked-token-test
(mt/with-temporary-setting-values [site-url "http://localhost:3000"]
(t2/with-transaction [_conn nil {:rollback-only true}]
- (let [user-id (mt/user->id :rasta)
- token (str (random-uuid))]
- (save-access-token! token user-id [oauth-server/full-access-scope] (in-one-hour))
- (testing "the token authenticates before it is revoked"
- (is (= user-id (:metabase-user-id (merge-current-user-info (bearer-request token))))))
- (revoke-access-token! token)
- (testing "after revocation (as on logout) the same token no longer authenticates"
- (let [req (merge-current-user-info (bearer-request token))]
- (is (nil? (:metabase-user-id req)))
- (is (nil? (:token-scopes req)))))))))
+ (oauth-server.tu/with-oauth-client [client-id]
+ (let [user-id (mt/user->id :rasta)
+ token (str (random-uuid))]
+ (save-access-token! token user-id client-id [oauth-server/full-access-scope] (in-one-hour))
+ (testing "the token authenticates before it is revoked"
+ (is (= user-id (:metabase-user-id (merge-current-user-info (bearer-request token))))))
+ (revoke-access-token! token)
+ (testing "after revocation (as on logout) the same token no longer authenticates"
+ (let [req (merge-current-user-info (bearer-request token))]
+ (is (nil? (:metabase-user-id req)))
+ (is (nil? (:token-scopes req))))))))))
+
+(deftest bearer-bridge-deactivation-revokes-test
+ (testing "deactivating the user revokes the bearer token, and reactivating does NOT revive it (SEC-863)"
+ (mt/with-temporary-setting-values [site-url "http://localhost:3000"]
+ (t2/with-transaction [_conn nil {:rollback-only true}]
+ (oauth-server.tu/with-oauth-client [client-id]
+ (let [user-id (mt/user->id :rasta)
+ token (str (random-uuid))]
+ (save-access-token! token user-id client-id [oauth-server/full-access-scope] (in-one-hour))
+ (testing "authenticates before deactivation"
+ (is (= user-id (:metabase-user-id (merge-current-user-info (bearer-request token))))))
+ (t2/update! :model/User user-id {:is_active false})
+ (testing "after deactivation the token no longer authenticates"
+ (is (nil? (:metabase-user-id (merge-current-user-info (bearer-request token))))))
+ (t2/update! :model/User user-id {:is_active true})
+ (testing "after reactivation the same token STILL does not authenticate"
+ (is (nil? (:metabase-user-id (merge-current-user-info (bearer-request token))))))))))))
(deftest bearer-bridge-precedence-test
(testing "session/api-key auth takes precedence — bearer resolution is not even attempted"
diff --git a/test/metabase/server/middleware/session_test.clj b/test/metabase/server/middleware/session_test.clj
index b6546108d62..a02e5b40ba9 100644
--- a/test/metabase/server/middleware/session_test.clj
+++ b/test/metabase/server/middleware/session_test.clj
@@ -13,6 +13,7 @@
[metabase.request.core :as request]
[metabase.server.middleware.session :as mw.session]
[metabase.session.core :as session]
+ [metabase.session.events.revoke-on-deactivation] ; for side effects: deletes sessions on deactivation
[metabase.test :as mt]
[metabase.test.fixtures :as fixtures]
[metabase.util.encryption :as encryption]
@@ -35,6 +36,25 @@
(def ^:private test-session-key-hashed (session/hash-session-key test-session-key))
(def ^:private test-session-id "abcd1234")
+(deftest session-deactivation-revokes-test
+ (init-status/set-complete!)
+ (testing "deactivating the user deletes the session; reactivating does NOT revive it (SEC-863)"
+ (mt/with-temp [:model/User {user-id :id} {:is_active true}]
+ (let [session-key (str (random-uuid))]
+ (t2/insert! (t2/table-name :model/Session)
+ {:id (session/generate-session-id)
+ :key_hashed (session/hash-session-key session-key)
+ :user_id user-id
+ :created_at :%now})
+ (testing "session authenticates while the user is active"
+ (is (some? (#'mw.session/current-user-info-for-session session-key nil))))
+ (t2/update! :model/User user-id {:is_active false})
+ (testing "after deactivation the session no longer authenticates"
+ (is (nil? (#'mw.session/current-user-info-for-session session-key nil))))
+ (t2/update! :model/User user-id {:is_active true})
+ (testing "after reactivation the same session STILL does not authenticate"
+ (is (nil? (#'mw.session/current-user-info-for-session session-key nil))))))))
+
(deftest session-expired-test
(init-status/set-complete!)
(testing "Session expiration time = 1 minute"
@@ -231,6 +251,27 @@
:message "Ignoring invalid API Key"}]
(messages))))))
+(deftest api-key-lifecycle-follows-synthetic-user-not-creator-test
+ (testing "an API key is gated by its own synthetic user, not the admin who created it (SEC-863)"
+ (mt/with-temp [:model/User {synthetic-id :id} {}
+ :model/User {creator-id :id} {}
+ :model/ApiKey _ {:name "An API Key"
+ :user_id synthetic-id
+ :creator_id creator-id
+ :updated_by_id creator-id
+ ::api-key/unhashed-key (u.secret/secret "mb_foobar123")}]
+ (let [authed? (fn [] (mt/with-premium-features #{}
+ (boolean (:metabase-user-id
+ (#'mw.session/merge-current-user-info {:headers {"x-api-key" "mb_foobar123"}})))))]
+ (testing "authenticates while its synthetic user is active"
+ (is (authed?)))
+ (testing "deactivating the creator does NOT revoke the key — creator_id is attribution only"
+ (t2/update! :model/User creator-id {:is_active false})
+ (is (authed?)))
+ (testing "deactivating the key's own synthetic user DOES revoke it"
+ (t2/update! :model/User synthetic-id {:is_active false})
+ (is (not (authed?))))))))
+
(deftest ^:parallel current-user-info-for-api-key-test-2
(mt/with-temp [:model/ApiKey _ {:name "An API Key without an internal user"
:user_id nil
diff --git a/test/metabase/session/events/revoke_on_deactivation_test.clj b/test/metabase/session/events/revoke_on_deactivation_test.clj
new file mode 100644
index 00000000000..8b3432c590c
--- /dev/null
+++ b/test/metabase/session/events/revoke_on_deactivation_test.clj
@@ -0,0 +1,44 @@
+(ns metabase.session.events.revoke-on-deactivation-test
+ (:require
+ [clojure.test :refer [deftest is testing]]
+ [metabase.events.core :as events]
+ [metabase.session.core :as session]
+ [metabase.session.events.revoke-on-deactivation] ; for side effects: registers the event subscriber
+ [metabase.test :as mt]
+ [toucan2.core :as t2]))
+
+(defn- insert-session!
+ "Insert a session row for `user-id` (bypassing model hooks, as the other session tests do) and return its id."
+ [user-id]
+ (let [id (session/generate-session-id)]
+ (t2/insert! (t2/table-name :model/Session)
+ {:id id
+ :key_hashed (session/hash-session-key (str (random-uuid)))
+ :user_id user-id
+ :created_at :%now})
+ id))
+
+(deftest revoke-on-event-test
+ (testing ":event/user-credentials-revoked deletes the user's sessions, leaving other users' untouched"
+ (mt/with-temp [:model/User {victim :id} {}
+ :model/User {bystander :id} {}]
+ (let [victim-session (insert-session! victim)
+ bystander-session (insert-session! bystander)]
+ (events/publish-event! :event/user-credentials-revoked {:user-id victim})
+ (is (not (t2/exists? :model/Session :id victim-session))
+ "victim's session is deleted")
+ (is (t2/exists? :model/Session :id bystander-session)
+ "an unrelated user's session is untouched")))))
+
+(deftest deactivation-revokes-and-reactivation-does-not-revive-test
+ (testing "deactivating a user deletes their sessions; reactivating does NOT bring them back (SEC-863)"
+ (mt/with-temp [:model/User {user-id :id} {:is_active true}]
+ (let [session-id (insert-session! user-id)]
+ (is (t2/exists? :model/Session :id session-id)
+ "session exists while the user is active")
+ (t2/update! :model/User user-id {:is_active false})
+ (is (not (t2/exists? :model/Session :id session-id))
+ "deactivation revokes the session")
+ (t2/update! :model/User user-id {:is_active true})
+ (is (not (t2/exists? :model/Session :id session-id))
+ "reactivation does not revive the pre-deactivation session")))))