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 Twilio source (#118441)

Tom Owers1784832b3d45
diff --git a/posthog/test/repo_invariants/dataclass_frozen_baseline.txt b/posthog/test/repo_invariants/dataclass_frozen_baseline.txt
index 7a7d9044e10f..45b28a669d9c 100644
--- a/posthog/test/repo_invariants/dataclass_frozen_baseline.txt
+++ b/posthog/test/repo_invariants/dataclass_frozen_baseline.txt
@@ -1172,7 +1172,6 @@
1 products/warehouse_sources/backend/temporal/data_imports/sources/twelve_data/twelve_data.py
1 products/warehouse_sources/backend/temporal/data_imports/sources/twelve_labs/settings.py
1 products/warehouse_sources/backend/temporal/data_imports/sources/twelve_labs/twelve_labs.py
-1 products/warehouse_sources/backend/temporal/data_imports/sources/twilio/settings.py
1 products/warehouse_sources/backend/temporal/data_imports/sources/twilio/twilio.py
1 products/warehouse_sources/backend/temporal/data_imports/sources/typeform/settings.py
1 products/warehouse_sources/backend/temporal/data_imports/sources/ubidots/settings.py
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 ae46cb8e375b..6b74e40240e7 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
@@ -12619,7 +12619,7 @@ Diffed against: <https://raw.githubusercontent.com/twilio/twilio-oai/main/spec/j
- [x] `Usage/Records (+ Daily/Monthly/Yearly variants)` — per-category usage and spend — the headline metric for anyone modeling Twilio cost (high)
- [ ] `Conferences/{ConferenceSid}/Participants` — per-participant rows are the only way to analyze conference attendance and talk time; conferences alone give no membership (high)
-- [ ] `Accounts (subaccount list)` — lookup table resolving the AccountSid carried on every message, call and recording already synced (high)
+- [x] `Accounts (subaccount list)` — lookup table resolving the AccountSid carried on every message, call and recording already synced (high)
- [ ] `Calls/{CallSid}/Events` — per-call state/transition history for debugging and funnel analysis of call flow (medium)
- [ ] `Notifications` — account-wide error and warning log, keyed to calls/messages — the standard delivery-failure diagnostic table (medium)
- [ ] `Messages/{MessageSid}/Media` — MMS media items per message; needed for attachment volume and storage analysis (medium)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/sample_scrub.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/sample_scrub.py
index 7c52ea1f5b5d..78c382bd6e64 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/sample_scrub.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/sample_scrub.py
@@ -60,6 +60,9 @@ REDACT_FIELD_NAMES: frozenset[str] = frozenset(
"imap_password",
# Synthesia's webhooks endpoint returns each webhook signing secret under this key.
"secret",
+ # Twilio's Accounts list returns each subaccount's live Auth Token here; the source's
+ # `data_map` drops it from rows, but that runs after sample capture.
+ "auth_token",
}
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/twilio/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/twilio/canonical_descriptions.py
index 4a513c976ec2..a08bb7ff71e9 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/twilio/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/twilio/canonical_descriptions.py
@@ -133,6 +133,21 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
friendly_name="User-provided name identifying the API key.",
),
},
+ "accounts": {
+ "description": "A Twilio account: the main account the credential belongs to, or one of its subaccounts.",
+ "docs_url": "https://www.twilio.com/docs/iam/api/account",
+ "columns": {
+ "sid": "Unique 34-character identifier for the account, starting with AC.",
+ "owner_account_sid": "SID of the parent account. Equals `sid` on the main account itself.",
+ "friendly_name": "Human-readable name for the account, up to 64 characters.",
+ "status": "Status of the account (active, suspended, or closed).",
+ "type": "Account type (Trial or Full).",
+ "date_created": "Time at which the account was created (RFC 2822 format).",
+ "date_updated": "Time at which the account was last updated (RFC 2822 format).",
+ "subresource_uris": "URIs of the related resources of the account, relative to the API base.",
+ "uri": "URI of the resource relative to the API base.",
+ },
+ },
"outgoing_caller_ids": {
"description": "A phone number verified for use as an outbound caller ID on the account.",
"docs_url": "https://www.twilio.com/docs/voice/api/outgoing-caller-ids",
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/twilio/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/twilio/settings.py
index 5564182dc2d8..fef6eefb31b5 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/twilio/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/twilio/settings.py
@@ -25,7 +25,7 @@ def _datetime_field(name: str, nullable: bool = False) -> IncrementalField:
}
-@dataclass
+@dataclass(frozen=True)
class TwilioEndpointConfig:
name: str
# For account-scoped endpoints, the suffix after `/2010-04-01/Accounts/{account_sid}/`, e.g.
@@ -57,6 +57,8 @@ class TwilioEndpointConfig:
sort_mode: SortMode = "asc"
# Rows per page. `None` sends no `PageSize` at all, leaving Twilio on its default of 50.
page_size: Optional[int] = DEFAULT_PAGE_SIZE
+ # Response fields dropped from every row before it reaches the warehouse.
+ excluded_fields: tuple[str, ...] = ()
TWILIO_ENDPOINTS: dict[str, TwilioEndpointConfig] = {
@@ -143,6 +145,17 @@ TWILIO_ENDPOINTS: dict[str, TwilioEndpointConfig] = {
response_key="transcriptions",
partition_key="date_created",
),
+ # The account itself plus every subaccount it owns. The list sits at the Accounts root, so it is not
+ # account-scoped.
+ "accounts": TwilioEndpointConfig(
+ name="accounts",
+ path="/2010-04-01/Accounts.json",
+ response_key="accounts",
+ account_scoped=False,
+ partition_key="date_created",
+ # Twilio returns the live Auth Token of each subaccount in this list. It must not land in the warehouse.
+ excluded_fields=("auth_token",),
+ ),
# Aggregated usage per category on the account. Records have no `sid`; each category appears once.
"usage_records": TwilioEndpointConfig(
name="usage_records",
@@ -184,11 +197,13 @@ TWILIO_ENDPOINTS: dict[str, TwilioEndpointConfig] = {
ENDPOINTS = tuple(TWILIO_ENDPOINTS.keys())
-# Twilio grants the Keys resource (/Accounts/{SID}/Keys) only to the Auth Token and to Main API keys.
-# Standard and Restricted API keys get a 401 with error 20003 on it, so the table has to be reported
-# as unreachable for those credentials instead of read as a failed credential check.
+# Twilio grants the Keys resource (/Accounts/{SID}/Keys) and the Accounts list only to the Auth Token
+# and to Main API keys. Standard and Restricted API keys get a 401 with error 20003 on them, so these
+# tables have to be reported as unreachable for those credentials instead of read as a failed
+# credential check.
# https://www.twilio.com/docs/iam/api-keys
-MAIN_KEY_ONLY_ENDPOINTS = frozenset({"keys"})
+# https://www.twilio.com/docs/iam/api/account
+MAIN_KEY_ONLY_ENDPOINTS = frozenset({"keys", "accounts"})
# `get_endpoint_permissions` only runs on the schema-picker path, so one-shot setup would otherwise
# enable a table it has no way to check. Defaulting these off covers both paths, since the picker and
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/twilio/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/twilio/source.py
index 84931f3bf1d7..d8f6aa61ada8 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/twilio/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/twilio/source.py
@@ -166,7 +166,7 @@ class TwilioSource(ResumableSource[TwilioSourceConfig, TwilioResumeConfig]):
Your **Account SID** is on the [Twilio Console dashboard](https://console.twilio.com). For credentials we recommend creating a [Standard API key](https://console.twilio.com/us1/account/keys-credentials/api-keys) (SID + Secret) since it can be revoked independently. You can also use your Account SID and Auth Token.
-Create the key in the same Twilio account as the Account SID above, in Twilio's default us1 region. A Standard key can read every table except `keys`, which needs your Auth Token or a Main API key.""",
+Create the key in the same Twilio account as the Account SID above, in Twilio's default us1 region. A Standard key can read every table except `keys` and `accounts`, which need your Auth Token or a Main API key.""",
iconPath="/static/services/twilio.png",
docsUrl="https://posthog.com/docs/cdp/sources/twilio",
fields=cast(
@@ -250,8 +250,8 @@ Create the key in the same Twilio account as the Account SID above, in Twilio's
# so this message has to cover both rather than asserting the credentials are invalid.
"Twilio rejected these credentials for this table. Either the Account SID and secret are wrong, "
"or the credential can't read this resource. A Restricted API key needs read access granted for "
- "it, and the keys table needs your Auth token or a Main API key. Fix the credential, then "
- "reconnect the source."
+ "it, and the keys and accounts tables need your Auth token or a Main API key. Fix the credential, "
+ "then reconnect the source."
)
forbidden = (
"Your Twilio credentials lack permission for this resource. Please check the credential's "
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/twilio/tests/test_twilio.py b/products/warehouse_sources/backend/temporal/data_imports/sources/twilio/tests/test_twilio.py
index f1bc1dbadd50..71a4324add0e 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/twilio/tests/test_twilio.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/twilio/tests/test_twilio.py
@@ -152,6 +152,7 @@ class TestValidateCredentials:
"schema_name, expected_message",
[
("keys", TWILIO_MAIN_KEY_REQUIRED_MESSAGE),
+ ("accounts", TWILIO_MAIN_KEY_REQUIRED_MESSAGE),
(
"messages",
"Twilio rejected these credentials for messages. Check that the Account SID and secret are "
@@ -243,6 +244,45 @@ class TestPagination:
assert result.requests[1].url == next_url
assert result.saved_states == [TwilioResumeConfig(next_url=next_url)]
+ def test_accounts_reads_the_accounts_root_and_drops_auth_tokens(self):
+ # Each subaccount row carries its live Auth Token. The list also sits outside the
+ # /Accounts/{SID}/ prefix that every other legacy table uses.
+ result = _run(
+ "accounts",
+ [
+ _response(
+ {
+ "accounts": [
+ {"sid": ACCOUNT_SID, "owner_account_sid": ACCOUNT_SID, "auth_token": "fake-token-1"},
+ {"sid": "AC11111111111111111111111111111111", "owner_account_sid": ACCOUNT_SID},
+ ],
+ "next_page_uri": "/2010-04-01/Accounts.json?PageSize=1000&Page=1&PageToken=PAfake",
+ }
+ ),
+ _response(
+ {
+ "accounts": [
+ {
+ "sid": "AC22222222222222222222222222222222",
+ "owner_account_sid": ACCOUNT_SID,
+ "auth_token": "fake-token-2",
+ }
+ ],
+ "next_page_uri": None,
+ }
+ ),
+ ],
+ )
+
+ assert result.rows == [
+ {"sid": ACCOUNT_SID, "owner_account_sid": ACCOUNT_SID},
+ {"sid": "AC11111111111111111111111111111111", "owner_account_sid": ACCOUNT_SID},
+ {"sid": "AC22222222222222222222222222222222", "owner_account_sid": ACCOUNT_SID},
+ ]
+ first, second = result.requests
+ assert first.origin + first.path == "https://api.twilio.com/2010-04-01/Accounts.json"
+ assert second.url == "https://api.twilio.com/2010-04-01/Accounts.json?PageSize=1000&Page=1&PageToken=PAfake"
+
def test_resumes_from_saved_state(self):
resume_url = "https://api.twilio.com/2010-04-01/Accounts/x/Messages.json?Page=5"
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/twilio/tests/test_twilio_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/twilio/tests/test_twilio_source.py
index b95cc7aea79c..75ee447e6cf3 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/twilio/tests/test_twilio_source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/twilio/tests/test_twilio_source.py
@@ -72,7 +72,7 @@ class TestTwilioSource:
mock_validate.assert_called_once_with(("SK123", "secret"), ACCOUNT_SID, "messages")
@pytest.mark.parametrize(
- "status_code, expected_keys_reason",
+ "status_code, expected_main_key_reason",
[
(401, TWILIO_MAIN_KEY_REQUIRED_REASON),
(403, TWILIO_MAIN_KEY_REQUIRED_REASON),
@@ -82,16 +82,17 @@ class TestTwilioSource:
(500, None),
],
)
- def test_get_endpoint_permissions_gates_only_the_keys_table(self, status_code, expected_keys_reason):
+ def test_get_endpoint_permissions_gates_only_the_main_key_tables(self, status_code, expected_main_key_reason):
+ main_key_only = {"keys", "accounts"}
with scripted_network(always(ScriptedResponse(status=status_code, json={}))) as network:
result = self.source.get_endpoint_permissions(self.config, self.team_id, list(ENDPOINTS))
- assert result["keys"] == expected_keys_reason
- assert {name: reason for name, reason in result.items() if name != "keys"} == dict.fromkeys(
- name for name in ENDPOINTS if name != "keys"
- )
+ assert result == {name: expected_main_key_reason if name in main_key_only else None for name in ENDPOINTS}
# Probing every table would add a round-trip per table to an interactive request.
- assert len({request.path for request in network.requests_log}) == 1
+ assert {request.path for request in network.requests_log} == {
+ f"/2010-04-01/Accounts/{ACCOUNT_SID}/Keys.json",
+ "/2010-04-01/Accounts.json",
+ }
def test_get_endpoint_permissions_survives_missing_secrets(self):
config = TwilioSourceConfig(account_sid=ACCOUNT_SID, auth_method=TwilioAuthMethodConfig(selection="api_key"))
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/twilio/twilio.py b/products/warehouse_sources/backend/temporal/data_imports/sources/twilio/twilio.py
index 1fbd2fce0b26..1716b308801a 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/twilio/twilio.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/twilio/twilio.py
@@ -1,4 +1,5 @@
import dataclasses
+from collections.abc import Callable
from datetime import UTC, date, datetime
from typing import Any, Optional
@@ -14,6 +15,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.res
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (
BaseNextUrlPaginator,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import EndpointResource
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
from products.warehouse_sources.backend.temporal.data_imports.sources.common.source_helpers import validate_via_probe
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
@@ -57,7 +59,7 @@ TWILIO_ACCOUNT_NOT_FOUND_MESSAGE = (
"dashboard. It starts with AC."
)
TWILIO_MAIN_KEY_REQUIRED_MESSAGE = (
- "Twilio's Keys resource needs your Auth Token or a Main API key. Standard and Restricted API keys cannot read it."
+ "This Twilio table needs your Auth Token or a Main API key. Standard and Restricted API keys cannot read it."
)
# The schema picker interpolates a reason into its own sentence ("Source credentials cannot read this
# table: {reason}. Grant the missing scope..."), so this has to be a fragment rather than the sentence
@@ -159,6 +161,13 @@ def _build_initial_params(
return params
+def _drop_fields(fields: tuple[str, ...]) -> Callable[[dict[str, Any]], dict[str, Any]]:
+ def drop(row: dict[str, Any]) -> dict[str, Any]:
+ return {key: value for key, value in row.items() if key not in fields}
+
+ return drop
+
+
def _build_resource_path(config: TwilioEndpointConfig, account_sid: str) -> str:
if config.account_scoped:
return f"/{TWILIO_API_VERSION}/Accounts/{account_sid}/{config.path}"
@@ -261,6 +270,17 @@ def twilio_source(
config, should_use_incremental_field, db_incremental_field_last_value, incremental_field
)
+ resource_config: EndpointResource = {
+ "name": endpoint,
+ "endpoint": {
+ "path": _build_resource_path(config, account_sid),
+ "params": params,
+ "data_selector": config.response_key,
+ },
+ }
+ if config.excluded_fields:
+ resource_config["data_map"] = _drop_fields(config.excluded_fields)
+
rest_config: RESTAPIConfig = {
"client": {
"base_url": config.base_url,
@@ -269,16 +289,7 @@ def twilio_source(
"paginator": TwilioNextPageUriPaginator(),
},
"resource_defaults": {},
- "resources": [
- {
- "name": endpoint,
- "endpoint": {
- "path": _build_resource_path(config, account_sid),
- "params": params,
- "data_selector": config.response_key,
- },
- }
- ],
+ "resources": [resource_config],
}
initial_paginator_state: Optional[dict[str, Any]] = None