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.

feat(stamphog): route hosted reviews and the digest through the ai-gateway (#93846)

Brandon866036827259
diff --git a/posthog/settings/integrations.py b/posthog/settings/integrations.py
index 5b2d60140a36..74778354e7a0 100644
--- a/posthog/settings/integrations.py
+++ b/posthog/settings/integrations.py
@@ -79,6 +79,10 @@ STAMPHOG_GITHUB_APP_SLUG = get_from_env("STAMPHOG_GITHUB_APP_SLUG", "")
# PyPI, the LLM gateway host, the PostHog capture host). Comma-separated; an ops escape hatch for
# when a legitimate dependency host is missing — never a way to open the sandbox wide.
STAMPHOG_SANDBOX_EXTRA_EGRESS_DOMAINS = get_list(get_from_env("STAMPHOG_SANDBOX_EXTRA_EGRESS_DOMAINS", ""))
+# Models the reviewer's per-run gateway token may call, comma-separated; empty leaves the token
+# unpinned. Set per region in charts (temporal-worker-stamphog); pin every model the Agent SDK
+# uses in a review, including its small utility model.
+STAMPHOG_REVIEWER_TOKEN_ALLOWED_MODELS = get_list(get_from_env("STAMPHOG_REVIEWER_TOKEN_ALLOWED_MODELS", ""))
# The in-product "Publish to community" flow runs as its own dedicated GitHub App, installed on the
# PostHog/community-skills repo alone. It does not fall back to the core GITHUB_APP_* App above,
# which is installed across the whole PostHog org: a dedicated App cannot reach another repository
diff --git a/products/stamphog/AGENTS.md b/products/stamphog/AGENTS.md
index 135b676ac726..70201455b3f2 100644
--- a/products/stamphog/AGENTS.md
+++ b/products/stamphog/AGENTS.md
@@ -93,11 +93,17 @@ add a read-then-act path, pin it; this class of bug has been found on five separ
## Sandbox credentials and egress
-- The sandbox holds NO long-lived secret. `_mint_reviewer_gateway_token` mints a per-run OAuth
- token under the repo's connecting user with exactly `["llm_gateway:read", "internal_run:read"]`
+- The sandbox holds NO long-lived secret; `_reviewer_environment` mints a per-run credential under
+ the repo's connecting user. With the Go ai-gateway configured (`AI_GATEWAY_URL` + `AI_GATEWAY_API_KEY`
+ in the worker env) that is a `phe_` scoped token from `POST /v1/tokens`: `product=aio_stamphog`,
+ `obo=<customer team>`, `cap_usd=5`, `ttl_seconds=3600`. The worker's `phs_` mints it and never
+ enters the sandbox, and the worker revokes the token once the sandbox is destroyed. With
+ `AI_GATEWAY_URL` on the Go host and no key the run fails closed: the OAuth token below is a
+ standard credential on the Go gateway and must never be sent there. The legacy path (`AI_GATEWAY_URL` alone, on the Python gateway's
+ `/stamphog/v1` route) mints an OAuth token with exactly `["llm_gateway:read", "internal_run:read"]`
and `include_internal_scopes=False`. Never switch to `include_internal_scopes=True` — that
drags `task:write` into a sandbox running an LLM over untrusted PR content. The
- `internal_run:read` marker is what satisfies the gateway route's `requires_server_credential`.
+ `internal_run:read` marker is what satisfies that route's `requires_server_credential`.
- The raw-Anthropic fallback exists for a local `review_pr.py` run only; hosted runs fail closed
without a gateway. No `ANTHROPIC_API_KEY` may enter the sandbox environment.
- Egress is an explicit domain allowlist (`_sandbox_egress_allowlist`). Additions go through
diff --git a/products/stamphog/README.md b/products/stamphog/README.md
index 85bf5880e311..34f1846bcfa9 100644
--- a/products/stamphog/README.md
+++ b/products/stamphog/README.md
@@ -47,4 +47,4 @@ Per-repo settings live on `StamphogRepoConfig` (synced via the GitHub App instal
## Security model, in one paragraph
-The sandbox runs an LLM over untrusted PR content, so it holds no long-lived secrets: it gets a per-run OAuth token (scoped to `llm_gateway:read` + the server-mint marker) that only works against the gateway's stamphog route, egress is fenced to an explicit domain allowlist, posted bodies are scrubbed and markdown-image-neutralized, and approvals are governed by a strict supersession protocol so no approval survives events it shouldn't (pushes, re-reviews, repo disable). Details and invariants: [AGENTS.md](AGENTS.md).
+The sandbox runs an LLM over untrusted PR content, so it holds no long-lived secrets: it gets a per-run gateway token (a `phe_` scoped token pinned to `product=aio_stamphog` and capped at $5 on the Go ai-gateway, or an OAuth token scoped to `llm_gateway:read` + the server-mint marker on the legacy gateway's stamphog route), egress is fenced to an explicit domain allowlist, posted bodies are scrubbed and markdown-image-neutralized, and approvals are governed by a strict supersession protocol so no approval survives events it shouldn't (pushes, re-reviews, repo disable). Details and invariants: [AGENTS.md](AGENTS.md).
diff --git a/products/stamphog/backend/logic/digest.py b/products/stamphog/backend/logic/digest.py
index cabb766139e7..16aa67df0ad4 100644
--- a/products/stamphog/backend/logic/digest.py
+++ b/products/stamphog/backend/logic/digest.py
@@ -28,7 +28,7 @@ from typing import TYPE_CHECKING, Any
import structlog
from posthog.dataclasses import frozen
-from posthog.llm.gateway_client import get_llm_client
+from posthog.llm.gateway_client import build_anthropic_client, team_distinct_id
if TYPE_CHECKING:
from ..models import PullRequest, PullRequestAudience
@@ -38,6 +38,8 @@ logger = structlog.get_logger(__name__)
# Cheap, fast model — the digest is a summarization job, not deep reasoning.
_DIGEST_MODEL = "claude-haiku-4-5"
_SOURCE_PRODUCT = "stamphog_digest"
+# The Messages shape requires an output ceiling; the selection answer is a short JSON list.
+_DIGEST_MAX_TOKENS = 4096
# Bounds on the headline call alone. That call is optional: the selection call's lines are already
# the digest, and losing the headline costs the channel its lead sentence and nothing else. It also
@@ -51,6 +53,8 @@ _SOURCE_PRODUCT = "stamphog_digest"
# than waiting another half minute for it.
_HEADLINE_TIMEOUT_SECONDS = 30.0
_HEADLINE_MAX_RETRIES = 1
+# One to three sentences; the gateway sizes its admission hold from max_tokens.
+_HEADLINE_MAX_TOKENS = 512
# A payload rail, never an editorial rule. Slack rejects a message past 50 blocks and the thread
# spends one on its lead line, so this sits well under that with room for a block someone adds
@@ -613,7 +617,13 @@ def summarize_merged_prs(prs: list[PullRequest], audiences: list[PullRequestAudi
team_id = prs[0].team_id
try:
- client = get_llm_client(product="stamphog", team_id=team_id)
+ client = build_anthropic_client(
+ "stamphog",
+ ai_product="aio_stamphog",
+ team_id=team_id,
+ properties={"source_product": _SOURCE_PRODUCT},
+ distinct_id=team_distinct_id(team_id),
+ )
picked = _parse_selection(
_complete(client, team_id, _build_selection_prompt(prs, audiences)),
dict(enumerate(prs)),
@@ -631,14 +641,16 @@ def summarize_merged_prs(prs: list[PullRequest], audiences: list[PullRequestAudi
return replace(summary, headline=_request_headline(client, team_id, summary.prs, prs))
-def _complete(client: Any, team_id: int, prompt: str) -> str:
- response = client.chat.completions.create(
+def _complete(client: Any, team_id: int, prompt: str, *, max_tokens: int = _DIGEST_MAX_TOKENS) -> str:
+ # Messages shape: the Go gateway serves Claude models on this route only. metadata.user_id is
+ # for the Python-gateway fallback; the Go gateway reads the distinct-id header.
+ response = client.messages.create(
model=_DIGEST_MODEL,
+ max_tokens=max_tokens,
messages=[{"role": "user", "content": prompt}],
- user=f"team-{team_id}",
- extra_headers={"x-posthog-property-source_product": _SOURCE_PRODUCT},
+ metadata={"user_id": team_distinct_id(team_id)},
)
- return response.choices[0].message.content or ""
+ return "".join(block.text for block in response.content if getattr(block, "type", "") == "text")
def _request_headline(client: Any, team_id: int, picked: list[DigestPRSummary], prs: list[PullRequest]) -> str:
@@ -652,7 +664,8 @@ def _request_headline(client: Any, team_id: int, picked: list[DigestPRSummary],
sources = {(pr.repo_config.repository, pr.pr_number): pr for pr in prs}
try:
bounded = client.with_options(timeout=_HEADLINE_TIMEOUT_SECONDS, max_retries=_HEADLINE_MAX_RETRIES)
- return _parse_headline(_complete(bounded, team_id, _build_headline_prompt(picked, sources)))
+ prompt = _build_headline_prompt(picked, sources)
+ return _parse_headline(_complete(bounded, team_id, prompt, max_tokens=_HEADLINE_MAX_TOKENS))
except Exception as e:
logger.warning("stamphog_digest_headline_fallback", team_id=team_id, error=str(e))
return ""
diff --git a/products/stamphog/backend/temporal/activities.py b/products/stamphog/backend/temporal/activities.py
index ca7151120062..27fbe9176fad 100644
--- a/products/stamphog/backend/temporal/activities.py
+++ b/products/stamphog/backend/temporal/activities.py
@@ -19,8 +19,10 @@ from __future__ import annotations
import os
import re
import json
+import time
import shlex
import base64
+import random
from collections.abc import Sequence
from dataclasses import dataclass
from pathlib import Path
@@ -32,9 +34,12 @@ from django.utils import timezone
from django.utils.dateparse import parse_datetime
import yaml
+import requests
+from prometheus_client import Counter
from temporalio import activity
-from posthog.models import User
+from posthog.llm.gateway_client import AIGatewayConfig, resolve_ai_gateway_config
+from posthog.models import OAuthAccessToken, User
from posthog.ph_client import ph_scoped_capture
from posthog.temporal.common.utils import asyncify
from posthog.temporal.oauth import create_oauth_access_token_for_user
@@ -116,20 +121,33 @@ def _load_run(input: StamphogReviewInput) -> ReviewRun:
)
-def _mint_reviewer_gateway_token(run: ReviewRun) -> str:
- """Short-lived OAuth token the sandboxed reviewer presents to the LLM gateway.
+# aio_ continues the series the Action-era runs emitted; the engine blob carries the same word.
+STAMPHOG_AI_PRODUCT = "aio_stamphog"
+# The cap bounds what a leaked token can spend; the TTL must outlive the 30-minute review activity.
+_REVIEWER_TOKEN_CAP_USD = "5"
+_REVIEWER_TOKEN_TTL_SECONDS = 3600
+_MINT_ATTEMPTS = 2
+_MINT_TIMEOUT_SECONDS = 3
- Minted under the user who connected the repo's installation (the same creator-credential model
- tasks uses with ``task.created_by``), under the shared sandbox OAuth app, carrying only
- ``llm_gateway:read`` plus the ``internal_run:read`` provenance marker — the gateway's stamphog
- route sets ``requires_server_credential`` and refuses OAuth tokens without the marker, so a
- user's own Desktop OAuth token can't reach the route. The marker is passed explicitly instead of
- ``include_internal_scopes=True`` to keep the rest of the internal bundle (``task:write``) out of
- a sandbox that runs an LLM over untrusted PR content. If that PR coaxes the reviewer into
- leaking the token, it buys a few hours of stamphog-route LLM calls and nothing else — the
- worker's own long-lived credential never enters the sandbox. Fails closed when the repo was
- never synced or the connecting user is gone; re-syncing stamps a fresh identity.
- """
+AI_GATEWAY_TOKEN_MINTS = Counter(
+ "stamphog_ai_gateway_token_mints_total",
+ "Scoped-token mint attempts for hosted stamphog reviews",
+ labelnames=["result"],
+)
+
+
+def _gateway_root(gateway: AIGatewayConfig) -> str:
+ # The config URL carries the OpenAI /v1 base; the token routes hang off the gateway root.
+ return gateway.url.rstrip("/").removesuffix("/v1")
+
+
+def _is_legacy_stamphog_route(url: str) -> bool:
+ # The legacy Python gateway resolves the product from the path, so its route ends in the slug.
+ return urlparse(url).path.rstrip("/").endswith("/stamphog/v1")
+
+
+def _connected_user(run: ReviewRun) -> User:
+ """The connecting user every sandbox credential is minted under; missing or inactive fails the run."""
user_id = run.pull_request.repo_config.connected_by_user_id
if user_id is None:
raise RuntimeError(
@@ -141,35 +159,164 @@ def _mint_reviewer_gateway_token(run: ReviewRun) -> str:
"The user who connected this installation is missing or deactivated; "
"re-sync the installation to mint sandbox LLM credentials"
)
+ return user
+
+
+def _mint_reviewer_oauth_token(run: ReviewRun, user: User) -> str:
+ """Short-lived OAuth token for the legacy gateway's stamphog route.
+
+ Carries only ``llm_gateway:read`` plus the ``internal_run:read`` marker that route requires.
+ Never ``include_internal_scopes=True``: it drags ``task:write`` into a sandbox running an LLM
+ over untrusted PR content.
+ """
return create_oauth_access_token_for_user(
user, run.team_id, scopes=["llm_gateway:read", "internal_run:read"], include_internal_scopes=False
)
-def _reviewer_environment(run: ReviewRun) -> dict[str, str]:
+def _mint_reviewer_scoped_token(gateway: AIGatewayConfig, run: ReviewRun, user: User) -> str:
+ """Per-run ``phe_`` minted with the worker's ``phs_``, which never enters the sandbox.
+
+ Pinned to product and team and capped in spend and lifetime, so a leak buys little. Retries once
+ on 429, 5xx and network errors; any other refusal is final, and hosted runs have no shared-key
+ fallback. A token minted without a requested model pin is revoked and fails the run. Kept
+ separate from the tasks and wizard minters: each product owns its failure posture, and this cap
+ and TTL are documented invariants rather than ops knobs.
+ """
+ body: dict[str, object] = {
+ "cap_usd": _REVIEWER_TOKEN_CAP_USD,
+ "ttl_seconds": _REVIEWER_TOKEN_TTL_SECONDS,
+ "product": STAMPHOG_AI_PRODUCT,
+ "obo": str(run.team_id),
+ }
+ if user.distinct_id:
+ body["user"] = user.distinct_id
+ # An empty entry (a trailing comma) is a mint 400, which fails every review.
+ allowed_models = [model.strip() for model in settings.STAMPHOG_REVIEWER_TOKEN_ALLOWED_MODELS if model.strip()]
+ if allowed_models:
+ body["allowed_models"] = allowed_models
+ mint_url = f"{_gateway_root(gateway)}/v1/tokens"
+ last_error = ""
+ for attempt in range(_MINT_ATTEMPTS):
+ try:
+ response = requests.post(
+ mint_url,
+ json=body,
+ headers={"Authorization": f"Bearer {gateway.api_key}"},
+ timeout=_MINT_TIMEOUT_SECONDS,
+ )
+ except requests.RequestException as e:
+ last_error = type(e).__name__
+ else:
+ if 200 <= response.status_code < 300:
+ try:
+ payload = response.json()
+ token = payload["token"]
+ except (ValueError, TypeError, KeyError):
+ payload, token = {}, None
+ if token:
+ if allowed_models and not payload.get("allowed_models"):
+ # A gateway that predates the pin field ignores it and mints an unpinned token.
+ _release_reviewer_token(gateway, token)
+ AI_GATEWAY_TOKEN_MINTS.labels(result="unpinned").inc()
+ raise RuntimeError(
+ "The gateway minted the reviewer token without the required model pin; "
+ "the gateway must support allowed_models before the reviewer model list is set"
+ )
+ AI_GATEWAY_TOKEN_MINTS.labels(result="ok").inc()
+ return token
+ last_error = "mint response carried no token"
+ break
+ if response.status_code == 429 or response.status_code >= 500:
+ last_error = f"HTTP {response.status_code}"
+ else:
+ last_error = f"HTTP {response.status_code}: {response.text[:200]}"
+ break
+ if attempt < _MINT_ATTEMPTS - 1:
+ time.sleep(0.5 + random.uniform(0, 0.25))
+ AI_GATEWAY_TOKEN_MINTS.labels(result="error").inc()
+ raise RuntimeError(
+ f"Could not mint the sandbox gateway token ({last_error}); hosted reviews require the LLM gateway"
+ )
+
+
+def _release_reviewer_token(gateway: AIGatewayConfig | None, token: str) -> None:
+ """Best-effort revoke of a token the run no longer needs; the TTL outlives the review by design.
+
+ A failure only logs (the token then expires) and never changes the run's outcome. A legacy
+ OAuth token is a row this worker created, so it is deleted here.
+ """
+ try:
+ if gateway is None:
+ deleted, _ = OAuthAccessToken.objects.filter(token=token).delete()
+ outcome = "ok" if deleted else "no such token"
+ else:
+ response = requests.post(
+ f"{_gateway_root(gateway)}/v1/tokens/revoke",
+ json={"token": token},
+ headers={"Authorization": f"Bearer {gateway.api_key}"},
+ timeout=_MINT_TIMEOUT_SECONDS,
+ )
+ if not 200 <= response.status_code < 300:
+ outcome = f"HTTP {response.status_code}"
+ else:
+ # The gateway answers 200 with revoked=false when no token matched.
+ outcome = "ok" if response.json().get("revoked", True) else "no such token"
+ except Exception as e: # noqa: BLE001 — a revoke failure must never mask the review outcome
+ outcome = type(e).__name__
+ if outcome != "ok":
+ activity.logger.warning(f"Could not revoke the reviewer token ({outcome}); it expires with its TTL")
+
+
+def _reviewer_environment(run: ReviewRun) -> tuple[dict[str, str], AIGatewayConfig | None]:
"""Environment for the in-sandbox reviewer.
The sandbox holds no GitHub token by design, and no long-lived LLM credential either: the only
- secret it receives is a per-run minted gateway token (see ``_mint_reviewer_gateway_token``). The
- gateway is mandatory for hosted runs — the engine's raw-Anthropic fallback exists for the GitHub
- Action runtime, where the env is the repo's own secrets, and an org-wide Anthropic key must never
- ride into a sandbox that runs an LLM over untrusted PR content. AI_GATEWAY_URL must point at the
- gateway's stamphog product route (``https://<gateway>/stamphog/v1``): that route allowlists the
- sandbox OAuth app the token is minted under, so a token presented anywhere else is refused.
+ secret it receives is a per-run minted gateway token. A gateway is mandatory for hosted runs —
+ the engine's raw-Anthropic fallback exists for a local run, where the env is the developer's
+ own, and an org-wide Anthropic key must never ride into a sandbox that runs an LLM over untrusted
+ PR content.
+
+ With ``AI_GATEWAY_URL`` and ``AI_GATEWAY_API_KEY`` both set, the token is a per-run ``phe_`` from
+ the Go ai-gateway; with the URL alone it must be the legacy ``/stamphog/v1`` route and the token
+ is the OAuth token that route allowlists. Any other pairing fails the run: the OAuth token is a
+ standard credential on the Go gateway and must never be sent there. Returns the env and the Go
+ config (None on the legacy path) so the caller can revoke the token.
POSTHOG_API_KEY/POSTHOG_HOST let the engine emit its stamphog_review_completed event and LLM
traces from inside the sandbox. The capture key is a public project write token — the same class of
token every frontend snippet ships — so its blast radius is event spam, not data access; it's still
added to _llm_env_secrets so persisted output stays tidy. STAMPHOG_EXTRA_PROPERTIES stamps the
- hosted runtime/team/run context onto those events (the Action never sets it).
+ hosted runtime/team/run context onto those events.
"""
- gateway_url = os.environ.get("AI_GATEWAY_URL")
- if not gateway_url:
- raise RuntimeError("AI_GATEWAY_URL is not configured; hosted reviews require the LLM gateway")
+ # Skip the resolver without a key: it warns per call, and legacy regions run keyless for good.
+ gateway = resolve_ai_gateway_config() if settings.AI_GATEWAY_API_KEY else None
+ if gateway is not None:
+ if _is_legacy_stamphog_route(gateway.url):
+ raise RuntimeError(
+ "AI_GATEWAY_API_KEY is set but AI_GATEWAY_URL is the legacy stamphog route; "
+ "the ai-gateway key belongs with the ai-gateway URL"
+ )
+ gateway_url = gateway.url
+ else:
+ gateway_url = settings.AI_GATEWAY_URL or ""
+ if not gateway_url:
+ raise RuntimeError("AI_GATEWAY_URL is not configured; hosted reviews require the LLM gateway")
+ if not _is_legacy_stamphog_route(gateway_url):
+ raise RuntimeError(
+ "AI_GATEWAY_URL is not the legacy stamphog route and AI_GATEWAY_API_KEY is unset; "
+ "hosted reviews need both values for the ai-gateway"
+ )
+ user = _connected_user(run)
+ token = (
+ _mint_reviewer_scoped_token(gateway, run, user)
+ if gateway is not None
+ else _mint_reviewer_oauth_token(run, user)
+ )
env = {
"STAMPHOG_REPO_DIR": STAMPHOG_SANDBOX_REPO_DIR,
"AI_GATEWAY_URL": gateway_url,
- "AI_GATEWAY_API_KEY": _mint_reviewer_gateway_token(run),
+ "AI_GATEWAY_API_KEY": token,
}
for key in ("POSTHOG_API_KEY", "POSTHOG_HOST"):
value = os.environ.get(key)
@@ -185,10 +332,10 @@ def _reviewer_environment(run: ReviewRun) -> dict[str, str]:
if (run.output or {}).get("inbox_review"):
extra_properties["stamphog_self_driving_review"] = True
env["STAMPHOG_EXTRA_PROPERTIES"] = json.dumps(extra_properties, separators=(",", ":"))
- return env
+ return env, gateway
-def _sandbox_egress_allowlist() -> list[str]:
+def _sandbox_egress_allowlist(gateway_url: str) -> list[str]:
"""Outbound domains the review sandbox may reach; Modal fences off everything else.
The sandbox env carries a live (if short-lived, narrowly scoped) credential next to an LLM
@@ -196,15 +343,16 @@ def _sandbox_egress_allowlist() -> list[str]:
stops a prompt-injected reviewer from POSTing what it holds to an arbitrary host — closing egress
to the hosts a review actually needs removes that channel: github.com for the clone, PyPI for the
engine's pinned deps, the gateway for LLM calls, and the PostHog capture host for telemetry.
+ ``gateway_url`` is the URL handed to the sandbox, so egress cannot drift from the route it calls.
STAMPHOG_SANDBOX_EXTRA_EGRESS_DOMAINS is the ops escape hatch for a missing legitimate host.
The docker backend (local dev) ignores the allowlist.
"""
domains = ["github.com", "pypi.org", "files.pythonhosted.org"]
- for url_env in ("AI_GATEWAY_URL", "POSTHOG_HOST"):
- host = urlparse(os.environ.get(url_env, "")).hostname
+ for url in (gateway_url, os.environ.get("POSTHOG_HOST", "")):
+ host = urlparse(url).hostname
if host:
domains.append(host)
- domains.extend(settings.STAMPHOG_SANDBOX_EXTRA_EGRESS_DOMAINS)
+ domains.extend(domain.strip() for domain in settings.STAMPHOG_SANDBOX_EXTRA_EGRESS_DOMAINS if domain.strip())
return list(dict.fromkeys(domains))
@@ -473,79 +621,85 @@ def run_review_in_sandbox(input: StamphogReviewInput) -> dict:
)
sandbox_class = get_sandbox_class_for_backend(_resolve_sandbox_backend())
- environment = _reviewer_environment(run)
+ environment, gateway = _reviewer_environment(run)
# Per-run credential, not in the worker env — scrub it explicitly wherever sandbox output
# is persisted or raised (_llm_env_secrets only covers worker-env values).
gateway_token = environment["AI_GATEWAY_API_KEY"]
- config = SandboxConfig(
- name=f"stamphog-review-{run.id}",
- template=SandboxTemplate.SLIM_BASE,
- metadata={"review_run_id": str(run.id)},
- environment_variables=environment,
- outbound_domain_allowlist=_sandbox_egress_allowlist(),
- )
- # The steps above cost nothing and keep their own exception type. From here the run makes a
- # sandbox and can run the reviewer, so failures raise SandboxPhaseError, which the retry policy
- # excludes. Both statements stay outside the try below, so the refusal keeps its own type and a
- # failed write stays retryable.
- #
- # Temporal applies the start-to-close timeout and retries a lost worker. Neither path raises a
- # type this code can mark, so the claim is what stops a second sandbox. Read it from the writer,
- # because a stalled attempt holds a copy from before its replacement wrote. Read and then write
- # is not atomic: two attempts in the same instant both pass. A column and a conditional update
- # would close that.
- latest_output = (
- ReviewRun.objects.for_team(input.team_id)
- .using(router.db_for_write(ReviewRun))
- .filter(id=run.id)
- .values_list("output", flat=True)
- .first()
- ) or {}
- if latest_output.get("sandbox_started_at"):
- raise SandboxPhaseError("an earlier attempt already provisioned a sandbox for this run")
- run.output = {**latest_output, "sandbox_started_at": timezone.now().isoformat()}
- run.save(update_fields=["output", "updated_at"])
-
+ # Every path from here releases the token, including a failed claim read or save.
try:
- sandbox = sandbox_class.create(config)
- try:
- _clone_pr(sandbox, repo, base_sha, run.head_sha, run.pull_request.pr_number, token)
- _inject_policy_files(sandbox, policy_files)
- _ship_engine(sandbox)
- _write_context(sandbox, invocation)
-
- command = f"cd {shlex.quote(STAMPHOG_SANDBOX_REPO_DIR)} && {_harden_reviewer_command(invocation.command)}"
- result = sandbox.execute(command, timeout_seconds=25 * 60)
- finally:
- # A destroy failure must not mask a completed review — the verdict below still has to be
- # persisted and posted. An orphaned sandbox self-terminates when SandboxConfig.ttl_seconds expires.
- try:
- sandbox.destroy()
- except Exception:
- activity.logger.exception(f"Failed to destroy sandbox for run {run.id}")
-
- # Scrub stdout before persisting: it can echo the LLM keys the sandbox holds, and it is
- # both stored on run.output and re-read verbatim to render the verdict posted to GitHub.
- run.output = {
- **(run.output or {}),
- "reviewer_raw": _scrub_credentials(result.stdout, token, gateway_token),
- "reviewer_exit_code": result.exit_code,
- }
+ config = SandboxConfig(
+ name=f"stamphog-review-{run.id}",
+ template=SandboxTemplate.SLIM_BASE,
+ metadata={"review_run_id": str(run.id)},
+ environment_variables=environment,
+ outbound_domain_allowlist=_sandbox_egress_allowlist(environment["AI_GATEWAY_URL"]),
+ )
+ # The steps above cost nothing and keep their own exception type. From here the run makes a
+ # sandbox and can run the reviewer, so failures raise SandboxPhaseError, which the retry policy
+ # excludes. Both statements stay outside the try below, so the refusal keeps its own type and a
+ # failed write stays retryable.
+ #
+ # Temporal applies the start-to-close timeout and retries a lost worker. Neither path raises a
+ # type this code can mark, so the claim is what stops a second sandbox. Read it from the writer,
+ # because a stalled attempt holds a copy from before its replacement wrote. Read and then write
+ # is not atomic: two attempts in the same instant both pass. A column and a conditional update
+ # would close that.
+ latest_output = (
+ ReviewRun.objects.for_team(input.team_id)
+ .using(router.db_for_write(ReviewRun))
+ .filter(id=run.id)
+ .values_list("output", flat=True)
+ .first()
+ ) or {}
+ if latest_output.get("sandbox_started_at"):
+ raise SandboxPhaseError("an earlier attempt already provisioned a sandbox for this run")
+ run.output = {**latest_output, "sandbox_started_at": timezone.now().isoformat()}
run.save(update_fields=["output", "updated_at"])
- if result.exit_code != 0:
- # The reviewer reads an untrusted PR head, so its stderr can contain repository content.
- # This message reaches run.error, so keep the stderr in the worker log only.
- activity.logger.error(
- f"Reviewer exited with code {result.exit_code} for run {run.id}: "
- f"{_scrub_credentials(result.stderr, token, gateway_token)[:500]}"
- )
- raise RuntimeError(f"reviewer exited with code {result.exit_code}")
- except Exception as exc:
- # Give the type only. Every step in this phase touches the sandbox, and anyone with
- # stamphog:read can read run.error without access to the repository. The setup phase above
- # keeps its text, because it fails on our own infrastructure and must stay diagnosable.
- raise SandboxPhaseError(f"the sandbox phase failed with {type(exc).__name__}") from exc
+ try:
+ sandbox = sandbox_class.create(config)
+ try:
+ _clone_pr(sandbox, repo, base_sha, run.head_sha, run.pull_request.pr_number, token)
+ _inject_policy_files(sandbox, policy_files)
+ _ship_engine(sandbox)
+ _write_context(sandbox, invocation)
+
+ command = (
+ f"cd {shlex.quote(STAMPHOG_SANDBOX_REPO_DIR)} && {_harden_reviewer_command(invocation.command)}"
+ )
+ result = sandbox.execute(command, timeout_seconds=25 * 60)
+ finally:
+ # A destroy failure must not mask a completed review — the verdict below still has to be
+ # persisted and posted. An orphaned sandbox self-terminates when SandboxConfig.ttl_seconds expires.
+ try:
+ sandbox.destroy()
+ except Exception:
+ activity.logger.exception(f"Failed to destroy sandbox for run {run.id}")
+
+ # Scrub stdout before persisting: it can echo the LLM keys the sandbox holds, and it is
+ # both stored on run.output and re-read verbatim to render the verdict posted to GitHub.
+ run.output = {
+ **(run.output or {}),
+ "reviewer_raw": _scrub_credentials(result.stdout, token, gateway_token),
+ "reviewer_exit_code": result.exit_code,
+ }
+ run.save(update_fields=["output", "updated_at"])
+
+ if result.exit_code != 0:
+ # The reviewer reads an untrusted PR head, so its stderr can contain repository content.
+ # This message reaches run.error, so keep the stderr in the worker log only.
+ activity.logger.error(
+ f"Reviewer exited with code {result.exit_code} for run {run.id}: "
+ f"{_scrub_credentials(result.stderr, token, gateway_token)[:500]}"
+ )
+ raise RuntimeError(f"reviewer exited with code {result.exit_code}")
+ except Exception as exc:
+ # Give the type only. Every step in this phase touches the sandbox, and anyone with
+ # stamphog:read can read run.error without access to the repository. The setup phase above
+ # keeps its text, because it fails on our own infrastructure and must stay diagnosable.
+ raise SandboxPhaseError(f"the sandbox phase failed with {type(exc).__name__}") from exc
+ finally:
+ _release_reviewer_token(gateway, gateway_token)
activity.logger.info(f"Reviewer completed for run {run.id}")
return {"exit_code": result.exit_code}
diff --git a/products/stamphog/backend/tests/conftest.py b/products/stamphog/backend/tests/conftest.py
index 83bf553a7d9a..74105e0b060a 100644
--- a/products/stamphog/backend/tests/conftest.py
+++ b/products/stamphog/backend/tests/conftest.py
@@ -1,4 +1,3 @@
-import os
from collections.abc import Iterator
from contextlib import AbstractContextManager, ExitStack
from dataclasses import dataclass
@@ -194,9 +193,9 @@ def stamphog_chain() -> Iterator[StamphogChain]:
STAMPHOG_GITHUB_APP_PRIVATE_KEY=_generate_app_private_key(),
)
)
- # Hosted reviews hard-require the gateway (no raw-Anthropic fallback); point it at the
- # stamphog product route like production would.
- stack.enter_context(patch.dict(os.environ, {"AI_GATEWAY_URL": "https://llm-gateway.test/stamphog/v1"}))
+ # Hosted reviews require a gateway; the fixture points settings at the legacy stamphog route.
+ # Go-gateway tests override both settings of the pair locally.
+ stack.enter_context(override_settings(AI_GATEWAY_URL="https://llm-gateway.test/stamphog/v1"))
# mark_review_failed emits a failure event through the real analytics client — a network
# boundary, faked like the rest. Tests asserting on the event re-patch this locally.
stack.enter_context(patch("products.stamphog.backend.temporal.activities.ph_scoped_capture"))
@@ -233,7 +232,7 @@ def stamphog_chain() -> Iterator[StamphogChain]:
stack.enter_context(patch("products.stamphog.backend.logic.channel_resolution.SlackIntegration", fake_slack))
stack.enter_context(
patch(
- "products.stamphog.backend.logic.digest.get_llm_client",
+ "products.stamphog.backend.logic.digest.build_anthropic_client",
side_effect=RuntimeError("no gateway in tests"),
)
)
diff --git a/products/stamphog/backend/tests/fakes.py b/products/stamphog/backend/tests/fakes.py
index 7a8b33173a5b..355489f28aae 100644
--- a/products/stamphog/backend/tests/fakes.py
+++ b/products/stamphog/backend/tests/fakes.py
@@ -516,7 +516,7 @@ def approved_engine_output() -> str:
return "uv run: resolved 1 package\n" + json.dumps(payload)
-def make_fake_sandbox_class(engine_output: str, write_sink: list[tuple[str, bytes]] | None = None) -> type:
+def make_fake_sandbox_class(engine_output: str, write_sink: list[tuple[str, bytes]] | None = None) -> type[Any]:
"""A sandbox class returning ``engine_output`` for the reviewer command, no-ops otherwise.
``write_sink``, when given, records every ``write_file`` as ``(path, payload)`` so a test can
diff --git a/products/stamphog/backend/tests/test_digest.py b/products/stamphog/backend/tests/test_digest.py
index bdc3c15a44c3..eec7e778a037 100644
--- a/products/stamphog/backend/tests/test_digest.py
+++ b/products/stamphog/backend/tests/test_digest.py
@@ -28,6 +28,7 @@ from products.stamphog.backend.logic.channel_resolution import (
)
from products.stamphog.backend.logic.digest import (
_HEADLINE_MAX_RETRIES,
+ _HEADLINE_MAX_TOKENS,
_HEADLINE_TIMEOUT_SECONDS,
GRAZE_CHANGED_FILES,
MAX_DIGEST_PRS,
@@ -678,17 +679,18 @@ def _recording_llm_client(answers: list[Any]) -> Any:
headline call are given different fates.
"""
prompts: list[str] = []
+ calls: list[dict[str, Any]] = []
def create(**kwargs: Any) -> Any:
+ calls.append(kwargs)
prompts.append(kwargs["messages"][0]["content"])
answer = answers[len(prompts) - 1]
if isinstance(answer, Exception):
raise answer
- return SimpleNamespace(choices=[SimpleNamespace(message=SimpleNamespace(content=answer))])
+ # The Anthropic Messages shape: a list of content blocks, text ones carry the answer.
+ return SimpleNamespace(content=[SimpleNamespace(type="text", text=answer)])
- client = SimpleNamespace(
- chat=SimpleNamespace(completions=SimpleNamespace(create=create)), prompts=prompts, options=[]
- )
+ client = SimpleNamespace(messages=SimpleNamespace(create=create), prompts=prompts, calls=calls, options=[])
# The real client hands back a bounded copy. The fake records the bounds and answers as itself,
# so a test can assert what the optional headline call was limited to.
client.with_options = lambda **kwargs: (client.options.append(kwargs), client)[1]
@@ -717,7 +719,7 @@ def test_the_headline_call_never_sees_a_merge_the_thread_left_out() -> None:
)
client = _recording_llm_client([selection, json.dumps({"headline": "The kept one shipped."})])
- with patch("products.stamphog.backend.logic.digest.get_llm_client", return_value=client):
+ with patch("products.stamphog.backend.logic.digest.build_anthropic_client", return_value=client):
summary = summarize_merged_prs(prs)
assert [p.pr_number for p in summary.prs] == [1]
@@ -741,7 +743,7 @@ def test_a_headline_failure_keeps_the_judged_digest() -> None:
client = _recording_llm_client(answers)
- with patch("products.stamphog.backend.logic.digest.get_llm_client", return_value=client):
+ with patch("products.stamphog.backend.logic.digest.build_anthropic_client", return_value=client):
summary = summarize_merged_prs(prs)
assert summary.judged is True
@@ -751,6 +753,34 @@ def test_a_headline_failure_keeps_the_judged_digest() -> None:
# and a team's audiences post one at a time, so an unbounded stall on an optional call holds up
# this digest and every audience behind it. The client's own default is ten minutes with retries.
assert client.options == [{"timeout": _HEADLINE_TIMEOUT_SECONDS, "max_retries": _HEADLINE_MAX_RETRIES}]
+ # The headline answers in a paragraph, so it reserves far less output than the selection call.
+ assert client.calls[1]["max_tokens"] == _HEADLINE_MAX_TOKENS < client.calls[0]["max_tokens"]
+
+
+def test_the_digest_call_names_its_product_team_and_source() -> None:
+ # The Go gateway serves Claude only on the Messages shape and reads labels from the client's
+ # headers, so the builder carries the product, team and source tag and every call sets the
+ # output ceiling the shape requires. metadata.user_id is for the Python-gateway fallback.
+ prs = [_pr_stub("o/r", 1, "Kept", "https://github.com/o/r/pull/1")]
+ client = _recording_llm_client([json.dumps({"prs": [{"index": 0, "rule": "contract", "summary": "It ships."}]})])
+
+ with patch("products.stamphog.backend.logic.digest.build_anthropic_client", return_value=client) as build:
+ summary = summarize_merged_prs(prs)
+
+ team_id = prs[0].team_id
+ assert summary.judged is True
+ build.assert_called_once_with(
+ "stamphog",
+ ai_product="aio_stamphog",
+ team_id=team_id,
+ properties={"source_product": "stamphog_digest"},
+ distinct_id=f"team-{team_id}",
+ )
+ (selection_call,) = client.calls[:1]
+ assert selection_call["model"] == "claude-haiku-4-5"
+ assert selection_call["max_tokens"] > 0
+ assert selection_call["metadata"] == {"user_id": f"team-{team_id}"}
+ assert "extra_headers" not in selection_call and "user" not in selection_call
@pytest.mark.parametrize(
@@ -784,7 +814,7 @@ def test_a_merge_that_only_grazed_the_team_never_reaches_the_model(
selection = json.dumps({"prs": [{"index": 0, "rule": "contract", "summary": "The first one."}]})
client = _recording_llm_client([selection, json.dumps({"headline": "Something shipped."})])
- with patch("products.stamphog.backend.logic.digest.get_llm_client", return_value=client):
+ with patch("products.stamphog.backend.logic.digest.build_anthropic_client", return_value=client):
summary = summarize_merged_prs([grazed, owned], audiences)
assert ("Swept in" in client.prompts[0]) is not dropped
@@ -800,7 +830,9 @@ def test_a_model_outage_posts_a_short_plain_list_and_says_it_judged_nothing() ->
# run consumes every merge it claims either way and the post reads like an ordinary quiet day.
prs = [_pr_stub("o/r", n, f"Change {n}", f"https://github.com/o/r/pull/{n}") for n in range(MAX_FALLBACK_PRS + 3)]
- with patch("products.stamphog.backend.logic.digest.get_llm_client", side_effect=RuntimeError("gateway down")):
+ with patch(
+ "products.stamphog.backend.logic.digest.build_anthropic_client", side_effect=RuntimeError("gateway down")
+ ):
summary = summarize_merged_prs(prs)
assert summary.judged is False
@@ -828,7 +860,7 @@ def test_same_pr_number_across_repos_both_survive_summarization() -> None:
)
with patch(
- "products.stamphog.backend.logic.digest.get_llm_client",
+ "products.stamphog.backend.logic.digest.build_anthropic_client",
return_value=_recording_llm_client([selection, json.dumps({"headline": "Both repos changed."})]),
):
summary = summarize_merged_prs(prs)
@@ -935,7 +967,9 @@ def test_the_headline_reaches_the_channel_as_one_link_free_paragraph(raw_headlin
json.dumps({"prs": [{"index": 0, "rule": "contract", "summary": "Ship it."}]}),
json.dumps({"headline": raw_headline}),
]
- with patch("products.stamphog.backend.logic.digest.get_llm_client", return_value=_recording_llm_client(contents)):
+ with patch(
+ "products.stamphog.backend.logic.digest.build_anthropic_client", return_value=_recording_llm_client(contents)
+ ):
summary = summarize_merged_prs([_pr_stub("o/r", 1, "Ship it", "https://example.com/1")])
assert summary.headline == expected
# A rejected headline never costs the change line the selection call already wrote.
diff --git a/products/stamphog/backend/tests/test_integration.py b/products/stamphog/backend/tests/test_integration.py
index 788767a0495c..58ef74b260ec 100644
--- a/products/stamphog/backend/tests/test_integration.py
+++ b/products/stamphog/backend/tests/test_integration.py
@@ -439,7 +439,19 @@ def test_sandbox_gets_minted_short_lived_credential_and_closed_egress(
recorder.policy_files[".stamphog/policy.yml"] = "version: 1\n"
worker_env = {"ANTHROPIC_API_KEY": "sk-ant-worker-secret", "AI_GATEWAY_API_KEY": "phs_worker_shared_key"}
- with patch.dict(os.environ, worker_env):
+ # The row is deleted once the sandbox is destroyed, so capture it at mint time.
+ minted_rows: list[OAuthAccessToken] = []
+ real_mint = activities.create_oauth_access_token_for_user
+
+ def recording_mint(*args, **kwargs):
+ minted_token = real_mint(*args, **kwargs)
+ minted_rows.append(OAuthAccessToken.objects.get(token=minted_token))
+ return minted_token
+
+ with (
+ patch.dict(os.environ, worker_env),
+ patch.object(activities, "create_oauth_access_token_for_user", recording_mint),
+ ):
stamphog_chain.post_webhook(_opened_event(110, "devex-dev", head_sha), delivery_id=str(uuid.uuid4()))
config = stamphog_chain.sandbox_class.created_configs[0]
@@ -447,7 +459,8 @@ def test_sandbox_gets_minted_short_lived_credential_and_closed_egress(
assert "ANTHROPIC_API_KEY" not in env
assert env["AI_GATEWAY_API_KEY"] != "phs_worker_shared_key"
- minted = OAuthAccessToken.objects.get(token=env["AI_GATEWAY_API_KEY"])
+ (minted,) = minted_rows
+ assert minted.token == env["AI_GATEWAY_API_KEY"]
assert minted.user_id == user.id
# internal_run:read is the server-mint provenance marker the gateway's stamphog route demands
# (requires_server_credential); llm_gateway:read is the only real capability. Anything broader
@@ -455,6 +468,8 @@ def test_sandbox_gets_minted_short_lived_credential_and_closed_egress(
assert set(minted.scope.split()) == {"llm_gateway:read", "internal_run:read"}
assert minted.scoped_teams == [team.id]
assert minted.expires is not None and minted.expires > timezone.now()
+ # Revoked with the sandbox: the row is gone once the run ends.
+ assert not OAuthAccessToken.objects.filter(token=env["AI_GATEWAY_API_KEY"]).exists()
assert "github.com" in config.outbound_domain_allowlist
assert "llm-gateway.test" in config.outbound_domain_allowlist
@@ -570,9 +585,10 @@ def test_hosted_review_fails_closed_without_gateway_instead_of_anthropic_fallbac
recorder.register_pr(REPO, 112, _pr_object(112, "devex-dev", "sha112a"), _pr_files())
recorder.policy_files[".stamphog/policy.yml"] = "version: 1\n"
- env_without_gateway = {k: v for k, v in os.environ.items() if k != "AI_GATEWAY_URL"}
- env_without_gateway["ANTHROPIC_API_KEY"] = "sk-ant-worker-secret"
- with patch.dict(os.environ, env_without_gateway, clear=True):
+ with (
+ override_settings(AI_GATEWAY_URL="", AI_GATEWAY_API_KEY=""),
+ patch.dict(os.environ, {"ANTHROPIC_API_KEY": "sk-ant-worker-secret"}),
+ ):
stamphog_chain.post_webhook(_opened_event(112, "devex-dev", "sha112a"), delivery_id=str(uuid.uuid4()))
run = ReviewRun.objects.for_team(team.id).latest("created_at")
@@ -584,6 +600,196 @@ def test_hosted_review_fails_closed_without_gateway_instead_of_anthropic_fallbac
assert not (run.error or "").startswith("SandboxPhaseError")
+_GO_GATEWAY_SETTINGS = {"AI_GATEWAY_URL": "https://ai-gateway.test/v1", "AI_GATEWAY_API_KEY": "phs_stamphog_mint"}
+
+
+def _mint_response(status_code: int, payload: dict | None = None, text: str = "") -> MagicMock:
+ response = MagicMock()
+ response.status_code = status_code
+ response.json.return_value = payload if payload is not None else {}
+ response.text = text
+ return response
+
+
+def _register_review(stamphog_chain: StamphogChain, number: int, head_sha: str) -> dict:
+ recorder = stamphog_chain.recorder
+ recorder.register_pr(REPO, number, _pr_object(number, "devex-dev", head_sha), _pr_files())
+ recorder.policy_files[".stamphog/policy.yml"] = "version: 1\n"
+ return _opened_event(number, "devex-dev", head_sha)
+
+
[email protected]_db(databases=PRODUCT_DATABASES)
+def test_sandbox_gets_a_scoped_gateway_token_when_the_go_gateway_is_configured(
+ team, user, stamphog_chain: StamphogChain
+) -> None:
+ # With the Go ai-gateway configured, the sandbox credential is a per-run phe_ minted with the
+ # worker's phs_ and pinned to the stamphog product and the customer team. The phs_ never enters
+ # the sandbox, no OAuth token is minted, and egress follows the URL the sandbox was handed.
+ _repo_config(team.id)
+ event = _register_review(stamphog_chain, 113, "sha113a")
+ minted = {"token": "phe_run", "expires_at": "2026-09-02T00:00:00Z", "cap_usd": "5"}
+ mint = MagicMock(return_value=_mint_response(201, minted))
+
+ with (
+ override_settings(**_GO_GATEWAY_SETTINGS),
+ patch.dict(os.environ, {"ANTHROPIC_API_KEY": "sk-ant-worker-secret"}),
+ patch.object(activities.requests, "post", mint),
+ ):
+ stamphog_chain.post_webhook(event, delivery_id=str(uuid.uuid4()))
+
+ config = stamphog_chain.sandbox_class.created_configs[0]
+ env = config.environment_variables
+ assert env["AI_GATEWAY_URL"] == "https://ai-gateway.test/v1"
+ assert env["AI_GATEWAY_API_KEY"] == "phe_run"
+ # Nothing long-lived crosses into the sandbox: not the worker's phs_, not an Anthropic key, and
+ # no key outside the documented set (a widened passthrough goes red here).
+ assert "phs_stamphog_mint" not in env.values()
+ assert "ANTHROPIC_API_KEY" not in env
+ assert set(env) <= {
+ "STAMPHOG_REPO_DIR",
+ "AI_GATEWAY_URL",
+ "AI_GATEWAY_API_KEY",
+ "POSTHOG_API_KEY",
+ "POSTHOG_HOST",
+ "STAMPHOG_EXTRA_PROPERTIES",
+ }
+ assert not OAuthAccessToken.objects.filter(user_id=user.id).exists()
+
+ mint_call, revoke_call = mint.call_args_list
+ assert mint_call.args == ("https://ai-gateway.test/v1/tokens",)
+ assert mint_call.kwargs["headers"] == {"Authorization": "Bearer phs_stamphog_mint"}
+ assert mint_call.kwargs["timeout"] == 3
+ assert user.distinct_id # the acting identity rides on the token
+ assert mint_call.kwargs["json"] == {
+ "cap_usd": "5",
+ "ttl_seconds": 3600,
+ "product": "aio_stamphog",
+ "obo": str(team.id),
+ "user": user.distinct_id,
+ }
+ # The token dies with its sandbox: a best-effort revoke follows destroy.
+ assert revoke_call.args == ("https://ai-gateway.test/v1/tokens/revoke",)
+ assert revoke_call.kwargs["json"] == {"token": "phe_run"}
+ assert revoke_call.kwargs["headers"] == {"Authorization": "Bearer phs_stamphog_mint"}
+ assert "ai-gateway.test" in config.outbound_domain_allowlist
+ assert "github.com" in config.outbound_domain_allowlist
+ assert "llm-gateway.test" not in config.outbound_domain_allowlist
+
+
[email protected]_db(databases=PRODUCT_DATABASES)
+def test_hosted_review_fails_closed_when_the_scoped_token_mint_fails(team, stamphog_chain: StamphogChain) -> None:
+ # A mint outage retries once and then fails the run: no sandbox, never a shared-key fallback.
+ # Nothing was paid for, so the failure stays retryable (not SandboxPhaseError).
+ _repo_config(team.id)
+ event = _register_review(stamphog_chain, 114, "sha114a")
+ mint = MagicMock(return_value=_mint_response(503, text="upstream unavailable"))
+
+ with (
+ override_settings(**_GO_GATEWAY_SETTINGS),
+ patch.object(activities.requests, "post", mint),
+ patch.object(activities.time, "sleep"),
+ ):
+ stamphog_chain.post_webhook(event, delivery_id=str(uuid.uuid4()))
+
+ run = ReviewRun.objects.for_team(team.id).latest("created_at")
+ assert run.status == ReviewRunStatus.FAILED
+ assert "gateway" in (run.error or "").lower()
+ assert "HTTP 503" in (run.error or "")
+ assert mint.call_count == 2
+ assert not stamphog_chain.sandbox_class.created_configs
+ assert not (run.error or "").startswith("SandboxPhaseError")
+
+
[email protected]_db(databases=PRODUCT_DATABASES)
+def test_scoped_token_mint_does_not_retry_a_credential_rejection(team, stamphog_chain: StamphogChain) -> None:
+ # A 4xx other than 429 is a final answer about the worker's own credential; retrying it only
+ # burns the mint quota. The gateway's reason survives into run.error for the operator.
+ _repo_config(team.id)
+ event = _register_review(stamphog_chain, 115, "sha115a")
+ refusal = '{"error":"only a standard credential may mint scoped tokens"}'
+ mint = MagicMock(return_value=_mint_response(403, text=refusal))
+
+ with override_settings(**_GO_GATEWAY_SETTINGS), patch.object(activities.requests, "post", mint):
+ stamphog_chain.post_webhook(event, delivery_id=str(uuid.uuid4()))
+
+ run = ReviewRun.objects.for_team(team.id).latest("created_at")
+ assert run.status == ReviewRunStatus.FAILED
+ assert "HTTP 403" in (run.error or "")
+ assert "only a standard credential" in (run.error or "")
+ assert mint.call_count == 1
+ assert not stamphog_chain.sandbox_class.created_configs
+
+
[email protected]_db(databases=PRODUCT_DATABASES)
+def test_a_half_configured_go_gateway_keeps_the_oauth_path(team, stamphog_chain: StamphogChain) -> None:
+ # The keyless shape: AI_GATEWAY_URL on the legacy stamphog route, no AI_GATEWAY_API_KEY. The worker
+ # mints OAuth tokens for that route and never calls the mint API.
+ _repo_config(team.id)
+ event = _register_review(stamphog_chain, 116, "sha116a")
+ mint = MagicMock()
+
+ with (
+ override_settings(AI_GATEWAY_URL="https://llm-gateway.test/stamphog/v1", AI_GATEWAY_API_KEY=""),
+ patch.object(activities.requests, "post", mint),
+ ):
+ stamphog_chain.post_webhook(event, delivery_id=str(uuid.uuid4()))
+
+ config = stamphog_chain.sandbox_class.created_configs[0]
+ env = config.environment_variables
+ assert env["AI_GATEWAY_URL"] == "https://llm-gateway.test/stamphog/v1"
+ assert env["AI_GATEWAY_API_KEY"].startswith("pha_")
+ mint.assert_not_called()
+ assert "llm-gateway.test" in config.outbound_domain_allowlist
+
+
[email protected]_db(databases=PRODUCT_DATABASES)
+def test_a_go_gateway_url_without_a_key_fails_closed(team, user, stamphog_chain: StamphogChain) -> None:
+ # Production has ONE AI_GATEWAY_URL. A key-only rollback or a URL flip ahead of its key leaves the
+ # Go URL with no key; the OAuth token is a standard credential on the Go gateway, so sending it
+ # there would run the review uncapped and unpinned. The run must fail before any sandbox exists.
+ _repo_config(team.id)
+ event = _register_review(stamphog_chain, 121, "sha121a")
+ mint = MagicMock()
+
+ with (
+ override_settings(AI_GATEWAY_URL="https://ai-gateway.test/v1", AI_GATEWAY_API_KEY=""),
+ patch.object(activities.requests, "post", mint),
+ ):
+ stamphog_chain.post_webhook(event, delivery_id=str(uuid.uuid4()))
+
+ run = ReviewRun.objects.for_team(team.id).latest("created_at")
+ assert run.status == ReviewRunStatus.FAILED
+ assert "AI_GATEWAY_API_KEY is unset" in (run.error or "")
+ assert not stamphog_chain.sandbox_class.created_configs
+ assert not OAuthAccessToken.objects.filter(user_id=user.id).exists()
+ mint.assert_not_called()
+ assert not (run.error or "").startswith("SandboxPhaseError")
+
+
[email protected]_db(databases=PRODUCT_DATABASES)
+def test_scoped_token_is_scrubbed_from_persisted_reviewer_output(team, stamphog_chain: StamphogChain) -> None:
+ # The per-run phe_ is not in the worker env, so _llm_env_secrets cannot catch it; the explicit
+ # gateway_token scrub must keep it out of ReviewRun.output.
+ _repo_config(team.id)
+ event = _register_review(stamphog_chain, 117, "sha117a")
+ leaky_sandbox = fakes.make_fake_sandbox_class("reviewer echoed phe_run\n" + fakes.approved_engine_output())
+ mint = MagicMock(return_value=_mint_response(201, {"token": "phe_run"}))
+
+ with (
+ override_settings(**_GO_GATEWAY_SETTINGS),
+ patch.object(activities.requests, "post", mint),
+ patch(
+ "products.stamphog.backend.temporal.activities.get_sandbox_class_for_backend",
+ lambda backend: leaky_sandbox,
+ ),
+ ):
+ stamphog_chain.post_webhook(event, delivery_id=str(uuid.uuid4()))
+
+ run = ReviewRun.objects.for_team(team.id).latest("created_at")
+ assert "phe_run" not in run.output["reviewer_raw"]
+ assert "reviewer echoed ***" in run.output["reviewer_raw"]
+
+
@pytest.mark.django_db(databases=PRODUCT_DATABASES)
def test_missing_policy_files_fall_back_to_server_defaults(team, stamphog_chain: StamphogChain) -> None:
# A target repo carrying neither .stamphog/policy.yml nor review-guidance.md must still get a
@@ -2043,3 +2249,201 @@ def test_inbox_review_approves_a_selfdriving_draft_pr_end_to_end(team, stamphog_
approvals = [w for w in recorder.github_writes if w["kind"] == "approve_review"]
assert len(approvals) == 1
assert approvals[0]["body"]["commit_id"] == "sha120a"
+
+
[email protected]_db(databases=PRODUCT_DATABASES)
+def test_mint_pins_allowed_models_when_configured(team, stamphog_chain: StamphogChain) -> None:
+ # A configured model list rides the mint request so a leaked token can call nothing else.
+ _repo_config(team.id)
+ event = _register_review(stamphog_chain, 118, "sha118a")
+ minted = {"token": "phe_run", "allowed_models": ["anthropic/claude-sonnet-5", "anthropic/claude-haiku-4-5"]}
+ mint = MagicMock(return_value=_mint_response(201, minted))
+
+ with (
+ override_settings(
+ **_GO_GATEWAY_SETTINGS, STAMPHOG_REVIEWER_TOKEN_ALLOWED_MODELS=["claude-sonnet-5", "claude-haiku-4-5", ""]
+ ),
+ patch.object(activities.requests, "post", mint),
+ ):
+ stamphog_chain.post_webhook(event, delivery_id=str(uuid.uuid4()))
+
+ # Empty entries (a trailing comma in the env value) never reach the gateway, which would 400.
+ assert mint.call_args_list[0].kwargs["json"]["allowed_models"] == ["claude-sonnet-5", "claude-haiku-4-5"]
+ env = stamphog_chain.sandbox_class.created_configs[0].environment_variables
+ assert env["AI_GATEWAY_API_KEY"] == "phe_run"
+
+
[email protected]_db(databases=PRODUCT_DATABASES)
+def test_mint_omits_allowed_models_by_default(team, stamphog_chain: StamphogChain) -> None:
+ # Unset means unpinned: the field is absent, never an empty list (which the gateway rejects).
+ _repo_config(team.id)
+ event = _register_review(stamphog_chain, 119, "sha119a")
+ mint = MagicMock(return_value=_mint_response(201, {"token": "phe_run"}))
+
+ with (
+ override_settings(**_GO_GATEWAY_SETTINGS, STAMPHOG_REVIEWER_TOKEN_ALLOWED_MODELS=[]),
+ patch.object(activities.requests, "post", mint),
+ ):
+ stamphog_chain.post_webhook(event, delivery_id=str(uuid.uuid4()))
+
+ assert "allowed_models" not in mint.call_args_list[0].kwargs["json"]
+ # No pin was asked for, so a missing echo is not a dropped pin and the review runs.
+ env = stamphog_chain.sandbox_class.created_configs[0].environment_variables
+ assert env["AI_GATEWAY_API_KEY"] == "phe_run"
+
+
[email protected]_db(databases=PRODUCT_DATABASES)
+def test_mint_fails_closed_when_the_gateway_ignores_the_model_pin(team, stamphog_chain: StamphogChain) -> None:
+ # A gateway replica that predates the pin field ignores it and mints an unpinned token. The
+ # token is revoked and the run fails: a sandbox never sees a credential looser than asked for.
+ _repo_config(team.id)
+ event = _register_review(stamphog_chain, 120, "sha120a")
+ mint = MagicMock(side_effect=[_mint_response(201, {"token": "phe_run"}), _mint_response(200, {"revoked": True})])
+ unpinned_before = activities.AI_GATEWAY_TOKEN_MINTS.labels(result="unpinned")._value.get()
+ ok_before = activities.AI_GATEWAY_TOKEN_MINTS.labels(result="ok")._value.get()
+ error_before = activities.AI_GATEWAY_TOKEN_MINTS.labels(result="error")._value.get()
+
+ with (
+ override_settings(**_GO_GATEWAY_SETTINGS, STAMPHOG_REVIEWER_TOKEN_ALLOWED_MODELS=["claude-sonnet-5"]),
+ patch.object(activities.requests, "post", mint),
+ ):
+ stamphog_chain.post_webhook(event, delivery_id=str(uuid.uuid4()))
+
+ run = ReviewRun.objects.for_team(team.id).latest("created_at")
+ assert run.status == ReviewRunStatus.FAILED
+ assert "model pin" in (run.error or "")
+ assert stamphog_chain.sandbox_class.created_configs == []
+ _, revoke_call = mint.call_args_list
+ assert revoke_call.args == ("https://ai-gateway.test/v1/tokens/revoke",)
+ assert revoke_call.kwargs["json"] == {"token": "phe_run"}
+ # One mint counts once: unpinned, never ok or error as well.
+ assert activities.AI_GATEWAY_TOKEN_MINTS.labels(result="unpinned")._value.get() == unpinned_before + 1
+ assert activities.AI_GATEWAY_TOKEN_MINTS.labels(result="ok")._value.get() == ok_before
+ assert activities.AI_GATEWAY_TOKEN_MINTS.labels(result="error")._value.get() == error_before
+
+
[email protected]_db(databases=PRODUCT_DATABASES)
+def test_mint_retries_a_network_error_and_records_the_outcome(team, stamphog_chain: StamphogChain) -> None:
+ # A transport blip (timeout, reset) is retried once and the review proceeds; the attempt carries
+ # the bounded timeout, and the counter records the outcome the operator will watch.
+ _repo_config(team.id)
+ event = _register_review(stamphog_chain, 122, "sha122a")
+ mint = MagicMock(
+ side_effect=[
+ requests.ConnectionError("reset"),
+ _mint_response(201, {"token": "phe_run"}),
+ _mint_response(200, {"revoked": True}),
+ ]
+ )
+ ok_before = activities.AI_GATEWAY_TOKEN_MINTS.labels(result="ok")._value.get()
+
+ with (
+ override_settings(**_GO_GATEWAY_SETTINGS),
+ patch.object(activities.requests, "post", mint),
+ patch.object(activities.time, "sleep") as sleep,
+ ):
+ stamphog_chain.post_webhook(event, delivery_id=str(uuid.uuid4()))
+
+ env = stamphog_chain.sandbox_class.created_configs[0].environment_variables
+ assert env["AI_GATEWAY_API_KEY"] == "phe_run"
+ assert [call.args[0] for call in mint.call_args_list] == [
+ "https://ai-gateway.test/v1/tokens",
+ "https://ai-gateway.test/v1/tokens",
+ "https://ai-gateway.test/v1/tokens/revoke",
+ ]
+ assert all(call.kwargs["timeout"] == 3 for call in mint.call_args_list)
+ sleep.assert_called_once()
+ assert activities.AI_GATEWAY_TOKEN_MINTS.labels(result="ok")._value.get() == ok_before + 1
+
+
+def test_product_tag_matches_the_engine_blob() -> None:
+ # The mint pins the product and the shipped engine stamps the same word in its properties blob;
+ # the two are hand-typed in different packages, so bind them here where both are visible.
+ engine_gateway = Path(activities.__file__).resolve().parents[2] / "packages" / "pr-approval-agent" / "gateway.py"
+ assert f'AI_PRODUCT = "{activities.STAMPHOG_AI_PRODUCT}"' in engine_gateway.read_text()
+
+
[email protected]_db(databases=PRODUCT_DATABASES)
+def test_scoped_token_is_revoked_when_the_sandbox_phase_fails(team, stamphog_chain: StamphogChain) -> None:
+ # The revoke exists for the runs that end badly: a sandbox that cannot be provisioned still had
+ # a live token minted for it, and the token dies with the attempt.
+ _repo_config(team.id)
+ event = _register_review(stamphog_chain, 123, "sha123a")
+ broken_sandbox = fakes.make_fake_sandbox_class(fakes.approved_engine_output())
+ broken_sandbox.create_error = RuntimeError("modal is down")
+ mint = MagicMock(side_effect=[_mint_response(201, {"token": "phe_run"}), _mint_response(200, {"revoked": True})])
+
+ with (
+ override_settings(**_GO_GATEWAY_SETTINGS),
+ patch.object(activities.requests, "post", mint),
+ patch(
+ "products.stamphog.backend.temporal.activities.get_sandbox_class_for_backend",
+ lambda backend: broken_sandbox,
+ ),
+ ):
+ stamphog_chain.post_webhook(event, delivery_id=str(uuid.uuid4()))
+
+ run = ReviewRun.objects.for_team(team.id).latest("created_at")
+ assert run.status == ReviewRunStatus.FAILED
+ assert (run.error or "").startswith("SandboxPhaseError")
+ _, revoke_call = mint.call_args_list
+ assert revoke_call.args == ("https://ai-gateway.test/v1/tokens/revoke",)
+ assert revoke_call.kwargs["json"] == {"token": "phe_run"}
+
+
[email protected]_db(databases=PRODUCT_DATABASES)
+def test_an_ineffective_revoke_is_logged(team, stamphog_chain: StamphogChain) -> None:
+ # The gateway answers 200 with revoked=false when nothing matched; that is the one signal that
+ # revocation is broken, so it must reach the warning like a transport failure does.
+ _repo_config(team.id)
+ event = _register_review(stamphog_chain, 124, "sha124a")
+ mint = MagicMock(side_effect=[_mint_response(201, {"token": "phe_run"}), _mint_response(200, {"revoked": False})])
+
+ with (
+ override_settings(**_GO_GATEWAY_SETTINGS),
+ patch.object(activities.requests, "post", mint),
+ patch.object(activities.activity.logger, "warning") as warning,
+ ):
+ stamphog_chain.post_webhook(event, delivery_id=str(uuid.uuid4()))
+
+ assert any(
+ "Could not revoke the reviewer token (no such token)" in str(call.args[0]) for call in warning.call_args_list
+ )
+
+
[email protected]_db(databases=PRODUCT_DATABASES)
+def test_a_legacy_oauth_token_is_deleted_after_the_run(team, user, stamphog_chain: StamphogChain) -> None:
+ # On the legacy path the credential is a row this worker created with a six-hour TTL; it goes
+ # when the sandbox does, the same as the Go token.
+ _repo_config(team.id)
+ event = _register_review(stamphog_chain, 125, "sha125a")
+
+ with override_settings(AI_GATEWAY_URL="https://llm-gateway.test/stamphog/v1", AI_GATEWAY_API_KEY=""):
+ stamphog_chain.post_webhook(event, delivery_id=str(uuid.uuid4()))
+
+ env = stamphog_chain.sandbox_class.created_configs[0].environment_variables
+ assert env["AI_GATEWAY_API_KEY"].startswith("pha_")
+ assert not OAuthAccessToken.objects.filter(token=env["AI_GATEWAY_API_KEY"]).exists()
+
+
[email protected]_db(databases=PRODUCT_DATABASES)
+def test_a_key_with_the_legacy_url_fails_before_the_mint(team, stamphog_chain: StamphogChain) -> None:
+ # An ai-gateway key next to the legacy route: the phs_ must not be posted to the Python host, so
+ # the run fails with a config message before any mint.
+ _repo_config(team.id)
+ event = _register_review(stamphog_chain, 126, "sha126a")
+ mint = MagicMock()
+
+ with (
+ override_settings(
+ AI_GATEWAY_URL="https://llm-gateway.test/stamphog/v1", AI_GATEWAY_API_KEY="phs_stamphog_mint"
+ ),
+ patch.object(activities.requests, "post", mint),
+ ):
+ stamphog_chain.post_webhook(event, delivery_id=str(uuid.uuid4()))
+
+ run = ReviewRun.objects.for_team(team.id).latest("created_at")
+ assert run.status == ReviewRunStatus.FAILED
+ assert "legacy stamphog route" in (run.error or "")
+ mint.assert_not_called()
+ assert not stamphog_chain.sandbox_class.created_configs