: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(signals): surface GitHub checks permission errors (#99707)
Mikayla Thompsona50ffc21155a
diff --git a/posthog/models/github_integration_base.py b/posthog/models/github_integration_base.pyindex 44493acfc35d..01cb7729e862 100644--- a/posthog/models/github_integration_base.py+++ b/posthog/models/github_integration_base.py@@ -1278,6 +1278,15 @@ class GitHubIntegrationBase:head_sha = pr.get("head_sha")if not head_sha:return {"success": False, "error": "Pull request has no head commit"}++ permissions = self.integration.config.get("permissions")+ if isinstance(permissions, dict) and permissions and permissions.get("checks") not in {"read", "write"}:+ return {+ "success": False,+ "error": "GitHub App is missing permission to read check runs",+ "error_code": "github_checks_permission_missing",+ }+repo_path = repository if "/" in repository else f"{self.organization()}/{repository}"checks: list[dict[str, Any]] = []diff --git a/posthog/models/test/integration/test_github.py b/posthog/models/test/integration/test_github.pyindex 24ddd6f3ab7e..4399734b9bcf 100644--- a/posthog/models/test/integration/test_github.py+++ b/posthog/models/test/integration/test_github.py@@ -76,6 +76,21 @@ class TestExtractFailingChecks(SimpleTestCase):assert (failing == [{"key": "CI/unit tests", "details_url": "https://ci/1"}]) is expected_reported+class TestGitHubPullRequestChecks(SimpleTestCase):+ def test_reports_missing_checks_permission(self):+ integration = MagicMock(kind="github", config={"permissions": {"contents": "read"}})+ github = GitHubIntegration(integration)++ with patch.object(github, "get_pull_request", return_value={"success": True, "head_sha": "abc123f"}):+ result = github.get_pull_request_checks("example/legacy", 7)++ assert result == {+ "success": False,+ "error": "GitHub App is missing permission to read check runs",+ "error_code": "github_checks_permission_missing",+ }++class TestParseRepoItemUrl(SimpleTestCase):@parameterized.expand([diff --git a/products/signals/backend/serializers.py b/products/signals/backend/serializers.pyindex c8c257733d52..bd1ed0d33724 100644--- a/products/signals/backend/serializers.py+++ b/products/signals/backend/serializers.py@@ -2061,6 +2061,17 @@ class PullRequestChecksResponseSerializer(serializers.Serializer):checks = PullRequestCheckSerializer(many=True, read_only=True)+class PullRequestChecksPermissionErrorSerializer(serializers.Serializer):+ """Response when the GitHub App cannot read pull request checks."""++ code = serializers.CharField(read_only=True, help_text="Stable code for a missing GitHub Checks permission.")+ error = serializers.CharField(read_only=True, help_text="What the GitHub App permission prevents.")+ remediation_url = serializers.CharField(+ read_only=True,+ help_text="Project integrations settings where a project admin can reconnect GitHub.",+ )++class PullRequestCiStatus(TextChoices):"""Coarse rollup of a pull request's checks, as mapped from GitHub's status check rollup."""diff --git a/products/signals/backend/test/test_signal_report_api.py b/products/signals/backend/test/test_signal_report_api.pyindex 56f3597b508f..d0bb7a5ccce7 100644--- a/products/signals/backend/test/test_signal_report_api.py+++ b/products/signals/backend/test/test_signal_report_api.py@@ -3561,6 +3561,35 @@ class TestSignalReportPrEndpoints(APIBaseTest):assert response.status_code == status.HTTP_502_BAD_GATEWAY+ def test_pr_checks_missing_permission_returns_remediation_for_selected_legacy_task_output(self):+ report = self._create_report()+ SignalReportAssignment.objects.for_team(self.team.id).filter(report=report).delete()+ Task = apps.get_model("tasks", "Task")+ TaskRun = apps.get_model("tasks", "TaskRun")+ task = Task.objects.create(team=self.team, title="Implementation", description="Fix a bug")+ TaskRun.objects.create(team=self.team, task=task, output={"pr_url": "https://github.com/example/legacy/pull/7"})+ SignalReportTask.objects.create(team=self.team, report=report, task=task, relationship="implementation")+ selected_pr_id = str(uuid.uuid5(uuid.NAMESPACE_URL, f"signals:{self.team.id}:example/legacy:7"))+ github = patch("products.signals.backend.views.GitHubIntegration.first_for_team_repository").start()+ self.addCleanup(patch.stopall)+ github.return_value.get_pull_request_checks.return_value = {+ "success": False,+ "error_code": "github_checks_permission_missing",+ }++ response = self.client.get(f"{self._checks_url(str(report.id))}?pull_request_id={selected_pr_id}")++ assert response.status_code == status.HTTP_403_FORBIDDEN+ assert response.json() == {+ "code": "github_checks_permission_missing",+ "error": (+ "GitHub can't read pull request checks. A project admin must reconnect GitHub and grant the Checks "+ "permission."+ ),+ "remediation_url": f"/project/{self.team.id}/settings/project-integrations",+ }+ github.return_value.get_pull_request_checks.assert_called_once_with("example/legacy", 7)+def test_pr_comments_success_returns_comments(self):report = self._create_report()github = patch("products.signals.backend.views.GitHubIntegration.first_for_team_repository").start()diff --git a/products/signals/backend/views.py b/products/signals/backend/views.pyindex 0f44bab22e3a..09626c039eb3 100644--- a/products/signals/backend/views.py+++ b/products/signals/backend/views.py@@ -151,6 +151,7 @@ from products.signals.backend.reviewer_correction_notes import ReviewerCorrectiofrom products.signals.backend.reviewer_pr_assignment import schedule_reviewer_pr_assignmentfrom products.signals.backend.serializers import (CommitDiffResponseSerializer,+ PullRequestChecksPermissionErrorSerializer,PullRequestChecksResponseSerializer,PullRequestCiStatusesResponseSerializer,PullRequestCommentsResponseSerializer,@@ -3139,6 +3140,10 @@ class SignalReportViewSet(404: OpenApiResponse(description="Report has no implementation PR, or no GitHub integration can access it."),+ 403: OpenApiResponse(+ response=PullRequestChecksPermissionErrorSerializer,+ description="GitHub is connected without permission to read pull request checks.",+ ),502: OpenApiResponse(description="GitHub could not return the checks."),503: OpenApiResponse(description="The GitHub egress budget is temporarily unavailable."),},@@ -3738,6 +3743,26 @@ class SignalReportViewSet({"error": f"GitHub could not return the {noun} for this pull request."},status=status.HTTP_502_BAD_GATEWAY,)+ if result.get("error_code") == "github_checks_permission_missing":+ logger.info(+ "signals pr checks missing GitHub Checks permission",+ team_id=self.team.id,+ repository=repository,+ pr_number=pr_number,+ )+ return Response(+ PullRequestChecksPermissionErrorSerializer(+ {+ "code": "github_checks_permission_missing",+ "error": (+ "GitHub can't read pull request checks. A project admin must reconnect GitHub and grant "+ "the Checks permission."+ ),+ "remediation_url": f"/project/{self.team.id}/settings/project-integrations",+ }+ ).data,+ status=status.HTTP_403_FORBIDDEN,+ )if not result.get("success"):return Response({"error": result.get("error") or f"GitHub could not return the {noun} for this pull request."},diff --git a/products/signals/frontend/generated/api.schemas.ts b/products/signals/frontend/generated/api.schemas.tsindex e316eefc9dca..f0072a433da6 100644--- a/products/signals/frontend/generated/api.schemas.ts+++ b/products/signals/frontend/generated/api.schemas.ts@@ -809,6 +809,18 @@ export interface PullRequestChecksResponseApi {readonly checks: readonly PullRequestCheckApi[]}+/**+ * Response when the GitHub App cannot read pull request checks.+ */+export interface PullRequestChecksPermissionErrorApi {+ /** Stable code for a missing GitHub Checks permission. */+ readonly code: string+ /** What the GitHub App permission prevents. */+ readonly error: string+ /** Project integrations settings where a project admin can reconnect GitHub. */+ readonly remediation_url: string+}+/*** * `conversation` - conversation* * `review` - reviewdiff --git a/products/signals/frontend/inbox/components/detail/PrChecksSection.tsx b/products/signals/frontend/inbox/components/detail/PrChecksSection.tsxindex f03fdb3dc540..1d5ec5453754 100644--- a/products/signals/frontend/inbox/components/detail/PrChecksSection.tsx+++ b/products/signals/frontend/inbox/components/detail/PrChecksSection.tsx@@ -159,7 +159,12 @@ export function PrChecksSection({ report }: { report: SignalReport }): JSX.Eleme>{prChecksError ? (<div className="rounded border border-danger bg-danger-highlight px-3 py-2.5 text-sm text-danger">- {prChecksError}+ <span>{prChecksError.message}</span>+ {prChecksError.remediationUrl ? (+ <Link to={prChecksError.remediationUrl} className="ml-2">+ Open GitHub integration settings+ </Link>+ ) : null}</div>) : prChecks === null ? (<div className="overflow-hidden rounded border border-primary bg-surface-primary">diff --git a/products/signals/frontend/inbox/logics/inboxReportDetailLogic.test.ts b/products/signals/frontend/inbox/logics/inboxReportDetailLogic.test.tsindex 7636230f3eb8..8d1c7b7a921a 100644--- a/products/signals/frontend/inbox/logics/inboxReportDetailLogic.test.ts+++ b/products/signals/frontend/inbox/logics/inboxReportDetailLogic.test.ts@@ -214,7 +214,14 @@ describe('inboxReportDetailLogic', () => {'/api/projects/:team_id/signals/reports/:id/pr_checks/': ({ request }) => {requestedPrIds.push(new URL(request.url).searchParams.get('pull_request_id'))prChecksRequests += 1- return [502, { error: 'GitHub could not return the checks for this pull request.' }]+ return [+ 403,+ {+ code: 'github_checks_permission_missing',+ error: "GitHub can't read pull request checks. A project admin must reconnect GitHub and grant the Checks permission.",+ remediation_url: '/project/2/settings/project-integrations',+ },+ ]},'/api/projects/:team_id/signals/reports/:id/pr_comments/': { comments: [] },},@@ -266,6 +273,16 @@ describe('inboxReportDetailLogic', () => {expect(logic.values.prChecksBackedOff).toBe(true)expect(logic.values.prChecksError).toBeTruthy()})++ it('shows how to restore the GitHub permission', async () => {+ await expectLogic(logic).toFinishAllListeners()++ expect(logic.values.prChecksError).toEqual({+ message:+ "GitHub can't read pull request checks. A project admin must reconnect GitHub and grant the Checks permission.",+ remediationUrl: '/project/2/settings/project-integrations',+ })+ })})describe('PR response races', () => {diff --git a/products/signals/frontend/inbox/logics/inboxReportDetailLogic.ts b/products/signals/frontend/inbox/logics/inboxReportDetailLogic.tsindex 16b97724099e..7f9d49314b63 100644--- a/products/signals/frontend/inbox/logics/inboxReportDetailLogic.ts+++ b/products/signals/frontend/inbox/logics/inboxReportDetailLogic.ts@@ -17,6 +17,7 @@ import { loaders } from 'kea-loaders'import { lemonToast } from '@posthog/lemon-ui'import api from 'lib/api'+import { ApiError } from 'lib/api-error'import { SignalNode } from 'scenes/debug/signals/types'import { personalIntegrationsLogic } from 'scenes/settings/user/personalIntegrationsLogic'import type { PersonalGitHubIntegration } from 'scenes/settings/user/personalIntegrationsLogic'@@ -79,6 +80,24 @@ const TERMINAL_RUN_STATUSES: TaskRunStatus[] = [TaskRunStatus.COMPLETED, TaskRun/** Why the report's one implementation slot is still claimed. Mirrors the server's `_ImplementationSlotClaim`. */export type ImplementationSlotClaim = 'in_flight' | 'shipped_pr'+export type PrChecksError = {+ message: string+ remediationUrl: string | null+}++const GITHUB_CHECKS_PERMISSION_MISSING_CODE = 'github_checks_permission_missing'++function prChecksErrorFrom(error: unknown): PrChecksError {+ if (error instanceof ApiError && error.code === GITHUB_CHECKS_PERMISSION_MISSING_CODE) {+ const remediationUrl = (error.data as { remediation_url?: unknown } | null)?.remediation_url+ return {+ message: error.message,+ remediationUrl: typeof remediationUrl === 'string' ? remediationUrl : null,+ }+ }+ return { message: "Couldn't load the PR checks from GitHub.", remediationUrl: null }+}+// The task↔report association is the `task_run` artefact log now (the legacy `/tasks/` endpoint is// gone), and the activity timeline renders the whole log. Pull a generous page so early entries// (the first task runs, repo selection) stay visible on reports with many findings — matching the@@ -291,7 +310,7 @@ export interface inboxReportDetailLogicValues {prChecks: readonly PullRequestCheckApi[] | nullprChecksBackedOff: booleanprChecksConsecutiveFailures: number- prChecksError: string | null+ prChecksError: PrChecksError | nullprChecksLoading: booleanprComments: readonly PullRequestCommentApi[] | nullprCommentsError: string | null@@ -945,10 +964,10 @@ export const inboxReportDetailLogic = kea<inboxReportDetailLogicType>([// Cleared only on success (not on load start), so the section keeps showing the error while// a backed-off retry is in flight instead of flashing back to the loading skeleton.prChecksError: [- null as string | null,+ null as PrChecksError | null,{loadPrChecksSuccess: () => null,- loadPrChecksFailure: () => "Couldn't load the PR checks from GitHub.",+ loadPrChecksFailure: (_, { errorObject }) => prChecksErrorFrom(errorObject),},],// Consecutive failed checks fetches — feeds `prChecksBackedOff`.diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex ffaf0b65645e..7384ae5180fa 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -74919,6 +74919,18 @@ export namespace Schemas {readonly url: string | null;}+ /**+ * Response when the GitHub App cannot read pull request checks.+ */+ export interface PullRequestChecksPermissionError {+ /** Stable code for a missing GitHub Checks permission. */+ readonly code: string;+ /** What the GitHub App permission prevents. */+ readonly error: string;+ /** Project integrations settings where a project admin can reconnect GitHub. */+ readonly remediation_url: string;+ }+/*** Response for the PR checks endpoint — the CI status of a report's implementation PR.*/