Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(data-warehouse): implement metabase import source (#65631)

Tom Owerse043677b9984
diff --git a/posthog/temporal/data_imports/sources/SOURCES.md b/posthog/temporal/data_imports/sources/SOURCES.md
index 01ff291a99a6..906a9a1772e3 100644
--- a/posthog/temporal/data_imports/sources/SOURCES.md
+++ b/posthog/temporal/data_imports/sources/SOURCES.md
@@ -136,6 +136,7 @@ the row lists both.
| mailjet | HTTP | requests | ✅ |
| matomo | HTTP | requests | ✅ |
| meta_ads | HTTP | requests | ✅ |
+| metabase | HTTP | requests | ✅ |
| mixpanel | HTTP | requests | ✅ |
| mollie | HTTP | requests | ✅ |
| monday | HTTP (GraphQL) | requests | ✅ |
@@ -486,7 +487,6 @@ doesn't conflict with concurrent PRs.
- mention
- mercado_ads
- merge
-- metabase
- metricool
- metronome
- microsoft_dataverse
diff --git a/posthog/temporal/data_imports/sources/common/http/observer.py b/posthog/temporal/data_imports/sources/common/http/observer.py
index fbe6c0cc859f..d39eb67729bd 100644
--- a/posthog/temporal/data_imports/sources/common/http/observer.py
+++ b/posthog/temporal/data_imports/sources/common/http/observer.py
@@ -89,11 +89,15 @@ def record_request(
started_at_monotonic: float,
exception: BaseException | None = None,
redact_values: tuple[str, ...] = (),
+ capture: bool = True,
) -> None:
"""Log + meter a single outbound request. Never raises.
`redact_values` are credential strings masked from the logged URL and the
- captured sample, on top of the name-based scrubbers.
+ captured sample, on top of the name-based scrubbers. `capture=False` keeps the
+ request metered and logged but excludes it from HTTP sample capture — for auth
+ exchanges whose request/response bodies inherently carry secrets the name-based
+ scrubbers can't recognise (e.g. a freshly minted session token).
"""
elapsed_ms = max(0, int((time.monotonic() - started_at_monotonic) * 1000))
method = (request.method or "GET").upper()
@@ -121,7 +125,10 @@ def record_request(
ctx = current_job_context()
_emit_log(record, host=host, url_template=template, ctx=ctx)
_emit_metrics(record, host=host, ctx=ctx)
- _maybe_capture_sample(request, response, record=record, ctx=ctx, exception=exception, redact_values=redact_values)
+ if capture:
+ _maybe_capture_sample(
+ request, response, record=record, ctx=ctx, exception=exception, redact_values=redact_values
+ )
def _emit_log(
diff --git a/posthog/temporal/data_imports/sources/common/http/sampling.py b/posthog/temporal/data_imports/sources/common/http/sampling.py
index 76ff650578b2..4afadf5f6131 100644
--- a/posthog/temporal/data_imports/sources/common/http/sampling.py
+++ b/posthog/temporal/data_imports/sources/common/http/sampling.py
@@ -76,6 +76,7 @@ _AUTH_HEADER_NAMES: frozenset[str] = frozenset(
"x-api-key",
"x-sn-apikey",
"x-auth-token",
+ "x-metabase-session",
"ob-token-v1",
"cookie",
"set-cookie",
diff --git a/posthog/temporal/data_imports/sources/common/http/transport.py b/posthog/temporal/data_imports/sources/common/http/transport.py
index 77b95bff2f71..853e4f3c57f1 100644
--- a/posthog/temporal/data_imports/sources/common/http/transport.py
+++ b/posthog/temporal/data_imports/sources/common/http/transport.py
@@ -45,10 +45,15 @@ class TrackedHTTPAdapter(HTTPAdapter):
logged URL or captured sample — value-based masking that complements the
name-based denylists for auth injected under an unpredictable param/header
name (e.g. an API key in a query param).
+
+ `capture=False` keeps requests metered and logged but excludes them from HTTP
+ sample capture — for auth exchanges whose bodies carry secrets the name-based
+ scrubbers can't recognise (e.g. a minted session token in a generic `id` field).
"""
- def __init__(self, *args: Any, redact_values: tuple[str, ...] = (), **kwargs: Any) -> None:
+ def __init__(self, *args: Any, redact_values: tuple[str, ...] = (), capture: bool = True, **kwargs: Any) -> None:
self._redact_values = redact_values
+ self._capture = capture
super().__init__(*args, **kwargs)
def send(
@@ -84,6 +89,7 @@ class TrackedHTTPAdapter(HTTPAdapter):
started_at_monotonic=started,
exception=exception,
redact_values=self._redact_values,
+ capture=self._capture,
)
except Exception:
# Belt-and-braces: record_request should never raise, but if
@@ -92,7 +98,7 @@ class TrackedHTTPAdapter(HTTPAdapter):
def make_tracked_adapter(
- retry: Retry | None = None, redact_values: tuple[str, ...] = (), **kwargs: Any
+ retry: Retry | None = None, redact_values: tuple[str, ...] = (), capture: bool = True, **kwargs: Any
) -> TrackedHTTPAdapter:
"""Construct a `TrackedHTTPAdapter`.
@@ -100,11 +106,12 @@ def make_tracked_adapter(
truly opt out of retries, pass `retry=Retry(total=0)`. To override with
different retry settings, pass a custom `Retry` instance. Any extra
kwargs are forwarded to `HTTPAdapter.__init__`. `redact_values` are
- credential strings to mask in logged URLs and captured samples.
+ credential strings to mask in logged URLs and captured samples. `capture=False`
+ excludes requests from HTTP sample capture (still metered and logged).
"""
if retry is None:
retry = DEFAULT_RETRY
- return TrackedHTTPAdapter(max_retries=retry, redact_values=redact_values, **kwargs)
+ return TrackedHTTPAdapter(max_retries=retry, redact_values=redact_values, capture=capture, **kwargs)
class _NoRedirectSession(requests.Session):
@@ -131,6 +138,7 @@ def make_tracked_session(
headers: dict[str, str] | None = None,
redact_values: tuple[str, ...] = (),
allow_redirects: bool = True,
+ capture: bool = True,
) -> requests.Session:
"""Return a fresh `requests.Session` with tracked HTTP/HTTPS adapters.
@@ -141,9 +149,12 @@ def make_tracked_session(
predict (e.g. an API key in a query param).
`allow_redirects=False` returns a session that never follows redirects — an
SSRF boundary for sources that fetch user-supplied hosts (see `_NoRedirectSession`).
+ `capture=False` excludes the session's requests from HTTP sample capture (still
+ metered and logged) — for auth exchanges whose bodies carry secrets the name-based
+ scrubbers can't recognise (e.g. a minted session token in a generic `id` field).
"""
session: requests.Session = requests.Session() if allow_redirects else _NoRedirectSession()
- adapter = make_tracked_adapter(retry=retry, redact_values=redact_values)
+ adapter = make_tracked_adapter(retry=retry, redact_values=redact_values, capture=capture)
session.mount("https://", adapter)
session.mount("http://", adapter)
if headers:
diff --git a/posthog/temporal/data_imports/sources/common/test/test_http_observer.py b/posthog/temporal/data_imports/sources/common/test/test_http_observer.py
index 20bb87fef16e..04e7bab2efe3 100644
--- a/posthog/temporal/data_imports/sources/common/test/test_http_observer.py
+++ b/posthog/temporal/data_imports/sources/common/test/test_http_observer.py
@@ -325,6 +325,16 @@ def test_sample_capture_called_with_context_and_response(job_ctx):
assert kwargs["ctx"].team_id == 99
+def test_sample_capture_skipped_when_capture_disabled(job_ctx):
+ request = _make_request()
+ response = _make_response(status_code=200)
+
+ with patch("posthog.temporal.data_imports.sources.common.http.observer.maybe_capture") as capture:
+ record_request(request, response, started_at_monotonic=time.monotonic(), capture=False)
+
+ capture.assert_not_called()
+
+
def test_observer_swallows_sampling_failures(job_ctx):
"""Sampling exception must not leak."""
request = _make_request()
diff --git a/posthog/temporal/data_imports/sources/common/test/test_http_sampling.py b/posthog/temporal/data_imports/sources/common/test/test_http_sampling.py
index dd3cf5ae8b62..fb481278a860 100644
--- a/posthog/temporal/data_imports/sources/common/test/test_http_sampling.py
+++ b/posthog/temporal/data_imports/sources/common/test/test_http_sampling.py
@@ -397,6 +397,7 @@ def test_sample_payload_preserves_json_body_keys():
"X-API-Key",
"x-sn-apikey",
"x-auth-token",
+ "X-Metabase-Session",
"Cookie",
"Set-Cookie",
"Proxy-Authorization",
diff --git a/posthog/temporal/data_imports/sources/common/test/test_http_transport.py b/posthog/temporal/data_imports/sources/common/test/test_http_transport.py
index eb666706a977..1ce2e65d2c11 100644
--- a/posthog/temporal/data_imports/sources/common/test/test_http_transport.py
+++ b/posthog/temporal/data_imports/sources/common/test/test_http_transport.py
@@ -134,6 +134,24 @@ def test_send_defaults_redact_values_to_empty(mock_record, fake_http_send):
assert mock_record.call_args.kwargs["redact_values"] == ()
+def test_send_captures_by_default(mock_record, fake_http_send):
+ session = make_tracked_session()
+
+ with fake_http_send(_fake_response(status_code=200, body=b"ok")):
+ session.get("https://api.example.com/v1/ok")
+
+ assert mock_record.call_args.kwargs["capture"] is True
+
+
+def test_send_forwards_capture_disabled_to_record(mock_record, fake_http_send):
+ session = make_tracked_session(capture=False)
+
+ with fake_http_send(_fake_response(status_code=200, body=b"ok")):
+ session.get("https://api.example.com/v1/ok")
+
+ assert mock_record.call_args.kwargs["capture"] is False
+
+
def test_send_records_request_for_2xx(mock_record, fake_http_send):
session = make_tracked_session()
diff --git a/posthog/temporal/data_imports/sources/generated_configs.py b/posthog/temporal/data_imports/sources/generated_configs.py
index 6214cf3460c2..fde7f941db7a 100644
--- a/posthog/temporal/data_imports/sources/generated_configs.py
+++ b/posthog/temporal/data_imports/sources/generated_configs.py
@@ -69,6 +69,14 @@ class HubspotCustomPropertiesConfig(config.Config):
meetings_properties: str | None = None
+class MetabaseAuthMethodConfig(config.Config):
+ selection: Literal["api_key", "session"] = "api_key"
+ api_key: str | None = None
+ username: str | None = None
+ password: str | None = None
+
+
@config.config
class ServiceNowAuthMethodConfig(config.Config):
selection: Literal["basic", "api_key"] = "basic"
@@ -1869,7 +1877,8 @@ class MetaAdsSourceConfig(config.Config):
@config.config
class MetabaseSourceConfig(config.Config):
- pass
+ host: str
+ auth_method: MetabaseAuthMethodConfig
@config.config
diff --git a/posthog/temporal/data_imports/sources/metabase/canonical_descriptions.py b/posthog/temporal/data_imports/sources/metabase/canonical_descriptions.py
new file mode 100644
index 000000000000..b3cc291cc814
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/metabase/canonical_descriptions.py
@@ -0,0 +1,97 @@
+from posthog.temporal.data_imports.sources.common.canonical_descriptions import CanonicalDescriptions
+
+# Sourced from the Metabase API reference (https://www.metabase.com/docs/latest/api-documentation).
+# Partial coverage is fine — any endpoint, column, or table-level description not listed here falls
+# back to the LLM enrichment pass.
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "cards": {
+ "description": 'Saved questions ("cards") — individual queries or visualizations saved in Metabase.',
+ "docs_url": "https://www.metabase.com/docs/latest/api/card",
+ "columns": {
+ "id": "Unique identifier for the card.",
+ "name": "Display name of the saved question.",
+ "description": "Optional human description of the card.",
+ "collection_id": "Id of the collection the card lives in (null for the root collection).",
+ "database_id": "Id of the database the card queries.",
+ "table_id": "Id of the primary table the card queries, when applicable.",
+ "query_type": 'Whether the card uses the query builder ("query") or native SQL ("native").',
+ "display": "Visualization type (e.g. table, line, bar, scalar).",
+ "creator_id": "Id of the user who created the card.",
+ "archived": "Whether the card has been archived.",
+ "created_at": "Timestamp when the card was created.",
+ "updated_at": "Timestamp when the card was last updated.",
+ },
+ },
+ "dashboards": {
+ "description": "Dashboards — collections of cards arranged on a grid.",
+ "docs_url": "https://www.metabase.com/docs/latest/api/dashboard",
+ "columns": {
+ "id": "Unique identifier for the dashboard.",
+ "name": "Display name of the dashboard.",
+ "description": "Optional human description of the dashboard.",
+ "collection_id": "Id of the collection the dashboard lives in (null for the root collection).",
+ "creator_id": "Id of the user who created the dashboard.",
+ "archived": "Whether the dashboard has been archived.",
+ "created_at": "Timestamp when the dashboard was created.",
+ "updated_at": "Timestamp when the dashboard was last updated.",
+ },
+ },
+ "collections": {
+ "description": "Collections — folders that organize cards, dashboards, and other collections.",
+ "docs_url": "https://www.metabase.com/docs/latest/api/collection",
+ "columns": {
+ "id": 'Unique identifier for the collection (may be the string "root").',
+ "name": "Display name of the collection.",
+ "description": "Optional human description of the collection.",
+ "slug": "URL-friendly slug derived from the name.",
+ "color": "Hex color used for the collection's icon.",
+ "location": "Materialized path of ancestor collection ids.",
+ "personal_owner_id": "User id when this is a user's personal collection, else null.",
+ "archived": "Whether the collection has been archived.",
+ },
+ },
+ "databases": {
+ "description": "Databases connected to the Metabase instance that cards and dashboards query against.",
+ "docs_url": "https://www.metabase.com/docs/latest/api/database",
+ "columns": {
+ "id": "Unique identifier for the database connection.",
+ "name": "Display name of the database connection.",
+ "engine": "Database engine (e.g. postgres, mysql, bigquery).",
+ "is_sample": "Whether this is Metabase's bundled sample database.",
+ "is_on_demand": "Whether field values are cached on demand rather than on a schedule.",
+ "created_at": "Timestamp when the database connection was created.",
+ "updated_at": "Timestamp when the database connection was last updated.",
+ },
+ },
+ "users": {
+ "description": "Metabase user accounts.",
+ "docs_url": "https://www.metabase.com/docs/latest/api/user",
+ "columns": {
+ "id": "Unique identifier for the user.",
+ "email": "User's email address (login).",
+ "first_name": "User's first name.",
+ "last_name": "User's last name.",
+ "common_name": "Full display name.",
+ "is_superuser": "Whether the user is an administrator.",
+ "is_active": "Whether the account is active (not deactivated).",
+ "is_qbnewb": "Whether the user has not yet dismissed the query-builder onboarding.",
+ "last_login": "Timestamp of the user's most recent login.",
+ "date_joined": "Timestamp when the account was created.",
+ },
+ },
+ "native_query_snippets": {
+ "description": "Reusable native (SQL) query snippets that can be inserted into native questions.",
+ "docs_url": "https://www.metabase.com/docs/latest/api/native-query-snippet",
+ "columns": {
+ "id": "Unique identifier for the snippet.",
+ "name": "Display name of the snippet.",
+ "description": "Optional human description of the snippet.",
+ "content": "The SQL fragment the snippet expands to.",
+ "collection_id": "Id of the snippet collection it belongs to, if any.",
+ "creator_id": "Id of the user who created the snippet.",
+ "archived": "Whether the snippet has been archived.",
+ "created_at": "Timestamp when the snippet was created.",
+ "updated_at": "Timestamp when the snippet was last updated.",
+ },
+ },
+}
diff --git a/posthog/temporal/data_imports/sources/metabase/metabase.py b/posthog/temporal/data_imports/sources/metabase/metabase.py
new file mode 100644
index 000000000000..ef12b173fe69
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/metabase/metabase.py
@@ -0,0 +1,282 @@
+import re
+import dataclasses
+from collections.abc import Iterator
+from typing import Any, Optional
+from urllib.parse import urlencode, urlparse
+
+import requests
+import structlog
+from structlog.types import FilteringBoundLogger
+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
+
+from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceResponse
+from posthog.temporal.data_imports.sources.common.http import make_tracked_session
+from posthog.temporal.data_imports.sources.common.mixins import _is_host_safe
+from posthog.temporal.data_imports.sources.metabase.settings import METABASE_ENDPOINTS, MetabaseEndpointConfig
+
+REQUEST_TIMEOUT_SECONDS = 60
+MAX_RETRIES = 5
+
+HOST_NOT_ALLOWED_ERROR = "Metabase host is not allowed"
+
+API_KEY_AUTH = "api_key"
+SESSION_AUTH = "session"
+
+# Loopback hosts where plaintext HTTP carries no network-exposure risk (local dev / self-hosted on the
+# same box). Every other host is forced to HTTPS so credentials never traverse a network in cleartext.
+LOOPBACK_HOSTS = {"localhost", "127.0.0.1", "::1"}
+
+
+class MetabaseRetryableError(Exception):
+ pass
+
+
+class MetabaseHostNotAllowedError(Exception):
+ pass
+
+
+class MetabaseAuthError(Exception):
+ """Raised when credentials are rejected (bad API key, or username/password that won't mint a
+ session). Deterministic — retrying never fixes it — so it surfaces via get_non_retryable_errors."""
+
+ pass
+
+
+class MetabaseAuth:
+ # "api_key" sends a static X-API-Key header; "session" mints a short-lived token via
+ # POST /api/session and sends it as X-Metabase-Session (for instances older than v0.47).
+ method: str
+ api_key: Optional[str] = None
+ username: Optional[str] = None
+ password: Optional[str] = None
+
+
+def normalize_host(host: str) -> str:
+ """Turn whatever the user typed into a bare instance base URL (scheme + host, no path).
+
+ Accepts ``https://company.metabaseapp.com``, ``company.metabaseapp.com``,
+ ``https://company.metabaseapp.com/api`` and returns ``https://company.metabaseapp.com``.
+ Defaults to https when no scheme is given, and forces a plaintext ``http://`` host to
+ ``https://`` so credentials are never sent over the network in cleartext — except for
+ loopback hosts (local dev / self-hosted on the same box), which are left untouched.
+ """
+ host = host.strip()
+ if not re.match(r"^https?://", host, flags=re.IGNORECASE):
+ host = f"https://{host}"
+ parsed = urlparse(host)
+ scheme = parsed.scheme.lower()
+ if scheme == "http" and (parsed.hostname or "").lower() not in LOOPBACK_HOSTS:
+ scheme = "https"
+ # Keep only scheme + host:port — urlparse drops any trailing path/slashes (e.g. "/api").
+ return f"{scheme}://{parsed.netloc}"
+
+
+def _hostname(host: str) -> str:
+ return (urlparse(normalize_host(host)).hostname or "").lower()
+
+
+def _redact_values_for_data_requests(auth: MetabaseAuth, headers: dict[str, str]) -> tuple[str, ...]:
+ """Credential strings to value-mask in any captured data-request sample, on top of the
+ name-based header/body scrubbers. Covers the static secret (API key, or username/password)
+ plus the minted session token from ``headers`` — value-based defense-in-depth in case a
+ credential ever echoes into a response body."""
+ values: list[str] = []
+ if auth.method == API_KEY_AUTH:
+ if auth.api_key:
+ values.append(auth.api_key)
+ else:
+ values.extend(v for v in (auth.username, auth.password) if v)
+ token = headers.get("X-Metabase-Session")
+ if token:
+ values.append(token)
+ return tuple(values)
+
+
+def _resolve_auth_headers(base_url: str, auth: MetabaseAuth, logger: FilteringBoundLogger) -> dict[str, str]:
+ """Build the auth header for every subsequent request.
+
+ API-key auth is a static header. Session auth exchanges username/password for a token via
+ POST /api/session and sends it as X-Metabase-Session. The token is minted per sync; Metabase
+ session tokens expire (~14 days) so we never persist them.
+ """
+ if auth.method == API_KEY_AUTH:
+ if not auth.api_key:
+ raise MetabaseAuthError("Missing Metabase API key")
+ return {"x-api-key": auth.api_key, "Accept": "application/json"}
+
+ if not auth.username or not auth.password:
+ raise MetabaseAuthError("Missing Metabase username or password")
+
+ # Mint on a capture-disabled session: the request body carries the password and the response
+ # body carries the freshly minted token under the generic key "id", neither of which the
+ # name-based body scrubbers recognise. Excluding this one exchange from sample capture keeps
+ # both out of any captured sample; every later request sends the token via the
+ # X-Metabase-Session header, which is on the capture denylist.
+ session = make_tracked_session(allow_redirects=False, capture=False)
+ try:
+ response = session.post(
+ f"{base_url}/api/session",
+ json={"username": auth.username, "password": auth.password},
+ timeout=REQUEST_TIMEOUT_SECONDS,
+ allow_redirects=False,
+ )
+ except requests.exceptions.RequestException as e:
+ raise MetabaseRetryableError(f"Metabase session request failed: {e}") from e
+
+ if response.status_code in (400, 401, 403):
+ raise MetabaseAuthError("Invalid Metabase username or password")
+ if response.status_code == 429 or response.status_code >= 500:
+ raise MetabaseRetryableError(f"Metabase session error (retryable): status={response.status_code}")
+ if not response.ok:
+ # Unexpected non-auth status (e.g. 404 wrong path, 422). Surface as a typed retryable error
+ # rather than letting raise_for_status() leak an HTTPError past callers' except clauses.
+ logger.error(f"Metabase session error: status={response.status_code}, body={response.text}")
+ raise MetabaseRetryableError(f"Metabase session error (retryable): status={response.status_code}")
+
+ token = response.json().get("id")
+ if not token:
+ raise MetabaseAuthError("Metabase session response did not contain a token")
+ return {"X-Metabase-Session": token, "Accept": "application/json"}
+
+
+def _extract_items(data: Any) -> list[dict[str, Any]]:
+ """Normalize Metabase's two list shapes into a flat list of records.
+
+ Some endpoints (``/api/card``, ``/api/dashboard``, ``/api/collection``) return a bare JSON
+ array; others (``/api/database``, ``/api/user``) wrap it as ``{"data": [...], "total": N}``.
+ """
+ if isinstance(data, list):
+ return [item for item in data if isinstance(item, dict)]
+ if isinstance(data, dict) and isinstance(data.get("data"), list):
+ return [item for item in data["data"] if isinstance(item, dict)]
+ return []
+
+
+def validate_credentials(
+ host: str, auth: MetabaseAuth, team_id: Optional[int] = None, schema_name: Optional[str] = None
+) -> tuple[bool, str | None]:
+ """Confirm the credentials are genuine with a cheap ``/api/user/current`` probe.
+
+ ``schema_name`` is unused here (every endpoint shares one instance-wide auth), but kept for the
+ base-class signature. The host is customer-controlled, so we block internal/private addresses
+ (SSRF, cloud only) and refuse to follow redirects.
+ """
+ try:
+ base_url = normalize_host(host)
+ except Exception:
+ return False, "Invalid Metabase host"
+
+ hostname = _hostname(host)
+ if not hostname or not re.match(r"^[A-Za-z0-9.\-]+$", hostname):
+ return False, "Invalid Metabase host"
+
+ if team_id is not None:
+ host_ok, host_err = _is_host_safe(hostname, team_id)
+ if not host_ok:
+ return False, host_err or HOST_NOT_ALLOWED_ERROR
+
+ try:
+ headers = _resolve_auth_headers(base_url, auth, structlog.get_logger())
+ except (MetabaseAuthError, MetabaseRetryableError) as e:
+ return False, str(e)
+
+ session = make_tracked_session(redact_values=_redact_values_for_data_requests(auth, headers))
+ try:
+ response = session.get(f"{base_url}/api/user/current", headers=headers, timeout=10, allow_redirects=False)
+ except requests.exceptions.RequestException as e:
+ return False, str(e)
+
+ if response.is_redirect or response.is_permanent_redirect:
+ return False, HOST_NOT_ALLOWED_ERROR
+ if response.status_code == 200:
+ return True, None
+ if response.status_code == 401:
+ return False, "Invalid Metabase credentials"
+ if response.status_code == 403:
+ # Valid credentials, missing permission for this probe — let source creation through.
+ if schema_name is None:
+ return True, None
+ return False, "Metabase credentials lack the required permissions"
+
+ try:
+ body = response.json()
+ return False, body.get("message", response.text)
+ except Exception:
+ return False, response.text
+
+
+def get_rows(
+ host: str,
+ auth: MetabaseAuth,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ team_id: int,
+) -> Iterator[list[dict[str, Any]]]:
+ config = METABASE_ENDPOINTS[endpoint]
+ base_url = normalize_host(host)
+
+ # Re-check at run time (not just source-create) in case the host was edited or now resolves to
+ # an internal address (SSRF / DNS rebinding). Only enforced on cloud.
+ host_ok, host_err = _is_host_safe(_hostname(host), team_id)
+ if not host_ok:
+ raise MetabaseHostNotAllowedError(host_err or HOST_NOT_ALLOWED_ERROR)
+
+ headers = _resolve_auth_headers(base_url, auth, logger)
+ session = make_tracked_session(redact_values=_redact_values_for_data_requests(auth, headers))
+
+ url = f"{base_url}{config.path}"
+ if config.params:
+ url = f"{url}?{urlencode(config.params)}"
+
+ @retry(
+ retry=retry_if_exception_type((MetabaseRetryableError, requests.ReadTimeout, requests.ConnectionError)),
+ stop=stop_after_attempt(MAX_RETRIES),
+ wait=wait_exponential_jitter(initial=1, max=30),
+ reraise=True,
+ )
+ def fetch(page_url: str) -> requests.Response:
+ # Don't follow redirects: a customer-controlled host could 3xx to an internal address,
+ # bypassing the host check above (SSRF).
+ response = session.get(page_url, headers=headers, timeout=REQUEST_TIMEOUT_SECONDS, allow_redirects=False)
+
+ if response.status_code == 429 or response.status_code >= 500:
+ raise MetabaseRetryableError(
+ f"Metabase API error (retryable): status={response.status_code}, url={page_url}"
+ )
+ if response.is_redirect or response.is_permanent_redirect:
+ raise MetabaseHostNotAllowedError(
+ f"Metabase API returned an unexpected redirect (status={response.status_code}); refusing to follow it"
+ )
+ if not response.ok:
+ logger.error(f"Metabase API error: status={response.status_code}, body={response.text}, url={page_url}")
+ response.raise_for_status()
+
+ return response
+
+ # Metabase list endpoints are unpaginated — one request returns the whole collection.
+ response = fetch(url)
+ items = _extract_items(response.json())
+ if items:
+ yield items
+
+
+def metabase_source(
+ host: str,
+ auth: MetabaseAuth,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ team_id: int,
+) -> SourceResponse:
+ config: MetabaseEndpointConfig = METABASE_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(host=host, auth=auth, endpoint=endpoint, logger=logger, team_id=team_id),
+ primary_keys=config.primary_keys,
+ partition_count=1,
+ partition_size=1,
+ partition_mode="datetime" if config.partition_key else None,
+ partition_format="week" if config.partition_key else None,
+ partition_keys=[config.partition_key] if config.partition_key else None,
+ )
diff --git a/posthog/temporal/data_imports/sources/metabase/settings.py b/posthog/temporal/data_imports/sources/metabase/settings.py
new file mode 100644
index 000000000000..3c596f2c28df
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/metabase/settings.py
@@ -0,0 +1,33 @@
+from dataclasses import dataclass, field
+from typing import Optional
+
+
+@dataclass
+class MetabaseEndpointConfig:
+ name: str
+ path: str
+ primary_keys: list[str] = field(default_factory=lambda: ["id"])
+ # Stable creation-time field used for datetime partitioning. Left None when the resource has no
+ # reliably-present creation timestamp (e.g. collections, whose `id` may be the string "root").
+ partition_key: Optional[str] = None
+ # Extra query params sent on the list request. Empty for every endpoint today — Metabase list
+ # endpoints take no required filters and we deliberately avoid version-specific optional params.
+ params: dict[str, str] = field(default_factory=dict)
+
+
+# Metabase list endpoints return the full collection in a single response — there is no pagination
+# and no server-side timestamp filter, so every schema is full-refresh only. The stream set mirrors
+# the canonical Metabase connector (cards, dashboards, collections, databases, users, snippets).
+METABASE_ENDPOINTS: dict[str, MetabaseEndpointConfig] = {
+ "cards": MetabaseEndpointConfig(name="cards", path="/api/card", partition_key="created_at"),
+ "dashboards": MetabaseEndpointConfig(name="dashboards", path="/api/dashboard", partition_key="created_at"),
+ # Collection ids can be the literal string "root" and the resource has no creation timestamp.
+ "collections": MetabaseEndpointConfig(name="collections", path="/api/collection"),
+ "databases": MetabaseEndpointConfig(name="databases", path="/api/database", partition_key="created_at"),
+ "users": MetabaseEndpointConfig(name="users", path="/api/user", partition_key="date_joined"),
+ "native_query_snippets": MetabaseEndpointConfig(
+ name="native_query_snippets", path="/api/native-query-snippet", partition_key="created_at"
+ ),
+}
+
+ENDPOINTS = tuple(METABASE_ENDPOINTS.keys())
diff --git a/posthog/temporal/data_imports/sources/metabase/source.py b/posthog/temporal/data_imports/sources/metabase/source.py
index 7ca85baed732..822e0afd61ab 100644
--- a/posthog/temporal/data_imports/sources/metabase/source.py
+++ b/posthog/temporal/data_imports/sources/metabase/source.py
@@ -1,14 +1,31 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
DataWarehouseSourceCategory,
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
+ SourceFieldSelectConfig,
+ SourceFieldSelectConfigOption,
)
+from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceInputs, SourceResponse
from posthog.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from posthog.temporal.data_imports.sources.common.canonical_descriptions import CanonicalDescriptions
from posthog.temporal.data_imports.sources.common.registry import SourceRegistry
+from posthog.temporal.data_imports.sources.common.schema import SourceSchema
from posthog.temporal.data_imports.sources.generated_configs import MetabaseSourceConfig
+from posthog.temporal.data_imports.sources.metabase.metabase import (
+ API_KEY_AUTH,
+ HOST_NOT_ALLOWED_ERROR,
+ SESSION_AUTH,
+ MetabaseAuth,
+ metabase_source,
+ validate_credentials as validate_metabase_credentials,
+)
+from posthog.temporal.data_imports.sources.metabase.settings import ENDPOINTS
from products.data_warehouse.backend.types import ExternalDataSourceType
@@ -25,7 +42,136 @@ class MetabaseSource(SimpleSource[MetabaseSourceConfig]):
name=SchemaExternalDataSourceType.METABASE,
category=DataWarehouseSourceCategory.ANALYTICS,
label="Metabase",
+ releaseStatus=ReleaseStatus.ALPHA,
+ caption="""Enter your Metabase instance URL and credentials to pull your Metabase data into the PostHog Data warehouse.
+
+Create an API key in your Metabase under **Admin settings > Authentication > API keys** (Metabase v0.47+). Older instances can authenticate with a username and password instead.
+
+The API key (or user) needs read access to the data you want to sync.""",
iconPath="/static/services/metabase.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl="https://posthog.com/docs/cdp/sources/metabase",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="host",
+ label="Instance URL",
+ type=SourceFieldInputConfigType.TEXT,
+ required=True,
+ placeholder="https://your-company.metabaseapp.com",
+ secret=False,
+ ),
+ SourceFieldSelectConfig(
+ name="auth_method",
+ label="Authentication method",
+ required=True,
+ defaultValue=API_KEY_AUTH,
+ options=[
+ SourceFieldSelectConfigOption(
+ label="API key",
+ value=API_KEY_AUTH,
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_key",
+ label="API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=False,
+ placeholder="mb_...",
+ secret=True,
+ ),
+ ],
+ ),
+ ),
+ SourceFieldSelectConfigOption(
+ label="Username & password",
+ value=SESSION_AUTH,
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="username",
+ label="Username (email)",
+ type=SourceFieldInputConfigType.EMAIL,
+ required=False,
+ placeholder="[email protected]",
+ secret=False,
+ ),
+ SourceFieldInputConfig(
+ name="password",
+ label="Password",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=False,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
+ ),
+ ],
+ ),
+ ],
+ ),
+ )
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "Invalid Metabase credentials": "Your Metabase credentials are invalid or expired. Update them and reconnect.",
+ "Invalid Metabase username or password": "Your Metabase username or password is incorrect. Update them and reconnect.",
+ "Missing Metabase API key": "No Metabase API key is configured. Update the source configuration and reconnect.",
+ "401 Client Error": "Your Metabase credentials are invalid or expired. Update them and reconnect.",
+ "403 Client Error": "Your Metabase credentials lack the permissions needed to sync this data. Grant read access and reconnect.",
+ HOST_NOT_ALLOWED_ERROR: "The Metabase host is not allowed. Please use your instance's public URL.",
+ }
+
+ def _build_auth(self, config: MetabaseSourceConfig) -> MetabaseAuth:
+ return MetabaseAuth(
+ method=config.auth_method.selection,
+ api_key=config.auth_method.api_key,
+ username=config.auth_method.username,
+ password=config.auth_method.password,
)
+
+ def get_schemas(
+ self,
+ config: MetabaseSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ # Metabase exposes no server-side timestamp filter or pagination cursor, so every endpoint
+ # is full refresh only.
+ schemas = [
+ SourceSchema(
+ name=endpoint,
+ supports_incremental=False,
+ supports_append=False,
+ incremental_fields=[],
+ )
+ for endpoint in ENDPOINTS
+ ]
+ if names is not None:
+ names_set = set(names)
+ schemas = [s for s in schemas if s.name in names_set]
+ return schemas
+
+ def validate_credentials(
+ self, config: MetabaseSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ return validate_metabase_credentials(config.host, self._build_auth(config), team_id, schema_name)
+
+ def source_for_pipeline(self, config: MetabaseSourceConfig, inputs: SourceInputs) -> SourceResponse:
+ return metabase_source(
+ host=config.host,
+ auth=self._build_auth(config),
+ endpoint=inputs.schema_name,
+ logger=inputs.logger,
+ team_id=inputs.team_id,
+ )
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from posthog.temporal.data_imports.sources.metabase.canonical_descriptions import CANONICAL_DESCRIPTIONS
+
+ return CANONICAL_DESCRIPTIONS
diff --git a/posthog/temporal/data_imports/sources/metabase/tests/test_metabase.py b/posthog/temporal/data_imports/sources/metabase/tests/test_metabase.py
new file mode 100644
index 000000000000..f6b4b7847048
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/metabase/tests/test_metabase.py
@@ -0,0 +1,314 @@
+from typing import Any, Optional
+
+import pytest
+from unittest import mock
+
+from posthog.temporal.data_imports.sources.metabase import metabase as metabase_module
+from posthog.temporal.data_imports.sources.metabase.metabase import (
+ API_KEY_AUTH,
+ SESSION_AUTH,
+ MetabaseAuth,
+ MetabaseAuthError,
+ MetabaseHostNotAllowedError,
+ _extract_items,
+ _redact_values_for_data_requests,
+ _resolve_auth_headers,
+ get_rows,
+ metabase_source,
+ normalize_host,
+ validate_credentials,
+)
+
+
+def _response(*, status_code: int = 200, json_data: Any = None, text: str = "") -> mock.MagicMock:
+ response = mock.MagicMock()
+ response.status_code = status_code
+ response.ok = 200 <= status_code < 400
+ response.is_redirect = status_code in (301, 302, 303, 307, 308)
+ response.is_permanent_redirect = status_code in (301, 308)
+ response.text = text
+ response.json.return_value = json_data
+ response.headers = {}
+ return response
+
+
+def _api_key_auth() -> MetabaseAuth:
+ return MetabaseAuth(method=API_KEY_AUTH, api_key="mb_secret")
+
+
+def _session_auth() -> MetabaseAuth:
+ return MetabaseAuth(method=SESSION_AUTH, username="[email protected]", password="hunter2")
+
+
+class TestNormalizeHost:
+ @pytest.mark.parametrize(
+ "raw, expected",
+ [
+ ("https://company.metabaseapp.com", "https://company.metabaseapp.com"),
+ ("company.metabaseapp.com", "https://company.metabaseapp.com"),
+ ("https://company.metabaseapp.com/", "https://company.metabaseapp.com"),
+ ("https://company.metabaseapp.com/api", "https://company.metabaseapp.com"),
+ (" company.metabaseapp.com ", "https://company.metabaseapp.com"),
+ ("http://localhost:3000", "http://localhost:3000"),
+ ("http://127.0.0.1:3000", "http://127.0.0.1:3000"),
+ # Plaintext HTTP to a remote host is upgraded to HTTPS so credentials aren't sent in the clear.
+ ("http://company.metabaseapp.com", "https://company.metabaseapp.com"),
+ ("HTTP://company.metabaseapp.com/api", "https://company.metabaseapp.com"),
+ ],
+ )
+ def test_normalize_host(self, raw, expected):
+ assert normalize_host(raw) == expected
+
+
+class TestExtractItems:
+ @pytest.mark.parametrize(
+ "data, expected",
+ [
+ ([{"id": 1}, {"id": 2}], [{"id": 1}, {"id": 2}]),
+ ({"data": [{"id": 1}], "total": 1}, [{"id": 1}]),
+ ({"total": 0}, []),
+ (None, []),
+ ("nonsense", []),
+ ([{"id": 1}, "skip-me", 5], [{"id": 1}]),
+ ],
+ )
+ def test_extract_items(self, data, expected):
+ assert _extract_items(data) == expected
+
+
+class TestResolveAuthHeaders:
+ def _patch_mint(self, post_response=None):
+ session = mock.MagicMock()
+ session.post.return_value = post_response
+ return session, mock.patch.object(metabase_module, "make_tracked_session", return_value=session)
+
+ def test_api_key_header(self):
+ session, patch = self._patch_mint()
+ with patch:
+ headers = _resolve_auth_headers("https://x.metabaseapp.com", _api_key_auth(), mock.MagicMock())
+ assert headers["x-api-key"] == "mb_secret"
+ # API-key auth makes no network call to mint anything.
+ session.post.assert_not_called()
+
+ def test_api_key_missing_raises(self):
+ auth = MetabaseAuth(method=API_KEY_AUTH, api_key=None)
+ with pytest.raises(MetabaseAuthError):
+ _resolve_auth_headers("https://x.metabaseapp.com", auth, mock.MagicMock())
+
+ def test_session_mints_token(self):
+ session, patch = self._patch_mint(_response(json_data={"id": "session-token-abc"}))
+ with patch as patched:
+ headers = _resolve_auth_headers("https://x.metabaseapp.com", _session_auth(), mock.MagicMock())
+ assert headers["X-Metabase-Session"] == "session-token-abc"
+ # The token is exchanged at the session endpoint, never persisted.
+ assert session.post.call_args.args[0] == "https://x.metabaseapp.com/api/session"
+ assert session.post.call_args.kwargs["allow_redirects"] is False
+ # The mint exchange is excluded from HTTP sample capture so neither the password
+ # (request body) nor the minted token (response `id`) can land in a captured sample.
+ assert patched.call_args.kwargs["capture"] is False
+
+ @pytest.mark.parametrize("status_code", [400, 401, 403])
+ def test_session_bad_credentials_raises_auth_error(self, status_code):
+ session, patch = self._patch_mint(_response(status_code=status_code))
+ with patch, pytest.raises(MetabaseAuthError):
+ _resolve_auth_headers("https://x.metabaseapp.com", _session_auth(), mock.MagicMock())
+
+ def test_session_missing_username_raises(self):
+ auth = MetabaseAuth(method=SESSION_AUTH, username=None, password="x")
+ with pytest.raises(MetabaseAuthError):
+ _resolve_auth_headers("https://x.metabaseapp.com", auth, mock.MagicMock())
+
+ def test_session_no_token_in_response_raises(self):
+ session, patch = self._patch_mint(_response(json_data={}))
+ with patch, pytest.raises(MetabaseAuthError):
+ _resolve_auth_headers("https://x.metabaseapp.com", _session_auth(), mock.MagicMock())
+
+ @pytest.mark.parametrize("status_code", [404, 422, 500])
+ def test_session_unexpected_status_raises_retryable_not_httperror(self, status_code):
+ # Unexpected non-auth statuses must surface as a typed retryable error so callers'
+ # except clauses catch them, not a raw requests HTTPError.
+ session, patch = self._patch_mint(_response(status_code=status_code))
+ with patch, pytest.raises(metabase_module.MetabaseRetryableError):
+ _resolve_auth_headers("https://x.metabaseapp.com", _session_auth(), mock.MagicMock())
+
+
+class TestRedactValuesForDataRequests:
+ def test_api_key(self):
+ assert _redact_values_for_data_requests(_api_key_auth(), {}) == ("mb_secret",)
+
+ def test_session_includes_creds_and_minted_token(self):
+ values = _redact_values_for_data_requests(_session_auth(), {"X-Metabase-Session": "tok-123"})
+ assert set(values) == {"[email protected]", "hunter2", "tok-123"}
+
+
+class TestValidateCredentials:
+ def _patch_session(self, get_response=None, raises=None):
+ session = mock.MagicMock()
+ if raises is not None:
+ session.get.side_effect = raises
+ else:
+ session.get.return_value = get_response
+ return mock.patch.object(metabase_module, "make_tracked_session", return_value=session)
+
+ def test_success(self):
+ with self._patch_session(_response(status_code=200)):
+ assert validate_credentials("https://x.metabaseapp.com", _api_key_auth()) == (True, None)
+
+ def test_invalid_credentials(self):
+ with self._patch_session(_response(status_code=401)):
+ valid, msg = validate_credentials("https://x.metabaseapp.com", _api_key_auth())
+ assert valid is False
+ assert msg == "Invalid Metabase credentials"
+
+ def test_403_at_source_create_is_accepted(self):
+ with self._patch_session(_response(status_code=403)):
+ assert validate_credentials("https://x.metabaseapp.com", _api_key_auth(), schema_name=None) == (True, None)
+
+ def test_403_for_scoped_probe_fails(self):
+ with self._patch_session(_response(status_code=403)):
+ valid, msg = validate_credentials("https://x.metabaseapp.com", _api_key_auth(), schema_name="cards")
+ assert valid is False
+ assert msg is not None
+
+ @pytest.mark.parametrize("bad_host", ["", "https://", "not a host!"])
+ def test_invalid_host_short_circuits(self, bad_host):
+ valid, msg = validate_credentials(bad_host, _api_key_auth())
+ assert valid is False
+ assert msg == "Invalid Metabase host"
+
+ def test_request_exception_returns_failure(self):
+ import requests
+
+ with self._patch_session(raises=requests.exceptions.ConnectionError("boom")):
+ valid, msg = validate_credentials("https://x.metabaseapp.com", _api_key_auth())
+ assert valid is False
+ assert "boom" in (msg or "")
+
+ def test_rejects_redirect_response(self):
+ with self._patch_session(_response(status_code=302)) as patched:
+ valid, msg = validate_credentials("https://x.metabaseapp.com", _api_key_auth())
+ assert valid is False
+ assert msg == metabase_module.HOST_NOT_ALLOWED_ERROR
+ assert patched.return_value.get.call_args.kwargs["allow_redirects"] is False
+
+ def test_blocks_unsafe_host(self):
+ with (
+ mock.patch.object(metabase_module, "_is_host_safe", return_value=(False, "internal address")),
+ self._patch_session(_response(status_code=200)) as patched,
+ ):
+ valid, msg = validate_credentials("https://10.0.0.1", _api_key_auth(), team_id=99)
+ assert valid is False
+ assert msg == "internal address"
+ patched.return_value.get.assert_not_called()
+
+ def test_bad_session_credentials_surface_before_probe(self):
+ session = mock.MagicMock()
+ session.post.return_value = _response(status_code=401)
+ with mock.patch.object(metabase_module, "make_tracked_session", return_value=session):
+ valid, msg = validate_credentials("https://x.metabaseapp.com", _session_auth())
+ assert valid is False
+ assert msg == "Invalid Metabase username or password"
+ session.get.assert_not_called()
+
+ def test_unexpected_session_status_returns_failure_not_raises(self):
+ # A 404 (e.g. wrong API path) during session minting must come back as (False, msg), not an
+ # uncaught HTTPError bubbling out of source creation.
+ session = mock.MagicMock()
+ session.post.return_value = _response(status_code=404)
+ with mock.patch.object(metabase_module, "make_tracked_session", return_value=session):
+ valid, msg = validate_credentials("https://x.metabaseapp.com", _session_auth())
+ assert valid is False
+ assert msg is not None
+ session.get.assert_not_called()
+
+
+class TestMetabaseSourceResponse:
+ @pytest.mark.parametrize(
+ "endpoint, primary_keys, partition_key",
+ [
+ ("cards", ["id"], "created_at"),
+ ("dashboards", ["id"], "created_at"),
+ ("databases", ["id"], "created_at"),
+ ("native_query_snippets", ["id"], "created_at"),
+ ("users", ["id"], "date_joined"),
+ ("collections", ["id"], None),
+ ],
+ )
+ def test_response_shape(self, endpoint, primary_keys, partition_key):
+ response = metabase_source(
+ host="https://x.metabaseapp.com",
+ auth=_api_key_auth(),
+ endpoint=endpoint,
+ logger=mock.MagicMock(),
+ team_id=1,
+ )
+ assert response.name == endpoint
+ assert response.primary_keys == primary_keys
+ if partition_key:
+ assert response.partition_keys == [partition_key]
+ assert response.partition_mode == "datetime"
+ else:
+ assert response.partition_keys is None
+ assert response.partition_mode is None
+
+
+class TestGetRows:
+ def _run(self, responses: list[Any], auth: Optional[MetabaseAuth] = None, endpoint: str = "cards"):
+ session = mock.MagicMock()
+ session.get.side_effect = responses
+ with mock.patch.object(metabase_module, "make_tracked_session", return_value=session):
+ rows: list[Any] = []
+ for table in get_rows(
+ host="https://x.metabaseapp.com",
+ auth=auth or _api_key_auth(),
+ endpoint=endpoint,
+ logger=mock.MagicMock(),
+ team_id=1,
+ ):
+ rows.extend(table)
+ return rows, session
+
+ def test_yields_bare_array(self):
+ rows, session = self._run([_response(json_data=[{"id": 1}, {"id": 2}])])
+ assert [r["id"] for r in rows] == [1, 2]
+ assert session.get.call_count == 1
+ assert session.get.call_args.args[0] == "https://x.metabaseapp.com/api/card"
+
+ def test_yields_wrapped_array(self):
+ rows, _ = self._run([_response(json_data={"data": [{"id": 7}], "total": 1})], endpoint="databases")
+ assert [r["id"] for r in rows] == [7]
+
+ def test_empty_collection_yields_nothing(self):
+ rows, _ = self._run([_response(json_data=[])])
+ assert rows == []
+
+ def test_passes_allow_redirects_false(self):
+ _rows, session = self._run([_response(json_data=[{"id": 1}])])
+ assert session.get.call_args.kwargs["allow_redirects"] is False
+
+ def test_rejects_redirect(self):
+ with pytest.raises(MetabaseHostNotAllowedError):
+ self._run([_response(status_code=302)])
+
+ def test_blocks_unsafe_host_at_runtime(self):
+ with mock.patch.object(metabase_module, "_is_host_safe", return_value=(False, "internal address")):
+ with pytest.raises(MetabaseHostNotAllowedError):
+ self._run([_response(json_data=[{"id": 1}])])
+
+ def test_session_auth_mints_token_then_lists(self):
+ session = mock.MagicMock()
+ session.post.return_value = _response(json_data={"id": "tok-123"})
+ session.get.return_value = _response(json_data=[{"id": 1}])
+ with mock.patch.object(metabase_module, "make_tracked_session", return_value=session):
+ rows = list(
+ get_rows(
+ host="https://x.metabaseapp.com",
+ auth=_session_auth(),
+ endpoint="cards",
+ logger=mock.MagicMock(),
+ team_id=1,
+ )
+ )
+ assert session.post.called
+ assert session.get.call_args.kwargs["headers"]["X-Metabase-Session"] == "tok-123"
+ assert [r["id"] for batch in rows for r in batch] == [1]
diff --git a/posthog/temporal/data_imports/sources/metabase/tests/test_metabase_source.py b/posthog/temporal/data_imports/sources/metabase/tests/test_metabase_source.py
new file mode 100644
index 000000000000..9d9b8a29e134
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/metabase/tests/test_metabase_source.py
@@ -0,0 +1,127 @@
+from typing import Literal
+
+import pytest
+from unittest import mock
+
+from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldSelectConfig
+
+from posthog.temporal.data_imports.sources.generated_configs import MetabaseAuthMethodConfig, MetabaseSourceConfig
+from posthog.temporal.data_imports.sources.metabase.metabase import API_KEY_AUTH, SESSION_AUTH, MetabaseAuth
+from posthog.temporal.data_imports.sources.metabase.settings import ENDPOINTS
+from posthog.temporal.data_imports.sources.metabase.source import MetabaseSource
+
+from products.data_warehouse.backend.types import ExternalDataSourceType
+
+
+def _config(selection: Literal["api_key", "session"] = "api_key", **auth_kwargs) -> MetabaseSourceConfig:
+ return MetabaseSourceConfig(
+ host="https://company.metabaseapp.com",
+ auth_method=MetabaseAuthMethodConfig(selection=selection, **auth_kwargs),
+ )
+
+
+class TestMetabaseSource:
+ def setup_method(self):
+ self.source = MetabaseSource()
+ self.team_id = 123
+ self.config = _config(api_key="mb_secret")
+
+ def test_source_type(self):
+ assert self.source.source_type == ExternalDataSourceType.METABASE
+
+ def test_get_source_config(self):
+ config = self.source.get_source_config
+
+ assert config.name.value == "Metabase"
+ assert config.label == "Metabase"
+ assert config.unreleasedSource is None
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert config.iconPath == "/static/services/metabase.png"
+
+ host_field, auth_field = config.fields
+ assert isinstance(host_field, SourceFieldInputConfig)
+ assert host_field.name == "host"
+ assert host_field.secret is False
+
+ assert isinstance(auth_field, SourceFieldSelectConfig)
+ assert auth_field.name == "auth_method"
+ assert [o.value for o in auth_field.options] == [API_KEY_AUTH, SESSION_AUTH]
+
+ def test_credential_fields_are_secret(self):
+ auth_field = self.source.get_source_config.fields[1]
+ assert isinstance(auth_field, SourceFieldSelectConfig)
+ secret_field_names = {
+ f.name
+ for option in auth_field.options
+ for f in (option.fields or [])
+ if isinstance(f, SourceFieldInputConfig) and f.secret
+ }
+ assert secret_field_names == {"api_key", "password"}
+
+ @pytest.mark.parametrize("expected_key", ["401 Client Error", "403 Client Error", "Invalid Metabase credentials"])
+ def test_non_retryable_errors(self, expected_key):
+ assert expected_key in self.source.get_non_retryable_errors()
+
+ def test_get_schemas_returns_all_endpoints(self):
+ schemas = self.source.get_schemas(self.config, self.team_id)
+ assert {s.name for s in schemas} == set(ENDPOINTS)
+
+ def test_all_schemas_are_full_refresh(self):
+ # Metabase has no server-side timestamp filter, so nothing is incremental.
+ for schema in self.source.get_schemas(self.config, self.team_id):
+ assert schema.supports_incremental is False
+ assert schema.supports_append is False
+ assert schema.incremental_fields == []
+
+ def test_get_schemas_filtered_by_names(self):
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["cards"])
+ assert [s.name for s in schemas] == ["cards"]
+
+ def test_get_schemas_unknown_name_returns_empty(self):
+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []
+
+ @pytest.mark.parametrize(
+ "selection, auth_kwargs, expected",
+ [
+ (API_KEY_AUTH, {"api_key": "mb_x"}, ("mb_x", None, None)),
+ (SESSION_AUTH, {"username": "[email protected]", "password": "pw"}, (None, "[email protected]", "pw")),
+ ],
+ )
+ def test_build_auth(self, selection, auth_kwargs, expected):
+ auth = self.source._build_auth(_config(selection, **auth_kwargs))
+ assert isinstance(auth, MetabaseAuth)
+ assert auth.method == selection
+ assert (auth.api_key, auth.username, auth.password) == expected
+
+ @pytest.mark.parametrize("mock_return", [(True, None), (False, "Invalid Metabase credentials")])
+ @mock.patch("posthog.temporal.data_imports.sources.metabase.source.validate_metabase_credentials")
+ def test_validate_credentials(self, mock_validate, mock_return):
+ mock_validate.return_value = mock_return
+
+ result = self.source.validate_credentials(self.config, self.team_id, schema_name="cards")
+
+ assert result == mock_return
+ args = mock_validate.call_args.args
+ assert args[0] == self.config.host
+ assert isinstance(args[1], MetabaseAuth)
+ assert args[2] == self.team_id
+ assert args[3] == "cards"
+
+ @mock.patch("posthog.temporal.data_imports.sources.metabase.source.metabase_source")
+ def test_source_for_pipeline_plumbs_arguments(self, mock_metabase_source):
+ inputs = mock.MagicMock()
+ inputs.schema_name = "cards"
+ inputs.team_id = 42
+
+ self.source.source_for_pipeline(self.config, inputs)
+
+ mock_metabase_source.assert_called_once()
+ kwargs = mock_metabase_source.call_args.kwargs
+ assert kwargs["host"] == "https://company.metabaseapp.com"
+ assert isinstance(kwargs["auth"], MetabaseAuth)
+ assert kwargs["endpoint"] == "cards"
+ assert kwargs["team_id"] == 42
+
+ def test_canonical_descriptions_cover_endpoints(self):
+ descriptions = self.source.get_canonical_descriptions()
+ assert set(descriptions.keys()) == set(ENDPOINTS)