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
feat(sdk-bundle): Modular embedding SDK insights collection (#75785)
Mahatthana (Kelvin) Nomsawadi5db67937adf7
diff --git a/.clj-kondo/config/modules/config.edn b/.clj-kondo/config/modules/config.ednindex 72f2bc27a34..5e317d954c7 100644--- a/.clj-kondo/config/modules/config.edn+++ b/.clj-kondo/config/modules/config.edn@@ -194,6 +194,7 @@analytics{:team "UX West":api #{metabase.analytics.api+ metabase.analytics.api.proxymetabase.analytics.coremetabase.analytics.eventmetabase.analytics.initdiff --git a/.github/workflows/embedding-sdk-component-tests.yml b/.github/workflows/embedding-sdk-component-tests.ymlindex beb2c9bbdbc..06868382138 100644--- a/.github/workflows/embedding-sdk-component-tests.yml+++ b/.github/workflows/embedding-sdk-component-tests.yml@@ -38,7 +38,7 @@ jobs:maildev: trueopenldap: falsewebhook: false- snowplow: false+ snowplow: truepostgres: falsemysql: falsemongo: false@@ -190,7 +190,7 @@ jobs:maildev: trueopenldap: falsewebhook: false- snowplow: false+ snowplow: truepostgres: falsemysql: falsemongo: falsediff --git a/bun.lock b/bun.lockindex ef7a7636b2f..cd1e12a25c7 100644--- a/bun.lock+++ b/bun.lock@@ -42,7 +42,7 @@"@popperjs/core": "^2.11.8","@react-oauth/google": "^0.11.1","@reduxjs/toolkit": "^2.5.0",- "@snowplow/browser-tracker": "^3.1.6",+ "@snowplow/browser-tracker": "3.2.0","@tanstack/react-table": "^8.21.3","@tanstack/react-virtual": "^3.13.2","@tippyjs/react": "^4.2.6",@@ -1474,11 +1474,11 @@"@sinonjs/fake-timers": ["@sinonjs/[email protected]", "", { "dependencies": { "@sinonjs/commons": "^1.7.0" } }, "sha512-BPS4ynJW/o92PUR4wgriz2Ud5gpST5vz6GQfMixEDK0Z8ZCUv2M7SkBLykH56T++Xs+8ln9zTGbOvNGIe02/jw=="],- "@snowplow/browser-tracker": ["@snowplow/[email protected]", "", { "dependencies": { "@snowplow/browser-tracker-core": "3.1.6", "@snowplow/tracker-core": "3.1.6", "tslib": "^2.3.0" } }, "sha512-6VY/3cgEvRzE6u52n0OSZR9pSjFzud4cICNIZrH2YVcF8/lCrHKscatBVffALrLShSglSB4FZPG9CtfPCAivow=="],+ "@snowplow/browser-tracker": ["@snowplow/[email protected]", "", { "dependencies": { "@snowplow/browser-tracker-core": "3.2.0", "@snowplow/tracker-core": "3.2.0", "tslib": "^2.3.0" } }, "sha512-k9oabjXpM7qIYM5CnMu1EZ/CbbffBKBK1TJTMJaf2k1F3Xplbyqx9DssN1NzgX+lH9Gc22n+yow+czRyppZOCg=="],- "@snowplow/browser-tracker-core": ["@snowplow/[email protected]", "", { "dependencies": { "@snowplow/tracker-core": "3.1.6", "sha1": "^1.1.1", "tslib": "^2.3.0", "uuid": "^3.4.0" } }, "sha512-IOsQaI5EOaaOHxxgIGAeSZIR7oM8sre0dDjgBwqsUFpQgpha2/c5mP0ui59hXhBzGFlXA+10wml50OXx/YwMCw=="],+ "@snowplow/browser-tracker-core": ["@snowplow/[email protected]", "", { "dependencies": { "@snowplow/tracker-core": "3.2.0", "sha1": "^1.1.1", "tslib": "^2.3.0", "uuid": "^3.4.0" } }, "sha512-20mrp4OtyzXJMrvDjDmiddKnDUjccg3jOzmK/sNIv8jwPNleHct/MTV1dBo8aTkzxR2jcwL55AqnrD4XIQYDVg=="],- "@snowplow/tracker-core": ["@snowplow/[email protected]", "", { "dependencies": { "tslib": "^2.3.0", "uuid": "^3.4.0" } }, "sha512-b2O1xXEqQRzuhIol+3mhk9Xvz/smiW+6pQ3W1fVWonXrYoKtTyak2K+98phj2e0V+H/jUXeviH8adLEdbRkCYA=="],+ "@snowplow/tracker-core": ["@snowplow/[email protected]", "", { "dependencies": { "tslib": "^2.3.0", "uuid": "^3.4.0" } }, "sha512-EsOs8HlWPp3SIFn3TSG5Eo8l/QEU0ZyHVIlvmoQT3fOdsWZVrTK9IlrWi/sA0S43tVxpHKLuiEKgmQIrQXuVyw=="],"@storybook/addon-a11y": ["@storybook/[email protected]", "", { "dependencies": { "@storybook/addon-highlight": "8.5.0", "@storybook/test": "8.5.0", "axe-core": "^4.2.0", "vitest-axe": "^0.1.0" } }, "sha512-dTKlnhOaDsAXxkmHz7m6/qb98IENoaXTCG3fXo2iwJ1xT27fZF+i8fz8oQprLAN5r7xlnz66ARJvEIKJ+Lxjgw=="],@@ -5740,13 +5740,13 @@"@rushstack/ts-command-line/argparse": ["[email protected]", "", { "dependencies": { "sprintf-js": "~1.0.2" } }, "sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg=="],- "@snowplow/browser-tracker/tslib": ["[email protected]", "", {}, "sha512-77EbyPPpMz+FRFRuAFlWMtmgUWGe9UOG2Z25NqCwiIjRhOf5iKGuzSe5P2w1laq+FkRy4p+PCuVkJSGkzTEKVw=="],+ "@snowplow/browser-tracker/tslib": ["[email protected]", "", {}, "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w=="],- "@snowplow/browser-tracker-core/tslib": ["[email protected]", "", {}, "sha512-77EbyPPpMz+FRFRuAFlWMtmgUWGe9UOG2Z25NqCwiIjRhOf5iKGuzSe5P2w1laq+FkRy4p+PCuVkJSGkzTEKVw=="],+ "@snowplow/browser-tracker-core/tslib": ["[email protected]", "", {}, "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w=="],"@snowplow/browser-tracker-core/uuid": ["[email protected]", "", { "bin": { "uuid": "./bin/uuid" } }, "sha512-HjSDRw6gZE5JMggctHBcjVak08+KEVhSIiDzFnT9S9aegmp85S/bReBVTb4QTFaRNptJ9kuYaNhnbNEOkbKb/A=="],- "@snowplow/tracker-core/tslib": ["[email protected]", "", {}, "sha512-77EbyPPpMz+FRFRuAFlWMtmgUWGe9UOG2Z25NqCwiIjRhOf5iKGuzSe5P2w1laq+FkRy4p+PCuVkJSGkzTEKVw=="],+ "@snowplow/tracker-core/tslib": ["[email protected]", "", {}, "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w=="],"@snowplow/tracker-core/uuid": ["[email protected]", "", { "bin": { "uuid": "./bin/uuid" } }, "sha512-HjSDRw6gZE5JMggctHBcjVak08+KEVhSIiDzFnT9S9aegmp85S/bReBVTb4QTFaRNptJ9kuYaNhnbNEOkbKb/A=="],diff --git a/e2e/test-component/scenarios/embedding-sdk/analytics-component-events.cy.spec.tsx b/e2e/test-component/scenarios/embedding-sdk/analytics-component-events.cy.spec.tsxnew file mode 100644index 00000000000..6536b46e6dc--- /dev/null+++ b/e2e/test-component/scenarios/embedding-sdk/analytics-component-events.cy.spec.tsx@@ -0,0 +1,210 @@+import {+ CollectionBrowser,+ CreateQuestion,+ InteractiveQuestion,+} from "@metabase/embedding-sdk-react";++import { SAMPLE_DATABASE } from "e2e/support/cypress_sample_database";+import { createQuestion, updateSetting } from "e2e/support/helpers";+import { getSdkRoot } from "e2e/support/helpers/e2e-embedding-sdk-helpers";+import {+ mountSdkContent,+ mountStaticQuestion,+} from "e2e/support/helpers/embedding-sdk-component-testing";+import { signInAsAdminAndEnableEmbeddingSdk } from "e2e/support/helpers/embedding-sdk-testing";+import { mockAuthProviderAndJwtSignIn } from "e2e/support/helpers/embedding-sdk-testing/embedding-sdk-helpers";++const { ORDERS, ORDERS_ID } = SAMPLE_DATABASE;++const EMBEDDING_SDK_SCHEMA = "iglu:com.metabase/embedding_sdk/jsonschema/1-0-0";++// The SDK tracker posts to /api/analytics-proxy with encodeBase64:false, so the+// Snowplow POST body is plain JSON: { data: [ { ue_pr: "<json>", ... } ] }.+// Each ue_pr is a self-describing unstruct_event whose inner `data` is the+// embedding_sdk event { component, properties, global }. Pull those out.+type SdkEventData = {+ component: string | null;+ properties: Record<string, unknown> | null;+ global: {+ auth_method: string;+ sdk_version: string | null;+ locale_used: boolean;+ };+};++const sdkEventsFromProxyBody = (body: unknown): SdkEventData[] => {+ const rows =+ body && Array.isArray((body as { data?: unknown[] }).data)+ ? (body as { data: Array<{ ue_pr?: string }> }).data+ : [];++ return rows+ .map((row) => {+ try {+ return JSON.parse(row.ue_pr ?? "");+ } catch {+ return null;+ }+ })+ .filter(Boolean)+ .map((unstruct) => unstruct.data) // unstruct_event -> { schema, data }+ .filter((selfDescribing) => selfDescribing?.schema === EMBEDDING_SDK_SCHEMA)+ .map((selfDescribing) => selfDescribing.data as SdkEventData);+};++describe("scenarios > embedding-sdk > analytics — per-mount component events", () => {+ beforeEach(() => {+ signInAsAdminAndEnableEmbeddingSdk();++ createQuestion({+ name: "Analytics events test question",+ query: {+ "source-table": ORDERS_ID,+ aggregation: [["max", ["field", ORDERS.QUANTITY, null]]],+ breakout: [["field", ORDERS.PRODUCT_ID, null]],+ limit: 2,+ },+ }).then(({ body: question }) => {+ cy.wrap(question.id).as("questionId");+ });+ });++ // Capture every POST to the proxy into a closure array so we can assert across+ // the several immediate (bufferSize: 1) posts a single mount produces.+ const interceptAnalyticsProxy = () => {+ const capturedEvents: SdkEventData[] = [];+ cy.intercept("POST", "/api/analytics-proxy", (request) => {+ capturedEvents.push(...sdkEventsFromProxyBody(request.body));+ request.continue();+ }).as("analyticsProxy");+ return capturedEvents;+ };++ it("fires a per-mount component event and a global init beacon through the proxy", () => {+ updateSetting("anon-tracking-enabled", true);+ cy.signOut();+ mockAuthProviderAndJwtSignIn();++ const capturedEvents = interceptAnalyticsProxy();++ mountStaticQuestion();++ // Ensures settings are loaded before the proxy wait (settings-load race guard).+ getSdkRoot().within(() => {+ cy.findByText("Product ID").should("be.visible");+ });++ // Beacon and component event are serialized by Snowplow's executingQueue:+ // event 2 is only sent after event 1's XHR response arrives, so they come+ // in two separate requests. Wait for both before asserting.+ cy.wait(["@analyticsProxy", "@analyticsProxy"]);++ cy.wrap(capturedEvents).should((events: SdkEventData[]) => {+ const componentEvent = events.find(+ (event) => event.component === "StaticQuestion",+ );+ expect(componentEvent, "StaticQuestion mount event").to.exist;+ expect(componentEvent?.global.auth_method, "auth_method global").to.eq(+ "sso",+ );+ expect(componentEvent?.global.sdk_version, "sdk_version global").to.be.a(+ "string",+ );+ });++ cy.wrap(capturedEvents).should((events: SdkEventData[]) => {+ const beacon = events.find((event) => event.component === null);+ expect(beacon, "global init beacon (component: null)").to.exist;+ });+ });++ it("CreateQuestion delegates to InteractiveQuestion — fires id_new event, not CreateQuestion", () => {+ updateSetting("anon-tracking-enabled", true);+ cy.signOut();+ mockAuthProviderAndJwtSignIn();++ const capturedEvents = interceptAnalyticsProxy();++ mountSdkContent(<CreateQuestion />);++ // The beacon fires only once per JS context (module-level singleton); it+ // already fired in the first test, so only the component event is captured here.+ cy.wait("@analyticsProxy");++ cy.wrap(capturedEvents).should((events: SdkEventData[]) => {+ const interactiveQuestionEvent = events.find(+ (event) => event.component === "InteractiveQuestion",+ );+ expect(interactiveQuestionEvent, "InteractiveQuestion mount event").to+ .exist;+ expect(+ interactiveQuestionEvent?.properties?.["id_new"],+ "id_new property",+ ).to.eq("true");+ });++ cy.wrap(capturedEvents).should((events: SdkEventData[]) => {+ const createQuestionEvent = events.find(+ (event) => event.component === "CreateQuestion",+ );+ expect(createQuestionEvent, "no CreateQuestion event").to.be.undefined;+ });+ });++ it("fires one component event per mounted component", () => {+ updateSetting("anon-tracking-enabled", true);+ cy.signOut();+ mockAuthProviderAndJwtSignIn();++ const capturedEvents = interceptAnalyticsProxy();++ cy.get<number>("@questionId").then((questionId) => {+ mountSdkContent(+ <>+ <InteractiveQuestion questionId={questionId} />+ <CollectionBrowser />+ </>,+ );+ });++ // Wait for the question to fully render before asserting analytics (same+ // settings-load race guard as test 1).+ getSdkRoot().within(() => {+ cy.findByText("Product ID").should("be.visible");+ });++ // beacon already fired in test 1 (once per JS context);+ // InteractiveQuestion + CollectionBrowser = 2 component events+ cy.wait(["@analyticsProxy", "@analyticsProxy"]);++ cy.wrap(capturedEvents).should((events: SdkEventData[]) => {+ const interactiveQuestionEvent = events.find(+ (event) => event.component === "InteractiveQuestion",+ );+ expect(interactiveQuestionEvent, "InteractiveQuestion mount event").to+ .exist;++ const collectionBrowserEvent = events.find(+ (event) => event.component === "CollectionBrowser",+ );+ expect(collectionBrowserEvent, "CollectionBrowser mount event").to.exist;+ });+ });++ it("does not fire events when anon-tracking is disabled (opt-out gate)", () => {+ updateSetting("anon-tracking-enabled", false);+ cy.signOut();+ mockAuthProviderAndJwtSignIn();++ const capturedEvents = interceptAnalyticsProxy();++ mountStaticQuestion();++ // Let the question fully render so any (incorrect) tracking would have fired.+ getSdkRoot().within(() => {+ cy.findByText("Product ID").should("be.visible");+ });++ cy.wrap(capturedEvents).should("have.length", 0);+ });+});diff --git a/e2e/test/scenarios/embedding/sdk-iframe-embedding/sdk-iframe-embedding.cy.spec.ts b/e2e/test/scenarios/embedding/sdk-iframe-embedding/sdk-iframe-embedding.cy.spec.tsindex 0fdae9a3070..2f1c051edca 100644--- a/e2e/test/scenarios/embedding/sdk-iframe-embedding/sdk-iframe-embedding.cy.spec.ts+++ b/e2e/test/scenarios/embedding/sdk-iframe-embedding/sdk-iframe-embedding.cy.spec.ts@@ -816,6 +816,32 @@ describe("scenarios > embedding > modular embedding", () => {});});+ it("should not send SDK tracker events through the analytics proxy", () => {+ let proxyCallCount = 0;+ cy.intercept("POST", "/api/analytics-proxy", () => {+ proxyCallCount++;+ }).as("analyticsProxy");++ cy.signOut();+ cy.visit("http://localhost:4000");+ H.loadSdkIframeEmbedTestPage({+ origin: "http://different-than-metabase-instance.com",+ elements: [+ {+ component: "metabase-dashboard",+ attributes: { dashboardId: ORDERS_DASHBOARD_ID },+ },+ ],+ selector: `[dashboard-id="${ORDERS_DASHBOARD_ID}"] > iframe`,+ }).within(() => {+ cy.findByText("Orders in a dashboard").should("be.visible");+ });++ cy.wrap(null).then(() => {+ expect(proxyCallCount).to.eq(0);+ });+ });+it("should not send an modular embedding usage event in the preview", () => {cy.visit(`/question/${ORDERS_QUESTION_ID}`);diff --git a/enterprise/frontend/src/embedding-sdk-ee/auth/auth.ts b/enterprise/frontend/src/embedding-sdk-ee/auth/auth.tsindex 6bd4ab019b1..44edf722073 100644--- a/enterprise/frontend/src/embedding-sdk-ee/auth/auth.ts+++ b/enterprise/frontend/src/embedding-sdk-ee/auth/auth.ts@@ -24,7 +24,7 @@ import type {SdkStoreState,} from "embedding-sdk-bundle/store/types";import type { MetabaseAuthConfig } from "embedding-sdk-bundle/types/auth-config";-import { getBuildInfo } from "embedding-sdk-shared/lib/get-build-info";+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";@@ -279,8 +279,7 @@ function getSdkRequestHeaders(hash?: string): Record<string, string> {"X-Metabase-Client": "embedding-sdk-react",// eslint-disable-next-line metabase/no-literal-metabase-strings -- header name"X-Metabase-Client-Version":- getBuildInfo("METABASE_EMBEDDING_SDK_PACKAGE_BUILD_INFO").version ??- EMBEDDING_SDK_PACKAGE_UNKNOWN_VERSION,+ getSdkPackageVersion() ?? EMBEDDING_SDK_PACKAGE_UNKNOWN_VERSION,// eslint-disable-next-line metabase/no-literal-metabase-strings -- header name...(hash && { "X-Metabase-SDK-JWT-Hash": hash }),};diff --git a/frontend/src/embedding-sdk-bundle/analytics/component-events.ts b/frontend/src/embedding-sdk-bundle/analytics/component-events.tsnew file mode 100644index 00000000000..9b9813a565e--- /dev/null+++ b/frontend/src/embedding-sdk-bundle/analytics/component-events.ts@@ -0,0 +1,196 @@+import { useEffect } from "react";++import { useSdkSelector } from "embedding-sdk-bundle/store";+import { getSdkPackageVersion } from "embedding-sdk-shared/lib/get-build-info";+import { useSetting } from "metabase/common/hooks";+import { isEmbeddingEajs, isEmbeddingSdk } from "metabase/embedding-sdk/config";++import { getSdkAuthMethod, getSdkLocaleUsed, trackSdkEvent } from "./snowplow";++export function useIsTrackingEnabled(): boolean {+ // Default false so we don't fire events during the settings-load window for users who opted out.+ return useSetting("anon-tracking-enabled") ?? false;+}++export const EMBEDDING_SDK_SCHEMA =+ "iglu:com.metabase/embedding_sdk/jsonschema/1-0-0";++// CreateQuestion is intentionally excluded — it renders InteractiveQuestion with+// questionId="new", which already fires an InteractiveQuestion event (id_new: true).+// CreateQuestion is also deprecated in favour of <InteractiveQuestion questionId="new" />.+export type SdkComponentName =+ | "StaticDashboard"+ | "InteractiveDashboard"+ | "EditableDashboard"+ | "StaticQuestion"+ | "InteractiveQuestion"+ | "CollectionBrowser"+ | "MetabotQuestion"+ | "CreateDashboardModal";++// StaticDashboard omits enableEntityNavigation from its public props —+// entity navigation requires drill-through, which static mode doesn't support.+type StaticDashboardProperties = {+ with_title: boolean;+ with_downloads: boolean;+ with_subscriptions: boolean;+ auto_refresh: boolean;+};++type DashboardProperties = StaticDashboardProperties & {+ enable_entity_navigation: boolean;+};++type QuestionBaseProperties = {+ with_title: boolean;+ with_downloads: boolean;+ with_alerts: boolean;+};++// CollectionBrowser and CreateDashboardModal have no configurable dimensions —+// the event itself signals presence. Sending { used: true } was always trivially+// true and added no analytical signal, so we send empty properties instead.+type EmptyProperties = Record<never, never>;++type NewQuestionProperties = QuestionBaseProperties & {+ id_new: boolean;+ id_new_native: boolean;+};++export type SdkComponentProperties = {+ StaticDashboard: StaticDashboardProperties;+ InteractiveDashboard: DashboardProperties;+ EditableDashboard: DashboardProperties;+ StaticQuestion: QuestionBaseProperties | NewQuestionProperties;+ InteractiveQuestion: (QuestionBaseProperties | NewQuestionProperties) & {+ is_save_enabled: boolean;+ };+ CollectionBrowser: EmptyProperties;+ MetabotQuestion: { layout: "auto" | "sidebar" | "stacked" };+ CreateDashboardModal: EmptyProperties;+};++// Centralized defaults. Components pass raw prop values (undefined when the+// user omits an optional prop); the hook fills gaps by merging these defaults+// over only the defined values. id_new and id_new_native are excluded because+// they are always set explicitly by the component.+const SDK_COMPONENT_DEFAULT_PROPERTIES: {+ [C in SdkComponentName]: Partial<SdkComponentProperties[C]>;+} = {+ StaticDashboard: {+ with_title: true,+ with_downloads: false,+ with_subscriptions: false,+ auto_refresh: false,+ },+ InteractiveDashboard: {+ with_title: true,+ with_downloads: false,+ with_subscriptions: false,+ auto_refresh: false,+ enable_entity_navigation: false,+ },+ EditableDashboard: {+ with_title: true,+ with_downloads: false,+ with_subscriptions: false,+ auto_refresh: false,+ enable_entity_navigation: false,+ },+ StaticQuestion: {+ with_title: false,+ with_downloads: false,+ with_alerts: false,+ },+ InteractiveQuestion: {+ with_title: true,+ with_downloads: false,+ with_alerts: false,+ is_save_enabled: true,+ },+ CollectionBrowser: {},+ MetabotQuestion: { layout: "auto" },+ CreateDashboardModal: {},+};++// In-memory dedup registry. Module-scoped so it survives re-renders and+// React 18 StrictMode double-mounts within a single JS load.+const firedKeys = new Set<string>();++// Fire a per-mount component-usage event through the SDK tracker.+//+// Dedup: one event per (componentName, entityId) per JS load. For presence+// components (entityId = null), one event per (componentName, 'presence') per load.+// For new questions the entityId encodes the variant ('new' or 'new-native').+//+// This hook must be called inside a component that is a descendant of+// MetabaseReduxProvider (i.e. inside a ComponentProvider subtree).+//+// Timing: events wait for both anon-tracking-enabled (opt-out gate) and+// sdkTrackerReady (set by ComponentProvider after initSdkTracker completes).+// Without the sdkTrackerReady gate, firing early would either silently drop the+// event (Snowplow discards calls before newTracker runs) or record auth_method+// as undefined because initSdkTracker hasn't written it yet.+export function useTrackSdkComponentMount<C extends SdkComponentName>(+ componentName: C,+ entityId: number | string | null,+ properties: Partial<SdkComponentProperties[C]>,+): void {+ const isTrackingEnabled = useIsTrackingEnabled();+ const isTrackerReady = useSdkSelector((state) => state.sdk.sdkTrackerReady);++ useEffect(() => {+ if (!isEmbeddingSdk() || isEmbeddingEajs()) {+ return;+ }+ if (!isTrackingEnabled || !isTrackerReady) {+ return;+ }++ const dedupKey =+ entityId !== null+ ? `${componentName}:${String(entityId)}`+ : `${componentName}:presence`;++ if (firedKeys.has(dedupKey)) {+ return;+ }+ firedKeys.add(dedupKey);++ const sdkVersion = getSdkPackageVersion();++ const definedProperties = Object.fromEntries(+ Object.entries(properties as Record<string, unknown>).filter(+ ([, value]) => value !== undefined,+ ),+ );+ const mergedProperties = {+ ...SDK_COMPONENT_DEFAULT_PROPERTIES[componentName],+ ...definedProperties,+ } as SdkComponentProperties[C];++ const serializedProperties = Object.fromEntries(+ Object.entries(+ mergedProperties as Record<string, boolean | string | null | undefined>,+ ).map(([key, value]) => [key, value == null ? null : String(value)]),+ );++ trackSdkEvent({+ schema: EMBEDDING_SDK_SCHEMA,+ data: {+ component: componentName,+ properties: serializedProperties,+ global: {+ auth_method: getSdkAuthMethod(),+ sdk_version: sdkVersion,+ locale_used: getSdkLocaleUsed(),+ },+ },+ });+ // deps are intentionally limited to the two gate flags — fires once when both+ // become true, capturing entityId and properties as a snapshot at that moment.+ // adding entityId/properties would re-fire on value changes and could produce+ // two events if entityId transitions from null to a real id after ready.+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [isTrackingEnabled, isTrackerReady]);+}diff --git a/frontend/src/embedding-sdk-bundle/analytics/events.unit.spec.tsx b/frontend/src/embedding-sdk-bundle/analytics/events.unit.spec.tsxnew file mode 100644index 00000000000..0d3837fd416--- /dev/null+++ b/frontend/src/embedding-sdk-bundle/analytics/events.unit.spec.tsx@@ -0,0 +1,206 @@+// jest.mock is hoisted before imports, so jest.fn() must be defined inline.+// External const refs (like `const mockFoo = jest.fn()`) cause TDZ errors.+jest.mock("./snowplow", () => ({+ trackSdkEvent: jest.fn(),+ getSdkAuthMethod: jest.fn(() => "sso"),+ getSdkLocaleUsed: jest.fn(() => false),+}));++jest.mock("embedding-sdk-shared/lib/get-build-info", () => ({+ getSdkPackageVersion: jest.fn(() => "1.2.3"),+}));++import { renderHookWithProviders } from "__support__/ui";+import { sdkReducers } from "embedding-sdk-bundle/store";+import { createMockSdkState } from "embedding-sdk-bundle/test/mocks/state";+import { setupSdkState } from "embedding-sdk-bundle/test/server-mocks/sdk-init";+import { createMockSettings } from "metabase-types/api/mocks";++import type { SdkComponentName } from "./component-events";+import { useTrackSdkComponentMount } from "./component-events";+import { trackSdkEvent } from "./snowplow";++const mockTrackSdkEvent = jest.mocked(trackSdkEvent);++// Unique entity IDs per test so the module-level firedKeys Set never causes+// cross-test interference (no jest.resetModules() needed).+let nextId = 1;+const uniqueId = () => nextId++;++const STUB_DASHBOARD_PROPS = {+ with_title: false,+ with_downloads: false,+ with_subscriptions: false,+ auto_refresh: false,+ enable_entity_navigation: false,+};++interface SetupOptions {+ trackingEnabled?: boolean;+ sdkTrackerReady?: boolean;+ componentName: SdkComponentName;+ entityId?: number | null;+ properties?: Record<string, unknown>;+}++function setup({+ trackingEnabled = true,+ sdkTrackerReady = true,+ componentName,+ entityId = null,+ properties = {},+}: SetupOptions) {+ const { state } = setupSdkState({+ settingValues: createMockSettings({+ "anon-tracking-enabled": trackingEnabled,+ }),+ sdkState: createMockSdkState({ sdkTrackerReady }),+ });++ return renderHookWithProviders(+ () => useTrackSdkComponentMount(componentName, entityId, properties),+ { storeInitialState: state, customReducers: sdkReducers },+ );+}++describe("useTrackSdkComponentMount", () => {+ beforeEach(() => {+ jest.clearAllMocks();+ });++ it("fires one event when tracking is enabled and tracker is ready", () => {+ const entityId = uniqueId();++ setup({+ componentName: "StaticDashboard",+ entityId,+ properties: { ...STUB_DASHBOARD_PROPS, with_title: true },+ });++ expect(mockTrackSdkEvent).toHaveBeenCalledTimes(1);+ expect(mockTrackSdkEvent).toHaveBeenCalledWith(+ expect.objectContaining({+ schema: "iglu:com.metabase/embedding_sdk/jsonschema/1-0-0",+ data: expect.objectContaining({+ component: "StaticDashboard",+ properties: expect.objectContaining({ with_title: "true" }),+ global: {+ auth_method: "sso",+ sdk_version: "1.2.3",+ locale_used: false,+ },+ }),+ }),+ );+ });++ it("does not fire when tracking is disabled", () => {+ setup({+ trackingEnabled: false,+ componentName: "StaticDashboard",+ entityId: uniqueId(),+ properties: STUB_DASHBOARD_PROPS,+ });++ expect(mockTrackSdkEvent).not.toHaveBeenCalled();+ });++ it("does not fire when isTrackingEnabled is true but isTrackerReady is false", () => {+ setup({+ trackingEnabled: true,+ sdkTrackerReady: false,+ componentName: "StaticDashboard",+ entityId: uniqueId(),+ properties: STUB_DASHBOARD_PROPS,+ });++ expect(mockTrackSdkEvent).not.toHaveBeenCalled();+ });++ it("deduplicates — re-renders with same key do not re-fire", () => {+ const entityId = uniqueId();++ const { rerender } = setup({+ componentName: "InteractiveDashboard",+ entityId,+ properties: STUB_DASHBOARD_PROPS,+ });+ rerender();+ rerender();++ expect(mockTrackSdkEvent).toHaveBeenCalledTimes(1);+ });++ it("deduplicates across separate hook instances with same presence key", () => {+ const { state } = setupSdkState({+ settingValues: createMockSettings({ "anon-tracking-enabled": true }),+ sdkState: createMockSdkState({ sdkTrackerReady: true }),+ });+ const renderOptions = {+ storeInitialState: state,+ customReducers: sdkReducers,+ };++ // First mount fires.+ renderHookWithProviders(+ () => useTrackSdkComponentMount("CollectionBrowser", null, {}),+ renderOptions,+ );+ // Second mount — same dedup key (CollectionBrowser:presence), already fired.+ renderHookWithProviders(+ () => useTrackSdkComponentMount("CollectionBrowser", null, {}),+ renderOptions,+ );++ expect(mockTrackSdkEvent).toHaveBeenCalledTimes(1);+ });++ it("fires separate events for different entity IDs", () => {+ const idA = uniqueId();+ const idB = uniqueId();+ const { state } = setupSdkState({+ settingValues: createMockSettings({ "anon-tracking-enabled": true }),+ sdkState: createMockSdkState({ sdkTrackerReady: true }),+ });+ const renderOptions = {+ storeInitialState: state,+ customReducers: sdkReducers,+ };++ renderHookWithProviders(+ () =>+ useTrackSdkComponentMount("StaticDashboard", idA, STUB_DASHBOARD_PROPS),+ renderOptions,+ );+ renderHookWithProviders(+ () =>+ useTrackSdkComponentMount("StaticDashboard", idB, STUB_DASHBOARD_PROPS),+ renderOptions,+ );++ expect(mockTrackSdkEvent).toHaveBeenCalledTimes(2);+ });++ it("uses the correct component name in the emitted event", () => {+ setup({ componentName: "MetabotQuestion", properties: { layout: "auto" } });++ expect(mockTrackSdkEvent).toHaveBeenCalledWith(+ expect.objectContaining({+ data: expect.objectContaining({ component: "MetabotQuestion" }),+ }),+ );+ });++ it("fires a presence event for CreateDashboardModal", () => {+ setup({ componentName: "CreateDashboardModal" });++ expect(mockTrackSdkEvent).toHaveBeenCalledWith(+ expect.objectContaining({+ data: expect.objectContaining({+ component: "CreateDashboardModal",+ properties: {},+ }),+ }),+ );+ });+});diff --git a/frontend/src/embedding-sdk-bundle/analytics/snowplow.ts b/frontend/src/embedding-sdk-bundle/analytics/snowplow.tsnew file mode 100644index 00000000000..2e9b431fe8c--- /dev/null+++ b/frontend/src/embedding-sdk-bundle/analytics/snowplow.ts@@ -0,0 +1,112 @@+import {+ type SelfDescribingJson,+ newTracker,+ trackSelfDescribingEvent,+} from "@snowplow/browser-tracker";++import type { SdkStoreState } from "embedding-sdk-bundle/store/types";++// The SDK runs inside the customer's app. A direct POST to the Snowplow+// collector (`sp.metabase.com`) is cross-origin and blocked by a strict+// `connect-src` CSP. We instead point the tracker at the customer's own+// Metabase instance, which proxies the payload to the collector server-side.+// `connect-src` matches host (not path), so the instance origin — already+// allowlisted for the SDK's data calls — passes with no extra customer config.++// Named tracker, isolated from the main-app tracker ("sp").+const SDK_TRACKER_NAME = "sdk";++export type SdkAuthMethod = "guest" | "api_key" | "sso";++// true = tracker initialized for the first time; false = already running (idempotent call)+type WasJustInitialized = boolean;++let trackerInitialized = false;+let sdkAuthMethod: SdkAuthMethod;+let sdkLocaleUsed: boolean = false;++// Initialize the SDK's Snowplow tracker. Idempotent — safe under StrictMode double-mount.+export function initSdkTracker({+ metabaseInstanceUrl,+ authMethod,+ localeUsed = false,+ store,+}: {+ metabaseInstanceUrl: string;+ authMethod: SdkAuthMethod;+ localeUsed?: boolean;+ store: { getState: () => SdkStoreState };+}): WasJustInitialized {+ if (trackerInitialized) {+ return false;+ }+ trackerInitialized = true;+ sdkAuthMethod = authMethod;+ sdkLocaleUsed = localeUsed;++ newTracker(SDK_TRACKER_NAME, metabaseInstanceUrl, {+ appId: "metabase",+ platform: "web",+ eventMethod: "post",+ contexts: { webPage: true },+ // Plain JSON on the wire. The main-app tracker uses the default (encodeBase64:true);+ // the SDK tracker is new, so there's no legacy format to preserve.+ encodeBase64: false,+ // Deliver through the instance proxy, not the collector's tp2 path.+ postPath: "/api/analytics-proxy",+ // No cookies / localStorage: the SDK must not touch the host page's storage.+ // This also makes cookie-domain config (e.g. discoverRootDomain) irrelevant.+ stateStorageStrategy: "none",+ // Server-side anonymisation: strip IP + network_userid, send the SP-Anonymous header.+ anonymousTracking: { withServerAnonymisation: true },+ // The proxy endpoint uses `Access-Control-Allow-Origin: *`. Wildcard CORS rejects+ // credentialed requests, so credentials must be omitted.+ withCredentials: false,+ plugins: [createSdkInstanceContextPlugin(store)],+ });+ return true;+}++export function getSdkAuthMethod(): SdkAuthMethod | undefined {+ return sdkAuthMethod;+}++export function getSdkLocaleUsed(): boolean {+ return sdkLocaleUsed;+}++// Attaches the instance context to every SDK event. Omits userId — unlike the+// main-app tracker, SDK component usage is tracked at instance granularity;+// the analytics-uuid already identifies the account.+function createSdkInstanceContextPlugin(store: {+ getState: () => SdkStoreState;+}) {+ return {+ contexts(): SelfDescribingJson[] {+ // Settings are guaranteed present: initSdkTracker is only called after+ // isTrackingEnabled, which requires anon-tracking-enabled to be loaded.+ const settings = store.getState().settings?.values;+ const version = settings?.["version"] ?? {};++ return [+ {+ schema: "iglu:com.metabase/instance/jsonschema/1-1-0",+ data: {+ id: settings?.["analytics-uuid"],+ version: {+ tag: (version as { tag?: string }).tag,+ },+ created_at: settings?.["instance-creation"],+ token_features: settings?.["token-features"],+ },+ },+ ];+ },+ };+}++// Send a self-describing event through the SDK tracker. Schema-agnostic: the caller+// supplies the Iglu schema + data, so the transport stays decoupled from the event shape.+export function trackSdkEvent(event: SelfDescribingJson): void {+ trackSelfDescribingEvent({ event }, [SDK_TRACKER_NAME]);+}diff --git a/frontend/src/embedding-sdk-bundle/analytics/snowplow.unit.spec.ts b/frontend/src/embedding-sdk-bundle/analytics/snowplow.unit.spec.tsnew file mode 100644index 00000000000..ca3bb66ead9--- /dev/null+++ b/frontend/src/embedding-sdk-bundle/analytics/snowplow.unit.spec.ts@@ -0,0 +1,192 @@+import type { SelfDescribingJson } from "@snowplow/browser-tracker";++import { createMockSdkState } from "embedding-sdk-bundle/test/mocks/state";+import { createMockSettingsState } from "metabase/redux/store/mocks/settings";+import { createMockState } from "metabase/redux/store/mocks/state";+import type { EnterpriseSettings } from "metabase-types/api";+import { createMockTokenFeatures } from "metabase-types/api/mocks";++const mockNewTracker = jest.fn();+const mockTrackSelfDescribingEvent = jest.fn();++jest.mock("@snowplow/browser-tracker", () => ({+ newTracker: mockNewTracker,+ trackSelfDescribingEvent: mockTrackSelfDescribingEvent,+}));++// Re-import the module under test so its module-scoped init guard resets per test.+const loadModule = () => import("./snowplow");++function makeStore(overrides: Partial<EnterpriseSettings> = {}) {+ return {+ getState: () =>+ createMockState({+ sdk: createMockSdkState(),+ settings: createMockSettingsState({+ "anon-tracking-enabled": true,+ ...overrides,+ }),+ }),+ };+}++describe("embedding-sdk-bundle/analytics/snowplow (CSP transport)", () => {+ beforeEach(() => {+ jest.clearAllMocks();+ jest.resetModules();+ });++ describe("initSdkTracker", () => {+ // Assert only the flags whose absence fails silently in a customer's prod app:+ // proxy path (CSP), server anonymisation (privacy), and no host-page storage.+ // CORS: 3.1.6 hardcoded withCredentials=true with no config option; 3.2.0 added+ // withCredentials as a config, so we pin it false to satisfy wildcard CORS on the proxy.+ // The rest is cosmetic config, not a safety contract.+ it("configures the proxy path, anonymises, and touches no storage", async () => {+ const { initSdkTracker } = await loadModule();++ initSdkTracker({+ metabaseInstanceUrl: "https://metabase.example.com",+ authMethod: "sso",+ localeUsed: false,+ store: makeStore(),+ });++ expect(mockNewTracker).toHaveBeenCalledTimes(1);+ expect(mockNewTracker).toHaveBeenCalledWith(+ "sdk",+ "https://metabase.example.com",+ // Only assert important config keys+ expect.objectContaining({+ postPath: "/api/analytics-proxy",+ stateStorageStrategy: "none",+ anonymousTracking: { withServerAnonymisation: true },+ }),+ );+ });++ it("is idempotent — a second call does not create another tracker", async () => {+ const { initSdkTracker } = await loadModule();++ initSdkTracker({+ metabaseInstanceUrl: "https://metabase.example.com",+ authMethod: "sso",+ localeUsed: false,+ store: makeStore(),+ });+ initSdkTracker({+ metabaseInstanceUrl: "https://metabase.example.com",+ authMethod: "sso",+ localeUsed: false,+ store: makeStore(),+ });++ expect(mockNewTracker).toHaveBeenCalledTimes(1);+ });++ it("wasJustInitialized: true on first call, false on subsequent calls", async () => {+ const { initSdkTracker } = await loadModule();++ const firstResult = initSdkTracker({+ metabaseInstanceUrl: "https://metabase.example.com",+ authMethod: "sso",+ localeUsed: false,+ store: makeStore(),+ });+ const secondResult = initSdkTracker({+ metabaseInstanceUrl: "https://metabase.example.com",+ authMethod: "sso",+ localeUsed: false,+ store: makeStore(),+ });++ expect(firstResult).toBe(true);+ expect(secondResult).toBe(false);+ });++ it("attaches the instance context with analytics-uuid to every event", async () => {+ const { initSdkTracker } = await loadModule();++ initSdkTracker({+ metabaseInstanceUrl: "https://metabase.example.com",+ authMethod: "sso",+ localeUsed: false,+ store: makeStore({+ "analytics-uuid": "test-uuid-123",+ version: { tag: "v0.50.0" },+ "instance-creation": "2024-01-01",+ "token-features": createMockTokenFeatures(),+ }),+ });++ const [, , config] = mockNewTracker.mock.lastCall!;+ const [plugin] = config.plugins;+ const contexts = plugin.contexts();++ expect(contexts).toContainEqual(+ expect.objectContaining({+ schema: "iglu:com.metabase/instance/jsonschema/1-1-0",+ data: expect.objectContaining({ id: "test-uuid-123" }),+ }),+ );+ });+ });++ describe("getSdkAuthMethod", () => {+ it("returns undefined before initSdkTracker is called", async () => {+ const { getSdkAuthMethod } = await loadModule();++ expect(getSdkAuthMethod()).toBeUndefined();+ });++ it("returns the auth method passed to initSdkTracker", async () => {+ const { initSdkTracker, getSdkAuthMethod } = await loadModule();++ initSdkTracker({+ metabaseInstanceUrl: "https://metabase.example.com",+ authMethod: "api_key",+ localeUsed: false,+ store: makeStore(),+ });++ expect(getSdkAuthMethod()).toBe("api_key");+ });+ });++ describe("getSdkLocaleUsed", () => {+ it("returns false before initSdkTracker is called", async () => {+ const { getSdkLocaleUsed } = await loadModule();++ expect(getSdkLocaleUsed()).toBe(false);+ });++ it("returns the locale_used flag passed to initSdkTracker", async () => {+ const { initSdkTracker, getSdkLocaleUsed } = await loadModule();++ initSdkTracker({+ metabaseInstanceUrl: "https://metabase.example.com",+ authMethod: "sso",+ localeUsed: true,+ store: makeStore(),+ });++ expect(getSdkLocaleUsed()).toBe(true);+ });+ });++ describe("trackSdkEvent", () => {+ it("routes to the isolated sdk tracker, not the default", async () => {+ const { trackSdkEvent } = await loadModule();+ const event: SelfDescribingJson = {+ schema: "iglu:com.metabase/embedded_analytics_js/jsonschema/3-0-0",+ data: { event: "setup" },+ };++ trackSdkEvent(event);++ expect(mockTrackSelfDescribingEvent).toHaveBeenCalledWith({ event }, [+ "sdk",+ ]);+ });+ });+});diff --git a/frontend/src/embedding-sdk-bundle/analytics/tracker.ts b/frontend/src/embedding-sdk-bundle/analytics/tracker.tsnew file mode 100644index 00000000000..0a7bc6c8a92--- /dev/null+++ b/frontend/src/embedding-sdk-bundle/analytics/tracker.ts@@ -0,0 +1,80 @@+import { useEffect } from "react";++import {+ EMBEDDING_SDK_SCHEMA,+ useIsTrackingEnabled,+} from "embedding-sdk-bundle/analytics/component-events";+import type { SdkAuthMethod } from "embedding-sdk-bundle/analytics/snowplow";+import {+ getSdkAuthMethod,+ getSdkLocaleUsed,+ initSdkTracker,+ trackSdkEvent,+} from "embedding-sdk-bundle/analytics/snowplow";+import { setSdkTrackerReady } from "embedding-sdk-bundle/store/reducer";+import type { SdkStore } from "embedding-sdk-bundle/store/types";+import type { MetabaseAuthConfig } from "embedding-sdk-bundle/types/auth-config";+import { getSdkPackageVersion } from "embedding-sdk-shared/lib/get-build-info";+import { isEmbeddingEajs } from "metabase/embedding-sdk/config";++export function deriveAuthMethod(+ authConfig: MetabaseAuthConfig,+): SdkAuthMethod {+ if (authConfig.isGuest) {+ return "guest";+ }+ if ("apiKey" in authConfig && authConfig.apiKey) {+ return "api_key";+ }+ return "sso";+}++// Initialize the SDK Snowplow tracker and fire the provider-init adoption beacon.+// Waits for anon-tracking-enabled to be loaded from the instance settings so the+// opt-out gate is respected. Fires once per JS load; idempotent under re-renders.+export function useInitSdkTracker(+ authConfig: MetabaseAuthConfig,+ reduxStore: SdkStore,+ localeUsed: boolean,+) {+ const isTrackingEnabled = useIsTrackingEnabled();++ useEffect(() => {+ if (isEmbeddingEajs() || !isTrackingEnabled) {+ return;+ }++ const authMethod = deriveAuthMethod(authConfig);+ const wasJustInitialized = initSdkTracker({+ metabaseInstanceUrl: authConfig.metabaseInstanceUrl,+ authMethod,+ localeUsed,+ store: reduxStore,+ });++ // setSdkTrackerReady unblocks per-mount hooks in child components. Set it+ // even when wasJustInitialized=false (e.g. multiple providers) so children+ // in a nested provider context can also fire.+ reduxStore.dispatch(setSdkTrackerReady(true));++ if (wasJustInitialized) {+ const sdkVersion = getSdkPackageVersion();++ trackSdkEvent({+ schema: EMBEDDING_SDK_SCHEMA,+ data: {+ component: null,+ properties: null,+ global: {+ auth_method: getSdkAuthMethod(),+ sdk_version: sdkVersion,+ locale_used: getSdkLocaleUsed(),+ },+ },+ });+ }+ // isTrackingEnabled is the only dep: fire once when the opt-out gate becomes+ // known. authConfig and reduxStore are stable across the provider lifetime.+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [isTrackingEnabled]);+}diff --git a/frontend/src/embedding-sdk-bundle/analytics/tracker.unit.spec.tsx b/frontend/src/embedding-sdk-bundle/analytics/tracker.unit.spec.tsxnew file mode 100644index 00000000000..83c5a30fd8a--- /dev/null+++ b/frontend/src/embedding-sdk-bundle/analytics/tracker.unit.spec.tsx@@ -0,0 +1,137 @@+jest.mock("embedding-sdk-bundle/analytics/component-events", () => ({+ ...jest.requireActual("embedding-sdk-bundle/analytics/component-events"),+ useIsTrackingEnabled: jest.fn(),+}));++jest.mock("embedding-sdk-bundle/analytics/snowplow", () => ({+ initSdkTracker: jest.fn(),+ trackSdkEvent: jest.fn(),+ getSdkAuthMethod: jest.fn(),+ getSdkLocaleUsed: jest.fn(),+}));++jest.mock("embedding-sdk-shared/lib/get-build-info", () => ({+ getSdkPackageVersion: jest.fn(() => "1.2.3"),+}));++import { renderHook } from "@testing-library/react";++import { useIsTrackingEnabled } from "embedding-sdk-bundle/analytics/component-events";+import {+ initSdkTracker,+ trackSdkEvent,+} from "embedding-sdk-bundle/analytics/snowplow";+import { setSdkTrackerReady } from "embedding-sdk-bundle/store/reducer";+import type { MetabaseAuthConfig } from "embedding-sdk-bundle/types/auth-config";+import { EMBEDDING_SDK_IFRAME_EMBEDDING_CONFIG } from "metabase/embedding-sdk/config";++import { deriveAuthMethod, useInitSdkTracker } from "./tracker";++const mockUseIsTrackingEnabled = jest.mocked(useIsTrackingEnabled);+const mockInitSdkTracker = jest.mocked(initSdkTracker);+const mockTrackSdkEvent = jest.mocked(trackSdkEvent);++function makeStore() {+ return { dispatch: jest.fn(), getState: jest.fn() } as any;+}++const SSO_AUTH_CONFIG: MetabaseAuthConfig = {+ metabaseInstanceUrl: "https://metabase.example.com",+ fetchRequestToken: jest.fn(),+};++describe("deriveAuthMethod", () => {+ it("returns 'guest' when isGuest is true", () => {+ expect(+ deriveAuthMethod({+ metabaseInstanceUrl: "https://metabase.example.com",+ isGuest: true,+ }),+ ).toBe("guest");+ });++ it("returns 'api_key' when apiKey is present", () => {+ expect(+ deriveAuthMethod({+ metabaseInstanceUrl: "https://metabase.example.com",+ apiKey: "mb_test_key",+ }),+ ).toBe("api_key");+ });++ it("returns 'sso' for JWT/SAML auth configs", () => {+ expect(deriveAuthMethod(SSO_AUTH_CONFIG)).toBe("sso");+ });+});++describe("useInitSdkTracker", () => {+ beforeEach(() => {+ jest.clearAllMocks();+ EMBEDDING_SDK_IFRAME_EMBEDDING_CONFIG.isSimpleEmbedding = false;+ });++ afterEach(() => {+ EMBEDDING_SDK_IFRAME_EMBEDDING_CONFIG.isSimpleEmbedding = false;+ });++ it("does nothing in iframe embed context", () => {+ EMBEDDING_SDK_IFRAME_EMBEDDING_CONFIG.isSimpleEmbedding = true;+ mockUseIsTrackingEnabled.mockReturnValue(true);+ const store = makeStore();++ renderHook(() => useInitSdkTracker(SSO_AUTH_CONFIG, store, false));++ expect(mockInitSdkTracker).not.toHaveBeenCalled();+ expect(store.dispatch).not.toHaveBeenCalled();+ });++ it("does nothing when tracking is disabled", () => {+ mockUseIsTrackingEnabled.mockReturnValue(false);+ const store = makeStore();++ renderHook(() => useInitSdkTracker(SSO_AUTH_CONFIG, store, false));++ expect(mockInitSdkTracker).not.toHaveBeenCalled();+ expect(store.dispatch).not.toHaveBeenCalled();+ });++ it("dispatches setSdkTrackerReady(true) when tracking is enabled", () => {+ mockUseIsTrackingEnabled.mockReturnValue(true);+ mockInitSdkTracker.mockReturnValue(true);+ const store = makeStore();++ renderHook(() => useInitSdkTracker(SSO_AUTH_CONFIG, store, false));++ expect(store.dispatch).toHaveBeenCalledWith(setSdkTrackerReady(true));+ });++ it("dispatches setSdkTrackerReady(true) even when tracker was already initialized", () => {+ mockUseIsTrackingEnabled.mockReturnValue(true);+ mockInitSdkTracker.mockReturnValue(false);+ const store = makeStore();++ renderHook(() => useInitSdkTracker(SSO_AUTH_CONFIG, store, false));++ expect(store.dispatch).toHaveBeenCalledWith(setSdkTrackerReady(true));+ });++ it("fires the init beacon only on first initialization", () => {+ mockUseIsTrackingEnabled.mockReturnValue(true);+ mockInitSdkTracker.mockReturnValue(true);+ const store = makeStore();++ renderHook(() => useInitSdkTracker(SSO_AUTH_CONFIG, store, false));++ expect(mockTrackSdkEvent).toHaveBeenCalledTimes(1);+ });++ it("does not fire the init beacon when tracker was already initialized", () => {+ mockUseIsTrackingEnabled.mockReturnValue(true);+ mockInitSdkTracker.mockReturnValue(false);+ const store = makeStore();++ renderHook(() => useInitSdkTracker(SSO_AUTH_CONFIG, store, false));++ expect(mockTrackSdkEvent).not.toHaveBeenCalled();+ });+});diff --git a/frontend/src/embedding-sdk-bundle/components/public/CollectionBrowser/CollectionBrowser.tsx b/frontend/src/embedding-sdk-bundle/components/public/CollectionBrowser/CollectionBrowser.tsxindex 57a9dc3bdc2..2ee1de8fcaa 100644--- a/frontend/src/embedding-sdk-bundle/components/public/CollectionBrowser/CollectionBrowser.tsx+++ b/frontend/src/embedding-sdk-bundle/components/public/CollectionBrowser/CollectionBrowser.tsx@@ -1,6 +1,7 @@import { type ComponentType, useEffect } from "react";import { t } from "ttag";+import { useTrackSdkComponentMount } from "embedding-sdk-bundle/analytics/component-events";import {CollectionNotFoundError,SdkLoader,@@ -106,6 +107,8 @@ export const CollectionBrowserInner = ({className,style,}: CollectionBrowserProps) => {+ useTrackSdkComponentMount("CollectionBrowser", null, {});+const {baseCollectionId,internalCollectionId,diff --git a/frontend/src/embedding-sdk-bundle/components/public/ComponentProvider/ComponentProvider.tsx b/frontend/src/embedding-sdk-bundle/components/public/ComponentProvider/ComponentProvider.tsxindex 9131ad83b1a..dd7b97cebf6 100644--- a/frontend/src/embedding-sdk-bundle/components/public/ComponentProvider/ComponentProvider.tsx+++ b/frontend/src/embedding-sdk-bundle/components/public/ComponentProvider/ComponentProvider.tsx@@ -2,6 +2,7 @@import { Global } from "@emotion/react";import { type JSX, memo, useEffect, useId, useRef } from "react";+import { useInitSdkTracker } from "embedding-sdk-bundle/analytics/tracker";import { ContentTranslationsProvider } from "embedding-sdk-bundle/components/private/ContentTranslationsProvider";import { SdkThemeProvider } from "embedding-sdk-bundle/components/private/SdkThemeProvider";import { useArePluginsReady } from "embedding-sdk-bundle/hooks/private/use-are-plugins-ready";@@ -105,6 +106,7 @@ export const ComponentProviderInternal = (});useInitPlugins(reduxStore);+ useInitSdkTracker(authConfig, reduxStore, locale != null);useSdkCustomLoader();diff --git a/frontend/src/embedding-sdk-bundle/components/public/CreateDashboardModal/CreateDashboardModal.tsx b/frontend/src/embedding-sdk-bundle/components/public/CreateDashboardModal/CreateDashboardModal.tsxindex 84a7382b3c2..11905db8ed1 100644--- a/frontend/src/embedding-sdk-bundle/components/public/CreateDashboardModal/CreateDashboardModal.tsx+++ b/frontend/src/embedding-sdk-bundle/components/public/CreateDashboardModal/CreateDashboardModal.tsx@@ -1,3 +1,4 @@+import { useTrackSdkComponentMount } from "embedding-sdk-bundle/analytics/component-events";import { withPublicComponentWrapper } from "embedding-sdk-bundle/components/private/PublicComponentWrapper";import {getCollectionIdSlugFromReference,@@ -72,6 +73,8 @@ const CreateDashboardModalInner = ({id: collectionIdSlug,});+ useTrackSdkComponentMount("CreateDashboardModal", null, {});+if (isLocaleLoading || isCollectionQueryLoading) {return null;}diff --git a/frontend/src/embedding-sdk-bundle/components/public/InteractiveQuestion/InteractiveQuestion.tsx b/frontend/src/embedding-sdk-bundle/components/public/InteractiveQuestion/InteractiveQuestion.tsxindex ae1c198bd43..fea24578761 100644--- a/frontend/src/embedding-sdk-bundle/components/public/InteractiveQuestion/InteractiveQuestion.tsx+++ b/frontend/src/embedding-sdk-bundle/components/public/InteractiveQuestion/InteractiveQuestion.tsx@@ -1,6 +1,7 @@import type { FC } from "react";import { useMemo } from "react";+import { useTrackSdkComponentMount } from "embedding-sdk-bundle/analytics/component-events";import { withPublicComponentWrapper } from "embedding-sdk-bundle/components/private/PublicComponentWrapper";import { SdkInternalNavigationBackButton } from "embedding-sdk-bundle/components/private/SdkInternalNavigation/SdkInternalNavigationBackButton";import {@@ -101,16 +102,56 @@ export type InteractiveQuestionComponents = {SqlParametersList: typeof SqlParametersList;};-function InteractiveQuestionInner({- query,- ...rest-}: InteractiveQuestionInternalProps) {+function InteractiveQuestionInner(props: InteractiveQuestionInternalProps) {+ const {+ query,+ questionId,+ title,+ withDownloads,+ isSaveEnabled,+ withAlerts,+ ...rest+ } = props;++ const isNewQuestion = questionId === "new" || questionId === "new-native";+ const trackingEntityId = questionId != null ? questionId : null;++ useTrackSdkComponentMount(+ "InteractiveQuestion",+ trackingEntityId,+ isNewQuestion+ ? {+ id_new: questionId === "new",+ id_new_native: questionId === "new-native",+ is_save_enabled: isSaveEnabled,+ with_title: title !== false,+ with_downloads: withDownloads,+ with_alerts: withAlerts,+ }+ : {+ is_save_enabled: isSaveEnabled,+ with_title: title !== false,+ with_downloads: withDownloads,+ with_alerts: withAlerts,+ },+ );+const deserializedCard = useMemo(() => (query ? deserializeCardFromQuery(query) : undefined),[query],);- return <SdkQuestion {...rest} deserializedCard={deserializedCard} />;+ return (+ <SdkQuestion+ {...rest}+ questionId={questionId}+ title={title}+ withDownloads={withDownloads}+ isSaveEnabled={isSaveEnabled}+ withAlerts={withAlerts}+ deserializedCard={deserializedCard}+ />+ );}export const _InteractiveQuestion = InteractiveQuestionInner;diff --git a/frontend/src/embedding-sdk-bundle/components/public/MetabotQuestion/MetabotQuestion.tsx b/frontend/src/embedding-sdk-bundle/components/public/MetabotQuestion/MetabotQuestion.tsxindex ea4c5f0a34f..9b04a28c153 100644--- a/frontend/src/embedding-sdk-bundle/components/public/MetabotQuestion/MetabotQuestion.tsx+++ b/frontend/src/embedding-sdk-bundle/components/public/MetabotQuestion/MetabotQuestion.tsx@@ -1,5 +1,6 @@import type { ReactNode } from "react";+import { useTrackSdkComponentMount } from "embedding-sdk-bundle/analytics/component-events";import type { UseMetabotResult } from "embedding-sdk-bundle/types/metabot";import type { FunctionSchema } from "embedding-sdk-bundle/types/schema";@@ -22,5 +23,9 @@ export const METABOT_SDK_EE_PLUGIN: {};export const MetabotQuestion = (props: MetabotQuestionProps) => {+ useTrackSdkComponentMount("MetabotQuestion", null, {+ layout: props.layout,+ });+return <METABOT_SDK_EE_PLUGIN.MetabotQuestion {...props} />;};diff --git a/frontend/src/embedding-sdk-bundle/components/public/StaticQuestion/StaticQuestion.tsx b/frontend/src/embedding-sdk-bundle/components/public/StaticQuestion/StaticQuestion.tsxindex 85b2f094911..7627ae5c1e9 100644--- a/frontend/src/embedding-sdk-bundle/components/public/StaticQuestion/StaticQuestion.tsx+++ b/frontend/src/embedding-sdk-bundle/components/public/StaticQuestion/StaticQuestion.tsx@@ -1,5 +1,6 @@import { type FC, type PropsWithChildren, useMemo } from "react";+import { useTrackSdkComponentMount } from "embedding-sdk-bundle/analytics/component-events";import { FlexibleSizeComponent } from "embedding-sdk-bundle/components/private/FlexibleSizeComponent";import { withPublicComponentWrapper } from "embedding-sdk-bundle/components/private/PublicComponentWrapper";import { RenderIfHasContent } from "embedding-sdk-bundle/components/private/RenderIfHasContent/RenderIfHasContent";@@ -131,6 +132,27 @@ const StaticQuestionInner = (children,} = normalizedProps;+ const isNewQuestion = questionId === "new" || questionId === "new-native";+ const trackingEntityId = questionId != null ? questionId : null;++ useTrackSdkComponentMount(+ "StaticQuestion",+ trackingEntityId,+ isNewQuestion+ ? {+ id_new: questionId === "new",+ id_new_native: questionId === "new-native",+ with_title: title !== false,+ with_downloads: withDownloads,+ with_alerts: withAlerts,+ }+ : {+ with_title: title !== false,+ with_downloads: withDownloads,+ with_alerts: withAlerts,+ },+ );+const deserializedCard = useMemo(() => (query ? deserializeCardFromQuery(query) : undefined),[query],diff --git a/frontend/src/embedding-sdk-bundle/components/public/dashboard/EditableDashboard/EditableDashboard.tsx b/frontend/src/embedding-sdk-bundle/components/public/dashboard/EditableDashboard/EditableDashboard.tsxindex bc8e5befffd..36fffcf8e6d 100644--- a/frontend/src/embedding-sdk-bundle/components/public/dashboard/EditableDashboard/EditableDashboard.tsx+++ b/frontend/src/embedding-sdk-bundle/components/public/dashboard/EditableDashboard/EditableDashboard.tsx@@ -1,5 +1,6 @@import { useCallback } from "react";+import { useTrackSdkComponentMount } from "embedding-sdk-bundle/analytics/component-events";import { withPublicComponentWrapper } from "embedding-sdk-bundle/components/private/PublicComponentWrapper";import { SdkInternalNavigationProvider } from "embedding-sdk-bundle/components/private/SdkInternalNavigation/SdkInternalNavigationProvider";import { useSdkInternalNavigation } from "embedding-sdk-bundle/components/private/SdkInternalNavigation/context";@@ -29,6 +30,23 @@ export type EditableDashboardProps = SdkDashboardProps &const EditableDashboardContent = (props: EditableDashboardProps) => {const { push: pushNavigation } = useSdkInternalNavigation();+ const {+ dashboardId,+ withTitle,+ withDownloads,+ withSubscriptions,+ autoRefreshInterval,+ enableEntityNavigation,+ } = props;++ useTrackSdkComponentMount("EditableDashboard", dashboardId, {+ with_title: withTitle,+ with_downloads: withDownloads,+ with_subscriptions: withSubscriptions,+ auto_refresh: autoRefreshInterval != null,+ enable_entity_navigation: enableEntityNavigation,+ });+const dashboardActions: SdkDashboardInnerProps["dashboardActions"] = ({isEditing,}) =>diff --git a/frontend/src/embedding-sdk-bundle/components/public/dashboard/InteractiveDashboard/InteractiveDashboard.tsx b/frontend/src/embedding-sdk-bundle/components/public/dashboard/InteractiveDashboard/InteractiveDashboard.tsxindex c984996e56d..45a54f12472 100644--- a/frontend/src/embedding-sdk-bundle/components/public/dashboard/InteractiveDashboard/InteractiveDashboard.tsx+++ b/frontend/src/embedding-sdk-bundle/components/public/dashboard/InteractiveDashboard/InteractiveDashboard.tsx@@ -1,5 +1,6 @@import { useCallback, useMemo } from "react";+import { useTrackSdkComponentMount } from "embedding-sdk-bundle/analytics/component-events";import { withPublicComponentWrapper } from "embedding-sdk-bundle/components/private/PublicComponentWrapper";import { SdkInternalNavigationProvider } from "embedding-sdk-bundle/components/private/SdkInternalNavigation/SdkInternalNavigationProvider";import { useSdkInternalNavigation } from "embedding-sdk-bundle/components/private/SdkInternalNavigation/context";@@ -35,6 +36,23 @@ export const InteractiveDashboardContent = (const globalPlugins = useSdkSelector(getPlugins);const { push: pushNavigation } = useSdkInternalNavigation();+ const {+ dashboardId,+ withTitle,+ withDownloads,+ withSubscriptions,+ autoRefreshInterval,+ enableEntityNavigation,+ } = props;++ useTrackSdkComponentMount("InteractiveDashboard", dashboardId, {+ with_title: withTitle,+ with_downloads: withDownloads,+ with_subscriptions: withSubscriptions,+ auto_refresh: autoRefreshInterval != null,+ enable_entity_navigation: enableEntityNavigation,+ });+const plugins: MetabasePluginsConfig = useMemo(() => {return { ...globalPlugins, ...props.plugins };}, [globalPlugins, props.plugins]);diff --git a/frontend/src/embedding-sdk-bundle/components/public/dashboard/StaticDashboard/StaticDashboard.tsx b/frontend/src/embedding-sdk-bundle/components/public/dashboard/StaticDashboard/StaticDashboard.tsxindex 3b93fc377ef..d8e09e9b2c1 100644--- a/frontend/src/embedding-sdk-bundle/components/public/dashboard/StaticDashboard/StaticDashboard.tsx+++ b/frontend/src/embedding-sdk-bundle/components/public/dashboard/StaticDashboard/StaticDashboard.tsx@@ -1,3 +1,4 @@+import { useTrackSdkComponentMount } from "embedding-sdk-bundle/analytics/component-events";import { withPublicComponentWrapper } from "embedding-sdk-bundle/components/private/PublicComponentWrapper";import { useNormalizeGuestEmbedQuestionOrDashboardComponentProps } from "embedding-sdk-bundle/hooks/private/use-normalize-guest-embed-question-or-dashboard-component-props";import type { SdkDashboardEntityPublicProps } from "embedding-sdk-bundle/types/dashboard";@@ -33,7 +34,21 @@ const StaticDashboardInner = (props: StaticDashboardProps) => {const normalizedProps =useNormalizeGuestEmbedQuestionOrDashboardComponentProps(props);- const { withDownloads } = normalizedProps;+ const { withDownloads, withTitle, withSubscriptions, autoRefreshInterval } =+ normalizedProps;++ const dashboardId = "dashboardId" in props ? props.dashboardId : undefined;++ useTrackSdkComponentMount(+ "StaticDashboard",+ dashboardId != null ? dashboardId : null,+ {+ with_title: withTitle,+ with_downloads: withDownloads,+ with_subscriptions: withSubscriptions,+ auto_refresh: autoRefreshInterval != null,+ },+ );const getClickActionMode: ClickActionModeGetter = ({ question }) =>getEmbeddingMode({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.tsindex 210d4b9c507..1257abed717 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@@ -15,7 +15,7 @@ import type { MetabaseAuthConfig } from "embedding-sdk-bundle/types";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 { getBuildInfo } from "embedding-sdk-shared/lib/get-build-info";+import { getSdkPackageVersion } from "embedding-sdk-shared/lib/get-build-info";import { api } from "metabase/api/client";import registerDashboardVisualizations from "metabase/dashboard/visualizations/register";import {@@ -100,8 +100,7 @@ export const useInitDataInternal = ({const fetchRefreshTokenFnFromStore = useLazySelector(getFetchRefreshTokenFn);- const sdkPackageVersion =- getBuildInfo("METABASE_EMBEDDING_SDK_PACKAGE_BUILD_INFO").version ?? null;+ const sdkPackageVersion = getSdkPackageVersion();// We have to initialize the API fields before other possible API callsif (api.basename !== authConfig.metabaseInstanceUrl) {diff --git a/frontend/src/embedding-sdk-bundle/store/reducer.ts b/frontend/src/embedding-sdk-bundle/store/reducer.tsindex 859b361b0d8..eadfacff5b7 100644--- a/frontend/src/embedding-sdk-bundle/store/reducer.ts+++ b/frontend/src/embedding-sdk-bundle/store/reducer.ts@@ -57,6 +57,9 @@ export const setUsageProblem = createAction<SdkUsageProblem | null>(const SET_PLUGINS_READY = "sdk/SET_PLUGINS_READY";export const setPluginsReady = createAction<boolean>(SET_PLUGINS_READY);+const SET_SDK_TRACKER_READY = "sdk/SET_SDK_TRACKER_READY";+export const setSdkTrackerReady = createAction<boolean>(SET_SDK_TRACKER_READY);+const SET_INITIAL_DASHBOARD_TAB_ID = "sdk/SET_INITIAL_DASHBOARD_TAB_ID";export const setInitialDashboardTabId = createAction<DashboardTabId | null>(SET_INITIAL_DASHBOARD_TAB_ID,@@ -81,6 +84,7 @@ const initialState: SdkState = {fetchRefreshTokenFn: null,pluginsReady: false,initialDashboardTabId: null,+ sdkTrackerReady: false,};export const sdk = createReducer(initialState, (builder) => {@@ -213,4 +217,8 @@ export const sdk = createReducer(initialState, (builder) => {builder.addCase(setInitialDashboardTabId, (state, action) => {state.initialDashboardTabId = action.payload;});++ builder.addCase(setSdkTrackerReady, (state, action) => {+ state.sdkTrackerReady = action.payload;+ });});diff --git a/frontend/src/embedding-sdk-bundle/store/types.ts b/frontend/src/embedding-sdk-bundle/store/types.tsindex c9629dbc5e6..2b23b7f99a9 100644--- a/frontend/src/embedding-sdk-bundle/store/types.ts+++ b/frontend/src/embedding-sdk-bundle/store/types.ts@@ -53,6 +53,12 @@ export type SdkState = {* cross-dashboard push overwrites this slot anyway.*/initialDashboardTabId: DashboardTabId | null;+ /**+ * True once initSdkTracker has been called and the Snowplow SDK tracker+ * is ready to accept events. Per-mount hooks depend on this flag so they+ * never fire before the provider has wired up the tracker and authMethod.+ */+ sdkTrackerReady: boolean;};export interface SdkStoreState extends State {diff --git a/frontend/src/embedding-sdk-bundle/test/mocks/state.ts b/frontend/src/embedding-sdk-bundle/test/mocks/state.tsindex b456566dd08..763a9a72c8a 100644--- a/frontend/src/embedding-sdk-bundle/test/mocks/state.ts+++ b/frontend/src/embedding-sdk-bundle/test/mocks/state.ts@@ -40,6 +40,7 @@ export const createMockSdkState = ({fetchRefreshTokenFn: null,pluginsReady: true,initialDashboardTabId: null,+ sdkTrackerReady: false,...opts,};};diff --git a/frontend/src/embedding-sdk-shared/lib/get-build-info.ts b/frontend/src/embedding-sdk-shared/lib/get-build-info.tsindex 580fb471589..8ad0adaca88 100644--- a/frontend/src/embedding-sdk-shared/lib/get-build-info.ts+++ b/frontend/src/embedding-sdk-shared/lib/get-build-info.ts@@ -15,3 +15,9 @@ export const getBuildInfo = (buildTime: buildInfo?.buildTime,};};++export function getSdkPackageVersion(): string | null {+ return (+ getBuildInfo("METABASE_EMBEDDING_SDK_PACKAGE_BUILD_INFO").version ?? null+ );+}diff --git a/frontend/src/metabase/analytics/event.ts b/frontend/src/metabase/analytics/event.tsindex 98aeb23756d..1401fd74954 100644--- a/frontend/src/metabase/analytics/event.ts+++ b/frontend/src/metabase/analytics/event.ts@@ -64,12 +64,15 @@ export function trackSchemaEvent<S extends SchemaType>(}if (shouldSendSnowplow) {- Snowplow.trackSelfDescribingEvent({- event: {- schema: `iglu:com.metabase/${schema}/jsonschema/${VERSIONS[schema]}`,- data: event,+ Snowplow.trackSelfDescribingEvent(+ {+ event: {+ schema: `iglu:com.metabase/${schema}/jsonschema/${VERSIONS[schema]}`,+ data: event,+ },},- });+ ["sp"],+ );}if (Settings.get("metaplow-tracking-enabled")) {diff --git a/package.json b/package.jsonindex 467c74a5538..b9d912d5b4d 100644--- a/package.json+++ b/package.json@@ -51,7 +51,7 @@"@popperjs/core": "^2.11.8","@react-oauth/google": "^0.11.1","@reduxjs/toolkit": "^2.5.0",- "@snowplow/browser-tracker": "^3.1.6",+ "@snowplow/browser-tracker": "3.2.0","@tanstack/react-table": "^8.21.3","@tanstack/react-virtual": "^3.13.2","@tippyjs/react": "^4.2.6",diff --git a/snowplow/iglu-client-embedded/schemas/com.metabase/embedding_sdk/jsonschema/1-0-0 b/snowplow/iglu-client-embedded/schemas/com.metabase/embedding_sdk/jsonschema/1-0-0new file mode 100644index 00000000000..c4fe0741ec2--- /dev/null+++ b/snowplow/iglu-client-embedded/schemas/com.metabase/embedding_sdk/jsonschema/1-0-0@@ -0,0 +1,68 @@+{+ "$schema": "http://iglucentral.com/schemas/com.snowplowanalytics.self-desc/schema/jsonschema/1-0-0#",+ "description": "Per-mount component usage event for the Metabase Embedding SDK",+ "self": {+ "vendor": "com.metabase",+ "name": "embedding_sdk",+ "format": "jsonschema",+ "version": "1-0-0"+ },+ "type": "object",+ "properties": {+ "component": {+ "description": "Name of the SDK component that was mounted. Null for provider-init beacon events.",+ "type": [+ "string",+ "null"+ ],+ "maxLength": 1024+ },+ "properties": {+ "description": "Component-specific dimension values captured at mount time. Null for provider-init beacon events.",+ "type": [+ "object",+ "null"+ ],+ "additionalProperties": {+ "description": "String or null value for a tracked component property dimension.",+ "type": [+ "string",+ "null"+ ],+ "maxLength": 1024+ }+ },+ "global": {+ "description": "Session-level flags repeated on each event.",+ "type": "object",+ "properties": {+ "auth_method": {+ "description": "Authentication method used for the embedding. `session` (reuses the current Metabase user session from the cookie) is not applicable to the SDK — SDK users are always pre-authenticated via API key or SSO.",+ "type": "string",+ "enum": [+ "api_key",+ "sso",+ "guest"+ ],+ "maxLength": 1024+ },+ "sdk_version": {+ "description": "SDK package version string.",+ "type": [+ "string",+ "null"+ ],+ "maxLength": 1024+ },+ "locale_used": {+ "description": "Whether the consumer set an explicit locale.",+ "type": "boolean"+ }+ },+ "required": ["auth_method", "sdk_version", "locale_used"],+ "additionalProperties": true+ }+ },+ "required": ["global"],+ "additionalProperties": false+}diff --git a/src/metabase/analytics/api/proxy.clj b/src/metabase/analytics/api/proxy.cljnew file mode 100644index 00000000000..be362eee364--- /dev/null+++ b/src/metabase/analytics/api/proxy.clj@@ -0,0 +1,44 @@+(ns metabase.analytics.api.proxy+ "Public, anonymous Snowplow telemetry passthrough for the Embedding SDK.++ The SDK runs inside the customer's page, where the customer's `connect-src` CSP blocks a direct browser POST to+ the Snowplow collector (`sp.metabase.com`). The SDK instead POSTs the tracker's `tp2` payload here — the same+ instance host its data calls already go to, so it is already CSP-allowlisted — and we forward it to `sp.metabase.com` server-side, where no browser CSP applies.++ Body handling: `wrap-json-body` parses the body before this handler runs, so `body` arrives as a map and we+ re-encode it — not a byte-exact relay. Safe for `tp2` because it has no checksum, all field values are JSON strings+ (base64 blobs survive a parse→encode round-trip), and v1 pins `eventMethod: \"post\"` with a JSON content-type."+ (:require+ [clj-http.client :as http]+ [metabase.analytics.settings :as analytics.settings]+ [metabase.api.macros :as api.macros]+ [metabase.util.json :as json]+ [metabase.util.log :as log]))++(def ^:private forward-timeout-ms 5000)++;; No response schema: the body is an opaque relay of the collector's own response. The tracker drives its retry+;; outbox off the HTTP status, so we forward status + body verbatim; a fabricated schema would be misleading.+;;+#_{:clj-kondo/ignore [:metabase/validate-defendpoint-has-response-schema]}+(api.macros/defendpoint :post "/"+ "Forward a Snowplow `tp2` payload to `sp.metabase.com` server-side, bypassing the customer page's+ `connect-src` CSP."+ [_route-params+ _query-params+ body]+ (let [collector-url (str (analytics.settings/snowplow-url) "/com.snowplowanalytics.snowplow/tp2")]+ (try+ (let [response (http/post collector-url+ {:body (json/encode body)+ :content-type :json+ :connection-timeout forward-timeout-ms+ :socket-timeout forward-timeout-ms+ :throw-exceptions false})]+ ;; Relay status + body unchanged: 2xx clears the tracker's event, non-2xx schedules a retry.+ {:status (:status response)+ :body (:body response)})+ (catch Exception e+ ;; 502 is retryable by the tracker; a fake 2xx would silently drop the event.+ (log/errorf e "analytics-proxy failed forwarding to %s" collector-url)+ {:status 502 :body nil}))))diff --git a/src/metabase/api_routes/routes.clj b/src/metabase/api_routes/routes.cljindex 7309133999d..b9516e5e6e4 100644--- a/src/metabase/api_routes/routes.clj+++ b/src/metabase/api_routes/routes.clj@@ -5,6 +5,7 @@[metabase.activity-feed.api][metabase.agent-api.api][metabase.analytics.api]+ [metabase.analytics.api.proxy][metabase.api-keys.api][metabase.api.docs][metabase.api.macros :as api.macros]@@ -78,6 +79,7 @@metabase.activity-feed.api/keep-memetabase.agent-api.api/keep-memetabase.analytics.api/keep-me+ metabase.analytics.api.proxy/keep-memetabase.api-keys.api/keep-memetabase.api.util/keep-memetabase.bookmarks.api/keep-me@@ -164,6 +166,7 @@"/ai-entity-analysis" metabase.metabot.api.entity-analysis/routes"/alert" (+auth metabase.pulse.api/alert-routes)"/analytics" (+auth 'metabase.analytics.api)+ "/analytics-proxy" (+public-exceptions 'metabase.analytics.api.proxy)"/api-key" (+auth 'metabase.api-keys.api)"/automagic-dashboards" (+auth metabase.xrays.api/automagic-dashboards-routes)"/bookmark" (+auth 'metabase.bookmarks.api)diff --git a/test/metabase/analytics/api/proxy_test.clj b/test/metabase/analytics/api/proxy_test.cljnew file mode 100644index 00000000000..45142836416--- /dev/null+++ b/test/metabase/analytics/api/proxy_test.clj@@ -0,0 +1,83 @@+(ns metabase.analytics.api.proxy-test+ "Integration tests for the public Snowplow telemetry proxy (`POST /api/analytics-proxy`).++ Mirrors `metabase.geojson.api-test`: a public endpoint that forwards an outbound HTTP call, exercised with+ `clj-http.fake/with-fake-routes` to mock the collector and `metabase.test.http-client/client` for anonymous+ requests."+ (:require+ [clj-http.fake :as fake]+ [clojure.test :refer :all]+ [metabase.test :as mt]+ [metabase.test.http-client :as client]+ [metabase.util.json :as json]))++(set! *warn-on-reflection* true)++(def ^:private fake-collector-host "http://fake-collector.test")++(defn- collector-url []+ (str fake-collector-host "/com.snowplowanalytics.snowplow/tp2"))++(def ^:private sample-payload+ "A minimal Snowplow `tp2` envelope shape — schema + an events array."+ {:schema "iglu:com.snowplowanalytics.snowplow/payload_data/jsonschema/1-0-4"+ :data [{:e "ue" :p "web" :tv "js-3.24.6"}]})++(defmacro ^:private with-collector+ "Run `body` with `snowplow-url` pinned to the fake collector host and a fake route that returns `response`.+ When `request-atom` is provided, records the inbound request into it for inspection."+ [& args]+ (if (symbol? (first args))+ (let [[request-atom response & body] args]+ `(mt/with-temporary-setting-values [~'snowplow-url fake-collector-host]+ (fake/with-fake-routes+ {(collector-url) (fn [request#]+ (reset! ~request-atom request#)+ ~response)}+ ~@body)))+ (let [[response & body] args]+ `(mt/with-temporary-setting-values [~'snowplow-url fake-collector-host]+ (fake/with-fake-routes+ {(collector-url) (constantly ~response)}+ ~@body)))))++(deftest anonymous-public-route-test+ (testing "an anonymous POST reaches the handler (no auth required) and gets a 2xx back"+ (with-collector {:status 200 :headers {} :body "{}"}+ ;; client/client with no user = anonymous. A 401 here would mean the route isn't public.+ (is (= {} (client/client :post 200 "analytics-proxy" sample-payload))))))++(deftest forwards-payload-to-collector-test+ (testing "the handler forwards the body to the collector's tp2 endpoint as JSON, semantically unchanged"+ (let [captured (atom nil)]+ (with-collector captured {:status 200 :headers {} :body "{}"}+ (client/client :post 200 "analytics-proxy" sample-payload))+ (testing "outbound URL is sp.metabase.com + tp2 path"+ (is (= (collector-url) (str (name (:scheme @captured)) "://" (:server-name @captured) (:uri @captured)))))+ (testing "outbound body round-trips to the same JSON the SDK sent (re-encode is semantically lossless)"+ (is (= (json/decode (json/encode sample-payload))+ (json/decode (slurp (:body @captured))))))+ (testing "outbound content-type is JSON"+ (is (re-find #"(?i)application/json"+ (get-in @captured [:headers "content-type"] "")))))))++(deftest relays-collector-status-verbatim-test+ (testing "non-2xx status and body are relayed unchanged so the tracker can retry"+ (with-collector {:status 400 :headers {} :body "{\"error\":\"bad payload\"}"}+ (is (= {:error "bad payload"}+ (client/client :post 400 "analytics-proxy" sample-payload))))))++(deftest unreachable-collector-returns-502-test+ (testing "when the collector is unreachable the proxy returns 502 (retryable) rather than throwing"+ (mt/with-temporary-setting-values [snowplow-url fake-collector-host]+ (fake/with-fake-routes+ {(collector-url) (fn [_request]+ (throw (java.net.ConnectException. "connection refused")))}+ (client/client :post 502 "analytics-proxy" sample-payload)))))++(deftest no-client-ip-forwarded-test+ (testing "the proxy does not add X-Forwarded-For (preserves the tracker's server-anonymisation intent)"+ (let [captured (atom nil)]+ (with-collector captured {:status 200 :headers {} :body "{}"}+ (client/client :post 200 "analytics-proxy" sample-payload))+ (is (nil? (get-in @captured [:headers "x-forwarded-for"]))))))