: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): derive unsyncable tables from the installation's permissions (#74705)
posthog[bot]7bdeec07d33a
diff --git a/posthog/models/github_integration_base.py b/posthog/models/github_integration_base.pyindex a2721cd056d1..081b4d1ac5b1 100644--- a/posthog/models/github_integration_base.py+++ b/posthog/models/github_integration_base.py@@ -406,6 +406,12 @@ class GitHubIntegrationBase:"expires_in": expires_in,"refreshed_at": int(time.time()),}+ # The token response names the permissions this installation actually holds. Persisting them+ # lets the warehouse schema picker mark tables the installation can't read without an API+ # call, and keeps the copy current as the App's requested permissions change: every hourly+ # refresh rewrites it, including for integrations connected before this key existed.+ if isinstance(data.get("permissions"), dict):+ config["permissions"] = data["permissions"]config.pop(INSTALLATION_UNAVAILABLE_SINCE_CONFIG_KEY, None)self.integration.config = configself.integration.sensitive_config = {diff --git a/posthog/models/integration.py b/posthog/models/integration.pyindex 49d93f401d1d..4fed4e9246a3 100644--- a/posthog/models/integration.py+++ b/posthog/models/integration.py@@ -3390,6 +3390,10 @@ class GitHubIntegration(GitHubIntegrationBase):"name": dot_get(installation_access.installation_info, "account.login", installation_id),},}+ # See GitHubIntegrationBase.refresh_access_token for why permissions are persisted.+ permissions = installation_access.installation_info.get("permissions")+ if isinstance(permissions, dict):+ config["permissions"] = permissionssensitive_config = {"access_token": installation_access.access_token}diff --git a/posthog/models/test/test_integration_model.py b/posthog/models/test/test_integration_model.pyindex 7207f09112bd..73595664337d 100644--- a/posthog/models/test/test_integration_model.py+++ b/posthog/models/test/test_integration_model.py@@ -1687,7 +1687,13 @@ class TestGitHubIntegrationModel(BaseTest):)def mock_github_client_request(- self, status_code=201, token="ACCESS_TOKEN", repository_selection="all", expires_in_hours=1, error_text=None+ self,+ status_code=201,+ token="ACCESS_TOKEN",+ repository_selection="all",+ expires_in_hours=1,+ error_text=None,+ permissions=None,):def _client_request(endpoint, method="GET"):mock_response = MagicMock()@@ -1701,13 +1707,17 @@ class TestGitHubIntegrationModel(BaseTest):"token": token,"repository_selection": repository_selection,"expires_at": iso_time,+ **({"permissions": permissions} if permissions is not None else {}),}else:mock_response.text = error_text or "error"mock_response.json.return_value = {}else:mock_response.status_code = 200- mock_response.json.return_value = {"account": {"type": "Organization", "login": "PostHog"}}+ mock_response.json.return_value = {+ "account": {"type": "Organization", "login": "PostHog"},+ **({"permissions": permissions} if permissions is not None else {}),+ }return mock_responsereturn _client_request@@ -2302,6 +2312,25 @@ class TestGitHubIntegrationModel(BaseTest):"access_token": "ACCESS_TOKEN",}+ @patch("posthog.models.github_integration_base.GitHubIntegrationBase.client_request")+ def test_github_integration_persists_installation_permissions(self, mock_client_request):+ # The warehouse schema picker reads config["permissions"] to mark tables the installation+ # can't sync. Dropping this on connect or refresh silently returns the picker to offering+ # tables whose every sync 403s.+ mock_client_request.side_effect = self.mock_github_client_request(+ permissions={"contents": "read", "metadata": "read"}+ )+ integration = GitHubIntegration.integration_from_installation_id("INSTALLATION_ID", self.team.id, self.user)+ assert integration.config["permissions"] == {"contents": "read", "metadata": "read"}++ # A permission update to the App shows up on the next hourly token refresh, including for+ # integrations connected before this key was persisted at all.+ mock_client_request.side_effect = self.mock_github_client_request(+ permissions={"contents": "read", "metadata": "read", "deployments": "read"}+ )+ GitHubIntegration(integration).refresh_access_token()+ assert integration.config["permissions"] == {"contents": "read", "metadata": "read", "deployments": "read"}+@patch("posthog.models.integration.reload_integrations_on_workers")@patch("posthog.models.github_integration_base.GitHubIntegrationBase.client_request")def test_github_refresh_access_token_handles_errors(self, mock_client_request, mock_reload):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 aa1eb60d9fb0..4cffd8060409 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@@ -35,7 +35,10 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.resfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponsefrom products.warehouse_sources.backend.temporal.data_imports.sources.common.webhook_s3 import WebhookSourceManagerfrom products.warehouse_sources.backend.temporal.data_imports.sources.github.settings import (+ ENDPOINT_REQUIRED_PERMISSION,GITHUB_ENDPOINTS,+ GRANT_DENIAL_PREFIX,+ GRANT_NAMES,GithubEndpointConfig,)@@ -91,7 +94,8 @@ class GithubAccessDeniedError(Exception):"""GitHub refused the call with a 403 that is not a rate limit (``_fetch_page`` classifies ratelimits 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."""+ own explanation so the curated copy can name the cause. When the denial is about one endpoint's+ grant, the message also names the grant to add, which reaches the failed job's internal error."""pass@@ -705,6 +709,38 @@ def _is_feature_unavailable_denial(message: str) -> bool:return any(marker in lowered for marker in _FEATURE_UNAVAILABLE_MARKERS)+# GitHub's wording when the connection holds no grant for the endpoint. The first two are what an+# App installation and a fine-grained token get; the push/admin pair is what the endpoints behind+# the administration grant (traffic, self-hosted runners) answer instead.+_PERMISSION_DENIED_MARKERS = (+ "resource not accessible by",+ "must have push access",+ "must have admin rights",+)+++def _is_endpoint_permission_denial(message: str) -> bool:+ lowered = message.lower()+ return any(marker in lowered for marker in _PERMISSION_DENIED_MARKERS)+++def _grant_hint(required_permission: str | None) -> str:+ names = GRANT_NAMES.get(required_permission) if required_permission is not None else None+ if names is None:+ # No mapped grant, so the denial may be an account access-level gate (collaborators needs+ # push access) rather than a missing permission. Offer both routes instead of claiming a+ # permission alone fixes it.+ return (+ " Add the missing permission to your GitHub connection, or connect with a personal "+ "access token from an account that has the access GitHub names, then sync again."+ )+ fine_grained, classic_scope = names+ return (+ f' Grant "{fine_grained}" on a fine-grained token or app installation, '+ f"or {classic_scope} on a classic token, then sync again."+ )++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@@ -791,6 +827,7 @@ def _fetch_page(egress_identity: GithubEgressIdentity | None = None,skip_on_not_found: bool = False,repository: str | None = None,+ required_permission: 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@@ -839,8 +876,21 @@ def _fetch_page(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})")+ # A SAML or blocked-repository 403 denies the whole connection, so it keeps the generic+ # wording: naming one table's grant there would send the user to the wrong setting.+ if not _is_endpoint_permission_denial(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})")++ # This message reaches the user as the schema's error, because GithubSource's+ # get_non_retryable_errors keys GRANT_DENIAL_PREFIX and the permission markers to None, so+ # curated copy never replaces it. The URL stays in the log line rather than in what the+ # user reads.+ grant_hint = _grant_hint(required_permission)+ logger.error(+ f"Github API error: status=403, body={response.text}, grant_hint={grant_hint.strip()}, url={page_url}"+ )+ raise GithubAccessDeniedError(f"{GRANT_DENIAL_PREFIX}: {message.rstrip('. ')}.{grant_hint}")# 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.@@ -873,6 +923,7 @@ def _iter_pages(egress_identity: GithubEgressIdentity | None = None,skip_on_not_found: bool = False,repository: str | None = None,+ required_permission: 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``,@@ -888,6 +939,7 @@ def _iter_pages(egress_identity,skip_on_not_found=skip_on_not_found,repository=repository,+ required_permission=required_permission,)except GithubResourceUnavailableError:logger.debug(f"Github: endpoint holds nothing for this repository, syncing zero rows: url={url}")@@ -951,6 +1003,7 @@ def _iter_child_for_parent(page_cap_context={"repository": repository, fan_out_param: parent_value},egress_identity=egress_identity,repository=repository,+ required_permission=ENDPOINT_REQUIRED_PERMISSION.get(config.name),):for item in items:if item_filter and not item_filter(item):@@ -1079,6 +1132,7 @@ def _fan_out_get_rows(egress_identity=egress_identity,skip_on_not_found=parent_org_scoped,repository=repository,+ required_permission=ENDPOINT_REQUIRED_PERMISSION.get(parent_config.name),):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)@@ -1188,6 +1242,7 @@ def get_rows(egress_identity,skip_on_not_found=skip_on_not_found,repository=repository,+ required_permission=ENDPOINT_REQUIRED_PERMISSION.get(endpoint),)except GithubEmptyRepositoryError:logger.debug(f"Github: repository has no commits (empty repository), syncing zero rows: url={url}")diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/github/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/github/settings.pyindex 16b0d9c82771..aa57bc49bd70 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/github/settings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/github/settings.py@@ -834,3 +834,70 @@ ENDPOINTS = tuple(GITHUB_ENDPOINTS.keys())INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {name: config.incremental_fields for name, config in GITHUB_ENDPOINTS.items()}++# The grant a connection needs before GitHub will answer this endpoint, keyed the way GitHub names+# it in an installation's permission set, so the picker can compare it against the permissions the+# installation actually holds. Endpoints not listed here need no grant beyond the metadata/contents+# read that every connection is validated for at connect time, so a denial on those is not a+# per-table gap.+ENDPOINT_REQUIRED_PERMISSION: dict[str, str] = {+ "issues": "issues",+ "issue_comments": "issues",+ "issue_events": "issues",+ "issue_types": "issues",+ "labels": "issues",+ "milestones": "issues",+ "pull_requests": "pull_requests",+ "pull_request_comments": "pull_requests",+ "reviews": "pull_requests",+ "workflow_runs": "actions",+ "workflow_jobs": "actions",+ "workflows": "actions",+ "artifacts": "actions",+ "actions_caches": "actions",+ "check_runs": "checks",+ "commit_statuses": "statuses",+ "environments": "environments",+ "deployments": "deployments",+ "deployment_statuses": "deployments",+ "code_scanning_alerts": "security_events",+ "secret_scanning_alerts": "secret_scanning_alerts",+ "dependabot_alerts": "vulnerability_alerts",+ "security_advisories": "repository_advisories",+ "runners": "administration",+ "traffic_views": "administration",+ "traffic_clones": "administration",+ "traffic_referrers": "administration",+ "traffic_paths": "administration",+ "hooks": "repository_hooks",+ "teams": "members",+ "team_members": "members",+}++# Prefix of every per-endpoint grant-denial message _fetch_page raises. GithubSource's+# get_non_retryable_errors keys its catch-all on this exact string: GitHub phrases denials per+# endpoint ("Must have push access to view repository collaborators"), so without the shared prefix+# those wordings would match no key and the job would retry a denial forever instead of disabling+# the schema.+GRANT_DENIAL_PREFIX = "GitHub can't read this table"++# What to ask for, as (name on a fine-grained token or app installation, scope on a classic token).+# The three name the same grant differently, so the message carries both rather than making the+# reader translate. _grant_hint in github.py builds the sentence, which keeps the wording in one+# place and out of the user-facing string, where markdown does not render.+GRANT_NAMES: dict[str, tuple[str, str]] = {+ "issues": ("Issues: read", "repo"),+ "pull_requests": ("Pull requests: read", "repo"),+ "actions": ("Actions: read", "repo"),+ "checks": ("Checks: read", "repo"),+ "statuses": ("Commit statuses: read", "repo:status"),+ "environments": ("Environments: read", "repo"),+ "deployments": ("Deployments: read", "repo_deployment"),+ "security_events": ("Code scanning alerts: read", "security_events"),+ "secret_scanning_alerts": ("Secret scanning alerts: read", "repo"),+ "vulnerability_alerts": ("Dependabot alerts: read", "security_events"),+ "repository_advisories": ("Repository security advisories: read", "repo"),+ "administration": ("Administration: read", "repo"),+ "repository_hooks": ("Webhooks: read", "admin:repo_hook"),+ "members": ("Members: read on the organization", "read:org"),+}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 a1959b8b980a..cdc3c0a4f3bd 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@@ -46,6 +46,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.typfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.webhook_s3 import WebhookSourceManagerfrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.github import GithubSourceConfigfrom products.warehouse_sources.backend.temporal.data_imports.sources.github.github import (+ _ORG_PERMISSION_REASON,ORG_SCOPED_ENDPOINTS,GithubEgressIdentity,GithubResumeConfig,@@ -64,8 +65,11 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.github.namsplit_schema_name,)from products.warehouse_sources.backend.temporal.data_imports.sources.github.settings import (+ ENDPOINT_REQUIRED_PERMISSION,ENDPOINTS,GITHUB_ENDPOINTS,+ GRANT_DENIAL_PREFIX,+ GRANT_NAMES,INCREMENTAL_FIELDS,)from products.warehouse_sources.backend.types import ExternalDataSourceType@@ -242,10 +246,20 @@ 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.",- # GitHub's own wording for the two denials a user can actually act on. Both are matched+ # None deliberately: _fetch_page already raises these denials with a message naming the+ # exact grant, and the job finalizer only overwrites latest_error when the value here is+ # not None. Curated copy would replace that grant name with a vaguer sentence. 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.",+ "Resource not accessible by integration": None,+ "Resource not accessible by personal access token": None,+ # GitHub's wording for the tables behind the administration grant (traffic, self-hosted+ # runners). The picker only offers these on a token connection, so the reader is already+ # on a token and needs the access level, not a route they are on.+ "Must have push access to repository": "This table needs push access to the repository. Use a personal access token from an account with push access, then sync again.",+ "Must have admin rights": "This table needs admin access to the repository. Use a personal access token from an account with admin access, then sync again.",+ # Catch-all for the denial wordings GitHub phrases per endpoint ("Must have push access+ # to view repository collaborators"), which the keys above can't enumerate.+ GRANT_DENIAL_PREFIX: None,"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@@ -443,6 +457,36 @@ If automatic creation failed, your token needs webhook permissions — the **admschemas = [s for s in schemas if s.name in names_set]return schemas+ def _installation_permissions(self, config: GithubSourceConfig, team_id: int) -> dict[str, str] | None:+ """The permission set the App installation holds, or None when it can't be known (a token+ connection, a broken integration, a row connected before permissions were persisted — the+ hourly token-refresh sweep backfills those). None fails open: the picker shows the table,+ and a real denial still fails the sync with the grant named."""+ if config.auth_method.selection == "pat" or not config.auth_method.github_integration_id:+ return None+ try:+ integration = self.get_oauth_integration(config.auth_method.github_integration_id, team_id)+ held = integration.config.get("permissions")+ return held if isinstance(held, dict) else None+ except Exception:+ return None++ @staticmethod+ def _missing_permission_reason(required_permission: str) -> str:+ # Rendered inside SchemaForm's tooltip wrapper ("Source credentials cannot read this+ # table: {reason}. ..."), so this must stay a sentence fragment with no trailing period,+ # like _ORG_PERMISSION_REASON.+ fine_grained, classic_scope = GRANT_NAMES.get(required_permission, (required_permission, "repo"))+ # The administration endpoints also gate on the account's own access level, so scope alone+ # isn't enough there.+ account_needs = (+ " from an account with admin access to the repository" if required_permission == "administration" else ""+ )+ return (+ f'Requires the "{fine_grained}" permission, which this GitHub app installation does not hold; '+ f"use a personal access token with the {classic_scope} scope{account_needs} instead"+ )+def get_endpoint_permissions(self, config: GithubSourceConfig, team_id: int, endpoints: list[str], api_version: str | None = None) -> dict[str, str | None]:@@ -452,9 +496,22 @@ If automatic creation failed, your token needs webhook permissions — the **adm# unique owner and fan the reason back per input name, so a repo-scoped connection sees# exactly which tables need the extra grant and can deselect them.result: dict[str, str | None] = dict.fromkeys(endpoints)+ # An installation can only hold permissions the App requests, so a table whose grant is+ # absent from the held set can never sync on this connection, however often the user+ # reconnects. A token connection returns None here (token grants aren't introspectable), so+ # its denials surface at sync time instead, where the error names the grant.+ held_permissions = self._installation_permissions(config, team_id)org_endpoints: dict[str, str] = {} # input name -> repository to probe throughfor name in endpoints:repository, endpoint = split_schema_name(name)+ required = ENDPOINT_REQUIRED_PERMISSION.get(endpoint)+ if held_permissions is not None and required is not None and required not in held_permissions:+ # The org tables keep their existing reason: it carries the org-owned-repository+ # caveat this generic wording lacks, and the two surfaces should not diverge.+ result[name] = (+ _ORG_PERMISSION_REASON if required == "members" else self._missing_permission_reason(required)+ )+ continueif endpoint not in ORG_SCOPED_ENDPOINTS:continueorg_endpoints[name] = (repository or config.repository or "").strip().lower()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 69fd5f5f04a2..94831e75dc6e 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@@ -9,7 +9,9 @@ from prometheus_client import REGISTRYfrom posthog.egress.github.limiter import GitHubRateResourcefrom posthog.egress.limiter.policies import Priority+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import error_message_matchesfrom products.warehouse_sources.backend.temporal.data_imports.sources.github import github+from products.warehouse_sources.backend.temporal.data_imports.sources.github.source import GithubSourcedef _ok_response() -> mock.Mock:@@ -215,6 +217,7 @@ def _error_response(status_code: int, message: str, headers: dict[str, str] | No# 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),+ ("Resource protected by organization SAML enforcement", github.GithubAccessDeniedError),],)def test_fetch_page_403_separates_switched_off_features_from_denials(message, expected_exc):@@ -228,6 +231,63 @@ def test_fetch_page_403_separates_switched_off_features_from_denials(message, exassert message in str(raised.value)+ "message,required_permission,expected_advice,carries_url",+ [+ # This message reaches the user as the schema's error, so a denial that omits the grant+ # leaves them with a disabled table and no stated way to re-enable it. The user reads it,+ # so the API URL stays in the log line instead.+ ("Resource not accessible by integration", "deployments", "Deployments: read", False),+ # An endpoint with no mapped grant still has to end in an action.+ ("Resource not accessible by integration", None, "Add the missing permission", False),+ # An organization-level denial is not about this table's grant, and naming one would send+ # the user to the wrong setting. Curated copy replaces this one, so it keeps the URL.+ ("Resource protected by organization SAML enforcement", "deployments", "GitHub denied access", True),+ ],+)+def test_fetch_page_denial_states_the_action_that_fits_the_denial(+ message, required_permission, expected_advice, carries_url+):+ 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(github.GithubAccessDeniedError) as raised:+ github._fetch_page(+ "https://api.github.com/repos/o/r/deployments",+ {},+ mock.Mock(),+ repository="o/r",+ required_permission=required_permission,+ )++ assert expected_advice in str(raised.value)+ assert ("api.github.com" in str(raised.value)) is carries_url+++ "message",+ [+ "Resource not accessible by integration",+ # Per-endpoint wording no enumerated error key can match; only the message prefix does.+ "Must have push access to view repository collaborators",+ ],+)+def test_denials_raised_by_fetch_page_are_classified_non_retryable(message):+ # The raised message and GithubSource.get_non_retryable_errors are two halves of one contract:+ # a denial that matches no key there keeps retrying and never disables the schema. Drive the+ # real raised message through the real key set, so rewording either side alone fails here.+ 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(github.GithubAccessDeniedError) as raised:+ github._fetch_page("https://api.github.com/repos/o/r/collaborators", {}, mock.Mock(), repository="o/r")++ errors = GithubSource().get_non_retryable_errors()+ assert any(error_message_matches(str(raised.value), [key]) for key in errors)++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.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 d24ac33457b6..c4f4ca76dea3 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@@ -15,7 +15,12 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.github.namresolve_schema_repo_endpoint,split_schema_name,)-from products.warehouse_sources.backend.temporal.data_imports.sources.github.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.github.settings import (+ ENDPOINT_REQUIRED_PERMISSION,+ ENDPOINTS,+ GITHUB_ENDPOINTS,+ GRANT_NAMES,+)from products.warehouse_sources.backend.temporal.data_imports.sources.github.source import GithubSourcefrom products.warehouse_sources.backend.types import ExternalDataSourceType@@ -119,16 +124,27 @@ class TestGithubSource:"raised_message,expected_key",[(- "GitHub denied access: Resource not accessible by integration (url=https://api.github.com/repos/o/r/issues)",+ 'GitHub can\'t read this table: Resource not accessible by integration. Grant "Deployments: read" on a fine-grained token or app installation, or repo_deployment on a classic token, then sync again.',"Resource not accessible by integration",),+ # GitHub phrases some denials per endpoint, so no enumerated key can match them; the+ # message prefix has to, or the job retries the denial forever instead of disabling+ # the schema.+ (+ "GitHub can't read this table: Must have push access to view repository collaborators. Add the missing permission to your GitHub connection, or connect with a personal access token from an account that has the access GitHub names, then sync again.",+ "GitHub can't read this table",+ ),("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 can't read this table: Must have admin rights to Repository.",+ "Must have admin rights",+ ),+ (+ "GitHub can't read this table: Must have push access to repository.",+ "Must have push access to repository",),("GitHub repository is not accessible: owner/repo", "GitHub repository is not accessible"),],@@ -140,6 +156,28 @@ class TestGithubSource:matched = next(key for key in errors if error_message_matches(raised_message, [key]))assert matched == expected_key+ @pytest.mark.parametrize(+ "key",+ [+ "Resource not accessible by integration",+ "Resource not accessible by personal access token",+ "GitHub can't read this table",+ ],+ )+ def test_grant_denials_keep_the_message_that_names_the_grant(self, key):+ # latest_error is the only error field the schema serializer exposes, and the job overwrites+ # it with the curated copy whenever that copy is not None. Curated copy here would replace+ # the one sentence that names the grant to add with a vaguer one, which is the whole point+ # of naming it.+ assert self.source.get_non_retryable_errors()[key] is None++ def test_required_permissions_reference_real_endpoints_and_grants(self):+ # ENDPOINT_REQUIRED_PERMISSION sits ~700 lines from the endpoint definitions it keys on, so+ # a typo or a renamed endpoint would silently drop the grant from the failure message and+ # from the picker, with nothing else failing.+ assert set(ENDPOINT_REQUIRED_PERMISSION) <= set(GITHUB_ENDPOINTS)+ assert set(ENDPOINT_REQUIRED_PERMISSION.values()) <= set(GRANT_NAMES)+def test_suspended_installation_token_refresh_is_non_retryable(self):# The raw GitHubIntegrationError raised by refresh_access_token on a suspended installation.error_message = (@@ -192,6 +230,70 @@ class TestGithubSource:assert result["teams"] == "No GitHub account is connected. Please reconnect your GitHub account."assert result["team_members"] == result["teams"]+ @pytest.mark.parametrize(+ "endpoint,is_blocked",+ [+ # An installation can only hold permissions the App requests, so a table whose grant is+ # absent from the held set can never sync on this connection. Offering it just defers+ # the failure to the first sync.+ ("traffic_views", True),+ ("runners", True),+ ("deployments", True),+ ("code_scanning_alerts", True),+ # The org tables short-circuit on the held set too, with their existing org reason.+ ("teams", True),+ ("issues", False),+ # No required grant beyond the baseline every connection is validated for.+ ("tags", False),+ ],+ )+ def test_tables_the_installation_cannot_read_are_marked_unavailable(self, endpoint, is_blocked):+ config = GithubSourceConfig(+ auth_method=GithubAuthMethodConfig(github_integration_id=7, selection="oauth", personal_access_token=""),+ repository="acme/widgets",+ )+ integration = mock.Mock()+ integration.config = {"permissions": {"metadata": "read", "contents": "read", "issues": "read"}}++ with mock.patch.object(self.source, "get_oauth_integration", return_value=integration):+ result = self.source.get_endpoint_permissions(config, self.team_id, [endpoint])++ reason = result[endpoint]+ if is_blocked:+ assert reason is not None+ assert "personal access token" in reason+ else:+ assert reason is None++ def test_pat_connections_are_not_blocked_by_permission_data(self):+ # Token grants aren't introspectable, so a token connection must fail open here: a denial+ # surfaces at sync time instead, where the error names the grant.+ config = GithubSourceConfig(+ auth_method=GithubAuthMethodConfig(github_integration_id=None, selection="pat", personal_access_token="t"),+ repository="acme/widgets",+ )++ result = self.source.get_endpoint_permissions(config, self.team_id, ["traffic_views", "deployments"])++ assert result == {"traffic_views": None, "deployments": None}++ def test_unknown_permissions_fail_open(self):+ # Rows connected before permissions were persisted have no stored set until the hourly+ # token-refresh sweep backfills it. Blocking every gated table on missing data would hide+ # tables the installation can actually read, so the picker shows them and sync-time errors+ # carry the grant.+ config = GithubSourceConfig(+ auth_method=GithubAuthMethodConfig(github_integration_id=7, selection="oauth", personal_access_token=""),+ repository="acme/widgets",+ )+ integration = mock.Mock()+ integration.config = {}++ with mock.patch.object(self.source, "get_oauth_integration", return_value=integration):+ result = self.source.get_endpoint_permissions(config, self.team_id, ["deployments"])++ assert result == {"deployments": None}+@pytest.mark.parametrize("endpoint", ["teams", "team_members"])def test_org_schemas_are_full_refresh_only_and_off_by_default(self, endpoint):# teams / team_members expose no timestamps, so they must never advertise incremental,