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(egress): gate warehouse github validation and webhook calls (#100818)

Julian Bezf0a32817fd1f
diff --git a/posthog/egress/github/README.md b/posthog/egress/github/README.md
index 6a975f7c53b9..9c7bf06d10c2 100644
--- a/posthog/egress/github/README.md
+++ b/posthog/egress/github/README.md
@@ -26,6 +26,7 @@ All three budgets use the default reserve ladder.
Deferrable background callers construct their client on the `BATCH` lane (`GitHubIntegration(integration, source=..., priority=Priority.BATCH)`; `api_request` also takes a per-call override).
A shed sweep stops for the cycle and resumes on the next scheduled run.
A caller that walks pages, such as the warehouse source, paces with `github_installation_pace_seconds` instead of getting denied.
+The warehouse source's page fetches run on `BATCH`, while its repository validation and webhook management run on `NORMAL`, because a person waits on them.
The `BATCH` floor on the `core` resource is **demand-responsive**, because a reserve is only worth holding against traffic that exists.
An installation whose only consumer is a bulk one (a warehouse backfill of a repository nothing else touches) would otherwise forfeit 30% of its hourly budget to contention that never arrives, and the hourly budget is what decides whether a large backfill finishes in one run.
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/github/github.py b/products/warehouse_sources/backend/temporal/data_imports/sources/github/github.py
index aae9db8f1fcc..8288d97798b9 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/github/github.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/github/github.py
@@ -381,7 +381,10 @@ REPOSITORY_NOT_ACCESSIBLE_REASON = "not found or not accessible"
def validate_credentials(
- personal_access_token: str, repository: str, api_version: str = GITHUB_DEFAULT_API_VERSION
+ personal_access_token: str,
+ repository: str,
+ egress_identity: GithubEgressIdentity | None = None,
+ api_version: str = GITHUB_DEFAULT_API_VERSION,
) -> tuple[bool, str | None]:
"""Validate GitHub API credentials by making a test request to the repository."""
# A bare owner name otherwise reaches the API as a nonsense path, 404s, and gets reported as
@@ -402,7 +405,18 @@ def validate_credentials(
headers = _get_headers(personal_access_token, api_version=api_version)
try:
- response = make_tracked_session().get(url, headers=headers, timeout=10)
+ # NORMAL, not BATCH: the source wizard waits on this answer.
+ response = github_request(
+ "GET",
+ url,
+ source="warehouse",
+ headers=headers,
+ installation_id=egress_identity.installation_id if egress_identity is not None else None,
+ priority=Priority.NORMAL,
+ timeout=10,
+ session=make_tracked_session(retry=_NO_ADAPTER_RETRY),
+ )
+ raise_if_github_rate_limited(response)
if response.status_code == 200:
return True, None
@@ -429,6 +443,8 @@ def validate_credentials(
False,
f"GitHub rejected the request (status {response.status_code}). Please check your token and repository access.",
)
+ except (GitHubEgressBudgetExhausted, GitHubRateLimitError):
+ return False, "GitHub rate limit reached while validating the repository; please retry shortly."
except requests.exceptions.RequestException as e:
return False, str(e)
@@ -471,7 +487,7 @@ def check_org_endpoint_permission(
installation_id=installation_id,
priority=Priority.NORMAL,
timeout=10,
- session=make_tracked_session(),
+ session=make_tracked_session(retry=_NO_ADAPTER_RETRY),
)
# A rate-limited 403 carries limit markers; without this check it would read as a missing grant.
raise_if_github_rate_limited(response)
@@ -726,6 +742,8 @@ _github_backoff_wait = wait_exponential_jitter(initial=1, max=30)
# would defeat the 300s cap below and stack a second, untested retry layer. With
# adapter retries off, _fetch_page sees every response/exception and our tenacity
# layer is the single, rate-limit-aware retry authority.
+# Every gated GET uses it too: an adapter retry happens after egress admission, so one admitted
+# call could send several GitHub requests that the installation budget never counts.
_NO_ADAPTER_RETRY = Retry(total=0)
@@ -1649,6 +1667,7 @@ def create_repo_webhook(
webhook_url: str,
events: list[str],
secret: str,
+ egress_identity: GithubEgressIdentity | None = None,
api_version: str = GITHUB_DEFAULT_API_VERSION,
) -> WebhookCreationResult:
"""Create a repo webhook via POST /repos/{repo}/hooks.
@@ -1669,8 +1688,22 @@ def create_repo_webhook(
}
try:
- response = make_tracked_session().post(
- f"{GITHUB_BASE_URL}/repos/{repo}/hooks", headers=headers, json=payload, timeout=30
+ response = github_request(
+ "POST",
+ f"{GITHUB_BASE_URL}/repos/{repo}/hooks",
+ source="warehouse",
+ headers=headers,
+ installation_id=egress_identity.installation_id if egress_identity is not None else None,
+ priority=Priority.NORMAL,
+ timeout=30,
+ session=make_tracked_session(),
+ json=payload,
+ )
+ raise_if_github_rate_limited(response)
+ except (GitHubEgressBudgetExhausted, GitHubRateLimitError):
+ return WebhookCreationResult(
+ success=False,
+ error="GitHub rate limit reached while creating the repository webhook; please retry shortly.",
)
except requests.exceptions.RequestException as e:
return WebhookCreationResult(success=False, error=f"Failed to create webhook automatically: {e}")
@@ -1724,7 +1757,9 @@ def ensure_repo_webhook(
hook = _match_hook_by_url(hooks or [], webhook_url)
if hook is None:
- return create_repo_webhook(token, repo, webhook_url, events, secret=secret, api_version=api_version)
+ return create_repo_webhook(
+ token, repo, webhook_url, events, secret=secret, egress_identity=egress_identity, api_version=api_version
+ )
merged_events = sorted(set(hook.get("events") or []) | set(events))
try:
@@ -1791,7 +1826,7 @@ def _list_repo_hooks(
installation_id=installation_id,
priority=Priority.NORMAL,
timeout=30,
- session=make_tracked_session(),
+ session=make_tracked_session(retry=_NO_ADAPTER_RETRY),
)
raise_if_github_rate_limited(response)
except (GitHubEgressBudgetExhausted, GitHubRateLimitError):
@@ -1855,8 +1890,21 @@ def delete_repo_webhook(
headers = _get_headers(token, api_version=api_version)
try:
- response = make_tracked_session().delete(
- f"{GITHUB_BASE_URL}/repos/{repo}/hooks/{hook_id}", headers=headers, timeout=30
+ response = github_request(
+ "DELETE",
+ f"{GITHUB_BASE_URL}/repos/{repo}/hooks/{hook_id}",
+ source="warehouse",
+ headers=headers,
+ installation_id=egress_identity.installation_id if egress_identity is not None else None,
+ priority=Priority.NORMAL,
+ timeout=30,
+ session=make_tracked_session(),
+ )
+ raise_if_github_rate_limited(response)
+ except (GitHubEgressBudgetExhausted, GitHubRateLimitError):
+ return WebhookDeletionResult(
+ success=False,
+ error="GitHub rate limit reached while deleting the repository webhook; please retry shortly.",
)
except requests.exceptions.RequestException as e:
return WebhookDeletionResult(success=False, error=f"Failed to delete webhook: {e}")
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/github/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/github/source.py
index ff27b1018631..1dcf2aa208df 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/github/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/github/source.py
@@ -660,11 +660,15 @@ If automatic creation failed with a permissions error, the fix depends on how yo
) -> tuple[bool, str | None]:
try:
access_token = self._get_access_token(config, team_id)
+ egress_identity = self._egress_identity(config, team_id)
repositories = self.effective_repositories(config)
failures: list[str] = []
for repository in repositories[: self.MAX_VALIDATED_REPOSITORIES]:
is_valid, message = validate_github_credentials(
- access_token, repository, api_version=self.resolve_api_version(api_version)
+ access_token,
+ repository,
+ egress_identity=egress_identity,
+ api_version=self.resolve_api_version(api_version),
)
if is_valid:
continue
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/github/tests/test_github_api_version_headers.py b/products/warehouse_sources/backend/temporal/data_imports/sources/github/tests/test_github_api_version_headers.py
index 73c0be241b91..294926150f02 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/github/tests/test_github_api_version_headers.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/github/tests/test_github_api_version_headers.py
@@ -4,6 +4,8 @@ from typing import Any
import pytest
from unittest import mock
+from posthog.egress.limiter.policies import Priority
+
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.github import (
GithubAuthMethodConfig,
GithubSourceConfig,
@@ -34,11 +36,7 @@ def _run(surface: Callable[[GithubSource, str | None], object], api_version: str
headers.append(kwargs["headers"])
return _response()
- session = mock.Mock()
- session.get.side_effect = record
- session.post.side_effect = record
- session.delete.side_effect = record
- with mock.patch.object(github, "make_tracked_session", return_value=session):
+ with mock.patch.object(github, "make_tracked_session", return_value=mock.Mock()):
with mock.patch.object(github, "github_request", side_effect=record):
surface(GithubSource(), api_version)
assert headers, "surface made no GitHub request"
@@ -80,3 +78,37 @@ def test_non_sync_surfaces_send_resolved_api_version(
) -> None:
for headers in _run(_SURFACES[surface], api_version):
assert headers["X-GitHub-Api-Version"] == expected_header
+
+
+ "surface,hooks,expected_methods",
+ [
+ ("validate_credentials", [], {"GET"}),
+ ("create_webhook", [], {"GET", "POST"}),
+ ("delete_webhook", [{"id": 42, "config": {"url": _WEBHOOK_URL}}], {"GET", "DELETE"}),
+ ],
+)
+def test_installation_backed_surfaces_gate_on_the_installation(
+ surface: str, hooks: list[dict[str, Any]], expected_methods: set[str]
+) -> None:
+ # On the GitHub App path these calls spend the installation's shared budget: a call that drops the
+ # installation id goes ungated, and each runs on NORMAL because a person waits on it.
+ calls: list[tuple[str, dict[str, Any]]] = []
+
+ def record(method: str, url: str, **kwargs: Any) -> mock.Mock:
+ calls.append((method, kwargs))
+ response = _response()
+ response.json.return_value = hooks
+ return response
+
+ identity = github.GithubEgressIdentity(installation_id="42")
+ with (
+ mock.patch.object(GithubSource, "_egress_identity", return_value=identity),
+ mock.patch.object(github, "make_tracked_session", return_value=mock.Mock()),
+ mock.patch.object(github, "github_request", side_effect=record),
+ ):
+ _SURFACES[surface](GithubSource(), None)
+
+ assert {method for method, _ in calls} == expected_methods
+ assert all(kwargs["installation_id"] == "42" for _, kwargs in calls)
+ assert all(kwargs["priority"] is Priority.NORMAL for _, kwargs in calls)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/github/tests/test_github_validate_credentials.py b/products/warehouse_sources/backend/temporal/data_imports/sources/github/tests/test_github_validate_credentials.py
index 13a9fdcaf482..8b36c253ff73 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/github/tests/test_github_validate_credentials.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/github/tests/test_github_validate_credentials.py
@@ -9,6 +9,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.github imp
def _response(status_code: int, *, json_body: object | None = None, text: str = "") -> mock.Mock:
response = mock.Mock(spec=requests.Response)
response.status_code = status_code
+ response.headers = {}
response.text = text
if json_body is None:
response.json.side_effect = requests.exceptions.JSONDecodeError("no json", "", 0)
@@ -19,7 +20,7 @@ def _response(status_code: int, *, json_body: object | None = None, text: str =
def _validate_with(response: mock.Mock) -> tuple[bool, str | None]:
session = mock.Mock()
- session.get.return_value = response
+ session.request.return_value = response
with mock.patch.object(github, "make_tracked_session", return_value=session):
return github.validate_credentials("token", "owner/repo")
@@ -81,9 +82,27 @@ def test_repository_url_is_read_as_owner_repo(repository):
# A pasted GitHub URL names the repo unambiguously, so it must reach the API as owner/repo
# instead of being rejected for its format.
session = mock.Mock()
- session.get.return_value = _response(200, json_body={})
+ session.request.return_value = _response(200, json_body={})
with mock.patch.object(github, "make_tracked_session", return_value=session):
is_valid, message = github.validate_credentials("token", repository)
assert (is_valid, message) == (True, None)
- assert session.get.call_args.args[0].endswith("/repos/owner/repo")
+ assert session.request.call_args.args[1].endswith("/repos/owner/repo")
+
+
+ "status_code,headers",
+ [
+ (429, {}), # secondary rate limit
+ (403, {"x-ratelimit-remaining": "0"}), # primary limit exhausted
+ ],
+)
+def test_rate_limit_is_not_read_as_a_credential_problem(status_code, headers):
+ # A throttled validation must tell the user to retry, not surface the 403 or 429 as if the
+ # token or repository were wrong.
+ response = _response(status_code, json_body={"message": "API rate limit exceeded"})
+ response.headers = headers
+ is_valid, message = _validate_with(response)
+ assert is_valid is False
+ assert message is not None
+ assert "retry" in message
diff --git a/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/github/test_github_source.py b/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/github/test_github_source.py
index 504b429b1c7b..cece0dd23983 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/github/test_github_source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/github/test_github_source.py
@@ -433,7 +433,7 @@ class TestValidateCredentials:
with mock.patch(
"products.warehouse_sources.backend.temporal.data_imports.sources.github.github.make_tracked_session"
) as mock_get:
- mock_get.return_value.get.return_value = mock.MagicMock(status_code=200)
+ mock_get.return_value.request.return_value = mock.MagicMock(status_code=200)
valid, error = validate_credentials("token", "owner/repo")
assert valid is True
@@ -449,7 +449,7 @@ class TestValidateCredentials:
with mock.patch(
"products.warehouse_sources.backend.temporal.data_imports.sources.github.github.make_tracked_session"
) as mock_get:
- mock_get.return_value.get.return_value = mock.MagicMock(status_code=status_code)
+ mock_get.return_value.request.return_value = mock.MagicMock(status_code=status_code)
valid, error = validate_credentials("token", "owner/repo")
assert valid is False
@@ -459,19 +459,19 @@ class TestValidateCredentials:
with mock.patch(
"products.warehouse_sources.backend.temporal.data_imports.sources.github.github.make_tracked_session"
) as mock_get:
- mock_response = mock.MagicMock(status_code=403)
- mock_response.json.return_value = {"message": "API rate limit exceeded"}
- mock_get.return_value.get.return_value = mock_response
+ mock_response = mock.MagicMock(status_code=403, headers={}, text="Resource not accessible by integration")
+ mock_response.json.return_value = {"message": "Resource not accessible by integration"}
+ mock_get.return_value.request.return_value = mock_response
valid, error = validate_credentials("token", "owner/repo")
assert valid is False
- assert error == "API rate limit exceeded"
+ assert error == "Resource not accessible by integration"
def test_request_exception(self) -> None:
with mock.patch(
"products.warehouse_sources.backend.temporal.data_imports.sources.github.github.make_tracked_session"
) as mock_get:
- mock_get.return_value.get.side_effect = requests.exceptions.ConnectionError("Connection refused")
+ mock_get.return_value.request.side_effect = requests.exceptions.ConnectionError("Connection refused")
valid, error = validate_credentials("token", "owner/repo")
assert valid is False
@@ -482,11 +482,11 @@ class TestValidateCredentials:
with mock.patch(
"products.warehouse_sources.backend.temporal.data_imports.sources.github.github.make_tracked_session"
) as mock_get:
- mock_get.return_value.get.return_value = mock.MagicMock(status_code=200)
+ mock_get.return_value.request.return_value = mock.MagicMock(status_code=200)
validate_credentials("my-token", "owner/repo")
- mock_get.return_value.get.assert_called_once()
- call_kwargs = mock_get.return_value.get.call_args
+ mock_get.return_value.request.assert_called_once()
+ call_kwargs = mock_get.return_value.request.call_args
assert call_kwargs is not None
headers = call_kwargs.kwargs["headers"]
assert headers["Authorization"] == "Bearer my-token"
@@ -1539,15 +1539,9 @@ class TestGithubWebhookSource:
assert self.source.get_desired_webhook_events(_pat_config(), eligible) == expected_events
def test_create_webhook_sends_secret_and_returns_it_as_extra_input(self) -> None:
- captured: dict[str, Any] = {}
-
- def post(url: str, headers: Any = None, json: Any = None, timeout: Any = None) -> Any:
- captured["url"] = url
- captured["json"] = json
- return _make_response(status=201, body={"id": 99})
-
- session = mock.Mock()
- session.post.side_effect = post
+ session = self._hook_session(
+ _make_response(status=200, body=[]), post_response=_make_response(status=201, body={"id": 99})
+ )
with mock.patch(
"products.warehouse_sources.backend.temporal.data_imports.sources.github.github.make_tracked_session",
@@ -1555,8 +1549,9 @@ class TestGithubWebhookSource:
):
result = self.source.create_webhook(_pat_config(), "https://app.posthog.com/webhook", team_id=1)
- assert "/repos/owner/repo/hooks" in captured["url"]
- sent_secret = captured["json"]["config"]["secret"]
+ post = next(call for call in session.request.call_args_list if call.args[0] == "POST")
+ assert "/repos/owner/repo/hooks" in post.args[1]
+ sent_secret = post.kwargs["json"]["config"]["secret"]
assert sent_secret # a non-empty secret is minted and handed to GitHub
assert result.success is True
# GitHub never echoes the secret, so create_webhook returns the minted one
@@ -1564,8 +1559,9 @@ class TestGithubWebhookSource:
assert result.extra_inputs["signing_secret"] == sent_secret
def test_create_webhook_permission_error_falls_back_to_manual(self) -> None:
- session = mock.Mock()
- session.post.return_value = _make_response(status=403, body={"message": "Forbidden"})
+ denied = _make_response(status=403, body={"message": "Forbidden"})
+ denied.text = "Forbidden" # no rate-limit markers, so this must map to the grant hint
+ session = self._hook_session(_make_response(status=200, body=[]), post_response=denied)
with mock.patch(
"products.warehouse_sources.backend.temporal.data_imports.sources.github.github.make_tracked_session",
@@ -1578,16 +1574,23 @@ class TestGithubWebhookSource:
assert "admin:repo_hook" in result.error
@staticmethod
- def _hook_session(list_response: mock.Mock, patch_response: mock.Mock | None = None) -> mock.Mock:
- # The hook list rides github_request, which sends via session.request(method, url, ...);
+ def _hook_session(
+ list_response: mock.Mock,
+ patch_response: mock.Mock | None = None,
+ post_response: mock.Mock | None = None,
+ delete_response: mock.Mock | None = None,
+ ) -> mock.Mock:
+ # Every hook call rides github_request, which sends via session.request(method, url, ...);
# route by method so a stray write (e.g. a PATCH on a no-drift path) fails loudly.
session = mock.Mock()
+ write_responses = {"PATCH": patch_response, "POST": post_response, "DELETE": delete_response}
def route(method: str, url: str, **kwargs: Any) -> mock.Mock:
if method == "GET":
return list_response
- if method == "PATCH" and patch_response is not None:
- return patch_response
+ write_response = write_responses.get(method)
+ if write_response is not None:
+ return write_response
raise AssertionError(f"Unexpected {method} request: {url}")
session.request.side_effect = route
@@ -1595,8 +1598,10 @@ class TestGithubWebhookSource:
def test_delete_webhook_lists_then_deletes_matching_hook(self) -> None:
webhook_url = "https://app.posthog.com/webhook"
- session = self._hook_session(_make_response(status=200, body=[{"id": 42, "config": {"url": webhook_url}}]))
- session.delete.return_value = _make_response(status=204)
+ session = self._hook_session(
+ _make_response(status=200, body=[{"id": 42, "config": {"url": webhook_url}}]),
+ delete_response=_make_response(status=204),
+ )
with mock.patch(
"products.warehouse_sources.backend.temporal.data_imports.sources.github.github.make_tracked_session",
@@ -1605,8 +1610,8 @@ class TestGithubWebhookSource:
result = self.source.delete_webhook(_pat_config(), webhook_url, team_id=1)
assert result.success is True
- delete_url = session.delete.call_args.args[0]
- assert "/repos/owner/repo/hooks/42" in delete_url
+ delete = next(call for call in session.request.call_args_list if call.args[0] == "DELETE")
+ assert "/repos/owner/repo/hooks/42" in delete.args[1]
def test_get_external_webhook_info_reports_existing_hook(self) -> None:
webhook_url = "https://app.posthog.com/webhook"
@@ -1640,8 +1645,10 @@ class TestGithubWebhookSource:
# The hook is found in the list but DELETE races a concurrent removal and
# 404s — the desired end state, so it must not surface as a permission error.
webhook_url = "https://app.posthog.com/webhook"
- session = self._hook_session(_make_response(status=200, body=[{"id": 42, "config": {"url": webhook_url}}]))
- session.delete.return_value = _make_response(status=404, body={"message": "Not Found"})
+ session = self._hook_session(
+ _make_response(status=200, body=[{"id": 42, "config": {"url": webhook_url}}]),
+ delete_response=_make_response(status=404, body={"message": "Not Found"}),
+ )
with mock.patch(
"products.warehouse_sources.backend.temporal.data_imports.sources.github.github.make_tracked_session",
@@ -1768,6 +1775,38 @@ class TestGithubWebhookSource:
assert "rate limit" in result.error
assert "admin:repo_hook" not in result.error
+ @parameterized.expand(
+ [
+ ("create", [], "post_response", "create_webhook"),
+ (
+ "delete",
+ [{"id": 42, "config": {"url": "https://app.posthog.com/webhook"}}],
+ "delete_response",
+ "delete_webhook",
+ ),
+ ]
+ )
+ def test_webhook_write_rate_limit_is_not_a_permission_error(
+ self, _name: str, hooks: list[dict[str, Any]], write_response: str, method: str
+ ) -> None:
+ # The listing succeeds but the write itself is rate limited; reading that 403 as a missing
+ # admin:repo_hook grant would send the user off to rotate a token that is fine.
+ rate_limited = _make_response(status=403, body={"message": "API rate limit exceeded"})
+ rate_limited.headers = {"x-ratelimit-remaining": "0"}
+ rate_limited.text = "API rate limit exceeded"
+ session = self._hook_session(_make_response(status=200, body=hooks), **{write_response: rate_limited})
+
+ with mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.github.github.make_tracked_session",
+ return_value=session,
+ ):
+ result = getattr(self.source, method)(_pat_config(), "https://app.posthog.com/webhook", team_id=1)
+
+ assert result.success is False
+ assert result.error is not None
+ assert "rate limit" in result.error
+ assert "admin:repo_hook" not in result.error
+
@parameterized.expand(
[
("already_subscribed", ["workflow_job", "workflow_run", "pull_request_review"]),