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
Built-in MCP server (#70787)
Chris Truter2ace0b69c17b
diff --git a/.clj-kondo/config.edn b/.clj-kondo/config.ednindex 95ff39763b2..01b4e0ec7f4 100644--- a/.clj-kondo/config.edn+++ b/.clj-kondo/config.edn@@ -179,6 +179,7 @@metabase.warehouses.models.database/assert-not-h2!metabase.driver.sql-jdbc.execute/execute-prepared-statement!metabase.notification.models/create-notification!+ metabase.oauth-server.core/reset-provider!metabase.pulse.send/send-pulse!metabase-enterprise.transforms-python.python-runner-test/execute!;; Workspace isolation functions are safe in parallel tests because they operate ondiff --git a/.clj-kondo/config/modules/config.edn b/.clj-kondo/config/modules/config.ednindex 4280afc2cbf..3a6c3a8bf31 100644--- a/.clj-kondo/config/modules/config.edn+++ b/.clj-kondo/config/modules/config.edn@@ -222,6 +222,7 @@metabase.api.docsmetabase.api.initmetabase.api.macros+ metabase.api.macros.defendpoint.tools-manifestmetabase.api.macros.scopemetabase.api.open-apimetabase.api.routes.common@@ -545,6 +546,10 @@:model/NotificationHandler:model/NotificationRecipient:model/NotificationSubscription+ :model/OAuthAccessToken+ :model/OAuthAuthorizationCode+ :model/OAuthClient+ :model/OAuthRefreshToken:model/ParameterCard:model/Permissions:model/PermissionsGroup@@ -1173,6 +1178,18 @@util}:model-exports #{:model/LoginHistory}}+ mcp+ {:team "Metabot"+ :api #{metabase.mcp.api}+ :uses #{agent-api+ api+ config+ oauth-server+ request+ server+ system+ util}}+measures{:team "Graphy":api #{metabase.measures.api}@@ -1400,6 +1417,22 @@:model/DashboardTab:model/User}}+ oauth-server+ {:team "UX West"+ :api #{metabase.oauth-server.api+ metabase.oauth-server.core+ metabase.oauth-server.init}+ :uses #{api+ appearance+ models+ settings+ system+ util}+ :model-exports #{:model/OAuthAccessToken+ :model/OAuthAuthorizationCode+ :model/OAuthClient+ :model/OAuthRefreshToken}}+;; TODO -- too many API namespacesparameters{:team "Graphy"@@ -1890,6 +1923,7 @@embeddinginitialization-statuslib-be+ oauth-serverpremium-featuresquery-processorrequest@@ -2927,11 +2961,13 @@premium-features}:model-imports #{:model/Card :model/Collection :model/Table}}+enterprise/metabot{:team "Metabot":api #{}:friends #{enterprise/agent-apislackbot+ mcpmetabot}:uses #{apilib-be@@ -2943,6 +2979,7 @@enterprise/transforms-python}:model-imports #{:model/Card :model/Transform}}+enterprise/permission-debug{:team "UX West":api #{metabase-enterprise.permission-debug.api}diff --git a/.gitignore b/.gitignoreindex 8e2e6b34fe6..abe9ff231dd 100644--- a/.gitignore+++ b/.gitignore@@ -176,3 +176,4 @@ CLAUDE.local.md/resources/python-sources/sqlglot-*.dist-info//resources/python-sources/.lock__pycache__/+.mcp.jsondiff --git a/deps.edn b/deps.ednindex 8f1337e5d3f..a76f70e40a3 100644--- a/deps.edn+++ b/deps.edn@@ -106,6 +106,7 @@methodical/methodical {:mvn/version "1.0.127"} ; drop-in replacements for Clojure multimethods and adds several advanced featuresmetosin/malli {:git/url "https://github.com/metabase/malli" ; Data-driven Schemas for Clojure/Script and babashka:git/sha "b4a2d78647a049870b316753d7aae7fb4ade3ae5"} ; patched to resolve an issue causing OOM+ net.carcdr/oidc-provider {:mvn/version "0.6.2"} ; OAuth/OIDC server abstract implementationnet.cgrand/macrovich {:mvn/version "0.2.2"} ; utils for writing macros for both Clojure & ClojureScriptnet.clojars.wkok/openai-clojure {:mvn/version "0.23.0":exclusions [lambdaisland/uri]} ; OpenAIdiff --git a/enterprise/backend/src/metabase_enterprise/serialization/v2/models.clj b/enterprise/backend/src/metabase_enterprise/serialization/v2/models.cljindex f3fa4be9d08..b2a2b0facd7 100644--- a/enterprise/backend/src/metabase_enterprise/serialization/v2/models.clj+++ b/enterprise/backend/src/metabase_enterprise/serialization/v2/models.clj@@ -92,6 +92,10 @@"NotificationHandler""NotificationRecipient""NotificationSubscription"+ "OAuthAccessToken"+ "OAuthAuthorizationCode"+ "OAuthClient"+ "OAuthRefreshToken""Permissions""PermissionsGroup""PermissionsGroupMembership"diff --git a/enterprise/backend/test/metabase_enterprise/serialization/models/entity_id_test.clj b/enterprise/backend/test/metabase_enterprise/serialization/models/entity_id_test.cljindex 3cf00879db1..a4dddc2eabb 100644--- a/enterprise/backend/test/metabase_enterprise/serialization/models/entity_id_test.clj+++ b/enterprise/backend/test/metabase_enterprise/serialization/models/entity_id_test.clj@@ -66,6 +66,10 @@:model/NotificationSubscription:model/NotificationHandler:model/NotificationRecipient+ :model/OAuthAccessToken+ :model/OAuthAuthorizationCode+ :model/OAuthClient+ :model/OAuthRefreshToken:model/ParameterCard:model/Permissions:model/PermissionsGroupdiff --git a/frontend/src/metabase/route-guards.tsx b/frontend/src/metabase/route-guards.tsxindex 0022176df86..69336a4a261 100644--- a/frontend/src/metabase/route-guards.tsx+++ b/frontend/src/metabase/route-guards.tsx@@ -15,6 +15,12 @@ import { canAccessTransforms } from "./transforms/selectors";type Props = { children: React.ReactElement };+/** Paths that are handled by the backend server, not the frontend SPA router. */+export const BACKEND_ONLY_PATH_PREFIXES = ["/oauth/"];++export const isBackendOnlyPath = (path: string): boolean =>+ BACKEND_ONLY_PATH_PREFIXES.some((prefix) => path.startsWith(prefix));+const getRedirectUrl = () => {const params = new URLSearchParams(window.location.search);const redirectUrlParam = params.get("redirect");@@ -68,7 +74,19 @@ const UserIsNotAuthenticated = connectedReduxRedirect<Props, State>({authenticatingSelector: (state) =>state.auth.loginPending || !state.auth.redirect,authenticatedSelector: (state) => !state.currentUser,- redirectAction: routerActions.replace,+ redirectAction: (location: {+ pathname: string;+ query?: Record<string, string>;+ }) => {+ if (isBackendOnlyPath(location.pathname)) {+ const params = new URLSearchParams(location.query);+ const qs = params.toString();+ const url = qs ? `${location.pathname}?${qs}` : location.pathname;+ window.location.replace(url);+ return routerActions.replace("/");+ }+ return routerActions.replace(location);+ },context: MetabaseReduxContext,});diff --git a/frontend/src/metabase/route-guards.unit.spec.tsx b/frontend/src/metabase/route-guards.unit.spec.tsxindex 2765aad6bb5..9cf212cf3a5 100644--- a/frontend/src/metabase/route-guards.unit.spec.tsx+++ b/frontend/src/metabase/route-guards.unit.spec.tsx@@ -6,6 +6,7 @@ import { renderWithProviders, screen } from "__support__/ui";import { createMockState } from "metabase-types/store/mocks";import { MetabaseReduxContext } from "./lib/redux";+import { isBackendOnlyPath } from "./route-guards";describe("route-guards", () => {describe("patched redux-auth-wrapper", () => {@@ -63,6 +64,25 @@ describe("route-guards", () => {expect(screen.queryByText(text)).not.toBeInTheDocument();});});++ describe("isBackendOnlyPath", () => {+ it("should return true for /oauth/ paths", () => {+ expect(isBackendOnlyPath("/oauth/authorize")).toBe(true);+ expect(isBackendOnlyPath("/oauth/authorize/decision")).toBe(true);+ expect(isBackendOnlyPath("/oauth/token")).toBe(true);+ });++ it("should return false for frontend paths", () => {+ expect(isBackendOnlyPath("/")).toBe(false);+ expect(isBackendOnlyPath("/auth/login")).toBe(false);+ expect(isBackendOnlyPath("/collection/root")).toBe(false);+ expect(isBackendOnlyPath("/question/1")).toBe(false);+ });++ it("should not match partial prefixes", () => {+ expect(isBackendOnlyPath("/oauthx/foo")).toBe(false);+ });+ });});function setupRouteGuard(opts: {diff --git a/resources/migrations/060/20260311_oauth_server_tables.yaml b/resources/migrations/060/20260311_oauth_server_tables.yamlnew file mode 100644index 00000000000..e57d0632c5a--- /dev/null+++ b/resources/migrations/060/20260311_oauth_server_tables.yaml@@ -0,0 +1,463 @@+## OAuth/OIDC provider server tables for embedded OAuth support++databaseChangeLog:+ - logicalFilePath: migrations/060_update_migrations.yaml++ # oauth_client table+ - changeSet:+ id: v60.2026-03-11T00:00:00+ author: epaget+ comment: Create oauth_client table for embedded OAuth provider+ changes:+ - createTable:+ tableName: oauth_client+ remarks: Stores OAuth2/OIDC client registrations for the embedded provider+ columns:+ - column:+ name: id+ type: int+ remarks: Auto-incrementing primary key+ autoIncrement: true+ constraints:+ primaryKey: true+ nullable: false+ - column:+ name: client_id+ type: varchar(255)+ remarks: OAuth client_id (UUID)+ constraints:+ nullable: false+ - column:+ name: client_secret_hash+ type: ${text.type}+ remarks: PBKDF2 hash of client secret+ constraints:+ nullable: true+ - column:+ name: redirect_uris+ type: ${text.type}+ remarks: JSON array of redirect URIs+ constraints:+ nullable: false+ - column:+ name: grant_types+ type: ${text.type}+ remarks: JSON array of grant types+ constraints:+ nullable: false+ - column:+ name: response_types+ type: ${text.type}+ remarks: JSON array of response types+ constraints:+ nullable: false+ - column:+ name: scopes+ type: ${text.type}+ remarks: JSON array of scopes+ constraints:+ nullable: false+ - column:+ name: token_endpoint_auth_method+ type: varchar(50)+ remarks: OAuth token endpoint auth method (e.g. client_secret_basic)+ constraints:+ nullable: true+ - column:+ name: client_name+ type: varchar(255)+ remarks: Human-readable client name+ constraints:+ nullable: true+ - column:+ name: client_uri+ type: ${text.type}+ remarks: URL of the client home page+ constraints:+ nullable: true+ - column:+ name: logo_uri+ type: ${text.type}+ remarks: URL of the client logo image+ constraints:+ nullable: true+ - column:+ name: contacts+ type: ${text.type}+ remarks: JSON array of contact strings+ constraints:+ nullable: true+ - column:+ name: registration_type+ type: varchar(50)+ remarks: "static or dynamic"+ constraints:+ nullable: false+ - column:+ name: client_type+ type: varchar(50)+ remarks: "confidential or public"+ defaultValue: "confidential"+ constraints:+ nullable: false+ - column:+ name: application_type+ type: varchar(50)+ remarks: OAuth application type (web or native), defaults to web+ defaultValue: web+ constraints:+ nullable: true+ - column:+ name: registration_access_token_hash+ type: ${text.type}+ remarks: Hashed RFC 7592 registration access token+ constraints:+ nullable: true+ - column:+ name: created_at+ type: ${timestamp_type}+ remarks: Timestamp of client registration+ defaultValueComputed: current_timestamp+ constraints:+ nullable: false+ - column:+ name: updated_at+ type: ${timestamp_type}+ remarks: Timestamp of last client update+ defaultValueComputed: current_timestamp+ constraints:+ nullable: false++ - changeSet:+ id: v60.2026-03-11T00:00:01+ author: epaget+ comment: Add unique index on oauth_client.client_id+ changes:+ - addUniqueConstraint:+ tableName: oauth_client+ constraintName: uq_oauth_client_client_id+ columnNames: client_id++ # oauth_authorization_code table+ - changeSet:+ id: v60.2026-03-11T00:00:02+ author: epaget+ comment: Create oauth_authorization_code table+ changes:+ - createTable:+ tableName: oauth_authorization_code+ remarks: Stores authorization codes for the embedded OAuth provider+ columns:+ - column:+ name: id+ type: int+ remarks: Auto-incrementing primary key+ autoIncrement: true+ constraints:+ primaryKey: true+ nullable: false+ - column:+ name: code+ type: varchar(255)+ remarks: The authorization code string+ constraints:+ nullable: false+ - column:+ name: user_id+ type: int+ remarks: FK to core_user.id+ constraints:+ nullable: false+ - column:+ name: client_id+ type: varchar(255)+ remarks: The OAuth client_id+ constraints:+ nullable: false+ - column:+ name: redirect_uri+ type: ${text.type}+ remarks: Redirect URI for this authorization+ constraints:+ nullable: false+ - column:+ name: scope+ type: ${text.type}+ remarks: JSON array of scope strings+ constraints:+ nullable: false+ - column:+ name: nonce+ type: varchar(255)+ remarks: OIDC nonce value+ constraints:+ nullable: true+ - column:+ name: expiry+ type: bigint+ remarks: Milliseconds since epoch+ constraints:+ nullable: false+ - column:+ name: code_challenge+ type: varchar(255)+ remarks: PKCE code challenge+ constraints:+ nullable: true+ - column:+ name: code_challenge_method+ type: varchar(10)+ remarks: PKCE code challenge method+ constraints:+ nullable: true+ - column:+ name: resource+ type: ${text.type}+ remarks: JSON array of resource URIs (RFC 8707)+ constraints:+ nullable: true+ - column:+ name: created_at+ type: ${timestamp_type}+ remarks: Timestamp of code creation+ defaultValueComputed: current_timestamp+ constraints:+ nullable: false++ - changeSet:+ id: v60.2026-03-11T00:00:03+ author: epaget+ comment: Add unique index on oauth_authorization_code.code+ changes:+ - addUniqueConstraint:+ tableName: oauth_authorization_code+ constraintName: uq_oauth_authorization_code_code+ columnNames: code++ - changeSet:+ id: v60.2026-03-11T00:00:04+ author: epaget+ comment: Add index on oauth_authorization_code.expiry for cleanup+ changes:+ - createIndex:+ tableName: oauth_authorization_code+ indexName: idx_oauth_authorization_code_expiry+ columns:+ - column:+ name: expiry++ - changeSet:+ id: v60.2026-03-11T00:00:05+ author: epaget+ comment: Add index on oauth_authorization_code.user_id+ changes:+ - createIndex:+ tableName: oauth_authorization_code+ indexName: idx_oauth_authorization_code_user_id+ columns:+ - column:+ name: user_id++ - changeSet:+ id: v60.2026-03-11T00:00:06+ author: epaget+ comment: Add FK on oauth_authorization_code.user_id+ changes:+ - addForeignKeyConstraint:+ baseTableName: oauth_authorization_code+ baseColumnNames: user_id+ referencedTableName: core_user+ referencedColumnNames: id+ constraintName: fk_oauth_authorization_code_user_id++ # oauth_access_token table+ - changeSet:+ id: v60.2026-03-11T00:00:07+ author: epaget+ comment: Create oauth_access_token table+ changes:+ - createTable:+ tableName: oauth_access_token+ remarks: Stores access tokens for the embedded OAuth provider+ columns:+ - column:+ name: id+ type: int+ remarks: Auto-incrementing primary key+ autoIncrement: true+ constraints:+ primaryKey: true+ nullable: false+ - column:+ name: token+ type: varchar(255)+ remarks: The access token string+ constraints:+ nullable: false+ - column:+ name: user_id+ type: int+ remarks: FK to core_user.id (null for client_credentials)+ constraints:+ nullable: true+ - column:+ name: client_id+ type: varchar(255)+ remarks: The OAuth client_id+ constraints:+ nullable: false+ - column:+ name: scope+ type: ${text.type}+ remarks: JSON array of scopes+ constraints:+ nullable: false+ - column:+ name: expiry+ type: bigint+ remarks: Milliseconds since epoch+ constraints:+ nullable: false+ - column:+ name: resource+ type: ${text.type}+ remarks: JSON array of resource URIs+ constraints:+ nullable: true+ - column:+ name: revoked_at+ type: ${timestamp_type}+ remarks: Null if active+ constraints:+ nullable: true+ - column:+ name: created_at+ type: ${timestamp_type}+ remarks: Timestamp of token creation+ defaultValueComputed: current_timestamp+ constraints:+ nullable: false++ - changeSet:+ id: v60.2026-03-11T00:00:08+ author: epaget+ comment: Add unique index on oauth_access_token.token+ changes:+ - addUniqueConstraint:+ tableName: oauth_access_token+ constraintName: uq_oauth_access_token_token+ columnNames: token++ - changeSet:+ id: v60.2026-03-11T00:00:09+ author: epaget+ comment: Add index on oauth_access_token.expiry+ changes:+ - createIndex:+ tableName: oauth_access_token+ indexName: idx_oauth_access_token_expiry+ columns:+ - column:+ name: expiry++ - changeSet:+ id: v60.2026-03-11T00:00:10+ author: epaget+ comment: Add index on oauth_access_token.user_id+ changes:+ - createIndex:+ tableName: oauth_access_token+ indexName: idx_oauth_access_token_user_id+ columns:+ - column:+ name: user_id++ - changeSet:+ id: v60.2026-03-11T00:00:11+ author: epaget+ comment: Add FK on oauth_access_token.user_id+ changes:+ - addForeignKeyConstraint:+ baseTableName: oauth_access_token+ baseColumnNames: user_id+ referencedTableName: core_user+ referencedColumnNames: id+ constraintName: fk_oauth_access_token_user_id++ # oauth_refresh_token table+ - changeSet:+ id: v60.2026-03-11T00:00:12+ author: epaget+ comment: Create oauth_refresh_token table+ changes:+ - createTable:+ tableName: oauth_refresh_token+ remarks: Stores refresh tokens for the embedded OAuth provider+ columns:+ - column:+ name: id+ type: int+ remarks: Auto-incrementing primary key+ autoIncrement: true+ constraints:+ primaryKey: true+ nullable: false+ - column:+ name: token+ type: varchar(255)+ remarks: The refresh token string+ constraints:+ nullable: false+ - column:+ name: user_id+ type: int+ remarks: FK to core_user.id+ constraints:+ nullable: true+ - column:+ name: client_id+ type: varchar(255)+ remarks: The OAuth client_id+ constraints:+ nullable: false+ - column:+ name: scope+ type: ${text.type}+ remarks: JSON array of scopes+ constraints:+ nullable: false+ - column:+ name: resource+ type: ${text.type}+ remarks: JSON array of resource URIs+ constraints:+ nullable: true+ - column:+ name: expiry+ type: bigint+ remarks: Milliseconds since epoch (null means no expiry)+ constraints:+ nullable: true+ - column:+ name: revoked_at+ type: ${timestamp_type}+ remarks: Null if active+ constraints:+ nullable: true+ - column:+ name: created_at+ type: ${timestamp_type}+ remarks: Timestamp of token creation+ defaultValueComputed: current_timestamp+ constraints:+ nullable: false++ - changeSet:+ id: v60.2026-03-11T00:00:13+ author: epaget+ comment: Add unique index on oauth_refresh_token.token+ changes:+ - addUniqueConstraint:+ tableName: oauth_refresh_token+ constraintName: uq_oauth_refresh_token_token+ columnNames: tokendiff --git a/src/metabase/api/macros/defendpoint/tools_manifest.clj b/src/metabase/api/macros/defendpoint/tools_manifest.cljindex 555bc4e2fd2..f05a1186def 100644--- a/src/metabase/api/macros/defendpoint/tools_manifest.clj+++ b/src/metabase/api/macros/defendpoint/tools_manifest.clj@@ -177,7 +177,8 @@input-schema (merge-input-schemas defs form)resp-schema (response-schema->json-schema defs (:response-schema form))annotations (infer-annotations method (:annotations tool-md))- task-support (:task-support tool-md)]+ task-support (:task-support tool-md)+ scope (get-in form [:metadata :scope])](cond-> {:name tool-name:description description:endpoint {:method (u/upper-case-en (name method))@@ -185,7 +186,8 @@input-schema (assoc :inputSchema input-schema)resp-schema (assoc :responseSchema resp-schema)(seq annotations) (assoc :annotations annotations)- task-support (assoc :execution {:taskSupport (name task-support)}))))+ task-support (assoc :execution {:taskSupport (name task-support)})+ (string? scope) (assoc :scope scope))))(defn check-tool-uniqueness"Throws if `tools` contains duplicate `:name` values. The exception message lists eachdiff --git a/src/metabase/api_routes/routes.clj b/src/metabase/api_routes/routes.cljindex a744b790fcc..66a1cb02f35 100644--- a/src/metabase/api_routes/routes.clj+++ b/src/metabase/api_routes/routes.clj@@ -32,6 +32,7 @@[metabase.llm.api][metabase.logger.api][metabase.login-history.api]+ [metabase.mcp.api][metabase.measures.api][metabase.metabot.api][metabase.metabot.api.entity-analysis]@@ -94,6 +95,7 @@metabase.indexed-entities.api/keep-memetabase.logger.api/keep-memetabase.login-history.api/keep-me+ metabase.mcp.api/keep-memetabase.measures.api/keep-memetabase.metrics.api/keep-memetabase.model-persistence.api/keep-me@@ -190,6 +192,7 @@"/llm" (+auth metabase.llm.api/routes)"/logger" (+auth 'metabase.logger.api)"/login-history" (+auth 'metabase.login-history.api)+ "/mcp" metabase.mcp.api/handler"/measure" (+auth 'metabase.measures.api)"/metabot" metabase.metabot.api/routes"/metric" (+auth 'metabase.metrics.api)diff --git a/src/metabase/cmd/copy.clj b/src/metabase/cmd/copy.cljindex 8fa6c812057..51b99e22081 100644--- a/src/metabase/cmd/copy.clj+++ b/src/metabase/cmd/copy.clj@@ -126,6 +126,10 @@;; 59+:model/Measure;; 60++ :model/OAuthClient+ :model/OAuthAuthorizationCode+ :model/OAuthAccessToken+ :model/OAuthRefreshToken:model/Metabot:model/MetabotConversation:model/MetabotMessagediff --git a/src/metabase/core/init.clj b/src/metabase/core/init.cljindex a0bbda245b8..c7bfdecf7e2 100644--- a/src/metabase/core/init.clj+++ b/src/metabase/core/init.clj@@ -41,6 +41,7 @@[metabase.model-persistence.init][metabase.models.init][metabase.notification.init]+ [metabase.oauth-server.init][metabase.parameters.init][metabase.permissions.init][metabase.premium-features.init]diff --git a/src/metabase/mcp/api.clj b/src/metabase/mcp/api.cljnew file mode 100644index 00000000000..5fc384e8854--- /dev/null+++ b/src/metabase/mcp/api.clj@@ -0,0 +1,292 @@+(ns metabase.mcp.api+ "MCP (Model Context Protocol) Streamable HTTP transport handler.+ Exposes Metabase's agent tools via JSON-RPC 2.0 over a single `/api/mcp` endpoint."+ (:require+ [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]+ [metabase.mcp.tools :as mcp.tools]+ [metabase.oauth-server.core :as oauth-server]+ [metabase.request.core :as request]+ [metabase.server.streaming-response :as streaming-response]+ [metabase.system.core :as system]+ [metabase.util.json :as json]+ [metabase.util.log :as log]+ [oidc-provider.store :as oidc.store])+ (:import+ (java.io BufferedWriter OutputStreamWriter)+ (java.net URI)+ (java.nio.charset StandardCharsets)+ (java.util UUID)))++(set! *warn-on-reflection* true)++;;; --------------------------------------------------- Sessions ----------------------------------------------------++(defn- create-session!+ "Generate an MCP session ID for protocol compatibility.+ The server currently treats MCP sessions as degenerate: callers must still+ send a session ID after `initialize`, but the ID is not otherwise required+ for auth, initialization state, or server-side validation."+ [_user-id]+ (str (UUID/randomUUID)))++;;; -------------------------------------------------- Auth --------------------------------------------------------++(defn- validate-bearer-token+ "Look up and validate an OAuth bearer token. Returns `{:user-id <int> :scopes <set>}` on success, nil on failure."+ [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 #{})})))))))++;;; ------------------------------------------------- JSON-RPC 2.0 --------------------------------------------------++(def ^:private server-info+ {:name "metabase"+ :version "0.1.0"})++(def ^:private protocol-version "2025-03-26")++(defn- jsonrpc-response [id result]+ {:jsonrpc "2.0" :id id :result result})++(defn- jsonrpc-error [id code message]+ {:jsonrpc "2.0" :id id :error {:code code :message message}})++(defn- handle-initialize [id params]+ (when-let [client-info (:clientInfo params)]+ (log/infof "MCP client connected: %s %s" (:name client-info) (:version client-info)))+ (jsonrpc-response+ id+ {:protocolVersion protocol-version+ :capabilities {:tools {}}+ :serverInfo server-info}))++(defn- handle-tools-list [id _params token-scopes]+ (jsonrpc-response id {:tools (mcp.tools/list-tools token-scopes)}))++(defn- handle-tools-call [id params token-scopes]+ (let [tool-name (:name params)+ arguments (or (:arguments params) {})]+ (jsonrpc-response id (mcp.tools/call-tool token-scopes tool-name arguments))))++(defn- handle-ping [id _params]+ (jsonrpc-response id {}))++(defn- dispatch-request+ "Dispatch a single JSON-RPC request. Returns a response map or nil for notifications."+ [msg _session-id token-scopes]+ (let [id (:id msg)+ method (:method msg)+ params (:params msg)]+ (try+ (case method+ "notifications/initialized" nil+ "tools/list" (handle-tools-list id params token-scopes)+ "tools/call" (handle-tools-call id params token-scopes)+ "ping" (handle-ping id params)+ (if id+ (jsonrpc-error id -32601 (str "Method not found: " method))+ nil))+ (catch Throwable e+ (log/error e "Error dispatching JSON-RPC method" method)+ (jsonrpc-error id -32603 (or (ex-message e) "Internal error"))))))++;;; ----------------------------------------------------- SSE ------------------------------------------------------++(defn- accepts-sse?+ "Return true if the request's Accept header includes text/event-stream."+ [request]+ (some-> (get-in request [:headers "accept"])+ (str/includes? "text/event-stream")))++(defn- sse-body+ "Format a sequence of JSON-RPC messages as SSE event text."+ [messages]+ (str/join (map #(str "event: message\ndata: " (json/encode %) "\n\n") messages)))++;;; -------------------------------------------------- Responses ---------------------------------------------------++(defn- json-response+ ([status body]+ (json-response status body nil))+ ([status body extra-headers]+ {:status status+ :headers (merge {"Content-Type" "application/json"} extra-headers)+ :body (json/encode body)}))++(defn- sse-response+ "Return a plain Ring response with SSE-formatted body for POST requests."+ ([messages]+ (sse-response messages nil))+ ([messages extra-headers]+ {:status 200+ :headers (merge {"Content-Type" "text/event-stream"+ "Cache-Control" "no-cache"}+ extra-headers)+ :body (sse-body messages)}))++;;; ------------------------------------------------- Validation --------------------------------------------------++(defn- validate-origin+ "Validate the Origin header to prevent DNS rebinding attacks (MCP spec requirement).+ Returns a 403 response if Origin is present and doesn't match the request's Host header.+ Non-browser clients that omit the Origin header are allowed through."+ [request]+ (when-let [origin (get-in request [:headers "origin"])]+ (let [host (get-in request [:headers "host"])]+ (when-not (try+ (let [origin-host (.getHost (URI. origin))+ request-host (first (str/split (str host) #":"))]+ (= origin-host request-host))+ (catch Exception _ false))+ (json-response 403 (jsonrpc-error nil -32600 "Origin not allowed"))))))++(defn- session-error-response+ "Return an HTTP error response when the MCP session header is missing, or nil if present.+ The session ID is compatibility-only and is not validated server-side."+ [session-id]+ (when (str/blank? session-id)+ (json-response 400 (jsonrpc-error nil -32600 "Missing Mcp-Session-Id header"))))++;;; -------------------------------------------------- Handlers ---------------------------------------------------++(defn- handle-post+ "Handle a POST request containing one or more JSON-RPC messages."+ [user-id request]+ (let [body (:body request)+ session-id (get-in request [:headers "mcp-session-id"])+ batch? (sequential? body)+ session-err (delay (session-error-response session-id))]+ (cond+ (nil? body)+ (json-response 400 (jsonrpc-error nil -32700 "Parse error: empty body"))++ (and (not (map? body)) (not batch?))+ (json-response 400 (jsonrpc-error nil -32600 "Invalid request: expected object or array"))++ ;; JSON-RPC 2.0: empty batch is invalid+ (and batch? (empty? body))+ (json-response 400 (jsonrpc-error nil -32600 "Invalid request: empty batch"))++ ;; MCP spec: "The initialize request MUST NOT be part of a JSON-RPC batch"+ (and batch? (some #(= "initialize" (:method %)) body))+ (json-response 400 (jsonrpc-error nil -32600 "initialize must not be batched"))++ ;; Initialize: create session and return response with session header+ (and (not batch?) (= "initialize" (:method body)))+ (let [session-id (create-session! user-id)+ init-response (handle-initialize (:id body) (:params body))]+ (if (accepts-sse? request)+ (sse-response [init-response] {"Mcp-Session-Id" session-id})+ (json-response 200 init-response {"Mcp-Session-Id" session-id})))++ ;; All other requests require a valid session (400 for missing header, 404 for invalid)+ (some? @session-err) @session-err++ :else+ (let [messages (if batch? body [body])+ results (mapv #(dispatch-request % session-id (:token-scopes request)) messages)+ responses (filterv some? results)]+ (cond+ (empty? responses)+ {:status 202 :headers {} :body ""}++ (accepts-sse? request)+ (sse-response responses)++ (and (not batch?) (= 1 (count responses)))+ (json-response 200 (first responses))++ :else+ (json-response 200 responses))))))++(defn- handle-get+ "Handle a GET request for SSE stream (keepalive for server-initiated notifications)."+ [_user-id request respond raise]+ (let [session-id (get-in request [:headers "mcp-session-id"])+ session-err (session-error-response session-id)]+ (cond+ (some? session-err)+ (respond session-err)++ :else+ (let [resp (streaming-response/streaming-response+ {:content-type "text/event-stream"+ :headers {"Cache-Control" "no-cache"}+ :status 200}+ [os canceled-chan]+ (let [writer (BufferedWriter. (OutputStreamWriter. os StandardCharsets/UTF_8))]+ (loop []+ (when-not (a/poll! canceled-chan)+ (.write writer ": keepalive\n\n")+ (.flush writer)+ (Thread/sleep 30000)+ (recur)))))]+ (compojure.response/send* resp request respond raise)))))++(defn- handle-delete+ "Handle a DELETE request to tear down a session."+ [_user-id request]+ (let [session-id (get-in request [:headers "mcp-session-id"])+ session-err (session-error-response session-id)]+ (or session-err+ {:status 200 :headers {"Content-Type" "application/json"} :body ""})))++;;; ---------------------------------------------------- Handler ---------------------------------------------------++(defn- www-authenticate-discovery []+ (str "Bearer realm=\"mcp\" resource_metadata=\"" (system/site-url) "/.well-known/oauth-protected-resource/api/mcp\""))++(def ^{:arglists '([request respond raise])} handler+ "Ring async handler for the MCP endpoint.+ Uses JSON-RPC 2.0 over HTTP rather than REST, so the OpenAPI spec is empty."+ (open-api/handler-with-open-api-spec+ (fn [request respond raise]+ (let [origin-error (validate-origin request)+ bearer-token (oauth-server/extract-bearer-token request)+ session-auth api/*current-user-id*]+ (letfn [(dispatch [user-id token-scopes]+ (request/with-current-user user-id+ (try+ (let [request (assoc request :token-scopes token-scopes)]+ (case (:request-method request)+ :post (respond (handle-post user-id request))+ :get (handle-get user-id request respond raise)+ :delete (respond (handle-delete user-id request))+ (respond (json-response 405 (jsonrpc-error nil -32600 "Method not allowed")))))+ (catch Throwable e+ (raise e)))))]+ (cond+ (some? origin-error)+ (respond origin-error)++ ;; Session auth (browser/cookie) — unrestricted scopes+ session-auth+ (dispatch session-auth #{::scope/unrestricted})++ ;; Bearer token auth — validate and extract scopes+ bearer-token+ (if-let [{:keys [user-id scopes]} (validate-bearer-token bearer-token)]+ (dispatch user-id scopes)+ (respond (json-response 401 (jsonrpc-error nil -32603 "Invalid bearer token")+ {"WWW-Authenticate" "Bearer error=\"invalid_token\""})))++ ;; No auth at all — return 401 with discovery+ :else+ (respond (json-response 401 (jsonrpc-error nil -32603 "Authentication required")+ {"WWW-Authenticate" (www-authenticate-discovery)}))))))+ (constantly nil)))diff --git a/src/metabase/mcp/tools.clj b/src/metabase/mcp/tools.cljnew file mode 100644index 00000000000..4a230847e49--- /dev/null+++ b/src/metabase/mcp/tools.clj@@ -0,0 +1,244 @@+(ns metabase.mcp.tools+ "MCP tool dispatch. Generates tool definitions from defendpoint metadata and delegates+ tool calls to existing agent API endpoints."+ (:require+ [clojure.core.async :as a]+ [clojure.string :as str]+ [clojure.walk :as walk]+ [metabase.agent-api.api :as agent-api]+ [metabase.api.common :as api]+ [metabase.api.macros.defendpoint.tools-manifest :as tools-manifest]+ [metabase.api.macros.scope :as scope]+ [metabase.config.core :as config]+ [metabase.server.streaming-response :as streaming-response]+ [metabase.util :as u]+ [metabase.util.json :as json])+ (:import+ (java.io ByteArrayOutputStream)+ (java.net URLEncoder)+ (metabase.server.streaming_response StreamingResponse)))++(set! *warn-on-reflection* true)++(comment streaming-response/keep-me) ; ensure StreamingResponse class is loaded++(defn- generate-manifest+ "Generate tools manifest from agent API endpoint metadata."+ []+ (tools-manifest/generate-tools-manifest+ {'metabase.agent-api.api "/api/agent"}))++(def ^:private manifest-delay+ (delay (generate-manifest)))++(defn- manifest+ "Return the tools manifest. Cached in prod, recomputed each call in dev."+ []+ (if config/is-dev?+ (generate-manifest)+ @manifest-delay))++(defn- collect-refs+ "Walk a JSON Schema and return a set of def names referenced via $ref."+ [schema]+ (let [refs (volatile! #{})]+ (walk/postwalk+ (fn [x]+ (when-let [ref (and (map? x) (:$ref x))]+ (when-let [[_ def-name] (re-matches #"#/\$defs/(.+)" ref)]+ (vswap! refs conj def-name)))+ x)+ schema)+ @refs))++(defn- referenced-defs+ "Return the subset of `all-defs` transitively referenced from `schema`."+ [schema all-defs]+ (loop [to-visit (collect-refs schema)+ visited #{}+ result {}]+ (if-let [def-name (first to-visit)]+ (if (visited def-name)+ (recur (disj to-visit def-name) visited result)+ (let [def-schema (get all-defs def-name)]+ (recur (into (disj to-visit def-name) (when def-schema (collect-refs def-schema)))+ (conj visited def-name)+ (cond-> result def-schema (assoc def-name def-schema)))))+ result)))++(defn- scope-matches?+ "Does `token-scopes` grant access to a tool with the given `tool-scope`?+ - nil token-scopes → always matches (internal callers)+ - ::scope/unrestricted in token-scopes → always matches+ - nil tool-scope → always matches (tool has no scope restriction)+ - empty token-scopes #{} → only matches tools with nil tool-scope+ - wildcard scopes like \"agent:*\" match any tool scope starting with \"agent:\""+ [token-scopes tool-scope]+ (or (nil? token-scopes)+ (contains? token-scopes ::scope/unrestricted)+ (nil? tool-scope)+ (contains? token-scopes tool-scope)+ (some (fn [s]+ (when (string? s)+ (when-let [prefix (when (str/ends-with? s ":*")+ (subs s 0 (dec (count s))))]+ (str/starts-with? tool-scope prefix))))+ token-scopes)))++(defn list-tools+ "Return the tool definitions suitable for MCP `tools/list` responses.+ Inlines referenced `$defs` into each tool's `inputSchema` so that `$ref` pointers resolve.+ When `token-scopes` is provided, only tools whose scope matches are included."+ [token-scopes]+ (let [{:keys [tools $defs]} (manifest)]+ (into []+ (comp (filter #(scope-matches? token-scopes (:scope %)))+ (map (fn [tool]+ (let [input (:inputSchema tool)+ used (when (and (seq $defs) input)+ (referenced-defs input $defs))]+ (cond-> {:name (:name tool)+ :description (:description tool)+ :inputSchema (cond-> input+ ;; the root object of an MCP tool inputSchema MUST be an+ ;; "object" malli.json-schema rightly doesn't set type: "object"+ ;; on a :or schema.+ (not (:type input)) (assoc :type "object"))}+ (seq used) (update :inputSchema assoc :$defs used))))))+ tools)))++(defn- build-tool-index []+ (into {} (map (juxt :name identity)) (:tools (manifest))))++(def ^:private tool-index-delay+ (delay (build-tool-index)))++(defn- tool-index+ "Lookup from tool name to its full manifest definition. Cached in prod, recomputed each call in dev."+ []+ (if config/is-dev?+ (build-tool-index)+ @tool-index-delay))++;;; ------------------------------------------------- Tool Dispatch -------------------------------------------------++(defn- text-content+ "Wrap a value as MCP text content."+ [v]+ {:content [{:type "text" :text (if (string? v) v (json/encode v))}]})++(defn- error-content+ "Wrap an error message as MCP error content."+ [message]+ {:content [{:type "text" :text message}] :isError true})++(defn- capture-streaming-response+ "Execute a StreamingResponse in-process by writing to a ByteArrayOutputStream,+ then parse the JSON output and return it as MCP text content.++ NOTE: This intentionally bypasses the normal StreamingResponse lifecycle (thread pool,+ gzip, donechan delivery) because the agent-api streaming functions only write JSON to+ the output stream and don't depend on `streaming-response/*response*` or other+ infrastructure bindings. BOT-1120 tracks streaming MCP responses without buffering+ in memory, which will replace this approach."+ [^StreamingResponse response]+ (let [baos (ByteArrayOutputStream.)+ canceled-chan (a/promise-chan)+ f (.f response)]+ (f baos canceled-chan)+ (text-content (json/decode+kw (.toString baos "UTF-8")))))++(defn- deliver-agent-api-response+ "Dispatch to agent API routes and deliver response to promise."+ [result method path token-scopes body]+ (agent-api/routes+ (cond-> {:request-method method+ :uri path+ :metabase-user-id api/*current-user-id*+ :token-scopes token-scopes}+ body (assoc :body body))+ (fn [response] (deliver result response))+ (fn [error] (deliver result {:status 500 :body {:message (ex-message error)}}))))++(defn- invoke-agent-api+ "Invoke an Agent API endpoint with a synthetic Ring request.+ Returns MCP content (text-content on success, error-content on failure).++ Propagates `token-scopes` from the original MCP request so that scope restrictions+ are preserved through the synthetic request."+ [method path token-scopes & [body]]+ (let [result (promise)]+ (deliver-agent-api-response result method path token-scopes body)+ (let [response (deref result 30000 {:status 504 :body {:message "Timeout"}})]+ (cond+ (instance? StreamingResponse (:body response))+ (capture-streaming-response (:body response))++ (= 200 (:status response))+ (text-content (:body response))++ :else+ (error-content (or (some-> response :body :message)+ (some-> response :body :error)+ (str "Agent API error: " (:status response))))))))++(defn- interpolate-path+ "Replace `{param}` placeholders in `path` with values from `arguments`.+ Returns `[resolved-path remaining-args]` where remaining-args has path params removed."+ [path arguments]+ (let [params (re-seq #"\{([^}]+)\}" path)+ resolved (reduce (fn [p [placeholder k]]+ (let [v (get arguments (keyword k))]+ (when (nil? v)+ (throw (ex-info (str "Missing required path parameter: " k)+ {:parameter k :path path})))+ (str/replace p placeholder (URLEncoder/encode (str v) "UTF-8"))))+ path+ params)+ path-keys (set (map (comp keyword second) params))]+ [resolved (apply dissoc arguments path-keys)]))++(defn- strip-api-prefix+ "Strip the `/api/agent` prefix from manifest paths, since `invoke-agent-api`+ calls `agent-api/routes` directly which expects `/v1/...` paths."+ [path]+ (str/replace-first path #"^/api/agent" ""))++(defn- invoke-agent-api-with-params+ "Invoke an Agent API endpoint with query parameters for GET/DELETE requests.+ Appends `params` as a query string to `path`."+ [method path token-scopes params]+ (if (and (seq params) (not= :post method))+ (let [query-string (->> params+ (map (fn [[k v]] (str (name k) "=" (URLEncoder/encode (str v) "UTF-8"))))+ (str/join "&"))]+ (invoke-agent-api method (str path "?" query-string) token-scopes))+ (invoke-agent-api method path token-scopes (when (= :post method) params))))++(defn- dispatch-via-agent-api+ "Generic dispatch for tools whose responseFormat is \"json\".+ Looks up method/path from the tool definition, interpolates path params,+ and calls `invoke-agent-api`. For POST requests, remaining args are sent as the+ request body. For GET/DELETE requests, remaining args are sent as query params."+ [tool-def arguments token-scopes]+ (let [{:keys [method path]} (:endpoint tool-def)+ method (keyword (u/lower-case-en method))+ [resolved-path+ remaining-args] (interpolate-path path arguments)+ api-path (strip-api-prefix resolved-path)]+ (invoke-agent-api-with-params method api-path token-scopes remaining-args)))++(defn call-tool+ "Dispatch an MCP `tools/call` request to the appropriate handler.+ `token-scopes` from the original MCP session are propagated to the synthetic+ agent-api request so that scope restrictions are preserved.+ Returns MCP content on success, or error content on failure."+ [token-scopes tool-name arguments]+ (if-let [tool-def (get (tool-index) tool-name)]+ (if-not (scope-matches? token-scopes (:scope tool-def))+ (error-content (str "Insufficient scope to call tool: " tool-name))+ (try+ (dispatch-via-agent-api tool-def arguments token-scopes)+ (catch Exception e+ (error-content (or (ex-message e) "Internal error")))))+ (error-content (str "Unknown tool: " tool-name))))diff --git a/src/metabase/models/resolution.clj b/src/metabase/models/resolution.cljindex 72b098e2697..9cb8ac433c6 100644--- a/src/metabase/models/resolution.clj+++ b/src/metabase/models/resolution.clj@@ -63,6 +63,10 @@:model/ModerationReview metabase.content-verification.models.moderation-review:model/NativeQuerySnippet metabase.native-query-snippets.models.native-query-snippet:model/Notification metabase.notification.models+ :model/OAuthAccessToken metabase.oauth-server.models.oauth-access-token+ :model/OAuthAuthorizationCode metabase.oauth-server.models.oauth-authorization-code+ :model/OAuthClient metabase.oauth-server.models.oauth-client+ :model/OAuthRefreshToken metabase.oauth-server.models.oauth-refresh-token:model/NotificationCard metabase.notification.models:model/NotificationHandler metabase.notification.models:model/NotificationRecipient metabase.notification.modelsdiff --git a/src/metabase/oauth_server/api.clj b/src/metabase/oauth_server/api.cljnew file mode 100644index 00000000000..6d2c66c4828--- /dev/null+++ b/src/metabase/oauth_server/api.clj@@ -0,0 +1,18 @@+(ns metabase.oauth-server.api+ "Top-level route handlers for the embedded OAuth/OIDC provider.+ Assembles handlers from [[metabase.oauth-server.api.oauth]] and [[metabase.oauth-server.api.metadata]]."+ (:require+ [metabase.api.macros :as api.macros]+ [metabase.oauth-server.api.metadata]+ [metabase.oauth-server.api.oauth]))++(comment metabase.oauth-server.api.metadata/keep-me+ metabase.oauth-server.api.oauth/keep-me)++(def ^{:arglists '([request respond raise])} well-known-routes+ "Handler for `/.well-known/` routes (top-level, per RFC 8414 and RFC 9728)."+ (api.macros/ns-handler 'metabase.oauth-server.api.metadata))++(def ^{:arglists '([request respond raise])} oauth-routes+ "Handler for `/oauth/` routes."+ (api.macros/ns-handler 'metabase.oauth-server.api.oauth))diff --git a/src/metabase/oauth_server/api/metadata.clj b/src/metabase/oauth_server/api/metadata.cljnew file mode 100644index 00000000000..05bc7515f3c--- /dev/null+++ b/src/metabase/oauth_server/api/metadata.clj@@ -0,0 +1,57 @@+(ns metabase.oauth-server.api.metadata+ "Endpoints for OAuth discovery and resource metadata.+ Mounted under `/.well-known/`."+ (:require+ [metabase.api.macros :as api.macros]+ [metabase.oauth-server.core :as oauth-server]+ [metabase.oauth-server.settings :as oauth-settings]+ [metabase.system.core :as system]+ [oidc-provider.core :as oidc]))++(set! *warn-on-reflection* true)++(defn- discovery-response+ "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))]+ {:status 200+ :headers {"Content-Type" "application/json"}+ :body (if (oauth-settings/oauth-server-dynamic-registration-enabled)+ metadata+ (dissoc metadata :registration_endpoint "registration_endpoint"))})))++(api.macros/defendpoint :get "/oauth-authorization-server"+ :- [:or+ [:map+ [:status [:= 200]]+ [:body [:map+ [:issuer :string]+ [:authorization_endpoint :string]+ [:token_endpoint :string]]]]+ [:map+ [:status [:= 404]]+ [:body [:map [:error [:= "not_found"]]]]]]+ "Returns the OAuth Authorization Server Metadata (RFC 8414)."+ []+ (or (discovery-response)+ {:status 404 :body {:error "not_found"}}))++(api.macros/defendpoint :get "/oauth-protected-resource/api/mcp"+ :- [:map+ [:status [:= 200]]+ [:body [:map+ [:resource :string]+ [:authorization_servers [:sequential :string]]+ [:scopes_supported [:sequential :string]]+ [:bearer_methods_supported [:sequential :string]]]]]+ "Returns OAuth Protected Resource Metadata (RFC 9728) for the MCP endpoint."+ []+ (let [site-url (system/site-url)]+ {:status 200+ :headers {"Content-Type" "application/json"}+ :body {:resource (str site-url "/api/mcp")+ :authorization_servers [site-url]+ :scopes_supported (oauth-server/all-agent-scopes)+ :bearer_methods_supported ["header"]}}))diff --git a/src/metabase/oauth_server/api/oauth.clj b/src/metabase/oauth_server/api/oauth.cljnew file mode 100644index 00000000000..596737bf305--- /dev/null+++ b/src/metabase/oauth_server/api/oauth.clj@@ -0,0 +1,226 @@+(ns metabase.oauth-server.api.oauth+ "OAuth protocol endpoints. Mounted under `/oauth/`."+ (:require+ [buddy.core.codecs :as codecs]+ [buddy.core.nonce :as nonce]+ [clojure.string :as str]+ [metabase.api.macros :as api.macros]+ [metabase.oauth-server.consent-page :as consent-page]+ [metabase.oauth-server.core :as oauth-server]+ [metabase.oauth-server.settings :as oauth-settings]+ [metabase.system.core :as system]+ [oidc-provider.core :as oidc]+ [oidc-provider.protocol :as proto]+ [oidc-provider.registration :as reg]+ [oidc-provider.util :as oidc-util]+ [ring.util.response :as response])+ (:import+ (java.net URLEncoder)))++(set! *warn-on-reflection* true)++(def ^:private csrf-cookie-name "metabase.OAUTH_CSRF")++(defn- generate-csrf-token+ "Generate a random 32-hex-char CSRF token."+ []+ (codecs/bytes->hex (nonce/random-bytes 16)))++(defn- login-redirect-url+ "Build a redirect URL to the login page that will redirect back to the given path after login.+ Only allows redirecting back to OAuth paths to prevent open-redirect attacks."+ [request]+ (let [site-url (system/site-url)+ uri (:uri request)+ query (:query-string request)+ return-path (when (str/starts-with? uri "/oauth/")+ (if query (str uri "?" query) uri))+ redirect (if return-path+ (str site-url "/auth/login?redirect=" (URLEncoder/encode ^String return-path "UTF-8"))+ (str site-url "/auth/login"))]+ redirect))++;;; ------------------------------------------------ Endpoints ----------------------------------------------------++(api.macros/defendpoint :post "/register"+ :- [:map [:status [:enum 201 400 403 404]] [:body :any]]+ "Handles dynamic client registration (RFC 7591)."+ [_route-params _query-params body :- :any]+ (if-not (oauth-settings/oauth-server-dynamic-registration-enabled)+ {:status 403+ :headers {"Content-Type" "application/json"}+ :body {"error" "registration_not_supported"}}+ (or (when-let [provider (oauth-server/get-provider)]+ (if (nil? body)+ {:status 400+ :headers {"Content-Type" "application/json"}+ :body {"error" "invalid_client_metadata"+ "error_description" "Invalid or missing JSON body"}}+ (try+ ;; MCP clients frequently omit application_type, scope, and may request+ ;; unsupported grant types. We are required to support poorly-configured+ ;; clients, so we apply sensible defaults here:+ ;; - application_type defaults to "native" (not the RFC default "web") so+ ;; CLI tools and desktop apps can use HTTP loopback redirects.+ ;; - scope defaults to all provider-supported scopes when not specified.+ (let [body (cond-> body+ (not (contains? body :application_type))+ (assoc :application_type "native")+ (not (contains? body :scope))+ (assoc :scope (str/join " " (oauth-server/all-agent-scopes)))+ ;; Remove client_credentials grant type — tokens issued without a+ ;; user context are unusable for MCP (validate-bearer-token requires+ ;; a valid user-id).+ (contains? body :grant_types)+ (update :grant_types (fn [gts] (vec (remove #{"client_credentials"} gts)))))+ response (oidc/dynamic-register-client provider body)+ client-id (:client_id response)]+ ;; Mark as dynamically registered (the library doesn't know about registration_type)+ (proto/update-client (:client-store provider) client-id {:registration-type "dynamic"})+ {:status 201+ :headers {"Content-Type" "application/json"}+ :body response})+ (catch clojure.lang.ExceptionInfo e+ (reg/registration-error-response+ (ex-message e)+ (:error_description (ex-data e)))))))+ {:status 404 :body {:error "not_found"}})))++(api.macros/defendpoint :get "/register/:client-id"+ :- [:map [:status [:enum 200 401 404]] [:body :map]]+ "Handles client configuration read (RFC 7592)."+ [{:keys [client-id]}+ _query-params _body+ request]+ (or (when-let [provider (oauth-server/get-provider)]+ (let [token (oauth-server/extract-bearer-token request)]+ (if (str/blank? token)+ {:status 401+ :headers {"Content-Type" "application/json"}+ :body {"error" "invalid_token"}}+ (let [{:keys [status body]} (oidc/dynamic-read-client provider client-id token)]+ {:status status+ :headers {"Content-Type" "application/json"}+ :body body}))))+ {:status 404 :body {:error "not_found"}}))++(api.macros/defendpoint :get "/authorize"+ :- [:map [:status [:enum 200 302 400 404]] [:body [:or :string :map]]]+ "Handles the authorization endpoint (GET /oauth/authorize)."+ [_route-params query-params _body+ request]+ (if-not (:metabase-user-id request)+ {:status 302+ :headers {"Location" (login-redirect-url request)}+ :body ""}+ (or (when-let [provider (oauth-server/get-provider)]+ (try+ (let [parsed (oidc/parse-authorization-request provider query-params)+ client (proto/get-client (:client-store provider) (:client_id parsed))+ csrf-token (generate-csrf-token)]+ (-> {:status 200+ :headers {"Content-Type" "text/html; charset=utf-8"}+ :body (consent-page/render-consent-page+ {:client-name (or (:client-name client) "Unknown Application")+ :nonce (:nonce request)+ :csrf-token csrf-token+ :oauth-params {:client_id (:client_id parsed)+ :redirect_uri (:redirect_uri parsed)+ :response_type (:response_type parsed)+ :scope (:scope parsed)+ :state (:state parsed)+ :nonce (:nonce parsed)+ :code_challenge (:code_challenge parsed)+ :code_challenge_method (:code_challenge_method parsed)+ :resource (:resource parsed)}})}+ (response/set-cookie csrf-cookie-name csrf-token+ {:http-only true+ :same-site :strict+ :path "/oauth/authorize"+ :max-age 600})))+ (catch clojure.lang.ExceptionInfo e+ {:status 400+ :headers {"Content-Type" "application/json"}+ :body {:error "invalid_request"+ :error_description (ex-message e)}})))+ {:status 404 :body {:error "not_found"}})))++(api.macros/defendpoint :post "/authorize/decision"+ :- [:map [:status [:enum 302 400 401 403 404]] [:body [:or :string :map]]]+ "Handles the authorization decision (POST /oauth/authorize/decision)."+ [_route-params _query-params body+ request]+ (if-not (:metabase-user-id request)+ {:status 401+ :headers {"Content-Type" "application/json"}+ :body {:error "unauthorized"}}+ (or (when-let [provider (oauth-server/get-provider)]+ (let [cookie-token (get-in request [:cookies csrf-cookie-name :value])+ form-token (str (:csrf_token body))]+ (if (or (str/blank? cookie-token)+ (str/blank? form-token)+ (not (oidc-util/constant-time-eq? cookie-token form-token)))+ {:status 403+ :headers {"Content-Type" "application/json"}+ :body {:error "csrf_validation_failed"}}+ (let [approved (= "true" (str (:approved body)))+ auth-params (select-keys body [:client_id :redirect_uri :response_type :scope :state :nonce+ :code_challenge :code_challenge_method :resource])]+ (try+ (let [parsed (oidc/parse-authorization-request provider auth-params)]+ (if approved+ (let [url (oidc/authorize provider parsed (str (:metabase-user-id request)))]+ (-> {:status 302+ :headers {"Location" url}+ :body ""}+ (response/set-cookie csrf-cookie-name "" {:http-only true+ :same-site :strict+ :path "/oauth/authorize"+ :max-age 0})))+ (let [url (oidc/deny-authorization provider parsed "access_denied" "User denied the request")]+ (-> {:status 302+ :headers {"Location" url}+ :body ""}+ (response/set-cookie csrf-cookie-name "" {:http-only true+ :same-site :strict+ :path "/oauth/authorize"+ :max-age 0})))))+ (catch clojure.lang.ExceptionInfo e+ {:status 400+ :headers {"Content-Type" "application/json"}+ :body {:error "invalid_request"+ :error_description (ex-message e)}}))))))+ {:status 404 :body {:error "not_found"}})))++(api.macros/defendpoint :post "/token"+ :- [:map [:status [:enum 200 400 401 404]] [:body :map]]+ "Handles the token endpoint (POST /oauth/token)."+ [_route-params _query-params body+ request]+ (or (when-let [provider (oauth-server/get-provider)]+ (let [authorization-header (get-in request [:headers "authorization"])]+ (try+ (let [response (oidc/token-request provider body authorization-header)]+ {:status 200+ :headers {"Content-Type" "application/json"+ "Cache-Control" "no-store"+ "Pragma" "no-cache"}+ :body response})+ (catch clojure.lang.ExceptionInfo e+ (let [data (ex-data e)]+ {:status (if (= (:error data) "invalid_client") 401 400)+ :headers {"Content-Type" "application/json"+ "Cache-Control" "no-store"+ "Pragma" "no-cache"}+ :body {:error (or (:error data) "invalid_request")+ :error_description (ex-message e)}})))))+ {:status 404 :body {:error "not_found"}}))++(api.macros/defendpoint :post "/revoke"+ :- [:map [:status [:enum 200 404]]]+ "Handles the token revocation endpoint (POST /oauth/revoke) per RFC 7009."+ [_route-params _query-params _body+ request]+ (or (when-let [provider (oauth-server/get-provider)]+ ((oidc/revocation-handler provider) request))+ {:status 404 :body {:error "not_found"}}))diff --git a/src/metabase/oauth_server/consent_page.clj b/src/metabase/oauth_server/consent_page.cljnew file mode 100644index 00000000000..6668de75124--- /dev/null+++ b/src/metabase/oauth_server/consent_page.clj@@ -0,0 +1,115 @@+(ns metabase.oauth-server.consent-page+ "Server-side rendered consent page for the OAuth authorization flow."+ (:require+ [clojure.java.io :as io]+ [clojure.string :as str]+ [hiccup2.core :as h]+ [metabase.appearance.core :as appearance]+ [metabase.system.core :as system]))++(defn- absolute-url+ "Resolve a potentially relative path to an absolute URL using site-url."+ [path]+ (if (or (str/starts-with? path "http://")+ (str/starts-with? path "https://"))+ path+ (str (str/replace (system/site-url) #"/$" "")+ "/"+ (str/replace path #"^/" ""))))++(defn- css-escape-font-name+ "Escape single quotes in a font name for safe CSS interpolation."+ [font-name]+ (str/replace font-name "'" "\\'"))++(defn- font-face-css+ "Generate @font-face CSS rules for the given font, loading woff2 files from Metabase's+ bundled font directory. Returns an empty string for custom (non-bundled) fonts since+ they are loaded via application-font-files."+ [font-name]+ (let [dir-name (str/replace font-name " " "_")+ file-stem (str/replace font-name " " "")+ css-font-name (css-escape-font-name font-name)]+ (if (= font-name "Lato")+ (str "@font-face { font-family: 'Lato'; font-weight: 400; font-style: normal; font-display: swap;"+ " src: url('/app/fonts/Lato/lato-v16-latin-regular.woff2') format('woff2'); }\n"+ "@font-face { font-family: 'Lato'; font-weight: 700; font-style: normal; font-display: swap;"+ " src: url('/app/fonts/Lato/lato-v16-latin-700.woff2') format('woff2'); }\n")+ (str "@font-face { font-family: '" css-font-name "'; font-weight: 400; font-style: normal; font-display: swap;"+ " src: url('/app/fonts/" dir-name "/" file-stem "-Regular.woff2') format('woff2'); }\n"+ "@font-face { font-family: '" css-font-name "'; font-weight: 700; font-style: normal; font-display: swap;"+ " src: url('/app/fonts/" dir-name "/" file-stem "-Bold.woff2') format('woff2'); }\n"))))++(def ^:private default-logo-url "app/assets/img/logo.svg")++(def ^:private default-logo-svg+ (delay (some-> (io/resource "frontend_client/app/assets/img/logo.svg") slurp)))++(defn- branded-logo-svg+ "Return the default Metabase logo SVG with `currentColor` replaced by the brand color."+ [brand-color]+ (some-> @default-logo-svg (str/replace "currentColor" brand-color)))++(defn- appearance-settings+ "Return a map of appearance settings for the consent page."+ []+ (let [colors (appearance/application-colors)+ logo-url (appearance/application-logo-url)]+ {:font-family (appearance/application-font)+ :logo-url (absolute-url logo-url)+ :default-logo? (= logo-url default-logo-url)+ :brand-color (get colors "brand" "#509ee3")}))++(defn render-consent-page+ "Render a server-side HTML consent page for the OAuth authorization flow."+ [{:keys [client-name oauth-params nonce csrf-token]}]+ (let [{:keys [font-family logo-url default-logo? brand-color]} (appearance-settings)+ css-font-family (css-escape-font-name font-family)]+ (str+ "<!DOCTYPE html>"+ (h/html+ [:html {:lang "en"}+ [:head+ [:meta {:charset "UTF-8"}]+ [:meta {:name "viewport" :content "width=device-width, initial-scale=1.0"}]+ [:title "Authorize " client-name]+ [:style {:nonce nonce} (h/raw+ (str+ (font-face-css font-family)+ "* { box-sizing: border-box; margin: 0; padding: 0; }+ html { height: 100%; }+ body { font-family: '" css-font-family "', 'Lato', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;+ display: flex; justify-content: center; align-items: center;+ min-height: 100%; background: #f9fbfc; color: #4c5773; }+ .consent { background: #fff; border-radius: 8px;+ box-shadow: 0 1px 3px rgba(0,0,0,0.08), 0 4px 12px rgba(0,0,0,0.05);+ padding: 2.5rem; max-width: 440px; width: 100%; margin: 1rem; }+ .logo { display: flex; justify-content: center; margin-bottom: 1.5rem; }+ 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; }+ .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;+ transition: background-color 0.15s ease, border-color 0.15s ease, filter 0.15s ease; }+ .allow { background: " brand-color "; color: #fff; border: 1px solid " brand-color "; }+ .allow:hover { filter: brightness(0.9); }+ .deny { background: #fff; color: #4c5773; border: 1px solid #ddd; }+ .deny:hover { background: #f9fbfc; border-color: #ccc; }"))]]+ [:body+ [:div.consent+ [:div.logo+ (if-let [svg (when default-logo? (branded-logo-svg brand-color))]+ (h/raw svg)+ [:img {:src logo-url :alt "Logo" :height "32"}])]+ [:h1 "Authorize " client-name "?"]+ [: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."]+ [:form {:method "POST" :action "/oauth/authorize/decision"}+ [:input {:type "hidden" :name "csrf_token" :value csrf-token}]+ (for [[k v] oauth-params+ :when (some? v)+ v (if (sequential? v) v [v])]+ [:input {:type "hidden" :name (name k) :value v}])+ [:div.actions+ [:button.deny {:type "submit" :name "approved" :value "false"} "Cancel"]+ [:button.allow {:type "submit" :name "approved" :value "true"} "Authorize"]]]]]]))))diff --git a/src/metabase/oauth_server/core.clj b/src/metabase/oauth_server/core.cljnew file mode 100644index 00000000000..8390c639bf4--- /dev/null+++ b/src/metabase/oauth_server/core.clj@@ -0,0 +1,62 @@+(ns metabase.oauth-server.core+ (:require+ [clojure.string :as str]+ [metabase.api.macros :as api.macros]+ [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]))++(set! *warn-on-reflection* true)++(defonce ^:private provider (atom nil))++(defn all-agent-scopes+ "All supported OAuth scopes derived from defendpoint metadata on the agent API."+ []+ (into []+ (comp (keep #(get-in % [:form :metadata :scope]))+ (filter string?)+ (distinct))+ (vals (api.macros/ns-routes 'metabase.agent-api.api))))++(defn- build-provider-config+ "Build the configuration map for the OAuth provider from Metabase settings."+ []+ (let [base-url (system/site-url)]+ {:issuer base-url+ :authorization-endpoint (str base-url "/oauth/authorize")+ :token-endpoint (str base-url "/oauth/token")+ :registration-endpoint (str base-url "/oauth/register")+ :revocation-endpoint (str base-url "/oauth/revoke")+ :access-token-ttl-seconds (oauth-settings/oauth-server-access-token-ttl)+ :authorization-code-ttl-seconds (oauth-settings/oauth-server-authorization-code-ttl)+ :refresh-token-ttl-seconds (oauth-settings/oauth-server-refresh-token-ttl)+ :client-store (store/create-client-store)+ :code-store (store/create-authorization-code-store)+ :token-store (store/create-token-store)+ :scopes-supported (all-agent-scopes)}))++(defn- create-provider+ "Create a new OAuth provider instance."+ []+ (oidc/create-provider (build-provider-config)))++(defn get-provider+ "Returns the current provider instance, creating it lazily if needed."+ []+ (or @provider+ (swap! provider (fn [p] (or p (create-provider))))))++(defn reset-provider!+ "Reset the provider atom to nil. Useful for testing."+ []+ (reset! provider nil))++(defn extract-bearer-token+ "Extract the bearer token from the Authorization header of a Ring request."+ [request]+ (when-let [auth (get-in request [:headers "authorization"])]+ (when (str/starts-with? (u/lower-case-en auth) "bearer ")+ (str/trim (subs auth 7)))))diff --git a/src/metabase/oauth_server/init.clj b/src/metabase/oauth_server/init.cljnew file mode 100644index 00000000000..6709f1b2545--- /dev/null+++ b/src/metabase/oauth_server/init.clj@@ -0,0 +1,3 @@+(ns metabase.oauth-server.init+ (:require+ [metabase.oauth-server.settings]))diff --git a/src/metabase/oauth_server/models/oauth_access_token.clj b/src/metabase/oauth_server/models/oauth_access_token.cljnew file mode 100644index 00000000000..2db1a55d6d6--- /dev/null+++ b/src/metabase/oauth_server/models/oauth_access_token.clj@@ -0,0 +1,16 @@+(ns metabase.oauth-server.models.oauth-access-token+ (:require+ [metabase.models.interface :as mi]+ [methodical.core :as methodical]+ [toucan2.core :as t2]))++;; The `token` and `refresh_token` columns store hashed values.+;; The oidc-provider library hashes these before writing to the store.+(methodical/defmethod t2/table-name :model/OAuthAccessToken [_model] :oauth_access_token)++(doto :model/OAuthAccessToken+ (derive :metabase/model))++(t2/deftransforms :model/OAuthAccessToken+ {:scope mi/transform-json+ :resource mi/transform-json})diff --git a/src/metabase/oauth_server/models/oauth_authorization_code.clj b/src/metabase/oauth_server/models/oauth_authorization_code.cljnew file mode 100644index 00000000000..a923b44d4be--- /dev/null+++ b/src/metabase/oauth_server/models/oauth_authorization_code.clj@@ -0,0 +1,16 @@+(ns metabase.oauth-server.models.oauth-authorization-code+ (:require+ [metabase.models.interface :as mi]+ [methodical.core :as methodical]+ [toucan2.core :as t2]))++;; The `code` column stores a hashed value.+;; The oidc-provider library hashes the authorization code before writing to the store.+(methodical/defmethod t2/table-name :model/OAuthAuthorizationCode [_model] :oauth_authorization_code)++(doto :model/OAuthAuthorizationCode+ (derive :metabase/model))++(t2/deftransforms :model/OAuthAuthorizationCode+ {:scope mi/transform-json+ :resource mi/transform-json})diff --git a/src/metabase/oauth_server/models/oauth_client.clj b/src/metabase/oauth_server/models/oauth_client.cljnew file mode 100644index 00000000000..f3ce704a789--- /dev/null+++ b/src/metabase/oauth_server/models/oauth_client.clj@@ -0,0 +1,18 @@+(ns metabase.oauth-server.models.oauth-client+ (:require+ [metabase.models.interface :as mi]+ [methodical.core :as methodical]+ [toucan2.core :as t2]))++(methodical/defmethod t2/table-name :model/OAuthClient [_model] :oauth_client)++(doto :model/OAuthClient+ (derive :metabase/model)+ (derive :hook/timestamped?))++(t2/deftransforms :model/OAuthClient+ {:redirect_uris mi/transform-json+ :grant_types mi/transform-json+ :response_types mi/transform-json+ :scopes mi/transform-json+ :contacts mi/transform-json})diff --git a/src/metabase/oauth_server/models/oauth_refresh_token.clj b/src/metabase/oauth_server/models/oauth_refresh_token.cljnew file mode 100644index 00000000000..23f260ab7aa--- /dev/null+++ b/src/metabase/oauth_server/models/oauth_refresh_token.clj@@ -0,0 +1,14 @@+(ns metabase.oauth-server.models.oauth-refresh-token+ (:require+ [metabase.models.interface :as mi]+ [methodical.core :as methodical]+ [toucan2.core :as t2]))++(methodical/defmethod t2/table-name :model/OAuthRefreshToken [_model] :oauth_refresh_token)++(doto :model/OAuthRefreshToken+ (derive :metabase/model))++(t2/deftransforms :model/OAuthRefreshToken+ {:scope mi/transform-json+ :resource mi/transform-json})diff --git a/src/metabase/oauth_server/settings.clj b/src/metabase/oauth_server/settings.cljnew file mode 100644index 00000000000..09a25811a76--- /dev/null+++ b/src/metabase/oauth_server/settings.clj@@ -0,0 +1,40 @@+(ns metabase.oauth-server.settings+ (:require+ [metabase.settings.core :refer [defsetting]]+ [metabase.util.i18n :refer [deferred-tru]]))++(defsetting oauth-server-access-token-ttl+ (deferred-tru "Access token time-to-live in seconds for the embedded OAuth server.")+ :type :integer+ :visibility :internal+ :default 3600+ :doc false+ :export? false+ :audit :never)++(defsetting oauth-server-authorization-code-ttl+ (deferred-tru "Authorization code time-to-live in seconds for the embedded OAuth server.")+ :type :integer+ :visibility :internal+ :default 600+ :doc false+ :export? false+ :audit :never)++(defsetting oauth-server-refresh-token-ttl+ (deferred-tru "Refresh token time-to-live in seconds for the embedded OAuth server.")+ :type :integer+ :visibility :internal+ :default 2592000+ :doc false+ :export? false+ :audit :never)++(defsetting oauth-server-dynamic-registration-enabled+ (deferred-tru "Whether dynamic client registration (RFC 7591) is enabled for the embedded OAuth server.")+ :type :boolean+ :default true+ :visibility :internal+ :doc false+ :export? false+ :audit :getter)diff --git a/src/metabase/oauth_server/store.clj b/src/metabase/oauth_server/store.cljnew file mode 100644index 00000000000..a10c8d116c4--- /dev/null+++ b/src/metabase/oauth_server/store.clj@@ -0,0 +1,223 @@+(ns metabase.oauth-server.store+ "Database-backed implementations of OAuth provider storage protocols."+ (:require+ [metabase.util :as u]+ [oidc-provider.protocol :as proto]+ [toucan2.core :as t2]))++(set! *warn-on-reflection* true)++;;; ------------------------------------------------- Helpers ----------------------------------------------------------++(defn- parse-user-id+ "Parse a user-id string to an integer, returning nil if not a valid integer.+ The oidc-provider library passes user-id as a string. For authorization_code and+ refresh_token grants this is a stringified Metabase user ID. For client_credentials+ grants the library passes the client-id string, which is not a valid integer."+ [user-id]+ (when user-id+ (try+ (Integer/parseInt (str user-id))+ (catch NumberFormatException _+ nil))))++(def ^:private client-db-columns+ "DB columns to select/project for OAuthClient rows."+ [:client_id :client_type :redirect_uris :grant_types :response_types :scopes :registration_type+ :client_secret_hash :token_endpoint_auth_method :client_name :client_uri :logo_uri+ :contacts :registration_access_token_hash :application_type])++(defn- select-and-kebab-keys+ "Select `ks` from `row`, convert keys to kebab-case, and remove nil values."+ [row ks]+ (-> (select-keys row ks)+ (update-keys u/->kebab-case-en)+ (->> (into {} (remove (comp nil? val))))))++(defn- kebab->snake-keys+ "Convert all keys in `m` from kebab-case to snake_case."+ [m]+ (update-keys m u/->snake_case_en))++(defn- db-row->client-config+ "Convert a DB row from :model/OAuthClient to the protocol's ClientConfig shape.+ Aliases :registration-access-token-hash as :registration-access-token so that+ the oidc-provider library can find the hash where it expects it."+ [row]+ (when row+ (let [m (select-and-kebab-keys row client-db-columns)]+ (cond-> m+ (:registration-access-token-hash m)+ (assoc :registration-access-token (:registration-access-token-hash m))))))++(defn- client-config->db-row+ "Convert a protocol ClientConfig map to DB column format for insert/update."+ [config]+ (-> config+ (update :registration-type #(or % "static"))+ (select-keys (map u/->kebab-case-en client-db-columns))+ kebab->snake-keys))++(def ^:private auth-code-db-columns+ [:user_id :client_id :redirect_uri :scope :nonce :expiry+ :code_challenge :code_challenge_method :resource])++(defn- db-row->auth-code+ "Convert a DB row from :model/OAuthAuthorizationCode to the protocol's map shape.+ Converts user-id to a string since the oidc-provider library expects string user IDs.+ Ensures :resource is a vector (JSON deserialization may return a list)."+ [row]+ (when row+ (let [m (-> (select-and-kebab-keys row auth-code-db-columns)+ (update :user-id #(some-> % str)))]+ (cond-> m+ (:resource m) (update :resource vec)))))++(def ^:private access-token-db-columns+ [:user_id :client_id :scope :expiry :resource])++(defn- db-row->access-token+ "Convert a DB row from :model/OAuthAccessToken to the protocol's map shape."+ [row]+ (when row+ (let [m (-> (select-and-kebab-keys row access-token-db-columns)+ (update :user-id #(some-> % str)))]+ (cond-> m+ (:resource m) (update :resource vec)))))++(def ^:private refresh-token-db-columns+ [:user_id :client_id :scope :expiry :resource])++(defn- db-row->refresh-token+ "Convert a DB row from :model/OAuthRefreshToken to the protocol's map shape."+ [row]+ (when row+ (let [m (-> (select-and-kebab-keys row refresh-token-db-columns)+ (update :user-id #(some-> % str)))]+ (cond-> m+ (:resource m) (update :resource vec)))))++;;; ------------------------------------------------ ClientStore -------------------------------------------------------++(defrecord DbClientStore []+ proto/ClientStore+ (get-client [_ client-id]+ (-> (t2/select-one :model/OAuthClient :client_id client-id)+ db-row->client-config))++ (register-client [_ client-config]+ (let [client-id (or (:client-id client-config)+ (str (java.util.UUID/randomUUID)))+ config (-> client-config+ (assoc :client-id client-id)+ (cond->+ ;; The library pre-hashes the registration-access-token before calling+ ;; register-client; map it to the DB column name.+ (:registration-access-token client-config)+ (-> (assoc :registration-access-token-hash (:registration-access-token client-config))+ (dissoc :registration-access-token))+ ;; The library pre-hashes the client-secret before calling register-client;+ ;; map it to the DB column name.+ (:client-secret client-config)+ (-> (assoc :client-secret-hash (:client-secret client-config))+ (dissoc :client-secret))))+ row (client-config->db-row config)]+ (t2/insert! :model/OAuthClient row)+ config))++ (update-client [_ client-id updated-config]+ (let [existing (t2/select-one :model/OAuthClient :client_id client-id)]+ (when existing+ (let [existing-config (db-row->client-config existing)+ merged (-> (merge existing-config updated-config)+ (assoc :client-id client-id))+ row (client-config->db-row merged)]+ (t2/update! :model/OAuthClient (:id existing) row)+ merged)))))++;;; ----------------------------------------- AuthorizationCodeStore ---------------------------------------------------++(defrecord DbAuthorizationCodeStore []+ proto/AuthorizationCodeStore+ (save-authorization-code [_ code user-id client-id redirect-uri scope nonce expiry code-challenge code-challenge-method resource]+ (t2/insert! :model/OAuthAuthorizationCode+ (cond-> {:code code+ :user_id (parse-user-id user-id)+ :client_id client-id+ :redirect_uri redirect-uri+ :scope (vec scope)+ :nonce nonce+ :expiry expiry}+ code-challenge (assoc :code_challenge code-challenge)+ code-challenge-method (assoc :code_challenge_method code-challenge-method)+ resource (assoc :resource (vec resource))))+ true)++ (get-authorization-code [_ code]+ (-> (t2/select-one :model/OAuthAuthorizationCode :code code)+ db-row->auth-code))++ (delete-authorization-code [_ code]+ (t2/delete! :model/OAuthAuthorizationCode :code code)+ true)++ (consume-authorization-code [_ code]+ (t2/with-transaction [_conn]+ (when-let [row (t2/select-one :model/OAuthAuthorizationCode :code code {:for :update})]+ (t2/delete! :model/OAuthAuthorizationCode :code code)+ (db-row->auth-code row)))))++;;; ------------------------------------------------ TokenStore --------------------------------------------------------++(defrecord DbTokenStore []+ proto/TokenStore+ (save-access-token [_ token user-id client-id scope expiry resource]+ (t2/insert! :model/OAuthAccessToken+ (cond-> {:token token+ :user_id (parse-user-id user-id)+ :client_id client-id+ :scope (vec scope)+ :expiry expiry}+ resource (assoc :resource (vec resource))))+ true)++ (get-access-token [_ token]+ (-> (t2/select-one :model/OAuthAccessToken :token token :revoked_at nil)+ db-row->access-token))++ (save-refresh-token [_ token user-id client-id scope expiry resource]+ (t2/insert! :model/OAuthRefreshToken+ (cond-> {:token token+ :user_id (parse-user-id user-id)+ :client_id client-id+ :scope (vec scope)}+ expiry (assoc :expiry expiry)+ resource (assoc :resource (vec resource))))+ true)++ (get-refresh-token [_ token]+ (-> (t2/select-one :model/OAuthRefreshToken :token token :revoked_at nil)+ db-row->refresh-token))++ (revoke-token [_ token]+ (let [now (java.time.OffsetDateTime/now)]+ (t2/update! :model/OAuthAccessToken {:token token} {:revoked_at now})+ (t2/update! :model/OAuthRefreshToken {:token token} {:revoked_at now}))+ true))++;;; ------------------------------------------------ Constructors ------------------------------------------------------++(defn create-client-store+ "Creates a database-backed client store."+ []+ (->DbClientStore))++(defn create-authorization-code-store+ "Creates a database-backed authorization code store."+ []+ (->DbAuthorizationCodeStore))++(defn create-token-store+ "Creates a database-backed token store."+ []+ (->DbTokenStore))diff --git a/src/metabase/server/middleware/log.clj b/src/metabase/server/middleware/log.cljindex 3a44d2f3da6..45d3ade41fc 100644--- a/src/metabase/server/middleware/log.clj+++ b/src/metabase/server/middleware/log.clj@@ -211,10 +211,12 @@(cond-> #{"/api/logger/logs"}(not (server.settings/health-check-logging-enabled)) (into #{"/api/health" "/livez" "/readyz"})))-(defn- should-log-request? [{:keys [uri], :as request}]+(defn- should-log-request? [{:keys [^String uri], :as request}];; don't log calls to health checks or /logger/logs because they clutter up the logs (especially the window in admin);; with useless lines(and (or (request/api-call? request)+ (str/starts-with? uri "/.well-known")+ (str/starts-with? uri "/oauth")(contains? #{"/livez" "/readyz"} uri))(not ((logging-disabled-uris) uri))))diff --git a/src/metabase/server/routes.clj b/src/metabase/server/routes.cljindex a5689268141..fa4614edab9 100644--- a/src/metabase/server/routes.clj+++ b/src/metabase/server/routes.clj@@ -8,6 +8,7 @@[metabase.app-db.core :as mdb][metabase.appearance.core :as appearance][metabase.initialization-status.core :as init-status]+ [metabase.oauth-server.api :as oauth-server.api][metabase.query-processor.schema :as qp.schema][metabase.server.auth-wrapper :as auth-wrapper][metabase.server.middleware.embedding-sdk-bundle :as mw.embedding-sdk-bundle]@@ -97,6 +98,8 @@#_{:clj-kondo/ignore [:discouraged-var]}(compojure/routesauth-wrapper/routes+ (context "/.well-known" [] oauth-server.api/well-known-routes)+ (context "/oauth" [] oauth-server.api/oauth-routes);; ^/$ -> index.html(GET "/" [] index/index)(GET "/favicon.ico" [] (response/resource-response (appearance/application-favicon-url)))diff --git a/test/metabase/api/macros/defendpoint/tools_manifest_test.clj b/test/metabase/api/macros/defendpoint/tools_manifest_test.cljindex 238880b78f2..e06e86f0a69 100644--- a/test/metabase/api/macros/defendpoint/tools_manifest_test.clj+++ b/test/metabase/api/macros/defendpoint/tools_manifest_test.clj@@ -100,7 +100,30 @@:required [:name]}:annotations {:readOnlyHint true:idempotentHint true}}- result)))))+ result))))++ (testing "Scope is included when metadata has :scope"+ (let [defs (atom (sorted-map))+ form {:method :get+ :route {:path "/v1/table/:id"}+ :params {:route {:binding '{:keys [id]}+ :schema [:map [:id :int]]}}+ :docstr "Get a table."+ :metadata {:scope "agent:table:read"+ :tool {:name "get_table"}}+ :body '(nil)}+ result (tools-manifest/endpoint->tool-definition defs "/api/agent" {:form form})]+ (is (= "agent:table:read" (:scope result)))))++ (testing "Scope is omitted when metadata has no :scope"+ (let [defs (atom (sorted-map))+ form {:method :get+ :route {:path "/v1/test"}+ :docstr "Test endpoint."+ :metadata {:tool {:name "test_no_scope"}}+ :body '(nil)}+ result (tools-manifest/endpoint->tool-definition defs "/api/test" {:form form})]+ (is (nil? (:scope result))))));; This test verifies the full pipeline with actual defendpoint endpoints.;; It requires the agent API namespace to be loaded.diff --git a/test/metabase/mcp/api_test.clj b/test/metabase/mcp/api_test.cljnew file mode 100644index 00000000000..8881edf1405--- /dev/null+++ b/test/metabase/mcp/api_test.clj@@ -0,0 +1,483 @@+(ns metabase.mcp.api-test+ (:require+ [clojure.string :as str]+ [clojure.test :refer :all]+ [metabase.api.macros.scope :as scope]+ [metabase.mcp.tools :as mcp.tools]+ [metabase.oauth-server.core :as oauth-server]+ [metabase.search.test-util :as search.tu]+ [metabase.test :as mt]+ [metabase.test.data.users :as test.users]+ [metabase.test.fixtures :as fixtures]+ [metabase.test.http-client :as client]+ [metabase.util.json :as json]+ [toucan2.core :as t2]))++(set! *warn-on-reflection* true)++(use-fixtures :once (fixtures/initialize :db :test-users))++;;; --------------------------------------------------- Helpers ----------------------------------------------------++(defn- mcp-request+ "Make a POST request to /api/mcp with the given JSON-RPC body and optional extra headers.+ Authenticates as :crowberto (superuser) by default."+ ([body]+ (mcp-request body {}))+ ([body extra-headers]+ (client/client-full-response (test.users/username->token :crowberto)+ :post "mcp"+ {:request-options {:headers extra-headers}}+ body)))++(defn- mcp-request-unauthenticated+ "Make an unauthenticated POST request to /api/mcp."+ ([body]+ (mcp-request-unauthenticated body {}))+ ([body extra-headers]+ (client/client-full-response :post 401 "mcp"+ {:request-options {:headers extra-headers}}+ body)))++(defn- mcp-request-with-bearer+ "Make a POST request to /api/mcp with a bearer token and optional extra headers."+ [bearer-token expected-status body extra-headers]+ (client/client-full-response :post expected-status "mcp"+ {:request-options {:headers (merge {"authorization" (str "Bearer " bearer-token)}+ extra-headers)}}+ body))++(defn- mcp-delete+ "Make a DELETE request to /api/mcp with optional headers.+ Authenticates as :crowberto (superuser) by default."+ [extra-headers]+ (client/client-full-response (test.users/username->token :crowberto)+ :delete "mcp"+ {:request-options {:headers extra-headers}}))++(defn- jsonrpc-request+ "Build a JSON-RPC 2.0 request map."+ ([method]+ (jsonrpc-request method {} 1))+ ([method params]+ (jsonrpc-request method params 1))+ ([method params id]+ {:jsonrpc "2.0" :method method :params params :id id}))++(defn- jsonrpc-notification+ "Build a JSON-RPC 2.0 notification (no id)."+ ([method]+ (jsonrpc-notification method {}))+ ([method params]+ {:jsonrpc "2.0" :method method :params params}))++(defn- initialize!+ "Perform the full MCP initialize handshake (initialize + notifications/initialized).+ Returns [session-id init-response]."+ []+ (let [response (mcp-request (jsonrpc-request "initialize"))+ session-id (get-in response [:headers "Mcp-Session-Id"])]+ ;; Complete the handshake so the session is marked initialized+ (mcp-request (jsonrpc-notification "notifications/initialized")+ {"mcp-session-id" session-id})+ [session-id response]))++(defn- call-tool+ "Call an MCP tool within an initialized session. Returns the parsed MCP result+ content (the JSON-decoded text from the first content block).+ Records test failures if the response status is not 200 or the tool returns an error."+ [session-id tool-name arguments]+ (let [response (mcp-request (jsonrpc-request "tools/call"+ {:name tool-name :arguments arguments})+ {"mcp-session-id" session-id})+ result (get-in response [:body :result])]+ (is (= 200 (:status response))+ (str "Expected 200 from tools/call " tool-name))+ (is (not (:isError result))+ (str "Tool " tool-name " error: " (some-> result :content first :text)))+ (when-not (:isError result)+ (json/decode+kw (:text (first (:content result)))))))++;;; ---------------------------------------------------- Tests -----------------------------------------------------++(deftest authentication-required-test+ (testing "unauthenticated requests return 401"+ (let [response (client/client-full-response :post 401 "mcp"+ (jsonrpc-request "initialize"))]+ (is (= 401 (:status response)))+ (is (= -32603 (get-in response [:body :error :code]))))))++(deftest initialize-test+ (testing "initialize returns protocol version, capabilities, and server info"+ (let [[session-id response] (initialize!)]+ (is (= 200 (:status response)))+ (is (some? session-id))+ (is (= "2.0" (get-in response [:body :jsonrpc])))+ (is (= 1 (get-in response [:body :id])))+ (let [result (get-in response [:body :result])]+ (is (= "2025-03-26" (:protocolVersion result)))+ (is (= {:tools {}} (:capabilities result)))+ (is (= {:name "metabase" :version "0.1.0"} (:serverInfo result)))))))++(deftest notifications-initialized-test+ (testing "notifications/initialized returns 202"+ (let [[session-id _] (initialize!)+ response (mcp-request (jsonrpc-notification "notifications/initialized")+ {"mcp-session-id" session-id})]+ (is (= 202 (:status response))))))++(deftest session-validation-test+ (testing "requests without a session ID return 400"+ (let [response (mcp-request (jsonrpc-request "tools/list"))]+ (is (= 400 (:status response)))+ (is (= -32600 (get-in response [:body :error :code]))))))++(deftest degenerate-session-id-test+ (testing "requests with any nonblank session ID are accepted"+ (let [response (mcp-request (jsonrpc-request "tools/list")+ {"mcp-session-id" "bogus-session-id"})]+ (is (= 200 (:status response)))+ (is (some? (get-in response [:body :result :tools]))))))++(deftest session-delete-test+ (testing "DELETE succeeds but does not invalidate a degenerate session ID"+ (let [[session-id _] (initialize!)+ delete-response (mcp-delete {"mcp-session-id" session-id})+ post-response (mcp-request (jsonrpc-request "tools/list")+ {"mcp-session-id" session-id})]+ (is (= 200 (:status delete-response)))+ (is (= 200 (:status post-response))))))++(deftest tools-list-test+ (testing "tools/list returns the 7 agent tools"+ (let [[session-id _] (initialize!)+ response (mcp-request (jsonrpc-request "tools/list")+ {"mcp-session-id" session-id})+ tools (get-in response [:body :result :tools])]+ (is (= 200 (:status response)))+ (is (pos? (count tools)))+ (is (= #{"search" "get_table" "get_metric" "get_table_field_values"+ "get_metric_field_values" "construct_query" "execute_query"}+ (set (map :name tools))))+ (testing "each tool has a description and inputSchema"+ (doseq [tool tools]+ (is (string? (:description tool)))+ (is (map? (:inputSchema tool))))))))++(deftest ping-test+ (testing "ping returns empty result"+ (let [[session-id _] (initialize!)+ response (mcp-request (jsonrpc-request "ping")+ {"mcp-session-id" session-id})]+ (is (= 200 (:status response)))+ (is (= {} (get-in response [:body :result]))))))++(deftest method-not-found-test+ (testing "unknown method returns -32601 error"+ (let [[session-id _] (initialize!)+ response (mcp-request (jsonrpc-request "nonexistent/method")+ {"mcp-session-id" session-id})]+ (is (= 200 (:status response)))+ (is (= -32601 (get-in response [:body :error :code]))))))++(deftest batch-request-test+ (testing "batch requests are processed together"+ (let [[session-id _] (initialize!)+ response (mcp-request [(jsonrpc-request "ping" {} 1)+ (jsonrpc-request "tools/list" {} 2)]+ {"mcp-session-id" session-id})]+ (is (= 200 (:status response)))+ (is (sequential? (:body response)))+ (is (= 2 (count (:body response))))+ (is (= #{1 2} (set (map :id (:body response))))))))++(deftest tools-call-unknown-tool-test+ (testing "calling an unknown tool returns isError content"+ (let [[session-id _] (initialize!)+ response (mcp-request (jsonrpc-request "tools/call"+ {:name "nonexistent_tool" :arguments {}})+ {"mcp-session-id" session-id})+ result (get-in response [:body :result])]+ (is (= 200 (:status response)))+ (is (true? (:isError result)))+ (is (= "text" (:type (first (:content result))))))))++(deftest tools-call-search-test+ (testing "search tool invocation works and returns parseable results"+ ;; Revert to the in-place search engine so test doesn't depend on the appdb search index being built.+ (search.tu/with-legacy-search+ (let [[session-id _] (initialize!)+ response (mcp-request (jsonrpc-request "tools/call"+ {:name "search"+ :arguments {:term_queries ["orders"]}})+ {"mcp-session-id" session-id})+ result (get-in response [:body :result])]+ (is (= 200 (:status response)))+ (is (nil? (:isError result)))+ (is (= "text" (:type (first (:content result)))))+ (let [search-data (json/decode+kw (:text (first (:content result))))]+ (is (contains? search-data :data))+ (is (contains? search-data :total_count)))))))++;;; ------------------------------------------------ SSE Transport -------------------------------------------------++(deftest sse-post-response-test+ (testing "POST with Accept: text/event-stream returns SSE format"+ (let [[session-id _] (initialize!)+ response (mcp-request (jsonrpc-request "ping")+ {"mcp-session-id" session-id+ "accept" "text/event-stream"})]+ (is (= 200 (:status response)))+ (is (= "text/event-stream" (get-in response [:headers "Content-Type"])))+ ;; Body should be SSE events (raw string since it's not JSON)+ (is (string? (:body response)))+ (is (str/includes? (:body response) "event: message"))+ (is (str/includes? (:body response) "data: "))))++ (testing "POST without Accept: text/event-stream returns JSON (backward-compatible)"+ (let [[session-id _] (initialize!)+ response (mcp-request (jsonrpc-request "ping")+ {"mcp-session-id" session-id})]+ (is (= 200 (:status response)))+ (is (= "application/json" (get-in response [:headers "Content-Type"])))+ ;; Body should be parsed JSON+ (is (map? (:body response))))))++(deftest sse-post-initialize-test+ (testing "initialize via SSE returns session header and SSE body"+ (let [response (mcp-request (jsonrpc-request "initialize")+ {"accept" "text/event-stream"})]+ (is (= 200 (:status response)))+ (is (some? (get-in response [:headers "Mcp-Session-Id"])))+ (is (= "text/event-stream" (get-in response [:headers "Content-Type"])))+ (is (string? (:body response)))+ ;; Parse the SSE data line to verify JSON-RPC structure+ (let [data-line (->> (str/split-lines (:body response))+ (filter #(str/starts-with? % "data: "))+ first)+ json-data (json/decode+kw (subs data-line 6))]+ (is (= "2.0" (:jsonrpc json-data)))+ (is (= 1 (:id json-data)))+ (is (some? (get-in json-data [:result :protocolVersion])))))))++(deftest get-without-session-test+ (testing "GET without auth returns 401"+ (let [response (client/client-full-response (test.users/username->token :crowberto)+ :get "mcp")]+ (is (= 400 (:status response)))+ (is (= -32600 (get-in response [:body :error :code]))))))++;;; --------------------------------------------- Type-Safe Responses -----------------------------------------------++(deftest type-safe-get-table-test+ (testing "get_table response has properly encoded keys from Agent API"+ (let [[session-id _] (initialize!)+ response (mcp-request (jsonrpc-request "tools/call"+ {:name "get_table"+ :arguments {:id (mt/id :orders)}})+ {"mcp-session-id" session-id})+ result (get-in response [:body :result])+ ;; Use first+:text since :content is a lazy seq (not indexable by get-in)+ content-text (:text (first (:content result)))]+ (is (= 200 (:status response)))+ (is (nil? (:isError result)))+ (is (string? content-text))+ ;; Parse the content text as JSON and verify snake_case keys from Malli encoding+ (let [table-data (json/decode+kw content-text)]+ (is (some? (:name table-data)))+ (is (some? (:display_name table-data)))+ (is (some? (:database_id table-data)))+ (is (= "table" (:type table-data)))+ (is (seq (:fields table-data)))))))++(deftest initialized-notification-compatibility-test+ (testing "requests succeed without notifications/initialized"+ (let [response (mcp-request (jsonrpc-request "initialize"))+ session-id (get-in response [:headers "Mcp-Session-Id"])+ list-response (mcp-request (jsonrpc-request "tools/list")+ {"mcp-session-id" session-id})]+ (is (= 200 (:status list-response)))+ (is (some? (get-in list-response [:body :result :tools])))))++ (testing "notifications/initialized remains accepted for compatibility"+ (let [response (mcp-request (jsonrpc-request "initialize"))+ session-id (get-in response [:headers "Mcp-Session-Id"])]+ (is (= 202 (:status (mcp-request (jsonrpc-notification "notifications/initialized")+ {"mcp-session-id" session-id})))))))++(deftest full-handshake-test+ (testing "complete MCP handshake flow"+ (let [[session-id init-response] (initialize!)+ _ (is (= 200 (:status init-response)))+ _ (is (some? session-id))+ ;; tools/list should work after full handshake+ list-response (mcp-request (jsonrpc-request "tools/list")+ {"mcp-session-id" session-id})]+ (is (= 200 (:status list-response)))+ (is (pos? (count (get-in list-response [:body :result :tools])))))))++(deftest batch-with-notifications-test+ (testing "batch with mix of notifications and requests returns only request responses"+ (let [[session-id _] (initialize!)+ response (mcp-request [(jsonrpc-notification "notifications/initialized")+ (jsonrpc-request "ping" {} 1)]+ {"mcp-session-id" session-id})]+ (is (= 200 (:status response)))+ (is (sequential? (:body response)))+ (is (= 1 (count (:body response))))+ (is (= 1 (:id (first (:body response))))))))++(deftest tools-call-missing-params-test+ (testing "tools/call without name returns an error"+ (let [[session-id _] (initialize!)+ response (mcp-request (jsonrpc-request "tools/call"+ {:arguments {}})+ {"mcp-session-id" session-id})+ result (get-in response [:body :result])]+ (is (= 200 (:status response)))+ (is (true? (:isError result)))))++ (testing "tools/call with missing path params returns an error"+ (let [[session-id _] (initialize!)+ response (mcp-request (jsonrpc-request "tools/call"+ {:name "get_table" :arguments {}})+ {"mcp-session-id" session-id})+ result (get-in response [:body :result])]+ (is (= 200 (:status response)))+ (is (true? (:isError result)))+ (is (str/includes? (:text (first (:content result))) "Missing required path parameter")))))++(deftest tools-list-defs-inlined-test+ (testing "tools with $ref in inputSchema have $defs inlined"+ (let [tools (mcp.tools/list-tools nil)]+ (doseq [tool tools]+ (let [schema (:inputSchema tool)+ refs (into #{} (map second) (re-seq #"#/\$defs/([A-Za-z0-9._-]+)" (pr-str schema)))]+ (when (seq refs)+ (testing (str (:name tool) " has $defs for all $ref targets")+ (is (map? (:$defs schema))+ (str (:name tool) " is missing $defs"))+ (doseq [def-name refs]+ (is (contains? (:$defs schema) def-name)+ (str (:name tool) " missing def: " def-name))))))))))++(deftest tools-call-execute-query-test+ (testing "execute_query returns a streaming response captured as MCP text content"+ (let [streamed? (atom false)+ original-fn (mt/original-fn #'mcp.tools/capture-streaming-response)]+ (mt/with-dynamic-fn-redefs [mcp.tools/capture-streaming-response+ (fn [response]+ (reset! streamed? true)+ (original-fn response))]+ (let [[session-id _] (initialize!)+ construct-data (call-tool session-id "construct_query" {:table_id (mt/id :orders) :limit 5})+ execute-data (call-tool session-id "execute_query" {:query (:query construct-data)})]+ (is (true? @streamed?) "execute_query should use the streaming response path")+ (is (=? {:status "completed"+ :row_count 5+ :data {:cols sequential?+ :rows (fn [rows] (= 5 (count rows)))}}+ execute-data)))))))++;;; --------------------------------------------- OAuth Bearer Auth -------------------------------------------------++(deftest unauthenticated-returns-401-test+ (testing "POST without any auth returns 401 with WWW-Authenticate discovery header"+ (mt/with-temporary-setting-values [site-url "http://localhost:3000"]+ (let [response (mcp-request-unauthenticated (jsonrpc-request "initialize"))]+ (is (=? {:status 401+ :headers {"WWW-Authenticate" #(str/includes? % "oauth-protected-resource")}}+ response))))))++(deftest invalid-bearer-token-returns-401-test+ (testing "POST with invalid bearer token returns 401 with invalid_token error"+ (mt/with-premium-features #{:metabot-v3}+ (mt/with-temporary-setting-values [site-url "http://localhost:3000"]+ (oauth-server/reset-provider!)+ (try+ (let [response (mcp-request-with-bearer "totally-bogus-token" 401+ (jsonrpc-request "initialize")+ {})]+ (is (=? {:status 401+ :headers {"WWW-Authenticate" #(str/includes? % "invalid_token")}}+ response)))+ (finally+ (oauth-server/reset-provider!)))))))++;;; --------------------------------------------- Scope Filtering ---------------------------------------------------++(deftest tools-list-scope-filtering-test+ (testing "tools/list with unrestricted scopes returns all tools"+ (let [tools (mcp.tools/list-tools #{::scope/unrestricted})]+ (is (= 7 (count tools)))))++ (testing "tools/list with specific scope only returns matching tools"+ (let [tools (mcp.tools/list-tools #{"agent:search"})+ tool-names (set (map :name tools))]+ ;; Should include search (matches scope)+ (is (contains? tool-names "search"))+ ;; Should NOT include tools with other scopes+ (is (not (contains? tool-names "get_table")))+ (is (not (contains? tool-names "construct_query")))))++ (testing "tools/list with wildcard scope matches all agent tools"+ (let [tools (mcp.tools/list-tools #{"agent:*"})]+ (is (= 7 (count tools)))))++ (testing "tools/list with nil scopes returns all tools"+ (let [tools (mcp.tools/list-tools nil)]+ (is (= 7 (count tools)))))++ (testing "tools/list with empty scopes does not return all tools"+ (let [tools (mcp.tools/list-tools #{})]+ (is (zero? (count tools))+ "Empty scopes should not grant access to scoped tools"))))++(defn- insert-expired-oauth-token!+ "Insert an OAuth access token into the DB with an expiry in the past.+ Returns the token string."+ [user-id client-id]+ (let [token (str (random-uuid))+ expired (- (quot (System/currentTimeMillis) 1000) 3600)]+ (t2/insert! :model/OAuthAccessToken+ {:token token+ :user_id user-id+ :client_id client-id+ :scope ["openid"]+ :expiry expired})+ token))++(deftest expired-oauth-bearer-token-returns-401-test+ (testing "POST with expired OAuth bearer token returns 401"+ (mt/with-premium-features #{:metabot-v3}+ (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))))))))++(deftest tools-call-scope-enforcement-test+ (testing "tool call is rejected when token scopes don't include the required scope"+ (let [result (mt/with-current-user (mt/user->id :crowberto)+ (mcp.tools/call-tool #{"agent:search"} "get_table" {:id (mt/id :orders)}))]+ (is (=? {:isError true} result))+ (is (= "Insufficient scope to call tool: get_table"+ (-> result :content first :text))+ "Error must not leak the required scope name")))+ (testing "tool call with matching scope is not rejected by scope enforcement"+ (let [result (mt/with-current-user (mt/user->id :crowberto)+ (mcp.tools/call-tool #{"agent:table:read"} "get_table" {:id (mt/id :orders)}))]+ (is (not (:isError result)))))+ (testing "tool call with empty scopes is rejected for scoped tools"+ (let [result (mt/with-current-user (mt/user->id :crowberto)+ (mcp.tools/call-tool #{} "get_table" {:id (mt/id :orders)}))]+ (is (=? {:isError true} result))+ (is (= "Insufficient scope to call tool: get_table"+ (-> result :content first :text))+ "Error must not leak the required scope name"))))diff --git a/test/metabase/oauth_server/api_test.clj b/test/metabase/oauth_server/api_test.cljnew file mode 100644index 00000000000..2fcd944f535--- /dev/null+++ b/test/metabase/oauth_server/api_test.clj@@ -0,0 +1,861 @@+(ns metabase.oauth-server.api-test+ (:require+ [clojure.string :as str]+ [clojure.test :refer [deftest is testing use-fixtures]]+ [metabase.oauth-server.core :as oauth-server]+ [metabase.test :as mt]+ [metabase.test.http-client :as client]+ [oidc-provider.util :as oidc-util]+ [toucan2.core :as t2])+ (:import+ (java.security MessageDigest)+ (java.util Base64)))++;; reset-provider! is safe here — it resets a local atom, no global side effects.+;; kondo flags it because of the `!` suffix in a fixture.+#_{:clj-kondo/ignore [:metabase/validate-deftest]}+(use-fixtures :each (fn [thunk]+ (oauth-server/reset-provider!)+ (binding [client/*url-prefix* ""]+ (thunk))+ (oauth-server/reset-provider!)))++(deftest discovery-endpoint-test+ (testing "Discovery endpoint returns valid OAuth metadata"+ (mt/with-temporary-setting-values [site-url "http://localhost:3000"+ oauth-server-dynamic-registration-enabled true]+ (let [response (mt/user-http-request :crowberto :get 200+ ".well-known/oauth-authorization-server")]+ (is (=? {:issuer "http://localhost:3000"+ :authorization_endpoint string?+ :token_endpoint string?+ :response_types_supported sequential?+ :registration_endpoint "http://localhost:3000/oauth/register"}+ response))+ (is (nil? (:jwks_uri response)))+ (is (nil? (:id_token_signing_alg_values_supported response)))))))++(deftest protected-resource-metadata-test+ (testing "GET /.well-known/oauth-protected-resource/api/mcp returns correct metadata"+ (mt/with-temporary-setting-values [site-url "http://localhost:3000"]+ (let [response (mt/user-http-request :crowberto :get 200+ ".well-known/oauth-protected-resource/api/mcp")]+ (is (=? {:resource "http://localhost:3000/api/mcp"+ :authorization_servers ["http://localhost:3000"]+ :bearer_methods_supported ["header"]}+ response))))))++;;; ----------------------------------------- Dynamic Client Registration ----------------------------------------------++(defn- register-client!+ "Helper to register a dynamic client via POST /oauth/register."+ [body & {:keys [expected-status] :or {expected-status 201}}]+ (client/client :post expected-status "oauth/register" body))++(defn- read-client-config+ "Helper to read client config via GET /oauth/register/:client-id with bearer token."+ [client-id token & {:keys [expected-status] :or {expected-status 200}}]+ (client/client :get expected-status (str "oauth/register/" client-id)+ {:request-options {:headers {"authorization" (str "Bearer " token)}}}))++(deftest dynamic-register-valid-test+ (testing "POST /oauth/register with valid metadata returns 201 with credentials"+ (mt/with-temporary-setting-values [site-url "http://localhost:3000"+ oauth-server-dynamic-registration-enabled true]+ (t2/with-transaction [_conn nil {:rollback-only true}]+ (let [response (register-client! {:redirect_uris ["https://example.com/callback"]+ :client_name "Test Client"+ :token_endpoint_auth_method "client_secret_basic"})]+ (is (=? {:client_id string?+ :client_secret string?+ :registration_access_token string?+ :redirect_uris ["https://example.com/callback"]+ :client_name "Test Client"}+ response)))))))++(deftest dynamic-register-missing-redirect-uris-test+ (testing "POST /oauth/register with missing redirect_uris returns 400"+ (mt/with-temporary-setting-values [site-url "http://localhost:3000"+ oauth-server-dynamic-registration-enabled true]+ (let [response (register-client! {:client_name "No Redirects"}+ :expected-status 400)]+ (is (=? {:error "invalid_client_metadata"} response))))))++(deftest dynamic-register-non-https-redirect-test+ (testing "POST /oauth/register with non-HTTPS redirect URI returns 400"+ (mt/with-temporary-setting-values [site-url "http://localhost:3000"+ oauth-server-dynamic-registration-enabled true]+ (let [response (register-client! {:redirect_uris ["http://example.com/callback"]}+ :expected-status 400)]+ (is (=? {:error "invalid_client_metadata"} response))))))++(deftest dynamic-register-native-http-localhost-allowed-test+ (testing "POST /oauth/register with application_type=native allows HTTP localhost redirect URI"+ (mt/with-temporary-setting-values [site-url "http://localhost:3000"+ oauth-server-dynamic-registration-enabled true]+ (t2/with-transaction [_conn nil {:rollback-only true}]+ (let [response (register-client! {:redirect_uris ["http://localhost:8080/callback"]+ :application_type "native"})]+ (is (=? {:client_id string?+ :redirect_uris ["http://localhost:8080/callback"]}+ response)))))))++(deftest dynamic-register-sets-registration-type-test+ (testing "Dynamically registered client has registration_type = dynamic"+ (mt/with-temporary-setting-values [site-url "http://localhost:3000"+ oauth-server-dynamic-registration-enabled true]+ (t2/with-transaction [_conn nil {:rollback-only true}]+ (let [response (register-client! {:redirect_uris ["https://example.com/callback"]})+ client-id (:client_id response)+ db-client (t2/select-one :model/OAuthClient :client_id client-id)]+ (is (= "dynamic" (:registration_type db-client))))))))++(deftest dynamic-client-read-valid-test+ (testing "GET /oauth/register/:client-id with valid registration_access_token returns 200"+ (mt/with-temporary-setting-values [site-url "http://localhost:3000"+ oauth-server-dynamic-registration-enabled true]+ (t2/with-transaction [_conn nil {:rollback-only true}]+ (let [reg-response (register-client! {:redirect_uris ["https://example.com/callback"]+ :client_name "Read Test"})+ client-id (:client_id reg-response)+ token (:registration_access_token reg-response)+ read-response (read-client-config client-id token)]+ (is (=? {:client_id client-id+ :redirect_uris ["https://example.com/callback"]}+ read-response)))))))++(deftest dynamic-client-read-invalid-token-test+ (testing "GET /oauth/register/:client-id with invalid token returns 401"+ (mt/with-temporary-setting-values [site-url "http://localhost:3000"+ oauth-server-dynamic-registration-enabled true]+ (t2/with-transaction [_conn nil {:rollback-only true}]+ (let [reg-response (register-client! {:redirect_uris ["https://example.com/callback"]})+ client-id (:client_id reg-response)+ response (read-client-config client-id "wrong-token" :expected-status 401)]+ (is (= "invalid_token" (:error response))))))))++(deftest dynamic-client-read-missing-token-test+ (testing "GET /oauth/register/:client-id with missing Authorization header returns 401"+ (mt/with-temporary-setting-values [site-url "http://localhost:3000"+ oauth-server-dynamic-registration-enabled true]+ (t2/with-transaction [_conn nil {:rollback-only true}]+ (let [reg-response (register-client! {:redirect_uris ["https://example.com/callback"]})+ client-id (:client_id reg-response)]+ ;; Use mt/user-http-request (which doesn't set Authorization header, only session header)+ (is (= "invalid_token"+ (:error (mt/user-http-request :crowberto :get 401+ (str "oauth/register/" client-id))))))))))++(deftest dynamic-client-read-wrong-client-id-test+ (testing "GET /oauth/register/:client-id with wrong client-id returns 401"+ (mt/with-temporary-setting-values [site-url "http://localhost:3000"+ oauth-server-dynamic-registration-enabled true]+ (t2/with-transaction [_conn nil {:rollback-only true}]+ (let [reg-response (register-client! {:redirect_uris ["https://example.com/callback"]})+ token (:registration_access_token reg-response)+ response (read-client-config "nonexistent-client" token :expected-status 401)]+ (is (= "invalid_token" (:error response))))))))++;;; --------------------------------- Dynamic Registration Security Tests -----------------------------------------++(deftest dynamic-register-disabled-test+ (testing "POST /oauth/register returns 403 when dynamic registration is disabled"+ (mt/with-temporary-setting-values [site-url "http://localhost:3000"+ oauth-server-dynamic-registration-enabled false]+ (let [response (register-client! {:redirect_uris ["https://example.com/callback"]}+ :expected-status 403)]+ (is (= "registration_not_supported" (:error response)))))))++(deftest discovery-registration-endpoint-disabled-test+ (testing "Discovery document omits registration_endpoint when DCR is disabled"+ (mt/with-temporary-setting-values [site-url "http://localhost:3000"+ oauth-server-dynamic-registration-enabled false]+ (let [response (mt/user-http-request :crowberto :get 200+ ".well-known/oauth-authorization-server")]+ (is (not (contains? response :registration_endpoint)))))))++(deftest discovery-registration-endpoint-enabled-test+ (testing "Discovery document includes registration_endpoint when DCR is enabled"+ (mt/with-temporary-setting-values [site-url "http://localhost:3000"+ oauth-server-dynamic-registration-enabled true]+ (let [response (mt/user-http-request :crowberto :get 200+ ".well-known/oauth-authorization-server")]+ (is (= "http://localhost:3000/oauth/register" (:registration_endpoint response)))))))++;;; ----------------------------------------- Authorization Endpoint ------------------------------------------------++(defn- create-test-client!+ "Insert a static OAuth client directly into the database and return a map+ with the client fields plus the plaintext `:client_secret`."+ ([]+ (create-test-client! {}))+ ([overrides]+ (let [client-secret (oidc-util/generate-client-secret)+ defaults {:client_id (str (random-uuid))+ :client_type "confidential"+ :client_secret_hash (oidc-util/hash-client-secret client-secret)+ :redirect_uris ["https://example.com/callback"]+ :client_name "Test Auth Client"+ :grant_types ["authorization_code" "refresh_token"]+ :response_types ["code"]+ :scopes ["profile"]+ :application_type "web"+ :registration_type "static"}+ [inserted] (t2/insert-returning-instances! :model/OAuthClient (merge defaults overrides))]+ (assoc inserted :client_secret client-secret))))++(deftest authorize-valid-request-test+ (testing "GET /oauth/authorize with valid params returns HTML consent page"+ (mt/with-temporary-setting-values [site-url "http://localhost:3000"]+ (t2/with-transaction [_conn nil {:rollback-only true}]+ (let [client (create-test-client!)+ client-id (:client_id client)+ response (mt/user-http-request-full-response+ :crowberto :get 200 "oauth/authorize"+ :client_id client-id+ :redirect_uri "https://example.com/callback"+ :response_type "code"+ :scope "profile"+ :state "test-state")+ body (:body response)]+ (is (str/includes? (get-in response [:headers "Content-Type"]) "text/html"))+ (is (str/includes? body "Test Auth Client"))+ (is (str/includes? body "profile"))+ (is (str/includes? body client-id))+ (is (str/includes? body "test-state"))+ (is (str/includes? body "/oauth/authorize/decision")))))))++(deftest authorize-invalid-client-id-test+ (testing "GET /oauth/authorize with missing/invalid client_id returns 400"+ (mt/with-temporary-setting-values [site-url "http://localhost:3000"]+ (let [response (mt/user-http-request :crowberto :get 400+ "oauth/authorize"+ :client_id "nonexistent-client"+ :redirect_uri "https://example.com/callback"+ :response_type "code")]+ (is (= "invalid_request" (:error response)))))))++(deftest authorize-mismatched-redirect-uri-test+ (testing "GET /oauth/authorize with mismatched redirect_uri returns 400"+ (mt/with-temporary-setting-values [site-url "http://localhost:3000"]+ (t2/with-transaction [_conn nil {:rollback-only true}]+ (let [client (create-test-client!)+ client-id (:client_id client)+ response (mt/user-http-request :crowberto :get 400+ "oauth/authorize"+ :client_id client-id+ :redirect_uri "https://evil.com/callback"+ :response_type "code")]+ (is (= "invalid_request" (:error response))))))))++(deftest authorize-unauthenticated-test+ (testing "GET /oauth/authorize without session redirects to login page"+ (mt/with-temporary-setting-values [site-url "http://localhost:3000"]+ (let [response (client/client-full-response :get 302 "oauth/authorize"+ :client_id "some-client"+ :redirect_uri "https://example.com/callback"+ :response_type "code")]+ (is (str/starts-with? (get-in response [:headers "Location"])+ "http://localhost:3000/auth/login?redirect="))))))++;;; ----------------------------------------- Authorization Decision ------------------------------------------------++(defn- get-consent-page!+ "GET the consent page and return the full response (including CSRF cookie)."+ [user client-id]+ (mt/user-http-request-full-response+ user :get 200 "oauth/authorize"+ :client_id client-id+ :redirect_uri "https://example.com/callback"+ :response_type "code"+ :scope "profile"+ :state "test-state"))++(defn- extract-csrf-token-from-consent+ "Extract the CSRF token from the consent page HTML body."+ [body]+ (second (re-find #"name=\"csrf_token\"[^>]*value=\"([a-f0-9]+)\"" body)))++(defn- extract-csrf-cookie+ "Extract the CSRF cookie value from the response.+ Checks both the :cookies map and the Set-Cookie header (which may be a string or vector of strings)."+ [response]+ (or+ ;; Try :cookies map first (set by ring.util.response/set-cookie, before wrap-cookies processing)+ (get-in response [:cookies "metabase.OAUTH_CSRF" :value])+ ;; Fall back to parsing Set-Cookie header+ (let [set-cookie (get-in response [:headers "Set-Cookie"])+ cookies (cond+ (string? set-cookie) [set-cookie]+ (sequential? set-cookie) (vec set-cookie)+ :else [])]+ (some #(when (string? %) (second (re-find #"metabase\.OAUTH_CSRF=([a-f0-9]+)" %))) cookies))))++(defn- form-post-decision!+ "POST form-encoded params to /oauth/authorize/decision as an authenticated user."+ [user params expected-status & {:keys [csrf-cookie]}]+ (mt/user-http-request-full-response+ user :post expected-status "oauth/authorize/decision"+ {:request-options {:headers {"content-type" "application/x-www-form-urlencoded"+ "cookie" (when csrf-cookie+ (str "metabase.OAUTH_CSRF=" csrf-cookie))}}}+ params))++(deftest authorize-decision-approve-test+ (testing "POST /oauth/authorize/decision with approved=true returns 302 redirect with code"+ (mt/with-temporary-setting-values [site-url "http://localhost:3000"]+ (t2/with-transaction [_conn nil {:rollback-only true}]+ (let [client (create-test-client!)+ client-id (:client_id client)+ consent-resp (get-consent-page! :crowberto client-id)+ csrf-token (extract-csrf-token-from-consent (:body consent-resp))+ csrf-cookie (extract-csrf-cookie consent-resp)+ response (form-post-decision!+ :crowberto+ {:approved "true"+ :csrf_token csrf-token+ :client_id client-id+ :redirect_uri "https://example.com/callback"+ :response_type "code"+ :scope "profile"+ :state "test-state"}+ 302+ :csrf-cookie csrf-cookie)+ location (get-in response [:headers "Location"])]+ (is (string? csrf-token) "Consent page should contain a CSRF token")+ (is (string? csrf-cookie) "Response should contain a CSRF cookie")+ (is (= csrf-token csrf-cookie) "Cookie and form token should match")+ (is (string? location) "Should have a Location header")+ (is (str/starts-with? location "https://example.com/callback?"))+ (is (str/includes? location "code="))+ (is (str/includes? location "state=test-state")))))))++(deftest authorize-decision-deny-test+ (testing "POST /oauth/authorize/decision with approved=false returns 302 redirect with error"+ (mt/with-temporary-setting-values [site-url "http://localhost:3000"]+ (t2/with-transaction [_conn nil {:rollback-only true}]+ (let [client (create-test-client!)+ client-id (:client_id client)+ consent-resp (get-consent-page! :crowberto client-id)+ csrf-token (extract-csrf-token-from-consent (:body consent-resp))+ csrf-cookie (extract-csrf-cookie consent-resp)+ response (form-post-decision!+ :crowberto+ {:approved "false"+ :csrf_token csrf-token+ :client_id client-id+ :redirect_uri "https://example.com/callback"+ :response_type "code"+ :scope "profile"+ :state "test-state"}+ 302+ :csrf-cookie csrf-cookie)+ location (get-in response [:headers "Location"])]+ (is (some? location))+ (is (str/starts-with? location "https://example.com/callback?"))+ (is (str/includes? location "error=access_denied"))+ (is (str/includes? location "state=test-state")))))))++(deftest authorize-decision-csrf-missing-test+ (testing "POST /oauth/authorize/decision without CSRF token returns 403"+ (mt/with-temporary-setting-values [site-url "http://localhost:3000"]+ (t2/with-transaction [_conn nil {:rollback-only true}]+ (let [client (create-test-client!)+ client-id (:client_id client)+ response (form-post-decision!+ :crowberto+ {:approved "true"+ :client_id client-id+ :redirect_uri "https://example.com/callback"+ :response_type "code"+ :scope "profile"+ :state "test-state"}+ 403)]+ (is (= "csrf_validation_failed" (:error (:body response)))))))))++(deftest authorize-decision-csrf-mismatch-test+ (testing "POST /oauth/authorize/decision with mismatched CSRF token returns 403"+ (mt/with-temporary-setting-values [site-url "http://localhost:3000"]+ (t2/with-transaction [_conn nil {:rollback-only true}]+ (let [client (create-test-client!)+ client-id (:client_id client)+ consent-resp (get-consent-page! :crowberto client-id)+ csrf-cookie (extract-csrf-cookie consent-resp)+ response (form-post-decision!+ :crowberto+ {:approved "true"+ :csrf_token "00000000000000000000000000000000"+ :client_id client-id+ :redirect_uri "https://example.com/callback"+ :response_type "code"+ :scope "profile"+ :state "test-state"}+ 403+ :csrf-cookie csrf-cookie)]+ (is (= "csrf_validation_failed" (:error (:body response)))))))))++(deftest authorize-decision-unauthenticated-test+ (testing "POST /oauth/authorize/decision without session returns 401"+ (mt/with-temporary-setting-values [site-url "http://localhost:3000"]+ (let [response (client/client :post 401 "oauth/authorize/decision"+ {:request-options {:headers {"content-type" "application/x-www-form-urlencoded"}}}+ {:approved "true"+ :client_id "some-client"+ :redirect_uri "https://example.com/callback"+ :response_type "code"})]+ (is (= "unauthorized" (:error response)))))))++;;; ----------------------------------------- Token Endpoint -------------------------------------------------------++(defn- extract-query-param+ "Extract a query parameter value from a URL string."+ [url param-name]+ (when-let [query (second (str/split url #"\?" 2))]+ (->> (str/split query #"&")+ (some (fn [pair]+ (let [[k v] (str/split pair #"=" 2)]+ (when (= k param-name) v)))))))++(defn- authorize-and-get-code!+ "Complete the authorize flow and return the authorization code.+ Creates a client, authorizes, and extracts the code from the redirect."+ [client-id]+ (let [consent-resp (get-consent-page! :crowberto client-id)+ csrf-token (extract-csrf-token-from-consent (:body consent-resp))+ csrf-cookie (extract-csrf-cookie consent-resp)+ response (form-post-decision!+ :crowberto+ {:approved "true"+ :csrf_token csrf-token+ :client_id client-id+ :redirect_uri "https://example.com/callback"+ :response_type "code"+ :scope "profile"+ :state "test-state"}+ 302+ :csrf-cookie csrf-cookie)+ location (get-in response [:headers "Location"])]+ (extract-query-param location "code")))++(defn- token-request!+ "POST to /oauth/token with form-encoded params."+ [params & {:keys [expected-status authorization]+ :or {expected-status 200}}]+ (let [request-options (cond-> {:headers {"content-type" "application/x-www-form-urlencoded"}}+ authorization (assoc-in [:headers "authorization"] authorization))]+ (client/client :post expected-status "oauth/token"+ {:request-options request-options}+ params)))++(set! *warn-on-reflection* true)++(defn- basic-auth-header+ "Build an HTTP Basic auth header value."+ [client-id client-secret]+ (str "Basic " (.encodeToString (Base64/getEncoder)+ (.getBytes (str client-id ":" client-secret) "UTF-8"))))++(deftest token-auth-code-full-flow-test+ (testing "Authorization code grant -- full flow returns tokens"+ (mt/with-temporary-setting-values [site-url "http://localhost:3000"]+ (t2/with-transaction [_conn nil {:rollback-only true}]+ (let [test-client (create-test-client!)+ client-id (:client_id test-client)+ client-secret (:client_secret test-client)+ code (authorize-and-get-code! client-id)]+ (is (some? code) "Should get an authorization code")+ (is (=? {:access_token string?+ :token_type "Bearer"+ :expires_in pos-int?+ :refresh_token string?+ :scope string?}+ (token-request!+ {:grant_type "authorization_code"+ :code code+ :redirect_uri "https://example.com/callback"}+ :authorization (basic-auth-header client-id client-secret)))+ "Should return full token response"))))))++(deftest token-auth-code-invalid-code-test+ (testing "Authorization code grant -- invalid code returns error"+ (mt/with-temporary-setting-values [site-url "http://localhost:3000"]+ (t2/with-transaction [_conn nil {:rollback-only true}]+ (let [test-client (create-test-client!)+ client-id (:client_id test-client)+ client-secret (:client_secret test-client)+ response (token-request!+ {:grant_type "authorization_code"+ :code "bogus-code"+ :redirect_uri "https://example.com/callback"}+ :expected-status 400+ :authorization (basic-auth-header client-id client-secret))]+ (is (=? {:error string?} response)))))))++(deftest token-auth-code-wrong-client-test+ (testing "Authorization code grant -- wrong client gets error"+ (mt/with-temporary-setting-values [site-url "http://localhost:3000"]+ (t2/with-transaction [_conn nil {:rollback-only true}]+ (let [client-a (create-test-client!)+ client-b (create-test-client! {:redirect_uris ["https://other.com/callback"]+ :client_name "Other Client"+ :grant_types ["authorization_code"]+ :response_types ["code"]+ :scopes ["profile"]})+ code (authorize-and-get-code! (:client_id client-a))+ response (token-request!+ {:grant_type "authorization_code"+ :code code+ :redirect_uri "https://example.com/callback"}+ :expected-status 400+ :authorization (basic-auth-header (:client_id client-b) (:client_secret client-b)))]+ (is (=? {:error string?} response)))))))++(deftest token-refresh-grant-test+ (testing "Refresh token grant -- returns new access token"+ (mt/with-temporary-setting-values [site-url "http://localhost:3000"]+ (t2/with-transaction [_conn nil {:rollback-only true}]+ (let [test-client (create-test-client!)+ client-id (:client_id test-client)+ client-secret (:client_secret test-client)+ code (authorize-and-get-code! client-id)+ token-response (token-request!+ {:grant_type "authorization_code"+ :code code+ :redirect_uri "https://example.com/callback"}+ :authorization (basic-auth-header client-id client-secret))+ refresh-response (token-request!+ {:grant_type "refresh_token"+ :refresh_token (:refresh_token token-response)}+ :authorization (basic-auth-header client-id client-secret))]+ (is (=? {:access_token string?+ :token_type "Bearer"+ :expires_in pos-int?}+ refresh-response)))))))++(deftest refresh-token-has-expiry-test+ (testing "Refresh tokens are stored with an expiry derived from oauth-server-refresh-token-ttl"+ (mt/with-temporary-setting-values [site-url "http://localhost:3000"+ oauth-server-refresh-token-ttl 7200]+ (t2/with-transaction [_conn nil {:rollback-only true}]+ (let [test-client (create-test-client!)+ client-id (:client_id test-client)+ client-secret (:client_secret test-client)+ code (authorize-and-get-code! client-id)+ token-response (token-request!+ {:grant_type "authorization_code"+ :code code+ :redirect_uri "https://example.com/callback"}+ :authorization (basic-auth-header client-id client-secret))]+ (is (some? (:refresh_token token-response)))+ (let [db-token (t2/select-one :model/OAuthRefreshToken :client_id client-id)]+ (is (some? db-token) "Refresh token should be stored in the database")+ (is (some? (:expiry db-token)) "Refresh token should have an expiry set")+ (when (:expiry db-token)+ (let [now-ms (System/currentTimeMillis)+ ;; expiry should be ~7200s from now; allow 60s tolerance+ expected (* 7200 1000)+ actual (- (:expiry db-token) now-ms)]+ (is (< (abs (- actual expected)) 60000)+ (str "Refresh token expiry should be ~7200s from now, got "+ (/ actual 1000.0) "s"))))))))))++(deftest dcr-strips-client-credentials-grant-type-test+ (testing "Dynamic client registration strips client_credentials from grant_types"+ ;; client_credentials tokens have no user context (user_id = NULL) which makes+ ;; them unusable for MCP — validate-bearer-token requires a valid integer user-id.+ (mt/with-temporary-setting-values [site-url "http://localhost:3000"+ oauth-server-dynamic-registration-enabled true]+ (t2/with-transaction [_conn nil {:rollback-only true}]+ (let [response (mt/user-http-request :crowberto :post 201 "oauth/register"+ {:client_name "CC Client"+ :redirect_uris ["https://example.com/callback"]+ :grant_types ["authorization_code" "client_credentials"]})]+ (is (= ["authorization_code"] (:grant_types response))))))))++(deftest token-wrong-client-secret-test+ (testing "Token request with wrong client secret returns 400"+ (mt/with-temporary-setting-values [site-url "http://localhost:3000"]+ (t2/with-transaction [_conn nil {:rollback-only true}]+ (let [test-client (create-test-client!)+ client-id (:client_id test-client)+ response (token-request!+ {:grant_type "authorization_code"+ :code "some-code"+ :redirect_uri "https://example.com/callback"}+ :expected-status 400+ :authorization (basic-auth-header client-id "wrong-secret"))]+ (is (=? {:error string?} response)))))))++(deftest token-missing-grant-type-test+ (testing "Missing grant_type -- returns 400"+ (mt/with-temporary-setting-values [site-url "http://localhost:3000"]+ (t2/with-transaction [_conn nil {:rollback-only true}]+ (let [test-client (create-test-client!)+ response (token-request!+ {}+ :expected-status 400+ :authorization (basic-auth-header (:client_id test-client) (:client_secret test-client)))]+ (is (=? {:error string?} response)))))))++(deftest token-basic-auth-test+ (testing "Client auth via Basic header works"+ (mt/with-temporary-setting-values [site-url "http://localhost:3000"]+ (t2/with-transaction [_conn nil {:rollback-only true}]+ (let [test-client (create-test-client!)+ client-id (:client_id test-client)+ client-secret (:client_secret test-client)+ code (authorize-and-get-code! client-id)+ response (token-request!+ {:grant_type "authorization_code"+ :code code+ :redirect_uri "https://example.com/callback"}+ :authorization (basic-auth-header client-id client-secret))]+ (is (=? {:access_token string?+ :token_type "Bearer"}+ response)))))))++;;; ----------------------------------------- PKCE Tests -------------------------------------------------------++(defn- pkce-s256-challenge+ "Compute a S256 PKCE code challenge from a code verifier."+ [^String code-verifier]+ (let [digest (.digest (MessageDigest/getInstance "SHA-256") (.getBytes code-verifier "US-ASCII"))]+ (-> (Base64/getUrlEncoder)+ .withoutPadding+ (.encodeToString digest))))++(defn- authorize-and-get-code-with-params!+ "Complete the authorize flow with extra decision params and return the authorization code."+ [client-id extra-params]+ (let [consent-resp (get-consent-page! :crowberto client-id)+ csrf-token (extract-csrf-token-from-consent (:body consent-resp))+ csrf-cookie (extract-csrf-cookie consent-resp)+ response (form-post-decision!+ :crowberto+ (merge {:approved "true"+ :csrf_token csrf-token+ :client_id client-id+ :redirect_uri "https://example.com/callback"+ :response_type "code"+ :scope "profile"+ :state "test-state"}+ extra-params)+ 302+ :csrf-cookie csrf-cookie)+ location (get-in response [:headers "Location"])]+ (extract-query-param location "code")))++(deftest token-auth-code-pkce-s256-test+ (testing "Authorization code grant with S256 PKCE succeeds"+ (mt/with-temporary-setting-values [site-url "http://localhost:3000"]+ (t2/with-transaction [_conn nil {:rollback-only true}]+ (let [test-client (create-test-client!)+ client-id (:client_id test-client)+ client-secret (:client_secret test-client)+ code-verifier "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk"+ code-challenge (pkce-s256-challenge code-verifier)+ code (authorize-and-get-code-with-params!+ client-id+ {:code_challenge code-challenge+ :code_challenge_method "S256"})]+ (is (string? code) "Should get an authorization code")+ (is (=? {:access_token string?+ :token_type "Bearer"+ :expires_in pos-int?}+ (token-request!+ {:grant_type "authorization_code"+ :code code+ :redirect_uri "https://example.com/callback"+ :code_verifier code-verifier}+ :authorization (basic-auth-header client-id client-secret)))))))))++(deftest token-auth-code-pkce-missing-verifier-test+ (testing "Authorization code grant with PKCE but missing code_verifier returns error"+ (mt/with-temporary-setting-values [site-url "http://localhost:3000"]+ (t2/with-transaction [_conn nil {:rollback-only true}]+ (let [test-client (create-test-client!)+ client-id (:client_id test-client)+ client-secret (:client_secret test-client)+ code-verifier "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk"+ code-challenge (pkce-s256-challenge code-verifier)+ code (authorize-and-get-code-with-params!+ client-id+ {:code_challenge code-challenge+ :code_challenge_method "S256"})+ response (token-request!+ {:grant_type "authorization_code"+ :code code+ :redirect_uri "https://example.com/callback"}+ :expected-status 400+ :authorization (basic-auth-header client-id client-secret))]+ (is (=? {:error string?} response)))))))++;;; ----------------------------------------- Expired / Revoked Token Tests ------------------------------------++(deftest token-auth-code-expired-code-test+ (testing "Authorization code grant with expired code returns error"+ (mt/with-temporary-setting-values [site-url "http://localhost:3000"+ oauth-server-authorization-code-ttl 1]+ (t2/with-transaction [_conn nil {:rollback-only true}]+ (let [test-client (create-test-client!)+ client-id (:client_id test-client)+ client-secret (:client_secret test-client)+ code (authorize-and-get-code! client-id)]+ (is (string? code) "Should get an authorization code")+ (Thread/sleep 1500)+ (is (=? {:error string?}+ (token-request!+ {:grant_type "authorization_code"+ :code code+ :redirect_uri "https://example.com/callback"}+ :expected-status 400+ :authorization (basic-auth-header client-id client-secret)))))))))++;;; ------------------------------------------ Revocation Endpoint -----------------------------------------------++(defn- revoke-request!+ "POST to /oauth/revoke with form-encoded params."+ [params & {:keys [expected-status authorization]+ :or {expected-status 200}}]+ (let [request-options (cond-> {:headers {"content-type" "application/x-www-form-urlencoded"}}+ authorization (assoc-in [:headers "authorization"] authorization))]+ (client/client :post expected-status "oauth/revoke"+ {:request-options request-options}+ params)))++(deftest token-refresh-revoked-token-test+ (testing "Refresh token grant with revoked refresh token returns error"+ (mt/with-temporary-setting-values [site-url "http://localhost:3000"]+ (t2/with-transaction [_conn nil {:rollback-only true}]+ (let [test-client (create-test-client!)+ client-id (:client_id test-client)+ client-secret (:client_secret test-client)+ code (authorize-and-get-code! client-id)+ token-response (token-request!+ {:grant_type "authorization_code"+ :code code+ :redirect_uri "https://example.com/callback"}+ :authorization (basic-auth-header client-id client-secret))+ refresh-token (:refresh_token token-response)]+ ;; Revoke via the revocation endpoint (tokens are hashed in the DB)+ (revoke-request!+ {:token refresh-token}+ :authorization (basic-auth-header client-id client-secret))+ (let [response (token-request!+ {:grant_type "refresh_token"+ :refresh_token refresh-token}+ :expected-status 400+ :authorization (basic-auth-header client-id client-secret))]+ (is (=? {:error string?} response))))))))++(deftest revocation-valid-token-test+ (testing "Revocation returns 200 for a valid access token"+ (mt/with-temporary-setting-values [site-url "http://localhost:3000"]+ (t2/with-transaction [_conn nil {:rollback-only true}]+ (let [test-client (create-test-client!)+ client-id (:client_id test-client)+ client-secret (:client_secret test-client)+ code (authorize-and-get-code! client-id)+ token-resp (token-request!+ {:grant_type "authorization_code"+ :code code+ :redirect_uri "https://example.com/callback"}+ :authorization (basic-auth-header client-id client-secret))+ access-token (:access_token token-resp)]+ (is (some? access-token))+ (revoke-request!+ {:token access-token}+ :authorization (basic-auth-header client-id client-secret)))))))++(deftest revocation-unknown-token-test+ (testing "Revocation returns 200 for an unknown token (RFC 7009 S2.2)"+ (mt/with-temporary-setting-values [site-url "http://localhost:3000"]+ (t2/with-transaction [_conn nil {:rollback-only true}]+ (let [test-client (create-test-client!)+ client-id (:client_id test-client)+ client-secret (:client_secret test-client)]+ (revoke-request!+ {:token "nonexistent-token"}+ :authorization (basic-auth-header client-id client-secret)))))))++(deftest discovery-includes-revocation-endpoint-test+ (testing "Discovery document includes revocation_endpoint"+ (mt/with-temporary-setting-values [site-url "http://localhost:3000"+ oauth-server-dynamic-registration-enabled true]+ (let [response (mt/user-http-request :crowberto :get 200+ ".well-known/oauth-authorization-server")]+ (is (= "http://localhost:3000/oauth/revoke"+ (:revocation_endpoint response)))))))++;;; ----------------------------------------- Bearer Token Parsing ---------------------------------------------------++(deftest extract-bearer-token-test+ (testing "standard Bearer token"+ (is (= "abc123" (oauth-server/extract-bearer-token {:headers {"authorization" "Bearer abc123"}}))))+ (testing "case-insensitive prefix"+ (is (= "TOKEN" (oauth-server/extract-bearer-token {:headers {"authorization" "bearer TOKEN"}}))))+ (testing "trims whitespace after prefix"+ (is (= "TOKEN" (oauth-server/extract-bearer-token {:headers {"authorization" "Bearer TOKEN"}}))))+ (testing "Bearer with no token returns empty string"+ (is (= "" (oauth-server/extract-bearer-token {:headers {"authorization" "Bearer "}}))))+ (testing "missing header returns nil"+ (is (nil? (oauth-server/extract-bearer-token {:headers {}}))))+ (testing "empty header returns nil"+ (is (nil? (oauth-server/extract-bearer-token {:headers {"authorization" ""}}))))+ (testing "non-Bearer scheme returns nil"+ (is (nil? (oauth-server/extract-bearer-token {:headers {"authorization" "Basic abc123"}})))))++;;; ----------------------------------------- State Round-Trip -------------------------------------------------------++(deftest authorize-state-special-characters-test+ (testing "OAuth state with special characters survives the authorize round-trip"+ (mt/with-temporary-setting-values [site-url "http://localhost:3000"]+ (t2/with-transaction [_conn nil {:rollback-only true}]+ (let [state "abc+/=&foo=bar baz"+ client (create-test-client!)+ client-id (:client_id client)+ consent-resp (mt/user-http-request-full-response+ :crowberto :get 200 "oauth/authorize"+ :client_id client-id+ :redirect_uri "https://example.com/callback"+ :response_type "code"+ :scope "profile"+ :state state)+ csrf-token (extract-csrf-token-from-consent (:body consent-resp))+ csrf-cookie (extract-csrf-cookie consent-resp)+ response (form-post-decision!+ :crowberto+ {:approved "true"+ :csrf_token csrf-token+ :client_id client-id+ :redirect_uri "https://example.com/callback"+ :response_type "code"+ :scope "profile"+ :state state}+ 302+ :csrf-cookie csrf-cookie)+ location (get-in response [:headers "Location"])]+ (is (str/includes? location "state="))+ (is (str/includes? location (java.net.URLEncoder/encode state "UTF-8"))))))))++;;; ----------------------------------------- Consent Page Security --------------------------------------------------++(deftest consent-page-xss-client-name-test+ (testing "Client name with HTML/script tags is escaped in the consent page"+ (mt/with-temporary-setting-values [site-url "http://localhost:3000"]+ (t2/with-transaction [_conn nil {:rollback-only true}]+ (let [xss-name "<script>alert('xss')</script>"+ client (create-test-client! {:client_name xss-name})+ client-id (:client_id client)+ response (mt/user-http-request-full-response+ :crowberto :get 200 "oauth/authorize"+ :client_id client-id+ :redirect_uri "https://example.com/callback"+ :response_type "code"+ :scope "profile"+ :state "test-state")+ body (:body response)]+ (is (not (str/includes? body "<script>alert('xss')</script>"))+ "Raw script tags must not appear in the consent page")+ (is (str/includes? body "<script>")+ "Script tags should be HTML-escaped"))))))diff --git a/test/metabase/oauth_server/consent_page_test.clj b/test/metabase/oauth_server/consent_page_test.cljnew file mode 100644index 00000000000..dc0d16bde02--- /dev/null+++ b/test/metabase/oauth_server/consent_page_test.clj@@ -0,0 +1,33 @@+(ns metabase.oauth-server.consent-page-test+ (:require+ [clojure.test :refer [deftest is testing]]+ [metabase.oauth-server.consent-page :as consent-page]+ [metabase.test :as mt]))++(defn- render!+ "Render the consent page with default params."+ []+ (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"}+ :nonce "test-nonce"+ :csrf-token "test-csrf"})))++(deftest consent-page-heading-test+ (testing "heading includes client name with question mark"+ (let [html (render!)]+ (is (re-find #"Authorize Test App\?" html)))))++(deftest consent-page-buttons-test+ (testing "buttons say Cancel and Authorize"+ (let [html (render!)]+ (is (re-find #">Cancel<" html))+ (is (re-find #">Authorize<" html)))))++(deftest default-logo-inlined-with-brand-color-test+ (testing "default logo is inlined as SVG with brand color replacing currentColor"+ (let [html (render!)]+ (is (re-find #"<svg" html) "should contain inline SVG")+ (is (not (re-find #"currentColor" html)) "should not contain currentColor")+ (is (re-find #"#509ee3" html) "should contain the default brand color"))))diff --git a/test/metabase/oauth_server/core_test.clj b/test/metabase/oauth_server/core_test.cljnew file mode 100644index 00000000000..0125d7a03c4--- /dev/null+++ b/test/metabase/oauth_server/core_test.clj@@ -0,0 +1,28 @@+(ns metabase.oauth-server.core-test+ (:require+ [clojure.test :refer [deftest is testing use-fixtures]]+ [metabase.oauth-server.core :as oauth-server]+ [metabase.test :as mt]))++;; TODO (Chris 2026-03-24) — remove kondo ignore once linter respects the thread-safe list in use-fixtures+#_{:clj-kondo/ignore [:metabase/validate-deftest]}+(use-fixtures :each (fn [thunk]+ (oauth-server/reset-provider!)+ (thunk)+ (oauth-server/reset-provider!)))++(deftest get-provider-test+ (testing "get-provider returns a Provider instance"+ (mt/with-temporary-setting-values [site-url "http://localhost:3000"]+ (let [provider (oauth-server/get-provider)]+ (is (some? provider))+ (is (instance? oidc_provider.core.Provider provider))))))++(deftest provider-endpoints-test+ (testing "provider's config contains endpoints rooted at the configured site-url"+ (mt/with-temporary-setting-values [site-url "http://localhost:3000"]+ (let [provider (oauth-server/get-provider)+ config (:config provider)]+ (is (= "http://localhost:3000" (:issuer config)))+ (is (= "http://localhost:3000/oauth/authorize" (:authorization-endpoint config)))+ (is (= "http://localhost:3000/oauth/token" (:token-endpoint config)))))))diff --git a/test/metabase/oauth_server/settings_test.clj b/test/metabase/oauth_server/settings_test.cljnew file mode 100644index 00000000000..a29d02fb438--- /dev/null+++ b/test/metabase/oauth_server/settings_test.clj@@ -0,0 +1,19 @@+(ns metabase.oauth-server.settings-test+ (:require+ [clojure.test :refer [deftest is testing]]+ [metabase.oauth-server.settings :as oauth-settings]+ [metabase.test :as mt]))++(deftest settings-work-without-feature-flag-test+ (testing "oauth-server settings work without any premium feature flag"+ (mt/with-temporary-setting-values [oauth-server-access-token-ttl 3600]+ (is (= 3600 (oauth-settings/oauth-server-access-token-ttl)))+ (oauth-settings/oauth-server-access-token-ttl! 7200)+ (is (= 7200 (oauth-settings/oauth-server-access-token-ttl))))))++(deftest refresh-token-ttl-setting-test+ (testing "oauth-server-refresh-token-ttl defaults to 30 days and can be changed"+ (mt/with-temporary-setting-values [oauth-server-refresh-token-ttl 2592000]+ (is (= 2592000 (oauth-settings/oauth-server-refresh-token-ttl)))+ (oauth-settings/oauth-server-refresh-token-ttl! 86400)+ (is (= 86400 (oauth-settings/oauth-server-refresh-token-ttl))))))diff --git a/test/metabase/oauth_server/store_test.clj b/test/metabase/oauth_server/store_test.cljnew file mode 100644index 00000000000..1fa63ec3ab3--- /dev/null+++ b/test/metabase/oauth_server/store_test.clj@@ -0,0 +1,294 @@+(ns metabase.oauth-server.store-test+ (:require+ [clojure.test :refer [deftest is testing]]+ [metabase.oauth-server.store :as store]+ [metabase.test :as mt]+ [oidc-provider.protocol :as proto]+ [oidc-provider.util :as oidc-util]+ [toucan2.core :as t2]))++;;; ------------------------------------------------ ClientStore -------------------------------------------------------++(deftest client-store-register-and-get-test+ (t2/with-transaction [_conn nil {:rollback-only true}]+ (let [cs (store/create-client-store)+ secret-hash (oidc-util/hash-client-secret "super-secret")+ config {:client-id (str (random-uuid))+ ;; The library pre-hashes the client secret before calling register-client+ :client-secret secret-hash+ :redirect-uris ["https://example.com/callback"]+ :grant-types ["authorization_code"]+ :response-types ["code"]+ :scopes ["openid" "profile"]}+ result (proto/register-client cs config)]+ (testing "register-client returns config with client-id"+ (is (= (:client-id config) (:client-id result))))+ (testing "client secret hash is stored"+ (is (=? {:client-secret-hash string?}+ result)))+ (testing "get-client returns only the hash, not plaintext secret"+ (let [fetched (proto/get-client cs (:client-id config))]+ (is (=? {:client-secret-hash string?} fetched))+ (is (nil? (:client-secret fetched)))))+ (testing "get-client returns the registered client"+ (let [fetched (proto/get-client cs (:client-id config))]+ (is (=? {:client-id (:client-id config)+ :redirect-uris ["https://example.com/callback"]+ :grant-types ["authorization_code"]+ :response-types ["code"]+ :scopes ["openid" "profile"]+ :client-secret-hash string?}+ fetched))))+ (testing "stored hash verifies against original secret"+ (let [fetched (proto/get-client cs (:client-id config))]+ (is (oidc-util/verify-client-secret "super-secret" (:client-secret-hash fetched))))))))++(deftest client-store-generate-client-id-test+ (t2/with-transaction [_conn nil {:rollback-only true}]+ (let [cs (store/create-client-store)+ config {:redirect-uris ["https://example.com/callback"]+ :grant-types ["authorization_code"]+ :response-types ["code"]+ :scopes ["openid"]}+ result (proto/register-client cs config)]+ (testing "client-id is generated when not provided"+ (is (some? (:client-id result)))+ (is (string? (:client-id result)))))))++(deftest client-store-update-test+ (t2/with-transaction [_conn nil {:rollback-only true}]+ (let [cs (store/create-client-store)+ client-id (str (random-uuid))+ config {:client-id client-id+ :redirect-uris ["https://example.com/callback"]+ :grant-types ["authorization_code"]+ :response-types ["code"]+ :scopes ["openid"]+ :client-name "Original Name"}]+ (proto/register-client cs config)+ (let [updated (proto/update-client cs client-id {:client-name "Updated Name"})]+ (testing "update-client returns merged config"+ (is (= "Updated Name" (:client-name updated)))+ (is (= ["https://example.com/callback"] (:redirect-uris updated))))+ (testing "get-client reflects the update"+ (let [fetched (proto/get-client cs client-id)]+ (is (= "Updated Name" (:client-name fetched)))))))))++(deftest client-store-get-nonexistent-test+ (let [cs (store/create-client-store)]+ (testing "get-client returns nil for nonexistent client"+ (is (nil? (proto/get-client cs "nonexistent-id"))))))++(deftest client-store-update-nonexistent-test+ (let [cs (store/create-client-store)]+ (testing "update-client returns nil for nonexistent client"+ (is (nil? (proto/update-client cs "nonexistent-id" {:client-name "Nope"}))))))++(deftest client-store-register-public-client-test+ (t2/with-transaction [_conn nil {:rollback-only true}]+ (let [cs (store/create-client-store)+ config {:client-id (str (random-uuid))+ :redirect-uris ["https://example.com/callback"]+ :grant-types ["authorization_code"]+ :response-types ["code"]+ :scopes ["openid"]+ :token-endpoint-auth-method "none"}+ result (proto/register-client cs config)]+ (testing "public client has no secret hash"+ (is (nil? (:client-secret-hash result))))+ (testing "get-client returns nil for client-secret-hash"+ (let [fetched (proto/get-client cs (:client-id config))]+ (is (nil? (:client-secret-hash fetched)))+ (is (= "none" (:token-endpoint-auth-method fetched))))))))++(deftest client-store-registration-access-token-test+ (t2/with-transaction [_conn nil {:rollback-only true}]+ (let [cs (store/create-client-store)+ rat "my-registration-access-token"+ rat-hash (oidc-util/hash-client-secret rat)+ config {:client-id (str (random-uuid))+ :redirect-uris ["https://example.com/callback"]+ :grant-types ["authorization_code"]+ :response-types ["code"]+ :scopes ["openid"]+ ;; The library pre-hashes before calling register-client+ :registration-access-token rat-hash}+ result (proto/register-client cs config)]+ (testing "register-client stores the hash"+ (is (=? {:registration-access-token-hash string?}+ result)))+ (testing "get-client returns hash under both :registration-access-token-hash and :registration-access-token"+ (let [fetched (proto/get-client cs (:client-id config))]+ (is (=? {:registration-access-token-hash string?+ :registration-access-token string?} fetched))+ (is (= (:registration-access-token-hash fetched)+ (:registration-access-token fetched)))))+ (testing "stored hash verifies against original plaintext token"+ (let [fetched (proto/get-client cs (:client-id config))]+ (is (oidc-util/verify-client-secret rat (:registration-access-token fetched))))))))++;;; ----------------------------------------- AuthorizationCodeStore ---------------------------------------------------++(deftest authorization-code-store-save-and-get-test+ (t2/with-transaction [_conn nil {:rollback-only true}]+ (let [acs (store/create-authorization-code-store)+ code (str (random-uuid))+ user-id (mt/user->id :rasta)+ client-id (str (random-uuid))+ expiry (+ (inst-ms (java.util.Date.)) 600000)]+ (testing "save-authorization-code returns true"+ (is (true? (proto/save-authorization-code acs code user-id client-id+ "https://example.com/callback"+ ["openid" "profile"]+ "test-nonce"+ expiry+ "challenge123"+ "S256"+ ["https://api.example.com"]))))+ (testing "get-authorization-code returns the saved code data"+ (let [fetched (proto/get-authorization-code acs code)]+ (is (=? {:user-id (str user-id)+ :client-id client-id+ :redirect-uri "https://example.com/callback"+ :scope ["openid" "profile"]+ :nonce "test-nonce"+ :expiry expiry+ :code-challenge "challenge123"+ :code-challenge-method "S256"+ :resource ["https://api.example.com"]}+ fetched)))))))++(deftest authorization-code-store-delete-test+ (t2/with-transaction [_conn nil {:rollback-only true}]+ (let [acs (store/create-authorization-code-store)+ code (str (random-uuid))+ user-id (mt/user->id :rasta)+ client-id (str (random-uuid))]+ (proto/save-authorization-code acs code user-id client-id+ "https://example.com/callback"+ ["openid"] nil+ (+ (inst-ms (java.util.Date.)) 600000)+ nil nil nil)+ (testing "delete-authorization-code returns true"+ (is (true? (proto/delete-authorization-code acs code))))+ (testing "get returns nil after delete"+ (is (nil? (proto/get-authorization-code acs code)))))))++(deftest authorization-code-store-get-nonexistent-test+ (let [acs (store/create-authorization-code-store)]+ (testing "get-authorization-code returns nil for nonexistent code"+ (is (nil? (proto/get-authorization-code acs "nonexistent-code"))))))++(deftest authorization-code-store-consume-test+ (t2/with-transaction [_conn nil {:rollback-only true}]+ (let [acs (store/create-authorization-code-store)+ code (str (random-uuid))+ user-id (mt/user->id :rasta)+ client-id (str (random-uuid))+ expiry (+ (inst-ms (java.util.Date.)) 600000)]+ (proto/save-authorization-code acs code user-id client-id+ "https://example.com/callback"+ ["openid" "profile"]+ "test-nonce"+ expiry+ "challenge123"+ "S256"+ ["https://api.example.com"])+ (testing "consume returns the saved code data"+ (let [consumed (proto/consume-authorization-code acs code)]+ (is (=? {:user-id (str user-id)+ :client-id client-id+ :redirect-uri "https://example.com/callback"+ :scope ["openid" "profile"]+ :nonce "test-nonce"+ :expiry expiry+ :code-challenge "challenge123"+ :code-challenge-method "S256"+ :resource ["https://api.example.com"]}+ consumed))))+ (testing "get returns nil after consume"+ (is (nil? (proto/get-authorization-code acs code))))+ (testing "consuming again returns nil"+ (is (nil? (proto/consume-authorization-code acs code)))))))++(deftest authorization-code-store-consume-race-test+ (testing "concurrent consume calls: exactly one succeeds"+ (let [acs (store/create-authorization-code-store)+ code (str (random-uuid))+ user-id (mt/user->id :rasta)+ client-id (str (random-uuid))+ expiry (+ (inst-ms (java.util.Date.)) 600000)]+ (proto/save-authorization-code acs code user-id client-id+ "https://example.com/callback"+ ["openid" "profile"]+ "test-nonce"+ expiry+ "challenge123"+ "S256"+ ["https://api.example.com"])+ (let [results (->> (repeatedly 10 #(future (proto/consume-authorization-code acs code)))+ doall+ (map deref))]+ (is (= 1 (count (filter some? results))))))))++;;; ------------------------------------------------ TokenStore --------------------------------------------------------++(deftest token-store-access-token-test+ (t2/with-transaction [_conn nil {:rollback-only true}]+ (let [ts (store/create-token-store)+ token (str (random-uuid))+ user-id (mt/user->id :rasta)+ client-id (str (random-uuid))+ expiry (+ (inst-ms (java.util.Date.)) 3600000)]+ (testing "save-access-token returns true"+ (is (true? (proto/save-access-token ts token user-id client-id+ ["openid" "profile"] expiry+ ["https://api.example.com"]))))+ (testing "get-access-token returns the saved token data"+ (let [fetched (proto/get-access-token ts token)]+ (is (=? {:user-id (str user-id)+ :client-id client-id+ :scope ["openid" "profile"]+ :expiry expiry+ :resource ["https://api.example.com"]}+ fetched)))))))++(deftest token-store-refresh-token-test+ (t2/with-transaction [_conn nil {:rollback-only true}]+ (let [ts (store/create-token-store)+ token (str (random-uuid))+ user-id (mt/user->id :rasta)+ client-id (str (random-uuid))]+ (testing "save-refresh-token returns true"+ (is (true? (proto/save-refresh-token ts token user-id client-id+ ["openid"] nil nil))))+ (testing "get-refresh-token returns the saved token data"+ (let [fetched (proto/get-refresh-token ts token)]+ (is (=? {:user-id (str user-id)+ :client-id client-id+ :scope ["openid"]}+ fetched)))))))++(deftest token-store-revoke-test+ (t2/with-transaction [_conn nil {:rollback-only true}]+ (let [ts (store/create-token-store)+ access-tok (str (random-uuid))+ refresh-tok (str (random-uuid))+ user-id (mt/user->id :rasta)+ client-id (str (random-uuid))+ expiry (+ (inst-ms (java.util.Date.)) 3600000)]+ (proto/save-access-token ts access-tok user-id client-id ["openid"] expiry nil)+ (proto/save-refresh-token ts refresh-tok user-id client-id ["openid"] nil nil)+ (testing "revoke-token returns true"+ (is (true? (proto/revoke-token ts access-tok)))+ (is (true? (proto/revoke-token ts refresh-tok))))+ (testing "get returns nil after revocation"+ (is (nil? (proto/get-access-token ts access-tok)))+ (is (nil? (proto/get-refresh-token ts refresh-tok)))))))++(deftest token-store-get-nonexistent-test+ (let [ts (store/create-token-store)]+ (testing "get-access-token returns nil for nonexistent token"+ (is (nil? (proto/get-access-token ts "nonexistent"))))+ (testing "get-refresh-token returns nil for nonexistent token"+ (is (nil? (proto/get-refresh-token ts "nonexistent"))))))diff --git a/test/metabase/test.clj b/test/metabase/test.cljindex f7f6faa8b89..2382e46f66d 100644--- a/test/metabase/test.clj+++ b/test/metabase/test.clj@@ -186,6 +186,7 @@[metabase.test.util.dynamic-redefsdynamic-value+ original-fnwith-dynamic-fn-redefs][premium-features.test-utildiff --git a/test/metabase/test/util/dynamic_redefs.clj b/test/metabase/test/util/dynamic_redefs.cljindex 6d166fd793b..17a445699e3 100644--- a/test/metabase/test/util/dynamic_redefs.clj+++ b/test/metabase/test/util/dynamic_redefs.clj@@ -14,6 +14,13 @@(get *local-redefs* a-var(get (meta a-var) ::original)))+(defn original-fn+ "Return the original (unpatched) function for `a-var`. If the var has been+ patched by [[with-dynamic-fn-redefs]], returns the stored original; otherwise+ returns the var's current root value."+ [a-var]+ (or (::original (meta a-var)) @a-var))+(defn- var->proxy"Build a proxy function to intercept the given var. The proxy checks the current scope for what to call."[a-var]