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(visual_review): allow CI runner to provide github_check_run_id (#61391)

Julian Bez53fd218e847c
diff --git a/products/visual_review/backend/facade/api.py b/products/visual_review/backend/facade/api.py
index 1d0f8a348045..8cd91511a756 100644
--- a/products/visual_review/backend/facade/api.py
+++ b/products/visual_review/backend/facade/api.py
@@ -28,20 +28,33 @@ User = get_user_model()
# Server-owned run.metadata keys — never accept these from client input.
# Allowing clients to set these would let them target arbitrary GitHub
# comments for PATCH, or spoof baseline commit SHAs in the audit trail.
+# These are all written by the server itself, never by the CI runner.
+# `github_check_run_id` is deliberately NOT reserved: the CI runner is its
+# only source (from `JOB_CHECK_RUN_ID=${{ job.check_run_id }}`), and the
+# rerun it enables is fenced by `_rerun_github_job` — the job must run on the
+# run's commit and belong to the recorded workflow run (`github_run_id`).
_RESERVED_RUN_METADATA_KEYS = frozenset(
{
"github_comment_id",
"baseline_commit_sha",
"baseline_healed_from_merge_base",
- "github_check_run_id",
}
)
+# GitHub identifiers arrive as JSON, so a client can send them as numbers.
+# Store them as strings so rerun logic (which calls `.isdigit()`) and
+# workflow-run comparisons stay type-stable.
+_STRING_RUN_METADATA_KEYS = frozenset({"github_check_run_id", "github_run_id"})
+
def _sanitize_run_metadata(metadata: dict | None) -> dict:
if not metadata:
return {}
- return {k: v for k, v in metadata.items() if k not in _RESERVED_RUN_METADATA_KEYS}
+ cleaned = {k: v for k, v in metadata.items() if k not in _RESERVED_RUN_METADATA_KEYS}
+ for key in _STRING_RUN_METADATA_KEYS:
+ if cleaned.get(key) is not None:
+ cleaned[key] = str(cleaned[key])
+ return cleaned
# Re-export exceptions for callers
diff --git a/products/visual_review/backend/logic.py b/products/visual_review/backend/logic.py
index 8710505ad248..7829479fed4b 100644
--- a/products/visual_review/backend/logic.py
+++ b/products/visual_review/backend/logic.py
@@ -1172,7 +1172,8 @@ def recompute_run(run_id: UUID, team_id: int | None = None) -> dict:
if not check_run_id:
ci_rerun_error = "CI job ID not available (set JOB_CHECK_RUN_ID=${{ job.check_run_id }} in workflow)"
else:
- ci_rerun_triggered, ci_rerun_error = _rerun_github_job(run, check_run_id)
+ # Stored as a string, but coerce defensively — `_rerun_github_job` calls `.isdigit()`.
+ ci_rerun_triggered, ci_rerun_error = _rerun_github_job(run, str(check_run_id))
return {
"counts_changed": counts_changed,
@@ -1183,7 +1184,17 @@ def recompute_run(run_id: UUID, team_id: int | None = None) -> dict:
def _rerun_github_job(run: Run, check_run_id: str) -> tuple[bool, str | None]:
- """Rerun a specific GitHub Actions job by its numeric ID. Returns (success, error_message)."""
+ """Rerun the visual-review CI job by its numeric ID. Returns (success, error_message).
+
+ The job ID and workflow run ID both come from client-supplied run metadata
+ (the CI runner has no server-verified channel today), so before calling
+ GitHub we bind the rerun two ways: the job must run on this run's commit
+ (``head_sha``) and must belong to the workflow run recorded at creation
+ (``github_run_id``). That pins recompute to the workflow run that produced
+ this visual-review run instead of letting it re-trigger any job on the
+ commit. It is defense-in-depth, not an identity proof — a caller who forges
+ a self-consistent metadata set can still reach sibling jobs of that run.
+ """
if not check_run_id.isdigit():
return False, "Invalid check run ID"
@@ -1191,34 +1202,50 @@ def _rerun_github_job(run: Run, check_run_id: str) -> tuple[bool, str | None]:
if not repo.repo_full_name:
return False, "Repo has no GitHub full name configured"
+ expected_run_id = (run.metadata or {}).get("github_run_id")
+ if not expected_run_id:
+ return False, "Workflow run ID not recorded for this run"
+
+ # `${{ job.check_run_id }}` doubles as the Actions job ID, so the jobs API
+ # gives us head_sha and the owning workflow run (run_id) in one call.
try:
- check_run_response = _github_api_request(
+ job_response = _github_api_request(
"GET",
repo,
- f"check-runs/{check_run_id}",
+ f"actions/jobs/{check_run_id}",
timeout=10,
)
except Exception:
- return False, "Failed to verify check run ownership"
+ return False, "Failed to verify CI job ownership"
- if check_run_response.status_code != 200:
- return False, f"Could not fetch check run details (status {check_run_response.status_code})"
+ if job_response.status_code != 200:
+ return False, f"Could not fetch CI job details (status {job_response.status_code})"
try:
- check_run_data = check_run_response.json()
+ job_data = job_response.json()
except Exception:
- return False, "Failed to parse check run response"
+ return False, "Failed to parse CI job response"
- if check_run_data.get("head_sha") != run.commit_sha:
+ if job_data.get("head_sha") != run.commit_sha:
logger.warning(
"visual_review.ci_rerun_sha_mismatch",
run_id=str(run.id),
check_run_id=check_run_id,
expected_sha=run.commit_sha,
- actual_sha=check_run_data.get("head_sha"),
+ actual_sha=job_data.get("head_sha"),
)
return False, "Check run does not belong to this commit"
+ if str(job_data.get("run_id")) != str(expected_run_id):
+ logger.warning(
+ "visual_review.ci_rerun_workflow_mismatch",
+ run_id=str(run.id),
+ check_run_id=check_run_id,
+ expected_workflow_run=str(expected_run_id),
+ actual_workflow_run=str(job_data.get("run_id")),
+ )
+ return False, "CI job does not belong to this run's workflow"
+
try:
response = _github_api_request(
"POST",
diff --git a/products/visual_review/backend/tests/test_api.py b/products/visual_review/backend/tests/test_api.py
index bffbb4efae5a..39aade832d17 100644
--- a/products/visual_review/backend/tests/test_api.py
+++ b/products/visual_review/backend/tests/test_api.py
@@ -109,7 +109,9 @@ class TestRunAPI:
def test_create_run_strips_reserved_metadata_keys(self, mock_presigned, repo):
# Clients must not be able to seed server-owned metadata keys —
# otherwise they could target arbitrary GitHub comments for PATCH
- # or spoof baseline commit SHAs in the audit trail.
+ # or spoof baseline commit SHAs in the audit trail. github_check_run_id
+ # is NOT reserved: the CI runner is its only source, and the rerun it
+ # enables is guarded by a head_sha match in _rerun_github_job.
mock_presigned.return_value = {"url": "https://s3.example.com/upload", "fields": {}}
result = api.create_run(
@@ -131,7 +133,28 @@ class TestRunAPI:
)
run = Run.objects.get(id=result.run_id)
- assert run.metadata == {"pr_title": "kept"}
+ assert run.metadata == {"pr_title": "kept", "github_check_run_id": "72855643533"}
+
+ @patch("products.visual_review.backend.storage.ArtifactStorage.get_presigned_upload_url")
+ def test_create_run_normalizes_github_ids_to_strings(self, mock_presigned, repo):
+ # GitHub IDs can arrive as JSON numbers; rerun logic calls .isdigit(),
+ # so they must be stored as strings.
+ mock_presigned.return_value = {"url": "https://s3.example.com/upload", "fields": {}}
+
+ result = api.create_run(
+ CreateRunInput(
+ repo_id=repo.id,
+ run_type=RunType.STORYBOOK,
+ commit_sha="abc123",
+ branch="main",
+ snapshots=[],
+ metadata={"github_check_run_id": 72855643533, "github_run_id": 98765},
+ ),
+ team_id=repo.team_id,
+ )
+
+ run = Run.objects.get(id=result.run_id)
+ assert run.metadata == {"github_check_run_id": "72855643533", "github_run_id": "98765"}
def test_get_run_returns_dto(self, repo):
create_result = api.create_run(
diff --git a/products/visual_review/backend/tests/test_logic.py b/products/visual_review/backend/tests/test_logic.py
index fd13e60844da..218a3a220460 100644
--- a/products/visual_review/backend/tests/test_logic.py
+++ b/products/visual_review/backend/tests/test_logic.py
@@ -1673,7 +1673,10 @@ class TestRerunGithubJob:
def repo(self, team):
return logic.create_repo(team_id=team.id, repo_external_id=55555, repo_full_name="org/test-repo")
- def _make_run(self, repo: "Repo", commit_sha: str = "abc123def456") -> "Run":
+ def _make_run(self, repo: "Repo", commit_sha: str = "abc123def456", workflow_run_id: str | None = "98765") -> "Run":
+ metadata: dict = {"github_check_run_id": "72855643533"}
+ if workflow_run_id is not None:
+ metadata["github_run_id"] = workflow_run_id
run, _ = logic.create_run(
repo_id=repo.id,
team_id=repo.team_id,
@@ -1682,7 +1685,7 @@ class TestRerunGithubJob:
branch="feature",
pr_number=1,
snapshots=[],
- metadata={"github_check_run_id": "72855643533"},
+ metadata=metadata,
)
return run
@@ -1692,11 +1695,17 @@ class TestRerunGithubJob:
assert success is False
assert error == "Invalid check run ID"
+ def test_rejects_when_workflow_run_id_missing(self, repo):
+ run = self._make_run(repo, workflow_run_id=None)
+ success, error = logic._rerun_github_job(run, "72855643533")
+ assert success is False
+ assert error == "Workflow run ID not recorded for this run"
+
def test_rejects_when_sha_does_not_match(self, repo, mocker):
run = self._make_run(repo, commit_sha="abc123")
mock_response = mocker.MagicMock()
mock_response.status_code = 200
- mock_response.json.return_value = {"head_sha": "different_sha_entirely"}
+ mock_response.json.return_value = {"head_sha": "different_sha_entirely", "run_id": 98765}
mocker.patch("products.visual_review.backend.logic._github_api_request", return_value=mock_response)
success, error = logic._rerun_github_job(run, "72855643533")
@@ -1704,6 +1713,19 @@ class TestRerunGithubJob:
assert success is False
assert error == "Check run does not belong to this commit"
+ def test_rejects_when_workflow_run_does_not_match(self, repo, mocker):
+ commit_sha = "abc123def456"
+ run = self._make_run(repo, commit_sha=commit_sha, workflow_run_id="98765")
+ mock_response = mocker.MagicMock()
+ mock_response.status_code = 200
+ mock_response.json.return_value = {"head_sha": commit_sha, "run_id": 11111}
+ mocker.patch("products.visual_review.backend.logic._github_api_request", return_value=mock_response)
+
+ success, error = logic._rerun_github_job(run, "72855643533")
+
+ assert success is False
+ assert error == "CI job does not belong to this run's workflow"
+
def test_rejects_when_check_run_fetch_fails(self, repo, mocker):
run = self._make_run(repo)
mock_response = mocker.MagicMock()
@@ -1716,20 +1738,20 @@ class TestRerunGithubJob:
assert error is not None
assert "404" in error
- def test_triggers_rerun_when_sha_matches(self, repo, mocker):
+ def test_triggers_rerun_when_sha_and_workflow_match(self, repo, mocker):
commit_sha = "abc123def456"
- run = self._make_run(repo, commit_sha=commit_sha)
+ run = self._make_run(repo, commit_sha=commit_sha, workflow_run_id="98765")
- check_run_response = mocker.MagicMock()
- check_run_response.status_code = 200
- check_run_response.json.return_value = {"head_sha": commit_sha}
+ job_response = mocker.MagicMock()
+ job_response.status_code = 200
+ job_response.json.return_value = {"head_sha": commit_sha, "run_id": 98765}
rerun_response = mocker.MagicMock()
rerun_response.status_code = 201
mocker.patch(
"products.visual_review.backend.logic._github_api_request",
- side_effect=[check_run_response, rerun_response],
+ side_effect=[job_response, rerun_response],
)
success, error = logic._rerun_github_job(run, "72855643533")
diff --git a/products/visual_review/frontend/scenes/VisualReviewRunScene.tsx b/products/visual_review/frontend/scenes/VisualReviewRunScene.tsx
index 67c184f334cd..91caada43935 100644
--- a/products/visual_review/frontend/scenes/VisualReviewRunScene.tsx
+++ b/products/visual_review/frontend/scenes/VisualReviewRunScene.tsx
@@ -324,12 +324,14 @@ export function VisualReviewRunScene(): JSX.Element {
const hasMore = diffChanged + diffNew + diffRemoved > reviewPending + reviewApproved + reviewTolerated
- // Re-trigger calls the GitHub API `/actions/jobs/{job_id}/rerun`; we only have that ID
- // when the workflow wired `JOB_CHECK_RUN_ID=${{ job.check_run_id }}` into the CLI env.
- // Older runs and runs from forks without that env var can't be re-triggered.
- const ciRetriggerUnavailableReason = !run.metadata?.github_check_run_id
- ? "This run wasn't recorded with a CI job ID, so it can't be re-triggered. Push a new commit to re-run CI."
- : undefined
+ // Re-trigger calls the GitHub API `/actions/jobs/{job_id}/rerun`; the backend needs both the
+ // job ID and the workflow run ID (it binds the rerun to the originating run), wired in via
+ // `JOB_CHECK_RUN_ID` and `GITHUB_RUN_ID`. Older runs and forks without those env vars can't
+ // be re-triggered — don't offer the banner when the rerun would just error.
+ const ciRetriggerUnavailableReason =
+ !run.metadata?.github_check_run_id || !run.metadata?.github_run_id
+ ? "This run wasn't recorded with a CI job ID, so it can't be re-triggered. Push a new commit to re-run CI."
+ : undefined
const handleApproveSnapshot = (): void => {
if (selectedSnapshot) {