Skip to content

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

Fix MCP OAuth consent flow when Metabase is hosted under a subpath (#77765)

dpsutton5fb83b02e7ae
diff --git a/frontend/src/metabase/router/guards.tsx b/frontend/src/metabase/router/guards.tsx
index 34ad844efc2..613e4ea5de9 100644
--- a/frontend/src/metabase/router/guards.tsx
+++ b/frontend/src/metabase/router/guards.tsx
@@ -8,6 +8,7 @@ import { getAdminPaths } from "metabase/selectors/admin";
import { getIsEmbeddingIframe } from "metabase/selectors/embed";
import { getCanAccessOnboardingPage } from "metabase/selectors/onboarding";
import { getSetting } from "metabase/selectors/settings";
+import { getBasename } from "metabase/utils/basename";
import { isSameOrSiteUrlOrigin, replaceLocation } from "metabase/utils/dom";
import { Navigate } from "./Navigate";
@@ -32,6 +33,37 @@ const getRedirectUrl = () => {
: "/";
};
+/**
+ * A redirect target arrives in one of two shapes: an absolute URL
+ * (`https://host/metabase/x`, `//host/x`) whose pathname is already what the
+ * browser sees, or a basename-relative path (`/oauth/x`, sloppily `oauth/x`) —
+ * the convention for every SPA path, including the backend's login redirect
+ * (the server sits behind the prefix-stripping proxy and never sees the
+ * subpath). Normalize to a browser-real URL.
+ */
+const toBrowserUrl = (url: string) => {
+ const hasExplicitOrigin = /^[a-z][a-z0-9+.-]*:|^\/\//i.test(url);
+ // String-join for paths, not URL resolution: a leading "/" is *root*-relative
+ // and would discard the basename from a URL base.
+ return hasExplicitOrigin
+ ? new URL(url, window.location.origin)
+ : new URL(
+ `${getBasename()}/${url.replace(/^\//, "")}`,
+ window.location.origin,
+ );
+};
+
+/** The inverse: strip the basename back off for the SPA router, which prepends
+ * it itself (and for prefix checks like `isBackendOnlyPath`). */
+const toRouterPath = ({ pathname, search, hash }: URL) => {
+ const basename = getBasename();
+ const relativePathname =
+ basename && pathname.startsWith(`${basename}/`)
+ ? pathname.slice(basename.length)
+ : pathname;
+ return `${relativePathname}${search}${hash}`;
+};
+
/**
* `getRedirectUrl` accepts site-url-origin targets as well as same-origin ones,
* so it can hand back an absolute URL. The SPA router only understands in-app
@@ -39,13 +71,13 @@ const getRedirectUrl = () => {
* can serve that origin at all.
*/
const resolveRedirectTarget = (url: string) => {
- const target = new URL(url, window.location.origin);
+ const target = toBrowserUrl(url);
return {
// Absolute, so a full-page redirect is not re-resolved against the current
// path (a bare `auth/sso/x` would otherwise land under `/auth/login`).
href: target.href,
- path: `${target.pathname}${target.search}${target.hash}`,
+ path: toRouterPath(target),
isInAppOrigin: target.origin === window.location.origin,
};
};
diff --git a/frontend/src/metabase/router/guards.unit.spec.tsx b/frontend/src/metabase/router/guards.unit.spec.tsx
index 40f969822da..c5ce3be3fb1 100644
--- a/frontend/src/metabase/router/guards.unit.spec.tsx
+++ b/frontend/src/metabase/router/guards.unit.spec.tsx
@@ -4,6 +4,7 @@ import {
createMockSettingsState,
createMockState,
} from "metabase/redux/store/mocks";
+import { setBasename } from "metabase/utils/basename";
import { replaceLocation } from "metabase/utils/dom";
import { createMockUser } from "metabase-types/api/mocks";
@@ -154,6 +155,7 @@ describe("route-guards", () => {
window.history.replaceState({}, "", "/");
// reset the global MetabaseSettings singleton mutated by mockSettings
mockSettings();
+ setBasename("");
});
it("does a full-page redirect for a relative backend-only path", async () => {
@@ -211,6 +213,66 @@ describe("route-guards", () => {
});
expect(history?.getCurrentLocation().pathname).toBe("/auth/login");
});
+
+ describe("when Metabase is hosted under a subpath (GIT-10551)", () => {
+ beforeEach(() => {
+ setBasename("/metabase");
+ });
+
+ it("prefixes the subpath on a full-page redirect to a backend-only path", async () => {
+ const { history } = setup("/oauth/authorize?client_id=abc");
+
+ await waitFor(() => {
+ expect(replaceLocationMock).toHaveBeenCalledWith(
+ `${ORIGIN}/metabase/oauth/authorize?client_id=abc`,
+ );
+ });
+ expect(history?.getCurrentLocation().pathname).toBe("/auth/login");
+ });
+
+ it("does not double the subpath when navigating in-app", async () => {
+ const { history } = setup("/dashboard/1");
+
+ await waitFor(() => {
+ expect(history?.getCurrentLocation().pathname).toBe("/dashboard/1");
+ });
+ expect(replaceLocationMock).not.toHaveBeenCalled();
+ });
+
+ it("recognizes a backend-only path behind the subpath in an absolute URL", async () => {
+ const { history } = setup(`${ORIGIN}/metabase/oauth/authorize`);
+
+ await waitFor(() => {
+ expect(replaceLocationMock).toHaveBeenCalledWith(
+ `${ORIGIN}/metabase/oauth/authorize`,
+ );
+ });
+ expect(history?.getCurrentLocation().pathname).toBe("/auth/login");
+ });
+
+ it("does not strip a lookalike path prefix that is not the basename", async () => {
+ const { history } = setup(`${ORIGIN}/metabase-docs/foo`);
+
+ await waitFor(() => {
+ expect(history?.getCurrentLocation().pathname).toBe(
+ "/metabase-docs/foo",
+ );
+ });
+ expect(replaceLocationMock).not.toHaveBeenCalled();
+ });
+
+ it("handles a nested subpath basename", async () => {
+ setBasename("/bi/metabase");
+ const { history } = setup("/oauth/authorize?client_id=abc");
+
+ await waitFor(() => {
+ expect(replaceLocationMock).toHaveBeenCalledWith(
+ `${ORIGIN}/bi/metabase/oauth/authorize?client_id=abc`,
+ );
+ });
+ expect(history?.getCurrentLocation().pathname).toBe("/auth/login");
+ });
+ });
});
describe("isBackendOnlyPath", () => {
diff --git a/src/metabase/oauth_server/api/oauth.clj b/src/metabase/oauth_server/api/oauth.clj
index 8fcd2b674c9..b25e96f42f8 100644
--- a/src/metabase/oauth_server/api/oauth.clj
+++ b/src/metabase/oauth_server/api/oauth.clj
@@ -23,7 +23,7 @@
[throttle.core :as throttle])
(:import
(clojure.lang ExceptionInfo)
- (java.net URLEncoder)))
+ (java.net URI URLEncoder)))
(set! *warn-on-reflection* true)
@@ -34,12 +34,22 @@
[]
(codecs/bytes->hex (nonce/random-bytes 16)))
+(defn- site-path-prefix
+ "Path component of site-url with no trailing slash (e.g. `/metabase` when Metabase is hosted
+ under a subpath), or an empty string when site-url has no path or is unset."
+ []
+ (or (some-> (system/site-url) (URI.) (.getPath) (str/replace #"/$" "") not-empty)
+ ""))
+
(defn- csrf-cookie-opts
- "Cookie options for the CSRF cookie. Sets `:secure` when site-url is HTTPS."
+ "Cookie options for the CSRF cookie. Sets `:secure` when site-url is HTTPS.
+ The cookie `:path` is the path the *browser* sees, so it must include the subpath prefix
+ when Metabase is hosted under one — otherwise the cookie is never sent back with the
+ consent form POST and CSRF validation fails."
[max-age]
(cond-> {:http-only true
:same-site :strict
- :path "/oauth/authorize"
+ :path (str (site-path-prefix) "/oauth/authorize")
:max-age max-age}
(some-> (system/site-url) (str/starts-with? "https"))
(assoc :secure true)))
diff --git a/src/metabase/oauth_server/consent_page.clj b/src/metabase/oauth_server/consent_page.clj
index c489a31dec3..c1e7fe3ec2e 100644
--- a/src/metabase/oauth_server/consent_page.clj
+++ b/src/metabase/oauth_server/consent_page.clj
@@ -32,16 +32,17 @@
[font-name]
(let [dir-name (str/replace font-name " " "_")
file-stem (str/replace font-name " " "")
- css-font-name (css-escape-font-name font-name)]
+ css-font-name (css-escape-font-name font-name)
+ fonts-url (absolute-url "/app/fonts")]
(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"
+ " src: url('" fonts-url "/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")
+ " src: url('" fonts-url "/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"
+ " src: url('" fonts-url "/" 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"))))
+ " src: url('" fonts-url "/" dir-name "/" file-stem "-Bold.woff2') format('woff2'); }\n"))))
(def ^:private default-logo-url "app/assets/img/logo.svg")
@@ -168,7 +169,9 @@
(render-scope-list scopes)
(when-let [redirect-host (some-> (:redirect_uri oauth-params) not-empty (java.net.URI.) (.getHost))]
[:p.destination "Redirects to " [:strong redirect-host]])
- [:form {:method "POST" :action "/oauth/authorize/decision"}
+ ;; Absolute action: a root-relative path would drop the subpath when Metabase is hosted
+ ;; under one (site-url like https://example.com/metabase).
+ [:form {:method "POST" :action (absolute-url "/oauth/authorize/decision")}
[:input {:type "hidden" :name "csrf_token" :value csrf-token}]
[:input {:type "hidden" :name "params_sig" :value params-sig}]
(for [[k v] oauth-params
diff --git a/test/metabase/oauth_server/api_test.clj b/test/metabase/oauth_server/api_test.clj
index ebc2a10476c..f9ff7ba4111 100644
--- a/test/metabase/oauth_server/api_test.clj
+++ b/test/metabase/oauth_server/api_test.clj
@@ -2,6 +2,7 @@
(:require
[clojure.string :as str]
[clojure.test :refer [deftest is testing use-fixtures]]
+ [metabase.oauth-server.api.oauth :as api.oauth]
[metabase.oauth-server.core :as oauth-server]
[metabase.test :as mt]
[metabase.test.http-client :as client]
@@ -408,6 +409,84 @@
(is (str/includes? location "error=access_denied"))
(is (str/includes? location "state=test-state")))))))
+;;; -------------------------------------- Subpath hosting (GIT-10551) ---------------------------------------------
+
+;; Metabase doesn't officially support being hosted under a subpath, but the OAuth consent flow is entirely
+;; driven by site-url, so these tests pin the parts of the flow the *browser* sees — the consent form action,
+;; the CSRF cookie path, and the login redirect — to subpath-aware values. The server never sees the subpath
+;; (the reverse proxy strips it), so the routes themselves are unchanged.
+
+(defn- extract-csrf-cookie-path
+ "Extract the Path attribute of the CSRF cookie from the response.
+ Checks both the :cookies map and the Set-Cookie header (which may be a string or vector of strings)."
+ [response]
+ (or (get-in response [:cookies "metabase.OAUTH_CSRF" :path])
+ (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 (and (string? %) (str/includes? % "metabase.OAUTH_CSRF="))
+ (second (re-find #"Path=([^;]+)" %)))
+ cookies))))
+
+(deftest csrf-cookie-path-follows-site-url-test
+ (doseq [[site-url expected-path] {"http://localhost:3000" "/oauth/authorize"
+ "http://localhost:3000/metabase" "/metabase/oauth/authorize"
+ "http://localhost:3000/metabase/" "/metabase/oauth/authorize"
+ "http://localhost:3000/bi/metabase" "/bi/metabase/oauth/authorize"}]
+ (testing (str "site-url " site-url)
+ (mt/with-temporary-setting-values [site-url site-url]
+ (is (= expected-path (:path (#'api.oauth/csrf-cookie-opts 600))))))))
+
+(deftest subpath-consent-flow-test
+ (mt/with-temporary-setting-values [site-url "http://localhost:3000/metabase"]
+ (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)
+ consent-body (:body consent-resp)]
+ (testing "the consent form posts to the absolute, subpath-prefixed decision URL"
+ (is (str/includes? consent-body
+ "action=\"http://localhost:3000/metabase/oauth/authorize/decision\"")))
+ (testing "the CSRF cookie path includes the subpath so the browser sends the cookie with the form POST"
+ (is (= "/metabase/oauth/authorize" (extract-csrf-cookie-path consent-resp))))
+ (testing "the consent -> decision flow still round-trips"
+ (let [csrf-token (extract-csrf-token-from-consent consent-body)
+ csrf-cookie (extract-csrf-cookie consent-resp)
+ params-sig (extract-params-sig-from-consent consent-body)
+ response (form-post-decision!
+ :crowberto
+ {:approved "true"
+ :csrf_token csrf-token
+ :params_sig params-sig
+ :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 (str/starts-with? location "https://example.com/callback?"))
+ (is (str/includes? location "code="))
+ (testing "the decision response clears the CSRF cookie at the same subpath-prefixed path
+ (a clear at a different path would leave the old cookie shadowing the next flow)"
+ (is (= "/metabase/oauth/authorize" (extract-csrf-cookie-path response))))))))))
+
+(deftest subpath-login-redirect-test
+ (testing "unauthenticated GET /oauth/authorize under a subpath"
+ (mt/with-temporary-setting-values [site-url "http://localhost:3000/metabase"]
+ (let [response (client/client-full-response :get 302 "oauth/authorize"
+ :client_id "some-client"
+ :redirect_uri "https://example.com/callback"
+ :response_type "code")
+ location (get-in response [:headers "Location"])]
+ (testing "the login page URL carries the subpath"
+ (is (str/starts-with? location "http://localhost:3000/metabase/auth/login?redirect=")))
+ (testing "the redirect param stays basename-relative — the SPA router re-adds the subpath"
+ (is (str/includes? location (str "redirect=" (URLEncoder/encode "/oauth/authorize" "UTF-8")))))))))
+
(defn- approve-or-deny!
"Drive the consent + decision flow for `client-id` and return the decision response.
`approved?` chooses approve vs deny."
diff --git a/test/metabase/oauth_server/consent_page_test.clj b/test/metabase/oauth_server/consent_page_test.clj
index 0645aa84c5a..cb65ad1bac7 100644
--- a/test/metabase/oauth_server/consent_page_test.clj
+++ b/test/metabase/oauth_server/consent_page_test.clj
@@ -77,6 +77,21 @@
(is (re-find #"http://localhost:3000/app/assets/img/custom\.png" html)
"relative path should be resolved to absolute URL")))))
+(deftest consent-page-subpath-form-action-test
+ (testing "form action is absolute so it survives hosting under a subpath (GIT-10551)"
+ (let [html (mt/with-temporary-setting-values [site-url "https://example.com/metabase"]
+ (consent-page/render-consent-page
+ {:client-name "Test App"
+ :oauth-params {:response_type "code" :client_id "abc123"}
+ :nonce "test-nonce"
+ :csrf-token "test-csrf"}))]
+ (is (re-find #"action=\"https://example\.com/metabase/oauth/authorize/decision\"" html))
+ (testing "bundled fonts are also loaded from under the subpath"
+ (is (re-find #"url\('https://example\.com/metabase/app/fonts/" html)))))
+ (testing "at the domain root the action still targets /oauth/authorize/decision"
+ (let [html (render!)]
+ (is (re-find #"action=\"http://localhost:3000/oauth/authorize/decision\"" html)))))
+
(defn- render-with-scopes! [scopes]
(mt/with-temporary-setting-values [site-url "http://localhost:3000"]
(consent-page/render-consent-page