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(tasks): verify denied clones with GitHub before failing the run (#123981)

Alessandro Pogliaghi70105014c01b
diff --git a/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py b/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py
index 929434d1dffa..1f7d221e64a5 100644
--- a/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py
+++ b/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py
@@ -18,6 +18,7 @@ from temporalio import activity
from posthog.dataclasses import frozen
from posthog.egress.github.transport import GitHubEgressBudgetExhausted, GitHubRateLimitError
from posthog.models.github_integration_base import GitHubIntegrationError
+from posthog.models.integration import GitHubIntegration
from posthog.models.user_integration import ReauthorizationRequired
from posthog.temporal.common.utils import asyncify
@@ -92,11 +93,16 @@ from products.tasks.backend.temporal.process_task.activities.get_pr_context impo
from products.tasks.backend.temporal.process_task.organization import check_organization_execution
from products.tasks.backend.temporal.process_task.sandbox_connection import persist_sandbox_connection
from products.tasks.backend.temporal.process_task.sandbox_credentials import (
+ apply_github_credentials_to_sandbox,
replace_sandbox_credentials,
+ sandbox_credential_lock,
set_git_remote_token,
)
from products.tasks.backend.temporal.process_task.utils import (
+ PrAuthorshipMode,
+ forget_cached_github_tokens,
get_git_identity_env_vars,
+ get_pr_authorship_mode,
get_readonly_github_token,
get_sandbox_api_url,
get_sandbox_github_token,
@@ -104,8 +110,11 @@ from products.tasks.backend.temporal.process_task.utils import (
get_sandbox_otel_env_vars,
get_sandbox_snapshot_metadata,
get_task_run_credential_user,
+ installation_confirms_repository_denied,
mcp_exec_skills_env_vars,
parse_run_state,
+ resolve_installation_github_integration,
+ resolve_readonly_github_integration,
run_gateway_env_vars,
)
@@ -1172,6 +1181,20 @@ def clone_repository_in_sandbox(input: CloneRepositoryInSandboxInput) -> CloneRe
):
log_with_activity_context(f"Cloning {input.repository} into sandbox", run_id=ctx.run_id)
sandbox = get_sandbox_class_for_sandbox_id(input.sandbox_id).get_by_id(input.sandbox_id)
+ github_token = input.github_token
+ if github_token and activity.info().attempt > 1:
+ github_token = _reresolve_sandbox_github_token(ctx, input.repository)
+ if not github_token:
+ raise RepositoryCloneError(
+ f"Could not refresh the GitHub token before retrying the clone of {input.repository}",
+ {
+ "repository": input.repository,
+ "sandbox_id": input.sandbox_id,
+ "attempt": activity.info().attempt,
+ },
+ cause=RuntimeError("GitHub token refresh returned no token"),
+ next_retry_delay=_clone_retry_delay(activity.info().attempt),
+ )
state = parse_run_state(ctx.state)
is_resume = bool(state.resume_from_run_id or state.same_run_resume)
@@ -1184,7 +1207,7 @@ def clone_repository_in_sandbox(input: CloneRepositoryInSandboxInput) -> CloneRe
) as clone_timer:
clone_result = sandbox.clone_repository(
input.repository,
- github_token=input.github_token,
+ github_token=github_token,
shallow=input.shallow_clone,
branch=ctx.branch if is_resume else None,
blobless=blobless_clone,
@@ -1198,23 +1221,21 @@ def clone_repository_in_sandbox(input: CloneRepositoryInSandboxInput) -> CloneRe
)
clone_result = sandbox.clone_repository(
input.repository,
- github_token=input.github_token,
+ github_token=github_token,
shallow=input.shallow_clone,
branch=None,
blobless=blobless_clone,
)
if clone_result.exit_code != 0:
- stderr = _redact_clone_output(clone_result.stderr, input.github_token)
- stdout = _redact_clone_output(clone_result.stdout, input.github_token)
- execution_error = (
- _redact_clone_output(clone_result.error, input.github_token) if clone_result.error else None
- )
+ stderr = _redact_clone_output(clone_result.stderr, github_token)
+ stdout = _redact_clone_output(clone_result.stdout, github_token)
+ execution_error = _redact_clone_output(clone_result.error, github_token) if clone_result.error else None
error_context = {
"repository": input.repository,
"sandbox_id": input.sandbox_id,
"exit_code": clone_result.exit_code,
- "has_github_token": bool(input.github_token),
+ "has_github_token": bool(github_token),
"stderr": stderr,
"stdout": stdout,
"error": execution_error,
@@ -1228,7 +1249,22 @@ def clone_repository_in_sandbox(input: CloneRepositoryInSandboxInput) -> CloneRe
"shallow_clone": input.shallow_clone,
},
)
+ retry_delay = _clone_retry_delay(activity.info().attempt)
if _is_repository_access_denied_clone_error(clone_result):
+ installation = _installation_behind_sandbox_token(ctx) if github_token else None
+ if installation is not None and not installation_confirms_repository_denied(
+ installation, input.repository
+ ):
+ _log_repository_clone_denied(ctx, input.repository, stderr, confirmed=False)
+ forget_cached_github_tokens(installation, ctx.repositories)
+ raise RepositoryCloneError(
+ f"Could not clone {input.repository}: GitHub denied the sandbox token although the "
+ "installation can read the repository",
+ error_context,
+ cause=RuntimeError(stderr[:200] or "GitHub denied access"),
+ next_retry_delay=retry_delay,
+ )
+ _log_repository_clone_denied(ctx, input.repository, stderr, confirmed=True)
raise RepositoryAccessError(
f"Could not clone {input.repository}: GitHub denied access. Check that the PostHog "
"GitHub app is installed on this repository's account and can read this repository.",
@@ -1236,16 +1272,25 @@ def clone_repository_in_sandbox(input: CloneRepositoryInSandboxInput) -> CloneRe
)
error_output = stderr or stdout or execution_error or "No output captured"
- attempt = activity.info().attempt
raise RepositoryCloneError(
f"Could not clone {input.repository} (git exited with code {clone_result.exit_code})",
error_context,
cause=RuntimeError(error_output[:200]),
- next_retry_delay=(
- timedelta(seconds=REPOSITORY_CLONE_RETRY_DELAYS_SECONDS[attempt - 1])
- if attempt <= len(REPOSITORY_CLONE_RETRY_DELAYS_SECONDS)
- else None
- ),
+ next_retry_delay=retry_delay,
+ )
+
+ if github_token != input.github_token:
+ with sandbox_credential_lock(sandbox.id) as acquired:
+ applied = acquired and apply_github_credentials_to_sandbox(sandbox, [input.repository], github_token)
+ if not applied:
+ logger.warning(
+ "refreshed_github_token_not_applied",
+ extra={
+ "run_id": ctx.run_id,
+ "repository": input.repository,
+ "sandbox_id": sandbox.id,
+ "lock_acquired": acquired,
+ },
)
# A fresh single-repository run checks its requested branch out in the next
@@ -1258,6 +1303,39 @@ def clone_repository_in_sandbox(input: CloneRepositoryInSandboxInput) -> CloneRe
return CloneRepositoryInSandboxOutput(clone_ms=clone_timer.elapsed_ms)
+def _clone_retry_delay(attempt: int) -> timedelta | None:
+ if attempt <= len(REPOSITORY_CLONE_RETRY_DELAYS_SECONDS):
+ return timedelta(seconds=REPOSITORY_CLONE_RETRY_DELAYS_SECONDS[attempt - 1])
+ return None
+
+
+def _log_repository_clone_denied(ctx: TaskProcessingContext, repository: str, stderr: str, *, confirmed: bool) -> None:
+ log_with_activity_context(
+ "repository_clone_denied",
+ run_id=ctx.run_id,
+ repository=repository,
+ origin_product=ctx.origin_product,
+ denial_confirmed=confirmed,
+ stderr=stderr,
+ )
+
+
+def _reresolve_sandbox_github_token(ctx: TaskProcessingContext, repository: str) -> str:
+ task = _load_task(ctx)
+ actor_user = get_task_run_credential_user(task, ctx.state)
+ return _resolve_sandbox_github_token(ctx, task=task, actor_user=actor_user, repository=repository, has_repo=True)
+
+
+def _installation_behind_sandbox_token(ctx: TaskProcessingContext) -> GitHubIntegration | None:
+ if ctx.github_read_access:
+ return resolve_readonly_github_integration(ctx.team_id)
+ if ctx.github_integration_id is None:
+ return None
+ if get_pr_authorship_mode(_load_task(ctx), ctx.state) != PrAuthorshipMode.BOT:
+ return None
+ return resolve_installation_github_integration(ctx.github_integration_id)
+
+
def _is_repository_access_denied_clone_error(result: ExecutionResult) -> bool:
if result.exit_code == 0:
return False
diff --git a/products/tasks/backend/temporal/process_task/activities/tests/test_provision_sandbox.py b/products/tasks/backend/temporal/process_task/activities/tests/test_provision_sandbox.py
index 5a6519536f58..f179397b0aa5 100644
--- a/products/tasks/backend/temporal/process_task/activities/tests/test_provision_sandbox.py
+++ b/products/tasks/backend/temporal/process_task/activities/tests/test_provision_sandbox.py
@@ -4,6 +4,7 @@ import socket
import asyncio
import subprocess
import dataclasses
+from contextlib import nullcontext
from datetime import timedelta
from pathlib import Path
@@ -42,6 +43,7 @@ from products.tasks.backend.temporal.process_task.activities.provision_sandbox i
clone_repository_in_sandbox,
create_sandbox_for_repository,
)
+from products.tasks.backend.temporal.process_task.utils import PrAuthorshipMode
@pytest.fixture(autouse=True)
@@ -728,6 +730,7 @@ def test_clone_failure_diagnostics_redact_credentials_before_truncation(
"products.tasks.backend.temporal.process_task.activities.provision_sandbox.get_sandbox_class_for_sandbox_id",
return_value=mocker.Mock(get_by_id=mocker.Mock(return_value=sandbox)),
)
+ mocker.patch.object(provision_sandbox_module, "_installation_behind_sandbox_token", return_value=None)
capture_exception = mocker.patch("products.tasks.backend.exceptions.capture_exception")
warning = mocker.patch("products.tasks.backend.temporal.process_task.activities.provision_sandbox.logger.warning")
@@ -761,6 +764,166 @@ def test_clone_failure_diagnostics_redact_credentials_before_truncation(
assert "fake-other-credential" not in diagnostics
+def _clone_context(**overrides) -> TaskProcessingContext:
+ fields = {
+ "task_id": "task-id",
+ "run_id": "run-id",
+ "team_id": 1,
+ "team_uuid": "team-uuid",
+ "organization_id": "organization-id",
+ "github_integration_id": 123,
+ "repository": "acme/repo",
+ "distinct_id": "distinct-id",
+ "state": {},
+ }
+ return TaskProcessingContext(**{**fields, **overrides})
+
+
+def _clone_input(context: TaskProcessingContext, github_token: str) -> CloneRepositoryInSandboxInput:
+ return CloneRepositoryInSandboxInput(
+ context=context,
+ sandbox_id="sandbox-id",
+ repository="acme/repo",
+ github_token=github_token,
+ shallow_clone=True,
+ )
+
+
+def _mock_clone_sandbox(mocker, clone_result: ExecutionResult):
+ sandbox = mocker.Mock()
+ sandbox.clone_repository.return_value = clone_result
+ mocker.patch.object(
+ provision_sandbox_module,
+ "get_sandbox_class_for_sandbox_id",
+ return_value=mocker.Mock(get_by_id=mocker.Mock(return_value=sandbox)),
+ )
+ return sandbox
+
+
+ "confirmed, expected_error",
+ [(True, RepositoryAccessError), (False, RepositoryCloneError)],
+ ids=["installation_cannot_read_repo", "installation_can_read_repo"],
+)
+def test_denied_clone_with_installation_token_fails_for_good_only_when_github_confirms(
+ mocker, activity_environment, confirmed, expected_error
+):
+ stderr = (
+ "Cloning into 'repo'...\n"
+ "warning: redirecting to https://x-access-token:[email protected]/acme/repo.git/\n"
+ "fatal: could not read Username for 'https://github.com': terminal prompts disabled\n"
+ )
+ _mock_clone_sandbox(mocker, ExecutionResult(stdout="", stderr=stderr, exit_code=128, error=None))
+ installation = mocker.Mock()
+ mocker.patch.object(provision_sandbox_module, "_installation_behind_sandbox_token", return_value=installation)
+ mocker.patch.object(provision_sandbox_module, "installation_confirms_repository_denied", return_value=confirmed)
+ forget = mocker.patch.object(provision_sandbox_module, "forget_cached_github_tokens")
+ mocker.patch("products.tasks.backend.exceptions.capture_exception")
+
+ with pytest.raises(expected_error) as error:
+ async_to_sync(activity_environment.run)(
+ clone_repository_in_sandbox, _clone_input(_clone_context(), github_token="ghs_secret")
+ )
+
+ assert error.value.non_retryable is confirmed
+ assert error.value.context["stderr"] == stderr.replace("ghs_secret", "<redacted>")
+ assert "ghs_secret" not in str(error.value)
+ if confirmed:
+ forget.assert_not_called()
+ else:
+ forget.assert_called_once_with(installation, ["acme/repo"])
+ assert error.value.next_retry_delay == timedelta(seconds=1)
+
+
+def test_denied_clone_without_installation_token_is_not_verified(mocker, activity_environment):
+ _mock_clone_sandbox(
+ mocker,
+ ExecutionResult(
+ stdout="",
+ stderr="fatal: Authentication failed for 'https://github.com/acme/repo.git/'\n",
+ exit_code=128,
+ error=None,
+ ),
+ )
+ mocker.patch.object(provision_sandbox_module, "_installation_behind_sandbox_token", return_value=None)
+ confirms = mocker.patch.object(provision_sandbox_module, "installation_confirms_repository_denied")
+
+ with pytest.raises(RepositoryAccessError):
+ async_to_sync(activity_environment.run)(
+ clone_repository_in_sandbox, _clone_input(_clone_context(), github_token="ghu_user")
+ )
+
+ confirms.assert_not_called()
+
+
+ "attempt, lock_acquired, expected_token, credentials_applied",
+ [(1, True, "github-token", False), (2, True, "fresh-token", True), (2, False, "fresh-token", False)],
+ ids=["first_attempt", "retry", "retry_without_credential_lock"],
+)
+def test_retried_clone_resolves_a_fresh_github_token(
+ mocker, activity_environment, attempt, lock_acquired, expected_token, credentials_applied
+):
+ activity_environment.info = dataclasses.replace(activity_environment.info, attempt=attempt)
+ sandbox = _mock_clone_sandbox(mocker, ExecutionResult(stdout="", stderr="", exit_code=0))
+ mocker.patch.object(provision_sandbox_module, "_reresolve_sandbox_github_token", return_value="fresh-token")
+ mocker.patch.object(provision_sandbox_module, "_prepare_posthog_desktop_cloud_task")
+ mocker.patch.object(provision_sandbox_module, "sandbox_credential_lock", return_value=nullcontext(lock_acquired))
+ apply_credentials = mocker.patch.object(
+ provision_sandbox_module, "apply_github_credentials_to_sandbox", return_value=True
+ )
+
+ async_to_sync(activity_environment.run)(
+ clone_repository_in_sandbox, _clone_input(_clone_context(), github_token="github-token")
+ )
+
+ assert sandbox.clone_repository.call_args.kwargs["github_token"] == expected_token
+ if credentials_applied:
+ apply_credentials.assert_called_once_with(sandbox, ["acme/repo"], "fresh-token")
+ else:
+ apply_credentials.assert_not_called()
+
+
+def test_retried_clone_fails_transiently_when_no_fresh_token_is_available(mocker, activity_environment):
+ activity_environment.info = dataclasses.replace(activity_environment.info, attempt=2)
+ sandbox = _mock_clone_sandbox(mocker, ExecutionResult(stdout="", stderr="", exit_code=0))
+ mocker.patch.object(provision_sandbox_module, "_reresolve_sandbox_github_token", return_value="")
+ mocker.patch("products.tasks.backend.exceptions.capture_exception")
+
+ with pytest.raises(RepositoryCloneError) as error:
+ async_to_sync(activity_environment.run)(
+ clone_repository_in_sandbox, _clone_input(_clone_context(), github_token="github-token")
+ )
+
+ assert error.value.non_retryable is False
+ sandbox.clone_repository.assert_not_called()
+
+
+ "state, github_integration_id, authorship_mode, expected",
+ [
+ ({"github_read_access": True}, None, None, "readonly"),
+ ({}, 123, PrAuthorshipMode.BOT, "installation"),
+ ({}, 123, PrAuthorshipMode.USER, None),
+ ({}, None, PrAuthorshipMode.BOT, None),
+ ],
+ ids=["readonly_run", "bot_run_with_installation", "user_authored_run", "run_without_integration"],
+)
+def test_installation_behind_sandbox_token_skips_user_credentials(
+ mocker, state, github_integration_id, authorship_mode, expected
+):
+ mocker.patch.object(provision_sandbox_module, "_load_task")
+ mocker.patch.object(provision_sandbox_module, "get_pr_authorship_mode", return_value=authorship_mode)
+ mocker.patch.object(provision_sandbox_module, "resolve_readonly_github_integration", return_value="readonly")
+ mocker.patch.object(
+ provision_sandbox_module, "resolve_installation_github_integration", return_value="installation"
+ )
+
+ context = _clone_context(state=state, github_integration_id=github_integration_id)
+
+ assert provision_sandbox_module._installation_behind_sandbox_token(context) == expected
+
+
def _prepared_for_create() -> PrepareSandboxForRepositoryOutput:
return PrepareSandboxForRepositoryOutput(
sandbox_name="sandbox-name",
diff --git a/products/tasks/backend/temporal/process_task/tests/test_utils.py b/products/tasks/backend/temporal/process_task/tests/test_utils.py
index 20007657684f..21412f996490 100644
--- a/products/tasks/backend/temporal/process_task/tests/test_utils.py
+++ b/products/tasks/backend/temporal/process_task/tests/test_utils.py
@@ -859,6 +859,64 @@ class TestGetGithubToken(TestCase):
with self.assertRaises(CredentialUnavailableError):
get_github_token(integration.id)
+ @override_settings(
+ TASKS_REDIS_URL="",
+ CACHES={"default": {"BACKEND": "django.core.cache.backends.locmem.LocMemCache"}},
+ )
+ def test_forgetting_cached_tokens_forces_a_fresh_scoped_mint(self):
+ from posthog.egress.limiter.policies import Priority
+ from posthog.models import Integration, Organization, Team
+ from posthog.models.integration import GitHubIntegration
+
+ from products.tasks.backend.redis import get_tasks_cache
+ from products.tasks.backend.temporal.process_task.utils import forget_cached_github_tokens, get_github_token
+
+ get_tasks_cache().clear()
+ org = Organization.objects.create(name="o")
+ team = Team.objects.create(organization=org, name="t")
+ integration = Integration.objects.create(
+ team=team,
+ kind="github",
+ integration_id="INSTALL",
+ config={"installation_id": "INSTALL", "account": {"type": "Organization", "name": "Acme"}},
+ sensitive_config={"access_token": "ghs_shared"},
+ )
+
+ with patch.object(GitHubIntegration, "mint_scoped_installation_token", side_effect=["ghs_1", "ghs_2"]) as mint:
+ first = [get_github_token(integration.id, repositories=["acme/api"]) for _ in range(2)]
+ forget_cached_github_tokens(
+ GitHubIntegration(integration, source="tasks_sandbox", priority=Priority.CRITICAL), ["Acme/API"]
+ )
+ second = get_github_token(integration.id, repositories=["acme/api"])
+
+ assert first == ["ghs_1", "ghs_1"]
+ assert second == "ghs_2"
+ assert mint.call_count == 2
+
+ @parameterized.expand(
+ [
+ ("readable", 200, False),
+ ("not_found", 404, True),
+ ("forbidden", 403, True),
+ ("unauthorized", 401, False),
+ ("upstream_error", 503, False),
+ ("probe_raises", None, False),
+ ]
+ )
+ def test_installation_confirms_repository_denied_only_on_a_clear_refusal(self, _name, status, expected):
+ from posthog.models.integration import GitHubIntegration
+
+ from products.tasks.backend.temporal.process_task.utils import installation_confirms_repository_denied
+
+ github = MagicMock(spec=GitHubIntegration)
+ if status is None:
+ github.api_request.side_effect = RuntimeError("probe failed")
+ else:
+ github.api_request.return_value = MagicMock(status_code=status)
+
+ assert installation_confirms_repository_denied(github, "acme/api") is expected
+ github.api_request.assert_called_once_with("GET", "/repos/acme/api", endpoint="/repos/{owner}/{repo}")
+
@parameterized.expand(
[
("renamed_account", "OldAcme", ["acme/api"], ["api"], "ghs_scoped"),
diff --git a/products/tasks/backend/temporal/process_task/utils.py b/products/tasks/backend/temporal/process_task/utils.py
index 11845aa2de0d..b7e9c9f5b096 100644
--- a/products/tasks/backend/temporal/process_task/utils.py
+++ b/products/tasks/backend/temporal/process_task/utils.py
@@ -1024,11 +1024,36 @@ def _resolve_installation_repository_names(
return sorted(resolved)
+def _scoped_token_cache_key(github_integration: GitHubIntegrationBase, names: Sequence[str]) -> str:
+ return f"task-sandbox-github-token:{github_integration.github_installation_id}:{','.join(names)}"
+
+
+def forget_cached_github_tokens(github_integration: GitHubIntegrationBase, repositories: Sequence[str]) -> None:
+ names = _installation_repository_names(github_integration, _private_repositories(repositories))
+ get_tasks_cache().delete(_scoped_token_cache_key(github_integration, names))
+
+
+def installation_confirms_repository_denied(github_integration: GitHubIntegrationBase, repository: str) -> bool:
+ try:
+ response = github_integration.api_request("GET", f"/repos/{repository}", endpoint="/repos/{owner}/{repo}")
+ except Exception:
+ logger.warning("Could not verify GitHub installation access to %s", repository, exc_info=True)
+ return False
+ return response.status_code in (403, 404)
+
+
+def resolve_installation_github_integration(github_integration_id: int) -> GitHubIntegration | None:
+ integration = Integration.objects.filter(id=github_integration_id, kind="github").first()
+ if integration is None:
+ return None
+ return GitHubIntegration(integration, source="tasks_sandbox", priority=Priority.CRITICAL)
+
+
def _mint_repository_scoped_token(github_integration: GitHubIntegrationBase, repositories: Sequence[str]) -> str | None:
names = _installation_repository_names(github_integration, repositories)
if not names:
return None
- cache_key = f"task-sandbox-github-token:{github_integration.github_installation_id}:{','.join(names)}"
+ cache_key = _scoped_token_cache_key(github_integration, names)
cache = get_tasks_cache()
cached = cache.get(cache_key)
if isinstance(cached, str):