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 baserow import source (#72639)

Tom Owersea89d4c41d91
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
index f378e458b979..4ddbb19df9ce 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -81,6 +81,7 @@ the row lists both.
| azure_devops | HTTP | requests | ✅ |
| babelforce | HTTP | requests | ✅ |
| bamboohr | HTTP | requests | ✅ |
+| baserow | HTTP | requests + `rest_source.RESTClient` | ✅ |
| baseten | HTTP | requests | ✅ |
| beamer | HTTP | requests | ✅ |
| better_stack | HTTP | requests | ✅ |
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/baserow/baserow.py b/products/warehouse_sources/backend/temporal/data_imports/sources/baserow/baserow.py
new file mode 100644
index 000000000000..ee9889619a00
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/baserow/baserow.py
@@ -0,0 +1,360 @@
+import threading
+import dataclasses
+from collections import Counter
+from typing import Any, Optional
+from urllib.parse import urlparse
+
+import requests
+from requests import PreparedRequest, Response
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse
+from products.warehouse_sources.backend.temporal.data_imports.sources.baserow.settings import (
+ CONNECT_TIMEOUT_SECONDS,
+ DEFAULT_BASE_URL,
+ MAX_PAGES_PER_SYNC,
+ MAX_RESPONSE_BYTES,
+ PAGE_SIZE,
+ READ_DEADLINE_SECONDS,
+ READ_TIMEOUT_SECONDS,
+ REQUEST_TIMEOUT_SECONDS,
+ RESPONSE_READ_CHUNK_BYTES,
+ ROWS_PRIMARY_KEYS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_adapter
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http.transport import _NoRedirectSession
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source import (
+ RESTAPIConfig,
+ rest_api_resource,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (
+ JSONResponsePaginator,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.source_helpers import validate_via_probe
+
+
+class BaserowResumeConfig:
+ next_url: str
+
+
+def normalize_base_url(base_url: Optional[str]) -> str:
+ """Normalize the instance URL and reject anything that isn't HTTPS.
+
+ The database token travels in a header to a user-supplied host, so plaintext
+ http:// is rejected to keep it off the wire in the clear. Bare hosts default
+ to https; a blank value means the hosted baserow.io service.
+ """
+ host = (base_url or "").strip()
+ if not host:
+ return DEFAULT_BASE_URL
+ if "://" not in host:
+ host = f"https://{host}"
+ host = host.rstrip("/")
+ # Reject characters that make urlparse (which the SSRF host check trusts) and the HTTP
+ # client disagree on the target host — a backslash or an encoded authority delimiter
+ # is the wedge, so refuse them outright.
+ lowered = host.lower()
+ if "\\" in host or "%5c" in lowered or "%40" in lowered:
+ raise ValueError(f"Invalid Baserow instance URL: {host}")
+ try:
+ parsed = urlparse(host)
+ port = parsed.port
+ except ValueError:
+ raise ValueError(f"Invalid Baserow instance URL: {host}")
+ if parsed.scheme != "https" or not parsed.hostname:
+ raise ValueError(f"Invalid Baserow instance URL (must be https): {host}")
+ # Credentials in the authority (user:pass@host) would ship the token to `host` while the
+ # safety check could be aimed elsewhere; require the authority to be exactly host[:port].
+ host_part = f"[{parsed.hostname}]" if ":" in parsed.hostname else parsed.hostname
+ expected_netloc = host_part + (f":{port}" if port else "")
+ if parsed.netloc.lower() != expected_netloc.lower():
+ raise ValueError(f"Invalid Baserow instance URL: {host}")
+ return host
+
+
+def hostname_of(base_url: Optional[str]) -> str:
+ return urlparse(normalize_base_url(base_url)).hostname or ""
+
+
+class _BoundedSession(_NoRedirectSession):
+ """No-redirect session that also bounds each request on time and response size.
+
+ The base_url is user-supplied, so a hostile host could accept the connection and
+ then stall the response (``RESTClient.send()`` passes no timeout) or return an
+ arbitrarily large / highly compressed body (``requests`` buffers and decodes it
+ eagerly before returning) to exhaust a worker. Pin a connect/read timeout when the
+ caller supplies none, and stream the body under a hard per-response byte cap.
+ """
+
+ def send(self, request: PreparedRequest, **kwargs: Any) -> Response:
+ kwargs.setdefault("timeout", (CONNECT_TIMEOUT_SECONDS, READ_TIMEOUT_SECONDS))
+ kwargs["stream"] = True
+ response = super().send(request, **kwargs)
+ try:
+ body = _read_capped(response)
+ finally:
+ response.close()
+ response._content = body
+ response._content_consumed = True # type: ignore[attr-defined]
+ return response
+
+
+def _read_capped(response: Response) -> bytes:
+ """Buffer the body under both a size cap and a hard wall-clock deadline.
+
+ READ_TIMEOUT_SECONDS is only a socket-inactivity timeout, so a host that drips a byte
+ before each idle window keeps the read blocked indefinitely while staying under the byte
+ cap. Read on a daemon thread and abandon it past READ_DEADLINE_SECONDS, closing the
+ response to unblock the socket, so a slow-drip host can't monopolize a worker.
+ """
+ result: dict[str, Any] = {}
+
+ def drain() -> None:
+ try:
+ result["body"] = _stream_under_cap(response)
+ except BaseException as exc: # noqa: BLE001 — surfaced to the caller after the join below
+ result["error"] = exc
+
+ thread = threading.Thread(target=drain, daemon=True)
+ thread.start()
+ thread.join(READ_DEADLINE_SECONDS)
+ if thread.is_alive():
+ # Closing the response unblocks the raw read so the abandoned daemon thread can exit.
+ response.close()
+ raise ValueError(f"Baserow response body was not fully delivered within {READ_DEADLINE_SECONDS}s")
+ if "error" in result:
+ raise result["error"]
+ return result.get("body", b"")
+
+
+def _stream_under_cap(response: Response) -> bytes:
+ # Stream *decoded* chunks and abort the instant the running total crosses the cap. A
+ # single read(decode_content=True) would inflate the whole compressed body at once — a
+ # gzipped page decompresses fully before any size check — so a bomb is bounded only by
+ # decoding incrementally and stopping early.
+ chunks: list[bytes] = []
+ decoded = 0
+ for chunk in response.raw.stream(RESPONSE_READ_CHUNK_BYTES, decode_content=True):
+ decoded += len(chunk)
+ if decoded > MAX_RESPONSE_BYTES:
+ raise ValueError(f"Baserow response body exceeded the {MAX_RESPONSE_BYTES}-byte limit")
+ chunks.append(chunk)
+ return b"".join(chunks)
+
+
+def _bounded_session(database_token: str, *, extra_headers: Optional[dict[str, str]] = None) -> requests.Session:
+ """A tracked, no-redirect, time- and size-bounded session for Baserow's user-supplied host.
+
+ No-redirect is an SSRF boundary: a user-supplied base_url must not be able to bounce API
+ calls (and the token header) to an internal host via a 3xx. The bounds keep a hostile host
+ from stalling a request or returning an unbounded body. Credentials are registered for
+ value-based log redaction.
+ """
+ session = _BoundedSession()
+ adapter = make_tracked_adapter(redact_values=(database_token,))
+ session.mount("https://", adapter)
+ session.mount("http://", adapter)
+ headers = {"Accept": "application/json"}
+ if extra_headers:
+ headers.update(extra_headers)
+ session.headers.update(headers)
+ return session
+
+
+def _get_session(database_token: str) -> requests.Session:
+ return _bounded_session(database_token, extra_headers={"Authorization": f"Token {database_token}"})
+
+
+class BaserowPaginator(JSONResponsePaginator):
+ """Follows the `next` URL in Baserow's paginated body, pinned to the configured origin.
+
+ The next URL comes from the response body (and is persisted in resume state), so a
+ tampered response must not be able to redirect the token-bearing request to another
+ host, port, or a plaintext http:// URL.
+ """
+
+ def __init__(self, base_url: str) -> None:
+ super().__init__(next_url_path="next")
+ self._allowed_netloc = urlparse(normalize_base_url(base_url)).netloc.lower()
+ # Cycle guards: a host that keeps returning a `next` link can otherwise keep a
+ # resumable import issuing requests until its week-long activity timeout. Track the
+ # link we just followed to catch a repeated URL, and count pages as a coarse backstop.
+ self._previous_next_url: Optional[str] = None
+ self._pages_followed = 0
+
+ def _pin(self, url: str) -> None:
+ target = urlparse(url)
+ if target.scheme != "https" or target.netloc.lower() != self._allowed_netloc:
+ raise ValueError(f"Baserow pagination URL {url!r} is not on the configured instance")
+
+ def _guard_progress(self) -> None:
+ if self._next_url is None:
+ return
+ self._pin(self._next_url)
+ if self._next_url == self._previous_next_url:
+ raise ValueError(f"Baserow pagination is not advancing (repeated next URL {self._next_url!r})")
+ self._pages_followed += 1
+ if self._pages_followed > MAX_PAGES_PER_SYNC:
+ raise ValueError(f"Baserow sync exceeded the {MAX_PAGES_PER_SYNC}-page limit")
+ self._previous_next_url = self._next_url
+
+ def update_state(self, response: requests.Response, data: Optional[list[Any]] = None) -> None:
+ super().update_state(response, data)
+ if self._has_next_page:
+ self._guard_progress()
+
+ def set_resume_state(self, state: dict[str, Any]) -> None:
+ super().set_resume_state(state)
+ if self._next_url is not None:
+ # Seed the repeat guard from the resumed link so a host that immediately echoes it
+ # back is caught, and pin it here too (a tampered resume URL must not be followed).
+ self._pin(self._next_url)
+ self._previous_next_url = self._next_url
+
+
+def list_tables(base_url: Optional[str], database_token: str) -> list[dict[str, Any]]:
+ """List every table the database token can see, across all databases in its workspace."""
+ base = normalize_base_url(base_url)
+ response = _get_session(database_token).get(
+ f"{base}/api/database/tables/all-tables/", timeout=REQUEST_TIMEOUT_SECONDS
+ )
+ response.raise_for_status()
+ tables = response.json()
+ if not isinstance(tables, list):
+ raise ValueError("Unexpected response from Baserow when listing tables")
+ return tables
+
+
+def build_schema_name_map(tables: list[dict[str, Any]]) -> dict[str, dict[str, Any]]:
+ """Map schema name -> table. Names stay human-readable; only tables whose name repeats
+ across the token's databases get the table id appended, deterministically."""
+ name_counts = Counter(str(table["name"]) for table in tables)
+ return {
+ (str(table["name"]) if name_counts[str(table["name"])] == 1 else f"{table['name']} ({table['id']})"): table
+ for table in tables
+ }
+
+
+def resolve_table_id(
+ base_url: Optional[str],
+ database_token: str,
+ schema_name: str,
+ schema_metadata: Optional[dict[str, Any]],
+) -> int:
+ # The table id is stamped into schema_metadata at schema creation, so a later rename of
+ # the Baserow table keeps syncing into the same warehouse table. The re-listing below is
+ # only a safety net for schemas persisted without metadata.
+ if schema_metadata and schema_metadata.get("table_id") is not None:
+ return int(schema_metadata["table_id"])
+
+ table = build_schema_name_map(list_tables(base_url, database_token)).get(schema_name)
+ if table is None:
+ raise ValueError(f"Baserow table for schema {schema_name!r} not found — it may have been renamed or deleted")
+ return int(table["id"])
+
+
+def check_table_read_permission(base_url: Optional[str], database_token: str, table_id: int) -> str | None:
+ """Return None when the token can read the table's rows, or a short reason when it can't.
+
+ Database tokens carry per-table CRUD toggles; a token without read on a table gets a 401
+ ``ERROR_NO_PERMISSION_TO_TABLE`` from the rows endpoint. Only a real denial is a missing
+ permission — a throttle, 5xx, or network blip must not mark the table unreachable.
+ """
+ base = normalize_base_url(base_url)
+ try:
+ response = _get_session(database_token).get(
+ f"{base}/api/database/rows/table/{table_id}/",
+ params={"size": 1},
+ timeout=REQUEST_TIMEOUT_SECONDS,
+ )
+ except Exception:
+ return None
+ if response.status_code in (401, 403):
+ return "The database token does not have read permission for this table. Enable read access for it in Baserow's token settings."
+ return None
+
+
+def validate_credentials(base_url: Optional[str], database_token: str) -> tuple[bool, int | None]:
+ base = normalize_base_url(base_url)
+ return validate_via_probe(
+ lambda: _bounded_session(database_token),
+ f"{base}/api/database/tables/all-tables/",
+ headers={"Authorization": f"Token {database_token}"},
+ timeout=REQUEST_TIMEOUT_SECONDS,
+ allow_redirects=False,
+ )
+
+
+def baserow_rows_source(
+ base_url: Optional[str],
+ database_token: str,
+ table_id: int,
+ schema_name: str,
+ team_id: int,
+ job_id: str,
+ resumable_source_manager: ResumableSourceManager[BaserowResumeConfig],
+) -> SourceResponse:
+ base = normalize_base_url(base_url)
+
+ config: RESTAPIConfig = {
+ "client": {
+ "base_url": base,
+ "auth": {
+ "type": "api_key",
+ "name": "Authorization",
+ "api_key": f"Token {database_token}",
+ "location": "header",
+ },
+ "paginator": BaserowPaginator(base),
+ # RESTClient.send() passes no timeout and buffers the whole body eagerly, so the
+ # row-page reads run through the bounded session — otherwise a user-controlled host
+ # could stall a request or return an unbounded page and occupy an import worker.
+ "session": _bounded_session(database_token),
+ },
+ "resources": [
+ {
+ "name": "rows",
+ "endpoint": {
+ "path": f"/api/database/rows/table/{table_id}/",
+ "params": {
+ "size": PAGE_SIZE,
+ # Human-readable column names. Safe: Baserow reserves `id` and
+ # `order` as field names, so the row's own keys can't be shadowed.
+ "user_field_names": "true",
+ },
+ "data_selector": "results",
+ },
+ # Rows expose no server-side updated-since filter, so every sync is a full refresh.
+ "write_disposition": "replace",
+ "table_format": "delta",
+ }
+ ],
+ }
+
+ initial_paginator_state: Optional[dict[str, Any]] = None
+ if resumable_source_manager.can_resume():
+ resume_config = resumable_source_manager.load_state()
+ if resume_config is not None:
+ initial_paginator_state = {"next_url": resume_config.next_url}
+
+ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:
+ # Only persist when there's a next page to resume to; the Redis TTL
+ # handles cleanup on completion.
+ if state and state.get("next_url"):
+ resumable_source_manager.save_state(BaserowResumeConfig(next_url=str(state["next_url"])))
+
+ resource = rest_api_resource(
+ config,
+ team_id,
+ job_id,
+ None,
+ resume_hook=save_checkpoint,
+ initial_paginator_state=initial_paginator_state,
+ )
+
+ return SourceResponse(
+ name=schema_name,
+ items=lambda: resource,
+ primary_keys=list(ROWS_PRIMARY_KEYS),
+ )
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/baserow/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/baserow/settings.py
new file mode 100644
index 000000000000..819955ddcb23
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/baserow/settings.py
@@ -0,0 +1,41 @@
+DEFAULT_BASE_URL = "https://api.baserow.io"
+
+# Baserow caps the row list page size at 200 (ERROR_PAGE_SIZE_LIMIT above it).
+PAGE_SIZE = 200
+
+# Row ids are unique within a table, and each Baserow table syncs into its own
+# warehouse table, so the bare id is unique table-wide.
+ROWS_PRIMARY_KEYS = ["id"]
+
+REQUEST_TIMEOUT_SECONDS = 30.0
+
+# Split connect/read timeouts for the row-sync path: RESTClient.send() supplies no
+# timeout, so without this a user-controlled host could accept the connection and then
+# leave a row response unfinished, occupying an import worker until the resumable
+# activity's week-long timeout.
+CONNECT_TIMEOUT_SECONDS = 10.0
+READ_TIMEOUT_SECONDS = 30.0
+
+# Hard wall-clock ceiling on delivering a single response body. READ_TIMEOUT_SECONDS is only
+# a socket-inactivity timeout: a host that drips a byte before each idle window keeps the read
+# blocked indefinitely while staying under the byte cap. The body is read on a daemon thread
+# that is abandoned past this deadline (closing the response to unblock the socket), so a
+# slow-drip host can't monopolize an import worker. Generous for a legitimate page on a slow
+# link while still bounding a stalled transfer.
+READ_DEADLINE_SECONDS = 120.0
+
+# Hard per-response cap on decoded body bytes. `requests` buffers and decodes the whole
+# body before returning, so a hostile host could return an arbitrarily large — or highly
+# compressed — page and exhaust a worker's memory. The body is streamed and decoded
+# incrementally under this ceiling and aborted the instant it is crossed. Sized well above
+# a legitimate 200-row page while still bounding a single response.
+MAX_RESPONSE_BYTES = 100 * 1024 * 1024
+# Compressed bytes pulled per streamed read while enforcing the cap; small so a
+# decompression bomb can inflate at most one chunk's worth past the cap before we abort.
+RESPONSE_READ_CHUNK_BYTES = 64 * 1024
+
+# Coarse backstop on pages followed in a single sync run — far above any realistic Baserow
+# table (200 rows/page), so it never bites a legitimate sync. Paired with the same-URL
+# cycle guard in BaserowPaginator, it stops a host that returns an endless stream of
+# distinct `next` URLs from keeping a resumable import running until its activity timeout.
+MAX_PAGES_PER_SYNC = 1_000_000
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/baserow/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/baserow/source.py
index 14565e696358..22da3185df69 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/baserow/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/baserow/source.py
@@ -1,13 +1,34 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
DataWarehouseSourceCategory,
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (
+ SourceInputs,
+ SourceResponse,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.baserow.baserow import (
+ BaserowResumeConfig,
+ baserow_rows_source,
+ build_schema_name_map,
+ check_table_read_permission,
+ hostname_of,
+ list_tables,
+ normalize_base_url,
+ resolve_table_id,
+ validate_credentials as validate_baserow_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.mixins import ValidateDatabaseHostMixin
from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchema
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.baserow import (
BaserowSourceConfig,
)
@@ -15,18 +36,148 @@ from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class BaserowSource(SimpleSource[BaserowSourceConfig]):
+class BaserowSource(ResumableSource[BaserowSourceConfig, BaserowResumeConfig], ValidateDatabaseHostMixin):
+ # Baserow's REST API carries no version segment or version header.
+ api_docs_url = "https://baserow.io/api-docs"
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.BASEROW
+ @property
+ def connection_host_fields(self) -> list[str]:
+ # `base_url` decides where the stored database token is sent; retargeting it must
+ # re-require the token so an editor can't exfiltrate it to a host they control.
+ return ["base_url"]
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=SchemaExternalDataSourceType.BASEROW,
category=DataWarehouseSourceCategory.PRODUCTIVITY,
label="Baserow",
+ caption="""Sync the tables from your Baserow databases into the PostHog Data warehouse — each Baserow table becomes its own warehouse table.
+
+Create a database token in Baserow under **Settings > Database tokens** and make sure **read** permission is enabled for the tables you want to sync. Leave the instance URL blank to use Baserow's hosted service; self-hosted instances must be reachable over https.""",
iconPath="/static/services/baserow.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl="https://posthog.com/docs/cdp/sources/baserow",
+ releaseStatus=ReleaseStatus.ALPHA,
+ keywords=["airtable alternative", "no-code database"],
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="database_token",
+ label="Database token",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ SourceFieldInputConfig(
+ name="base_url",
+ label="Instance URL (optional)",
+ type=SourceFieldInputConfigType.TEXT,
+ required=False,
+ placeholder="https://api.baserow.io",
+ secret=False,
+ ),
+ ],
+ ),
+ )
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error": "Your Baserow database token does not have permission for this table. Enable read access for it in Baserow's token settings.",
+ "403 Client Error": "Your Baserow database token is invalid or has been revoked. Please create a new token and reconnect.",
+ "404 Client Error": "The Baserow table was not found — it may have been deleted.",
+ "Invalid Baserow instance URL": "The Baserow instance URL is invalid. Please enter the instance's canonical https URL.",
+ }
+
+ def get_schemas(
+ self,
+ config: BaserowSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ # One schema per Baserow table the token can see. Rows expose no server-side
+ # updated-since filter, so every table is full refresh only.
+ tables_by_name = build_schema_name_map(list_tables(config.base_url, config.database_token))
+ schemas = [
+ SourceSchema(
+ name=name,
+ supports_incremental=False,
+ supports_append=False,
+ incremental_fields=[],
+ schema_metadata={"table_id": table["id"], "database_id": table["database_id"]},
+ )
+ for name, table in sorted(tables_by_name.items())
+ ]
+ if names is not None:
+ names_set = set(names)
+ schemas = [s for s in schemas if s.name in names_set]
+ return schemas
+
+ def get_endpoint_permissions(
+ self, config: BaserowSourceConfig, team_id: int, endpoints: list[str]
+ ) -> dict[str, str | None]:
+ # Database tokens have per-table read toggles, so surface unreadable tables in the
+ # schema picker instead of failing the sync later.
+ result: dict[str, str | None] = dict.fromkeys(endpoints)
+ try:
+ tables_by_name = build_schema_name_map(list_tables(config.base_url, config.database_token))
+ except Exception:
+ return result
+ for name in endpoints:
+ table = tables_by_name.get(name)
+ if table is None:
+ continue
+ result[name] = check_table_read_permission(config.base_url, config.database_token, int(table["id"]))
+ return result
+
+ def validate_credentials(
+ self, config: BaserowSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ try:
+ base = normalize_base_url(config.base_url)
+ except ValueError:
+ return False, "Invalid Baserow instance URL"
+
+ host_valid, host_error = self.is_database_host_valid(hostname_of(base), team_id)
+ if not host_valid:
+ return False, host_error
+
+ ok, status = validate_baserow_credentials(config.base_url, config.database_token)
+ if ok:
+ return True, None
+ # Unlike most APIs, Baserow returns 403 for a token that doesn't exist
+ # (ERROR_TOKEN_DOES_NOT_EXIST), so 403 at create still means a bad token.
+ if status in (401, 403):
+ return False, "Invalid Baserow database token"
+ return False, "Could not connect to Baserow. Please check the instance URL."
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[BaserowResumeConfig]:
+ return ResumableSourceManager[BaserowResumeConfig](inputs, BaserowResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: BaserowSourceConfig,
+ resumable_source_manager: ResumableSourceManager[BaserowResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ host_valid, host_error = self.is_database_host_valid(hostname_of(config.base_url), inputs.team_id)
+ if not host_valid:
+ raise ValueError(host_error or "Invalid Baserow host")
+
+ table_id = resolve_table_id(config.base_url, config.database_token, inputs.schema_name, inputs.schema_metadata)
+ return baserow_rows_source(
+ base_url=config.base_url,
+ database_token=config.database_token,
+ table_id=table_id,
+ schema_name=inputs.schema_name,
+ team_id=inputs.team_id,
+ job_id=inputs.job_id,
+ resumable_source_manager=resumable_source_manager,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/baserow/tests/test_baserow.py b/products/warehouse_sources/backend/temporal/data_imports/sources/baserow/tests/test_baserow.py
new file mode 100644
index 000000000000..3f8ad599a928
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/baserow/tests/test_baserow.py
@@ -0,0 +1,352 @@
+import json
+import threading
+from collections.abc import Iterable
+from typing import Any, cast
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+import requests
+from requests import Request, Response
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.baserow.baserow import (
+ BaserowPaginator,
+ BaserowResumeConfig,
+ _BoundedSession,
+ _read_capped,
+ baserow_rows_source,
+ check_table_read_permission,
+ normalize_base_url,
+ resolve_table_id,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.baserow.settings import (
+ CONNECT_TIMEOUT_SECONDS,
+ DEFAULT_BASE_URL,
+ READ_TIMEOUT_SECONDS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+
+BASE_URL = "https://api.baserow.io"
+
+
+class TestNormalizeBaseUrl:
+ @pytest.mark.parametrize(
+ ("raw", "expected"),
+ [
+ (None, DEFAULT_BASE_URL),
+ ("", DEFAULT_BASE_URL),
+ (" ", DEFAULT_BASE_URL),
+ ("baserow.example.com", "https://baserow.example.com"),
+ ("https://baserow.example.com/", "https://baserow.example.com"),
+ ("https://baserow.example.com:8443", "https://baserow.example.com:8443"),
+ ],
+ )
+ def test_normalizes_valid_urls(self, raw: str | None, expected: str) -> None:
+ assert normalize_base_url(raw) == expected
+
+ @pytest.mark.parametrize(
+ "raw",
+ [
+ "http://baserow.example.com", # plaintext would put the token on the wire in the clear
+ "https://user:[email protected]", # credentials in the authority
+ "https://evil.com\\@baserow.example.com", # urlparse/http-client host disagreement
+ "https://evil.com%40baserow.example.com", # encoded authority delimiter
+ "https://",
+ ],
+ )
+ def test_rejects_unsafe_urls(self, raw: str) -> None:
+ with pytest.raises(ValueError):
+ normalize_base_url(raw)
+
+
+class TestBaserowPaginator:
+ def _response(self, body: dict[str, Any]) -> MagicMock:
+ response = MagicMock()
+ response.json.return_value = body
+ return response
+
+ def test_follows_same_origin_next_url(self) -> None:
+ paginator = BaserowPaginator(BASE_URL)
+ paginator.update_state(
+ self._response({"count": 300, "next": f"{BASE_URL}/api/database/rows/table/1/?page=2", "results": []})
+ )
+
+ assert paginator.has_next_page is True
+ request = Request(method="GET", url=f"{BASE_URL}/api/database/rows/table/1/", params={"size": 200})
+ paginator.update_request(request)
+ assert request.url == f"{BASE_URL}/api/database/rows/table/1/?page=2"
+
+ def test_stops_when_next_is_null(self) -> None:
+ paginator = BaserowPaginator(BASE_URL)
+ paginator.update_state(self._response({"count": 1, "next": None, "results": [{"id": 1}]}))
+
+ assert paginator.has_next_page is False
+ assert paginator.get_resume_state() is None
+
+ @pytest.mark.parametrize(
+ "next_url",
+ [
+ "http://api.baserow.io/api/database/rows/table/1/?page=2", # https downgrade
+ "https://evil.example.com/api/database/rows/table/1/?page=2", # other host
+ "https://api.baserow.io:8443/api/database/rows/table/1/?page=2", # other port
+ ],
+ )
+ def test_rejects_next_url_off_the_configured_origin(self, next_url: str) -> None:
+ paginator = BaserowPaginator(BASE_URL)
+ with pytest.raises(ValueError):
+ paginator.update_state(self._response({"count": 300, "next": next_url, "results": []}))
+
+ def test_resume_state_round_trip(self) -> None:
+ next_url = f"{BASE_URL}/api/database/rows/table/1/?page=3"
+ paginator = BaserowPaginator(BASE_URL)
+ paginator.update_state(self._response({"count": 500, "next": next_url, "results": []}))
+ assert paginator.get_resume_state() == {"next_url": next_url}
+
+ resumed = BaserowPaginator(BASE_URL)
+ resumed.set_resume_state({"next_url": next_url})
+ request = Request(method="GET", url=f"{BASE_URL}/api/database/rows/table/1/", params={"size": 200})
+ resumed.init_request(request)
+ assert request.url == next_url
+
+ def test_set_resume_state_rejects_cross_origin_url(self) -> None:
+ paginator = BaserowPaginator(BASE_URL)
+ with pytest.raises(ValueError):
+ paginator.set_resume_state({"next_url": "https://evil.example.com/api/database/rows/table/1/?page=2"})
+
+ def test_rejects_repeated_next_url(self) -> None:
+ # A host that keeps echoing the same next link would otherwise loop until the
+ # activity timeout; the second identical link aborts the sync.
+ next_url = f"{BASE_URL}/api/database/rows/table/1/?page=2"
+ paginator = BaserowPaginator(BASE_URL)
+ paginator.update_state(self._response({"count": 300, "next": next_url, "results": []}))
+ with pytest.raises(ValueError, match="not advancing"):
+ paginator.update_state(self._response({"count": 300, "next": next_url, "results": []}))
+
+ def test_aborts_when_page_budget_exhausted(self) -> None:
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.baserow.baserow.MAX_PAGES_PER_SYNC",
+ 2,
+ ):
+ paginator = BaserowPaginator(BASE_URL)
+ paginator.update_state(self._response({"count": 9, "next": f"{BASE_URL}/rows/?page=2", "results": []}))
+ paginator.update_state(self._response({"count": 9, "next": f"{BASE_URL}/rows/?page=3", "results": []}))
+ with pytest.raises(ValueError, match="page limit"):
+ paginator.update_state(self._response({"count": 9, "next": f"{BASE_URL}/rows/?page=4", "results": []}))
+
+
+class TestResolveTableId:
+ def test_schema_metadata_short_circuits_without_listing_tables(self) -> None:
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.baserow.baserow.list_tables"
+ ) as mock_list:
+ table_id = resolve_table_id(None, "tok", "Projects", {"table_id": 42, "database_id": 1})
+
+ assert table_id == 42
+ mock_list.assert_not_called()
+
+ def test_falls_back_to_name_lookup(self) -> None:
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.baserow.baserow.list_tables",
+ return_value=[{"id": 7, "name": "Projects", "order": 1, "database_id": 1}],
+ ):
+ assert resolve_table_id(None, "tok", "Projects", None) == 7
+
+ def test_raises_for_unknown_schema(self) -> None:
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.baserow.baserow.list_tables",
+ return_value=[{"id": 7, "name": "Projects", "order": 1, "database_id": 1}],
+ ):
+ with pytest.raises(ValueError, match="renamed or deleted"):
+ resolve_table_id(None, "tok", "Deleted table", None)
+
+
+class TestCheckTableReadPermission:
+ @pytest.mark.parametrize(
+ ("status_code", "expects_reason"),
+ [
+ (200, False),
+ (401, True), # ERROR_NO_PERMISSION_TO_TABLE — read toggle off for this table
+ (403, True),
+ (429, False), # a throttle is not a missing permission
+ (500, False),
+ ],
+ )
+ def test_maps_status_to_reason(self, status_code: int, expects_reason: bool) -> None:
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.baserow.baserow._get_session"
+ ) as mock_session:
+ mock_session.return_value.get.return_value = MagicMock(status_code=status_code)
+ reason = check_table_read_permission(None, "tok", 42)
+
+ assert (reason is not None) is expects_reason
+
+
+def _streamed_response(chunks: list[bytes], status_code: int = 200) -> Response:
+ resp = Response()
+ resp.status_code = status_code
+ raw = MagicMock()
+ raw.stream.return_value = iter(chunks)
+ resp.raw = raw
+ return resp
+
+
+class TestBoundedSession:
+ def test_read_capped_returns_full_body_under_limit(self) -> None:
+ assert _read_capped(_streamed_response([b"ab", b"cd"])) == b"abcd"
+
+ def test_read_capped_aborts_over_limit(self) -> None:
+ # A hostile host can return an arbitrarily large / highly compressed body; the cap
+ # aborts mid-stream instead of buffering it all into worker memory.
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.baserow.baserow.MAX_RESPONSE_BYTES",
+ 3,
+ ):
+ with pytest.raises(ValueError, match="exceeded"):
+ _read_capped(_streamed_response([b"ab", b"cd"]))
+
+ def test_read_capped_aborts_on_slow_drip(self) -> None:
+ # READ_TIMEOUT_SECONDS is only socket-inactivity, so a host that trickles bytes stays
+ # under it forever; the wall-clock deadline abandons the stalled read and closes the
+ # response to unblock the socket.
+ stalled = threading.Event()
+
+ def stalled_stream(*_a: Any, **_k: Any) -> Iterable[bytes]:
+ stalled.wait() # never delivers until the test releases it
+ yield b"x"
+
+ response = MagicMock()
+ response.raw.stream.side_effect = stalled_stream
+ try:
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.baserow.baserow.READ_DEADLINE_SECONDS",
+ 0.1,
+ ):
+ with pytest.raises(ValueError, match="not fully delivered"):
+ _read_capped(response)
+ response.close.assert_called_once()
+ finally:
+ stalled.set()
+
+ def test_send_defaults_timeout_and_streams_on_row_sync_path(self) -> None:
+ # RESTClient.send() passes no timeout — the session must supply one so a stalled
+ # host can't hang the request thread, and stream so the body stays capped.
+ prepared = Request(method="GET", url=f"{BASE_URL}/x").prepare()
+ with patch.object(requests.Session, "send", return_value=_streamed_response([b"{}"])) as parent_send:
+ _BoundedSession().send(prepared)
+ forwarded = parent_send.call_args.kwargs
+ assert forwarded["allow_redirects"] is False
+ assert forwarded["stream"] is True
+ assert forwarded["timeout"] == (CONNECT_TIMEOUT_SECONDS, READ_TIMEOUT_SECONDS)
+
+ def test_send_respects_explicit_timeout(self) -> None:
+ prepared = Request(method="GET", url=f"{BASE_URL}/x").prepare()
+ with patch.object(requests.Session, "send", return_value=_streamed_response([b"{}"])) as parent_send:
+ _BoundedSession().send(prepared, timeout=5)
+ assert parent_send.call_args.kwargs["timeout"] == 5
+
+
+def _make_http_response(body: dict[str, Any], status_code: int = 200) -> Response:
+ resp = Response()
+ resp.status_code = status_code
+ resp._content = json.dumps(body).encode()
+ resp.headers["Content-Type"] = "application/json"
+ return resp
+
+
+class TestBaserowRowsSourceResumeBehavior:
+ """End-to-end pagination + resume behaviour of ``baserow_rows_source`` via ``rest_api_resource``."""
+
+ def _drive(
+ self, manager: MagicMock, responses: list[Response]
+ ) -> tuple[list[list[dict[str, Any]]], list[tuple[str, dict[str, Any]]]]:
+ """Drive ``baserow_rows_source`` with a mocked HTTP session.
+
+ Returns ``(rows, sent)`` where ``sent`` is a list of ``(url, params)`` captured at
+ send-time — the underlying Request object is mutated in-place by the paginator
+ between pages, so we can't rely on mock ``call_args_list`` to preserve history.
+ """
+ sent: list[tuple[str, dict[str, Any]]] = []
+ response_iter = iter(responses)
+
+ def fake_send(request: Any, *_args: Any, **_kwargs: Any) -> Response:
+ sent.append((request.url, dict(request.params or {})))
+ return next(response_iter)
+
+ # The rows source injects its own bounded session, so intercept the factory rather
+ # than RESTClient's internal make_tracked_session (which it no longer calls).
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.baserow.baserow._bounded_session"
+ ) as mock_factory:
+ mock_session = MagicMock()
+ mock_session.headers = {}
+ mock_session.prepare_request.side_effect = lambda req: req
+ mock_session.send.side_effect = fake_send
+ mock_factory.return_value = mock_session
+
+ source = baserow_rows_source(
+ base_url=None,
+ database_token="test-token",
+ table_id=42,
+ schema_name="Projects",
+ team_id=123,
+ job_id="test_job",
+ resumable_source_manager=manager,
+ )
+ pages = list(cast(Iterable[list[dict[str, Any]]], source.items()))
+ return pages, sent
+
+ def test_fresh_run_pages_through_next_urls_and_checkpoints(self) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+
+ page_2 = f"{BASE_URL}/api/database/rows/table/42/?page=2&size=200&user_field_names=true"
+ responses = [
+ _make_http_response({"count": 3, "next": page_2, "previous": None, "results": [{"id": 1}, {"id": 2}]}),
+ _make_http_response({"count": 3, "next": None, "previous": "prev", "results": [{"id": 3}]}),
+ ]
+ pages, sent = self._drive(manager, responses)
+
+ # The resource yields one batch (list of row dicts) per page.
+ assert [[row["id"] for row in page] for page in pages] == [[1, 2], [3]]
+ # First request hits the table path with the declared params; the second follows the
+ # self-contained next URL with the original params dropped.
+ assert sent[0][0] == f"{DEFAULT_BASE_URL}/api/database/rows/table/42/"
+ assert sent[0][1] == {"size": 200, "user_field_names": "true"}
+ assert sent[1] == (page_2, {})
+
+ saved = [call.args[0] for call in manager.save_state.call_args_list]
+ assert saved == [BaserowResumeConfig(next_url=page_2)]
+
+ def test_resume_starts_from_saved_next_url(self) -> None:
+ saved_url = f"{BASE_URL}/api/database/rows/table/42/?page=5&size=200&user_field_names=true"
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = True
+ manager.load_state.return_value = BaserowResumeConfig(next_url=saved_url)
+
+ responses = [_make_http_response({"count": 900, "next": None, "previous": "prev", "results": [{"id": 801}]})]
+ _, sent = self._drive(manager, responses)
+
+ assert sent[0][0] == saved_url
+
+ def test_terminal_single_page_does_not_save_state(self) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+
+ responses = [_make_http_response({"count": 1, "next": None, "previous": None, "results": [{"id": 1}]})]
+ self._drive(manager, responses)
+
+ manager.save_state.assert_not_called()
+
+ def test_cross_origin_next_url_aborts_the_sync(self) -> None:
+ # Guards the wiring: the rows resource must run the origin-pinned paginator, so a
+ # tampered body can't bounce the token-bearing request to another host.
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+
+ responses = [
+ _make_http_response(
+ {"count": 3, "next": "https://evil.example.com/rows/?page=2", "previous": None, "results": [{"id": 1}]}
+ ),
+ ]
+ with pytest.raises(ValueError, match="not on the configured instance"):
+ self._drive(manager, responses)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/baserow/tests/test_baserow_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/baserow/tests/test_baserow_source.py
new file mode 100644
index 000000000000..11554db71cab
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/baserow/tests/test_baserow_source.py
@@ -0,0 +1,187 @@
+from typing import Any
+
+import pytest
+from unittest import mock
+
+from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceInputs
+from products.warehouse_sources.backend.temporal.data_imports.sources.baserow.baserow import BaserowResumeConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.baserow.source import BaserowSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.baserow import (
+ BaserowSourceConfig,
+)
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+# Two databases sharing a table name — only the colliding names get the id suffix.
+TABLES = [
+ {"id": 10, "name": "Projects", "order": 1, "database_id": 1},
+ {"id": 11, "name": "Tasks", "order": 2, "database_id": 1},
+ {"id": 12, "name": "Tasks", "order": 1, "database_id": 2},
+]
+
+SOURCE_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.baserow.source"
+
+
+def _make_inputs(**overrides: Any) -> SourceInputs:
+ defaults: dict[str, Any] = {
+ "schema_name": "Projects",
+ "schema_id": "schema-1",
+ "source_id": "source-1",
+ "team_id": 123,
+ "should_use_incremental_field": False,
+ "db_incremental_field_last_value": None,
+ "db_incremental_field_earliest_value": None,
+ "incremental_field": None,
+ "incremental_field_type": None,
+ "job_id": "job-1",
+ "logger": mock.MagicMock(),
+ "reset_pipeline": False,
+ }
+ defaults.update(overrides)
+ return SourceInputs(**defaults)
+
+
+class TestBaserowSource:
+ def setup_method(self) -> None:
+ self.source = BaserowSource()
+ self.team_id = 123
+ self.config = BaserowSourceConfig(database_token="test-token", base_url=None)
+
+ def test_source_type(self) -> None:
+ assert self.source.source_type == ExternalDataSourceType.BASEROW
+
+ def test_base_url_is_a_connection_host_field(self) -> None:
+ # Changing base_url must force the database token to be re-entered, so the stored
+ # token is never sent to a freshly-specified host.
+ assert self.source.connection_host_fields == ["base_url"]
+
+ def test_get_source_config(self) -> None:
+ config = self.source.get_source_config
+
+ assert config.name.value == "Baserow"
+ assert config.unreleasedSource is None
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+
+ token_field, base_url_field = config.fields
+ assert isinstance(token_field, SourceFieldInputConfig)
+ assert token_field.name == "database_token"
+ assert token_field.type == SourceFieldInputConfigType.PASSWORD
+ assert token_field.required is True
+ assert token_field.secret is True
+
+ assert isinstance(base_url_field, SourceFieldInputConfig)
+ assert base_url_field.name == "base_url"
+ assert base_url_field.type == SourceFieldInputConfigType.TEXT
+ assert base_url_field.required is False
+
+ @pytest.mark.parametrize(
+ "expected_key",
+ ["401 Client Error", "403 Client Error", "404 Client Error", "Invalid Baserow instance URL"],
+ )
+ def test_non_retryable_errors(self, expected_key: str) -> None:
+ assert expected_key in self.source.get_non_retryable_errors()
+
+ def test_get_schemas_builds_one_schema_per_table(self) -> None:
+ with mock.patch(f"{SOURCE_MODULE}.list_tables", return_value=TABLES):
+ schemas = self.source.get_schemas(self.config, self.team_id)
+
+ assert [s.name for s in schemas] == ["Projects", "Tasks (11)", "Tasks (12)"]
+ assert all(s.supports_incremental is False and s.supports_append is False for s in schemas)
+ assert schemas[0].schema_metadata == {"table_id": 10, "database_id": 1}
+
+ def test_get_schemas_filters_by_names(self) -> None:
+ with mock.patch(f"{SOURCE_MODULE}.list_tables", return_value=TABLES):
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["Tasks (12)"])
+
+ assert [s.name for s in schemas] == ["Tasks (12)"]
+
+ @pytest.mark.parametrize(
+ ("probe_result", "expected_valid", "expected_message"),
+ [
+ ((True, 200), True, None),
+ # Baserow returns 403 (ERROR_TOKEN_DOES_NOT_EXIST) for a bad token, not 401.
+ ((False, 403), False, "Invalid Baserow database token"),
+ ((False, 401), False, "Invalid Baserow database token"),
+ ((False, None), False, "Could not connect to Baserow. Please check the instance URL."),
+ ],
+ )
+ def test_validate_credentials_maps_probe_results(
+ self, probe_result: tuple[bool, int | None], expected_valid: bool, expected_message: str | None
+ ) -> None:
+ with (
+ mock.patch.object(BaserowSource, "is_database_host_valid", return_value=(True, None)),
+ mock.patch(f"{SOURCE_MODULE}.validate_baserow_credentials", return_value=probe_result),
+ ):
+ valid, message = self.source.validate_credentials(self.config, self.team_id)
+
+ assert valid is expected_valid
+ assert message == expected_message
+
+ def test_validate_credentials_rejects_invalid_url_without_probing(self) -> None:
+ config = BaserowSourceConfig(database_token="test-token", base_url="http://insecure.example.com")
+ with mock.patch(f"{SOURCE_MODULE}.validate_baserow_credentials") as mock_probe:
+ valid, message = self.source.validate_credentials(config, self.team_id)
+
+ assert valid is False
+ assert message == "Invalid Baserow instance URL"
+ mock_probe.assert_not_called()
+
+ def test_validate_credentials_rejects_blocked_host(self) -> None:
+ with mock.patch.object(BaserowSource, "is_database_host_valid", return_value=(False, "Host is not allowed")):
+ valid, message = self.source.validate_credentials(self.config, self.team_id)
+
+ assert valid is False
+ assert message == "Host is not allowed"
+
+ def test_get_resumable_source_manager_binds_resume_config(self) -> None:
+ manager = self.source.get_resumable_source_manager(_make_inputs())
+ assert manager._data_class is BaserowResumeConfig
+
+ def test_source_for_pipeline_resolves_table_id_from_schema_metadata(self) -> None:
+ inputs = _make_inputs(schema_name="Projects", schema_metadata={"table_id": 10, "database_id": 1})
+ manager = mock.MagicMock()
+
+ with (
+ mock.patch.object(BaserowSource, "is_database_host_valid", return_value=(True, None)),
+ mock.patch(f"{SOURCE_MODULE}.baserow_rows_source") as mock_rows_source,
+ ):
+ response = self.source.source_for_pipeline(self.config, manager, inputs)
+
+ assert response is mock_rows_source.return_value
+ mock_rows_source.assert_called_once_with(
+ base_url=None,
+ database_token="test-token",
+ table_id=10,
+ schema_name="Projects",
+ team_id=123,
+ job_id="job-1",
+ resumable_source_manager=manager,
+ )
+
+ def test_source_for_pipeline_rejects_blocked_host(self) -> None:
+ with mock.patch.object(BaserowSource, "is_database_host_valid", return_value=(False, "Host is not allowed")):
+ with pytest.raises(ValueError, match="Host is not allowed"):
+ self.source.source_for_pipeline(self.config, mock.MagicMock(), _make_inputs())
+
+ def test_get_endpoint_permissions_reports_unreadable_tables(self) -> None:
+ reason = "The database token does not have read permission for this table."
+
+ def permission_for(base_url: Any, token: str, table_id: int) -> str | None:
+ return reason if table_id == 11 else None
+
+ with (
+ mock.patch(f"{SOURCE_MODULE}.list_tables", return_value=TABLES),
+ mock.patch(f"{SOURCE_MODULE}.check_table_read_permission", side_effect=permission_for),
+ ):
+ result = self.source.get_endpoint_permissions(
+ self.config, self.team_id, ["Projects", "Tasks (11)", "Deleted table"]
+ )
+
+ assert result == {"Projects": None, "Tasks (11)": reason, "Deleted table": None}
+
+ def test_get_endpoint_permissions_never_blocks_on_listing_failure(self) -> None:
+ with mock.patch(f"{SOURCE_MODULE}.list_tables", side_effect=RuntimeError("boom")):
+ result = self.source.get_endpoint_permissions(self.config, self.team_id, ["Projects"])
+
+ assert result == {"Projects": None}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/baserow.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/baserow.py
index 1df0e4719a28..f01ca614bd95 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/baserow.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/baserow.py
@@ -6,4 +6,5 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp
@config.config
class BaserowSourceConfig(config.Config):
- pass
+ database_token: str
+ base_url: str | None = None