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): add Firebase source (#78831)

Tom Owers11219ae927e8
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 e31b4cf82104..1c3c3b9a4bb8 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -263,6 +263,7 @@ the row lists both.
| financial_modelling | HTTP | requests | ✅ |
| finnhub | HTTP | requests | ✅ |
| finnworlds | HTTP | requests | ✅ |
+| firebase | HTTP | requests + `pyjwt` | ✅ |
| firecrawl | HTTP | requests | ✅ |
| fireworks_ai | HTTP | requests | ✅ |
| fleetio | HTTP | requests | ✅ |
@@ -973,7 +974,6 @@ doesn't conflict with concurrent PRs.
- filevine
- finout
- fintoc
-- firebase
- firebolt
- five9
- flagsmith
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/firebase/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/firebase/canonical_descriptions.py
new file mode 100644
index 000000000000..257cae9d9cd6
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/firebase/canonical_descriptions.py
@@ -0,0 +1,35 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.firebase.settings import AUTH_USERS_TABLE
+
+# Only Firebase Auth has a fixed schema. Firestore collections and Realtime Database paths are
+# shaped by the customer's own app, so their columns fall back to the LLM enrichment pass.
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ AUTH_USERS_TABLE: {
+ "description": "One row per Firebase Authentication account in the project. Password hashes and salts are never synced.",
+ "docs_url": "https://cloud.google.com/identity-platform/docs/reference/rest/v1/projects.accounts/batchGet",
+ "columns": {
+ "localId": "Immutable unique ID of the account.",
+ "email": "The account's email address.",
+ "emailVerified": "Whether the account's email address has been verified.",
+ "initialEmail": "The first email address associated with this account.",
+ "displayName": "The display name of the account.",
+ "photoUrl": "URL of the account's profile photo.",
+ "phoneNumber": "The account's phone number.",
+ "disabled": "Whether the account is disabled and blocked from signing in.",
+ "createdAt": "Time the account was created, in milliseconds since epoch.",
+ "lastLoginAt": "Last time the account signed in, in milliseconds since epoch.",
+ "lastRefreshAt": "Timestamp when an ID token was last minted for this account.",
+ "passwordUpdatedAt": "Time the account's password was last updated, in milliseconds since epoch.",
+ "validSince": "Oldest timestamp, in seconds since epoch, at which an ID token is still considered valid.",
+ "providerUserInfo": "JSON list of the identity providers linked to the account.",
+ "mfaInfo": "JSON list of the multi-factor authentication providers enabled for the account.",
+ "customAttributes": "JSON custom claims added to any ID token minted for the account.",
+ "customAuth": "Whether the account has authenticated with a custom token.",
+ "emailLinkSignin": "Whether the account can authenticate with an email link.",
+ "tenantId": "ID of the Identity Platform tenant the account belongs to, when tenants are in use.",
+ "version": "Version of the account's password.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/firebase/firebase.py b/products/warehouse_sources/backend/temporal/data_imports/sources/firebase/firebase.py
new file mode 100644
index 000000000000..315b461a2cd7
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/firebase/firebase.py
@@ -0,0 +1,645 @@
+import json
+import time
+import dataclasses
+from collections.abc import Iterator
+from typing import Any, Optional
+from urllib.parse import quote, urlparse
+
+import jwt
+import requests
+import structlog
+from structlog.types import FilteringBoundLogger
+
+from posthog.dataclasses import frozen
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
+from products.warehouse_sources.backend.temporal.data_imports.sources.firebase.settings import (
+ AUTH_USERS_PAGE_SIZE,
+ AUTH_USERS_PRIMARY_KEY,
+ AUTH_USERS_TABLE,
+ FIRESTORE_API_ROOT,
+ FIRESTORE_COLLECTION_IDS_PAGE_SIZE,
+ FIRESTORE_CREATE_TIME_COLUMN,
+ FIRESTORE_ID_COLUMN,
+ FIRESTORE_PAGE_SIZE,
+ FIRESTORE_PATH_COLUMN,
+ FIRESTORE_UPDATE_TIME_COLUMN,
+ GOOGLE_TOKEN_URI,
+ IDENTITY_TOOLKIT_API_ROOT,
+ JWT_ASSERTION_LIFETIME_SECONDS,
+ JWT_GRANT_TYPE,
+ MAX_ERROR_BODY_BYTES,
+ MAX_PAGES,
+ MAX_RESPONSE_BYTES,
+ MAX_TOKEN_RESPONSE_BYTES,
+ OAUTH_SCOPES,
+ REALTIME_DATABASE_HOST_SUFFIXES,
+ REALTIME_DATABASE_KEY_COLUMN,
+ REALTIME_DATABASE_PAGE_SIZE,
+ REALTIME_DATABASE_PATH_COLUMN,
+ REALTIME_DATABASE_VALUE_COLUMN,
+ REDACTED_AUTH_USER_FIELDS,
+ REQUEST_TIMEOUT_SECONDS,
+ RESPONSE_TOO_LARGE_ERROR,
+ TOKEN_EXPIRY_SKEW_SECONDS,
+ firestore_table_name,
+ realtime_database_table_name,
+)
+
+LOGGER: FilteringBoundLogger = structlog.get_logger(__name__)
+
+
+class FirebaseAuthError(Exception):
+ """Raised when Google refuses to issue an access token for the service account."""
+
+
+class FirebaseConfigError(Exception):
+ """Raised when the source form describes something the transport cannot act on."""
+
+
+class FirebaseResponseTooLargeError(Exception):
+ """Raised when a response body exceeds the byte cap for its endpoint."""
+
+
+@frozen
+class FirebaseResumeConfig:
+ """Resume cursor: a Firestore/Identity Platform page token, or a Realtime Database key."""
+
+ cursor: str
+
+
[email protected](frozen=True, kw_only=True)
+class FirebaseCredentials:
+ project_id: str
+ client_email: str
+ private_key: str
+ private_key_id: Optional[str] = None
+ # Kept as it was read from the key file, but never used as a request target — see `token_endpoint`.
+ token_uri: Optional[str] = None
+ database_id: str = "(default)"
+ realtime_database_url: Optional[str] = None
+ realtime_database_paths: tuple[str, ...] = ()
+
+ @property
+ def token_endpoint(self) -> str:
+ # Pinned to Google rather than read from the uploaded file. `token_uri` is user-supplied
+ # input, and honoring it would let anyone who can configure a source aim the worker — and
+ # the signed assertion — at an arbitrary host, including an internal one. Google-generated
+ # service account keys always carry exactly this endpoint, so nothing legitimate is lost.
+ return GOOGLE_TOKEN_URI
+
+ @property
+ def secret_values(self) -> tuple[str, ...]:
+ return (self.private_key,) if self.private_key else ()
+
+
+def validate_realtime_database_url(url: str) -> str:
+ """Return the normalized Realtime Database base URL, or raise if it is not a Firebase host."""
+ parsed = urlparse(url.strip())
+ host = (parsed.hostname or "").lower()
+ if parsed.scheme != "https" or not host.endswith(REALTIME_DATABASE_HOST_SUFFIXES):
+ raise FirebaseConfigError(
+ "The Realtime Database URL has to be an https URL on firebaseio.com or firebasedatabase.app, "
+ "for example https://my-project-default-rtdb.firebaseio.com."
+ )
+ return f"https://{host}"
+
+
+def _auth_session(credentials: FirebaseCredentials) -> requests.Session:
+ # The token exchange carries the private key in the request and a bearer token in the
+ # response, so it stays out of HTTP sample capture entirely.
+ return make_tracked_session(redact_values=credentials.secret_values, capture=False)
+
+
+def _api_session(credentials: FirebaseCredentials, *, capture: bool = True) -> requests.Session:
+ return make_tracked_session(
+ headers={"Accept": "application/json"},
+ redact_values=credentials.secret_values,
+ capture=capture,
+ )
+
+
+def build_jwt_assertion(credentials: FirebaseCredentials) -> str:
+ issued_at = int(time.time())
+ claims: dict[str, Any] = {
+ "iss": credentials.client_email,
+ "scope": OAUTH_SCOPES,
+ "aud": credentials.token_endpoint,
+ "iat": issued_at,
+ "exp": issued_at + JWT_ASSERTION_LIFETIME_SECONDS,
+ }
+ headers = {"kid": credentials.private_key_id} if credentials.private_key_id else None
+ try:
+ return jwt.encode(claims, credentials.private_key, algorithm="RS256", headers=headers)
+ except Exception as e:
+ raise FirebaseAuthError(
+ "Your Firebase service account private key could not be read. Upload the JSON key file "
+ "exactly as Google generated it."
+ ) from e
+
+
+def mint_access_token(session: requests.Session, credentials: FirebaseCredentials) -> tuple[str, int]:
+ """Exchange the service-account assertion for a short-lived token and its lifetime in seconds."""
+ # stream=True so the body isn't buffered before _read_capped_body bounds it.
+ response = session.post(
+ credentials.token_endpoint,
+ data={"grant_type": JWT_GRANT_TYPE, "assertion": build_jwt_assertion(credentials)},
+ timeout=REQUEST_TIMEOUT_SECONDS,
+ stream=True,
+ )
+ if not response.ok:
+ detail = _error_detail(response, _read_truncated_body(response, MAX_ERROR_BODY_BYTES))
+ raise FirebaseAuthError(f"Google refused to issue an access token: {detail}")
+
+ raw = _read_capped_body(response, MAX_TOKEN_RESPONSE_BYTES)
+ try:
+ body = json.loads(raw)
+ except ValueError:
+ raise FirebaseAuthError("Google's token response could not be read as JSON.")
+ if not isinstance(body, dict):
+ raise FirebaseAuthError("Google's token response did not contain an access token.")
+ token = body.get("access_token")
+ if not token:
+ raise FirebaseAuthError("Google's token response did not contain an access token.")
+ # A literal `0` is a meaningful lifetime; folding it into the default with `or` would cache a
+ # token that has already expired. Only a missing or unreadable value falls back.
+ try:
+ expires_in = int(body["expires_in"])
+ except (KeyError, TypeError, ValueError):
+ expires_in = JWT_ASSERTION_LIFETIME_SECONDS
+ return str(token), expires_in
+
+
+class AccessTokenProvider:
+ """Mints Google access tokens and reuses them until they are close to expiring.
+
+ Tokens last about an hour and a sync can run longer, so the token is refreshed on demand
+ rather than minted once per job.
+ """
+
+ def __init__(self, session: requests.Session, credentials: FirebaseCredentials) -> None:
+ self._session = session
+ self._credentials = credentials
+ self._token: Optional[str] = None
+ self._expires_at: float = 0.0
+
+ def token(self, force_refresh: bool = False) -> str:
+ if force_refresh or self._token is None or time.time() >= self._expires_at:
+ token, expires_in = mint_access_token(self._session, self._credentials)
+ self._token = token
+ self._expires_at = time.time() + max(expires_in - TOKEN_EXPIRY_SKEW_SECONDS, 0)
+ return self._token
+
+
+def _read_capped_body(response: requests.Response, cap: int) -> bytes:
+ """Read one response body under a fixed cap on its decompressed size.
+
+ Every request is issued with ``stream=True``, so nothing is materialised until this read. We
+ ask for one byte past the cap: that detects an oversized body without ever buffering more than
+ the cap itself, and ``decode_content=True`` applies the cap after decompression so a compressed
+ payload can't expand past it. The connection is released either way.
+ """
+ try:
+ raw: bytes = response.raw.read(cap + 1, decode_content=True)
+ finally:
+ response.close()
+ if len(raw) > cap:
+ raise FirebaseResponseTooLargeError(f"{RESPONSE_TOO_LARGE_ERROR}: exceeded {cap} bytes")
+ return raw
+
+
+def _read_truncated_body(response: requests.Response, cap: int) -> bytes:
+ """Read at most ``cap`` bytes of a failed response, discarding the rest.
+
+ The error paths exist to explain an HTTP failure that already happened, so an oversized body is
+ truncated here instead of raising — otherwise a huge error page would mask the 401/403 the
+ caller actually needs to see and turn a diagnosable failure into a size complaint.
+ """
+ try:
+ return response.raw.read(cap, decode_content=True)
+ finally:
+ response.close()
+
+
+def _error_detail(response: requests.Response, raw: bytes) -> str:
+ """Google reports permanent problems in the body (`invalid_grant`, `PERMISSION_DENIED`)."""
+ try:
+ body = json.loads(raw)
+ except ValueError:
+ return f"status={response.status_code}"
+ if isinstance(body, dict):
+ error = body.get("error")
+ if isinstance(error, dict):
+ return f"status={response.status_code} status_code={error.get('status')} message={error.get('message')}"
+ if error:
+ return f"status={response.status_code} error={error} description={body.get('error_description')}"
+ return f"status={response.status_code}"
+
+
+def _request(
+ session: requests.Session,
+ tokens: AccessTokenProvider,
+ method: str,
+ url: str,
+ *,
+ params: Optional[dict[str, Any]] = None,
+ json_body: Optional[dict[str, Any]] = None,
+) -> Any:
+ def _do(token: str) -> requests.Response:
+ # stream=True so a page isn't buffered before _read_capped_body bounds it.
+ return session.request(
+ method,
+ url,
+ params=params,
+ json=json_body,
+ headers={"Authorization": f"Bearer {token}"},
+ timeout=REQUEST_TIMEOUT_SECONDS,
+ stream=True,
+ )
+
+ response = _do(tokens.token())
+ # A token that expired mid-sync looks exactly like a bad one; re-mint once before giving up.
+ if response.status_code == 401:
+ # Release the connection without pulling a body we're about to discard.
+ response.close()
+ response = _do(tokens.token(force_refresh=True))
+
+ if not response.ok:
+ # `raise_for_status` reports status and URL only, so drain a tightly bounded prefix purely
+ # to release the connection — the error path never needs a full page's worth of bytes.
+ _read_truncated_body(response, MAX_ERROR_BODY_BYTES)
+ response.raise_for_status()
+
+ raw = _read_capped_body(response, MAX_RESPONSE_BYTES)
+ if not raw:
+ return None
+ return json.loads(raw)
+
+
+def decode_firestore_value(value: Any) -> Any:
+ """Unwrap one Firestore typed value (`{"stringValue": "x"}`) into a plain Python value."""
+ if not isinstance(value, dict):
+ return None
+ if "nullValue" in value:
+ return None
+ if "booleanValue" in value:
+ return bool(value["booleanValue"])
+ if "integerValue" in value:
+ # Firestore encodes int64 as a JSON string to survive JavaScript's number range.
+ try:
+ return int(value["integerValue"])
+ except (TypeError, ValueError):
+ return None
+ if "doubleValue" in value:
+ try:
+ return float(value["doubleValue"])
+ except (TypeError, ValueError):
+ return None
+ for key in ("timestampValue", "stringValue", "bytesValue", "referenceValue"):
+ if key in value:
+ return value[key]
+ if "geoPointValue" in value:
+ point = value["geoPointValue"] or {}
+ return {"latitude": point.get("latitude"), "longitude": point.get("longitude")}
+ if "arrayValue" in value:
+ return [decode_firestore_value(item) for item in (value["arrayValue"] or {}).get("values") or []]
+ if "mapValue" in value:
+ fields = (value["mapValue"] or {}).get("fields") or {}
+ return {name: decode_firestore_value(item) for name, item in fields.items()}
+ # Pipeline and expression wrappers exist in the API surface but never in a stored document.
+ return None
+
+
+def _as_column(value: Any) -> Any:
+ """Give a column one stable type.
+
+ Firestore and the Realtime Database are schemaless, so a nested value's shape varies document
+ to document. Scalars land in their natural type; anything structured is serialized to JSON so
+ the column stays a string no matter what the next document holds.
+ """
+ if isinstance(value, (dict, list)):
+ return json.dumps(value, default=str)
+ return value
+
+
+def flatten_firestore_document(document: dict[str, Any]) -> dict[str, Any]:
+ """Turn one Firestore document into a flat row of top-level fields plus metadata columns."""
+ name = str(document.get("name") or "")
+ path = name.split("/documents/", 1)[1] if "/documents/" in name else name
+ fields = document.get("fields")
+ if not isinstance(fields, dict):
+ fields = {}
+
+ row: dict[str, Any] = {field: _as_column(decode_firestore_value(value)) for field, value in fields.items()}
+ row[FIRESTORE_ID_COLUMN] = path.rsplit("/", 1)[-1]
+ row[FIRESTORE_PATH_COLUMN] = path
+ row[FIRESTORE_CREATE_TIME_COLUMN] = document.get("createTime")
+ row[FIRESTORE_UPDATE_TIME_COLUMN] = document.get("updateTime")
+ return row
+
+
+def flatten_auth_user(user: dict[str, Any]) -> dict[str, Any]:
+ return {key: _as_column(value) for key, value in user.items() if key not in REDACTED_AUTH_USER_FIELDS}
+
+
+def flatten_realtime_database_child(path: str, key: str, value: Any) -> dict[str, Any]:
+ """Turn one Realtime Database child node into a row.
+
+ Object children get their top-level entries promoted to columns; scalars land in `value`.
+ """
+ row: dict[str, Any] = {}
+ if isinstance(value, dict):
+ row = {name: _as_column(item) for name, item in value.items()}
+ else:
+ row[REALTIME_DATABASE_VALUE_COLUMN] = _as_column(value)
+ row[REALTIME_DATABASE_KEY_COLUMN] = key
+ row[REALTIME_DATABASE_PATH_COLUMN] = f"{path}/{key}"
+ return row
+
+
+def _firestore_documents_root(credentials: FirebaseCredentials) -> str:
+ return f"{FIRESTORE_API_ROOT}/projects/{credentials.project_id}/databases/{credentials.database_id}/documents"
+
+
+def list_collection_ids(
+ session: requests.Session, tokens: AccessTokenProvider, credentials: FirebaseCredentials
+) -> list[str]:
+ """List the root-level Firestore collections in the project's database."""
+ url = f"{_firestore_documents_root(credentials)}:listCollectionIds"
+ collection_ids: list[str] = []
+ page_token: Optional[str] = None
+
+ for _ in range(MAX_PAGES):
+ body: dict[str, Any] = {"pageSize": FIRESTORE_COLLECTION_IDS_PAGE_SIZE}
+ if page_token:
+ body["pageToken"] = page_token
+ payload = _request(session, tokens, "POST", url, json_body=body) or {}
+ collection_ids.extend(str(c) for c in payload.get("collectionIds") or [])
+ page_token = payload.get("nextPageToken")
+ if not page_token:
+ break
+
+ return collection_ids
+
+
+def iter_firestore_documents(
+ session: requests.Session,
+ tokens: AccessTokenProvider,
+ credentials: FirebaseCredentials,
+ collection_id: str,
+ resumable_source_manager: ResumableSourceManager[FirebaseResumeConfig],
+ logger: FilteringBoundLogger,
+) -> Iterator[list[dict[str, Any]]]:
+ url = f"{_firestore_documents_root(credentials)}/{quote(collection_id, safe='')}"
+ page_token = _resume_cursor(resumable_source_manager, logger, f"Firestore collection {collection_id}")
+
+ for _ in range(MAX_PAGES):
+ params: dict[str, Any] = {"pageSize": FIRESTORE_PAGE_SIZE}
+ if page_token:
+ params["pageToken"] = page_token
+ payload = _request(session, tokens, "GET", url, params=params) or {}
+
+ documents = [doc for doc in payload.get("documents") or [] if isinstance(doc, dict)]
+ if documents:
+ yield [flatten_firestore_document(document) for document in documents]
+
+ page_token = payload.get("nextPageToken")
+ if not page_token:
+ break
+ # Saved after yielding so a crash re-yields the last page instead of skipping it.
+ resumable_source_manager.save_state(FirebaseResumeConfig(cursor=page_token))
+
+ resumable_source_manager.clear_state()
+
+
+def iter_auth_users(
+ session: requests.Session,
+ tokens: AccessTokenProvider,
+ credentials: FirebaseCredentials,
+ resumable_source_manager: ResumableSourceManager[FirebaseResumeConfig],
+ logger: FilteringBoundLogger,
+) -> Iterator[list[dict[str, Any]]]:
+ url = f"{IDENTITY_TOOLKIT_API_ROOT}/projects/{credentials.project_id}/accounts:batchGet"
+ page_token = _resume_cursor(resumable_source_manager, logger, "Firebase Auth users")
+
+ for _ in range(MAX_PAGES):
+ params: dict[str, Any] = {"maxResults": AUTH_USERS_PAGE_SIZE}
+ if page_token:
+ params["nextPageToken"] = page_token
+ payload = _request(session, tokens, "GET", url, params=params) or {}
+
+ users = [user for user in payload.get("users") or [] if isinstance(user, dict)]
+ if users:
+ yield [flatten_auth_user(user) for user in users]
+
+ page_token = payload.get("nextPageToken")
+ if not page_token or not users:
+ break
+ resumable_source_manager.save_state(FirebaseResumeConfig(cursor=page_token))
+
+ resumable_source_manager.clear_state()
+
+
+def iter_realtime_database(
+ session: requests.Session,
+ tokens: AccessTokenProvider,
+ credentials: FirebaseCredentials,
+ path: str,
+ resumable_source_manager: ResumableSourceManager[FirebaseResumeConfig],
+ logger: FilteringBoundLogger,
+) -> Iterator[list[dict[str, Any]]]:
+ if not credentials.realtime_database_url:
+ raise FirebaseConfigError("This table needs a Realtime Database URL on the source.")
+
+ base_url = validate_realtime_database_url(credentials.realtime_database_url)
+ url = f"{base_url}/{quote(path, safe='/')}.json"
+ cursor = _resume_cursor(resumable_source_manager, logger, f"Realtime Database path {path}")
+
+ for _ in range(MAX_PAGES):
+ # Ordering by "$key" is always indexed, so paging a large node never needs a rules change.
+ # JSON-quoted values are what the REST API expects for orderBy/startAt.
+ params: dict[str, Any] = {"orderBy": '"$key"', "limitToFirst": REALTIME_DATABASE_PAGE_SIZE}
+ if cursor is not None:
+ params["startAt"] = json.dumps(cursor)
+ payload = _request(session, tokens, "GET", url, params=params)
+
+ children = _realtime_database_children(payload)
+ if children is None:
+ # A scalar node has no children to page through; it is the single row.
+ if payload is not None:
+ scalar_row: dict[str, Any] = {
+ REALTIME_DATABASE_VALUE_COLUMN: _as_column(payload),
+ REALTIME_DATABASE_KEY_COLUMN: path.rsplit("/", 1)[-1],
+ REALTIME_DATABASE_PATH_COLUMN: path,
+ }
+ yield [scalar_row]
+ break
+
+ # `startAt` is inclusive, so each page after the first repeats the cursor row.
+ rows = [(key, value) for key, value in children if cursor is None or key > cursor]
+ if rows:
+ yield [flatten_realtime_database_child(path, key, value) for key, value in rows]
+
+ if len(children) < REALTIME_DATABASE_PAGE_SIZE or not rows:
+ break
+ cursor = rows[-1][0]
+ resumable_source_manager.save_state(FirebaseResumeConfig(cursor=cursor))
+
+ resumable_source_manager.clear_state()
+
+
+def _realtime_database_children(payload: Any) -> Optional[list[tuple[str, Any]]]:
+ """Normalize a Realtime Database node into sorted (key, value) pairs, or None if it has none.
+
+ A node whose keys are consecutive integers comes back as a JSON array, so the index is the key.
+ """
+ if isinstance(payload, dict):
+ # JSON object keys are always strings, but say so explicitly so the row's key column
+ # keeps one type regardless of what the decoder handed back.
+ children: list[tuple[str, Any]] = [(str(key), value) for key, value in payload.items()]
+ return sorted(children)
+ if isinstance(payload, list):
+ return [(str(index), value) for index, value in enumerate(payload) if value is not None]
+ return None
+
+
+def _resume_cursor(
+ resumable_source_manager: ResumableSourceManager[FirebaseResumeConfig],
+ logger: FilteringBoundLogger,
+ label: str,
+) -> Optional[str]:
+ if not resumable_source_manager.can_resume():
+ return None
+ resume = resumable_source_manager.load_state()
+ if resume is None:
+ return None
+ logger.debug(f"Resuming {label} from cursor={resume.cursor}")
+ return resume.cursor
+
+
+def get_rows(
+ credentials: FirebaseCredentials,
+ table_name: str,
+ resumable_source_manager: ResumableSourceManager[FirebaseResumeConfig],
+ logger: FilteringBoundLogger,
+) -> Iterator[list[dict[str, Any]]]:
+ tokens = AccessTokenProvider(_auth_session(credentials), credentials)
+
+ if table_name == AUTH_USERS_TABLE:
+ # Identity Platform hands back `passwordHash`, `salt` and `rawPassword` in the raw response,
+ # and a sample is captured before `flatten_auth_user` strips them — so this surface is read
+ # over a session that never captures at all.
+ auth_session = _api_session(credentials, capture=False)
+ yield from iter_auth_users(auth_session, tokens, credentials, resumable_source_manager, logger)
+ return
+
+ api_session = _api_session(credentials)
+
+ collection_id = _resolve_firestore_collection(table_name)
+ if collection_id is not None:
+ yield from iter_firestore_documents(
+ api_session, tokens, credentials, collection_id, resumable_source_manager, logger
+ )
+ return
+
+ path = _resolve_realtime_database_path(credentials, table_name)
+ if path is not None:
+ yield from iter_realtime_database(api_session, tokens, credentials, path, resumable_source_manager, logger)
+ return
+
+ raise FirebaseConfigError(f"Firebase table {table_name} is not configured on this source.")
+
+
+def _resolve_firestore_collection(table_name: str) -> Optional[str]:
+ """Recover the Firestore collection id a table name was built from."""
+ prefix = firestore_table_name("")
+ if not table_name.startswith(prefix) or len(table_name) == len(prefix):
+ return None
+ return table_name[len(prefix) :]
+
+
+def _resolve_realtime_database_path(credentials: FirebaseCredentials, table_name: str) -> Optional[str]:
+ for path in credentials.realtime_database_paths:
+ if realtime_database_table_name(path) == table_name:
+ return path
+ return None
+
+
+def get_tables(credentials: FirebaseCredentials) -> list[str]:
+ """List every table this source can sync: Auth users, Firestore collections, configured paths."""
+ tables: list[str] = [AUTH_USERS_TABLE]
+
+ tokens = AccessTokenProvider(_auth_session(credentials), credentials)
+ api_session = _api_session(credentials)
+ try:
+ collection_ids = list_collection_ids(api_session, tokens, credentials)
+ tables.extend(firestore_table_name(collection_id) for collection_id in collection_ids)
+ except requests.HTTPError as e:
+ # A project with no Firestore database answers 404, and a service account without the
+ # Datastore role answers 403. Neither should hide the tables the source can still read.
+ status = e.response.status_code if e.response is not None else None
+ if status not in (403, 404):
+ raise
+ LOGGER.warning(f"Skipping Firestore collections for Firebase project {credentials.project_id}: {status}")
+
+ tables.extend(realtime_database_table_name(path) for path in credentials.realtime_database_paths)
+ return tables
+
+
+def validate_credentials(credentials: FirebaseCredentials) -> tuple[bool, Optional[str]]:
+ """Mint a token — the cheapest end-to-end proof the service account key works."""
+ if credentials.realtime_database_url:
+ try:
+ validate_realtime_database_url(credentials.realtime_database_url)
+ except FirebaseConfigError as e:
+ return False, str(e)
+ if not credentials.realtime_database_paths:
+ return False, "Add at least one Realtime Database path to sync, for example `rooms`."
+
+ try:
+ mint_access_token(_auth_session(credentials), credentials)
+ except FirebaseAuthError as e:
+ return False, str(e)
+ except Exception:
+ return False, "Could not reach Google with the provided Firebase service account key."
+ return True, None
+
+
+def firebase_source(
+ credentials: FirebaseCredentials,
+ table_name: str,
+ resumable_source_manager: ResumableSourceManager[FirebaseResumeConfig],
+ logger: FilteringBoundLogger,
+) -> SourceResponse:
+ is_firestore = _resolve_firestore_collection(table_name) is not None
+
+ if table_name == AUTH_USERS_TABLE:
+ primary_keys = AUTH_USERS_PRIMARY_KEY
+ elif is_firestore:
+ primary_keys = [FIRESTORE_ID_COLUMN]
+ else:
+ primary_keys = [REALTIME_DATABASE_KEY_COLUMN]
+
+ return SourceResponse(
+ name=table_name,
+ items=lambda: get_rows(
+ credentials=credentials,
+ table_name=table_name,
+ resumable_source_manager=resumable_source_manager,
+ logger=logger,
+ ),
+ primary_keys=primary_keys,
+ # Rows arrive ordered by document key, not by time, and no surface here filters on a
+ # timestamp, so there is no ascending watermark to declare.
+ sort_mode=None,
+ # Firestore documents run to 1 MiB each, so chunks are capped tighter than the default.
+ chunk_size=2000,
+ chunk_size_bytes=100 * 1024 * 1024,
+ partition_count=1 if is_firestore else None,
+ partition_size=1 if is_firestore else None,
+ partition_mode="datetime" if is_firestore else None,
+ partition_format="month" if is_firestore else None,
+ partition_keys=[FIRESTORE_CREATE_TIME_COLUMN] if is_firestore else None,
+ )
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/firebase/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/firebase/settings.py
new file mode 100644
index 000000000000..e723df6ef42e
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/firebase/settings.py
@@ -0,0 +1,102 @@
+from typing import Final
+
+# Firestore and Identity Platform both expose a `v1` REST surface alongside older `v1beta*`
+# channels; `v1` is the generally available one.
+API_VERSION: Final[str] = "v1"
+
+FIRESTORE_API_ROOT: Final[str] = f"https://firestore.googleapis.com/{API_VERSION}"
+IDENTITY_TOOLKIT_API_ROOT: Final[str] = f"https://identitytoolkit.googleapis.com/{API_VERSION}"
+GOOGLE_TOKEN_URI: Final[str] = "https://oauth2.googleapis.com/token"
+
+# Scopes requested in the service-account assertion. Google mints a token for whatever a service
+# account asks for; what it can actually read is decided by the IAM roles on the project, so
+# asking for all three costs nothing and keeps one token usable across every surface.
+OAUTH_SCOPES: Final[str] = (
+ "https://www.googleapis.com/auth/datastore " # Cloud Firestore
+ "https://www.googleapis.com/auth/firebase " # Identity Platform / Firebase Auth
+ "https://www.googleapis.com/auth/firebase.database " # Realtime Database
+ "https://www.googleapis.com/auth/userinfo.email" # required alongside firebase.database
+)
+
+DEFAULT_DATABASE_ID: Final[str] = "(default)"
+
+AUTH_USERS_TABLE: Final[str] = "auth_users"
+FIRESTORE_TABLE_PREFIX: Final[str] = "firestore_"
+REALTIME_DATABASE_TABLE_PREFIX: Final[str] = "realtime_database_"
+
+# Firestore caps a `listDocuments` page at 300 documents; Identity Platform caps `accounts:batchGet`
+# at 1000; the Realtime Database has no documented cap, so this is a memory choice.
+FIRESTORE_PAGE_SIZE: Final[int] = 300
+FIRESTORE_COLLECTION_IDS_PAGE_SIZE: Final[int] = 300
+AUTH_USERS_PAGE_SIZE: Final[int] = 1000
+REALTIME_DATABASE_PAGE_SIZE: Final[int] = 500
+
+# Hard stop so an endpoint that keeps handing back a page token can't page forever.
+MAX_PAGES: Final[int] = 100_000
+
+REQUEST_TIMEOUT_SECONDS: Final[int] = 120
+
+# Byte caps on response bodies. The page sizes above bound the row count but not the byte count —
+# a Firestore document may be 1 MiB and the Realtime Database documents no page ceiling at all — so
+# without these a single page could buffer hundreds of MiB in a shared worker before `json.loads`
+# builds a second, larger representation of it. The caps apply to the *decompressed* body, so a
+# compressed payload can't expand past them either.
+#
+# 64 MiB sits far above any realistic page (300 Firestore documents at a typical few KiB each is
+# single-digit MiB) while still bounding the spike. Token and error bodies are small and
+# well-known, so they get much tighter caps.
+MAX_RESPONSE_BYTES: Final[int] = 64 * 1024 * 1024
+MAX_TOKEN_RESPONSE_BYTES: Final[int] = 256 * 1024
+MAX_ERROR_BODY_BYTES: Final[int] = 64 * 1024
+
+# Re-fetching the same page returns the same oversized body, so this never becomes retryable.
+RESPONSE_TOO_LARGE_ERROR: Final[str] = "Firebase returned an oversized response body"
+
+# Re-mint a little before Google's stated expiry so a long-running page fetch can't start with a
+# token that expires mid-flight.
+TOKEN_EXPIRY_SKEW_SECONDS: Final[int] = 120
+JWT_ASSERTION_LIFETIME_SECONDS: Final[int] = 3600
+JWT_GRANT_TYPE: Final[str] = "urn:ietf:params:oauth:grant-type:jwt-bearer"
+
+# Firestore documents are schemaless, so the sync adds its own metadata columns. The `_firestore_`
+# prefix keeps them from colliding with a document field of the same name.
+FIRESTORE_ID_COLUMN: Final[str] = "_firestore_id"
+FIRESTORE_PATH_COLUMN: Final[str] = "_firestore_path"
+FIRESTORE_CREATE_TIME_COLUMN: Final[str] = "_firestore_create_time"
+FIRESTORE_UPDATE_TIME_COLUMN: Final[str] = "_firestore_update_time"
+
+REALTIME_DATABASE_KEY_COLUMN: Final[str] = "_realtime_database_key"
+REALTIME_DATABASE_PATH_COLUMN: Final[str] = "_realtime_database_path"
+# Holds the child node when it is a scalar rather than an object.
+REALTIME_DATABASE_VALUE_COLUMN: Final[str] = "value"
+
+AUTH_USERS_PRIMARY_KEY: Final[list[str]] = ["localId"]
+
+# Password material Identity Platform returns to sufficiently privileged callers. Warehousing a
+# password hash serves no analytics purpose, so it never leaves the source.
+REDACTED_AUTH_USER_FIELDS: Final[frozenset[str]] = frozenset({"passwordHash", "salt", "rawPassword"})
+
+# The only hosts a Realtime Database lives on. Restricting to these stops a source edit from
+# pointing the minted Google access token at an arbitrary server.
+REALTIME_DATABASE_HOST_SUFFIXES: Final[tuple[str, ...]] = (".firebaseio.com", ".firebasedatabase.app")
+
+
+def firestore_table_name(collection_id: str) -> str:
+ return f"{FIRESTORE_TABLE_PREFIX}{collection_id}"
+
+
+def realtime_database_table_name(path: str) -> str:
+ """Table name for one Realtime Database path. `rooms/lobby` becomes `..._rooms_lobby`."""
+ return f"{REALTIME_DATABASE_TABLE_PREFIX}{path.strip('/').replace('/', '_')}"
+
+
+def parse_realtime_database_paths(raw: str | None) -> list[str]:
+ """Split the comma-separated path list from the source form, dropping blanks and slashes."""
+ if not raw:
+ return []
+ seen: list[str] = []
+ for candidate in raw.split(","):
+ path = candidate.strip().strip("/")
+ if path and path not in seen:
+ seen.append(path)
+ return seen
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/firebase/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/firebase/source.py
index f30ab0e748c1..4aae7b85d3ad 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/firebase/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/firebase/source.py
@@ -1,13 +1,37 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
DataWarehouseSourceCategory,
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldFileUploadConfig,
+ SourceFieldFileUploadJsonFormatConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
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.common.typings import SourceInputs, SourceResponse
+from products.warehouse_sources.backend.temporal.data_imports.sources.firebase.firebase import (
+ FirebaseCredentials,
+ FirebaseResumeConfig,
+ firebase_source,
+ get_tables,
+ validate_credentials as validate_firebase_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.firebase.settings import (
+ API_VERSION,
+ DEFAULT_DATABASE_ID,
+ RESPONSE_TOO_LARGE_ERROR,
+ parse_realtime_database_paths,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.firebase import (
FirebaseSourceConfig,
)
@@ -15,18 +39,147 @@ from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class FirebaseSource(SimpleSource[FirebaseSourceConfig]):
+class FirebaseSource(ResumableSource[FirebaseSourceConfig, FirebaseResumeConfig]):
+ # Firestore and Identity Platform both keep `v1beta*` channels alongside `v1`; `v1` is GA.
+ supported_versions = (API_VERSION,)
+ default_version = API_VERSION
+ api_docs_url = "https://firebase.google.com/docs/firestore/reference/rest"
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.FIREBASE
+ @property
+ def connection_host_fields(self) -> list[str]:
+ # The Realtime Database URL is where the minted Google access token gets sent, so
+ # retargeting it has to re-require the service account key. `database_id` and
+ # `realtime_database_paths` don't change the host, but they do select which Firestore
+ # database and which Realtime Database nodes the preserved key reads — the same
+ # retargeting risk against a different data scope — so gate all three the same way.
+ return ["database_id", "realtime_database_url", "realtime_database_paths"]
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "error=invalid_grant": "Google rejected this service account key. Generate a new key in the Firebase console and reconnect.",
+ "Google refused to issue an access token": "Google could not issue an access token for this service account. Check that the key file is complete and the service account still exists.",
+ "private key could not be read": "The uploaded key file does not contain a usable private key. Upload the JSON key exactly as Google generated it.",
+ "401 Client Error: Unauthorized": "Firebase rejected the access token. The service account key may have been revoked — please reconnect.",
+ "403 Client Error: Forbidden": "This service account cannot read the requested Firebase data. Grant it the Firebase Viewer, Cloud Datastore Viewer, or Firebase Realtime Database Viewer role.",
+ RESPONSE_TOO_LARGE_ERROR: "Firebase returned a page too large to process. Reduce the size of the documents in this collection or path, then re-run the sync.",
+ }
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=SchemaExternalDataSourceType.FIREBASE,
category=DataWarehouseSourceCategory.DATABASES,
label="Firebase",
+ caption="""Connect a Firebase project to pull Cloud Firestore collections, Firebase Auth users, and Realtime Database paths into the PostHog Data warehouse.
+
+Create a service account key in the Firebase console under Project settings, Service accounts, Generate new private key, then upload that JSON file here. Grant the service account **Firebase Viewer** to read Auth users, **Cloud Datastore Viewer** to read Firestore, and **Firebase Realtime Database Viewer** to read the Realtime Database.""",
iconPath="/static/services/firebase.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl="https://posthog.com/docs/cdp/sources/firebase",
+ releaseStatus=ReleaseStatus.ALPHA,
+ keywords=["firestore", "rtdb", "gcp", "nosql"],
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldFileUploadConfig(
+ name="key_file",
+ label="Firebase service account JSON key file",
+ fileFormat=SourceFieldFileUploadJsonFormatConfig(
+ format=".json",
+ keys=["project_id", "private_key", "private_key_id", "client_email", "token_uri"],
+ ),
+ required=True,
+ ),
+ SourceFieldInputConfig(
+ name="database_id",
+ label="Firestore database ID",
+ type=SourceFieldInputConfigType.TEXT,
+ required=False,
+ placeholder=DEFAULT_DATABASE_ID,
+ secret=False,
+ ),
+ SourceFieldInputConfig(
+ name="realtime_database_url",
+ label="Realtime Database URL",
+ type=SourceFieldInputConfigType.TEXT,
+ required=False,
+ placeholder="https://my-project-default-rtdb.firebaseio.com",
+ secret=False,
+ ),
+ SourceFieldInputConfig(
+ name="realtime_database_paths",
+ label="Realtime Database paths",
+ type=SourceFieldInputConfigType.TEXT,
+ required=False,
+ placeholder="rooms, messages/lobby",
+ secret=False,
+ ),
+ ],
+ ),
+ )
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.firebase.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_schemas(
+ self,
+ config: FirebaseSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ api_version: str | None = None,
+ ) -> list[SourceSchema]:
+ # Firestore collections are created by the customer's app, so the table list can only come
+ # from the live project. Nothing here supports a server-side timestamp filter, so every
+ # table is full refresh.
+ tables = get_tables(self._credentials(config))
+ if names is not None:
+ wanted = set(names)
+ tables = [table for table in tables if table in wanted]
+ return [SourceSchema(name=table, supports_incremental=False, supports_append=False) for table in tables]
+
+ def _credentials(self, config: FirebaseSourceConfig) -> FirebaseCredentials:
+ database_id = (config.database_id or "").strip() or DEFAULT_DATABASE_ID
+ return FirebaseCredentials(
+ project_id=config.key_file.project_id,
+ client_email=config.key_file.client_email,
+ private_key=config.key_file.private_key,
+ private_key_id=config.key_file.private_key_id,
+ token_uri=config.key_file.token_uri,
+ database_id=database_id,
+ realtime_database_url=(config.realtime_database_url or "").strip() or None,
+ realtime_database_paths=tuple(parse_realtime_database_paths(config.realtime_database_paths)),
+ )
+
+ def validate_credentials(
+ self,
+ config: FirebaseSourceConfig,
+ team_id: int,
+ schema_name: Optional[str] = None,
+ api_version: str | None = None,
+ ) -> tuple[bool, str | None]:
+ return validate_firebase_credentials(self._credentials(config))
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[FirebaseResumeConfig]:
+ return ResumableSourceManager[FirebaseResumeConfig](inputs, FirebaseResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: FirebaseSourceConfig,
+ resumable_source_manager: ResumableSourceManager[FirebaseResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return firebase_source(
+ credentials=self._credentials(config),
+ table_name=inputs.schema_name,
+ resumable_source_manager=resumable_source_manager,
+ logger=inputs.logger,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/firebase/tests/conftest.py b/products/warehouse_sources/backend/temporal/data_imports/sources/firebase/tests/conftest.py
new file mode 100644
index 000000000000..65ea787b31e3
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/firebase/tests/conftest.py
@@ -0,0 +1,159 @@
+import json
+from collections.abc import Iterator
+from typing import Any, Optional, cast
+
+import pytest
+
+import requests
+import structlog
+from cryptography.hazmat.primitives import serialization
+from cryptography.hazmat.primitives.asymmetric import rsa
+from structlog.types import FilteringBoundLogger
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.firebase.firebase import (
+ FirebaseCredentials,
+ FirebaseResumeConfig,
+)
+
+_KEY = rsa.generate_private_key(public_exponent=65537, key_size=2048)
+
+PRIVATE_KEY_PEM: str = _KEY.private_bytes(
+ encoding=serialization.Encoding.PEM,
+ format=serialization.PrivateFormat.PKCS8,
+ encryption_algorithm=serialization.NoEncryption(),
+).decode()
+
+PUBLIC_KEY_PEM: str = (
+ _KEY.public_key()
+ .public_bytes(
+ encoding=serialization.Encoding.PEM,
+ format=serialization.PublicFormat.SubjectPublicKeyInfo,
+ )
+ .decode()
+)
+
+TOKEN_PAYLOAD: dict[str, Any] = {"access_token": "tok-1", "expires_in": 3600, "token_type": "Bearer"}
+
+
+class FakeRaw:
+ """Minimal stand-in for urllib3's response body: a capped, position-tracking read().
+
+ `bytes_read` lets a test assert how much of an oversized body actually got pulled into memory,
+ which is the whole point of the caps — a body that is merely *rejected* after being fully
+ buffered would still have caused the memory spike.
+ """
+
+ def __init__(self, body: bytes) -> None:
+ self._body = body
+ self.bytes_read = 0
+
+ def read(self, amt: Optional[int] = None, decode_content: bool = False) -> bytes:
+ end = len(self._body) if amt is None else min(self.bytes_read + amt, len(self._body))
+ chunk = self._body[self.bytes_read : end]
+ self.bytes_read = end
+ return chunk
+
+
+class FakeResponse:
+ def __init__(
+ self,
+ status_code: int = 200,
+ payload: Any = None,
+ url: str = "https://firestore.googleapis.com/v1",
+ body: Optional[bytes] = None,
+ ) -> None:
+ self.status_code = status_code
+ self.url = url
+ # The transport reads bodies via `raw.read(...)` under a byte cap and never calls `.json()`,
+ # so the fake carries the payload as serialized bytes exactly like a real response would —
+ # and deliberately offers no `.json()`, so a regression back to it fails loudly. `body` lets
+ # a test supply bytes directly, for the oversized and malformed cases `payload` can't express.
+ if body is None:
+ body = b"" if payload is None else json.dumps(payload).encode()
+ self.raw = FakeRaw(body)
+ self.closed = False
+
+ @property
+ def ok(self) -> bool:
+ return self.status_code < 400
+
+ def close(self) -> None:
+ self.closed = True
+
+ def raise_for_status(self) -> None:
+ if self.ok:
+ return
+ label = "Client Error" if self.status_code < 500 else "Server Error"
+ response = requests.Response()
+ response.status_code = self.status_code
+ response.url = self.url
+ raise requests.HTTPError(f"{self.status_code} {label}: for url: {self.url}", response=response)
+
+
+class FakeSession:
+ """Stand-in for the tracked session: pops queued responses and records every call."""
+
+ def __init__(
+ self,
+ request_responses: Optional[list[FakeResponse]] = None,
+ post_responses: Optional[list[FakeResponse]] = None,
+ ) -> None:
+ self.request_queue: list[FakeResponse] = list(request_responses or [])
+ self.post_queue: list[FakeResponse] = list(post_responses or [])
+ self.requests: list[tuple[str, str, dict[str, Any]]] = []
+ self.posts: list[tuple[str, dict[str, Any]]] = []
+
+ def request(self, method: str, url: str, **kwargs: Any) -> FakeResponse:
+ self.requests.append((method, url, kwargs))
+ if not self.request_queue:
+ raise AssertionError(f"unexpected {method} {url}")
+ return self.request_queue.pop(0)
+
+ def post(self, url: str, **kwargs: Any) -> FakeResponse:
+ self.posts.append((url, kwargs))
+ if not self.post_queue:
+ raise AssertionError(f"unexpected POST {url}")
+ return self.post_queue.pop(0)
+
+ def as_session(self) -> requests.Session:
+ """Hand this fake to helpers that take a real `requests.Session`."""
+ return cast("requests.Session", self)
+
+
+class FakeResumeManager(ResumableSourceManager[FirebaseResumeConfig]):
+ """In-memory resume manager so transport tests don't need Redis."""
+
+ def __init__(self, state: Optional[FirebaseResumeConfig] = None) -> None:
+ self.state = state
+ self.saved: list[FirebaseResumeConfig] = []
+ self.cleared = False
+
+ def can_resume(self) -> bool:
+ return self.state is not None
+
+ def load_state(self) -> Optional[FirebaseResumeConfig]:
+ return self.state
+
+ def save_state(self, data: FirebaseResumeConfig) -> None:
+ self.saved.append(data)
+
+ def clear_state(self) -> None:
+ self.cleared = True
+
+
+def credentials(**overrides: Any) -> FirebaseCredentials:
+ defaults: dict[str, Any] = {
+ "project_id": "demo-project",
+ "client_email": "[email protected]",
+ "private_key": PRIVATE_KEY_PEM,
+ "private_key_id": "key-id",
+ "token_uri": "https://oauth2.googleapis.com/token",
+ }
+ defaults.update(overrides)
+ return FirebaseCredentials(**defaults)
+
+
+def logger() -> Iterator[FilteringBoundLogger]:
+ yield structlog.get_logger("firebase-test")
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/firebase/tests/test_firebase.py b/products/warehouse_sources/backend/temporal/data_imports/sources/firebase/tests/test_firebase.py
new file mode 100644
index 000000000000..ad30902d7fa4
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/firebase/tests/test_firebase.py
@@ -0,0 +1,802 @@
+import json
+from typing import Any, Optional
+
+import pytest
+from unittest import mock
+
+import jwt
+import requests
+from structlog.types import FilteringBoundLogger
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.firebase.firebase import (
+ AccessTokenProvider,
+ FirebaseAuthError,
+ FirebaseConfigError,
+ FirebaseResponseTooLargeError,
+ FirebaseResumeConfig,
+ build_jwt_assertion,
+ decode_firestore_value,
+ firebase_source,
+ flatten_auth_user,
+ flatten_firestore_document,
+ flatten_realtime_database_child,
+ get_rows,
+ get_tables,
+ iter_auth_users,
+ iter_firestore_documents,
+ iter_realtime_database,
+ list_collection_ids,
+ mint_access_token,
+ validate_credentials,
+ validate_realtime_database_url,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.firebase.settings import (
+ AUTH_USERS_TABLE,
+ FIRESTORE_CREATE_TIME_COLUMN,
+ FIRESTORE_ID_COLUMN,
+ FIRESTORE_PATH_COLUMN,
+ FIRESTORE_UPDATE_TIME_COLUMN,
+ GOOGLE_TOKEN_URI,
+ JWT_ASSERTION_LIFETIME_SECONDS,
+ OAUTH_SCOPES,
+ REALTIME_DATABASE_KEY_COLUMN,
+ REALTIME_DATABASE_PAGE_SIZE,
+ REALTIME_DATABASE_PATH_COLUMN,
+ REALTIME_DATABASE_VALUE_COLUMN,
+ RESPONSE_TOO_LARGE_ERROR,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.firebase.tests.conftest import (
+ PUBLIC_KEY_PEM,
+ TOKEN_PAYLOAD,
+ FakeResponse,
+ FakeResumeManager,
+ FakeSession,
+ credentials,
+)
+
+_FIREBASE_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.firebase.firebase"
+_SESSION_FACTORY = f"{_FIREBASE_MODULE}.make_tracked_session"
+
+# Stand-ins for the shipped byte caps, small enough that a test can overflow one cheaply.
+_PAGE_CAP = 2048
+_ERROR_CAP = 64
+
+DOCUMENTS_ROOT = "https://firestore.googleapis.com/v1/projects/demo-project/databases/(default)/documents"
+
+
+def token_provider(session: FakeSession) -> AccessTokenProvider:
+ return AccessTokenProvider(session.as_session(), credentials())
+
+
+def firestore_document(document_id: str, fields: Optional[dict[str, Any]] = None) -> dict[str, Any]:
+ return {
+ "name": f"projects/demo-project/databases/(default)/documents/rooms/{document_id}",
+ "fields": fields if fields is not None else {"title": {"stringValue": document_id}},
+ "createTime": "2024-01-02T03:04:05.000000Z",
+ "updateTime": "2024-05-06T07:08:09.000000Z",
+ }
+
+
+class TestFirestoreValueDecoding:
+ @pytest.mark.parametrize(
+ "wrapper,expected",
+ [
+ ({"stringValue": "hello"}, "hello"),
+ ({"integerValue": "42"}, 42),
+ ({"integerValue": "not-a-number"}, None),
+ ({"doubleValue": 1.5}, 1.5),
+ ({"booleanValue": False}, False),
+ ({"nullValue": "NULL_VALUE"}, None),
+ ({"timestampValue": "2024-01-01T00:00:00Z"}, "2024-01-01T00:00:00Z"),
+ ({"bytesValue": "aGk="}, "aGk="),
+ (
+ {"referenceValue": "projects/p/databases/(default)/documents/rooms/a"},
+ "projects/p/databases/(default)/documents/rooms/a",
+ ),
+ ({"geoPointValue": {"latitude": 1.0, "longitude": 2.0}}, {"latitude": 1.0, "longitude": 2.0}),
+ ({"arrayValue": {"values": [{"stringValue": "a"}, {"integerValue": "2"}]}}, ["a", 2]),
+ ({"arrayValue": {}}, []),
+ ({"mapValue": {"fields": {"inner": {"stringValue": "x"}}}}, {"inner": "x"}),
+ ({"doubleValue": "not-a-number"}, None),
+ ({"pipelineValue": {}}, None),
+ ("not-a-wrapper", None),
+ ],
+ )
+ def test_decodes_every_stored_value_type(self, wrapper: Any, expected: Any) -> None:
+ assert decode_firestore_value(wrapper) == expected
+
+ def test_nested_containers_are_json_encoded_so_the_column_type_is_stable(self) -> None:
+ row = flatten_firestore_document(
+ firestore_document(
+ "abc",
+ {
+ "title": {"stringValue": "Lobby"},
+ "members": {"arrayValue": {"values": [{"stringValue": "a"}]}},
+ "meta": {"mapValue": {"fields": {"pinned": {"booleanValue": True}}}},
+ },
+ )
+ )
+
+ assert row["title"] == "Lobby"
+ assert json.loads(row["members"]) == ["a"]
+ assert json.loads(row["meta"]) == {"pinned": True}
+
+ def test_metadata_columns_describe_the_document(self) -> None:
+ row = flatten_firestore_document(firestore_document("abc"))
+
+ assert row[FIRESTORE_ID_COLUMN] == "abc"
+ assert row[FIRESTORE_PATH_COLUMN] == "rooms/abc"
+ assert row[FIRESTORE_CREATE_TIME_COLUMN] == "2024-01-02T03:04:05.000000Z"
+ assert row[FIRESTORE_UPDATE_TIME_COLUMN] == "2024-05-06T07:08:09.000000Z"
+
+ def test_document_with_no_fields_still_produces_metadata(self) -> None:
+ row = flatten_firestore_document({"name": "", "createTime": None, "updateTime": None})
+
+ assert row[FIRESTORE_ID_COLUMN] == ""
+ assert row[FIRESTORE_PATH_COLUMN] == ""
+
+
+class TestRowFlattening:
+ def test_auth_user_drops_password_material(self) -> None:
+ row = flatten_auth_user(
+ {
+ "localId": "u1",
+ "email": "[email protected]",
+ "passwordHash": "hash",
+ "salt": "salt",
+ "rawPassword": "hunter2",
+ "providerUserInfo": [{"providerId": "google.com"}],
+ }
+ )
+
+ assert set(row) == {"localId", "email", "providerUserInfo"}
+ assert json.loads(row["providerUserInfo"]) == [{"providerId": "google.com"}]
+
+ @pytest.mark.parametrize(
+ "value,expected_columns",
+ [
+ ({"name": "Lobby", "size": 3}, {"name": "Lobby", "size": 3}),
+ ({"nested": {"a": 1}}, {"nested": '{"a": 1}'}),
+ ("scalar", {REALTIME_DATABASE_VALUE_COLUMN: "scalar"}),
+ (7, {REALTIME_DATABASE_VALUE_COLUMN: 7}),
+ ],
+ )
+ def test_realtime_database_child_shapes(self, value: Any, expected_columns: dict[str, Any]) -> None:
+ row = flatten_realtime_database_child("rooms", "k1", value)
+
+ assert row[REALTIME_DATABASE_KEY_COLUMN] == "k1"
+ assert row[REALTIME_DATABASE_PATH_COLUMN] == "rooms/k1"
+ for column, expected in expected_columns.items():
+ assert row[column] == expected
+
+
+class TestAccessTokens:
+ def test_assertion_is_signed_for_googles_token_endpoint(self) -> None:
+ assertion = build_jwt_assertion(credentials())
+
+ claims = jwt.decode(
+ assertion, PUBLIC_KEY_PEM, algorithms=["RS256"], audience="https://oauth2.googleapis.com/token"
+ )
+ assert claims["iss"] == "[email protected]"
+ assert claims["scope"] == OAUTH_SCOPES
+ assert jwt.get_unverified_header(assertion)["kid"] == "key-id"
+
+ def test_token_uri_from_the_key_file_cannot_retarget_the_exchange(self) -> None:
+ hostile = credentials(token_uri="http://169.254.169.254/latest/meta-data/")
+ session = FakeSession(post_responses=[FakeResponse(payload=TOKEN_PAYLOAD)])
+
+ mint_access_token(session.as_session(), hostile)
+
+ assert session.posts[0][0] == GOOGLE_TOKEN_URI
+ claims = jwt.decode(
+ session.posts[0][1]["data"]["assertion"],
+ PUBLIC_KEY_PEM,
+ algorithms=["RS256"],
+ audience=GOOGLE_TOKEN_URI,
+ )
+ assert claims["aud"] == GOOGLE_TOKEN_URI
+
+ def test_unreadable_private_key_is_reported_as_an_auth_error(self) -> None:
+ with pytest.raises(FirebaseAuthError, match="could not be read"):
+ build_jwt_assertion(credentials(private_key="not-a-key"))
+
+ def test_mint_returns_the_token_and_its_lifetime(self) -> None:
+ session = FakeSession(post_responses=[FakeResponse(payload=TOKEN_PAYLOAD)])
+
+ assert mint_access_token(session.as_session(), credentials()) == ("tok-1", 3600)
+
+ @pytest.mark.parametrize(
+ "response,message",
+ [
+ (FakeResponse(status_code=400, payload={"error": "invalid_grant"}), "invalid_grant"),
+ (FakeResponse(status_code=403, payload={"error": {"status": "PERMISSION_DENIED"}}), "PERMISSION_DENIED"),
+ # A gateway can answer with HTML or an empty body; the status alone still has to surface.
+ (FakeResponse(status_code=502), "status=502"),
+ (FakeResponse(status_code=400, payload={"nothing": "useful"}), "status=400"),
+ (FakeResponse(payload={"token_type": "Bearer"}), "did not contain an access token"),
+ ],
+ )
+ def test_token_failures_raise_with_googles_reason(self, response: FakeResponse, message: str) -> None:
+ session = FakeSession(post_responses=[response])
+
+ with pytest.raises(FirebaseAuthError, match=message):
+ mint_access_token(session.as_session(), credentials())
+
+ @pytest.mark.parametrize(
+ "body,expected_lifetime",
+ [
+ # A zero lifetime is a real answer, not a missing one: treating it as missing would
+ # cache a dead token for an hour and turn every request into a 401.
+ ({**TOKEN_PAYLOAD, "expires_in": 0}, 0),
+ ({**TOKEN_PAYLOAD, "expires_in": 60}, 60),
+ ({"access_token": "tok-1", "token_type": "Bearer"}, JWT_ASSERTION_LIFETIME_SECONDS),
+ ({**TOKEN_PAYLOAD, "expires_in": "not-a-number"}, JWT_ASSERTION_LIFETIME_SECONDS),
+ ],
+ )
+ def test_lifetime_falls_back_only_when_google_omits_it(self, body: Any, expected_lifetime: int) -> None:
+ session = FakeSession(post_responses=[FakeResponse(payload=body)])
+
+ assert mint_access_token(session.as_session(), credentials()) == ("tok-1", expected_lifetime)
+
+ def test_token_is_reused_until_forced_to_refresh(self) -> None:
+ session = FakeSession(
+ post_responses=[
+ FakeResponse(payload=TOKEN_PAYLOAD),
+ FakeResponse(payload={**TOKEN_PAYLOAD, "access_token": "tok-2"}),
+ ]
+ )
+ tokens = token_provider(session)
+
+ assert tokens.token() == "tok-1"
+ assert tokens.token() == "tok-1"
+ assert tokens.token(force_refresh=True) == "tok-2"
+ assert len(session.posts) == 2
+
+ def test_expired_token_mid_sync_is_reminted_once(self, logger: FilteringBoundLogger) -> None:
+ session = FakeSession(
+ request_responses=[
+ FakeResponse(status_code=401, payload={"error": {"status": "UNAUTHENTICATED"}}),
+ FakeResponse(payload={"documents": [firestore_document("abc")]}),
+ ],
+ post_responses=[
+ FakeResponse(payload=TOKEN_PAYLOAD),
+ FakeResponse(payload={**TOKEN_PAYLOAD, "access_token": "tok-2"}),
+ ],
+ )
+
+ batches = list(
+ iter_firestore_documents(
+ session.as_session(), token_provider(session), credentials(), "rooms", FakeResumeManager(), logger
+ )
+ )
+
+ assert len(batches) == 1
+ assert session.requests[1][2]["headers"] == {"Authorization": "Bearer tok-2"}
+
+
+class TestFirestorePagination:
+ def test_pages_and_checkpoints_after_each_yield(self, logger: FilteringBoundLogger) -> None:
+ session = FakeSession(
+ request_responses=[
+ FakeResponse(payload={"documents": [firestore_document("a")], "nextPageToken": "page-2"}),
+ FakeResponse(payload={"documents": [firestore_document("b")]}),
+ ],
+ post_responses=[FakeResponse(payload=TOKEN_PAYLOAD)],
+ )
+ manager = FakeResumeManager()
+
+ batches = list(
+ iter_firestore_documents(
+ session.as_session(), token_provider(session), credentials(), "rooms", manager, logger
+ )
+ )
+
+ assert [row[FIRESTORE_ID_COLUMN] for batch in batches for row in batch] == ["a", "b"]
+ assert [state.cursor for state in manager.saved] == ["page-2"]
+ assert manager.cleared is True
+ assert session.requests[1][2]["params"]["pageToken"] == "page-2"
+
+ def test_resumes_from_the_saved_page_token(self, logger: FilteringBoundLogger) -> None:
+ session = FakeSession(
+ request_responses=[FakeResponse(payload={"documents": [firestore_document("c")]})],
+ post_responses=[FakeResponse(payload=TOKEN_PAYLOAD)],
+ )
+
+ list(
+ iter_firestore_documents(
+ session.as_session(),
+ token_provider(session),
+ credentials(),
+ "rooms",
+ FakeResumeManager(FirebaseResumeConfig(cursor="page-9")),
+ logger,
+ )
+ )
+
+ assert session.requests[0][2]["params"]["pageToken"] == "page-9"
+
+ def test_a_resume_marker_with_no_state_behind_it_starts_from_the_beginning(
+ self, logger: FilteringBoundLogger
+ ) -> None:
+ # `can_resume()` and `load_state()` are two round trips to the store, so a checkpoint that
+ # is cleared between them is reachable. It has to read as "no cursor", not crash.
+ class VanishingResumeManager(FakeResumeManager):
+ def can_resume(self) -> bool:
+ return True
+
+ session = FakeSession(
+ request_responses=[FakeResponse(payload={"documents": [firestore_document("a")]})],
+ post_responses=[FakeResponse(payload=TOKEN_PAYLOAD)],
+ )
+
+ list(
+ iter_firestore_documents(
+ session.as_session(),
+ token_provider(session),
+ credentials(),
+ "rooms",
+ VanishingResumeManager(),
+ logger,
+ )
+ )
+
+ assert "pageToken" not in session.requests[0][2]["params"]
+
+ def test_collection_id_is_url_escaped(self, logger: FilteringBoundLogger) -> None:
+ session = FakeSession(
+ request_responses=[FakeResponse(payload={})], post_responses=[FakeResponse(payload=TOKEN_PAYLOAD)]
+ )
+
+ list(
+ iter_firestore_documents(
+ session.as_session(), token_provider(session), credentials(), "chat rooms", FakeResumeManager(), logger
+ )
+ )
+
+ assert session.requests[0][1] == f"{DOCUMENTS_ROOT}/chat%20rooms"
+
+ def test_collection_ids_are_paged(self) -> None:
+ session = FakeSession(
+ request_responses=[
+ FakeResponse(payload={"collectionIds": ["rooms"], "nextPageToken": "next"}),
+ FakeResponse(payload={"collectionIds": ["users"]}),
+ ],
+ post_responses=[FakeResponse(payload=TOKEN_PAYLOAD)],
+ )
+
+ assert list_collection_ids(session.as_session(), token_provider(session), credentials()) == ["rooms", "users"]
+ assert session.requests[0][1] == f"{DOCUMENTS_ROOT}:listCollectionIds"
+ assert session.requests[1][2]["json"]["pageToken"] == "next"
+
+
+class TestAuthUsersPagination:
+ def test_stops_when_google_returns_no_token(self, logger: FilteringBoundLogger) -> None:
+ session = FakeSession(
+ request_responses=[
+ FakeResponse(payload={"users": [{"localId": "u1"}], "nextPageToken": "p2"}),
+ FakeResponse(payload={"users": [{"localId": "u2"}]}),
+ ],
+ post_responses=[FakeResponse(payload=TOKEN_PAYLOAD)],
+ )
+ manager = FakeResumeManager()
+
+ batches = list(iter_auth_users(session.as_session(), token_provider(session), credentials(), manager, logger))
+
+ assert [row["localId"] for batch in batches for row in batch] == ["u1", "u2"]
+ assert [state.cursor for state in manager.saved] == ["p2"]
+ assert session.requests[0][1].endswith("/projects/demo-project/accounts:batchGet")
+
+ def test_stops_on_an_empty_page_even_when_a_token_is_returned(self, logger: FilteringBoundLogger) -> None:
+ session = FakeSession(
+ request_responses=[FakeResponse(payload={"users": [], "nextPageToken": "p2"})],
+ post_responses=[FakeResponse(payload=TOKEN_PAYLOAD)],
+ )
+
+ batches = list(
+ iter_auth_users(session.as_session(), token_provider(session), credentials(), FakeResumeManager(), logger)
+ )
+
+ assert batches == []
+
+
+class TestRealtimeDatabase:
+ @pytest.mark.parametrize(
+ "url,expected",
+ [
+ ("https://demo-default-rtdb.firebaseio.com", "https://demo-default-rtdb.firebaseio.com"),
+ ("https://demo.europe-west1.firebasedatabase.app/", "https://demo.europe-west1.firebasedatabase.app"),
+ (" https://Demo-Default-Rtdb.firebaseio.com ", "https://demo-default-rtdb.firebaseio.com"),
+ ],
+ )
+ def test_accepts_firebase_hosts(self, url: str, expected: str) -> None:
+ assert validate_realtime_database_url(url) == expected
+
+ @pytest.mark.parametrize(
+ "url",
+ [
+ "http://demo-default-rtdb.firebaseio.com",
+ "https://attacker.example.com",
+ "https://firebaseio.com.attacker.example",
+ "https://169.254.169.254",
+ "not-a-url",
+ ],
+ )
+ def test_rejects_everything_else(self, url: str) -> None:
+ with pytest.raises(FirebaseConfigError):
+ validate_realtime_database_url(url)
+
+ def test_pages_by_key_and_drops_the_repeated_boundary_row(self, logger: FilteringBoundLogger) -> None:
+ first_page = {f"k{index:04d}": {"n": index} for index in range(REALTIME_DATABASE_PAGE_SIZE)}
+ last_key = f"k{REALTIME_DATABASE_PAGE_SIZE - 1:04d}"
+ session = FakeSession(
+ request_responses=[
+ FakeResponse(payload=first_page),
+ FakeResponse(payload={last_key: {"n": -1}, "k9999": {"n": 1}}),
+ ],
+ post_responses=[FakeResponse(payload=TOKEN_PAYLOAD)],
+ )
+ manager = FakeResumeManager()
+
+ batches = list(
+ iter_realtime_database(
+ session.as_session(),
+ token_provider(session),
+ credentials(realtime_database_url="https://demo-default-rtdb.firebaseio.com"),
+ "rooms",
+ manager,
+ logger,
+ )
+ )
+
+ keys = [row[REALTIME_DATABASE_KEY_COLUMN] for batch in batches for row in batch]
+ assert keys[-1] == "k9999"
+ assert keys.count(last_key) == 1
+ assert session.requests[0][2]["params"]["orderBy"] == '"$key"'
+ assert session.requests[1][2]["params"]["startAt"] == json.dumps(last_key)
+ assert [state.cursor for state in manager.saved] == [last_key]
+
+ def test_scalar_node_yields_a_single_row(self, logger: FilteringBoundLogger) -> None:
+ session = FakeSession(
+ request_responses=[FakeResponse(payload="online")], post_responses=[FakeResponse(payload=TOKEN_PAYLOAD)]
+ )
+
+ batches = list(
+ iter_realtime_database(
+ session.as_session(),
+ token_provider(session),
+ credentials(realtime_database_url="https://demo-default-rtdb.firebaseio.com"),
+ "status/global",
+ FakeResumeManager(),
+ logger,
+ )
+ )
+
+ assert batches == [
+ [
+ {
+ REALTIME_DATABASE_VALUE_COLUMN: "online",
+ REALTIME_DATABASE_KEY_COLUMN: "global",
+ REALTIME_DATABASE_PATH_COLUMN: "status/global",
+ }
+ ]
+ ]
+
+ def test_array_node_uses_the_index_as_the_key(self, logger: FilteringBoundLogger) -> None:
+ session = FakeSession(
+ request_responses=[FakeResponse(payload=[{"n": 0}, None, {"n": 2}])],
+ post_responses=[FakeResponse(payload=TOKEN_PAYLOAD)],
+ )
+
+ batches = list(
+ iter_realtime_database(
+ session.as_session(),
+ token_provider(session),
+ credentials(realtime_database_url="https://demo-default-rtdb.firebaseio.com"),
+ "rooms",
+ FakeResumeManager(),
+ logger,
+ )
+ )
+
+ assert [row[REALTIME_DATABASE_KEY_COLUMN] for row in batches[0]] == ["0", "2"]
+
+ def test_missing_url_is_a_config_error(self, logger: FilteringBoundLogger) -> None:
+ session = FakeSession(post_responses=[FakeResponse(payload=TOKEN_PAYLOAD)])
+
+ with pytest.raises(FirebaseConfigError, match="Realtime Database URL"):
+ list(
+ iter_realtime_database(
+ session.as_session(), token_provider(session), credentials(), "rooms", FakeResumeManager(), logger
+ )
+ )
+
+
+class TestTableDiscovery:
+ def test_lists_auth_firestore_and_configured_paths(self) -> None:
+ session = FakeSession(
+ request_responses=[FakeResponse(payload={"collectionIds": ["rooms", "users"]})],
+ post_responses=[FakeResponse(payload=TOKEN_PAYLOAD)],
+ )
+
+ with mock.patch(_SESSION_FACTORY, return_value=session.as_session()):
+ tables = get_tables(
+ credentials(
+ realtime_database_url="https://demo-default-rtdb.firebaseio.com",
+ realtime_database_paths=("rooms", "messages/lobby"),
+ )
+ )
+
+ assert tables == [
+ AUTH_USERS_TABLE,
+ "firestore_rooms",
+ "firestore_users",
+ "realtime_database_rooms",
+ "realtime_database_messages_lobby",
+ ]
+
+ @pytest.mark.parametrize("status", [403, 404])
+ def test_unreachable_firestore_does_not_hide_the_other_tables(self, status: int) -> None:
+ session = FakeSession(
+ request_responses=[FakeResponse(status_code=status, payload={"error": {"status": "PERMISSION_DENIED"}})],
+ post_responses=[FakeResponse(payload=TOKEN_PAYLOAD)],
+ )
+
+ with mock.patch(_SESSION_FACTORY, return_value=session.as_session()):
+ assert get_tables(credentials()) == [AUTH_USERS_TABLE]
+
+ def test_other_firestore_errors_propagate(self) -> None:
+ session = FakeSession(
+ request_responses=[FakeResponse(status_code=500, payload={"error": {"status": "INTERNAL"}})],
+ post_responses=[FakeResponse(payload=TOKEN_PAYLOAD)],
+ )
+
+ with mock.patch(_SESSION_FACTORY, return_value=session.as_session()):
+ with pytest.raises(requests.HTTPError):
+ get_tables(credentials())
+
+
+class TestSampleCapture:
+ def test_auth_user_responses_never_reach_sample_capture(self, logger: FilteringBoundLogger) -> None:
+ session = FakeSession(
+ request_responses=[FakeResponse(payload={"users": [{"localId": "u1", "passwordHash": "hash"}]})],
+ post_responses=[FakeResponse(payload=TOKEN_PAYLOAD)],
+ )
+
+ with mock.patch(_SESSION_FACTORY, return_value=session.as_session()) as factory:
+ batches = list(get_rows(credentials(), AUTH_USERS_TABLE, FakeResumeManager(), logger))
+
+ # The raw response carries password material that row-level redaction only removes
+ # afterwards, so no session used for this table may capture a sample.
+ assert [call.kwargs["capture"] for call in factory.call_args_list] == [False, False]
+ assert "passwordHash" not in batches[0][0]
+
+ def test_firestore_responses_are_still_captured(self, logger: FilteringBoundLogger) -> None:
+ session = FakeSession(
+ request_responses=[FakeResponse(payload={"documents": [firestore_document("a")]})],
+ post_responses=[FakeResponse(payload=TOKEN_PAYLOAD)],
+ )
+
+ with mock.patch(_SESSION_FACTORY, return_value=session.as_session()) as factory:
+ list(get_rows(credentials(), "firestore_rooms", FakeResumeManager(), logger))
+
+ assert factory.call_args_list[-1].kwargs["capture"] is True
+
+
+class TestResponseSizeCaps:
+ """Bodies are read under a byte cap so one page can't spike a shared worker's memory.
+
+ The real caps are patched down to a few kilobytes throughout: the behaviour under test is
+ "stop reading at N bytes", and allocating 64 MiB per test to demonstrate it would be waste.
+ """
+
+ def test_pages_are_requested_as_streams_rather_than_buffered(self, logger: FilteringBoundLogger) -> None:
+ session = FakeSession(
+ request_responses=[FakeResponse(payload={"documents": [firestore_document("a")]})],
+ post_responses=[FakeResponse(payload=TOKEN_PAYLOAD)],
+ )
+
+ with mock.patch(_SESSION_FACTORY, return_value=session.as_session()):
+ list(get_rows(credentials(), "firestore_rooms", FakeResumeManager(), logger))
+
+ # Without stream=True, requests materialises the whole body before we get a chance to cap it.
+ assert session.posts[0][1]["stream"] is True
+ assert all(kwargs["stream"] is True for _, _, kwargs in session.requests)
+
+ def test_an_oversized_page_is_rejected_instead_of_buffered(self, logger: FilteringBoundLogger) -> None:
+ oversized = FakeResponse(body=b"x" * (_PAGE_CAP + 1))
+ session = FakeSession(
+ request_responses=[oversized],
+ post_responses=[FakeResponse(payload=TOKEN_PAYLOAD)],
+ )
+
+ with mock.patch(_SESSION_FACTORY, return_value=session.as_session()):
+ with mock.patch(f"{_FIREBASE_MODULE}.MAX_RESPONSE_BYTES", _PAGE_CAP):
+ with pytest.raises(FirebaseResponseTooLargeError, match=RESPONSE_TOO_LARGE_ERROR):
+ list(get_rows(credentials(), "firestore_rooms", FakeResumeManager(), logger))
+
+ # Never more than one byte past the cap, and the connection is released either way.
+ assert oversized.raw.bytes_read == _PAGE_CAP + 1
+ assert oversized.closed is True
+
+ def test_a_page_that_exactly_fills_the_cap_is_still_accepted(self, logger: FilteringBoundLogger) -> None:
+ # Whitespace is JSON-insignificant, so padding to the cap keeps the page parseable.
+ page = json.dumps({"documents": [firestore_document("a")]}).encode()
+ session = FakeSession(
+ request_responses=[FakeResponse(body=page + b" " * (_PAGE_CAP - len(page)))],
+ post_responses=[FakeResponse(payload=TOKEN_PAYLOAD)],
+ )
+
+ with mock.patch(_SESSION_FACTORY, return_value=session.as_session()):
+ with mock.patch(f"{_FIREBASE_MODULE}.MAX_RESPONSE_BYTES", _PAGE_CAP):
+ batches = list(get_rows(credentials(), "firestore_rooms", FakeResumeManager(), logger))
+
+ assert [row[FIRESTORE_ID_COLUMN] for row in batches[0]] == ["a"]
+
+ def test_an_oversized_token_body_is_rejected(self) -> None:
+ session = FakeSession(post_responses=[FakeResponse(body=b"x" * (_PAGE_CAP + 1))])
+
+ with mock.patch(f"{_FIREBASE_MODULE}.MAX_TOKEN_RESPONSE_BYTES", _PAGE_CAP):
+ with pytest.raises(FirebaseResponseTooLargeError, match=RESPONSE_TOO_LARGE_ERROR):
+ mint_access_token(session.as_session(), credentials())
+
+ def test_a_token_body_that_is_not_json_is_reported_as_an_auth_error(self) -> None:
+ session = FakeSession(post_responses=[FakeResponse(body=b"<html>maintenance window</html>")])
+
+ with pytest.raises(FirebaseAuthError, match="could not be read as JSON"):
+ mint_access_token(session.as_session(), credentials())
+
+ @pytest.mark.parametrize("body", [b"[]", b'"tok-1"', b"null"], ids=["array", "string", "null"])
+ def test_a_token_body_that_is_json_but_not_an_object_has_no_token(self, body: bytes) -> None:
+ # `json.loads` is happy with any JSON value, so the object check is what stops a bare
+ # array or string from reaching `.get("access_token")` and raising AttributeError.
+ session = FakeSession(post_responses=[FakeResponse(body=body)])
+
+ with pytest.raises(FirebaseAuthError, match="did not contain an access token"):
+ mint_access_token(session.as_session(), credentials())
+
+ def test_an_empty_body_is_treated_as_no_payload(self, logger: FilteringBoundLogger) -> None:
+ # A 200 with no body at all is not JSON; it means the node holds nothing.
+ session = FakeSession(
+ request_responses=[FakeResponse(body=b"")],
+ post_responses=[FakeResponse(payload=TOKEN_PAYLOAD)],
+ )
+ configured = credentials(
+ realtime_database_url="https://demo-default-rtdb.firebaseio.com",
+ realtime_database_paths=("rooms",),
+ )
+
+ with mock.patch(_SESSION_FACTORY, return_value=session.as_session()):
+ assert list(get_rows(configured, "realtime_database_rooms", FakeResumeManager(), logger)) == []
+
+ def test_a_huge_error_body_is_truncated_not_masking_the_status(self, logger: FilteringBoundLogger) -> None:
+ # A 403 has to stay a 403 — it maps to an actionable "grant the service account a role"
+ # message. Complaining about the body's size instead would bury that.
+ failure = FakeResponse(status_code=403, body=b"x" * (_PAGE_CAP + 1))
+ session = FakeSession(
+ request_responses=[failure],
+ post_responses=[FakeResponse(payload=TOKEN_PAYLOAD)],
+ )
+
+ with mock.patch(_SESSION_FACTORY, return_value=session.as_session()):
+ with mock.patch(f"{_FIREBASE_MODULE}.MAX_ERROR_BODY_BYTES", _ERROR_CAP):
+ with pytest.raises(requests.HTTPError, match="403"):
+ list(get_rows(credentials(), "firestore_rooms", FakeResumeManager(), logger))
+
+ assert failure.raw.bytes_read == _ERROR_CAP
+ assert failure.closed is True
+
+ def test_a_huge_token_error_body_is_truncated_rather_than_masking_the_status(self) -> None:
+ failure = FakeResponse(status_code=400, body=b"x" * (_PAGE_CAP + 1))
+ session = FakeSession(post_responses=[failure])
+
+ with mock.patch(f"{_FIREBASE_MODULE}.MAX_ERROR_BODY_BYTES", _ERROR_CAP):
+ with pytest.raises(FirebaseAuthError, match="status=400"):
+ mint_access_token(session.as_session(), credentials())
+
+ assert failure.raw.bytes_read == _ERROR_CAP
+
+ def test_the_body_of_a_retried_401_is_never_read(self, logger: FilteringBoundLogger) -> None:
+ unauthorized = FakeResponse(status_code=401, payload={"error": {"status": "UNAUTHENTICATED"}})
+ session = FakeSession(
+ request_responses=[unauthorized, FakeResponse(payload={"documents": [firestore_document("a")]})],
+ post_responses=[
+ FakeResponse(payload=TOKEN_PAYLOAD),
+ FakeResponse(payload={**TOKEN_PAYLOAD, "access_token": "tok-2"}),
+ ],
+ )
+
+ with mock.patch(_SESSION_FACTORY, return_value=session.as_session()):
+ batches = list(get_rows(credentials(), "firestore_rooms", FakeResumeManager(), logger))
+
+ # The discarded 401 is closed without its body being pulled at all.
+ assert unauthorized.raw.bytes_read == 0
+ assert unauthorized.closed is True
+ assert [row[FIRESTORE_ID_COLUMN] for row in batches[0]] == ["a"]
+
+
+class TestSourceResponseShape:
+ @pytest.mark.parametrize(
+ "table_name,primary_keys,partitioned",
+ [
+ (AUTH_USERS_TABLE, ["localId"], False),
+ ("firestore_rooms", [FIRESTORE_ID_COLUMN], True),
+ ("realtime_database_rooms", [REALTIME_DATABASE_KEY_COLUMN], False),
+ ],
+ )
+ def test_primary_keys_and_partitioning_match_the_table_kind(
+ self, table_name: str, primary_keys: list[str], partitioned: bool, logger: FilteringBoundLogger
+ ) -> None:
+ response = firebase_source(credentials(), table_name, FakeResumeManager(), logger)
+
+ assert response.name == table_name
+ assert response.primary_keys == primary_keys
+ assert (response.partition_mode == "datetime") is partitioned
+ assert (response.partition_keys == [FIRESTORE_CREATE_TIME_COLUMN]) is partitioned
+
+ def test_realtime_database_table_is_dispatched_by_its_configured_path(self, logger: FilteringBoundLogger) -> None:
+ session = FakeSession(
+ request_responses=[FakeResponse(payload={"k1": {"n": 1}})],
+ post_responses=[FakeResponse(payload=TOKEN_PAYLOAD)],
+ )
+ configured = credentials(
+ realtime_database_url="https://demo-default-rtdb.firebaseio.com",
+ realtime_database_paths=("rooms",),
+ )
+
+ with mock.patch(_SESSION_FACTORY, return_value=session.as_session()):
+ batches = list(get_rows(configured, "realtime_database_rooms", FakeResumeManager(), logger))
+
+ assert [row[REALTIME_DATABASE_KEY_COLUMN] for row in batches[0]] == ["k1"]
+
+ def test_unknown_table_is_rejected(self, logger: FilteringBoundLogger) -> None:
+ with mock.patch(_SESSION_FACTORY, return_value=FakeSession().as_session()):
+ with pytest.raises(FirebaseConfigError, match="not configured"):
+ list(get_rows(credentials(), "made_up_table", FakeResumeManager(), logger))
+
+
+class TestCredentialValidation:
+ def test_valid_key_mints_a_token(self) -> None:
+ session = FakeSession(post_responses=[FakeResponse(payload=TOKEN_PAYLOAD)])
+
+ with mock.patch(_SESSION_FACTORY, return_value=session.as_session()):
+ assert validate_credentials(credentials()) == (True, None)
+
+ def test_rejected_key_reports_googles_reason(self) -> None:
+ session = FakeSession(post_responses=[FakeResponse(status_code=400, payload={"error": "invalid_grant"})])
+
+ with mock.patch(_SESSION_FACTORY, return_value=session.as_session()):
+ valid, message = validate_credentials(credentials())
+
+ assert valid is False
+ assert message is not None and "invalid_grant" in message
+
+ def test_unreachable_google_is_not_reported_as_a_bad_key(self) -> None:
+ session = mock.MagicMock()
+ session.post.side_effect = requests.ConnectionError("boom")
+
+ with mock.patch(_SESSION_FACTORY, return_value=session):
+ valid, message = validate_credentials(credentials())
+
+ assert valid is False
+ assert message == "Could not reach Google with the provided Firebase service account key."
+
+ @pytest.mark.parametrize(
+ "overrides,message",
+ [
+ (
+ {"realtime_database_url": "https://attacker.example.com", "realtime_database_paths": ("rooms",)},
+ "firebaseio.com",
+ ),
+ (
+ {"realtime_database_url": "https://demo-default-rtdb.firebaseio.com"},
+ "at least one Realtime Database path",
+ ),
+ ],
+ )
+ def test_realtime_database_settings_are_checked_before_any_request(
+ self, overrides: dict[str, Any], message: str
+ ) -> None:
+ valid, reason = validate_credentials(credentials(**overrides))
+
+ assert valid is False
+ assert reason is not None and message in reason
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/firebase/tests/test_firebase_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/firebase/tests/test_firebase_source.py
new file mode 100644
index 000000000000..27d71cb6b1cc
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/firebase/tests/test_firebase_source.py
@@ -0,0 +1,158 @@
+from typing import Any
+
+import pytest
+from unittest import mock
+
+import structlog
+
+from posthog.schema import ReleaseStatus, SourceFieldFileUploadConfig, SourceFieldInputConfig
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs
+from products.warehouse_sources.backend.temporal.data_imports.sources.firebase.firebase import FirebaseResumeConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.firebase.settings import AUTH_USERS_TABLE
+from products.warehouse_sources.backend.temporal.data_imports.sources.firebase.source import FirebaseSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.firebase import (
+ FirebaseKeyFileConfig,
+ FirebaseSourceConfig,
+)
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+_GET_TABLES = "products.warehouse_sources.backend.temporal.data_imports.sources.firebase.source.get_tables"
+_VALIDATE = (
+ "products.warehouse_sources.backend.temporal.data_imports.sources.firebase.source.validate_firebase_credentials"
+)
+
+
+def firebase_config(**overrides: Any) -> FirebaseSourceConfig:
+ return FirebaseSourceConfig(
+ key_file=FirebaseKeyFileConfig(
+ project_id=overrides.pop("project_id", "demo-project"),
+ private_key="-----BEGIN PRIVATE KEY-----",
+ private_key_id="key-id",
+ client_email="[email protected]",
+ token_uri="https://oauth2.googleapis.com/token",
+ ),
+ database_id=overrides.pop("database_id", None),
+ realtime_database_url=overrides.pop("realtime_database_url", None),
+ realtime_database_paths=overrides.pop("realtime_database_paths", None),
+ )
+
+
+def source_inputs(schema_name: str, **overrides: Any) -> SourceInputs:
+ defaults: dict[str, Any] = {
+ "schema_name": schema_name,
+ "schema_id": "schema-id",
+ "source_id": "source-id",
+ "team_id": 1,
+ "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-id",
+ "logger": structlog.get_logger("firebase-test"),
+ "reset_pipeline": False,
+ }
+ defaults.update(overrides)
+ return SourceInputs(**defaults)
+
+
+class TestFirebaseSource:
+ def setup_method(self) -> None:
+ self.source = FirebaseSource()
+
+ def test_source_type(self) -> None:
+ assert self.source.source_type == ExternalDataSourceType.FIREBASE
+
+ def test_source_is_released_in_alpha(self) -> None:
+ config = self.source.get_source_config
+
+ assert config.unreleasedSource is None
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+
+ def test_form_takes_a_service_account_key_and_optional_realtime_database_settings(self) -> None:
+ fields = {field.name: field for field in self.source.get_source_config.fields}
+
+ assert isinstance(fields["key_file"], SourceFieldFileUploadConfig)
+ assert fields["key_file"].required is True
+ for name in ("database_id", "realtime_database_url", "realtime_database_paths"):
+ field = fields[name]
+ assert isinstance(field, SourceFieldInputConfig)
+ assert field.required is False
+
+ def test_connection_target_fields_require_credential_re_entry_when_changed(self) -> None:
+ # The Realtime Database host, the Firestore database selector and the Realtime Database
+ # path allow-list all decide what the preserved service account key reads, so editing any
+ # of them has to force key file re-entry.
+ assert self.source.connection_host_fields == [
+ "database_id",
+ "realtime_database_url",
+ "realtime_database_paths",
+ ]
+
+ def test_auth_users_columns_are_documented(self) -> None:
+ descriptions = self.source.get_canonical_descriptions()
+
+ assert "localId" in descriptions[AUTH_USERS_TABLE]["columns"]
+
+ def test_get_schemas_lists_discovered_tables_as_full_refresh(self) -> None:
+ with mock.patch(_GET_TABLES, return_value=[AUTH_USERS_TABLE, "firestore_rooms"]):
+ schemas = self.source.get_schemas(firebase_config(), team_id=1)
+
+ assert [schema.name for schema in schemas] == [AUTH_USERS_TABLE, "firestore_rooms"]
+ assert all(not schema.supports_incremental and not schema.supports_append for schema in schemas)
+
+ def test_get_schemas_honors_the_name_filter(self) -> None:
+ with mock.patch(_GET_TABLES, return_value=[AUTH_USERS_TABLE, "firestore_rooms"]):
+ schemas = self.source.get_schemas(firebase_config(), team_id=1, names=["firestore_rooms"])
+
+ assert [schema.name for schema in schemas] == ["firestore_rooms"]
+
+ @pytest.mark.parametrize(
+ "database_id,expected",
+ [(None, "(default)"), ("", "(default)"), (" ", "(default)"), ("analytics", "analytics")],
+ )
+ def test_blank_database_id_falls_back_to_the_default_database(self, database_id: Any, expected: str) -> None:
+ with mock.patch(_VALIDATE, return_value=(True, None)) as validate:
+ self.source.validate_credentials(firebase_config(database_id=database_id), team_id=1)
+
+ assert validate.call_args.args[0].database_id == expected
+
+ @pytest.mark.parametrize(
+ "raw,expected",
+ [
+ (None, ()),
+ ("", ()),
+ ("rooms", ("rooms",)),
+ (" rooms , /messages/lobby/ ,, rooms ", ("rooms", "messages/lobby")),
+ ],
+ )
+ def test_realtime_database_paths_are_split_and_deduplicated(self, raw: Any, expected: tuple[str, ...]) -> None:
+ with mock.patch(_VALIDATE, return_value=(True, None)) as validate:
+ self.source.validate_credentials(firebase_config(realtime_database_paths=raw), team_id=1)
+
+ assert validate.call_args.args[0].realtime_database_paths == expected
+
+ def test_validate_credentials_passes_through_the_transport_result(self) -> None:
+ with mock.patch(_VALIDATE, return_value=(False, "nope")):
+ assert self.source.validate_credentials(firebase_config(), team_id=1) == (False, "nope")
+
+ def test_resume_manager_is_bound_to_the_firebase_cursor(self) -> None:
+ manager = self.source.get_resumable_source_manager(source_inputs(AUTH_USERS_TABLE))
+
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is FirebaseResumeConfig
+
+ def test_source_for_pipeline_syncs_the_requested_table(self) -> None:
+ manager = self.source.get_resumable_source_manager(source_inputs("firestore_rooms"))
+
+ response = self.source.source_for_pipeline(firebase_config(), manager, source_inputs("firestore_rooms"))
+
+ assert response.name == "firestore_rooms"
+
+ def test_permanent_auth_failures_are_not_retried(self) -> None:
+ errors = self.source.get_non_retryable_errors()
+
+ assert "error=invalid_grant" in errors
+ assert "403 Client Error: Forbidden" in errors
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/firebase.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/firebase.py
index c35d7ca458af..22f5da38061d 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/firebase.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/firebase.py
@@ -4,6 +4,18 @@
from products.warehouse_sources.backend.temporal.data_imports.sources.common import config
+class FirebaseKeyFileConfig(config.Config):
+ project_id: str
+ private_key: str
+ private_key_id: str
+ client_email: str
+ token_uri: str
+
+
@config.config
class FirebaseSourceConfig(config.Config):
- pass
+ key_file: FirebaseKeyFileConfig
+ database_id: str | None = None
+ realtime_database_url: str | None = None
+ realtime_database_paths: str | None = None