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 1 missing table to the Firebase source (#118136)

Tom Owers12ddf11bfe33
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
index 01d072d1be8d..e347ed976e4e 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
@@ -4643,7 +4643,7 @@ Today (4): `auth_users`, `firestore_<collection_id>`, `firestore_collection_grou
Diffed against: <https://identitytoolkit.googleapis.com/$discovery/rest?version=v1>
-- [ ] `Tenant accounts (GET /v1/projects/{targetProjectId}/tenants/{tenantId}/accounts:batchGet)` — include tenant users in signup and account activity analysis for projects that use Identity Platform tenants (high)
+- [x] `Tenant accounts (GET /v1/projects/{targetProjectId}/tenants/{tenantId}/accounts:batchGet)` — include tenant users in signup and account activity analysis for projects that use Identity Platform tenants (high)
Note: Google discovery documents supplied Auth and Firestore operations, including the separate tenant account collection. Placeholders represent discovered collections and configured database paths; auth_users is fixed. Tenant accounts require Identity Toolkit v2 tenant discovery; current Auth reads use only the project route. Credentials, indexes, backups, and authentication settings are excluded; sampled subcollection discovery can also miss collections.
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
index 257cae9d9cd6..2121e2e773f6 100644
--- 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
@@ -1,7 +1,33 @@
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
+from products.warehouse_sources.backend.temporal.data_imports.sources.firebase.settings import (
+ AUTH_TENANT_USERS_TABLE,
+ AUTH_USERS_TABLE,
+)
+
+_AUTH_USER_COLUMNS: dict[str, str] = {
+ "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.",
+}
# 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.
@@ -9,27 +35,15 @@ 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": _AUTH_USER_COLUMNS,
+ },
+ AUTH_TENANT_USERS_TABLE: {
+ "description": "One row per account in each Identity Platform tenant of the project. Password hashes and salts are never synced.",
+ "docs_url": "https://cloud.google.com/identity-platform/docs/reference/rest/v1/projects.tenants.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.",
+ **_AUTH_USER_COLUMNS,
+ "localId": "Unique ID of the account inside its tenant.",
+ "tenantId": "ID of the Identity Platform tenant the account belongs to.",
},
},
}
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
index 608e3b0bb168..ceedc2d31ee9 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/firebase/firebase.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/firebase/firebase.py
@@ -25,6 +25,8 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.sch
)
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_TENANT_USERS_PRIMARY_KEY,
+ AUTH_TENANT_USERS_TABLE,
AUTH_USERS_PAGE_SIZE,
AUTH_USERS_PRIMARY_KEY,
AUTH_USERS_TABLE,
@@ -46,6 +48,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.firebase.s
FIRESTORE_SUBCOLLECTION_SAMPLE_DOCUMENTS,
FIRESTORE_UPDATE_TIME_COLUMN,
GOOGLE_TOKEN_URI,
+ IDENTITY_TOOLKIT_ADMIN_API_ROOT,
IDENTITY_TOOLKIT_API_ROOT,
JWT_ASSERTION_LIFETIME_SECONDS,
JWT_GRANT_TYPE,
@@ -63,6 +66,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.firebase.s
REDACTED_AUTH_USER_FIELDS,
REQUEST_TIMEOUT_SECONDS,
RESPONSE_TOO_LARGE_ERROR,
+ TENANTS_PAGE_SIZE,
TOKEN_EXPIRY_SKEW_SECONDS,
firestore_collection_group_table_name,
firestore_table_name,
@@ -97,6 +101,9 @@ class FirebaseResumeConfig:
# single opaque token and leaves this unset, which is also what a cursor saved before this field
# existed decodes to.
incremental_value: Optional[str] = None
+ # A tenant users read pages one tenant at a time. This holds the tenant to continue in, and
+ # `cursor` holds that tenant's page token, or "" to start at its first page.
+ tenant_id: Optional[str] = None
@frozen
@@ -803,6 +810,108 @@ def iter_auth_users(
resumable_source_manager.clear_state()
+def _tenant_id(tenant: Any) -> Optional[str]:
+ # A tenant's `name` is its resource path, `projects/{project}/tenants/{tenant_id}`.
+ name = tenant.get("name") if isinstance(tenant, dict) else None
+ if not isinstance(name, str) or "/tenants/" not in name:
+ return None
+ return name.rsplit("/", 1)[-1] or None
+
+
+def _list_tenants_page(
+ session: requests.Session,
+ tokens: AccessTokenProvider,
+ credentials: FirebaseCredentials,
+ page_size: int,
+ page_token: Optional[str],
+) -> tuple[list[str], Optional[str]]:
+ url = f"{IDENTITY_TOOLKIT_ADMIN_API_ROOT}/projects/{credentials.project_id}/tenants"
+ params: dict[str, Any] = {"pageSize": page_size}
+ if page_token:
+ params["pageToken"] = page_token
+ payload = _request(session, tokens, "GET", url, params=params) or {}
+ tenant_ids = [tenant_id for tenant in payload.get("tenants") or [] if (tenant_id := _tenant_id(tenant))]
+ return tenant_ids, payload.get("nextPageToken") or None
+
+
+def list_tenant_ids(
+ session: requests.Session, tokens: AccessTokenProvider, credentials: FirebaseCredentials
+) -> list[str]:
+ tenant_ids: set[str] = set()
+ page_token: Optional[str] = None
+ for _ in range(MAX_PAGES):
+ page, page_token = _list_tenants_page(session, tokens, credentials, TENANTS_PAGE_SIZE, page_token)
+ tenant_ids.update(page)
+ if not page_token or not page:
+ break
+ # Sorted so that a resumed read knows which tenants it already finished.
+ return sorted(tenant_ids)
+
+
+def has_tenants(session: requests.Session, tokens: AccessTokenProvider, credentials: FirebaseCredentials) -> bool:
+ tenant_ids, _ = _list_tenants_page(session, tokens, credentials, 1, None)
+ return bool(tenant_ids)
+
+
+def _resume_tenant_cursor(
+ resumable_source_manager: ResumableSourceManager[FirebaseResumeConfig],
+ logger: FilteringBoundLogger,
+) -> Optional[FirebaseResumeConfig]:
+ if not resumable_source_manager.can_resume():
+ return None
+ resume = resumable_source_manager.load_state()
+ if resume is None or resume.tenant_id is None:
+ return None
+ logger.debug(f"Resuming Firebase Auth tenant users from tenant={resume.tenant_id} cursor={resume.cursor}")
+ return resume
+
+
+def iter_tenant_auth_users(
+ session: requests.Session,
+ tokens: AccessTokenProvider,
+ credentials: FirebaseCredentials,
+ resumable_source_manager: ResumableSourceManager[FirebaseResumeConfig],
+ logger: FilteringBoundLogger,
+) -> Iterator[list[dict[str, Any]]]:
+ resume = _resume_tenant_cursor(resumable_source_manager, logger)
+ tenant_ids = list_tenant_ids(session, tokens, credentials)
+ if resume is not None:
+ # A tenant deleted since the checkpoint is gone from the list, so compare rather than look it up.
+ tenant_ids = [tenant_id for tenant_id in tenant_ids if tenant_id >= str(resume.tenant_id)]
+
+ for index, tenant_id in enumerate(tenant_ids):
+ url = (
+ f"{IDENTITY_TOOLKIT_API_ROOT}/projects/{credentials.project_id}"
+ f"/tenants/{quote(tenant_id, safe='')}/accounts:batchGet"
+ )
+ page_token = resume.cursor if resume is not None and resume.tenant_id == tenant_id else None
+
+ 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)]
+ page_token = payload.get("nextPageToken")
+ has_next_page = bool(page_token and users)
+ if has_next_page:
+ resumable_source_manager.save_state(FirebaseResumeConfig(cursor=str(page_token), tenant_id=tenant_id))
+ elif index + 1 < len(tenant_ids):
+ resumable_source_manager.save_state(FirebaseResumeConfig(cursor="", tenant_id=tenant_ids[index + 1]))
+
+ if users:
+ yield [{**flatten_auth_user(user), "tenantId": tenant_id} for user in users]
+ else:
+ # A tenant with no users yields nothing, so many of them in a row would hide a shutdown.
+ resumable_source_manager.safe_point()
+
+ if not has_next_page:
+ break
+
+ resumable_source_manager.clear_state()
+
+
def iter_realtime_database(
session: requests.Session,
tokens: AccessTokenProvider,
@@ -907,6 +1016,12 @@ def get_rows(
yield from iter_auth_users(auth_session, tokens, credentials, resumable_source_manager, logger)
return
+ if table_name == AUTH_TENANT_USERS_TABLE:
+ # Same password material as above, and a tenant listing also carries the tenant's hash signer key.
+ auth_session = _api_session(credentials, capture=False)
+ yield from iter_tenant_auth_users(auth_session, tokens, credentials, resumable_source_manager, logger)
+ return
+
api_session = _api_session(credentials)
# Incremental sync isn't supported for a collection group yet, so it always reads in full —
@@ -1121,7 +1236,7 @@ def _dedupe_by_storage_name(table_names: list[str]) -> list[str]:
def get_tables(credentials: FirebaseCredentials, force_refresh: bool = False) -> list[str]:
- """List every table this source can sync: Auth users, Firestore collections, configured paths."""
+ """List every table this source can sync: Auth users, tenant users, Firestore collections, configured paths."""
firestore_tables: list[str] = []
tokens = AccessTokenProvider(_auth_session(credentials), credentials)
@@ -1144,8 +1259,23 @@ def get_tables(credentials: FirebaseCredentials, force_refresh: bool = False) ->
raise
LOGGER.warning(f"Skipping Firestore collections for Firebase project {credentials.project_id}: {status}")
+ # Most projects never use Identity Platform tenants, so the table is listed only when one exists.
+ auth_tables = [AUTH_USERS_TABLE]
+ try:
+ if has_tenants(_api_session(credentials, capture=False), tokens, credentials):
+ auth_tables.append(AUTH_TENANT_USERS_TABLE)
+ except requests.HTTPError as e:
+ # A project without Identity Platform, or a service account that can't list tenants, gets
+ # one of these statuses. Neither should hide the tables the source can still read. Anything
+ # else (429, 5xx) is transient and must propagate, or the schema sync would treat the table
+ # as removed and disable an enabled sync.
+ status = e.response.status_code if e.response is not None else None
+ if status not in (400, 403, 404):
+ raise
+ LOGGER.warning(f"Skipping Firebase Auth tenants for Firebase project {credentials.project_id}: {status}")
+
rtdb_tables = [realtime_database_table_name(path) for path in credentials.realtime_database_paths]
- return _dedupe_by_storage_name([AUTH_USERS_TABLE, *firestore_tables, *rtdb_tables])
+ return _dedupe_by_storage_name([*auth_tables, *firestore_tables, *rtdb_tables])
def validate_credentials(credentials: FirebaseCredentials) -> tuple[bool, Optional[str]]:
@@ -1229,6 +1359,8 @@ def firebase_source(
if table_name == AUTH_USERS_TABLE:
primary_keys = AUTH_USERS_PRIMARY_KEY
+ elif table_name == AUTH_TENANT_USERS_TABLE:
+ primary_keys = AUTH_TENANT_USERS_PRIMARY_KEY
elif collection_group_id is not None:
# A collection group can hold documents with the same id under different parents, so the
# full document path is the only unique key.
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
index 82921b821994..5feb18b3c974 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/firebase/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/firebase/settings.py
@@ -9,6 +9,9 @@ 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}"
+# Identity Platform lists tenants only on its `v2` admin surface. The users in each tenant are still
+# read on `v1`, the same as the project's own users.
+IDENTITY_TOOLKIT_ADMIN_API_ROOT: Final[str] = "https://identitytoolkit.googleapis.com/v2"
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
@@ -24,6 +27,7 @@ OAUTH_SCOPES: Final[str] = (
DEFAULT_DATABASE_ID: Final[str] = "(default)"
AUTH_USERS_TABLE: Final[str] = "auth_users"
+AUTH_TENANT_USERS_TABLE: Final[str] = "auth_tenant_users"
FIRESTORE_TABLE_PREFIX: Final[str] = "firestore_"
# A subcollection reads as a collection group (every collection with the id, under any parent). The
# `/` in the prefix states that scope and cannot appear in a Firestore collection id, so no root
@@ -36,6 +40,7 @@ REALTIME_DATABASE_TABLE_PREFIX: Final[str] = "realtime_database_"
FIRESTORE_PAGE_SIZE: Final[int] = 300
FIRESTORE_COLLECTION_IDS_PAGE_SIZE: Final[int] = 300
AUTH_USERS_PAGE_SIZE: Final[int] = 1000
+TENANTS_PAGE_SIZE: Final[int] = 1000
REALTIME_DATABASE_PAGE_SIZE: Final[int] = 500
# Firestore has no API to list a collection's subcollections, only a single document's. So table
@@ -102,6 +107,8 @@ REALTIME_DATABASE_PATH_COLUMN: Final[str] = "_realtime_database_path"
REALTIME_DATABASE_VALUE_COLUMN: Final[str] = "value"
AUTH_USERS_PRIMARY_KEY: Final[list[str]] = ["localId"]
+# A user id is unique only inside its tenant.
+AUTH_TENANT_USERS_PRIMARY_KEY: Final[list[str]] = ["tenantId", "localId"]
# Firestore stores no schema, so the cursor fields a collection can offer are read off a sample of
# real documents. Ten is enough to reject a field that only some documents carry, while keeping
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
index 6f2fc1ee75b1..62f089c64746 100644
--- 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
@@ -33,6 +33,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.firebase.f
iter_firestore_documents,
iter_firestore_documents_incremental,
iter_realtime_database,
+ iter_tenant_auth_users,
list_collection_ids,
mint_access_token,
resolve_incremental_cursor,
@@ -41,6 +42,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.firebase.f
validate_realtime_database_url,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.firebase.settings import (
+ AUTH_TENANT_USERS_TABLE,
AUTH_USERS_TABLE,
FIRESTORE_CREATE_TIME_COLUMN,
FIRESTORE_ID_COLUMN,
@@ -674,6 +676,118 @@ class TestAuthUsersPagination:
assert session.requests[0][1].endswith("/projects/demo-project/accounts:batchGet")
+def tenant(tenant_id: str) -> dict[str, Any]:
+ return {"name": f"projects/demo-project/tenants/{tenant_id}", "displayName": tenant_id}
+
+
+TENANTS_URL = "https://identitytoolkit.googleapis.com/v2/projects/demo-project/tenants"
+
+
+def tenant_accounts_url(tenant_id: str) -> str:
+ return f"https://identitytoolkit.googleapis.com/v1/projects/demo-project/tenants/{tenant_id}/accounts:batchGet"
+
+
+class TestTenantAuthUsers:
+ def test_walks_every_tenant_in_order_and_stages_the_next_position_before_each_yield(
+ self, logger: FilteringBoundLogger
+ ) -> None:
+ session = FakeSession(
+ request_responses=[
+ # Tenants arrive out of order across two pages.
+ FakeResponse(payload={"tenants": [tenant("tenant-c"), tenant("tenant-a")], "nextPageToken": "t2"}),
+ FakeResponse(payload={"tenants": [tenant("tenant-b"), {"displayName": "no name"}]}),
+ FakeResponse(payload={"users": [{"localId": "u1"}], "nextPageToken": "p2"}),
+ FakeResponse(payload={"users": [{"localId": "u2", "passwordHash": "hash"}]}),
+ # A tenant with no users.
+ FakeResponse(payload={}),
+ FakeResponse(payload={"users": [{"localId": "u1", "tenantId": "tenant-c"}]}),
+ ],
+ post_responses=[FakeResponse(payload=TOKEN_PAYLOAD)],
+ )
+ manager = FakeResumeManager()
+
+ staged_at_each_yield: list[list[tuple[str, Optional[str]]]] = []
+ rows: list[dict[str, Any]] = []
+ for batch in iter_tenant_auth_users(
+ session.as_session(), token_provider(session), credentials(), manager, logger
+ ):
+ staged_at_each_yield.append([(state.cursor, state.tenant_id) for state in manager.saved])
+ rows.extend(batch)
+
+ # The same `localId` in two tenants is two accounts, and each row says which tenant it is in.
+ assert [(row["tenantId"], row["localId"]) for row in rows] == [
+ ("tenant-a", "u1"),
+ ("tenant-a", "u2"),
+ ("tenant-c", "u1"),
+ ]
+ assert all("passwordHash" not in row for row in rows)
+ assert staged_at_each_yield == [
+ [("p2", "tenant-a")],
+ [("p2", "tenant-a"), ("", "tenant-b")],
+ [("p2", "tenant-a"), ("", "tenant-b"), ("", "tenant-c")],
+ ]
+ assert manager.cleared is True
+ assert [(url, kwargs["params"]) for _, url, kwargs in session.requests] == [
+ (TENANTS_URL, {"pageSize": 1000}),
+ (TENANTS_URL, {"pageSize": 1000, "pageToken": "t2"}),
+ (tenant_accounts_url("tenant-a"), {"maxResults": 1000}),
+ (tenant_accounts_url("tenant-a"), {"maxResults": 1000, "nextPageToken": "p2"}),
+ (tenant_accounts_url("tenant-b"), {"maxResults": 1000}),
+ (tenant_accounts_url("tenant-c"), {"maxResults": 1000}),
+ ]
+
+ @pytest.mark.parametrize(
+ "state,expected_requests",
+ [
+ # Mid-tenant: the earlier tenant is skipped and the saved tenant continues from its token.
+ (
+ FirebaseResumeConfig(cursor="p2", tenant_id="tenant-b"),
+ [(tenant_accounts_url("tenant-b"), {"maxResults": 1000, "nextPageToken": "p2"})],
+ ),
+ # At a tenant boundary: the saved tenant starts at its first page.
+ (
+ FirebaseResumeConfig(cursor="", tenant_id="tenant-b"),
+ [(tenant_accounts_url("tenant-b"), {"maxResults": 1000})],
+ ),
+ # The saved tenant was deleted: the read continues at the next tenant, without its token.
+ (
+ FirebaseResumeConfig(cursor="p2", tenant_id="tenant-aa"),
+ [(tenant_accounts_url("tenant-b"), {"maxResults": 1000})],
+ ),
+ # A checkpoint with no tenant did not come from this table, so the read starts over.
+ (
+ FirebaseResumeConfig(cursor="p2"),
+ [
+ (tenant_accounts_url("tenant-a"), {"maxResults": 1000}),
+ (tenant_accounts_url("tenant-b"), {"maxResults": 1000}),
+ ],
+ ),
+ ],
+ ids=["mid-tenant", "tenant-boundary", "deleted-tenant", "foreign-checkpoint"],
+ )
+ def test_resumes_from_the_saved_tenant(
+ self,
+ state: FirebaseResumeConfig,
+ expected_requests: list[tuple[str, dict[str, Any]]],
+ logger: FilteringBoundLogger,
+ ) -> None:
+ session = FakeSession(
+ request_responses=[
+ FakeResponse(payload={"tenants": [tenant("tenant-a"), tenant("tenant-b")]}),
+ *[FakeResponse(payload={"users": [{"localId": "u9"}]}) for _ in expected_requests],
+ ],
+ post_responses=[FakeResponse(payload=TOKEN_PAYLOAD)],
+ )
+
+ list(
+ iter_tenant_auth_users(
+ session.as_session(), token_provider(session), credentials(), FakeResumeManager(state), logger
+ )
+ )
+
+ assert [(url, kwargs["params"]) for _, url, kwargs in session.requests[1:]] == expected_requests
+
+
class TestRealtimeDatabase:
@pytest.mark.parametrize(
"url",
@@ -823,6 +937,7 @@ class TestTableDiscovery:
FakeResponse(payload={"collectionIds": ["messages"]}),
# One collection-group sample for the single `messages` id, then nothing deeper.
FakeResponse(payload=[]),
+ FakeResponse(payload={}),
],
post_responses=[FakeResponse(payload=TOKEN_PAYLOAD)],
)
@@ -843,6 +958,7 @@ class TestTableDiscovery:
FakeResponse(payload={"documents": [firestore_document("room1")]}),
FakeResponse(payload={"collectionIds": ["messages"]}),
FakeResponse(payload=[]),
+ FakeResponse(payload={}),
],
post_responses=[FakeResponse(payload=TOKEN_PAYLOAD)],
)
@@ -865,7 +981,8 @@ class TestTableDiscovery:
"message": "The Cloud Firestore API is not available for Firestore in Datastore Mode database.",
}
},
- )
+ ),
+ FakeResponse(payload={}),
],
post_responses=[FakeResponse(payload=TOKEN_PAYLOAD)],
)
@@ -893,41 +1010,104 @@ class TestTableDiscovery:
get_tables(credentials())
def test_discovery_is_cached_and_force_refresh_rewalks(self) -> None:
- # `rooms` has no documents to probe, so one discovery pass is two requests: the root
- # `listCollectionIds` and the sample read that finds no subcollections.
+ # `rooms` has no documents to probe, so one Firestore discovery pass is two requests: the
+ # root `listCollectionIds` and the sample read that finds no subcollections. The tenant probe
+ # after it is one request on every lookup.
session = FakeSession(
request_responses=[
FakeResponse(payload={"collectionIds": ["rooms"]}),
FakeResponse(payload={"documents": []}),
+ FakeResponse(payload={}),
+ FakeResponse(payload={}),
],
- post_responses=[FakeResponse(payload=TOKEN_PAYLOAD), FakeResponse(payload=TOKEN_PAYLOAD)],
+ post_responses=[FakeResponse(payload=TOKEN_PAYLOAD) for _ in range(3)],
)
with mock.patch(_SESSION_FACTORY, return_value=session.as_session()):
first = get_tables(credentials())
# The second lookup reuses the cached collections instead of walking the project again.
cached = get_tables(credentials())
- assert len(session.requests) == 2
+ assert len(session.requests) == 4
# A forced refresh walks again, so it needs a fresh set of discovery responses.
session.request_queue.extend(
- [FakeResponse(payload={"collectionIds": ["rooms"]}), FakeResponse(payload={"documents": []})]
+ [
+ FakeResponse(payload={"collectionIds": ["rooms"]}),
+ FakeResponse(payload={"documents": []}),
+ FakeResponse(payload={}),
+ ]
)
get_tables(credentials(), force_refresh=True)
assert first == cached == [AUTH_USERS_TABLE, "firestore_rooms"]
- assert len(session.requests) == 4
+ assert len(session.requests) == 7
+
+ @pytest.mark.parametrize(
+ "tenant_response,expected_tables",
+ [
+ (FakeResponse(payload={"tenants": [tenant("tenant-a")]}), [AUTH_USERS_TABLE, AUTH_TENANT_USERS_TABLE]),
+ (FakeResponse(payload={}), [AUTH_USERS_TABLE]),
+ # A project without Identity Platform, or a service account that can't list tenants.
+ (
+ FakeResponse(status_code=400, payload={"error": {"message": "CONFIGURATION_NOT_FOUND"}}),
+ [AUTH_USERS_TABLE],
+ ),
+ (FakeResponse(status_code=403, payload={"error": {"status": "PERMISSION_DENIED"}}), [AUTH_USERS_TABLE]),
+ (FakeResponse(status_code=404, payload={"error": {"status": "NOT_FOUND"}}), [AUTH_USERS_TABLE]),
+ ],
+ ids=["has-tenants", "no-tenants", "no-identity-platform", "forbidden", "not-found"],
+ )
+ def test_tenant_users_table_is_listed_only_when_the_project_has_a_tenant(
+ self, tenant_response: FakeResponse, expected_tables: list[str]
+ ) -> None:
+ session = FakeSession(
+ request_responses=[FakeResponse(payload={}), tenant_response],
+ post_responses=[FakeResponse(payload=TOKEN_PAYLOAD)],
+ )
+
+ with mock.patch(_SESSION_FACTORY, return_value=session.as_session()) as factory:
+ tables = get_tables(credentials())
+
+ assert tables == expected_tables
+ assert session.requests[1][1] == TENANTS_URL
+ assert session.requests[1][2]["params"] == {"pageSize": 1}
+ # A tenant listing carries each tenant's password hash signer key, so it is never captured.
+ assert factory.call_args_list[-1].kwargs["capture"] is False
+
+ @pytest.mark.parametrize("status", [429, 500, 503])
+ def test_transient_tenant_listing_errors_propagate(self, status: int) -> None:
+ # Dropping the table on a transient error would make the schema sync treat it as removed.
+ session = FakeSession(
+ request_responses=[FakeResponse(payload={}), FakeResponse(status_code=status)],
+ post_responses=[FakeResponse(payload=TOKEN_PAYLOAD)],
+ )
+
+ with mock.patch(_SESSION_FACTORY, return_value=session.as_session()):
+ with pytest.raises(requests.HTTPError, match=str(status)):
+ get_tables(credentials())
class TestSampleCapture:
- def test_auth_user_responses_never_reach_sample_capture(self, logger: FilteringBoundLogger) -> None:
+ @pytest.mark.parametrize(
+ "table_name,listing_responses",
+ [
+ (AUTH_USERS_TABLE, []),
+ (AUTH_TENANT_USERS_TABLE, [FakeResponse(payload={"tenants": [tenant("tenant-a")]})]),
+ ],
+ )
+ def test_auth_user_responses_never_reach_sample_capture(
+ self, table_name: str, listing_responses: list[FakeResponse], logger: FilteringBoundLogger
+ ) -> None:
session = FakeSession(
- request_responses=[FakeResponse(payload={"users": [{"localId": "u1", "passwordHash": "hash"}]})],
+ request_responses=[
+ *listing_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))
+ batches = list(get_rows(credentials(), table_name, 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.
@@ -1045,6 +1225,8 @@ class TestSourceResponseShape:
"table_name,primary_keys,partitioned",
[
(AUTH_USERS_TABLE, ["localId"], False),
+ # A user id is unique only inside its tenant.
+ (AUTH_TENANT_USERS_TABLE, ["tenantId", "localId"], False),
("firestore_rooms", [FIRESTORE_ID_COLUMN], True),
# A subcollection is a collection group, so its unique key is the full document path.
("firestore_collection_group/messages", [FIRESTORE_PATH_COLUMN], True),