The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:
TypeScript analyticsbibusiness-intelligencebusinessintelligenceclojuredashboarddatadata-analysisdata-visualizationdatabasemetabasemysqlpostgrespostgresqlreportingslacksql-editorvisualization
Exchange a signed JWT for an MCP token (#84320)
Andrei Simionescu86426c54cc5f
diff --git a/.clj-kondo/config/modules/config.edn b/.clj-kondo/config/modules/config.ednindex ce1c6f3dbb0..850e3e56448 100644--- a/.clj-kondo/config/modules/config.edn+++ b/.clj-kondo/config/modules/config.edn@@ -1461,9 +1461,11 @@mcpmetabot.agent-apimodels+ premium-featuresrequestserversettings+ sso.auth-identitysystemtasktracingdiff --git a/docs/ai/mcp.md b/docs/ai/mcp.mdindex ea65bdaf2cc..901e75659eb 100644--- a/docs/ai/mcp.md+++ b/docs/ai/mcp.md@@ -160,10 +160,41 @@ The consent page lists the permission scopes the client is asking for. Each [too- `agent:sql:run`: write and run raw SQL on your connected databases.- `agent:delivery:write`: create alerts and subscriptions that email or Slack your data. Creating one also needs `agent:query:run`, since it runs a query when it fires.-The consent page may also list `agent:resource:read` (shown as **Read MCP resources**). No tool needs it; it covers the server's own reference material: the list of fields your agent can ask `get_content` to return for each content type.-Most clients ask for all of them. A scope never grants more than your Metabase permissions allow: `agent:sql:run` won't let a client run SQL against a database you can't write native queries on.+### Using the MCP server when embedding Metabase++{% include plans-blockquote.html feature="Headless access with JWT" %}++An agent in your app can use your embedded Metabase's MCP server on behalf of the person signed in to your app.++Your backend [signs a JWT](../people-and-groups/authenticating-with-jwt.md) for the person (as it would for SSO) and posts the JWT to the token endpoint. There's no browser sign-in or consent page.++```+curl https://{your-metabase.example.com}/oauth/token \+ -d grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer \+ -d assertion={signed-jwt}+```++Metabase checks the JWT the same way it does at SSO login, creates or updates the person's account, and returns an `access_token` for the MCP server. The JWT also needs `exp` (expiration time) and `iat` (issued at) claims, and Metabase accepts it for at most three minutes after its `iat`.++The token gets all the [permission scopes](#permission-scopes), unless you ask for fewer with a space-separated `scope` parameter. The token lasts an hour. To get a new one after the token expires, you'll need to sign a fresh JWT.++To request only the scopes for reading content and running queries:++```+curl https://{your-metabase.example.com}/oauth/token \+ -d grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer \+ -d assertion={signed-jwt} \+ --data-urlencode "scope=agent:content:read agent:query:run"+```++Your agent sends the token to the MCP server at `https://{your-metabase.example.com}/api/metabase-mcp` as `Authorization: Bearer {access_token}`.++Each token issued for headless access to the MCP server appears in the [Activity log](../usage-and-performance-tools/usage-analytics-reference.md#activity-log) with the topic `mcp-jwt-token-issued`. Calls made with these tokens appear in [MCP analytics](#mcp-analytics).++People who only use headless access show **Never** under **Last Login** in **Admin > People**.+## Authorization logsTo review which clients have connected, go to **Admin > AI > MCP** and open the **Authorizations** tab. The authorization logs are an audit log of MCP and Agent API client registrations and the authorization decisions people have approved or denied.diff --git a/docs/embedding/tenants.md b/docs/embedding/tenants.mdindex 2df0712d0ce..5840eb5f462 100644--- a/docs/embedding/tenants.md+++ b/docs/embedding/tenants.md@@ -388,6 +388,8 @@ To deactivate a tenant:All tenant users will be deactivated and won't be able to sign in anymore. Tenant users will not be permanently deleted (Metabase does not delete users, only deactivates), so even though the tenant users will be deactivated, you won't be able to create new users with the same email.+Metabase reactivates the tenant and the users deactivated with it on the next SSO sign-in from anyone in the tenant, if [user provisioning](../people-and-groups/authenticating-with-jwt.md#creating-metabase-accounts-with-sso) is on. To keep a tenant deactivated, turn off user provisioning (which also stops Metabase from creating accounts for new people).+## Changing tenant strategy### From single-tenant to multi-tenantdiff --git a/enterprise/backend/src/metabase_enterprise/sso/integrations/jwt.clj b/enterprise/backend/src/metabase_enterprise/sso/integrations/jwt.cljindex 64ca4453e40..51f2c167d86 100644--- a/enterprise/backend/src/metabase_enterprise/sso/integrations/jwt.clj+++ b/enterprise/backend/src/metabase_enterprise/sso/integrations/jwt.clj@@ -9,7 +9,7 @@[metabase.auth-identity.core :as auth-identity][metabase.embedding.settings :as embed.settings][metabase.embedding.util :as embed.util]- [metabase.premium-features.core :as premium-features]+ [metabase.premium-features.core :as premium-features :refer [defenterprise]][metabase.request.core :as request][metabase.util.i18n :refer [tru]][ring.util.response :as response]))@@ -41,6 +41,14 @@[jwt request](-> (session-data jwt (assoc request :token-exchange? true)) :session :key))+(defenterprise jwt-bearer-grant-enabled?+ "Return whether JWT authentication is enabled and configured.++ The JWT bearer grant (RFC 7523) requires this."+ :feature :sso-jwt+ []+ (sso-settings/jwt-enabled-and-configured))+(defn- throw-react-sdk-embedding-disabled[](throwdiff --git a/enterprise/backend/src/metabase_enterprise/sso/providers/jwt.clj b/enterprise/backend/src/metabase_enterprise/sso/providers/jwt.cljindex e9b2c97cd37..9b6bdb020c3 100644--- a/enterprise/backend/src/metabase_enterprise/sso/providers/jwt.clj+++ b/enterprise/backend/src/metabase_enterprise/sso/providers/jwt.clj@@ -2,6 +2,7 @@"JWT authentication provider implementation."(:require[buddy.sign.jwt :as jwt]+ [buddy.sign.util :as buddy-util][metabase-enterprise.sso.db :as sso.db][metabase-enterprise.sso.integrations.sso-utils :as sso-utils][metabase-enterprise.sso.settings :as sso-settings]@@ -24,6 +25,8 @@;; 3 minutes is the time used by Zendesk for their JWT SSO(def ^:private ^:const three-minutes-in-seconds 180)+(def ^:private ^:const clock-skew-in-seconds 60)+(def ^:private ^{:arglists '([])} jwt-attribute-email(comp keyword sso-settings/jwt-attribute-email))@@ -77,8 +80,28 @@{:status-code 401:error :invalid-jwt})))))+(defn- check-exp-and-iat+ "Return the verified `jwt-data` after checking its `exp` and `iat` claims.++ Both claims must be present. An `iat` up to [[clock-skew-in-seconds]] seconds ahead of now is accepted+ for clock skew. Throw when a check fails."+ [{:keys [exp iat] :as jwt-data}]+ (cond+ (not (and exp iat))+ (throw (ex-info (tru "The JWT must have exp and iat claims.")+ {:status-code 400+ :error :missing-exp-or-iat}))++ (> iat (+ (buddy-util/now) clock-skew-in-seconds))+ (throw (ex-info (tru "The JWT has an iat claim in the future.")+ {:status-code 400+ :error :future-iat}))++ :else+ jwt-data))+(methodical/defmethod auth-identity/authenticate :provider/jwt- [_provider {:keys [token] :as _request}]+ [_provider {:keys [token jwt/require-exp-and-iat?] :as _request}](cond(not (sso-settings/jwt-enabled-and-configured)){:success? false@@ -92,7 +115,8 @@:else(try- (let [jwt-data (decode-and-verify-jwt token)+ (let [jwt-data (cond-> (decode-and-verify-jwt token)+ require-exp-and-iat? check-exp-and-iat)email (get jwt-data (jwt-attribute-email))first-name (get jwt-data (jwt-attribute-firstname))last-name (get jwt-data (jwt-attribute-lastname))diff --git a/enterprise/backend/src/metabase_enterprise/tenants/auth_provider.clj b/enterprise/backend/src/metabase_enterprise/tenants/auth_provider.cljindex 424610468a6..00aaacada06 100644--- a/enterprise/backend/src/metabase_enterprise/tenants/auth_provider.clj+++ b/enterprise/backend/src/metabase_enterprise/tenants/auth_provider.clj@@ -46,7 +46,8 @@(defn- reactivate-tenant!"Reactivate a disabled tenant and any users that were deactivated along with it."[{tenant-id :id}]- (api.tenants/update-tenant! tenant-id {:is_active true}))+ (request/as-admin+ (api.tenants/update-tenant! tenant-id {:is_active true})))(defn- maybe-reactivate-tenant!"If the tenant is disabled and user provisioning is enabled,diff --git a/enterprise/backend/test/metabase_enterprise/sso/integrations/jwt_bearer_grant_test.clj b/enterprise/backend/test/metabase_enterprise/sso/integrations/jwt_bearer_grant_test.cljnew file mode 100644index 00000000000..0d174f0e130--- /dev/null+++ b/enterprise/backend/test/metabase_enterprise/sso/integrations/jwt_bearer_grant_test.clj@@ -0,0 +1,319 @@+(ns metabase-enterprise.sso.integrations.jwt-bearer-grant-test+ (:require+ [buddy.sign.jwt :as jwt]+ [buddy.sign.util :as buddy-util]+ [clojure.string :as str]+ [clojure.test :refer :all]+ [metabase-enterprise.mcp.test-util :as mcp.tu]+ [metabase-enterprise.sso.test-setup :as sso.test-setup]+ [metabase.config.core :as config]+ [metabase.mcp.core :as mcp]+ [metabase.mcp.v2.test-util]+ [metabase.system.core :as system]+ [metabase.test :as mt]+ [metabase.test.fixtures :as fixtures]+ [metabase.test.http-client :as client]+ [oidc-provider.util :as oidc-util]+ [toucan2.core :as t2]))++(use-fixtures :once (fixtures/initialize :test-users))++(defmacro ^:private with-jwt-bearer-setup!+ "Run `body` with JWT authentication set up, deleting the tokens and audit rows it creates."+ [& body]+ `(sso.test-setup/with-jwt-default-setup!+ (mt/with-model-cleanup [:model/OAuthAccessToken :model/AuditLog]+ ~@body)))++(defn- assertion+ "Return a JWT carrying `claims`, signed with the JWT authentication secret.++ Unless `claims` says otherwise, it's issued now and expires in a minute."+ [claims]+ (let [now (buddy-util/now)]+ (jwt/sign (merge {:iat now, :exp (+ now 60)} claims) sso.test-setup/default-jwt-secret)))++(defn- token-response+ "POST a JWT bearer grant request with `params` to the token endpoint and return the response.++ The response must have `status`."+ [status params]+ (binding [client/*url-prefix* ""]+ (client/client-full-response :post status "oauth/token"+ {:request-options {:headers {"content-type" "application/x-www-form-urlencoded"}}}+ (merge {:grant_type "urn:ietf:params:oauth:grant-type:jwt-bearer"} params))))++(defn- token!+ "Exchange a JWT naming `email` for a token, with the extra request `params`, and return the token response."+ [email & {:as params}]+ (:body (token-response 200 (merge {:assertion (assertion {:email email})} params))))++(defn- mcp-request+ "Send the JSON-RPC `method` with `params` to the MCP endpoint and return the response.++ Use the bearer `access-token` and, if non-nil, the MCP session `session-id`.+ The response must have `status`."+ [status access-token session-id method params]+ (client/client-full-response :post status "metabase-mcp"+ {:request-options {:headers (cond-> {"authorization" (str "Bearer " access-token)}+ session-id (assoc "mcp-session-id" session-id))}}+ {:jsonrpc "2.0" :id 1 :method method :params params}))++(defn- mcp-session+ "Open an MCP session with the bearer `access-token` and return its ID."+ [access-token]+ (get-in (mcp-request 200 access-token nil "initialize" {:capabilities {}}) [:headers "Mcp-Session-Id"]))++(defn- mcp-url []+ (str (system/site-url) "/api/metabase-mcp"))++(defn- discovered-grant-types []+ (binding [client/*url-prefix* ""]+ (:grant_types_supported (client/client :get 200 ".well-known/oauth-authorization-server"))))++(deftest exchange-test+ (testing "the exchange returns an MCP token and provisions the user named in the JWT as JWT login does"+ (with-jwt-bearer-setup!+ (let [response (token-response 200 {:assertion (assertion {:email "[email protected]"+ :first_name "Jay"+ :last_name "Bird"+ :plan "pro"})})+ user (t2/select-one [:model/User :id :type :first_name :last_name :sso_source :jwt_attributes]+ :email "[email protected]")]+ (testing "every MCP scope, for an hour, bound to the MCP endpoint, with no refresh token"+ (is (= {:token_type "Bearer"+ :expires_in 3600+ :scope (str/join " " (mcp/v2-scopes))+ :resource [(mcp-url)]}+ (dissoc (:body response) :access_token)))+ (is (= "no-store" (get-in response [:headers "Cache-Control"]))))+ (testing "a personal user with the JWT's names and attributes"+ (is (=? {:type :personal+ :first_name "Jay"+ :last_name "Bird"+ :sso_source :jwt+ :jwt_attributes {"plan" "pro"}}+ user)))+ (testing "the stored token belongs to that user and the built-in client"+ (is (=? {:user_id (:id user)+ :client_id "metabase-jwt-bearer"+ :scope (mcp/v2-scopes)+ :resource [(mcp-url)]}+ (t2/select-one :model/OAuthAccessToken+ :token (oidc-util/hash-token (get-in response [:body :access_token]))))))+ (testing "no session and no login history"+ (is (not (t2/exists? :model/Session :user_id (:id user))))+ (is (not (t2/exists? :model/LoginHistory :user_id (:id user)))))))))++(deftest exchange-group-sync-test+ (testing "the exchange syncs the user's groups from the JWT, as JWT login does"+ (with-jwt-bearer-setup!+ (mt/with-temp [:model/PermissionsGroup {group-id :id} {:name "jwt-bearer-group"}]+ (mt/with-temporary-setting-values [jwt-group-sync true+ jwt-group-mappings {"analysts" [group-id]}+ jwt-attribute-groups "groups"]+ (let [email "[email protected]"]+ (token-response 200 {:assertion (assertion {:email email, :groups ["analysts"]})})+ (is (t2/exists? :model/PermissionsGroupMembership+ :user_id (t2/select-one-pk :model/User :email email), :group_id group-id))))))))++(deftest exchange-scope-test+ (with-jwt-bearer-setup!+ (let [email "[email protected]"]+ (testing "the token carries the requested scopes, each once, in the order requested"+ (let [{:keys [access_token scope]} (token! email :scope "agent:query:run agent:sql:run agent:query:run")]+ (is (= "agent:query:run agent:sql:run" scope))+ (testing "and MCP refuses a tool that needs another scope"+ (is (re-find #"Requires \"agent:content:read\""+ (get-in (mcp-request 403 access_token (mcp-session access_token)+ "tools/call" {:name "test_echo" :arguments {}})+ [:body :error :message]))))))+ (testing "both MCP paths are accepted as resources and bind the token to the canonical endpoint"+ (doseq [resource [(mcp-url) (str (mcp-url) "/") (str (system/site-url) "/api/mcp")]]+ (testing resource+ (is (= [(mcp-url)] (:resource (token! email :resource resource))))))))))++(deftest exchange-provisioning-test+ (with-jwt-bearer-setup!+ (let [email "[email protected]"+ refused (fn []+ (mt/with-temporary-setting-values [jwt-user-provisioning-enabled? false]+ (:body (token-response 400 {:assertion (assertion {:email email})}))))]+ (testing "a JWT for an unknown user is refused without provisioning when provisioning is off"+ (is (=? {:error "invalid_grant"} (refused)))+ (is (not (t2/exists? :model/User :email email))))+ (token! email)+ (let [user-id (t2/select-one-pk :model/User :email email)]+ (testing "an existing user gets a token with provisioning off"+ (mt/with-temporary-setting-values [jwt-user-provisioning-enabled? false]+ (is (=? {:access_token string?} (token! email)))))+ (t2/update! :model/User user-id {:is_active false})+ (testing "a deactivated user is refused with provisioning off, and reactivated with it on"+ (is (=? {:error "invalid_grant"} (refused)))+ (is (=? {:access_token string?} (token! email)))+ (is (true? (t2/select-one-fn :is_active :model/User user-id))))))))++(deftest exchange-non-personal-user-test+ (testing "a JWT naming an API key's user or the internal user is refused, and leaves that user as it was"+ (with-jwt-bearer-setup!+ (mt/with-model-cleanup [:model/ApiKey]+ (let [api-key (mt/user-http-request :crowberto :post 200 "api-key"+ {:name (mt/random-name)+ :group_id (t2/select-one-pk :model/PermissionsGroup :name "All Users")})+ key-user (:body (client/client-full-response :get 200 "user/current"+ {:request-options {:headers {"x-api-key"+ (:unmasked_key api-key)}}}))+ state (fn [user-id]+ [(t2/select-one :core_user :id user-id)+ (t2/select :auth_identity :user_id user-id {:order-by [:id]})])]+ (doseq [{:keys [id email]} [key-user+ (t2/select-one [:model/User :id :email] :id config/internal-mb-user-id)]]+ (testing email+ (let [before (state id)]+ (is (=? {:error "invalid_grant"}+ (:body (token-response 400 {:assertion (assertion {:email email+ :first_name "Mallard"+ :last_name "Duck"+ :plan "pro"})}))))+ (is (= before (state id)))+ (is (not (t2/exists? :model/OAuthAccessToken :user_id id)))))))))))++(deftest exchange-refusal-test+ (with-jwt-bearer-setup!+ (let [email "[email protected]"+ signed (assertion {:email email})]+ (doseq [[description error params]+ [["no assertion" "invalid_request" {}]+ ["the wrong secret" "invalid_grant" {:assertion (jwt/sign {:email email} "not-the-secret")}]+ ["an algorithm not HS256" "invalid_grant" {:assertion (jwt/sign {:email email}+ sso.test-setup/default-jwt-secret+ {:alg :hs512})}]+ ["a stale iat" "invalid_grant" {:assertion (assertion {:email email+ :iat (- (buddy-util/now) 300)})}]+ ["an expired exp" "invalid_grant" {:assertion (assertion {:email email+ :exp (- (buddy-util/now) 60)})}]+ ["no email claim" "invalid_grant" {:assertion (assertion {:first_name "Jay"})}]+ ["mb:full" "invalid_scope" {:assertion signed, :scope "mb:full"}]+ ["an unknown scope" "invalid_scope" {:assertion signed, :scope "agent:query:run agent:all"}]+ ["an empty scope" "invalid_scope" {:assertion signed, :scope ""}]+ ["a whitespace scope" "invalid_scope" {:assertion signed, :scope " "}]+ ["another resource" "invalid_target" {:assertion signed, :resource "https://example.com/api/mcp"}]+ ["a malformed resource" "invalid_target" {:assertion signed, :resource "not a uri"}]]]+ (testing description+ (is (=? {:error error, :error_description string?}+ (:body (token-response 400 params))))))+ (testing "refused requests don't provision the user or issue a token"+ (is (not (t2/exists? :model/User :email email)))+ (is (not (t2/exists? :model/OAuthAccessToken :client_id "metabase-jwt-bearer")))))))++(deftest exchange-assertion-times-test+ (with-jwt-bearer-setup!+ (let [email "[email protected]"+ now (buddy-util/now)+ sign #(jwt/sign (assoc % :email email) sso.test-setup/default-jwt-secret)]+ (doseq [[description claims error-description]+ [["no exp" {:iat now} "The JWT must have exp and iat claims."]+ ["no iat" {:exp (+ now 60)} "The JWT must have exp and iat claims."]+ ["an iat in the future" {:iat (+ now 120), :exp (+ now 180)} "The JWT has an iat claim in the future."]]]+ (testing (str "an assertion with " description " is refused without provisioning anyone")+ (is (= {:error "invalid_grant", :error_description error-description}+ (:body (token-response 400 {:assertion (sign claims)}))))+ (is (not (t2/exists? :model/User :email email)))))+ (testing "an iat less than a minute ahead of Metabase's clock is accepted"+ (is (=? {:access_token string?}+ (:body (token-response 200 {:assertion (sign {:iat (+ now 30), :exp (+ now 90)})}))))))))++(deftest exchange-refusal-reason-test+ (testing "a refused login tells the caller why in `error_description`"+ (with-jwt-bearer-setup!+ (is (=? {:error "invalid_grant", :error_description "This login is only for personal accounts."}+ (:body (token-response 400 {:assertion (assertion {:email (t2/select-one-fn :email :model/User+ :id config/internal-mb-user-id)})})))))))++(deftest exchange-refusal-withheld-reason-test+ (with-jwt-bearer-setup!+ (let [email "[email protected]"+ refusal (fn [claims]+ (:body (token-response 400 {:assertion (assertion (assoc claims :email email))})))]+ (testing "a JWT that fails verification gets a fixed description instead of the verifier's message"+ (is (= {:error "invalid_grant", :error_description "The JWT could not be verified."}+ (refusal {:exp (- (buddy-util/now) 60)}))))+ (testing "an error message not written by Metabase gets the generic description without database details"+ (is (= {:error "invalid_grant", :error_description "The token request is invalid."}+ (refusal {:first_name (apply str (repeat 255 "x"))})))))))++(deftest discovery-test+ (testing "discovery lists the grant while the token endpoint accepts it"+ (with-jwt-bearer-setup!+ (is (= ["authorization_code" "refresh_token" "urn:ietf:params:oauth:grant-type:jwt-bearer"]+ (discovered-grant-types))))))++(deftest exchange-unsupported-test+ (with-jwt-bearer-setup!+ (let [email "[email protected]"+ refused (fn []+ (is (=? {:error "unsupported_grant_type"}+ (:body (token-response 400 {:assertion (assertion {:email email})}))))+ (is (not (t2/exists? :model/User :email email)))+ (is (not (t2/exists? :model/OAuthAccessToken :client_id "metabase-jwt-bearer")))+ (is (not (t2/exists? :model/AuditLog :topic "mcp-jwt-token-issued")))+ (is (= ["authorization_code" "refresh_token"] (discovered-grant-types))))]+ (testing "without the sso-jwt feature"+ (mt/with-premium-features #{}+ (refused)))+ (testing "with JWT authentication off"+ (mt/with-temporary-setting-values [jwt-enabled false]+ (refused)))+ (testing "with the MCP server off"+ (mt/with-temporary-setting-values [mcp-enabled? false]+ (refused))))))++(deftest exchange-mcp-group-access-test+ (with-jwt-bearer-setup!+ (mcp.tu/with-group-level-mode+ (mt/with-temp [:model/PermissionsGroup {group-id :id} {:name "jwt-bearer-mcp-group"}+ :model/McpGroupPermission _ {:group_id group-id, :mcp_enabled true, :tool_access {}}]+ (mt/with-temporary-setting-values [jwt-group-sync true+ jwt-group-mappings {"agents" [group-id]}]+ (let [email "[email protected]"]+ (testing "a user whose groups don't allow MCP is refused, and gets an account but no token or audit row"+ (is (= {:error "unsupported_grant_type"+ :error_description "MCP access is not enabled for this user's groups."}+ (:body (token-response 400 {:assertion (assertion {:email email})}))))+ (let [user-id (t2/select-one-pk :model/User :email email)]+ (is (some? user-id))+ (is (not (t2/exists? :model/OAuthAccessToken :user_id user-id)))+ (is (not (t2/exists? :model/AuditLog :topic "mcp-jwt-token-issued" :user_id user-id)))))+ (testing "once the JWT syncs the user into a group that allows MCP, they get a token that MCP accepts"+ (let [{:keys [access_token]} (:body (token-response 200 {:assertion (assertion {:email email+ :groups ["agents"]})}))]+ (is (some? (mcp-session access_token)))))))))))++(deftest token-drives-mcp-test+ (testing "MCP calls run as the user named in the JWT, and usage and audit rows belong to that user"+ (with-jwt-bearer-setup!+ (let [{:keys [access_token scope]} (token! "[email protected]")+ user-id (t2/select-one-pk :model/User :email "[email protected]")+ session-id (mcp-session access_token)]+ (is (= {:ok true :message "pong"}+ (get-in (mcp-request 200 access_token session-id "tools/call" {:name "test_echo" :arguments {}})+ [:body :result :structuredContent])))+ (is (= user-id (t2/select-one-fn :user_id :model/McpSessionLog :id session-id)))+ (is (=? [{:tool_name "test_echo" :status "success"}]+ (t2/select :model/McpToolCallLog :user_id user-id)))+ (is (=? {:user_id user-id :details {:scope scope}}+ (mt/latest-audit-log-entry :mcp-jwt-token-issued)))))))++(deftest token-reach-test+ (with-jwt-bearer-setup!+ (let [email "[email protected]"+ access-token (:access_token (token! email))]+ (testing "the REST API refuses the token"+ (is (= 403 (:status (client/client-full-response :get "user/current"+ {:request-options {:headers {"authorization"+ (str "Bearer " access-token)}}})))))+ (testing "deactivating the user revokes the token"+ (is (some? (mcp-session access-token)))+ (t2/update! :model/User (t2/select-one-pk :model/User :email email) {:is_active false})+ (is (=? {:error {:message "Invalid bearer token"}}+ (:body (mcp-request 401 access-token nil "initialize" {:capabilities {}}))))))))diff --git a/enterprise/backend/test/metabase_enterprise/sso/integrations/jwt_test.clj b/enterprise/backend/test/metabase_enterprise/sso/integrations/jwt_test.cljindex 0fb5cac45d7..fc43966bca5 100644--- a/enterprise/backend/test/metabase_enterprise/sso/integrations/jwt_test.clj+++ b/enterprise/backend/test/metabase_enterprise/sso/integrations/jwt_test.clj@@ -824,38 +824,29 @@(mt/with-additional-premium-features #{:tenants}(mt/with-temporary-setting-values [use-tenants true](mt/with-temp [:model/PermissionsGroup _my-group {:name (str ::my-group)}- :model/Tenant {tenant-id :id} {:slug "tenant-mctenantson"- :name "Tenant McTenantson"- :is_active false}+ :model/Tenant {tenant-id :id+ collection-id :tenant_collection_id} {:slug "tenant-mctenantson"+ :name "Tenant McTenantson"}:model/User {existing-email :email} {:tenant_id tenant-id}]- (mt/with-temporary-setting-values [use-tenants true]- (testing "a new user can log into a deactivated tenant"- (mt/with-model-cleanup [:model/User]+ (mt/with-model-cleanup [:model/User]+ (doseq [[user-type email] [["new" "[email protected]"] ["existing" existing-email]]]+ (testing (str "a " user-type " user can log into a deactivated tenant")+ (mt/user-http-request :crowberto :put 200 (str "/api/ee/tenant/" tenant-id) {:is_active false})+ (is (true? (t2/select-one-fn :archived :model/Collection :id collection-id)))(let [response (client/client-real-response :get 302 "/auth/sso"{:request-options {:redirect-strategy :none}}:return_to default-redirect-uri:jwt(jwt/sign- {:email "[email protected]"+ {:email email"@tenant" "tenant-mctenantson"- :first_name "New"+ :first_name "Test":last_name "User"}default-jwt-secret))](is (sso.test-setup/successful-login? response))- (is (t2/select-one-fn :is_active :model/Tenant :id tenant-id)))))- (testing "an existing user also fails to log in with correct error message"- (let [response (client/client-real-response :get 302 "/auth/sso"- {:request-options {:redirect-strategy :none}}- :return_to default-redirect-uri- :jwt- (jwt/sign- {:email existing-email- "@tenant" "tenant-mctenantson"- :first_name "Existing"- :last_name "User"}- default-jwt-secret))]- (is (sso.test-setup/successful-login? response))- (is (t2/select-one-fn :is_active :model/Tenant :id tenant-id))))))))))+ (is (true? (t2/select-one-fn :is_active :model/Tenant :id tenant-id)))+ (is (true? (t2/select-one-fn :is_active :model/User :email email)))+ (is (false? (t2/select-one-fn :archived :model/Collection :id collection-id))))))))))))(deftest users-cannot-log-into-deactivated-tenant-with-provisioning-disabled(with-jwt-default-setup!diff --git a/enterprise/backend/test/metabase_enterprise/sso/integrations/saml_test.clj b/enterprise/backend/test/metabase_enterprise/sso/integrations/saml_test.cljindex 01168f20886..ef05d2507b3 100644--- a/enterprise/backend/test/metabase_enterprise/sso/integrations/saml_test.clj+++ b/enterprise/backend/test/metabase_enterprise/sso/integrations/saml_test.clj@@ -1126,30 +1126,31 @@(mt/with-additional-premium-features #{:tenants}(mt/with-temporary-setting-values [use-tenants truesaml-attribute-tenant "tenant"]- (mt/with-temp [:model/Tenant {tenant-id :id} {:slug "tenant-mctenantson"- :name "Tenant McTenantson"- :is_active false}+ (mt/with-temp [:model/Tenant {tenant-id :id+ collection-id :tenant_collection_id} {:slug "tenant-mctenantson"+ :name "Tenant McTenantson"}:model/User {existing-email :email} {:tenant_id tenant-id}](do-with-some-validators-disabled!(fn []- (testing "a new user fails to log in"- (mt/with-model-cleanup [:model/User]- (let [req-options (saml-post-request-options (new-user-with-tenant-saml-test-response)- default-redirect-uri)- response (client/client-real-response :post 302 "/auth/sso" req-options)]- (is (successful-login? response)))))- (testing "an existing user also fails to log in"- ;; with-redefs (cross-thread): /auth/sso runs on Jetty workers that don't inherit *local-redefs*- ;; [kondo-keep] suppresses a warning :redundant-ignore can't see; --audit rechecks- #_{:clj-kondo/ignore [:metabase/prefer-with-dynamic-fn-redefs]}- (with-redefs [saml.p/saml-response->attributes- (fn [_]- {"http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress" existing-email- "tenant" "tenant-mctenantson"})]- (let [req-options (saml-post-request-options (new-user-with-tenant-saml-test-response)- default-redirect-uri)- response (client/client-real-response :post 302 "/auth/sso" req-options)]- (is (successful-login? response)))))))))))))+ (mt/with-model-cleanup [:model/User]+ (doseq [[user-type email] [["new" "[email protected]"] ["existing" existing-email]]]+ (testing (str "a " user-type " user can log into a deactivated tenant")+ (mt/user-http-request :crowberto :put 200 (str "/api/ee/tenant/" tenant-id) {:is_active false})+ (is (true? (t2/select-one-fn :archived :model/Collection :id collection-id)))+ ;; with-redefs (cross-thread): /auth/sso runs on Jetty workers that don't inherit *local-redefs*+ ;; [kondo-keep] suppresses a warning :redundant-ignore can't see; --audit rechecks+ #_{:clj-kondo/ignore [:metabase/prefer-with-dynamic-fn-redefs]}+ (with-redefs [saml.p/saml-response->attributes+ (fn [_]+ {"http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress" email+ "tenant" "tenant-mctenantson"})]+ (let [req-options (saml-post-request-options (new-user-with-tenant-saml-test-response)+ default-redirect-uri)+ response (client/client-real-response :post 302 "/auth/sso" req-options)]+ (is (successful-login? response))+ (is (true? (t2/select-one-fn :is_active :model/Tenant :id tenant-id)))+ (is (true? (t2/select-one-fn :is_active :model/User :email email)))+ (is (false? (t2/select-one-fn :archived :model/Collection :id collection-id))))))))))))))))(deftest a-user-can-not-log-into-deactivated-tenant-via-saml-if-provisioning-is-off(with-other-sso-types-disabled!diff --git a/resources/migrations/065/20261013_oauth_jwt_bearer_client.yaml b/resources/migrations/065/20261013_oauth_jwt_bearer_client.yamlnew file mode 100644index 00000000000..5ad7c3c57ec--- /dev/null+++ b/resources/migrations/065/20261013_oauth_jwt_bearer_client.yaml@@ -0,0 +1,41 @@+## Token resolution needs a stored issuing client, even though the JWT bearer grant doesn't authenticate a client.++databaseChangeLog:+ - changeSet:+ id: v65.uc38po+ author: andreis+ comment: Add the built-in OAuth client for the JWT bearer grant+ preConditions:+ - onFail: MARK_RAN+ - sqlCheck:+ expectedResult: 0+ sql: >-+ SELECT COUNT(*) FROM oauth_client WHERE client_id = 'metabase-jwt-bearer';+ changes:+ - sql:+ sql: >-+ INSERT INTO oauth_client (+ client_id+ , redirect_uris+ , grant_types+ , response_types+ , scopes+ , token_endpoint_auth_method+ , client_name+ , registration_type+ , client_type+ ) VALUES (+ 'metabase-jwt-bearer'+ , '[]'+ , '["urn:ietf:params:oauth:grant-type:jwt-bearer"]'+ , '[]'+ , '[]'+ , 'none'+ , 'JWT bearer grant'+ , 'static'+ , 'public'+ );+ rollback:+ - sql:+ sql: >-+ DELETE FROM oauth_client WHERE client_id = 'metabase-jwt-bearer';diff --git a/src/metabase/audit_app/events/audit_log.clj b/src/metabase/audit_app/events/audit_log.cljindex 35448606cb6..b6956152395 100644--- a/src/metabase/audit_app/events/audit_log.clj+++ b/src/metabase/audit_app/events/audit_log.clj@@ -186,6 +186,7 @@(events/derive! :event/mfa-required-enrollment-failed ::user-event)(events/derive! :event/mfa-enrolled ::user-event)(events/derive! :event/mfa-disabled ::user-event)+(events/derive! :event/mcp-jwt-token-issued ::user-event)(methodical/defmethod events/publish-event! ::user-event[topic event]diff --git a/src/metabase/auth_identity/db.clj b/src/metabase/auth_identity/db.cljindex 5fbeee54bfc..c7ae56d517e 100644--- a/src/metabase/auth_identity/db.clj+++ b/src/metabase/auth_identity/db.clj@@ -93,15 +93,18 @@(t2/select-one :model/User :%lower.email (u/lower-case-en email)))(mu/defn user-login-columns- "The id, active flag, last login, and tenant id of the User with `user-id`, or nil."+ "Return login details for the user with `user-id`, or nil.++ The details include the user's ID, active flag, last login, tenant ID, and type."[user-id :- ::lib.schema.id/user]- (t2/select-one [:model/User :id :is_active :last_login :tenant_id] :id (long user-id)))+ (t2/select-one [:model/User :id :is_active :last_login :tenant_id :type] :id (long user-id)))(mu/defn user-login-columns-by-email- "The id, active flag, last login, and tenant id of the User whose email matches `email` case-insensitively, or- nil."+ "Return login details for the user whose email matches `email`, or nil.++ The match is case-insensitive. The details include the user's ID, active flag, last login, tenant ID, and type."[email :- :string]- (t2/select-one [:model/User :id :is_active :last_login :tenant_id] :%lower.email (u/lower-case-en email)))+ (t2/select-one [:model/User :id :is_active :last_login :tenant_id :type] :%lower.email (u/lower-case-en email)))(mu/defn user-login-status"The id, active flag, and last login of the User with `user-id`, or nil."diff --git a/src/metabase/auth_identity/provider.clj b/src/metabase/auth_identity/provider.cljindex dfe437147ec..547ae698f17 100644--- a/src/metabase/auth_identity/provider.clj+++ b/src/metabase/auth_identity/provider.clj@@ -83,6 +83,7 @@(def ^:private disabled-account-message (deferred-tru "Your account is disabled. Please contact your administrator."))(def ^:private disabled-account-snippet (deferred-tru "Your account is disabled."))+(def ^:private personal-only-message (deferred-tru "This login is only for personal accounts."));;; -------------------------------------------------- Multimethod: validate --------------------------------------------------@@ -220,6 +221,11 @@- Authentication data (credentials, tokens, etc.)- :device-info - Device information for session tracking- :redirect-url - Optional redirect URL after login+ - :session/skip? - Optional; when true, the login creates no session+ - :user/personal-only? - Optional; when true, a user who is not a personal account is refused before any+ change is made to them+ - :jwt/require-exp-and-iat? - Optional; when true, a JWT login refuses a JWT that lacks an `exp` or `iat`+ claim, or whose `iat` is in the futureReturns:Map with one of three result types:@@ -291,6 +297,7 @@[:email {:optional true} [:maybe :string]][:error {:optional true} [:maybe :keyword]][:jwt-data {:optional true} [:maybe ms/JWTClaims]]+ [:jwt/require-exp-and-iat? {:optional true} [:maybe :boolean]][:message {:optional true} [:maybe [:or :string ms/LocalizedString]]][:oidc-nonce {:optional true} [:maybe :string]][:oidc-provider {:optional true} [:maybe :keyword]]@@ -304,6 +311,7 @@[:server-name {:optional true} [:maybe :string]][:server-port {:optional true} [:maybe :int]][:session/provider {:optional true} [:maybe :keyword]]+ [:session/skip? {:optional true} [:maybe :boolean]][:slack-data {:optional true} [:maybe [:map-of :string :string]]][:state {:optional true} [:maybe :string]][:success? {:optional true} [:maybe [:or :boolean [:enum :redirect]]]]@@ -313,6 +321,7 @@[:user-data {:optional true} [:maybe UserData]][:user-id {:optional true} [:maybe :int]][:user-provisioning-enabled? {:optional true} [:maybe :boolean]]+ [:user/personal-only? {:optional true} [:maybe :boolean]][:username {:optional true} [:maybe :string]]])(mu/defn- apply-inactive-check@@ -332,6 +341,24 @@:error disabled-account-snippet:message disabled-account-message)))+(mu/defn- apply-personal-only-check+ "Refuses a `request` that sets `:user/personal-only?` for a user who is not a personal account.++ Remove the user from the request on refusal so the rest of the login cannot change their account."+ [request :- [:merge+ ::request.schema/request+ (into [:map {:closed true}+ [:user {:optional true} [:maybe ::users.schema/user]]]+ login-pipeline-entries)]]+ (cond-> request+ (and (:user/personal-only? request)+ (:user request)+ (not= :personal (get-in request [:user :type])))+ (-> (dissoc :user)+ (assoc :success? false+ :error :non-personal-user+ :message personal-only-message))))+(mu/defn- create-session!"Create a new session for a user, attributed to the AuthIdentity of `(:session/provider request)` when a `login!`method set one, otherwise to that of `provider`. Updates the last_used_at timestamp on that AuthIdentity."@@ -407,6 +434,7 @@provider (some-> user-id class .getName))))(when-let [email (get-in $ [:user-data :email])](auth-identity.db/user-login-columns-by-email email)))))+ (apply-personal-only-check $)(cond-> $(and (:provider-id $) (:user-data $))(assoc-in [:user-data :provider-id] (:provider-id $)))@@ -420,7 +448,8 @@(cond-> $(and (true? (:success? $))(:user $)- (not (:mfa/pending? $))) (create-session! provider))+ (not (:mfa/pending? $))+ (not (:session/skip? $))) (create-session! provider))(select-keys $ [:success? :user :redirect-url :error :message :user-data :session :jwt-data :claims:oidc-provider-key :mfa/enroll? :mfa/pending? :mfa/methods :mfa/first-factor])))diff --git a/src/metabase/oauth_server/api/metadata.clj b/src/metabase/oauth_server/api/metadata.cljindex 4ce104c81b4..e0a1ef017df 100644--- a/src/metabase/oauth_server/api/metadata.clj+++ b/src/metabase/oauth_server/api/metadata.clj@@ -5,6 +5,7 @@[metabase.api.macros :as api.macros][metabase.mcp.core :as mcp][metabase.oauth-server.core :as oauth-server]+ [metabase.oauth-server.jwt-bearer :as jwt-bearer][metabase.oauth-server.settings :as oauth-settings][metabase.system.core :as system][oidc-provider.core :as oidc]))@@ -15,8 +16,9 @@"Build the OAuth discovery document response, or nil if the provider is unavailable."[](when-let [provider (oauth-server/get-provider)]- (let [metadata (-> (oidc/discovery-metadata provider)- (dissoc :jwks_uri :id_token_signing_alg_values_supported))]+ (let [metadata (cond-> (-> (oidc/discovery-metadata provider)+ (dissoc :jwks_uri :id_token_signing_alg_values_supported))+ (jwt-bearer/available?) (update :grant_types_supported conj jwt-bearer/grant-type))]{:status 200:headers {"Content-Type" "application/json"}:body (if (oauth-settings/oauth-server-dynamic-registration-enabled)diff --git a/src/metabase/oauth_server/api/oauth.clj b/src/metabase/oauth_server/api/oauth.cljindex 524982900eb..bae03e05f6e 100644--- a/src/metabase/oauth_server/api/oauth.clj+++ b/src/metabase/oauth_server/api/oauth.clj@@ -10,6 +10,7 @@[metabase.mcp.core :as mcp][metabase.oauth-server.consent-page :as consent-page][metabase.oauth-server.core :as oauth-server]+ [metabase.oauth-server.jwt-bearer :as jwt-bearer][metabase.oauth-server.models.oauth-client-event :as client-event][metabase.oauth-server.settings :as oauth-settings][metabase.request.core :as request]@@ -626,6 +627,7 @@_query-paramsbody :- [:map {:closed true, :decode/api {:enter (fn [body] (if (map? body) body {}))}}[:grant_type {:optional true} [:maybe :string]]+ [:assertion {:optional true} [:maybe :string]][:code {:optional true} [:maybe :string]][:redirect_uri {:optional true} [:maybe :string]][:refresh_token {:optional true} [:maybe :string]]@@ -645,7 +647,13 @@(let [authorization-header (get-in request [:headers "authorization"])](try(check-resource-indicators! (:resource body))- (let [response (oidc/token-request provider body authorization-header)]+ (let [response (if (= jwt-bearer/grant-type (:grant_type body))+ (jwt-bearer/exchange-jwt-for-token! provider request+ {:assertion (:assertion body)+ :scopes (when (some? (:scope body))+ (or (scope-tokens (:scope body)) []))+ :resource (:resource body)})+ (oidc/token-request provider body authorization-header))]{:status 200:headers {"Content-Type" "application/json""Cache-Control" "no-store"diff --git a/src/metabase/oauth_server/core.clj b/src/metabase/oauth_server/core.cljindex 2d64138774e..75d562ae602 100644--- a/src/metabase/oauth_server/core.clj+++ b/src/metabase/oauth_server/core.clj@@ -9,6 +9,7 @@[metabase.oauth-server.scopes :as scopes][metabase.oauth-server.settings :as oauth-settings][metabase.oauth-server.store :as store]+ [metabase.premium-features.core :refer [defenterprise]][metabase.system.core :as system][metabase.util :as u][oidc-provider.core :as oidc]@@ -166,6 +167,12 @@(subs 0 (dec (count path)))))))(catch java.net.URISyntaxException _ nil))))+(defn- mcp-endpoint-paths-by-url+ "Return the MCP endpoint paths keyed by their [[canonical-resource-uri]] under the Site URL."+ []+ (into {} (keep (fn [path] (some-> (canonical-resource-uri (str (system/site-url) path)) (vector path))))+ (mcp/mcp-endpoint-paths)))+(defn narrow-scope-to-resource"Narrow an OAuth `scope` string to what the requested `resources` accept.@@ -201,13 +208,28 @@;; token has to work against each -- so the accepted set is the UNION of what they accept, not the set;; of whichever one is checked first. Taking a single winner would drop the v1-only scopes when a v1;; alias is named alongside v2, silently shrinking a grant the client asked for and the user approved.- matched (filter #(contains? named (canonical-resource-uri (str (system/site-url) %)))- (mcp/mcp-endpoint-paths))]+ matched (keep (mcp-endpoint-paths-by-url) named)](if (or (not scope) (empty? matched))scope(let [accepted (into #{} (mapcat mcp-resource-scopes) matched)](not-empty (str/join " " (filter accepted (str/split scope #"\s+"))))))))+(defn mcp-resource-url+ "Return the canonical MCP endpoint's RFC 8707 resource indicator under the Site URL.++ Return nil when no Site URL is set."+ []+ (some-> (system/site-url) (str (mcp/mcp-canonical-path))))++(defn mcp-endpoint-resource?+ "Return whether every RFC 8707 indicator in `resources` names the MCP endpoint.++ Return true when `resources` names none. `resources` is a string or a sequence of strings.+ Compare each string's [[canonical-resource-uri]] with the Site URL joined to each of+ [[metabase.mcp.core/mcp-endpoint-paths]]."+ [resources]+ (every? (comp (mcp-endpoint-paths-by-url) canonical-resource-uri) (cond-> resources (string? resources) vector)))+(defn- build-provider-config"Build the configuration map for the OAuth provider from Metabase settings."[]@@ -285,3 +307,11 @@(when (oauth-server.db/active-user-exists? user-id){:user-id user-id:scopes (or (some->> (:scope token-data) (into #{})) #{})}))))))))++(defenterprise jwt-bearer-grant-enabled?+ "Return whether JWT authentication is enabled and configured.++ The JWT bearer grant (RFC 7523) requires this. Always false on OSS."+ metabase-enterprise.sso.integrations.jwt+ []+ false)diff --git a/src/metabase/oauth_server/jwt_bearer.clj b/src/metabase/oauth_server/jwt_bearer.cljnew file mode 100644index 00000000000..5b56363cdd0--- /dev/null+++ b/src/metabase/oauth_server/jwt_bearer.clj@@ -0,0 +1,132 @@+(ns metabase.oauth-server.jwt-bearer+ "Exchange a signed JWT for an MCP access token using the JWT bearer grant (RFC 7523).++ The token belongs to the user named in the JWT."+ (:require+ [clojure.string :as str]+ [metabase.auth-identity.core :as auth-identity]+ [metabase.events.core :as events]+ [metabase.mcp.core :as mcp]+ [metabase.mcp.permissions :as mcp.perms]+ [metabase.oauth-server.core :as oauth-server]+ [metabase.oauth-server.settings :as oauth-settings]+ [metabase.request.core :as request]+ [oidc-provider.store :as oidc.store]+ [oidc-provider.token :as oidc.token])+ (:import+ (clojure.lang ExceptionInfo)))++(set! *warn-on-reflection* true)++(def grant-type+ "The RFC 7523 `grant_type` of a JWT bearer grant request."+ "urn:ietf:params:oauth:grant-type:jwt-bearer")++(def ^:private client-id "metabase-jwt-bearer")++(defn available?+ "Return whether the token endpoint accepts the JWT bearer grant.++ JWT authentication and the MCP server must be enabled."+ []+ (and (oauth-server/jwt-bearer-grant-enabled?) (mcp/mcp-enabled?)))++(defn- check-request!+ "Throw `ex-info` with the RFC 6749 `:error` if the request is refused before checking its assertion."+ [assertion scopes resource]+ (cond+ (not (oauth-server/jwt-bearer-grant-enabled?))+ (throw (ex-info "JWT authentication is not enabled"+ {:error "unsupported_grant_type", :error-description "JWT authentication is not enabled."}))++ (not (mcp/mcp-enabled?))+ (throw (ex-info "the MCP server is not enabled"+ {:error "unsupported_grant_type", :error-description "The MCP server is not enabled."}))++ (str/blank? assertion)+ (throw (ex-info "no assertion was sent"+ {:error "invalid_request", :error-description "The request must include an assertion."}))++ (or (empty? scopes)+ (not-every? (set (mcp/v2-scopes)) scopes))+ (throw (ex-info "a requested scope is not an MCP scope"+ {:error "invalid_scope"+ :error-description (str "Request only MCP scopes, or omit scope to get all of them: "+ (str/join " " (mcp/v2-scopes)))}))++ (not (oauth-server/mcp-endpoint-resource? resource))+ (throw (ex-info "resource is not the MCP endpoint"+ {:error "invalid_target"+ :error-description (str "The resource must be the MCP endpoint, "+ (oauth-server/mcp-resource-url))}))))++(def ^:private own-reason-errors+ "These `:error` values identify refused JWT logins whose `:message` was written by Metabase for the caller."+ #{:non-personal-user :missing-email :missing-exp-or-iat :future-iat :invalid-tenant})++(defn- refusal-description+ "Return `error_description` for a refused JWT login, or nil to use the token endpoint's generic one.++ The login's `message` goes back only when Metabase wrote it for the caller: the login returned one of+ [[own-reason-errors]], or threw with a 4xx `status-code`. A JWT that fails verification gets a fixed description,+ since the verifier's message is library text."+ [{:keys [error status-code message]}]+ (cond+ (= :invalid-jwt error)+ "The JWT could not be verified."++ (or (own-reason-errors error) (<= 400 (or status-code 0) 499))+ (str message)))++(defn- log-in!+ "Log in through JWT authentication without creating a session.++ Return the user named in the JWT `assertion`, which must have `exp` and `iat` claims.+ Throw `ex-info` carrying `invalid_grant` and the [[refusal-description]] when the login is refused."+ [assertion request]+ (let [{:keys [success? user message] :as result}+ (try+ (auth-identity/login! :provider/jwt (assoc request+ :token assertion+ :session/skip? true+ :user/personal-only? true+ :jwt/require-exp-and-iat? true))+ (catch ExceptionInfo e+ {:message (ex-message e)+ :status-code (:status-code (ex-data e))}))]+ (if success?+ user+ (throw (ex-info (str message) {:error "invalid_grant", :error-description (refusal-description result)})))))++(defn- check-mcp-access!+ "Throws `ex-info` carrying `unsupported_grant_type` unless the groups of the User with `user-id` allow MCP."+ [user-id]+ (when-not (request/with-current-user user-id+ (mcp.perms/enabled? (mcp.perms/policy-for-current-user)))+ (throw (ex-info (str "MCP access is not enabled for the groups of user " user-id)+ {:error "unsupported_grant_type"+ :error-description "MCP access is not enabled for this user's groups."}))))++(defn exchange-jwt-for-token!+ "Issue an MCP access token to the user named in the JWT `assertion`.++ Return the RFC 6749 token response. The token carries `scopes`, or every MCP scope when `scopes` is nil,+ and is bound to the MCP endpoint, which `resource` must name when it is given.+ Throw `ex-info` carrying the RFC 6749 `:error` when the request is refused."+ [provider request {:keys [assertion scopes resource]}]+ (let [scopes (or scopes (mcp/v2-scopes))+ _ (check-request! assertion scopes resource)+ user-id (:id (log-in! assertion request))+ _ (check-mcp-access! user-id)+ token (oidc.token/generate-access-token)+ ttl (oauth-settings/oauth-server-access-token-ttl)+ granted (str/join " " scopes)+ bound [(oauth-server/mcp-resource-url)]]+ (oidc.store/save-access-token (:token-store provider) token (str user-id) client-id scopes+ (+ (System/currentTimeMillis) (* 1000 ttl)) bound)+ (events/publish-event! :event/mcp-jwt-token-issued {:user-id user-id, :details {:scope granted}})+ {:access_token token+ :token_type "Bearer"+ :expires_in ttl+ :scope granted+ :resource bound}))diff --git a/src/metabase/oauth_server/schema.clj b/src/metabase/oauth_server/schema.cljindex 3bbc834cd96..d447a555c1e 100644--- a/src/metabase/oauth_server/schema.clj+++ b/src/metabase/oauth_server/schema.clj@@ -107,3 +107,10 @@[:expiry {:optional true} [:maybe :int]][:revoked_at {:optional true} [:maybe ms/TemporalInstant]][:created_at {:optional true} [:maybe ms/TemporalInstant]]])++(mr/def :event/mcp-jwt-token-issued+ "The JWT bearer grant issued an MCP access token to the user with `:user-id`, granting `:scope`."+ [:map {:closed true}+ [:user-id ::lib.schema.id/user]+ [:details [:map {:closed true}+ [:scope ms/NonBlankString]]]])diff --git a/test/metabase/auth_identity/provider_test.clj b/test/metabase/auth_identity/provider_test.cljindex f439fe9dbcd..f5033bda1ab 100644--- a/test/metabase/auth_identity/provider_test.clj+++ b/test/metabase/auth_identity/provider_test.clj@@ -155,6 +155,31 @@(is (nil? (get-in result [:session :auth_identity_id]))"the session is attributed to the provider that actually authenticated, which has no AuthIdentity")))))+(deftest login!-without-a-session-test+ (testing "a login with `:session/skip?` returns the user without creating a session or login history"+ (mt/with-temp [:model/User user {}]+ (let [result (provider/login! :provider/test-plain-attribution+ {:user-id (:id user)+ :session/skip? true+ :device-info {:device_id "test"+ :embedded false+ :token_exchange false+ :device_description "Test"+ :ip_address "127.0.0.1"}})]+ (is (true? (:success? result)))+ (is (= (:id user) (get-in result [:user :id])))+ (is (nil? (:session result)))+ (is (not (t2/exists? :model/Session :user_id (:id user))))+ (is (not (t2/exists? :model/LoginHistory :user_id (:id user))))))))++(deftest login!-personal-only-test+ (testing "a login with `:user/personal-only?` refuses accounts that aren't personal without creating a session"+ (mt/with-temp [:model/User user {:type :api-key}]+ (is (=? {:success? false, :error :non-personal-user}+ (provider/login! :provider/test-plain-attribution+ {:user-id (:id user), :user/personal-only? true})))+ (is (not (t2/exists? :model/Session :user_id (:id user)))))))+(deftest ^:parallel ^:parallel three-valued-success-state-test(testing "Success states work correctly"(testing "Success state: true"