Skip to content

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

cli oauth (#75451)

Aleksandr Lesnenko31f7b5d27e13
diff --git a/.clj-kondo/config/modules/config.edn b/.clj-kondo/config/modules/config.edn
index d7d843b1de0..5e0a5e9c8eb 100644
--- a/.clj-kondo/config/modules/config.edn
+++ b/.clj-kondo/config/modules/config.edn
@@ -1448,6 +1448,7 @@
metabase.oauth-server.core
metabase.oauth-server.init}
:uses #{api
+ api-scope
appearance
mcp
models
diff --git a/src/metabase/mcp/api.clj b/src/metabase/mcp/api.clj
index e28fcc75017..629cfe34ca3 100644
--- a/src/metabase/mcp/api.clj
+++ b/src/metabase/mcp/api.clj
@@ -5,7 +5,6 @@
[clojure.core.async :as a]
[clojure.string :as str]
[compojure.response :as compojure.response]
- [java-time.api :as t]
[metabase.api.common :as api]
[metabase.api.macros.scope :as scope]
[metabase.api.open-api :as open-api]
@@ -22,7 +21,6 @@
[metabase.util :as u]
[metabase.util.json :as json]
[metabase.util.log :as log]
- [oidc-provider.store :as oidc.store]
[throttle.core :as throttle])
(:import
(java.io BufferedWriter OutputStreamWriter)
@@ -33,19 +31,10 @@
;;; -------------------------------------------------- Auth --------------------------------------------------------
(defn- validate-bearer-token
- "Look up and validate an OAuth bearer token. Returns `{:user-id <int> :scopes <set>}` on success, nil on failure."
+ "Look up and validate an OAuth bearer token. Returns `{:user-id <int> :scopes <set>}` on success, nil on failure.
+ Delegates to the shared resolver so MCP and the core session middleware agree on token validity and scopes."
[token-string]
- (when-let [provider (oauth-server/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)))
- (let [user-id (some-> (:user-id token-data) parse-long)
- scopes (when-let [scope-vec (:scope token-data)]
- (into #{} scope-vec))]
- (when user-id
- {:user-id user-id
- :scopes (or scopes #{})})))))))
+ (oauth-server/resolve-access-token token-string))
;;; ------------------------------------------------- JSON-RPC 2.0 --------------------------------------------------
diff --git a/src/metabase/oauth_server/api/oauth.clj b/src/metabase/oauth_server/api/oauth.clj
index ec8c81b9dad..c720fb35feb 100644
--- a/src/metabase/oauth_server/api/oauth.clj
+++ b/src/metabase/oauth_server/api/oauth.clj
@@ -5,6 +5,7 @@
[buddy.core.mac :as mac]
[buddy.core.nonce :as nonce]
[clojure.string :as str]
+ [metabase.api-scope.core :as api-scope]
[metabase.api.macros :as api.macros]
[metabase.oauth-server.consent-page :as consent-page]
[metabase.oauth-server.core :as oauth-server]
@@ -86,6 +87,23 @@
(str (subs s 0 (- max-len 3)) "...")
s))
+(defn- requested-scope-descriptions
+ "Turn the space-separated OAuth `scope` value into a vector of `{:scope :description}` maps for the
+ consent page, so the user sees exactly what the client is asking for. Falls back to the raw scope
+ string when a scope has no registered human-readable description. Returns nil when no scope was
+ requested."
+ [scope-param]
+ (when-let [scope-str (some-> scope-param str not-empty)]
+ (->> (str/split scope-str #"\s+")
+ (remove str/blank?)
+ distinct
+ (mapv (fn [s]
+ {:scope s
+ :description (or (some-> (api-scope/scope-description s) str) s)
+ ;; Flag the broad first-party grant so the consent page can warn about it without
+ ;; hardcoding the scope string in the view.
+ :full-access? (= s oauth-server/full-access-scope)})))))
+
(defn- redirect-authorization-decision
"Issue a 302 redirect for an approved or denied authorization decision, clearing the CSRF cookie."
[provider parsed approved request]
@@ -238,10 +256,10 @@
:headers {"Content-Type" "text/html; charset=utf-8"}
:body (consent-page/render-consent-page
{:client-name (some-> (:client-name client) (truncate 64))
- :client-id (:client_id parsed)
:nonce (:nonce request)
:csrf-token csrf-token
:params-sig params-sig
+ :scopes (requested-scope-descriptions (:scope oauth-params))
:oauth-params oauth-params})}
(response/set-cookie csrf-cookie-name csrf-token (csrf-cookie-opts 600))))
(catch ExceptionInfo e
diff --git a/src/metabase/oauth_server/consent_page.clj b/src/metabase/oauth_server/consent_page.clj
index 70f2b65c569..071ee249521 100644
--- a/src/metabase/oauth_server/consent_page.clj
+++ b/src/metabase/oauth_server/consent_page.clj
@@ -74,9 +74,30 @@
:default-logo? (= logo-url default-logo-url)
:brand-color (sanitize-css-color (get colors "brand"))}))
+(defn- render-scope-list
+ "Render the requested OAuth scopes as a hiccup list so the user sees exactly what they're granting.
+ `scopes` is a vector of `{:scope <string> :description <localized-string-or-raw-scope>}` maps.
+
+ Shows the human description and the raw scope string: the description is readable, the raw string
+ is the precise, unambiguous grant the token will carry — both matter when approving a broad scope.
+ When a scope has no registered description (it falls back to the raw string) the raw span is
+ omitted to avoid showing the same value twice."
+ [scopes]
+ (when (seq scopes)
+ [:ul.scopes
+ (for [{:keys [scope description full-access?]} scopes]
+ [:li (when full-access? {:class "full"})
+ [:span {:class (if full-access? "dot full" "dot")}]
+ (if full-access? [:strong description] [:span description])
+ (when (not= description scope)
+ [:span.raw scope])])]))
+
(defn render-consent-page
- "Render a server-side HTML consent page for the OAuth authorization flow."
- [{:keys [client-name client-id oauth-params nonce csrf-token params-sig]}]
+ "Render a server-side HTML consent page for the OAuth authorization flow.
+
+ `scopes` is a vector of `{:scope :description}` maps describing what the client is requesting; it is
+ shown to the user so a broad grant (e.g. full account access) is never approved blindly."
+ [{:keys [client-name oauth-params nonce csrf-token params-sig scopes]}]
(let [{:keys [font-family logo-url default-logo? brand-color]} (appearance-settings)
css-font-family (css-escape-font-name font-family)]
(str
@@ -100,10 +121,23 @@
padding: 2.5rem; max-width: 440px; width: 100%; margin: 1rem; }
.logo { display: flex; justify-content: center; margin-bottom: 1.5rem; }
.logo img { max-height: 32px; max-width: 100%; min-height: 100%; height: auto; }
- h1 { font-size: 1.25rem; font-weight: 700; color: #2e353b; text-align: center; margin-bottom: 0.25rem; }
- .client-id { text-align: center; font-size: 0.75rem; color: #949aab; margin-bottom: 1rem;
- font-family: monospace; word-break: break-all; }
+ h1 { font-size: 1.25rem; font-weight: 700; color: #2e353b; text-align: center; margin-bottom: 0.5rem; }
.subtitle { text-align: center; font-size: 0.875rem; line-height: 1.5; color: #696e7b; margin-bottom: 1.5rem; }
+ .scopes { list-style: none; margin: 0 0 1.5rem; padding: 0;
+ border: 1px solid #f0f0f0; border-radius: 8px; }
+ .scopes li { display: flex; align-items: baseline; gap: 0.5rem;
+ padding: 0.75rem 1rem; font-size: 0.875rem; color: #4c5773; }
+ .scopes li + li { border-top: 1px solid #f0f0f0; }
+ .scopes .dot { flex: 0 0 auto; width: 6px; height: 6px; border-radius: 50%;
+ background: " brand-color "; transform: translateY(-1px); }
+ .scopes .raw { font-family: monospace; font-size: 0.75rem; color: #949aab; }
+ .scopes li.full strong { color: #2e353b; }
+ .scopes .dot.full { background: #e35a4c; width: 8px; height: 8px; }
+ .warning { display: flex; gap: 0.5rem; align-items: flex-start;
+ background: #fdf3f2; border: 1px solid #f7d3cf; border-radius: 8px;
+ padding: 0.75rem 1rem; margin-bottom: 1.5rem;
+ font-size: 0.8125rem; line-height: 1.45; color: #883b34; }
+ .warning .mark { flex: 0 0 auto; font-weight: 700; }
.actions { display: flex; gap: 0.75rem; }
button { flex: 1; padding: 0.75rem 1rem; border-radius: 8px; font-size: 0.875rem; font-weight: 700;
font-family: inherit; cursor: pointer;
@@ -119,9 +153,15 @@
(h/raw svg)
[:img {:src logo-url :alt "Logo" :height "32"}])]
[:h1 "Authorize " (or client-name "Unknown Application") "?"]
- (when client-id [:p.client-id client-id])
- [:p.subtitle "This MCP client is requesting to be authorized. If you approve, it will be able to access resources from "
- [:strong (appearance/application-name)] " on your behalf."]
+ [:p.subtitle (or client-name "This application") " is requesting access to "
+ [:strong (appearance/application-name)] " on your behalf:"]
+ (when (some :full-access? scopes)
+ [:div.warning
+ [:span.mark "!"]
+ [:span "This grants " [:strong "complete access to your account"] " — anything you can do, "
+ (or client-name "this application") " can do, including reading and changing all data you "
+ "can reach. Only approve it for a tool you trust and control."]])
+ (render-scope-list scopes)
[:form {:method "POST" :action "/oauth/authorize/decision"}
[:input {:type "hidden" :name "csrf_token" :value csrf-token}]
[:input {:type "hidden" :name "params_sig" :value params-sig}]
diff --git a/src/metabase/oauth_server/core.clj b/src/metabase/oauth_server/core.clj
index 37c3377025e..9d28598872d 100644
--- a/src/metabase/oauth_server/core.clj
+++ b/src/metabase/oauth_server/core.clj
@@ -1,15 +1,24 @@
(ns metabase.oauth-server.core
(:require
[clojure.string :as str]
+ [java-time.api :as t]
[metabase.mcp.core :as mcp]
+ [metabase.oauth-server.scopes :as scopes]
[metabase.oauth-server.settings :as oauth-settings]
[metabase.oauth-server.store :as store]
[metabase.system.core :as system]
[metabase.util :as u]
- [oidc-provider.core :as oidc]))
+ [oidc-provider.core :as oidc]
+ [oidc-provider.store :as oidc.store]))
(set! *warn-on-reflection* true)
+(def full-access-scope
+ "The OAuth scope string that grants a bearer token full, user-equivalent access to the
+ general REST API. The session-middleware bearer bridge maps a token carrying this scope
+ onto the unrestricted scope sentinel (see [[metabase.server.middleware.session]])."
+ scopes/full-access)
+
;; Cache holds `{:site-url <string>, :provider <Provider>}`. Every endpoint baked into the provider config is
;; derived from the Site URL (see [[build-provider-config]]), so a changed Site URL must rebuild the provider --
;; otherwise discovery keeps advertising the stale issuer/endpoints (e.g. http:// behind a TLS-terminating proxy
@@ -17,11 +26,20 @@
(defonce ^:private provider (atom nil))
(defn all-agent-scopes
- "All supported OAuth scopes derived from defendpoint metadata on the agent API,
- plus scopes from MCP UI resources (e.g. visualize_query)."
+ "All agent OAuth scopes derived from defendpoint metadata on the agent API,
+ plus scopes from MCP UI resources (e.g. visualize_query). These are the scopes a
+ dynamically-registered MCP client is granted by default at registration time."
[]
(mcp/all-scopes))
+(defn supported-scopes
+ "All OAuth scopes advertised in the server's discovery metadata (`scopes-supported`):
+ the agent/MCP scopes plus the top-level first-party scopes (e.g. `mb:full`). This is a
+ superset of [[all-agent-scopes]] — the extra scopes are not part of the default grant a
+ client receives at registration, so a client must explicitly request them."
+ []
+ (conj (vec (all-agent-scopes)) full-access-scope))
+
(defn- build-provider-config
"Build the configuration map for the OAuth provider from Metabase settings."
[]
@@ -37,8 +55,8 @@
:client-store (store/create-client-store)
:code-store (store/create-authorization-code-store)
:token-store (store/create-token-store)
- ;; OIDC provider requires a vector; all-scopes returns a sorted set.
- :scopes-supported (vec (all-agent-scopes))
+ ;; OIDC provider requires a vector.
+ :scopes-supported (supported-scopes)
:rotate-refresh-tokens true}))
(defn- create-provider
@@ -68,3 +86,22 @@
(when-let [auth (get-in request [:headers "authorization"])]
(when (str/starts-with? (u/lower-case-en auth) "bearer ")
(str/trim (subs auth 7)))))
+
+(defn resolve-access-token
+ "Validate an OAuth bearer access token string against the token store. Returns
+ `{:user-id <int> :scopes <set-of-strings>}` on success, or nil on failure (unknown,
+ expired, or revoked token, or a token with no associated user).
+
+ This is the single token-resolution lookup shared by the MCP transport and the core
+ session middleware's bearer-token bridge — keep it the only place an access token is
+ turned into a user identity + scope set."
+ [token-string]
+ (when (seq token-string)
+ (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-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/scopes.clj b/src/metabase/oauth_server/scopes.clj
new file mode 100644
index 00000000000..7d0df9a9de7
--- /dev/null
+++ b/src/metabase/oauth_server/scopes.clj
@@ -0,0 +1,15 @@
+(ns metabase.oauth-server.scopes
+ "Top-level (non-agent) OAuth scopes issued by the embedded authorization server.
+
+ The granular `agent:*` scopes used by Metabot tools / the MCP server are declared in
+ [[metabase.metabot.scope]]. This namespace declares the broader, first-party grants
+ used by clients such as the Metabase CLI, where the credential is meant to act as the
+ human user across the whole REST API rather than a narrow set of agent endpoints."
+ (:require
+ [metabase.api-scope.core :as api-scope]
+ [metabase.util.i18n :refer [deferred-tru]]))
+
+(set! *warn-on-reflection* true)
+
+(api-scope/defscope full-access "mb:full"
+ (deferred-tru "Full access to Metabase as your user account"))
diff --git a/src/metabase/server/middleware/session.clj b/src/metabase/server/middleware/session.clj
index caa566c8ee5..c553ef09de1 100644
--- a/src/metabase/server/middleware/session.clj
+++ b/src/metabase/server/middleware/session.clj
@@ -22,9 +22,11 @@
[metabase.analytics.core :as analytics]
[metabase.api-keys.core :as api-key]
[metabase.api-keys.schema :as api-keys.schema]
+ [metabase.api.macros.scope :as scope]
[metabase.app-db.core :as mdb]
[metabase.config.core :as config]
[metabase.initialization-status.core :as init-status]
+ [metabase.oauth-server.core :as oauth-server]
[metabase.premium-features.core :as premium-features]
[metabase.request.core :as request]
[metabase.request.schema :as request.schema]
@@ -173,6 +175,31 @@
[:= :pgm.user_id :user.id]
[:is :pgm.is_group_manager true]]))))))))
+;; Like the session/api-key queries above, this runs on every OAuth-bearer-authenticated API request, so
+;; compile it to SQL once. Keyed on the resolved user id from the OAuth access token.
+(def ^:private ^{:arglists '([enable-advanced-permissions?])} user-data-for-id-query
+ (memoize
+ (fn [enable-advanced-permissions?]
+ (first
+ (t2.pipeline/compile*
+ (cond-> {:select [[:user.id :metabase-user-id]
+ [:user.is_superuser :is-superuser?]
+ [:user.is_data_analyst :is-data-analyst?]
+ [:user.locale :user-locale]]
+ :from [[:core_user :user]]
+ :where [:and
+ [:= :user.is_active true]
+ [:= :user.id [:raw "?"]]]
+ :limit [:inline 1]}
+ enable-advanced-permissions?
+ (->
+ (sql.helpers/select
+ [:pgm.is_group_manager :is-group-manager?])
+ (sql.helpers/left-join
+ [:permissions_group_membership :pgm] [:and
+ [:= :pgm.user_id :user.id]
+ [:is :pgm.is_group_manager true]]))))))))
+
(defn- valid-session-key?
"Validates that the given session-key looks like it could be a session id. Returns a 403 if it does not.
@@ -241,21 +268,63 @@
(-> user-info
(dissoc :api-key)))))))
+(def ^:private full-access-token-scopes
+ "The `:token-scopes` value that grants a bearer-authenticated request access to the general
+ REST API as its user. The `::scope/unrestricted` keyword sentinel (not the `\"*\"` string)
+ is the only thing that lets a scoped token through endpoints that declare no `:scope` (see
+ [[metabase.api.macros.scope/ensure-scopes-checked]])."
+ #{::scope/unrestricted})
+
+(defn- oauth-token->token-scopes
+ "Map the OAuth scopes granted to a bearer access token onto the `:token-scopes` value the API
+ scope middleware understands. A token carrying the full-access scope (`mb:full`) becomes the
+ unrestricted sentinel — reachable across the whole REST API as the user. Any narrower scope
+ set is passed through verbatim, so the token can reach only the agent endpoints that opt into
+ those scopes and is rejected elsewhere by `ensure-scopes-checked`.
+
+ This mapping is the single trust hinge for OAuth bearer auth on the general API; keep it here
+ and unit-test the two directions (full ⇒ unrestricted, narrow ⇒ passed through) so the
+ security invariant can't silently regress."
+ [granted-scopes]
+ (if (contains? granted-scopes oauth-server/full-access-scope)
+ full-access-token-scopes
+ granted-scopes))
+
+(mu/defn- current-user-info-for-oauth-token :- [:maybe ::request.schema/current-user-info]
+ "Return current-user-info for a valid OAuth bearer access token on `request`, or nil. Mirrors the
+ shape returned by the session/api-key resolvers and additionally attaches `:token-scopes`, so the
+ merged request carries both the user identity and the access the token was granted. This is the
+ only place an OAuth access token authenticates a request to the general (`/api/*`) API."
+ [request]
+ (when (init-status/complete?)
+ (when-let [token (oauth-server/extract-bearer-token request)]
+ (when-let [{:keys [user-id scopes]} (oauth-server/resolve-access-token token)]
+ (some-> (t2/query-one (cons (user-data-for-id-query (premium-features/enable-advanced-permissions?))
+ [user-id]))
+ (m/update-existing :is-group-manager? boolean)
+ (assoc :token-scopes (oauth-token->token-scopes scopes)))))))
+
(defn- auth-method
- [session-info api-key-info embedding-route]
+ [session-info api-key-info oauth-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")))
+ api-key-info "api-key"
+ oauth-info "oauth")))
(defn- merge-current-user-info
[{: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 is the lowest-precedence path: only consulted when there's no session or API key.
+ oauth-info (when-not (or session-info api-key-info)
+ (current-user-info-for-oauth-token request))
embedding-route (analytics/get-route)
- auth-method (auth-method session-info api-key-info embedding-route)]
+ auth-method (auth-method session-info api-key-info oauth-info embedding-route)]
(merge
request
- (dissoc (or session-info api-key-info) :auth-provider)
+ ;; 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) :auth-provider)
(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))
@@ -263,7 +332,8 @@
(defn wrap-current-user-info
"Add `:metabase-user-id`, `:is-superuser?`, `:is-group-manager?` and `:user-locale` to the request if a valid session
- token OR a valid API key was passed."
+ token, API key, OR OAuth bearer access token was passed. A bearer token additionally sets `:token-scopes` (the access
+ it was granted); precedence is session > API key > bearer."
[handler]
(fn [request respond raise]
(let [request' (tracing/with-span :db-app "db-app.session-lookup" {}
diff --git a/test/metabase/oauth_server/consent_page_test.clj b/test/metabase/oauth_server/consent_page_test.clj
index 186dc65dfa6..874919c9a6c 100644
--- a/test/metabase/oauth_server/consent_page_test.clj
+++ b/test/metabase/oauth_server/consent_page_test.clj
@@ -76,3 +76,42 @@
:csrf-token "test-csrf"}))]
(is (re-find #"http://localhost:3000/app/assets/img/custom\.png" html)
"relative path should be resolved to absolute URL")))))
+
+(defn- render-with-scopes! [scopes]
+ (mt/with-temporary-setting-values [site-url "http://localhost:3000"]
+ (consent-page/render-consent-page
+ {:client-name "Test App"
+ :oauth-params {:response_type "code" :client_id "abc123" :scope "mb:full"}
+ :nonce "test-nonce"
+ :csrf-token "test-csrf"
+ :scopes scopes})))
+
+(deftest consent-page-shows-requested-scopes-test
+ (testing "each requested scope's human description is shown so a broad grant is not approved blindly"
+ (let [html (render-with-scopes! [{:scope "mb:full" :description "Full access to Metabase as your user account"}
+ {:scope "agent:query" :description "Construct and execute queries"}])]
+ (is (re-find #"Full access to Metabase as your user account" html))
+ (is (re-find #"Construct and execute queries" html))
+ (testing "the raw scope string is shown alongside the description"
+ (is (re-find #"mb:full" html)))))
+ (testing "a scope with no human description falls back to the raw string and is not duplicated"
+ (let [html (render-with-scopes! [{:scope "weird:unlabeled" :description "weird:unlabeled"}])]
+ (is (re-find #"weird:unlabeled" html))
+ (is (not (re-find #"raw\">weird:unlabeled" html))
+ "should not also render the raw span when description equals the scope")))
+ (testing "no scope list is rendered when none were requested"
+ (is (not (re-find #"class=\"scopes\"" (render-with-scopes! nil))))))
+
+(deftest consent-page-full-access-warning-test
+ (testing "a full-access scope shows an explicit warning that it grants complete account access"
+ (let [html (render-with-scopes! [{:scope "mb:full"
+ :description "Full access to Metabase as your user account"
+ :full-access? true}])]
+ (is (re-find #"complete access to your account" html))
+ (is (re-find #"class=\"warning\"" html))))
+ (testing "a narrow scope shows no full-access warning"
+ (let [html (render-with-scopes! [{:scope "agent:query"
+ :description "Construct and execute queries"
+ :full-access? false}])]
+ (is (not (re-find #"class=\"warning\"" html)))
+ (is (not (re-find #"complete access to your account" html))))))
diff --git a/test/metabase/server/middleware/session_oauth_test.clj b/test/metabase/server/middleware/session_oauth_test.clj
new file mode 100644
index 00000000000..e12fbc668ae
--- /dev/null
+++ b/test/metabase/server/middleware/session_oauth_test.clj
@@ -0,0 +1,149 @@
+(ns metabase.server.middleware.session-oauth-test
+ "Tests for the OAuth bearer-token bridge in the core session middleware — the single place an OAuth
+ access token authenticates a request to the general (`/api/*`) API, and the single place the granted
+ 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.
+ [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.server.middleware.session :as mw.session]
+ [metabase.test :as mt]
+ [oidc-provider.store :as oidc.store]
+ [toucan2.core :as t2]))
+
+(set! *warn-on-reflection* true)
+
+;; The OAuth bearer path is gated on initialization being complete (like the session/api-key paths);
+;; the isolated test runner never boots the web server, so mark init complete as session_test does.
+(init-status/set-complete!)
+
+(def ^:private merge-current-user-info #'mw.session/merge-current-user-info)
+(def ^:private oauth-token->token-scopes #'mw.session/oauth-token->token-scopes)
+
+(defn- bearer-request [token]
+ {:headers {"authorization" (str "Bearer " token)}})
+
+(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]
+ (oidc.store/save-access-token (:token-store (oauth-server/get-provider))
+ token (str user-id) "test-client" (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."
+ [token]
+ (oidc.store/revoke-token (:token-store (oauth-server/get-provider)) token))
+
+;; Wall-clock epoch millis for token expiry timestamps (not duration measurements) — use Date/inst-ms
+;; rather than System/currentTimeMillis, matching the oauth-server store tests.
+(defn- now-ms [] (inst-ms (java.util.Date.)))
+(defn- in-one-hour [] (+ (now-ms) 3600000))
+(defn- one-hour-ago [] (- (now-ms) 3600000))
+
+;;; ----------------------------------------- scope mapping (the trust hinge) -----------------------------------------
+
+(deftest oauth-token->token-scopes-test
+ (testing "a token carrying the full-access scope maps to the unrestricted sentinel (general REST reachable)"
+ (is (= #{::scope/unrestricted}
+ (oauth-token->token-scopes #{oauth-server/full-access-scope})))
+ (is (= #{::scope/unrestricted}
+ (oauth-token->token-scopes #{oauth-server/full-access-scope "agent:query:execute"}))))
+ (testing "any narrower scope set is passed through verbatim (only opted-in agent endpoints reachable)"
+ (is (= #{"agent:query:execute"}
+ (oauth-token->token-scopes #{"agent:query:execute"})))
+ (is (= #{} (oauth-token->token-scopes #{})))))
+
+(deftest token-scopes-satisfy-scope-middleware-test
+ (testing "the full-access mapping passes endpoints that declare no :scope; a narrow one is rejected"
+ (let [reached (fn [token-scopes]
+ (let [p (promise)
+ wrapped (scope/ensure-scopes-checked
+ (fn [_ respond _] (respond {:status 200})))]
+ (wrapped {:token-scopes token-scopes}
+ (fn [resp] (deliver p (:status resp)))
+ (fn [e] (deliver p e)))
+ @p))]
+ (is (= 200 (reached (oauth-token->token-scopes #{oauth-server/full-access-scope}))))
+ (is (= 403 (reached (oauth-token->token-scopes #{"agent:query:execute"})))))))
+
+;;; -------------------------------------------- end-to-end bridge (DB-backed) ----------------------------------------
+
+;; The bearer bridge builds the OAuth provider (via `get-provider`), whose config derives its
+;; issuer/endpoints from `site-url` — unset, that fails the provider's `ProviderSetup` schema. Set
+;; it for every test that resolves a token, matching the other oauth-server tests.
+
+(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)))))))))
+
+(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)))))))))
+
+(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)))))))))
+
+(deftest bearer-bridge-unknown-token-test
+ (mt/with-temporary-setting-values [site-url "http://localhost:3000"]
+ (let [req (merge-current-user-info (bearer-request (str (random-uuid))))]
+ (testing "an unknown bearer token does not authenticate"
+ (is (nil? (:metabase-user-id req)))
+ (is (nil? (:token-scopes req)))))))
+
+(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)))))))))
+
+(deftest bearer-bridge-precedence-test
+ (testing "session/api-key auth takes precedence — bearer resolution is not even attempted"
+ (let [called? (atom false)]
+ (with-redefs [oauth-server/resolve-access-token (fn [_] (reset! called? true) nil)
+ ;; pretend an API key authenticated the request
+ mw.session/current-user-info-for-api-key (fn [_] {:metabase-user-id 99 :is-superuser? false})]
+ (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 7bd72714efa..8c631a73493 100644
--- a/test/metabase/server/middleware/session_test.clj
+++ b/test/metabase/server/middleware/session_test.clj
@@ -518,21 +518,23 @@
(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 embedding-route expected]
- (= expected (f session-info api-key-info embedding-route))
+ (are [session-info api-key-info oauth-info embedding-route expected]
+ (= expected (f session-info api-key-info oauth-info embedding-route))
;; session-based auth on non-special routes
- {:auth-provider "password"} nil nil "password"
- {:auth-provider "saml"} nil nil "saml"
- {:auth-provider "jwt"} nil nil "jwt"
- {:auth-provider "ldap"} nil nil "ldap"
- {} nil nil "session"
+ {:auth-provider "password"} nil nil nil "password"
+ {:auth-provider "saml"} nil nil nil "saml"
+ {:auth-provider "jwt"} nil nil nil "jwt"
+ {:auth-provider "ldap"} nil nil nil "ldap"
+ {} nil nil nil "session"
;; api-key on non-special route
- nil {} nil "api-key"
+ nil {} nil nil "api-key"
+ ;; oauth bearer on non-special route
+ nil nil {:metabase-user-id 1} nil "oauth"
;; route override: special routes win over credentials
- nil {} "guest-embed" "guest" ; api-key + embed -> guest
- nil nil "guest-embed" "guest" ; anon guest embed
- nil nil "public" "public"
- nil nil "metabot" "metabot"
- nil nil "agent-api" "agent-api"
+ nil {} nil "guest-embed" "guest" ; api-key + embed -> guest
+ nil nil nil "guest-embed" "guest" ; anon guest embed
+ nil nil nil "public" "public"
+ nil nil nil "metabot" "metabot"
+ nil nil nil "agent-api" "agent-api"
;; fully anonymous, non-special route
- nil nil nil nil))))
+ nil nil nil nil nil))))