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.

fix(warehouse-sources): probe SendGrid scopes per table (#78035)

jake sciotto1b11efed2bd9
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sendgrid/api_inventory.md b/products/warehouse_sources/backend/temporal/data_imports/sources/sendgrid/api_inventory.md
index 54c4bec2262f..56aca33d172d 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/sendgrid/api_inventory.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sendgrid/api_inventory.md
@@ -39,3 +39,11 @@ Notes:
- Rate limits: most v3 endpoints are generous, but the Email Activity API (`/messages`, deliberately not
synced here) is capped at ~6 req/min — webhook ingestion is the recommended path for per-event data and
is left as a follow-up.
+- Scopes are per endpoint, so a key that reads one table often can't read another.
+ `settings.py` records each endpoint's scope as `/v3/scopes` spells it (`suppression.bounces.read`,
+ `asm.groups.read`, `marketing.read`, `templates.read`), and `get_endpoint_permissions` probes them so the
+ schema picker can disable what the key can't reach.
+- `/marketing/lists` is the outlier: it needs `marketing.read` **and** an account with Marketing Campaigns.
+ Accounts without it, and accounts still on legacy Marketing Campaigns (a different API, scoped
+ `marketing_campaigns.read`), return 403 no matter how the key is scoped, so the table can be genuinely
+ unsyncable rather than misconfigured.
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sendgrid/sendgrid.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sendgrid/sendgrid.py
index 8dc6f042f664..7e783e07e6b3 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/sendgrid/sendgrid.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sendgrid/sendgrid.py
@@ -1,7 +1,7 @@
import dataclasses
from datetime import UTC, date, datetime
from typing import Any, Optional
-from urllib.parse import parse_qs, urlparse
+from urllib.parse import parse_qs, urlencode, urlparse
from requests import Response
@@ -228,12 +228,59 @@ def sendgrid_source(
)
-def get_status_code(api_key: str, path: str) -> Optional[int]:
+def get_status_code(api_key: str, path: str, params: Optional[dict[str, Any]] = None) -> Optional[int]:
"""Probe an endpoint to classify the credentials. Returns the HTTP status, or None on a
transport error."""
+ query = urlencode(params if params is not None else {"limit": 1})
_ok, status = validate_via_probe(
lambda: make_tracked_session(redact_values=(api_key,)),
- f"{SENDGRID_BASE_URL}{path}?limit=1",
+ f"{SENDGRID_BASE_URL}{path}?{query}",
headers=_get_headers(api_key),
)
return status
+
+
+def _probe_params(config: SendGridEndpointConfig) -> dict[str, Any]:
+ """Smallest valid request for a permission probe, using the endpoint's own pagination params so
+ the probe is never rejected for a param that endpoint doesn't accept."""
+ params: dict[str, Any] = dict(config.extra_params)
+ if config.pagination == "offset":
+ params["limit"] = 1
+ elif config.pagination == "metadata":
+ params["page_size"] = 1
+ return params
+
+
+def get_endpoint_status_code(api_key: str, config: SendGridEndpointConfig) -> Optional[int]:
+ return get_status_code(api_key, config.path, _probe_params(config))
+
+
+def permission_error_for(config: SendGridEndpointConfig) -> str:
+ message = f"Your SendGrid API key is missing the `{config.required_scope}` scope."
+ if config.permission_note:
+ return f"{message} {config.permission_note}"
+ return message
+
+
+def get_endpoint_permissions(api_key: str, endpoints: list[str]) -> dict[str, str | None]:
+ """Per-table scope probe for the schema picker: None when the key can read an endpoint, a short
+ reason naming the missing scope when it can't.
+
+ Only a definitive denial counts as unreachable. A throttle, 5xx, or transport error leaves the
+ table selectable, since sending someone to change scopes that are already correct is worse than
+ letting the sync report the real error.
+ """
+ results: dict[str, str | None] = {}
+ for name in endpoints:
+ config = SENDGRID_ENDPOINTS.get(name)
+ if config is None:
+ results[name] = None
+ continue
+ status = get_endpoint_status_code(api_key, config)
+ if status == 401:
+ results[name] = "Your SendGrid API key is invalid or expired."
+ elif status == 403:
+ results[name] = permission_error_for(config)
+ else:
+ results[name] = None
+ return results
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sendgrid/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sendgrid/settings.py
index b419844bad57..e9a4cf5789c6 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/sendgrid/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sendgrid/settings.py
@@ -27,6 +27,12 @@ class SendGridEndpointConfig:
incremental_param: Optional[str] = None
# Static query params always sent (e.g. templates' `generations`).
extra_params: dict[str, str] = field(default_factory=dict)
+ # SendGrid scope this endpoint reads, spelled as `/scopes` reports it. Surfaced per table in the
+ # schema picker when the key can't reach the endpoint, so the user grants that one access rather
+ # than regenerating a key that was never the problem.
+ required_scope: str = ""
+ # Appended to the missing-scope message where granting the scope may not be enough on its own.
+ permission_note: Optional[str] = None
def _epoch_field(name: str) -> IncrementalField:
@@ -51,6 +57,7 @@ SENDGRID_ENDPOINTS: dict[str, SendGridEndpointConfig] = {
partition_key="created",
incremental_fields=[_epoch_field("created")],
incremental_param="start_time",
+ required_scope="suppression.bounces.read",
),
"blocks": SendGridEndpointConfig(
name="blocks",
@@ -60,6 +67,7 @@ SENDGRID_ENDPOINTS: dict[str, SendGridEndpointConfig] = {
partition_key="created",
incremental_fields=[_epoch_field("created")],
incremental_param="start_time",
+ required_scope="suppression.blocks.read",
),
"invalid_emails": SendGridEndpointConfig(
name="invalid_emails",
@@ -69,6 +77,7 @@ SENDGRID_ENDPOINTS: dict[str, SendGridEndpointConfig] = {
partition_key="created",
incremental_fields=[_epoch_field("created")],
incremental_param="start_time",
+ required_scope="suppression.invalid_emails.read",
),
"spam_reports": SendGridEndpointConfig(
name="spam_reports",
@@ -78,6 +87,7 @@ SENDGRID_ENDPOINTS: dict[str, SendGridEndpointConfig] = {
partition_key="created",
incremental_fields=[_epoch_field("created")],
incremental_param="start_time",
+ required_scope="suppression.spam_reports.read",
),
"global_unsubscribes": SendGridEndpointConfig(
name="global_unsubscribes",
@@ -87,12 +97,14 @@ SENDGRID_ENDPOINTS: dict[str, SendGridEndpointConfig] = {
partition_key="created",
incremental_fields=[_epoch_field("created")],
incremental_param="start_time",
+ required_scope="suppression.unsubscribes.read",
),
"unsubscribe_groups": SendGridEndpointConfig(
name="unsubscribe_groups",
path="/asm/groups",
primary_keys=["id"],
pagination="single",
+ required_scope="asm.groups.read",
),
"marketing_lists": SendGridEndpointConfig(
name="marketing_lists",
@@ -101,6 +113,10 @@ SENDGRID_ENDPOINTS: dict[str, SendGridEndpointConfig] = {
pagination="metadata",
data_key="result",
page_size=100,
+ required_scope="marketing.read",
+ # Marketing Campaigns is provisioned per account, and legacy Marketing Campaigns serves a
+ # different API entirely, so both deny `/marketing/lists` however the key is scoped.
+ permission_note="Accounts without Marketing Campaigns, or on legacy Marketing Campaigns, cannot sync this table.",
),
"templates": SendGridEndpointConfig(
name="templates",
@@ -110,6 +126,7 @@ SENDGRID_ENDPOINTS: dict[str, SendGridEndpointConfig] = {
data_key="result",
page_size=100,
extra_params={"generations": "legacy,dynamic"},
+ required_scope="templates.read",
),
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sendgrid/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sendgrid/source.py
index 3d307e179553..661ec386ae88 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/sendgrid/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sendgrid/source.py
@@ -25,7 +25,10 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.generated_
)
from products.warehouse_sources.backend.temporal.data_imports.sources.sendgrid.sendgrid import (
SendGridResumeConfig,
+ get_endpoint_permissions as get_sendgrid_endpoint_permissions,
+ get_endpoint_status_code,
get_status_code,
+ permission_error_for,
sendgrid_source,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.sendgrid.settings import (
@@ -58,7 +61,9 @@ class SendGridSource(ResumableSource[SendGridSourceConfig, SendGridResumeConfig]
def get_non_retryable_errors(self) -> dict[str, str | None]:
return {
"401 Client Error: Unauthorized for url: https://api.sendgrid.com": "Your SendGrid API key is invalid or expired. Please generate a new key and reconnect.",
- "403 Client Error: Forbidden for url: https://api.sendgrid.com": "Your SendGrid API key is missing a scope required to sync this data. Please grant the required read scopes and reconnect.",
+ # Keyed on the error text, so this covers every endpoint and can't name the one scope.
+ # `get_endpoint_permissions` does that per table before a sync is ever queued.
+ "403 Client Error: Forbidden for url: https://api.sendgrid.com": "Your SendGrid API key cannot read this table. Add that table's read access to the key in SendGrid under Settings > API Keys, then resume this sync. Marketing lists also need an account with Marketing Campaigns.",
}
def get_schemas(
@@ -81,8 +86,12 @@ class SendGridSource(ResumableSource[SendGridSourceConfig, SendGridResumeConfig]
) -> tuple[bool, str | None]:
# `/scopes` is readable by any genuine key, so it's the cheapest probe at source-create.
# For a specific schema we probe its own endpoint to confirm the key has that read scope.
- path = SENDGRID_ENDPOINTS[schema_name].path if schema_name in SENDGRID_ENDPOINTS else "/scopes"
- status = get_status_code(config.api_key, path)
+ endpoint = SENDGRID_ENDPOINTS.get(schema_name) if schema_name is not None else None
+ status = (
+ get_endpoint_status_code(config.api_key, endpoint)
+ if endpoint is not None
+ else get_status_code(config.api_key, "/scopes")
+ )
if status == 200:
return True, None
@@ -92,6 +101,8 @@ class SendGridSource(ResumableSource[SendGridSourceConfig, SendGridResumeConfig]
# the endpoints they want); reject when validating a specific schema.
if schema_name is None:
return True, None
+ if endpoint is not None:
+ return False, permission_error_for(endpoint)
return False, "Your SendGrid API key is missing the scope required to sync this data."
if status == 401:
@@ -99,6 +110,11 @@ class SendGridSource(ResumableSource[SendGridSourceConfig, SendGridResumeConfig]
return False, "Could not validate SendGrid API key"
+ def get_endpoint_permissions(
+ self, config: SendGridSourceConfig, team_id: int, endpoints: list[str], api_version: str | None = None
+ ) -> dict[str, str | None]:
+ return get_sendgrid_endpoint_permissions(config.api_key, endpoints)
+
def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[SendGridResumeConfig]:
return ResumableSourceManager[SendGridResumeConfig](inputs, SendGridResumeConfig)
@@ -133,9 +149,11 @@ class SendGridSource(ResumableSource[SendGridSourceConfig, SendGridResumeConfig]
You can create an API key in your [SendGrid account settings](https://app.sendgrid.com/settings/api_keys).
Grant the following read access (Restricted Access) so the key can reach the data you want to sync:
-- **Suppressions** — bounces, blocks, invalid emails, spam reports, global unsubscribes, unsubscribe groups
-- **Marketing** — marketing lists
-- **Template Engine** — templates
+- **Suppressions**: bounces, blocks, invalid emails, spam reports, global unsubscribes, unsubscribe groups
+- **Marketing**: marketing lists. This also needs an account with Marketing Campaigns enabled.
+- **Template Engine**: templates
+
+Tables your key cannot read are flagged in the next step and left unselected.
""",
iconPath="/static/services/sendgrid.png",
docsUrl="https://posthog.com/docs/cdp/sources/sendgrid",
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sendgrid/tests/test_sendgrid.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sendgrid/tests/test_sendgrid.py
index d688a9d261dd..381dd19d4770 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/sendgrid/tests/test_sendgrid.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sendgrid/tests/test_sendgrid.py
@@ -1,6 +1,7 @@
import json
from datetime import UTC, date, datetime
from typing import Any
+from urllib.parse import parse_qs, urlparse
import pytest
from unittest import mock
@@ -11,6 +12,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.sendgrid.s
SendGridResumeConfig,
_offset_from_url,
_to_epoch_seconds,
+ get_endpoint_permissions,
get_status_code,
sendgrid_source,
)
@@ -301,3 +303,63 @@ class TestGetStatusCode:
session.get.side_effect = Exception("boom")
with mock.patch(SENDGRID_SESSION_PATCH, return_value=session):
assert get_status_code("k", "/scopes") is None
+
+
+class TestGetEndpointPermissions:
+ @staticmethod
+ def _probe(status: int | None, endpoints: list[str]) -> dict[str, str | None]:
+ session = mock.MagicMock()
+ if status is None:
+ session.get.side_effect = Exception("boom")
+ else:
+ session.get.return_value = mock.MagicMock(status_code=status)
+ with mock.patch(SENDGRID_SESSION_PATCH, return_value=session):
+ return get_endpoint_permissions("k", endpoints)
+
+ @pytest.mark.parametrize(
+ ("status", "expect_blocked"),
+ [
+ (200, False),
+ (403, True),
+ (401, True),
+ # A throttle, a 5xx, or a dead connection is not a scope problem. Blocking the table here
+ # would tell users to change permissions that are already correct.
+ (429, False),
+ (500, False),
+ (None, False),
+ ],
+ )
+ def test_only_a_definitive_denial_blocks_a_table(self, status: int | None, expect_blocked: bool) -> None:
+ permissions = self._probe(status, ["marketing_lists"])
+ assert (permissions["marketing_lists"] is not None) is expect_blocked
+
+ def test_403_names_the_scope_and_the_marketing_campaigns_caveat(self) -> None:
+ reason = self._probe(403, ["marketing_lists"])["marketing_lists"]
+ assert reason is not None
+ assert "marketing.read" in reason
+ assert "Marketing Campaigns" in reason
+
+ def test_unknown_endpoint_is_treated_as_reachable(self) -> None:
+ assert self._probe(403, ["not_an_endpoint"]) == {"not_an_endpoint": None}
+
+ @pytest.mark.parametrize(
+ ("endpoint", "expected_params"),
+ [
+ ("bounces", {"limit": "1"}),
+ # A blanket `limit=1` is not a param the marketing endpoints take, so probing with it
+ # risks a 400 that reads as "reachable" and hides the real denial.
+ ("marketing_lists", {"page_size": "1"}),
+ ("templates", {"page_size": "1", "generations": "legacy,dynamic"}),
+ ("unsubscribe_groups", {}),
+ ],
+ )
+ def test_probe_uses_the_endpoints_own_pagination_params(
+ self, endpoint: str, expected_params: dict[str, str]
+ ) -> None:
+ session = mock.MagicMock()
+ session.get.return_value = mock.MagicMock(status_code=200)
+ with mock.patch(SENDGRID_SESSION_PATCH, return_value=session):
+ get_endpoint_permissions("k", [endpoint])
+
+ url = session.get.call_args[0][0]
+ assert parse_qs(urlparse(url).query) == {key: [value] for key, value in expected_params.items()}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sendgrid/tests/test_sendgrid_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sendgrid/tests/test_sendgrid_source.py
index d31fefb036e5..6402764e4217 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/sendgrid/tests/test_sendgrid_source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sendgrid/tests/test_sendgrid_source.py
@@ -11,9 +11,13 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.generated_
SendGridSourceConfig,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.sendgrid.sendgrid import SendGridResumeConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.sendgrid.settings import SENDGRID_ENDPOINTS
from products.warehouse_sources.backend.temporal.data_imports.sources.sendgrid.source import SendGridSource
from products.warehouse_sources.backend.types import ExternalDataSourceType
+_SOURCE_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.sendgrid.source"
+_TRANSPORT_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.sendgrid.sendgrid"
+
ALL_ENDPOINTS = {
"bounces",
"blocks",
@@ -104,14 +108,41 @@ class TestSendGridSource:
def test_validate_credentials(
self, status: int | None, schema_name: str | None, expected_ok: bool, expected_has_msg: bool
) -> None:
- with patch(
- "products.warehouse_sources.backend.temporal.data_imports.sources.sendgrid.source.get_status_code",
- return_value=status,
+ # A named schema probes its own endpoint; source-create probes `/scopes`.
+ with (
+ patch(f"{_SOURCE_MODULE}.get_status_code", return_value=status),
+ patch(f"{_SOURCE_MODULE}.get_endpoint_status_code", return_value=status),
):
ok, msg = SendGridSource().validate_credentials(_config(), team_id=1, schema_name=schema_name)
assert ok is expected_ok
assert (msg is not None) is expected_has_msg
+ def test_per_schema_403_names_the_missing_scope(self) -> None:
+ with patch(f"{_SOURCE_MODULE}.get_endpoint_status_code", return_value=403):
+ _ok, msg = SendGridSource().validate_credentials(_config(), team_id=1, schema_name="marketing_lists")
+ assert msg is not None
+ assert "marketing.read" in msg
+
+ def test_get_endpoint_permissions_flags_only_the_unreadable_table(self) -> None:
+ # The bug this guards: with no per-table probe every table looked reachable, so a key without
+ # `marketing.read` still got marketing_lists enabled, and the first sync hard-failed.
+ def status_for(_api_key: str, config: Any) -> int:
+ return 403 if config.name == "marketing_lists" else 200
+
+ with patch(f"{_TRANSPORT_MODULE}.get_endpoint_status_code", side_effect=status_for):
+ permissions = SendGridSource().get_endpoint_permissions(_config(), team_id=1, endpoints=list(ALL_ENDPOINTS))
+
+ assert permissions["marketing_lists"] is not None
+ assert "marketing.read" in permissions["marketing_lists"]
+ assert {name: reason for name, reason in permissions.items() if reason is not None} == {
+ "marketing_lists": permissions["marketing_lists"]
+ }
+
+ @pytest.mark.parametrize("name", sorted(ALL_ENDPOINTS))
+ def test_every_endpoint_declares_a_scope_to_name(self, name: str) -> None:
+ # An endpoint added without one would render "missing the `` scope" at users.
+ assert SENDGRID_ENDPOINTS[name].required_scope
+
def test_get_resumable_source_manager_is_bound_to_resume_config(self) -> None:
manager = SendGridSource().get_resumable_source_manager(_source_inputs())
assert isinstance(manager, ResumableSourceManager)