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
Track embedding sdk host that use react 18 (#84303)
Nicolò Pretto5a30fa4e44dc
diff --git a/.clj-kondo/config/modules/config.edn b/.clj-kondo/config/modules/config.ednindex 16446627082..349d9e85848 100644--- a/.clj-kondo/config/modules/config.edn+++ b/.clj-kondo/config/modules/config.edn@@ -980,18 +980,21 @@{:team "Embedding":api #{metabase.embedding.initmetabase.embedding.jwt+ metabase.embedding.sdk-react-18metabase.embedding.settingsmetabase.embedding.utilmetabase.embedding.validation}:uses #{analyticsapi+ app-db+ batch-processingmodelspremium-featuresserversettingsutil}:model-imports #{:model/Card :model/Dashboard}- :model-exports #{:model/EmbeddingTheme}}+ :model-exports #{:model/EmbeddingSdkReact18Host :model/EmbeddingTheme}}embedding-hub{:team "Embedding"@@ -1037,7 +1040,11 @@requesttilesutil}- :model-imports #{:model/Card :model/Dashboard :model/DashboardCard :model/EmbeddingTheme}}+ :model-imports #{:model/Card+ :model/Dashboard+ :model/DashboardCard+ :model/EmbeddingSdkReact18Host+ :model/EmbeddingTheme}}events{:team "DevEx"diff --git a/enterprise/backend/src/metabase_enterprise/serialization/v2/models.clj b/enterprise/backend/src/metabase_enterprise/serialization/v2/models.cljindex 767312b3441..92a174293f1 100644--- a/enterprise/backend/src/metabase_enterprise/serialization/v2/models.clj+++ b/enterprise/backend/src/metabase_enterprise/serialization/v2/models.clj@@ -101,6 +101,7 @@"Dependency""DependencyStatus""DocumentBookmark"+ "EmbeddingSdkReact18Host""Exploration""ExplorationBlock""ExplorationBookmark"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 66bc5594d17..4d0493d0900 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@@ -64,6 +64,7 @@:model/Dependency:model/DependencyStatus:model/DocumentBookmark+ :model/EmbeddingSdkReact18Host:model/Exploration:model/ExplorationBookmark:model/ExplorationQuerydiff --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.tsindex bd786952f4c..6fe6c6b04ef 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@@ -30,6 +30,7 @@ import {import { setDataApp } from "metabase/embedding/config";import { setEmbedPreviewHeader } from "metabase/embedding/lib/auth/set-embed-preview-header";import { setReactSdkEmbedReferrerHeader } from "metabase/embedding/lib/auth/set-react-sdk-embed-referrer-header";+import { setReactSdkReactVersionHeader } from "metabase/embedding/lib/auth/set-react-sdk-react-version-header";import { setRequestClientHeaders } from "metabase/embedding/lib/auth/set-request-client-headers";import { setBasename } from "metabase/utils/basename";import { registerVisualizations } from "metabase/visualizations/register";@@ -143,6 +144,8 @@ export const useInitDataInternal = ({if (!isEmbeddingEajs()) {PLUGIN_API.onBeforeRequestHandlers.reactSdkEmbedReferrer =setReactSdkEmbedReferrerHeader;+ PLUGIN_API.onBeforeRequestHandlers.reactSdkReactVersion =+ setReactSdkReactVersionHeader;}// Dedupe by handler identity rather than total listener count — other codediff --git a/frontend/src/metabase/api/client/middleware.ts b/frontend/src/metabase/api/client/middleware.tsindex 928fbd5ba40..6fae207e904 100644--- a/frontend/src/metabase/api/client/middleware.ts+++ b/frontend/src/metabase/api/client/middleware.ts@@ -35,6 +35,7 @@ function getOnBeforeRequestHandlers(): OnBeforeRequestHandler[] {PLUGIN_API.onBeforeRequestHandlers.overrideRequestsForPublicEmbeds,PLUGIN_API.onBeforeRequestHandlers.rewriteEmbedPreviewUrl,PLUGIN_API.onBeforeRequestHandlers.reactSdkEmbedReferrer,+ PLUGIN_API.onBeforeRequestHandlers.reactSdkReactVersion,PLUGIN_API.onBeforeRequestHandlers.embedReferrer,];}diff --git a/frontend/src/metabase/api/client/request-handlers.ts b/frontend/src/metabase/api/client/request-handlers.tsindex aad04bd30a4..dfbcc6ae7c5 100644--- a/frontend/src/metabase/api/client/request-handlers.ts+++ b/frontend/src/metabase/api/client/request-handlers.ts@@ -69,6 +69,9 @@ const getDefaultPluginApi = () => ({// Send the host page URL as the embed referrer header. Installed by the// React SDK's init flow.reactSdkEmbedReferrer: noop,+ // Send the host app React version header. Installed by the React SDK's+ // init flow.+ reactSdkReactVersion: noop,// Send the host page URL as the embed referrer header. Installed by the// iframe SDK's embed route, which receives the URL via postMessage.embedReferrer: noop,diff --git a/frontend/src/metabase/embedding/lib/auth/set-react-sdk-react-version-header.ts b/frontend/src/metabase/embedding/lib/auth/set-react-sdk-react-version-header.tsnew file mode 100644index 00000000000..adda7a37d45--- /dev/null+++ b/frontend/src/metabase/embedding/lib/auth/set-react-sdk-react-version-header.ts@@ -0,0 +1,9 @@+/* eslint-disable metabase/no-literal-metabase-strings -- request header names */+import { version as hostReactVersion } from "react";++import type { OnBeforeRequestHandler } from "metabase/api/client";++export const setReactSdkReactVersionHeader: OnBeforeRequestHandler =+ async () => {+ return { headers: { "X-Metabase-Client-React-Version": hostReactVersion } };+ };diff --git a/resources/migrations/064/20261014_embedding_sdk_react_18_host.yaml b/resources/migrations/064/20261014_embedding_sdk_react_18_host.yamlnew file mode 100644index 00000000000..c922ef8068a--- /dev/null+++ b/resources/migrations/064/20261014_embedding_sdk_react_18_host.yaml@@ -0,0 +1,43 @@+## Adds embedding_sdk_react_18_host: the host apps that use the React embedding SDK with React 18, so admins can+## update them before Metabase 66 drops React 18. Temporary: a later release drops this table.++databaseChangeLog:+ - changeSet:+ id: v64.g8il3a+ author: npretto+ comment: Add embedding_sdk_react_18_host+ changes:+ - createTable:+ tableName: embedding_sdk_react_18_host+ remarks: Host apps that used the React embedding SDK with React 18+ columns:+ - column:+ name: id+ type: int+ remarks: Unique ID+ autoIncrement: true+ constraints:+ primaryKey: true+ nullable: false+ - column:+ name: host+ type: varchar(512)+ remarks: Hostname of the host app page, or an empty string when the page URL has no hostname+ constraints:+ nullable: false+ unique: true+ uniqueConstraintName: uq_embedding_sdk_react_18_host_host+ - column:+ name: created_at+ type: ${timestamp_type}+ remarks: When the host was first recorded+ defaultValueComputed: current_timestamp+ constraints:+ nullable: false+ - column:+ name: last_seen_at+ type: ${timestamp_type}+ remarks: When the host was last recorded+ defaultValueComputed: current_timestamp+ constraints:+ nullable: falsediff --git a/src/metabase/api_routes/routes.clj b/src/metabase/api_routes/routes.cljindex 967c67ae280..c70a529c8bc 100644--- a/src/metabase/api_routes/routes.clj+++ b/src/metabase/api_routes/routes.clj@@ -229,6 +229,7 @@"/embed-mcp" (+auth metabase.mcp.callback-api/routes)"/embed-theme" (+auth metabase.embedding-rest.api/theme-routes)"/embedding-hub" metabase.embedding-hub.api/routes+ "/embedding-sdk" (+auth metabase.embedding-rest.api/sdk-routes)"/eval-trace" (metabase.ai-tracing.api/+eval-capture-enabled metabase.ai-tracing.api/routes)"/exploration" (+auth metabase.explorations.api/routes)"/field" (+auth metabase.warehouse-schema-rest.api/field-routes)diff --git a/src/metabase/batch_processing/impl.clj b/src/metabase/batch_processing/impl.cljindex 5c988b2a0a1..0c514721e41 100644--- a/src/metabase/batch_processing/impl.clj+++ b/src/metabase/batch_processing/impl.clj@@ -109,6 +109,9 @@[:id :int]]sdk-tracked-rowid+timestamp+ [:map {:closed true}+ [:host :string]+ [:timestamp (ms/InstanceOfClass java.time.temporal.Temporal)]][:map {:closed true}[:user-id ms/PositiveInt][:dashboard-id ms/PositiveInt]diff --git a/src/metabase/embedding/db.clj b/src/metabase/embedding/db.cljindex a050e5eb26b..815907e83a6 100644--- a/src/metabase/embedding/db.clj+++ b/src/metabase/embedding/db.clj@@ -2,7 +2,9 @@"Application database queries for the embedding module. Every function here is a direct Toucan 2 call with noadditional logic, so the rest of the module never talks to `toucan2.core` itself."(:require+ [metabase.app-db.core :as mdb][metabase.util.malli :as mu]+ [metabase.util.malli.schema :as ms][toucan2.core :as t2]))(mu/defn count-embedded-cards@@ -14,3 +16,19 @@"Number of Dashboards that have embedding enabled."[](t2/count :model/Dashboard :enable_embedding true))++(mu/defn delete-sdk-react-18-hosts-last-seen-before!+ "Delete the EmbeddingSdkReact18Hosts last seen before `cutoff`."+ [cutoff :- ms/TemporalInstant]+ (t2/delete! :model/EmbeddingSdkReact18Host :last_seen_at [:< [:auto/param cutoff]]))++(mu/defn save-sdk-react-18-host!+ "Insert the EmbeddingSdkReact18Host `host` seen at `seen-at`, or move its `last_seen_at` forward to `seen-at`."+ [host :- :string+ seen-at :- ms/TemporalInstant]+ (mdb/update-or-insert! :model/EmbeddingSdkReact18Host {:host host}+ (fn [existing]+ ;; the INSERT also uses this, and GREATEST needs an existing row+ (if existing+ {:last_seen_at [:greatest :last_seen_at seen-at]}+ {:last_seen_at seen-at}))))diff --git a/src/metabase/embedding/models/sdk_react_18_host.clj b/src/metabase/embedding/models/sdk_react_18_host.cljnew file mode 100644index 00000000000..21278ee383c--- /dev/null+++ b/src/metabase/embedding/models/sdk_react_18_host.clj@@ -0,0 +1,24 @@+(ns metabase.embedding.models.sdk-react-18-host+ "Model for the host apps that use the React embedding SDK with React 18."+ (:require+ [metabase.embedding.schema :as embedding.schema]+ [metabase.models.interface :as mi]+ [metabase.util.malli.registry :as mr]+ [methodical.core :as methodical]+ [toucan2.core :as t2]))++(methodical/defmethod t2/table-name :model/EmbeddingSdkReact18Host [_model] :embedding_sdk_react_18_host)++(doto :model/EmbeddingSdkReact18Host+ (derive :metabase/model)+ (derive ::mi/read-policy.superuser)+ (derive ::mi/write-policy.superuser)+ (derive ::mi/create-policy.superuser)+ (derive :hook/created-at-timestamped?))++;; The middleware normalizes the host before it saves it; this rejects a new row whose host is not normalized.+(t2/define-before-insert :model/EmbeddingSdkReact18Host+ [{:keys [host], :as row}]+ (when-not (mr/validate ::embedding.schema/sdk-react-18-host.host host)+ (throw (ex-info (format "Invalid React 18 SDK host: %s" (pr-str host)) {:host host})))+ row)diff --git a/src/metabase/embedding/schema.clj b/src/metabase/embedding/schema.cljindex 688a5618c00..3c87f927b6a 100644--- a/src/metabase/embedding/schema.clj+++ b/src/metabase/embedding/schema.clj@@ -1,6 +1,7 @@(ns metabase.embedding.schema"Malli schemas for the embedding module."(:require+ [metabase.util :as u][metabase.util.malli.registry :as mr][metabase.util.malli.schema :as ms]))@@ -24,3 +25,24 @@[:is_default {:optional true} [:maybe :boolean]][:created_at {:optional true} [:maybe ms/TemporalInstant]][:updated_at {:optional true} [:maybe ms/TemporalInstant]]])++(mr/def ::sdk-react-18-host.host+ "The `host` of a EmbeddingSdkReact18Host: a lowercase hostname, or an empty string when the host app page URL has no+ hostname."+ [:and :string [:fn {:error/message "must be lowercase"} #(= % (u/lower-case-en %))]])++(mr/def ::sdk-react-18-host+ "A EmbeddingSdkReact18Host as selected from the app DB: every column of `:embedding_sdk_react_18_host`. `host` is an+ empty string when the host app page URL has no hostname."+ [:map {:closed true}+ [:id ms/PositiveInt]+ [:host ::sdk-react-18-host.host]+ [:created_at ms/TemporalInstant]+ [:last_seen_at ms/TemporalInstant]])++(mr/def ::sdk-react-18-host.response+ "A EmbeddingSdkReact18Host as the API returns it: `host` is nil when the host app page URL has no hostname."+ [:merge+ ::sdk-react-18-host+ [:map {:closed true}+ [:host [:maybe :string]]]])diff --git a/src/metabase/embedding/sdk_react_18.clj b/src/metabase/embedding/sdk_react_18.cljnew file mode 100644index 00000000000..9a5fa76cd20--- /dev/null+++ b/src/metabase/embedding/sdk_react_18.clj@@ -0,0 +1,79 @@+(ns metabase.embedding.sdk-react-18+ "Records the host apps that use the React embedding SDK with React 18, so admins can update them before Metabase 66+ drops React 18. Temporary: it goes away with React 18 support."+ (:require+ [clojure.string :as str]+ [java-time.api :as t]+ [metabase.analytics.core :as analytics]+ [metabase.batch-processing.core :as grouper]+ [metabase.embedding.db :as embedding.db]+ [metabase.embedding.util :as embedding.util]+ [metabase.util :as u]+ [metabase.util.log :as log]))++(def ^:private save-interval-seconds 60)++(defn last-seen-cutoff+ "Hosts last seen before this time are expired."+ []+ (t/minus (t/offset-date-time) (t/days 4)))++(def ^:private loopback-hosts #{"localhost" "127.0.0.1" "[::1]"})++(defn- react-18-sdk-request? [{:keys [headers] :as request}]+ (and (embedding.util/has-react-sdk-header? request)+ (some-> (get headers "x-metabase-client-react-version") (str/starts-with? "18."))))++(defn- record-host? [{:keys [headers request-method uri metabase-user-id]} {:keys [status]}]+ (and (= request-method :get)+ (int? status)+ (<= 200 status 299)+ (not= (get headers "x-metabase-embedded-preview") "true")+ ;; `/api/embed/` endpoints validate the guest token before they return a 2xx+ (or (some? metabase-user-id)+ (str/starts-with? uri "/api/embed/"))))++(defn- save-hosts!+ "Save the hosts submitted since the last save, each one with the newest time it was seen."+ [submitted]+ (try+ ;; Delete first: an expired row of a host goes away here, so another server's delete cannot remove it between+ ;; the SELECT and the UPDATE of the upsert.+ (embedding.db/delete-sdk-react-18-hosts-last-seen-before! (last-seen-cutoff))+ (catch Throwable e+ (log/warn e "Failed to delete the expired hosts that use the React embedding SDK with React 18")))+ (doseq [[host seen] (group-by :host submitted)]+ (try+ (embedding.db/save-sdk-react-18-host! host (apply t/max (map :timestamp seen)))+ (catch Throwable e+ (log/warn e "Failed to save a host that uses the React embedding SDK with React 18")))))++(defonce ^:private save-hosts-queue+ (delay (grouper/start! #'save-hosts!+ :capacity 500+ :interval (* save-interval-seconds 1000))))++(defn- maybe-record-host! [request response]+ (when (record-host? request response)+ ;; "" groups the host apps whose page URL has no hostname, e.g. an Electron app on file://+ (let [host (or (some-> (analytics/extract-hostname (get-in request [:headers "x-metabase-embed-referrer"]))+ u/lower-case-en)+ "")]+ (when-not (contains? loopback-hosts host)+ (grouper/submit! @save-hosts-queue {:host host, :timestamp (t/offset-date-time)})))))++(defn wrap-record-react-18-sdk-host+ "Ring middleware that saves the host apps that use the React embedding SDK with React 18. It must run after+ `wrap-current-user-info`, because it reads the `:metabase-user-id` that the auth middleware sets."+ [handler]+ (fn [request respond raise]+ (if-not (react-18-sdk-request? request)+ (handler request respond raise)+ (handler request+ (fn [response]+ (try+ (maybe-record-host! request response)+ (catch Throwable e+ (log/warn e "Failed to record a host that uses the React embedding SDK with React 18")))+ (respond response))+ raise))))diff --git a/src/metabase/embedding_rest/api.clj b/src/metabase/embedding_rest/api.cljindex 2f23a572b3f..3a742fe256c 100644--- a/src/metabase/embedding_rest/api.clj+++ b/src/metabase/embedding_rest/api.clj@@ -4,10 +4,12 @@[metabase.api.macros :as api.macros][metabase.embedding-rest.api.embed][metabase.embedding-rest.api.preview-embed]+ [metabase.embedding-rest.api.sdk][metabase.embedding-rest.api.theme]))(comment metabase.embedding-rest.api.embed/keep-memetabase.embedding-rest.api.preview-embed/keep-me+ metabase.embedding-rest.api.sdk/keep-memetabase.embedding-rest.api.theme/keep-me)(def ^{:arglists '([request respond raise])} embedding-routes@@ -21,3 +23,7 @@(def ^{:arglists '([request respond raise])} theme-routes"`/api/embed-theme` routes"(api.macros/ns-handler 'metabase.embedding-rest.api.theme api/+check-superuser))++(def ^{:arglists '([request respond raise])} sdk-routes+ "`/api/embedding-sdk` routes"+ (api.macros/ns-handler 'metabase.embedding-rest.api.sdk api/+check-superuser))diff --git a/src/metabase/embedding_rest/api/sdk.clj b/src/metabase/embedding_rest/api/sdk.cljnew file mode 100644index 00000000000..c17422241f4--- /dev/null+++ b/src/metabase/embedding_rest/api/sdk.clj@@ -0,0 +1,20 @@+(ns metabase.embedding-rest.api.sdk+ "`/api/embedding-sdk` endpoints, for admins."+ (:require+ [metabase.api.macros :as api.macros]+ [metabase.embedding-rest.db :as embedding-rest.db]+ [metabase.embedding.schema :as embedding.schema]+ [metabase.embedding.sdk-react-18 :as embedding.sdk-react-18]+ [metabase.models.interface :as mi]))++(set! *warn-on-reflection* true)++(def ^:private max-hosts 50)++(api.macros/defendpoint :get "/react-18-hosts" :- [:sequential ::embedding.schema/sdk-react-18-host.response]+ "The host apps that used the React embedding SDK with React 18 in the last 4 days, newest first, at most 50. `host`+ is null when the host app page URL has no hostname."+ []+ (->> (embedding-rest.db/sdk-react-18-hosts-last-seen-after (embedding.sdk-react-18/last-seen-cutoff) max-hosts)+ (filter mi/can-read?)+ (map #(update % :host not-empty))))diff --git a/src/metabase/embedding_rest/db.clj b/src/metabase/embedding_rest/db.cljindex 548a0afe0d8..73ed769e641 100644--- a/src/metabase/embedding_rest/db.clj+++ b/src/metabase/embedding_rest/db.clj@@ -87,3 +87,12 @@"Delete the EmbeddingTheme with `id`."[id :- ms/PositiveInt](t2/delete! :model/EmbeddingTheme :id id))++(mu/defn sdk-react-18-hosts-last-seen-after :- [:sequential ::embedding.schema/sdk-react-18-host]+ "The EmbeddingSdkReact18Hosts last seen after `cutoff`, newest first, at most `limit`."+ [cutoff :- ms/TemporalInstant+ limit :- ms/PositiveInt]+ (t2/select :model/EmbeddingSdkReact18Host {:select [:id :host :created_at :last_seen_at]+ :where [:> :last_seen_at [:auto/param cutoff]]+ :order-by [[:last_seen_at :desc] [:id :desc]]+ :limit limit}))diff --git a/src/metabase/models/resolution.clj b/src/metabase/models/resolution.cljindex 9d6b9441a3a..4bafbc3fc6b 100644--- a/src/metabase/models/resolution.clj+++ b/src/metabase/models/resolution.clj@@ -52,6 +52,7 @@:model/Dimension metabase.warehouse-schema.models.dimension:model/Document metabase.documents.models.document:model/DocumentBookmark metabase.bookmarks.models.bookmark+ :model/EmbeddingSdkReact18Host metabase.embedding.models.sdk-react-18-host:model/EmbeddingTheme metabase.embedding.models.theme:model/Exploration metabase.explorations.models.exploration:model/ExplorationBlock metabase.explorations.models.exploration-blockdiff --git a/src/metabase/server/handler.clj b/src/metabase/server/handler.cljindex c17e6b25ed0..53bc939e799 100644--- a/src/metabase/server/handler.clj+++ b/src/metabase/server/handler.clj@@ -4,6 +4,7 @@[metabase.analytics.core :as analytics][metabase.api.macros :as api.macros][metabase.config.core :as config]+ [metabase.embedding.sdk-react-18 :as embedding.sdk-react-18][metabase.metabot.agent-api.usage :as agent-api.usage][metabase.server.middleware.auth :as mw.auth][metabase.server.middleware.body-limit :as mw.body-limit]@@ -89,6 +90,7 @@#(#'mw.exceptions/catch-api-exceptions % cors) ; catch exceptions and return them in our expected format#'mw.log/log-api-call ; log info about the request, db call counts etc.#'agent-api.usage/wrap-record-cli-usage ; record CLI usage analytics for metabase-cli REST API calls+ #'embedding.sdk-react-18/wrap-record-react-18-sdk-host ; record host apps that use the React SDK with React 18; must run after auth#'mw.browser-cookie/ensure-browser-id-cookie ; add cookie to identify browser; add `:browser-id` to the request#(#'mw.security/add-security-headers % cors) ; Add HTTP headers to API responses to prevent them from being cached#'mw.json/wrap-json-body ; extracts json POST/PUT body and makes it available on requestdiff --git a/test/metabase/cmd/copy_test.clj b/test/metabase/cmd/copy_test.cljindex e435ced7d9e..e13f89b63d4 100644--- a/test/metabase/cmd/copy_test.clj+++ b/test/metabase/cmd/copy_test.clj@@ -151,6 +151,7 @@:model/DatabaseRouter:model/Dependency:model/DependencyStatus+ :model/EmbeddingSdkReact18Host:model/ExplorationQueryResult:model/McpQueryHandle:model/McpSessionLogdiff --git a/test/metabase/embedding/sdk_react_18_test.clj b/test/metabase/embedding/sdk_react_18_test.cljnew file mode 100644index 00000000000..711369dd0e7--- /dev/null+++ b/test/metabase/embedding/sdk_react_18_test.clj@@ -0,0 +1,181 @@+(ns metabase.embedding.sdk-react-18-test+ (:require+ [clojure.test :refer :all]+ [java-time.api :as t]+ [metabase.embedding.db :as embedding.db]+ [metabase.embedding.sdk-react-18 :as embedding.sdk-react-18]+ [metabase.test :as mt]+ [ring.mock.request :as ring.mock]+ [toucan2.core :as t2]))++(set! *warn-on-reflection* true)++(defn- react-18-sdk-request+ [{:keys [method uri user-id client react-version referrer preview?]+ :or {method :get+ uri "/api/user/current"+ user-id 1+ client "embedding-sdk-react"+ react-version "18.3.1"+ referrer "https://app.example.com/page"}}]+ (cond-> (ring.mock/request method uri)+ client (ring.mock/header "x-metabase-client" client)+ react-version (ring.mock/header "x-metabase-client-react-version" react-version)+ referrer (ring.mock/header "x-metabase-embed-referrer" referrer)+ preview? (ring.mock/header "x-metabase-embedded-preview" "true")+ user-id (assoc :metabase-user-id user-id)))++(defn- run-middleware [request status]+ (let [handler (embedding.sdk-react-18/wrap-record-react-18-sdk-host+ (fn [_ respond _] (respond {:status status})))]+ (handler request identity identity)))++(defn- saved-hosts!+ "Empties the table, calls `thunk` and returns the hosts it saved."+ [thunk]+ (t2/delete! :model/EmbeddingSdkReact18Host)+ (thunk)+ (vec (t2/select-fn-vec :host :model/EmbeddingSdkReact18Host)))++;; With `synchronous-batch-updates` the save runs right away, on the calling thread, instead of in a batch.+(deftest record-react-18-sdk-host-test+ (mt/with-temporary-setting-values [synchronous-batch-updates true]+ (mt/with-model-cleanup [:model/EmbeddingSdkReact18Host]+ (doseq [[description request-opts status recorded?]+ [["logged-in user" {} 200 true]+ ["valid guest token" {:user-id nil, :uri "/api/embed/card/token"} 200 true]+ ["streaming response" {} 202 true]+ ["React 19" {:react-version "19.1.0"} 200 false]+ ["no React version" {:react-version nil} 200 false]+ ["EAJS" {:client "embedding-simple"} 200 false]+ ["embed preview" {:preview? true} 200 false]+ ["POST" {:method :post} 200 false]+ ["OPTIONS on a guest route" {:method :options, :user-id nil, :uri "/api/embed/card/x"} 200 false]+ ["error" {} 500 false]+ ["anonymous" {:user-id nil} 200 false]+ ["invalid guest token" {:user-id nil, :uri "/api/embed/card/token"} 400 false]]]+ (testing description+ (is (= (if recorded? ["app.example.com"] [])+ (saved-hosts! #(is (= {:status status} (run-middleware (react-18-sdk-request request-opts) status))))))))+ (testing "lowercases the hostname"+ (is (= ["app.example.com"]+ (saved-hosts! #(run-middleware (react-18-sdk-request {:referrer "https://App.Example.COM/page"}) 200)))))+ (testing "records a host app without a hostname as an empty string"+ (doseq [referrer [nil "file:///app/index.html"]]+ (is (= [""] (saved-hosts! #(run-middleware (react-18-sdk-request {:referrer referrer}) 200)))+ (str referrer))))+ (testing "skips localhost"+ (doseq [referrer ["http://localhost:3000" "http://LOCALHOST:3000" "http://127.0.0.1:3000" "http://[::1]:3000"]]+ (is (= [] (saved-hosts! #(run-middleware (react-18-sdk-request {:referrer referrer}) 200)))+ referrer))))))++(deftest save-hosts-test+ (let [saved (atom [])+ earlier (t/offset-date-time "2026-10-13T10:00:00Z")+ later (t/offset-date-time "2026-10-13T10:00:30Z")]+ (mt/with-dynamic-fn-redefs [embedding.db/delete-sdk-react-18-hosts-last-seen-before! (constantly nil)+ embedding.db/save-sdk-react-18-host! #(swap! saved conj [%1 %2])]+ (testing "saves each host once, with the newest time it was seen"+ (#'embedding.sdk-react-18/save-hosts! [{:host "a.example.com", :timestamp later}+ {:host "a.example.com", :timestamp earlier}+ {:host "b.example.com", :timestamp earlier}])+ (is (= [["a.example.com" later] ["b.example.com" earlier]] (sort-by first @saved)))))))++(deftest save-hosts-failure-test+ (let [now (t/offset-date-time)+ saved (atom [])]+ (testing "a failed delete logs a warning, and the hosts are still saved"+ (mt/with-dynamic-fn-redefs [embedding.db/delete-sdk-react-18-hosts-last-seen-before! (fn [_] (throw (ex-info "boom" {})))+ embedding.db/save-sdk-react-18-host! (fn [host _] (swap! saved conj host))]+ (mt/with-log-messages-for-level [messages [metabase.embedding.sdk-react-18 :warn]]+ (#'embedding.sdk-react-18/save-hosts! [{:host "app.example.com", :timestamp now}])+ (is (= ["app.example.com"] @saved))+ (is (=? [{:level :warn, :message #"Failed to delete the expired hosts.*"}]+ (messages))))))+ (testing "a host that fails to save does not stop the other hosts"+ (reset! saved [])+ (mt/with-dynamic-fn-redefs [embedding.db/delete-sdk-react-18-hosts-last-seen-before! (constantly nil)+ embedding.db/save-sdk-react-18-host! (fn [host _]+ (when (= host "bad.example.com")+ (throw (ex-info "boom" {})))+ (swap! saved conj host))]+ (mt/with-log-messages-for-level [messages [metabase.embedding.sdk-react-18 :warn]]+ (#'embedding.sdk-react-18/save-hosts! [{:host "bad.example.com", :timestamp now}+ {:host "good.example.com", :timestamp now}])+ (is (= ["good.example.com"] @saved))+ (is (=? [{:level :warn, :message #"Failed to save a host.*"}]+ (messages))))))))++(defn- stored-host [host]+ (some-> (t2/select-one :model/EmbeddingSdkReact18Host :host host)+ (select-keys [:id :created_at :last_seen_at])+ (update :created_at t/instant)+ (update :last_seen_at t/instant)))++(defn- save-host! [host seen-at]+ (#'embedding.sdk-react-18/save-hosts! [{:host host, :timestamp (t/offset-date-time seen-at)}]))++(deftest save-host-test+ (mt/with-model-cleanup [:model/EmbeddingSdkReact18Host]+ (t2/delete! :model/EmbeddingSdkReact18Host)+ (mt/with-clock #t "2026-10-13T10:00:00Z[UTC]"+ (testing "inserts a new host, also the empty host of apps without a hostname"+ (save-host! "app.example.com" "2026-10-13T10:00:00Z")+ (save-host! "" "2026-10-13T10:00:00Z")+ (is (=? {:created_at some?, :last_seen_at (t/instant "2026-10-13T10:00:00Z")}+ (stored-host "app.example.com")))+ (is (=? {:last_seen_at (t/instant "2026-10-13T10:00:00Z")}+ (stored-host ""))))+ (let [inserted (stored-host "app.example.com")]+ (testing "moves last_seen_at forward and keeps the row and its created_at"+ (save-host! "app.example.com" "2026-10-13T11:00:00Z")+ (is (= (assoc inserted :last_seen_at (t/instant "2026-10-13T11:00:00Z"))+ (stored-host "app.example.com"))))+ (testing "never moves last_seen_at back, e.g. after a slow write from another server"+ (save-host! "app.example.com" "2026-10-13T10:30:00Z")+ (is (= (t/instant "2026-10-13T11:00:00Z")+ (:last_seen_at (stored-host "app.example.com")))))+ (testing "keeps one row per host"+ (is (= 1 (t2/count :model/EmbeddingSdkReact18Host :host "app.example.com"))))+ (mt/with-clock #t "2026-10-18T10:00:00Z[UTC]"+ (t2/update! :model/EmbeddingSdkReact18Host {:host ""} {:last_seen_at (t/offset-date-time "2026-10-15T10:00:00Z")})+ (save-host! "app.example.com" "2026-10-18T10:00:00Z")+ (testing "saves a host last seen more than 4 days ago again, as a new row"+ (is (=? {:id (partial not= (:id inserted))+ :last_seen_at (t/instant "2026-10-18T10:00:00Z")}+ (stored-host "app.example.com"))))+ (testing "keeps the hosts seen in the last 4 days"+ (is (=? {:last_seen_at (t/instant "2026-10-15T10:00:00Z")}+ (stored-host "")))))))))++(deftest host-validation-test+ (mt/with-model-cleanup [:model/EmbeddingSdkReact18Host]+ (t2/delete! :model/EmbeddingSdkReact18Host)+ (let [now (t/offset-date-time)]+ (testing "the model accepts a lowercase host, and \"\" for a host app without a hostname"+ (t2/insert! :model/EmbeddingSdkReact18Host [{:host "valid.example.com", :last_seen_at now}+ {:host "", :last_seen_at now}])+ (is (= 2 (t2/count :model/EmbeddingSdkReact18Host))))+ (testing "the model rejects any other host"+ (doseq [host ["Upper.example.com" nil]]+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"Invalid React 18 SDK host"+ (t2/insert! :model/EmbeddingSdkReact18Host {:host host, :last_seen_at now}))+ (pr-str host)))))))++(deftest record-react-18-sdk-host-handler-test+ (testing "the middleware runs after authentication and saves the host"+ (mt/with-temporary-setting-values [synchronous-batch-updates true]+ (mt/with-model-cleanup [:model/EmbeddingSdkReact18Host]+ (let [headers (fn [host]+ {"x-metabase-client" "embedding-sdk-react"+ "x-metabase-client-react-version" "18.3.1"+ "x-metabase-embed-referrer" (str "https://" host "/page")})]+ ;; so a row left by an earlier run can't make the assertions below pass+ (t2/delete! :model/EmbeddingSdkReact18Host :host [:in ["anonymous.example.com" "handler.example.com"]])+ (testing "anonymous requests are not recorded, even when they succeed"+ (mt/client :get 200 "session/properties" {:request-options {:headers (headers "anonymous.example.com")}})+ (is (not (t2/exists? :model/EmbeddingSdkReact18Host :host "anonymous.example.com"))))+ (testing "logged-in requests are recorded and saved"+ (mt/user-http-request :rasta :get 200 "user/current"+ {:request-options {:headers (headers "handler.example.com")}})+ (is (t2/exists? :model/EmbeddingSdkReact18Host :host "handler.example.com"))))))))diff --git a/test/metabase/embedding_rest/api/sdk_test.clj b/test/metabase/embedding_rest/api/sdk_test.cljnew file mode 100644index 00000000000..7773c57eb1e--- /dev/null+++ b/test/metabase/embedding_rest/api/sdk_test.clj@@ -0,0 +1,37 @@+(ns metabase.embedding-rest.api.sdk-test+ "Tests for /api/embedding-sdk endpoints."+ (:require+ [clojure.test :refer :all]+ [java-time.api :as t]+ [metabase.embedding-rest.api.sdk :as api.sdk]+ [metabase.test :as mt]+ [metabase.test.fixtures :as fixtures]+ [toucan2.core :as t2]))++(use-fixtures :once (fixtures/initialize :db :test-users :web-server))++(defn- days-ago [n]+ (t/minus (t/offset-date-time) (t/days n)))++(deftest react-18-hosts-test+ (testing "GET /api/embedding-sdk/react-18-hosts"+ (mt/with-model-cleanup [:model/EmbeddingSdkReact18Host]+ (t2/delete! :model/EmbeddingSdkReact18Host)+ (t2/insert! :model/EmbeddingSdkReact18Host [{:host "old.example.com", :last_seen_at (days-ago 5)}+ {:host "", :last_seen_at (days-ago 2)}+ {:host "app.example.com", :last_seen_at (days-ago 1)}])+ (testing "returns the hosts seen in the last 4 days, newest first, with a null host for apps without one"+ (let [hosts (mt/user-http-request :crowberto :get 200 "embedding-sdk/react-18-hosts")]+ (is (=? [{:host "app.example.com"} {:host nil}] hosts))+ (is (= #{:id :host :created_at :last_seen_at} (set (keys (first hosts)))))))+ (testing "returns at most 50 hosts, the newest, the last inserted first when they were seen at the same time"+ (let [now (t/offset-date-time)]+ (t2/insert! :model/EmbeddingSdkReact18Host (for [i (range @#'api.sdk/max-hosts)]+ {:host (str "host-" i ".example.com"), :last_seen_at now})))+ (is (= (for [i (reverse (range @#'api.sdk/max-hosts))]+ (str "host-" i ".example.com"))+ (map :host (mt/user-http-request :crowberto :get 200 "embedding-sdk/react-18-hosts")))))+ (testing "non-admins cannot read it"+ (mt/user-http-request :rasta :get 403 "embedding-sdk/react-18-hosts"))+ (testing "anonymous requests cannot read it"+ (mt/client :get 401 "embedding-sdk/react-18-hosts")))))