: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(github): name the real cause of a github 403 or 404 (#78196)
Tom Owers9ecb167e9f11
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.pyindex ccf09b90b98e..aa1eb60d9fb0 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@@ -68,7 +68,15 @@ class GithubEmptyRepositoryError(Exception):pass-class GithubOrgNotFoundError(Exception):+class GithubResourceUnavailableError(Exception):+ """This endpoint holds nothing for this repository, and never will until the owner changes+ something on GitHub's side. The repository itself is fine, so failing the schema would be wrong:+ ``_fetch_page`` raises this and the caller syncs zero rows."""++ pass+++class GithubOrgNotFoundError(GithubResourceUnavailableError):"""GitHub returns 404 on the org-scoped endpoints (``/orgs/{org}/teams`` and the membersfan-out) when the repository owner is a personal account rather than an organization, or thetoken has no org access, and on the ``tolerate_not_found`` endpoints (issue types, repository@@ -79,6 +87,24 @@ class GithubOrgNotFoundError(Exception):pass+class GithubAccessDeniedError(Exception):+ """GitHub refused the call with a 403 that is not a rate limit (``_fetch_page`` classifies rate+ limits first) and not a switched-off repository feature. The connection is missing a permission,+ or the organization has not approved it, so retrying cannot help — the message carries GitHub's+ own explanation so the curated copy can name the cause."""++ pass+++class GithubRepositoryNotFoundError(Exception):+ """The repository itself does not resolve for this connection: an endpoint 404'd and a probe of+ ``/repos/{owner}/{repo}`` 404'd too. A renamed or transferred repository still resolves (GitHub+ answers 301 to the new location and we follow it), so this means the repository was deleted or+ the connection lost access to it. Permanent until the source is reconfigured."""++ pass++class GithubRepositoryTooLargeError(Exception):"""GitHub's /stats/code_frequency permanently 422s once a repository passes 10,000 commits — adocumented limit of that specific endpoint (other stats endpoints keep working, just with@@ -654,6 +680,79 @@ _github_backoff_wait = wait_exponential_jitter(initial=1, max=30)_NO_ADAPTER_RETRY = Retry(total=0)+def _github_error_message(response: requests.Response) -> str:+ """GitHub's own explanation for a failed call, from the standard ``{"message": ...}`` error body.+ Empty when the body is missing or is not that shape (an HTML edge error page, say)."""+ try:+ body = response.json()+ except ValueError:+ return ""+ if not isinstance(body, dict):+ return ""+ message = body.get("message")+ return message if isinstance(message, str) else ""+++# GitHub answers 403 both for a real permission denial and for a repository feature the owner has+# switched off — Dependabot alerts disabled, code scanning without Advanced Security, an archived+# repository. A switched-off feature has nothing to sync now or on any later run, so it is a+# zero-row skip rather than something to fail the schema over. Matched against GitHub's own message.+_FEATURE_UNAVAILABLE_MARKERS = ("is disabled", "are disabled", "must be enabled", "not enabled", "is archived")+++def _is_feature_unavailable_denial(message: str) -> bool:+ lowered = message.lower()+ return any(marker in lowered for marker in _FEATURE_UNAVAILABLE_MARKERS)+++def _is_repository_scoped(page_url: str, repository: str) -> bool:+ """Does this URL address the repository itself or something under it? Org-scoped endpoints+ (``/orgs/{org}/...``) address a different resource, so the repository's state says nothing about+ a 404 they return."""+ marker = f"/repos/{repository.lower()}"+ lowered = page_url.lower()+ index = lowered.find(marker)+ if index == -1:+ return False+ tail = lowered[index + len(marker) :]+ return tail == "" or tail[0] in "/?#"+++def _repository_resolves(+ repository: str,+ headers: dict[str, str],+ egress_identity: GithubEgressIdentity | None,+) -> bool | None:+ """Does ``/repos/{owner}/{repo}`` still resolve for this connection? ``None`` when we could not+ tell (rate limit, 5xx, network error, shed by our own budget), so the caller keeps the cautious+ behavior instead of acting on a guess.++ This is what separates "the repository is gone" from "this table is not available for this+ repository" when an endpoint 404s. A renamed or transferred repository resolves through GitHub's+ 301 to the new location, which the HTTP layer follows, so a 404 here is a deleted repository or+ revoked access."""+ installation_id = egress_identity.installation_id if egress_identity is not None else None+ try:+ response = github_request(+ "GET",+ f"{GITHUB_BASE_URL}/repos/{repository}",+ source="warehouse",+ headers=headers,+ installation_id=installation_id,+ priority=Priority.BATCH,+ timeout=30,+ session=make_tracked_session(retry=_NO_ADAPTER_RETRY),+ )+ raise_if_github_rate_limited(response)+ except (GitHubEgressBudgetExhausted, GitHubRateLimitError, requests.RequestException):+ return None+ if response.status_code == 404:+ return False+ if response.ok:+ return True+ return None++def _github_retry_wait(state: RetryCallState) -> float:"""Sleep until GitHub's advertised rate-limit reset when it gave us one(capped, plus a little jitter so the sources sharing one installation's@@ -691,6 +790,7 @@ def _fetch_page(logger: FilteringBoundLogger,egress_identity: GithubEgressIdentity | None = None,skip_on_not_found: bool = False,+ repository: str | None = None,) -> requests.Response:# One gated + recorded GET through the shared egress client. The App path bills the shared# per-installation budget at BATCH (deferrable bulk); the PAT path (installation_id None) skips the@@ -714,8 +814,9 @@ def _fetch_page(raise GithubRetryableError(f"Github API error (retryable): status={response.status_code}, url={page_url}")# Rate limited (secondary 429, or primary 403 with a rate-limit body): raise- # so we retry honoring the reset/Retry-After. A genuine permission 403 carries- # no rate-limit body and falls through to raise_for_status below, staying fatal.+ # so we retry honoring the reset/Retry-After. Every 403 that survives this call+ # is therefore a denial, not a rate limit, which is what lets the messages below+ # name a cause instead of hedging between the two.raise_if_github_rate_limited(response)# An empty repository (no commits yet) returns 409 on the commits@@ -733,6 +834,28 @@ def _fetch_page(if skip_on_not_found and response.status_code == 404:raise GithubOrgNotFoundError()+ if response.status_code == 403:+ message = _github_error_message(response)+ if _is_feature_unavailable_denial(message):+ logger.info(f"Github: feature not available for this repository: url={page_url}, message={message}")+ raise GithubResourceUnavailableError(message)+ logger.error(f"Github API error: status=403, body={response.text}, url={page_url}")+ raise GithubAccessDeniedError(f"GitHub denied access: {message or 'no reason given'} (url={page_url})")++ # Only repository-scoped URLs, so an org-scoped 404 (a specific team's members, say) keeps its+ # own handling — the repository resolving says nothing about whether that org resource exists.+ if response.status_code == 404 and repository is not None and _is_repository_scoped(page_url, repository):+ # A 404 on one endpoint says nothing about the repository on its own — plenty of endpoints+ # 404 when the feature behind them was never turned on. Ask GitHub about the repository+ # before blaming it, so only a genuinely gone repository fails the schema.+ resolves = _repository_resolves(repository, headers, egress_identity)+ if resolves is True:+ logger.info(f"Github: endpoint not available for this repository, syncing zero rows: url={page_url}")+ raise GithubResourceUnavailableError(_github_error_message(response))+ if resolves is False:+ logger.error(f"Github: repository does not resolve: repository={repository}, url={page_url}")+ raise GithubRepositoryNotFoundError(f"GitHub repository is not accessible: {repository}")+if not response.ok:logger.error(f"Github API error: status={response.status_code}, body={response.text}, url={page_url}")response.raise_for_status()@@ -749,6 +872,7 @@ def _iter_pages(page_cap_context: dict[str, Any] | None = None,egress_identity: GithubEgressIdentity | None = None,skip_on_not_found: bool = False,+ repository: str | None = None,) -> Iterator[tuple[list[dict[str, Any]], str]]:"""Yield (items, page_url) for each page of a paginated GitHub list,unwrapping the envelope and following the Link header. Stops at ``max_pages``,@@ -757,9 +881,16 @@ def _iter_pages(page_count = 0while True:try:- response = _fetch_page(url, headers, logger, egress_identity, skip_on_not_found=skip_on_not_found)- except GithubOrgNotFoundError:- logger.debug(f"Github: org-scoped endpoint not found, syncing zero rows: url={url}")+ response = _fetch_page(+ url,+ headers,+ logger,+ egress_identity,+ skip_on_not_found=skip_on_not_found,+ repository=repository,+ )+ except GithubResourceUnavailableError:+ logger.debug(f"Github: endpoint holds nothing for this repository, syncing zero rows: url={url}")returnexcept GithubEmptyRepositoryError:# `commits` is a fan_out_parent (check_runs, commit_statuses), so this walk can hit the@@ -819,6 +950,7 @@ def _iter_child_for_parent(max_pages=config.max_pages_per_parent,page_cap_context={"repository": repository, fan_out_param: parent_value},egress_identity=egress_identity,+ repository=repository,):for item in items:if item_filter and not item_filter(item):@@ -946,6 +1078,7 @@ def _fan_out_get_rows(logger,egress_identity=egress_identity,skip_on_not_found=parent_org_scoped,+ repository=repository,):parents = [parent_mapper(parent) for parent in raw_parents] if parent_mapper else raw_parentsstop_after_this_page = _should_stop_desc(parents, "desc", parent_cursor_field, parent_cutoff)@@ -1048,11 +1181,18 @@ def get_rows(skip_on_not_found = endpoint in ORG_SCOPED_ENDPOINTS or config.tolerate_not_foundwhile True:try:- response = _fetch_page(url, headers, logger, egress_identity, skip_on_not_found=skip_on_not_found)+ response = _fetch_page(+ url,+ headers,+ logger,+ egress_identity,+ skip_on_not_found=skip_on_not_found,+ repository=repository,+ )except GithubEmptyRepositoryError:logger.debug(f"Github: repository has no commits (empty repository), syncing zero rows: url={url}")break- except GithubOrgNotFoundError:+ except GithubResourceUnavailableError:logger.debug(f"Github: {endpoint} not available for this repository, syncing zero rows: url={url}")breakexcept GithubRepositoryTooLargeError: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.pyindex eae9a6b206fb..a1959b8b980a 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@@ -242,8 +242,21 @@ If automatic creation failed, your token needs webhook permissions — the **admdef get_non_retryable_errors(self) -> dict[str, str | None]:return {"401 Client Error": "Invalid GitHub credentials. Please reconnect your account.",- "403 Client Error": "Access forbidden. Your token may lack required permissions or have hit rate limits.",- "404 Client Error": "Repository not found. Please verify the repository name and access permissions.",+ # GitHub's own wording for the two denials a user can actually act on. Both are matched+ # ahead of the generic 403 keys below, because the first match in this dict wins.+ "Resource not accessible by integration": "The GitHub app doesn't have permission to read this table. Give it the matching repository permission on GitHub, then reconnect your GitHub account.",+ "Resource not accessible by personal access token": "Your GitHub token doesn't have permission to read this table. Add the missing scope to the token, then update the source with the new token.",+ "SAML enforcement": "Your GitHub organization requires single sign-on for this connection. Authorize it on GitHub, then reconnect your GitHub account.",+ "OAuth App access restrictions": "Your GitHub organization hasn't approved this connection. Ask an organization owner to approve it, then reconnect your GitHub account.",+ # Rate-limited 403s never reach here: the sync classifies those as a rate limit and backs+ # off until GitHub's reset. A 403 that lands in this map is a permission denial.+ "GitHub denied access": "GitHub denied access to this repository. The connected account is missing a permission, or your organization hasn't approved it. Check the connection on GitHub, then reconnect your GitHub account.",+ "403 Client Error": "GitHub denied access to this repository. The connected account is missing a permission, or your organization hasn't approved it. Check the connection on GitHub, then reconnect your GitHub account.",+ # Raised only after a probe confirms the repository itself no longer resolves. A renamed+ # or transferred repository still resolves through GitHub's redirect, so this is a+ # deleted repository or one the connection can no longer see.+ "GitHub repository is not accessible": "This repository is no longer available on GitHub. It may have been deleted, or your connection may have lost access to it. Update the source with a repository you can still reach, or reconnect your GitHub account.",+ "404 Client Error": "GitHub couldn't find this repository. Check that it still exists and that your connection can access it.","Bad credentials": "Your GitHub connection is invalid or expired. Please reconnect.",# The GitHub App isn't configured on this PostHog instance, so an OAuth source can't mint# the App JWT to refresh its installation token. Deterministic — retrying never resolves it.diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/github/tests/test_github_fetch_page.py b/products/warehouse_sources/backend/temporal/data_imports/sources/github/tests/test_github_fetch_page.pyindex 49d538dccda0..69fd5f5f04a2 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/github/tests/test_github_fetch_page.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/github/tests/test_github_fetch_page.py@@ -187,6 +187,111 @@ def test_fetch_page_gates_on_egress_budget_when_installation_known():}+def _error_response(status_code: int, message: str, headers: dict[str, str] | None = None) -> mock.Mock:+ response = mock.Mock(spec=requests.Response)+ response.status_code = status_code+ response.ok = False+ response.headers = headers or {}+ response.text = json.dumps({"message": message})+ response.json.return_value = {"message": message}+ response.request = None+ response.raise_for_status.side_effect = requests.exceptions.HTTPError(+ f"{status_code} Client Error: for url", response=response+ )+ return response+++ "message,expected_exc",+ [+ # GitHub uses 403 for a repository feature the owner switched off. Nothing to sync, now or+ # ever, so the table must skip rather than fail the schema and stop syncing.+ ("Dependabot alerts are disabled for this repository.", github.GithubResourceUnavailableError),+ (+ "Advanced Security must be enabled for this repository to use code scanning.",+ github.GithubResourceUnavailableError,+ ),+ ("Secret scanning is disabled on this repository.", github.GithubResourceUnavailableError),+ # A real denial stays fatal, and carries GitHub's own reason so the curated copy can name it.+ ("Resource not accessible by integration", github.GithubAccessDeniedError),+ ("Must have admin rights to Repository.", github.GithubAccessDeniedError),+ ],+)+def test_fetch_page_403_separates_switched_off_features_from_denials(message, expected_exc):+ session = mock.Mock()+ session.request.return_value = _error_response(403, message)++ with mock.patch.object(github, "make_tracked_session", return_value=session):+ with pytest.raises(expected_exc) as raised:+ github._fetch_page("https://api.github.com/repos/o/r/dependabot/alerts", {}, mock.Mock(), repository="o/r")++ assert message in str(raised.value)+++def test_fetch_page_403_from_rate_limit_is_not_a_denial():+ # The denial classification must stay behind the rate-limit check: a rate-limited 403 has to keep+ # backing off and retrying, not become a permanent "GitHub denied access" that stops the schema.+ session = mock.Mock()+ session.request.return_value = _error_response(+ 403, "You have exceeded a secondary rate limit. Please wait a few minutes before you try again."+ )++ with (+ mock.patch.object(github, "make_tracked_session", return_value=session),+ mock.patch("tenacity.nap.time.sleep"),+ ):+ with pytest.raises(github.GitHubRateLimitError):+ github._fetch_page("https://api.github.com/repos/o/r/issues", {}, mock.Mock(), repository="o/r")+++ "page_url,probe_response,expected_exc,expected_calls",+ [+ # The repository still resolves, so the 404 is about this endpoint alone (a feature that was+ # never turned on) — sync zero rows instead of blaming the repository.+ (+ "https://api.github.com/repos/o/r/issue-types",+ _ok_response,+ github.GithubResourceUnavailableError,+ 2,+ ),+ # The repository itself is gone, which no retry can fix.+ (+ "https://api.github.com/repos/o/r/issue-types",+ lambda: _error_response(404, "Not Found"),+ github.GithubRepositoryNotFoundError,+ 2,+ ),+ # GitHub couldn't tell us either way, so keep the old cautious behavior.+ (+ "https://api.github.com/repos/o/r/issue-types",+ lambda: _error_response(500, "Server Error"),+ requests.exceptions.HTTPError,+ 2,+ ),+ # An org-scoped endpoint addresses a different resource, so the repository resolving says+ # nothing about it: don't probe, and keep the 404 fatal.+ (+ "https://api.github.com/orgs/o/teams/core/members",+ _ok_response,+ requests.exceptions.HTTPError,+ 1,+ ),+ ],+)+def test_fetch_page_404_probes_the_repository_before_blaming_it(page_url, probe_response, expected_exc, expected_calls):+ session = mock.Mock()+ session.request.side_effect = [_error_response(404, "Not Found"), probe_response()]++ with mock.patch.object(github, "make_tracked_session", return_value=session):+ with pytest.raises(expected_exc):+ github._fetch_page(page_url, {}, mock.Mock(), repository="o/r")++ assert session.request.call_count == expected_calls+ if expected_calls > 1:+ assert session.request.call_args_list[1].args[1] == "https://api.github.com/repos/o/r"++def test_fetch_page_skips_gate_on_pat_path():# PAT path has no installation budget, so the gate must never run and the request proceeds.session = mock.Mock()diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/github/tests/test_github_repository_endpoints.py b/products/warehouse_sources/backend/temporal/data_imports/sources/github/tests/test_github_repository_endpoints.pyindex 36e055203fbb..7851fbb2ec2d 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/github/tests/test_github_repository_endpoints.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/github/tests/test_github_repository_endpoints.py@@ -278,8 +278,9 @@ class TestNotFoundTolerance:# would break the whole schema for every personal repository.("issue_types", True),("repository_teams", True),- # A plain repo-scoped table keeps 404 fatal, so a genuinely wrong or revoked repository- # still fails loud instead of quietly syncing an empty table forever.+ # A plain repo-scoped table keeps 404 fatal once the repository probe 404s too, so a+ # genuinely wrong or revoked repository still fails loud instead of quietly syncing an+ # empty table forever.("labels", False),])@@ -289,7 +290,7 @@ class TestNotFoundTolerance:with mock.patch.object(github, "make_tracked_session", return_value=session):if not tolerated:- with pytest.raises(requests.exceptions.HTTPError):+ with pytest.raises(github.GithubRepositoryNotFoundError):_run_over_transport(endpoint)returnassert _run_over_transport(endpoint) == []diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/github/tests/test_github_source_class.py b/products/warehouse_sources/backend/temporal/data_imports/sources/github/tests/test_github_source_class.pyindex 9d5ddfd0b2df..d24ac33457b6 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/github/tests/test_github_source_class.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/github/tests/test_github_source_class.py@@ -3,6 +3,7 @@ from unittest import mockfrom posthog.models.integration import GitHubIntegrationError+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import error_message_matchesfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.integration_accounts import (IntegrationAccountListingError,)@@ -114,6 +115,31 @@ class TestGithubSource:def test_non_retryable_errors(self, expected_key):assert expected_key in self.source.get_non_retryable_errors()+ @pytest.mark.parametrize(+ "raised_message,expected_key",+ [+ (+ "GitHub denied access: Resource not accessible by integration (url=https://api.github.com/repos/o/r/issues)",+ "Resource not accessible by integration",+ ),+ (+ "GitHub denied access: Resource protected by organization SAML enforcement. You must grant your OAuth token access to this organization. (url=https://api.github.com/repos/o/r/issues)",+ "SAML enforcement",+ ),+ (+ "GitHub denied access: Must have admin rights to Repository. (url=https://api.github.com/repos/o/r/issues)",+ "GitHub denied access",+ ),+ ("GitHub repository is not accessible: owner/repo", "GitHub repository is not accessible"),+ ],+ )+ def test_sync_failures_pick_the_specific_friendly_error(self, raised_message, expected_key):+ # The job picks the first matching key, so a specific cause must be declared ahead of the+ # generic fallback or every denial reads as the vague one.+ errors = self.source.get_non_retryable_errors()+ matched = next(key for key in errors if error_message_matches(raised_message, [key]))+ assert matched == expected_key+def test_suspended_installation_token_refresh_is_non_retryable(self):# The raw GitHubIntegrationError raised by refresh_access_token on a suspended installation.error_message = (diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/github/tests/test_github_teams.py b/products/warehouse_sources/backend/temporal/data_imports/sources/github/tests/test_github_teams.pyindex 3c0b5f66d3a3..d4750482e25f 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/github/tests/test_github_teams.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/github/tests/test_github_teams.py@@ -53,7 +53,8 @@ def _not_found_response() -> mock.Mock:# rows, not fail the schema. teams walks it directly; team_members hits it via its fan-out parent.("teams", False),("team_members", False),- # Repo-scoped: a 404 is a genuinely missing/inaccessible repo and must stay fatal.+ # Repo-scoped: the repository probe 404s here too, so the repository really is gone and the+ # sync must stay fatal.("issues", True),],)@@ -70,7 +71,7 @@ def test_org_scoped_404_syncs_zero_rows_while_repo_scoped_404_stays_fatal(endpoiresumable_source_manager=_no_resume(),)if expect_raise:- with pytest.raises(requests.exceptions.HTTPError):+ with pytest.raises(github.GithubRepositoryNotFoundError):list(rows)else:assert list(rows) == []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.pyindex ad6c05fd4c96..fa0eae45d7ac 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@@ -21,6 +21,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.generated_)from products.warehouse_sources.backend.temporal.data_imports.sources.github.github import (GITHUB_MAX_RETRY_AFTER_SECONDS,+ GithubAccessDeniedError,GithubEgressIdentity,GithubResumeConfig,GithubRetryableError,@@ -1878,7 +1879,7 @@ class TestFetchPageRateLimit:"products.warehouse_sources.backend.temporal.data_imports.sources.github.github.make_tracked_session") as mock_get:mock_get.return_value.request.return_value = resp- with pytest.raises(requests.HTTPError):+ with pytest.raises(GithubAccessDeniedError):_fetch_page("https://api.github.com/x", {}, mock.Mock())assert mock_get.return_value.request.call_count == 1