Skip to content

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

Make all API client request middleware declared statically (#75779)

Romeo Van Snick6269865946ec
diff --git a/enterprise/frontend/src/embedding-sdk-ee/auth/auth.ts b/enterprise/frontend/src/embedding-sdk-ee/auth/auth.ts
index 44edf722073..94d3ac48c65 100644
--- a/enterprise/frontend/src/embedding-sdk-ee/auth/auth.ts
+++ b/enterprise/frontend/src/embedding-sdk-ee/auth/auth.ts
@@ -28,8 +28,11 @@ import { getSdkPackageVersion } from "embedding-sdk-shared/lib/get-build-info";
import { getWindow } from "embedding-sdk-shared/lib/get-window";
import type { SdkAuthState } from "embedding-sdk-shared/types/auth-state";
import { SDK_AUTH_STATE_KEY } from "embedding-sdk-shared/types/auth-state";
-import { api } from "metabase/api/client";
import { requestSessionTokenFromEmbedJs } from "metabase/embedding/embedding-iframe-sdk/utils";
+import {
+ sessionTokenHeaders,
+ setApiKeyHeader,
+} from "metabase/embedding/lib/embedding-request-auth";
import {
EMBEDDING_SDK_IFRAME_EMBEDDING_CONFIG,
isEmbeddingEajs,
@@ -37,7 +40,7 @@ import {
} from "metabase/embedding-sdk/config";
import { samlTokenStorage } from "metabase/embedding-sdk/lib/saml-token-storage";
import type { MetabaseEmbeddingSessionToken } from "metabase/embedding-sdk/types/refresh-token";
-import { PLUGIN_EMBEDDING_SDK } from "metabase/plugins";
+import { PLUGIN_API, PLUGIN_EMBEDDING_SDK } from "metabase/plugins";
import { loadSettings, refreshSiteSettings } from "metabase/redux/settings";
import { refreshCurrentUser } from "metabase/redux/user";
import { createAsyncThunk } from "metabase/redux/utils";
@@ -65,6 +68,15 @@ PLUGIN_EMBEDDING_SDK_AUTH.initAuth = async (
// remove any stale tokens that might be there from a previous session
samlTokenStorage.remove();
+ // Resolve the SSO session token (refreshing it when expired) and emit it as
+ // the X-Metabase-Session header. This runs on the refresh-handler slot, which
+ // is ordered after the static auth-header slot, so a freshly refreshed token
+ // applies to the very request that triggered the refresh.
+ const sessionTokenHandler = async () => {
+ const session = await dispatch(getOrRefreshSession(authConfig)).unwrap();
+ return session?.id ? sessionTokenHeaders(session.id) : undefined;
+ };
+
// Check if we can use the auth pre-fetched by the bootstrap chunk
const earlyAuthStatus = getAuthState()?.status;
if (earlyAuthStatus && earlyAuthStatus !== "skipped") {
@@ -84,7 +96,6 @@ PLUGIN_EMBEDDING_SDK_AUTH.initAuth = async (
authState.user &&
authState.siteSettings
) {
- api.sessionToken = authState.session.id;
// Store the session token in Redux so getOrRefreshSession finds it
// and doesn't trigger a redundant token refresh on the first API call.
dispatch(
@@ -96,16 +107,10 @@ PLUGIN_EMBEDDING_SDK_AUTH.initAuth = async (
dispatch(loadSettings(authState.siteSettings as Settings));
MetabaseSettings.setAll(authState.siteSettings as Settings);
- // Set up the refresh handler so API calls can renew the token later.
+ // The session handler emits the X-Metabase-Session header on every API
+ // call, renewing the token when it expires.
PLUGIN_EMBEDDING_SDK.onBeforeRequestHandlers.getOrRefreshSessionHandler =
- async () => {
- const session = await dispatch(
- getOrRefreshSession(authConfig),
- ).unwrap();
- if (session?.id) {
- api.sessionToken = session.id;
- }
- };
+ sessionTokenHandler;
return;
}
@@ -126,23 +131,20 @@ PLUGIN_EMBEDDING_SDK_AUTH.initAuth = async (
if (isValidApiKeyConfig) {
// API key setup
- api.apiKey = apiKey;
+ PLUGIN_API.onBeforeRequestHandlers.setEmbeddingRequestAuthHeaders =
+ setApiKeyHeader(apiKey);
} else if (EMBEDDING_SDK_IFRAME_EMBEDDING_CONFIG.useExistingUserSession) {
// Use existing user session. Do nothing.
} else if (isValidInstanceUrl) {
- // SSO setup
+ // SSO setup. The session handler sets the X-Metabase-Session header on every
+ // request and refreshes the token when it expires; later API calls pick it
+ // up because the handler runs in the request pipeline. Call it once eagerly
+ // to verify the session is valid before the app renders.
PLUGIN_EMBEDDING_SDK.onBeforeRequestHandlers.getOrRefreshSessionHandler =
- async () => {
- const session = await dispatch(
- getOrRefreshSession(authConfig),
- ).unwrap();
- if (session?.id) {
- api.sessionToken = session.id;
- }
- };
+ sessionTokenHandler;
try {
// verify that the session is actually valid before proceeding
- await dispatch(getOrRefreshSession(authConfig)).unwrap();
+ await sessionTokenHandler();
} catch (e) {
// TODO (Oisin 2025-05-27): Fix this. For some reason the instanceof check keeps returning `false`. I'd rather not do this
// but due to time constraints this is what we have to do to make sure tests pass.
diff --git a/enterprise/frontend/src/embedding-sdk-ee/tests/auth-flow/jwt.unit.spec.tsx b/enterprise/frontend/src/embedding-sdk-ee/tests/auth-flow/jwt.unit.spec.tsx
index 7ee49f66882..e8b1a74dd58 100644
--- a/enterprise/frontend/src/embedding-sdk-ee/tests/auth-flow/jwt.unit.spec.tsx
+++ b/enterprise/frontend/src/embedding-sdk-ee/tests/auth-flow/jwt.unit.spec.tsx
@@ -208,11 +208,15 @@ describe("Auth Flow - JWT", () => {
fetchRequestToken: customFetchFunction,
});
- setup({ authConfig });
+ const { getLastUserApiCall } = setup({ authConfig });
expect(
screen.queryByTestId("sdk-usage-problem-indicator"),
).not.toBeInTheDocument();
+
+ // Let the auth flow settle so its in-flight requests don't leak into the
+ // next test (the strict afterEach fails on unmocked routes).
+ await waitForRequest(() => getLastUserApiCall());
});
it("should include the subpath when requesting the SSO endpoint", async () => {
diff --git a/frontend/src/embedding-sdk-bundle/hooks/private/use-init-data/use-init-data-internal.ts b/frontend/src/embedding-sdk-bundle/hooks/private/use-init-data/use-init-data-internal.ts
index 1257abed717..18ad60f1db4 100644
--- a/frontend/src/embedding-sdk-bundle/hooks/private/use-init-data/use-init-data-internal.ts
+++ b/frontend/src/embedding-sdk-bundle/hooks/private/use-init-data/use-init-data-internal.ts
@@ -16,18 +16,26 @@ import { useLazySelector } from "embedding-sdk-shared/hooks/use-lazy-selector";
import { useMetabaseProviderPropsStore } from "embedding-sdk-shared/hooks/use-metabase-provider-props-store";
import { ensureMetabaseProviderPropsStore } from "embedding-sdk-shared/lib/ensure-metabase-provider-props-store";
import { getSdkPackageVersion } from "embedding-sdk-shared/lib/get-build-info";
-import { api } from "metabase/api/client";
+import {
+ type OnBeforeRequestHandler,
+ type RequestClientInfo,
+ api,
+} from "metabase/api/client";
import registerDashboardVisualizations from "metabase/dashboard/visualizations/register";
+import {
+ setEmbedPreviewHeader,
+ setRequestClientHeaders,
+} from "metabase/embedding/lib/embedding-request-auth";
import {
EMBEDDING_SDK_CONFIG,
isEmbeddingEajs,
} from "metabase/embedding-sdk/config";
-import type { OnBeforeRequestHandlerConfig } from "metabase/plugins/oss/api";
+import { PLUGIN_API, PLUGIN_EMBEDDING_SDK } from "metabase/plugins";
import registerVisualizations from "metabase/visualizations/register";
-const reactSdkEmbedReferrerHandler = async (
- config: OnBeforeRequestHandlerConfig,
-): Promise<OnBeforeRequestHandlerConfig | void> => ({
+const reactSdkEmbedReferrerHandler: OnBeforeRequestHandler = async (
+ config,
+) => ({
...config,
headers: {
...config.headers,
@@ -57,6 +65,17 @@ const registerDashboardVisualizationsOnce = _.once(
registerDashboardVisualizations,
);
+// Install the SDK's request-client header strategy once; re-renders keep the
+// first-set client (matching the previous set-once-if-unset behaviour).
+const setSdkRequestClientHeadersOnce = _.once(
+ (requestClient: RequestClientInfo) => {
+ PLUGIN_API.onBeforeRequestHandlers.setRequestClientHeaders =
+ setRequestClientHeaders(requestClient);
+ PLUGIN_API.onBeforeRequestHandlers.setEmbedPreviewHeader =
+ setEmbedPreviewHeader;
+ },
+);
+
interface InitDataLoaderParameters {
reduxStore: SdkStore;
isGuestEmbed?: boolean;
@@ -107,27 +126,22 @@ export const useInitDataInternal = ({
api.basename = authConfig.metabaseInstanceUrl;
}
- if (!api.requestClient) {
- api.requestClient = {
- name: EMBEDDING_SDK_CONFIG.metabaseClientRequestHeader,
- // Note: this is *package* version, it's undefined in EAJS
- version: sdkPackageVersion,
- };
- }
+ setSdkRequestClientHeadersOnce({
+ name: EMBEDDING_SDK_CONFIG.metabaseClientRequestHeader,
+ // Note: this is *package* version, it's undefined in EAJS
+ version: sdkPackageVersion,
+ });
// For the React SDK, send the host page URL as the embed referrer in a
- // header on every request. The EAJS iframe registers its own handler in
+ // header on every request. The EAJS iframe installs its own handler in
// SdkIframeEmbedRoute.tsx using the value received via postMessage.
- if (
- !isEmbeddingEajs() &&
- !api.beforeRequestHandlers.includes(reactSdkEmbedReferrerHandler)
- ) {
- api.beforeRequestHandlers.push(reactSdkEmbedReferrerHandler);
+ if (!isEmbeddingEajs()) {
+ PLUGIN_EMBEDDING_SDK.onBeforeRequestHandlers.reactSdkEmbedReferrer =
+ reactSdkEmbedReferrerHandler;
}
- // Dedupe by handler identity (matches the `beforeRequestHandlers` pattern
- // above) rather than total listener count — other code can register its own
- // `responseError` listeners without disabling ours.
+ // Dedupe by handler identity rather than total listener count — other code
+ // can register its own `responseError` listeners without disabling ours.
if (!api.listeners("responseError").includes(sdkResponseErrorHandler)) {
api.on("responseError", sdkResponseErrorHandler);
}
diff --git a/frontend/src/embedding-sdk-bundle/store/guest-embed/guest-embed.ts b/frontend/src/embedding-sdk-bundle/store/guest-embed/guest-embed.ts
index abdbb3725e1..3685bc33208 100644
--- a/frontend/src/embedding-sdk-bundle/store/guest-embed/guest-embed.ts
+++ b/frontend/src/embedding-sdk-bundle/store/guest-embed/guest-embed.ts
@@ -1,9 +1,9 @@
import { merge } from "icepick";
import type { MetabaseAuthConfig } from "embedding-sdk-bundle/types/auth-config";
+import type { OnBeforeRequestHandlerConfig } from "metabase/api/client";
import { overrideRequestsForGuestEmbeds } from "metabase/embedding/lib/override-requests-for-embeds";
import { PLUGIN_EMBEDDING_SDK } from "metabase/plugins";
-import type { OnBeforeRequestHandlerConfig } from "metabase/plugins/oss/api";
import { refreshSiteSettings } from "metabase/redux/settings";
import { createAsyncThunk } from "metabase/redux/utils";
import { isJWT } from "metabase/utils/jwt";
diff --git a/frontend/src/metabase-types/api/card.ts b/frontend/src/metabase-types/api/card.ts
index a83d8ac8950..cdd0ac56c89 100644
--- a/frontend/src/metabase-types/api/card.ts
+++ b/frontend/src/metabase-types/api/card.ts
@@ -526,9 +526,9 @@ export type GetPublicCard = Pick<Card, "id" | "name" | "public_uuid">;
export type GetEmbeddableCard = Pick<Card, "id" | "name">;
export type GetRemappedCardParameterValueRequest = {
- card_id?: CardId | EntityToken;
- entityIdentifier?: EntityUuid | EntityToken;
- parameter_id: ParameterId;
+ cardId?: CardId | EntityToken;
+ entityIdentifier?: EntityUuid | EntityToken | null;
+ paramId: ParameterId;
value: ParameterValueOrArray;
};
diff --git a/frontend/src/metabase-types/api/dashboard.ts b/frontend/src/metabase-types/api/dashboard.ts
index 2b99ba40453..6fdde167959 100644
--- a/frontend/src/metabase-types/api/dashboard.ts
+++ b/frontend/src/metabase-types/api/dashboard.ts
@@ -386,9 +386,9 @@ export type GetPublicDashboard = Pick<Dashboard, "id" | "name" | "public_uuid">;
export type GetEmbeddableDashboard = Pick<Dashboard, "id" | "name">;
export type GetRemappedDashboardParameterValueRequest = {
- dashboard_id?: DashboardId;
- entityIdentifier?: EntityUuid | EntityToken;
- parameter_id: ParameterId;
+ dashId?: DashboardId;
+ entityIdentifier?: EntityUuid | EntityToken | null;
+ paramId: ParameterId;
value: ParameterValueOrArray;
};
diff --git a/frontend/src/metabase/api/card.ts b/frontend/src/metabase/api/card.ts
index a668bfb5856..0185f14cb37 100644
--- a/frontend/src/metabase/api/card.ts
+++ b/frontend/src/metabase/api/card.ts
@@ -1,4 +1,3 @@
-import { PLUGIN_API } from "metabase/plugins";
import { QueryMetadataSchema, QuestionSchema } from "metabase/schema";
import type {
Card,
@@ -153,16 +152,17 @@ export const cardApi = Api.injectEndpoints({
FieldValue,
GetRemappedCardParameterValueRequest
>({
- query: ({ card_id, parameter_id, ...params }) => ({
+ query: ({ entityIdentifier, ...params }) => ({
method: "GET",
- url: PLUGIN_API.getRemappedCardParameterValueUrl(
- card_id,
- parameter_id,
- ),
- params,
+ url: "/api/card/:cardId/params/:paramId/remapping",
+ // In an embed the override rewrites `:cardId` → `:entityIdentifier` and
+ // drops the real `cardId` from the params (see
+ // override-requests-for-embeds); a null `entityIdentifier` is omitted
+ // so it never reaches the querystring.
+ params: { ...params, ...(entityIdentifier && { entityIdentifier }) },
}),
- providesTags: (_response, _error, { parameter_id }) =>
- provideParameterValuesTags(parameter_id),
+ providesTags: (_response, _error, { paramId }) =>
+ provideParameterValuesTags(paramId),
}),
createCard: builder.mutation<Card, CreateCardRequest>({
query: (body) => ({
diff --git a/frontend/src/metabase/api/client/client.ts b/frontend/src/metabase/api/client/client.ts
index 75d7deea268..842665add14 100644
--- a/frontend/src/metabase/api/client/client.ts
+++ b/frontend/src/metabase/api/client/client.ts
@@ -1,12 +1,6 @@
/* eslint-disable metabase/no-literal-metabase-strings */
import EventEmitter from "events";
-import { isEmbeddingSdk } from "metabase/embedding-sdk/config";
-import type {
- OnBeforeRequestHandler,
- OnBeforeRequestHandlerConfig,
-} from "metabase/plugins/oss/api";
-import { IFRAMED_IN_SELF, isWithinIframe } from "metabase/utils/iframe";
import { getTraceparentHeader } from "metabase/utils/otel";
import { retry } from "metabase/utils/retry";
@@ -14,10 +8,12 @@ import { addAntiCsrfToken, updateAntiCsrfToken } from "./csrf";
import { NetworkError, isRetriableError } from "./errors";
import { getLocaleHeader } from "./locale";
import { type RequestMethod, isRequestMethod } from "./method";
-import { apiRequestManipulationMiddleware } from "./middleware";
+import {
+ type OnBeforeRequestHandlerConfig,
+ apiRequestManipulationMiddleware,
+} from "./middleware";
import type {
EventMap,
- RequestClientInfo,
RequestInit,
RequestOptions,
ResponseFor,
@@ -33,11 +29,6 @@ const MAX_RETRIES = 10;
export class ApiClient extends EventEmitter<EventMap> {
basename = "";
- apiKey = "";
- sessionToken: string | undefined;
- requestClient: RequestClientInfo | undefined;
-
- beforeRequestHandlers: OnBeforeRequestHandler[] = [];
private buildUrl(
template: string,
@@ -56,32 +47,6 @@ export class ApiClient extends EventEmitter<EventMap> {
"Content-Type": "application/json",
};
- if (this.apiKey) {
- headers["X-Api-Key"] = this.apiKey;
- }
-
- if (this.sessionToken) {
- headers["X-Metabase-Session"] = this.sessionToken;
- }
-
- if (isWithinIframe() && !isEmbeddingSdk()) {
- headers["X-Metabase-Embedded"] = "true";
- }
-
- if (this.requestClient) {
- if (IFRAMED_IN_SELF) {
- headers["X-Metabase-Embedded-Preview"] = "true";
- }
- if (typeof this.requestClient === "object") {
- headers["X-Metabase-Client"] = this.requestClient.name;
- if (this.requestClient.version) {
- headers["X-Metabase-Client-Version"] = this.requestClient.version;
- }
- } else {
- headers["X-Metabase-Client"] = this.requestClient;
- }
- }
-
const locale = getLocaleHeader();
if (locale) {
headers["X-Metabase-Locale"] = locale;
@@ -99,20 +64,17 @@ export class ApiClient extends EventEmitter<EventMap> {
}
private async _resolveOptions(options: OnBeforeRequestHandlerConfig) {
- const middlewareResult = await apiRequestManipulationMiddleware(
- this.beforeRequestHandlers,
- {
- ...options,
- // `headers` is optional on the public API, but handlers may merge into
- // it, so always hand the pipeline a real object to spread into.
- headers: options.headers ?? {},
- // This will transform arrays to objects with numeric keys
- // we shouldn't be using top level-arrays in the API.
- // Both bags are defensively copied so middleware can safely mutate them.
- data: { ...options.data },
- body: options.body ? { ...options.body } : undefined,
- },
- );
+ const middlewareResult = await apiRequestManipulationMiddleware({
+ ...options,
+ // `headers` is optional on the public API, but handlers may merge into
+ // it, so always hand the pipeline a real object to spread into.
+ headers: options.headers ?? {},
+ // This will transform arrays to objects with numeric keys
+ // we shouldn't be using top level-arrays in the API.
+ // Both bags are defensively copied so middleware can safely mutate them.
+ data: { ...options.data },
+ body: options.body ? { ...options.body } : undefined,
+ });
return {
...middlewareResult,
diff --git a/frontend/src/metabase/api/client/client.unit.spec.ts b/frontend/src/metabase/api/client/client.unit.spec.ts
index b562b705e4a..822091218da 100644
--- a/frontend/src/metabase/api/client/client.unit.spec.ts
+++ b/frontend/src/metabase/api/client/client.unit.spec.ts
@@ -1,5 +1,7 @@
import fetchMock from "fetch-mock";
+import { PLUGIN_API, reinitialize } from "metabase/plugins";
+
import { ApiClient } from "./client";
describe("api", () => {
@@ -12,6 +14,8 @@ describe("api", () => {
afterEach(() => {
fetchMock.removeRoutes().clearHistory();
+ // Reset any plugin request handlers installed by a test.
+ reinitialize();
});
it("substitutes :tag URL placeholders from `params`", async () => {
@@ -145,16 +149,17 @@ describe("api", () => {
// from the body field — not just from URL params.
fetchMock.get("path:/api/embed/card/SOME_JWT/query", { rows: [] });
- apiInstance.beforeRequestHandlers.push(async (config) => {
- if (config.url === "/api/card/:cardId/query") {
- return {
- ...config,
- method: "GET" as const,
- url: "/api/embed/card/:token/query",
- };
- }
- return config;
- });
+ PLUGIN_API.onBeforeRequestHandlers.overrideRequestsForPublicEmbeds =
+ async (config) => {
+ if (config.url === "/api/card/:cardId/query") {
+ return {
+ ...config,
+ method: "GET" as const,
+ url: "/api/embed/card/:token/query",
+ };
+ }
+ return config;
+ };
await apiInstance.request({
method: "POST",
@@ -171,19 +176,20 @@ describe("api", () => {
expect(call?.options?.body).toBeFalsy();
});
- it("omits params with undefined values from the querystring", async () => {
+ it("omits params with null/undefined values from the querystring", async () => {
fetchMock.get("path:/api/search", { items: [] });
await apiInstance.request({
method: "GET",
url: "/api/search",
- params: { q: "foo", limit: undefined, offset: 0 },
+ params: { q: "foo", limit: undefined, cursor: null, offset: 0 },
});
const call = fetchMock.callHistory.lastCall();
expect(call?.url).toContain("q=foo");
expect(call?.url).toContain("offset=0");
expect(call?.url).not.toContain("limit");
+ expect(call?.url).not.toContain("cursor");
});
});
diff --git a/frontend/src/metabase/api/client/index.ts b/frontend/src/metabase/api/client/index.ts
index cb3d022fa03..8caf31a66a6 100644
--- a/frontend/src/metabase/api/client/index.ts
+++ b/frontend/src/metabase/api/client/index.ts
@@ -1,5 +1,9 @@
export * from "./client";
export * from "./method";
export * from "./errors";
-export type { RequestOptions } from "./types";
+export type {
+ OnBeforeRequestHandler,
+ OnBeforeRequestHandlerConfig,
+} from "./middleware";
+export type { RequestClientInfo, RequestOptions } from "./types";
export { setLocaleHeader } from "./locale";
diff --git a/frontend/src/metabase/api/client/middleware.ts b/frontend/src/metabase/api/client/middleware.ts
index fa65a8da1b1..c2bc22dfd4e 100644
--- a/frontend/src/metabase/api/client/middleware.ts
+++ b/frontend/src/metabase/api/client/middleware.ts
@@ -1,25 +1,75 @@
-import { PLUGIN_API, PLUGIN_EMBEDDING_SDK } from "metabase/plugins";
-import type {
- OnBeforeRequestHandler,
- OnBeforeRequestHandlerConfig,
-} from "metabase/plugins/oss/api";
+import {
+ PLUGIN_API,
+ PLUGIN_EMBEDDING_IFRAME_SDK,
+ PLUGIN_EMBEDDING_SDK,
+} from "metabase/plugins";
-export async function apiRequestManipulationMiddleware(
- beforeRequestHandlers: OnBeforeRequestHandler[],
- requestConfig: OnBeforeRequestHandlerConfig,
-): Promise<OnBeforeRequestHandlerConfig> {
- // Handlers order is important.
- // Handlers are executed in order and each handler uses the data returned by a previous handler.
- const handlers = [
+import type { RequestMethod } from "./method";
+
+export type OnBeforeRequestHandlerConfig = {
+ method: RequestMethod;
+ url: string;
+ headers?: Record<string, string>;
+ // URL `:tag` params (and querystring leftovers). For the legacy GET/POST
+ // helpers this holds the whole request bag.
+ data: Record<string, unknown>;
+ // The JSON-body bag, kept as a separate channel from `data`. Exposed to
+ // handlers so embed URL `:tag`s — notably the guest-embed `:token` — can be
+ // filled from body fields, and so the refresh handler can swap a stale body
+ // token. `undefined` for GETs, raw (FormData/URLSearchParams) bodies, and the
+ // legacy helpers (which pack everything into `data`).
+ body?: Record<string, unknown>;
+};
+
+export type OnBeforeRequestHandler = (
+ data: OnBeforeRequestHandlerConfig,
+) => Promise<void | Partial<OnBeforeRequestHandlerConfig>>;
+
+/**
+ * The complete, ordered request-manipulation pipeline.
+ *
+ * Every handler is a plugin slot — a no-op by default, populated by the owning
+ * feature's init flow (SDK auth, guest/public/static embeds, the embed-referrer
+ * handlers). Listing them here, rather than letting features push handlers onto
+ * a dynamic array, keeps the full set of things that can rewrite an outgoing
+ * request — and the order they run in — visible in one place.
+ *
+ * Order matters: handlers run in sequence and each one sees the result of the
+ * previous one. In particular the embed-preview rewrite must run after the
+ * embed overrides, which produce the `/api/embed/...` urls it rewrites.
+ */
+function getOnBeforeRequestHandlers(): OnBeforeRequestHandler[] {
+ return [
+ PLUGIN_API.onBeforeRequestHandlers.setRequestClientHeaders,
+ PLUGIN_API.onBeforeRequestHandlers.setEmbedPreviewHeader,
+ PLUGIN_API.onBeforeRequestHandlers.setEmbeddingRequestAuthHeaders,
+ PLUGIN_API.onBeforeRequestHandlers.setEmbeddedHeader,
PLUGIN_EMBEDDING_SDK.onBeforeRequestHandlers.getOrRefreshSessionHandler,
PLUGIN_EMBEDDING_SDK.onBeforeRequestHandlers
.getOrRefreshGuestSessionHandler,
PLUGIN_EMBEDDING_SDK.onBeforeRequestHandlers.overrideRequestsForGuestEmbeds,
PLUGIN_API.onBeforeRequestHandlers.overrideRequestsForPublicEmbeds,
- PLUGIN_API.onBeforeRequestHandlers.overrideRequestsForStaticEmbeds,
- ...beforeRequestHandlers,
+ PLUGIN_API.onBeforeRequestHandlers.rewriteEmbedPreviewUrl,
+ PLUGIN_EMBEDDING_SDK.onBeforeRequestHandlers.reactSdkEmbedReferrer,
+ PLUGIN_EMBEDDING_IFRAME_SDK.onBeforeRequestHandlers.embedReferrer,
];
+}
+export async function apiRequestManipulationMiddleware(
+ requestConfig: OnBeforeRequestHandlerConfig,
+): Promise<OnBeforeRequestHandlerConfig> {
+ return runBeforeRequestHandlers(getOnBeforeRequestHandlers(), requestConfig);
+}
+
+/**
+ * Run a list of handlers over the request config, in order, merging each
+ * handler's partial result into the running config. Exported so the
+ * merge/ordering semantics can be unit-tested with an explicit handler list.
+ */
+export async function runBeforeRequestHandlers(
+ handlers: OnBeforeRequestHandler[],
+ requestConfig: OnBeforeRequestHandlerConfig,
+): Promise<OnBeforeRequestHandlerConfig> {
let result = requestConfig;
for (const handler of handlers) {
const next = await handler(result);
diff --git a/frontend/src/metabase/api/client/middleware.unit.spec.ts b/frontend/src/metabase/api/client/middleware.unit.spec.ts
index e20a57b434d..60e686ca07a 100644
--- a/frontend/src/metabase/api/client/middleware.unit.spec.ts
+++ b/frontend/src/metabase/api/client/middleware.unit.spec.ts
@@ -1,8 +1,8 @@
-import type { OnBeforeRequestHandlerConfig } from "metabase/plugins/oss/api";
+import type { OnBeforeRequestHandlerConfig } from "metabase/api/client";
-import { apiRequestManipulationMiddleware } from "./middleware";
+import { runBeforeRequestHandlers } from "./middleware";
-describe("apiRequestManipulationMiddleware", () => {
+describe("runBeforeRequestHandlers", () => {
it("should return the original data when there are no handlers", async () => {
const inputData = {
method: "GET" as const,
@@ -11,7 +11,7 @@ describe("apiRequestManipulationMiddleware", () => {
data: {},
};
- const result = await apiRequestManipulationMiddleware([], inputData);
+ const result = await runBeforeRequestHandlers([], inputData);
expect(result).toEqual(inputData);
});
@@ -28,7 +28,7 @@ describe("apiRequestManipulationMiddleware", () => {
return;
});
- const result = await apiRequestManipulationMiddleware([handler], inputData);
+ const result = await runBeforeRequestHandlers([handler], inputData);
expect(result).toEqual(inputData);
expect(handler).toHaveBeenCalledWith(inputData);
@@ -51,7 +51,7 @@ describe("apiRequestManipulationMiddleware", () => {
};
});
- const result = await apiRequestManipulationMiddleware([handler], inputData);
+ const result = await runBeforeRequestHandlers([handler], inputData);
expect(result).toEqual({
...inputData,
@@ -77,7 +77,7 @@ describe("apiRequestManipulationMiddleware", () => {
return modifications;
});
- const result = await apiRequestManipulationMiddleware([handler], inputData);
+ const result = await runBeforeRequestHandlers([handler], inputData);
expect(result).toEqual({ ...inputData, ...modifications });
});
@@ -103,7 +103,7 @@ describe("apiRequestManipulationMiddleware", () => {
};
});
- const result = await apiRequestManipulationMiddleware([handler], inputData);
+ const result = await runBeforeRequestHandlers([handler], inputData);
expect(result.headers).toEqual({
"X-Original": "value",
@@ -148,7 +148,7 @@ describe("apiRequestManipulationMiddleware", () => {
};
});
- const result = await apiRequestManipulationMiddleware(
+ const result = await runBeforeRequestHandlers(
[handler1, handler2, handler3],
inputData,
);
@@ -181,7 +181,7 @@ describe("apiRequestManipulationMiddleware", () => {
};
});
- const result = await apiRequestManipulationMiddleware([handler], inputData);
+ const result = await runBeforeRequestHandlers([handler], inputData);
expect(result.url).toBe("/api/modified-url");
expect(result.headers).toEqual(inputData.headers);
diff --git a/frontend/src/metabase/api/client/types.ts b/frontend/src/metabase/api/client/types.ts
index fde712052fe..a8781fe2b66 100644
--- a/frontend/src/metabase/api/client/types.ts
+++ b/frontend/src/metabase/api/client/types.ts
@@ -22,9 +22,7 @@ export type ResponseFor<Raw extends boolean> = Raw extends true
? Response
: unknown;
-export type RequestClientInfo =
- | string
- | { name: string; version: string | null };
+export type RequestClientInfo = { name: string; version?: string | null };
export type ResponseErrorInfo = {
metabaseVersion: string | null;
diff --git a/frontend/src/metabase/api/client/utils.ts b/frontend/src/metabase/api/client/utils.ts
index 05abb396dcb..d9d105593f1 100644
--- a/frontend/src/metabase/api/client/utils.ts
+++ b/frontend/src/metabase/api/client/utils.ts
@@ -42,7 +42,9 @@ export function appendQueryParameters(
) {
for (const key in params) {
const value = params[key];
- if (value === undefined) {
+ // Skip nullish values so an absent param never becomes the literal string
+ // `"null"`/`"undefined"` in the querystring.
+ if (value == null) {
continue;
}
if (Array.isArray(value)) {
diff --git a/frontend/src/metabase/api/dashboard.ts b/frontend/src/metabase/api/dashboard.ts
index fb57518cdf1..405fdbbd3d1 100644
--- a/frontend/src/metabase/api/dashboard.ts
+++ b/frontend/src/metabase/api/dashboard.ts
@@ -1,4 +1,3 @@
-import { PLUGIN_API } from "metabase/plugins";
import { DashboardSchema, QueryMetadataSchema } from "metabase/schema";
import type {
CopyDashboardRequest,
@@ -144,16 +143,17 @@ export const dashboardApi = Api.injectEndpoints({
FieldValue,
GetRemappedDashboardParameterValueRequest
>({
- query: ({ dashboard_id, parameter_id, ...params }) => ({
+ query: ({ entityIdentifier, ...params }) => ({
method: "GET",
- url: PLUGIN_API.getRemappedDashboardParameterValueUrl(
- dashboard_id,
- parameter_id,
- ),
- params,
+ url: "/api/dashboard/:dashId/params/:paramId/remapping",
+ // In an embed the override rewrites `:dashId` → `:entityIdentifier` and
+ // drops the real `dashId` from the params (see
+ // override-requests-for-embeds); a null `entityIdentifier` is omitted
+ // so it never reaches the querystring.
+ params: { ...params, ...(entityIdentifier && { entityIdentifier }) },
}),
- providesTags: (_response, _error, { parameter_id }) =>
- provideParameterValuesTags(parameter_id),
+ providesTags: (_response, _error, { paramId }) =>
+ provideParameterValuesTags(paramId),
}),
getDashboardParameterValues: builder.query<
ParameterValues,
diff --git a/frontend/src/metabase/app-embed-mcp.tsx b/frontend/src/metabase/app-embed-mcp.tsx
index 1083fa53491..e312e526dde 100644
--- a/frontend/src/metabase/app-embed-mcp.tsx
+++ b/frontend/src/metabase/app-embed-mcp.tsx
@@ -8,8 +8,10 @@ import { createRoot } from "react-dom/client";
import "metabase/embedding-sdk/vendors-side-effects";
import { api } from "metabase/api/client";
+import { setSessionTokenHeader } from "metabase/embedding/lib/embedding-request-auth";
import { McpUiAppRoute } from "metabase/embedding/mcp/McpUiAppRoute";
import { EMBEDDING_SDK_CONFIG } from "metabase/embedding-sdk/config";
+import { PLUGIN_API } from "metabase/plugins";
// Load EE plugins (whitelabeling, etc.) - no-op in OSS
import "sdk-iframe-embedding-ee-plugins";
@@ -28,7 +30,8 @@ if (instanceUrl) {
}
if (sessionToken) {
- api.sessionToken = sessionToken;
+ PLUGIN_API.onBeforeRequestHandlers.setEmbeddingRequestAuthHeaders =
+ setSessionTokenHeader(sessionToken);
}
function init() {
diff --git a/frontend/src/metabase/app-main.js b/frontend/src/metabase/app-main.js
index 6dfa48aaeb5..b31da451d46 100644
--- a/frontend/src/metabase/app-main.js
+++ b/frontend/src/metabase/app-main.js
@@ -7,6 +7,8 @@ import _ from "underscore";
import { api } from "metabase/api/client";
import { init } from "metabase/app";
+import { setRequestClientHeaders } from "metabase/embedding/lib/embedding-request-auth";
+import { PLUGIN_API } from "metabase/plugins";
import { mainReducers } from "metabase/reducers-main";
import { setErrorPage } from "metabase/redux/app";
import { clearCurrentUser } from "metabase/redux/user";
@@ -27,7 +29,8 @@ const NOT_AUTHORIZED_TRIGGERS = [
* might want to use a flag too instead of just checking for being in an iframe.
*/
if (isWithinIframe() && !IFRAMED_IN_SELF) {
- api.requestClient = "embedding-iframe-full-app";
+ PLUGIN_API.onBeforeRequestHandlers.setRequestClientHeaders =
+ setRequestClientHeaders({ name: "embedding-iframe-full-app" });
}
init(mainReducers, getRoutes, (store) => {
diff --git a/frontend/src/metabase/embedding/config.ts b/frontend/src/metabase/embedding/config.ts
index 57c30516c6c..a12a9803cb8 100644
--- a/frontend/src/metabase/embedding/config.ts
+++ b/frontend/src/metabase/embedding/config.ts
@@ -1,5 +1,9 @@
-import { api } from "metabase/api/client";
+import {
+ setEmbedPreviewHeader,
+ setRequestClientHeaders,
+} from "metabase/embedding/lib/embedding-request-auth";
import { isEmbeddingSdk } from "metabase/embedding-sdk/config";
+import { PLUGIN_API } from "metabase/plugins";
import { IFRAMED_IN_SELF, isWithinIframe } from "metabase/utils/iframe";
type InternalEmbeddingConfig = {
@@ -13,7 +17,10 @@ const EMBEDDING_CONFIG: InternalEmbeddingConfig = {
};
export function setIsPublicEmbedding() {
- api.requestClient = "embedding-public";
+ PLUGIN_API.onBeforeRequestHandlers.setRequestClientHeaders =
+ setRequestClientHeaders({ name: "embedding-public" });
+ PLUGIN_API.onBeforeRequestHandlers.setEmbedPreviewHeader =
+ setEmbedPreviewHeader;
EMBEDDING_CONFIG.isPublicEmbedding = true;
}
@@ -25,7 +32,8 @@ export function setIsStaticEmbedding() {
* embedding iframe (only for Documents at the time of this comment)
*/
if (!isEmbedPreview()) {
- api.requestClient = "embedding-iframe-static";
+ PLUGIN_API.onBeforeRequestHandlers.setRequestClientHeaders =
+ setRequestClientHeaders({ name: "embedding-iframe-static" });
}
EMBEDDING_CONFIG.isStaticEmbedding = true;
}
diff --git a/frontend/src/metabase/embedding/embedding-iframe-sdk/components/SdkIframeEmbedRoute.tsx b/frontend/src/metabase/embedding/embedding-iframe-sdk/components/SdkIframeEmbedRoute.tsx
index 8600bd1137a..f4f94eff826 100644
--- a/frontend/src/metabase/embedding/embedding-iframe-sdk/components/SdkIframeEmbedRoute.tsx
+++ b/frontend/src/metabase/embedding/embedding-iframe-sdk/components/SdkIframeEmbedRoute.tsx
@@ -20,11 +20,10 @@ import type { SdkDashboardEntityPublicProps } from "embedding-sdk-bundle/types/d
import type { SdkQuestionEntityPublicProps } from "embedding-sdk-bundle/types/question";
import { applyThemePreset } from "embedding-sdk-shared/lib/apply-theme-preset";
import { createSnowplowTracker } from "metabase/analytics";
-import { api } from "metabase/api/client";
+import type { OnBeforeRequestHandler } from "metabase/api/client";
import { EmbeddingFooter } from "metabase/embedding/components/EmbeddingFooter/EmbeddingFooter";
import { EMBEDDING_SDK_IFRAME_EMBEDDING_CONFIG } from "metabase/embedding-sdk/config";
import { PLUGIN_EMBEDDING_IFRAME_SDK } from "metabase/plugins";
-import type { OnBeforeRequestHandlerConfig } from "metabase/plugins/oss/api";
import { useSelector } from "metabase/redux";
import { getSetting } from "metabase/selectors/settings";
import { getUserId } from "metabase/selectors/user";
@@ -47,9 +46,7 @@ import {
let _embedReferrer: string | undefined;
-const embedReferrerHandler = async (
- config: OnBeforeRequestHandlerConfig,
-): Promise<OnBeforeRequestHandlerConfig | void> => {
+const embedReferrerHandler: OnBeforeRequestHandler = async (config) => {
if (_embedReferrer) {
return {
...config,
@@ -62,10 +59,9 @@ const embedReferrerHandler = async (
}
};
-// Register once — uses a named function ref so it can't be pushed twice
-if (!api.beforeRequestHandlers.includes(embedReferrerHandler)) {
- api.beforeRequestHandlers.push(embedReferrerHandler);
-}
+// Install the iframe embed-referrer handler into its plugin slot.
+PLUGIN_EMBEDDING_IFRAME_SDK.onBeforeRequestHandlers.embedReferrer =
+ embedReferrerHandler;
const onSettingsChanged = (settings: SdkIframeEmbedSettings) => {
// Tell the SDK whether to use the existing user session or not.
diff --git a/frontend/src/metabase/embedding/lib/embedding-request-auth.ts b/frontend/src/metabase/embedding/lib/embedding-request-auth.ts
new file mode 100644
index 00000000000..b0f7313715f
--- /dev/null
+++ b/frontend/src/metabase/embedding/lib/embedding-request-auth.ts
@@ -0,0 +1,66 @@
+/* eslint-disable metabase/no-literal-metabase-strings -- request header names */
+import type {
+ OnBeforeRequestHandler,
+ OnBeforeRequestHandlerConfig,
+ RequestClientInfo,
+} from "metabase/api/client";
+import { IFRAMED_IN_SELF } from "metabase/utils/iframe";
+
+/**
+ * Factories for the embedding-only request-header plugin handlers. Each closes
+ * over its value, so there's no shared mutable state — the embedding setup flow
+ * installs the handlers it needs onto the plugin slots:
+ *
+ * - `setApiKeyHeader` / `setSessionTokenHeader` onto `setEmbeddingRequestAuthHeaders`
+ * for static auth (an API key, or a session token that never refreshes — e.g.
+ * MCP). A refreshing SSO session instead emits its header from
+ * `getOrRefreshSessionHandler` via `sessionTokenHeaders`, so the refreshed
+ * token applies to the request that triggered the refresh.
+ * - `setRequestClientHeaders` onto its own slot
+ * - `setEmbedPreviewHeader` onto its own slot (public + SDK flows only)
+ *
+ * In the normal app none are installed, so no embedding headers are emitted —
+ * keeping these embedding concerns out of the generic api client.
+ */
+export const setApiKeyHeader =
+ (apiKey: string): OnBeforeRequestHandler =>
+ async () => ({ headers: { "X-Api-Key": apiKey } });
+
+export const sessionTokenHeaders = (
+ sessionToken: string,
+): Partial<OnBeforeRequestHandlerConfig> => ({
+ headers: { "X-Metabase-Session": sessionToken },
+});
+
+export const setSessionTokenHeader =
+ (sessionToken: string): OnBeforeRequestHandler =>
+ async () =>
+ sessionTokenHeaders(sessionToken);
+
+export const setRequestClientHeaders =
+ (requestClient: RequestClientInfo): OnBeforeRequestHandler =>
+ async () => {
+ const headers: Record<string, string> = {};
+
+ if (requestClient.name) {
+ headers["X-Metabase-Client"] = requestClient.name;
+ }
+ if (requestClient.version) {
+ headers["X-Metabase-Client-Version"] = requestClient.version;
+ }
+
+ return { headers };
+ };
+
+/**
+ * Tag requests coming from an embed preview (the page is iframed into itself).
+ * Kept separate from `setRequestClientHeaders` because preview mode is
+ * orthogonal to which client is embedding. Installed only by the public and SDK
+ * embed flows — static and full-app deliberately don't tag preview requests
+ * (see EMB-930 in `metabase/embedding/config`).
+ */
+export const setEmbedPreviewHeader: OnBeforeRequestHandler = async () => {
+ if (IFRAMED_IN_SELF) {
+ return { headers: { "X-Metabase-Embedded-Preview": "true" } };
+ }
+};
diff --git a/frontend/src/metabase/embedding/lib/override-requests-for-embeds.ts b/frontend/src/metabase/embedding/lib/override-requests-for-embeds.ts
index 2f63d6ebb80..a13cb55dff7 100644
--- a/frontend/src/metabase/embedding/lib/override-requests-for-embeds.ts
+++ b/frontend/src/metabase/embedding/lib/override-requests-for-embeds.ts
@@ -1,13 +1,14 @@
import { sessionPropertiesPath } from "metabase/api";
-import { type RequestMethod, api } from "metabase/api/client";
+import type {
+ OnBeforeRequestHandlerConfig,
+ RequestMethod,
+} from "metabase/api/client";
import { isEmbedPreview } from "metabase/embedding/config";
import {
PLUGIN_API,
PLUGIN_CONTENT_TRANSLATION,
PLUGIN_EMBEDDING_SDK,
} from "metabase/plugins";
-import type { OnBeforeRequestHandlerConfig } from "metabase/plugins/oss/api";
-import type { CardId, DashboardId, ParameterId } from "metabase-types/api";
type EmbedType = "guest" | "static" | "public";
@@ -200,6 +201,17 @@ export const overrideRequests = async ({
return { method, url, headers, data };
}
+ // The matched embed endpoints address the entity by token/uuid
+ // (`:entityIdentifier`), never the real numeric id. Drop the id keys so they
+ // don't trail along as `?cardId=`/`?dashId=` querystring params now that the
+ // url has no `:cardId`/`:dashId` tag to consume them. The pipeline's merge
+ // can't delete keys, so mutate the bag in place — the client defensively
+ // copies it for exactly this.
+ if (findMatchingPattern(url)) {
+ delete data.cardId;
+ delete data.dashId;
+ }
+
return {
method: transformation.method,
url: replaceWithEmbedBase({ embedType, url: transformation.url }),
@@ -208,22 +220,6 @@ export const overrideRequests = async ({
};
};
-const setupRemappingUrls = (embedType: EmbedType) => {
- const baseUrl = getBaseUrlByEmbedType(embedType);
-
- PLUGIN_API.getRemappedDashboardParameterValueUrl = (
- _dashboardId: DashboardId | undefined,
- parameterId: ParameterId,
- ) =>
- `${baseUrl}/dashboard/:entityIdentifier/params/${encodeURIComponent(parameterId)}/remapping`;
-
- PLUGIN_API.getRemappedCardParameterValueUrl = (
- _cardId: CardId | string | undefined,
- parameterId: ParameterId,
- ) =>
- `${baseUrl}/card/:entityIdentifier/params/${encodeURIComponent(parameterId)}/remapping`;
-};
-
const EMBED_API_BASE_PATTERN = /^\/api\/embed(?=\/|$)/;
const EMBED_PREVIEW_API_BASE = "/api/preview_embed";
@@ -242,20 +238,18 @@ export const rewriteEmbedPreviewUrl = async ({
};
/**
- * Registers the embed-preview rewrite on the shared client. It runs after the
- * embed override handlers, so it covers both the override-produced
- * `/api/embed/...` urls and the embed endpoints called directly.
+ * Installs the embed-preview rewrite into its plugin slot. It runs after the
+ * embed override handlers (see the pipeline in `middleware.ts`), so it covers
+ * both the override-produced `/api/embed/...` urls and the embed endpoints
+ * called directly (e.g. `EmbedApi`, `embedApi`).
*
- * Idempotent, so call sites can register it at the earliest safe moment without
- * worrying about duplicates. For public/static embeds it must run *before* the
- * dashboard fetcher's effect (see `usePublicEndpoints`): React runs child
- * effects before parent effects, so registering from a parent `useMount` would
- * miss the very first embed request (the dashboard load).
+ * The slot's position in the pipeline is fixed, so this only needs to run before
+ * the first embed request — assigning the same handler again is a harmless
+ * no-op.
*/
export const setupEmbedPreviewRewrite = () => {
- if (!api.beforeRequestHandlers.includes(rewriteEmbedPreviewUrl)) {
- api.beforeRequestHandlers.push(rewriteEmbedPreviewUrl);
- }
+ PLUGIN_API.onBeforeRequestHandlers.rewriteEmbedPreviewUrl =
+ rewriteEmbedPreviewUrl;
};
/**
@@ -263,7 +257,6 @@ export const setupEmbedPreviewRewrite = () => {
* into guest embeds API requests.
*/
export const overrideRequestsForGuestEmbeds = () => {
- setupRemappingUrls("guest");
setupEmbedPreviewRewrite();
PLUGIN_EMBEDDING_SDK.onBeforeRequestHandlers.overrideRequestsForGuestEmbeds =
@@ -281,8 +274,6 @@ export const overrideRequestsForGuestEmbeds = () => {
export const overrideRequestsForPublicOrStaticEmbeds = (
embedType: "static" | "public",
) => {
- setupRemappingUrls(embedType);
-
PLUGIN_API.onBeforeRequestHandlers.overrideRequestsForPublicEmbeds = (data) =>
overrideRequests({
...data,
diff --git a/frontend/src/metabase/embedding/lib/override-requests-for-embeds.unit.spec.ts b/frontend/src/metabase/embedding/lib/override-requests-for-embeds.unit.spec.ts
index 62dafdcfd49..89b2d872874 100644
--- a/frontend/src/metabase/embedding/lib/override-requests-for-embeds.unit.spec.ts
+++ b/frontend/src/metabase/embedding/lib/override-requests-for-embeds.unit.spec.ts
@@ -1,5 +1,5 @@
-import { api } from "metabase/api/client";
import { isEmbedPreview } from "metabase/embedding/config";
+import { PLUGIN_API, reinitialize } from "metabase/plugins";
import {
matchUrlPattern,
@@ -16,6 +16,8 @@ const mockIsEmbedPreview = jest.mocked(isEmbedPreview);
afterEach(() => {
mockIsEmbedPreview.mockReset();
+ // Reset any plugin request handlers installed by a test.
+ reinitialize();
});
describe("matchUrlPattern", () => {
@@ -148,27 +150,49 @@ describe("overrideRequests", () => {
expect(result.url).toBe("/api/embed/card/:token/query");
expect(result.method).toBe("GET");
});
+
+ it("drops the real cardId so it isn't leaked as a querystring param", async () => {
+ const result = await overrideRequests({
+ embedType: "public",
+ method: "GET",
+ url: "/api/card/:cardId/params/:paramId/remapping",
+ data: { cardId: 123, paramId: "p1", entityIdentifier: "uuid-1" },
+ });
+
+ expect(result.url).toBe(
+ "/api/public/card/:entityIdentifier/params/:paramId/remapping",
+ );
+ expect(result.data).not.toHaveProperty("cardId");
+ expect(result.data.entityIdentifier).toBe("uuid-1");
+ });
+
+ it("drops the real dashId for dashboard parameter endpoints", async () => {
+ const result = await overrideRequests({
+ embedType: "guest",
+ method: "GET",
+ url: "/api/dashboard/:dashId/params/:paramId/values",
+ data: { dashId: 7, paramId: "p1", entityIdentifier: "uuid-2" },
+ });
+
+ expect(result.url).toBe(
+ "/api/embed/dashboard/:entityIdentifier/params/:paramId/values",
+ );
+ expect(result.data).not.toHaveProperty("dashId");
+ expect(result.data.entityIdentifier).toBe("uuid-2");
+ });
});
describe("setupEmbedPreviewRewrite", () => {
- // The embed route registers `usePublicEndpoints` on a parent of the dashboard
- // fetcher, and React runs child effects before parent effects, so this must be
- // called synchronously (not from an effect) to catch the first embed request.
- it("registers rewriteEmbedPreviewUrl on the shared client, idempotently", () => {
- const before = api.beforeRequestHandlers.filter(
- (handler) => handler === rewriteEmbedPreviewUrl,
- ).length;
-
- expect(before).toBe(0);
+ it("installs rewriteEmbedPreviewUrl into the PLUGIN_API slot", () => {
+ expect(PLUGIN_API.onBeforeRequestHandlers.rewriteEmbedPreviewUrl).not.toBe(
+ rewriteEmbedPreviewUrl,
+ );
setupEmbedPreviewRewrite();
- setupEmbedPreviewRewrite();
-
- const after = api.beforeRequestHandlers.filter(
- (handler) => handler === rewriteEmbedPreviewUrl,
- ).length;
- expect(after).toBe(1);
+ expect(PLUGIN_API.onBeforeRequestHandlers.rewriteEmbedPreviewUrl).toBe(
+ rewriteEmbedPreviewUrl,
+ );
});
});
diff --git a/frontend/src/metabase/parameters/actions.ts b/frontend/src/metabase/parameters/actions.ts
index b6a9766bab9..ee12712898f 100644
--- a/frontend/src/metabase/parameters/actions.ts
+++ b/frontend/src/metabase/parameters/actions.ts
@@ -71,7 +71,8 @@ export const fetchCardParameterValues =
}: FetchCardParameterValuesOpts) =>
(dispatch: DispatchFn, getState: GetState) => {
const baseRequest: CardParameterValuesRequest = {
- ...(entityIdentifier ? { entityIdentifier } : { cardId }),
+ cardId,
+ ...(entityIdentifier && { entityIdentifier }),
paramId: parameter.id,
};
const request:
@@ -106,7 +107,8 @@ export const fetchDashboardParameterValues =
}: FetchDashboardParameterValuesOpts) =>
(dispatch: DispatchFn, getState: GetState) => {
const baseRequest: DashboardParameterValuesRequest = {
- ...(entityIdentifier ? { entityIdentifier } : { dashId: dashboardId }),
+ dashId: dashboardId,
+ ...(entityIdentifier && { entityIdentifier }),
paramId: parameter.id,
...getFilteringParameterValuesMap(parameter, parameters),
};
diff --git a/frontend/src/metabase/parameters/actions.unit.spec.ts b/frontend/src/metabase/parameters/actions.unit.spec.ts
new file mode 100644
index 00000000000..920241c4569
--- /dev/null
+++ b/frontend/src/metabase/parameters/actions.unit.spec.ts
@@ -0,0 +1,111 @@
+import fetchMock from "fetch-mock";
+
+import type { DispatchFn } from "metabase/redux";
+import type { GetState } from "metabase/redux/store";
+import { stableStringify } from "metabase/utils/objects";
+import type { ParameterValues } from "metabase-types/api";
+import { createMockParameter } from "metabase-types/api/mocks";
+
+import {
+ fetchCardParameterValues,
+ fetchDashboardParameterValues,
+} from "./actions";
+
+const PARAMETER = createMockParameter({ id: "param-1", name: "Category" });
+
+const CACHED: ParameterValues = {
+ values: [["Doohickey"], ["Gadget"]],
+ has_more_values: false,
+};
+
+const createGetState = (cache: Record<string, ParameterValues>): GetState =>
+ (() => ({
+ parameters: { parameterValuesCache: cache },
+ })) as unknown as GetState;
+
+const dispatch = jest.fn() as unknown as DispatchFn;
+
+describe("parameters > actions", () => {
+ // Regression guard for the parameter-value dropdowns: the request used as the
+ // cache key (and sent to the overridden embed endpoints) must not carry a null
+ // `entityIdentifier`, otherwise it pollutes the key and every lookup misses.
+ describe("fetchDashboardParameterValues", () => {
+ const DASHBOARD_ID = 42;
+
+ it("hits the cache keyed by dashId/paramId when not embedding", async () => {
+ const getState = createGetState({
+ [stableStringify({ dashId: DASHBOARD_ID, paramId: PARAMETER.id })]:
+ CACHED,
+ });
+
+ const result = await fetchDashboardParameterValues({
+ dashboardId: DASHBOARD_ID,
+ entityIdentifier: null,
+ parameter: PARAMETER,
+ parameters: [],
+ })(dispatch, getState);
+
+ expect(result).toEqual(CACHED);
+ // A cache hit must not fall through to the network.
+ expect(fetchMock.callHistory.calls()).toHaveLength(0);
+ });
+
+ it("includes entityIdentifier in the cache key when embedding", async () => {
+ const getState = createGetState({
+ [stableStringify({
+ dashId: DASHBOARD_ID,
+ entityIdentifier: "uuid-1",
+ paramId: PARAMETER.id,
+ })]: CACHED,
+ });
+
+ const result = await fetchDashboardParameterValues({
+ dashboardId: DASHBOARD_ID,
+ entityIdentifier: "uuid-1",
+ parameter: PARAMETER,
+ parameters: [],
+ })(dispatch, getState);
+
+ expect(result).toEqual(CACHED);
+ expect(fetchMock.callHistory.calls()).toHaveLength(0);
+ });
+ });
+
+ describe("fetchCardParameterValues", () => {
+ const CARD_ID = 7;
+
+ it("hits the cache keyed by cardId/paramId when not embedding", async () => {
+ const getState = createGetState({
+ [stableStringify({ cardId: CARD_ID, paramId: PARAMETER.id })]: CACHED,
+ });
+
+ const result = await fetchCardParameterValues({
+ cardId: CARD_ID,
+ entityIdentifier: null,
+ parameter: PARAMETER,
+ })(dispatch, getState);
+
+ expect(result).toEqual(CACHED);
+ expect(fetchMock.callHistory.calls()).toHaveLength(0);
+ });
+
+ it("includes entityIdentifier in the cache key when embedding", async () => {
+ const getState = createGetState({
+ [stableStringify({
+ cardId: CARD_ID,
+ entityIdentifier: "uuid-1",
+ paramId: PARAMETER.id,
+ })]: CACHED,
+ });
+
+ const result = await fetchCardParameterValues({
+ cardId: CARD_ID,
+ entityIdentifier: "uuid-1",
+ parameter: PARAMETER,
+ })(dispatch, getState);
+
+ expect(result).toEqual(CACHED);
+ expect(fetchMock.callHistory.calls()).toHaveLength(0);
+ });
+ });
+});
diff --git a/frontend/src/metabase/parameters/components/widgets/ParameterFieldWidget/FieldValuesWidget/FieldValuesWidget.tsx b/frontend/src/metabase/parameters/components/widgets/ParameterFieldWidget/FieldValuesWidget/FieldValuesWidget.tsx
index dc2c29a1a25..50f4cfd3da5 100644
--- a/frontend/src/metabase/parameters/components/widgets/ParameterFieldWidget/FieldValuesWidget/FieldValuesWidget.tsx
+++ b/frontend/src/metabase/parameters/components/widgets/ParameterFieldWidget/FieldValuesWidget/FieldValuesWidget.tsx
@@ -739,10 +739,9 @@ function RemappedValue({
const { data: dashboardData } = useGetRemappedDashboardParameterValueQuery(
dashboardId != null && value != null && isRemapped
? {
- ...(entityIdentifier
- ? { entityIdentifier }
- : { dashboard_id: dashboardId }),
- parameter_id: parameter.id,
+ dashId: dashboardId,
+ ...(entityIdentifier && { entityIdentifier }),
+ paramId: parameter.id,
value,
}
: skipToken,
@@ -751,8 +750,9 @@ function RemappedValue({
const { data: cardData } = useGetRemappedCardParameterValueQuery(
cardId != null && value != null && isRemapped
? {
- ...(entityIdentifier ? { entityIdentifier } : { card_id: cardId }),
- parameter_id: parameter.id,
+ cardId,
+ ...(entityIdentifier && { entityIdentifier }),
+ paramId: parameter.id,
value,
}
: skipToken,
diff --git a/frontend/src/metabase/plugins/oss/api.ts b/frontend/src/metabase/plugins/oss/api.ts
index e8f9ff69328..12d51f40503 100644
--- a/frontend/src/metabase/plugins/oss/api.ts
+++ b/frontend/src/metabase/plugins/oss/api.ts
@@ -1,44 +1,41 @@
-import type { RequestMethod } from "metabase/api/client";
-import type { CardId, DashboardId, ParameterId } from "metabase-types/api";
+/* eslint-disable metabase/no-literal-metabase-strings -- request header names */
+import type { OnBeforeRequestHandler } from "metabase/api/client";
+import { isEmbeddingSdk } from "metabase/embedding-sdk/config";
+import { isWithinIframe } from "metabase/utils/iframe";
-export type OnBeforeRequestHandlerConfig = {
- method: RequestMethod;
- url: string;
- headers?: Record<string, string>;
- // URL `:tag` params (and querystring leftovers). For the legacy GET/POST
- // helpers this holds the whole request bag.
- data: Record<string, unknown>;
- // The JSON-body bag, kept as a separate channel from `data`. Exposed to
- // handlers so embed URL `:tag`s — notably the guest-embed `:token` — can be
- // filled from body fields, and so the refresh handler can swap a stale body
- // token. `undefined` for GETs, raw (FormData/URLSearchParams) bodies, and the
- // legacy helpers (which pack everything into `data`).
- body?: Record<string, unknown>;
-};
+const noop: OnBeforeRequestHandler = async () => {};
-export type OnBeforeRequestHandler = (
- data: OnBeforeRequestHandlerConfig,
-) => Promise<void | Partial<OnBeforeRequestHandlerConfig>>;
+// Tag requests from a non-SDK app running inside an iframe (interactive /
+// static / public embedding) so the backend knows it's embedded. Lives here
+// rather than in `metabase/api` so the client stays free of SDK imports.
+const setEmbeddedHeader: OnBeforeRequestHandler = async () => {
+ if (isWithinIframe() && !isEmbeddingSdk()) {
+ return { headers: { "X-Metabase-Embedded": "true" } };
+ }
+};
const getDefaultPluginApi = () => ({
onBeforeRequestHandlers: {
- overrideRequestsForPublicEmbeds: async (
- _data: OnBeforeRequestHandlerConfig,
- ): Promise<OnBeforeRequestHandlerConfig | void> => {},
- overrideRequestsForStaticEmbeds: async (
- _data: OnBeforeRequestHandlerConfig,
- ): Promise<OnBeforeRequestHandlerConfig | void> => {},
+ overrideRequestsForPublicEmbeds: noop,
+ rewriteEmbedPreviewUrl: noop,
+ setEmbeddedHeader,
+ // Emit the embedding client headers (`X-Metabase-Client` / `-Version`). A
+ // no-op slot: the embedding setup flow installs `setRequestClientHeaders`
+ // here, closing over the active client (see `embedding-request-auth`).
+ // Untouched in the normal app — keeping these embedding-only headers out of
+ // the generic api client.
+ setRequestClientHeaders: noop,
+ // Emit the embed-preview header (`X-Metabase-Embedded-Preview`). A no-op
+ // slot: the public and SDK embed flows install `setEmbedPreviewHeader` here,
+ // which tags requests when running inside an embed preview (see
+ // `embedding-request-auth`).
+ setEmbedPreviewHeader: noop,
+ // Emit the embedding auth header (`X-Api-Key` or `X-Metabase-Session`). A
+ // no-op slot: the embedding auth flow installs exactly one strategy here —
+ // `setApiKeyHeader` or `setSessionTokenHeader` — based on the auth method in
+ // use (see `embedding-request-auth`).
+ setEmbeddingRequestAuthHeaders: noop,
},
- getRemappedCardParameterValueUrl: (
- cardId: CardId | string | undefined,
- parameterId: ParameterId,
- ) =>
- `/api/card/${cardId}/params/${encodeURIComponent(parameterId)}/remapping`,
- getRemappedDashboardParameterValueUrl: (
- dashboardId: DashboardId | undefined,
- parameterId: ParameterId,
- ) =>
- `/api/dashboard/${dashboardId}/params/${encodeURIComponent(parameterId)}/remapping`,
});
export const PLUGIN_API = getDefaultPluginApi();
diff --git a/frontend/src/metabase/plugins/oss/embedding-iframe-sdk.ts b/frontend/src/metabase/plugins/oss/embedding-iframe-sdk.ts
index a9c1c4ef016..7632d32cce9 100644
--- a/frontend/src/metabase/plugins/oss/embedding-iframe-sdk.ts
+++ b/frontend/src/metabase/plugins/oss/embedding-iframe-sdk.ts
@@ -1,5 +1,12 @@
+import type { OnBeforeRequestHandler } from "metabase/api/client";
+
+const noop: OnBeforeRequestHandler = async () => {};
+
const getDefaultPluginEmbeddingIframeSdk = () => ({
isEnabled: () => false,
+ onBeforeRequestHandlers: {
+ embedReferrer: noop,
+ },
});
export const PLUGIN_EMBEDDING_IFRAME_SDK = getDefaultPluginEmbeddingIframeSdk();
diff --git a/frontend/src/metabase/plugins/oss/embedding-sdk.ts b/frontend/src/metabase/plugins/oss/embedding-sdk.ts
index 27505983310..2e3e4190ad8 100644
--- a/frontend/src/metabase/plugins/oss/embedding-sdk.ts
+++ b/frontend/src/metabase/plugins/oss/embedding-sdk.ts
@@ -1,15 +1,14 @@
-import type { OnBeforeRequestHandlerConfig } from "metabase/plugins/oss/api";
+import type { OnBeforeRequestHandler } from "metabase/api/client";
+
+const noop: OnBeforeRequestHandler = async () => {};
const getDefaultPluginEmbeddingSdk = () => ({
isEnabled: () => false,
onBeforeRequestHandlers: {
- getOrRefreshSessionHandler: async () => {},
- getOrRefreshGuestSessionHandler: async (
- _data: OnBeforeRequestHandlerConfig,
- ): Promise<OnBeforeRequestHandlerConfig | void> => {},
- overrideRequestsForGuestEmbeds: async (
- _data: OnBeforeRequestHandlerConfig,
- ): Promise<OnBeforeRequestHandlerConfig | void> => {},
+ getOrRefreshSessionHandler: noop,
+ getOrRefreshGuestSessionHandler: noop,
+ overrideRequestsForGuestEmbeds: noop,
+ reactSdkEmbedReferrer: noop,
},
});
diff --git a/frontend/src/metabase/redux/remappings.ts b/frontend/src/metabase/redux/remappings.ts
index bd9bff67936..dde08ce721c 100644
--- a/frontend/src/metabase/redux/remappings.ts
+++ b/frontend/src/metabase/redux/remappings.ts
@@ -77,8 +77,8 @@ export const fetchRemapping = createThunkAction(
{
...(entityIdentifier
? { entityIdentifier }
- : { dashboard_id: dashboardId }),
- parameter_id: parameter.id,
+ : { dashId: dashboardId }),
+ paramId: parameter.id,
value,
},
dispatch,
@@ -88,8 +88,8 @@ export const fetchRemapping = createThunkAction(
} else if (cardId != null) {
remapping = await runRtkEndpoint(
{
- ...(entityIdentifier ? { entityIdentifier } : { card_id: cardId }),
- parameter_id: parameter.id,
+ ...(entityIdentifier ? { entityIdentifier } : { cardId }),
+ paramId: parameter.id,
value,
},
dispatch,