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.

chore(stamphog): drop the legacy gateway credential path (#93847)

Brandon03b351d3f2f6
diff --git a/posthog/llm/gateway_client.py b/posthog/llm/gateway_client.py
index a05a2eda4da6..15aedc77f57b 100644
--- a/posthog/llm/gateway_client.py
+++ b/posthog/llm/gateway_client.py
@@ -41,7 +41,6 @@ Product = Literal[
"warehouse_semantic_enrichment",
"warehouse_custom_source_builder",
"web_analytics",
- "stamphog",
] # If you add a product here, make sure it's also in services/llm-gateway/src/llm_gateway/products/config.py
@@ -454,6 +453,47 @@ def build_async_anthropic_client(
return get_async_anthropic_gateway_client(product, team_id=team_id, use_bedrock_fallback=use_bedrock_fallback)
+def _ai_gateway_anthropic_client(
+ gateway: AIGatewayConfig,
+ ai_product: str | None,
+ trace_id: str | None,
+ properties: Mapping[str, str] | None,
+ distinct_id: str | None,
+ team_id: int | None,
+) -> Anthropic:
+ labels = dict(properties or {})
+ if team_id is not None:
+ labels["team_id"] = str(team_id)
+ return Anthropic(
+ api_key=gateway.api_key,
+ base_url=_anthropic_gateway_base_url(gateway.url),
+ default_headers=ai_gateway_headers(
+ ai_product=ai_product,
+ trace_id=trace_id or team_trace_id(team_id),
+ properties=labels,
+ distinct_id=distinct_id,
+ ),
+ http_client=httpx.Client(trust_env=False),
+ )
+
+
+def build_ai_gateway_anthropic_client(
+ ai_product: str | None = None,
+ trace_id: str | None = None,
+ properties: Mapping[str, str] | None = None,
+ distinct_id: str | None = None,
+ team_id: int | None = None,
+) -> Anthropic:
+ """:func:`build_anthropic_client` without the Python-gateway fallback, for callers with no route there.
+
+ Raises when the Go ai-gateway pair is unset or malformed.
+ """
+ gateway = resolve_ai_gateway_config()
+ if gateway is None:
+ raise ValueError("AI_GATEWAY_URL and AI_GATEWAY_API_KEY must be configured")
+ return _ai_gateway_anthropic_client(gateway, ai_product, trace_id, properties, distinct_id, team_id)
+
+
def build_anthropic_client(
product: Product,
ai_product: str | None = None,
@@ -470,20 +510,7 @@ def build_anthropic_client(
"""
gateway = resolve_ai_gateway_config()
if gateway:
- labels = dict(properties or {})
- if team_id is not None:
- labels["team_id"] = str(team_id)
- return Anthropic(
- api_key=gateway.api_key,
- base_url=_anthropic_gateway_base_url(gateway.url),
- default_headers=ai_gateway_headers(
- ai_product=ai_product,
- trace_id=trace_id or team_trace_id(team_id),
- properties=labels,
- distinct_id=distinct_id,
- ),
- http_client=httpx.Client(trust_env=False),
- )
+ return _ai_gateway_anthropic_client(gateway, ai_product, trace_id, properties, distinct_id, team_id)
fallback_headers = _python_gateway_observability_headers(trace_id, None, properties)
return get_anthropic_gateway_client(
product,
diff --git a/posthog/llm/test_gateway_client.py b/posthog/llm/test_gateway_client.py
index 021086ea4725..62e29dd491d2 100644
--- a/posthog/llm/test_gateway_client.py
+++ b/posthog/llm/test_gateway_client.py
@@ -9,6 +9,7 @@ from django.test import override_settings
from posthog.llm.gateway_client import (
AIGatewayConfig,
Product,
+ build_ai_gateway_anthropic_client,
build_anthropic_client,
build_async_anthropic_client,
build_async_openai_client,
@@ -477,3 +478,41 @@ class TestBuildAnthropicClient:
assert kwargs["default_headers"]["traceparent"].startswith("00-")
assert kwargs["default_headers"]["x-posthog-property-source_product"] == "notebook_widget"
assert result is mock_get_anthropic.return_value
+
+
+class TestBuildAIGatewayAnthropicClient:
+ @override_settings(AI_GATEWAY_URL=AI_GATEWAY_URL, AI_GATEWAY_API_KEY=AI_GATEWAY_KEY)
+ @patch("posthog.llm.gateway_client.httpx.Client")
+ @patch("posthog.llm.gateway_client.Anthropic")
+ def test_builds_the_go_gateway_client_with_attribution(self, mock_anthropic, mock_httpx):
+ result = build_ai_gateway_anthropic_client(
+ ai_product="aio_stamphog",
+ properties={"source_product": "stamphog_digest"},
+ distinct_id="team-42",
+ team_id=42,
+ )
+
+ kwargs = mock_anthropic.call_args.kwargs
+ assert kwargs["api_key"] == AI_GATEWAY_KEY
+ assert kwargs["base_url"] == "https://ai-gateway.example"
+ assert kwargs["http_client"] is mock_httpx.return_value
+ headers = kwargs["default_headers"]
+ assert headers["X-PostHog-Trace-Id"] == TEAM_42_TRACE_ID
+ assert headers["X-PostHog-Distinct-Id"] == "team-42"
+ assert json.loads(headers["X-PostHog-Properties"]) == {
+ "ai_product": "aio_stamphog",
+ "source_product": "stamphog_digest",
+ "team_id": "42",
+ }
+ assert result is mock_anthropic.return_value
+
+ @pytest.mark.parametrize(
+ ("url", "api_key"),
+ [("", ""), (AI_GATEWAY_URL, ""), ("https://ai-gateway.example", AI_GATEWAY_KEY)],
+ )
+ @patch("posthog.llm.gateway_client.get_anthropic_gateway_client")
+ def test_raises_instead_of_using_the_python_gateway(self, mock_get_anthropic, url, api_key):
+ with override_settings(AI_GATEWAY_URL=url, AI_GATEWAY_API_KEY=api_key):
+ with pytest.raises(ValueError, match="AI_GATEWAY_URL and AI_GATEWAY_API_KEY must be configured"):
+ build_ai_gateway_anthropic_client(ai_product="aio_stamphog")
+ mock_get_anthropic.assert_not_called()
diff --git a/products/stamphog/AGENTS.md b/products/stamphog/AGENTS.md
index 70201455b3f2..edbc0a1fca08 100644
--- a/products/stamphog/AGENTS.md
+++ b/products/stamphog/AGENTS.md
@@ -93,17 +93,13 @@ 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; `_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 that route's `requires_server_credential`.
+- The sandbox holds NO long-lived secret. `_mint_reviewer_scoped_token` mints a per-run `phe_`
+ from the Go ai-gateway (`POST /v1/tokens`) with the worker's `phs_` (`AI_GATEWAY_API_KEY`), pinned
+ to `product=aio_stamphog` and `obo=<customer team>`, capped at `cap_usd=5` and `ttl_seconds=3600`,
+ acting as the repo's connecting user. The `phs_` never enters the sandbox; a mint failure fails
+ the run (no shared-key fallback); the worker revokes the token once the sandbox is destroyed. Do
+ not widen the cap or TTL without a run-cost reason: they bound what a prompt-injected reviewer can
+ spend with a leaked token.
- 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 c2aaeed5e805..bf07ff6cf62c 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 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).
+The sandbox runs an LLM over untrusted PR content, so it holds no long-lived secrets: it gets a per-run `phe_` scoped token from the Go ai-gateway (pinned to `product=aio_stamphog`, capped at $5 and one hour, revoked when the sandbox is destroyed), 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 39c76fee7e24..37bc576730fa 100644
--- a/products/stamphog/backend/logic/digest.py
+++ b/products/stamphog/backend/logic/digest.py
@@ -34,7 +34,7 @@ from typing import TYPE_CHECKING, Any
import structlog
from posthog.dataclasses import frozen
-from posthog.llm.gateway_client import build_anthropic_client, team_distinct_id
+from posthog.llm.gateway_client import build_ai_gateway_anthropic_client, team_distinct_id
from .audiences import REPO_AUDIENCE_PREFIX, team_slug_from_handle
@@ -829,8 +829,8 @@ def summarize_merged_prs(prs: list[PullRequest], audiences: list[PullRequestAudi
team_id = told.prs[0].team_id
try:
- client = build_anthropic_client(
- "stamphog",
+ # No Python-gateway fallback: it has no stamphog route, so an unset pair posts the plain list.
+ client = build_ai_gateway_anthropic_client(
ai_product="aio_stamphog",
team_id=team_id,
properties={"source_product": _SOURCE_PRODUCT},
@@ -855,8 +855,7 @@ def summarize_merged_prs(prs: list[PullRequest], audiences: list[PullRequestAudi
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.
+ # Messages shape: the Go gateway serves Claude models on this route only.
response = client.messages.create(
model=_DIGEST_MODEL,
max_tokens=max_tokens,
diff --git a/products/stamphog/backend/temporal/activities.py b/products/stamphog/backend/temporal/activities.py
index cf58d804dea9..61e58c06c8be 100644
--- a/products/stamphog/backend/temporal/activities.py
+++ b/products/stamphog/backend/temporal/activities.py
@@ -41,10 +41,9 @@ from temporalio import activity
from posthog.dataclasses import frozen
from posthog.llm.gateway_client import AIGatewayConfig, resolve_ai_gateway_config
-from posthog.models import OAuthAccessToken, User
+from posthog.models import 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
from products.stamphog.backend.facade.enums import (
TERMINAL_STATUSES,
@@ -169,18 +168,6 @@ def _connected_user(run: ReviewRun) -> User:
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 _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.
@@ -247,35 +234,30 @@ def _mint_reviewer_scoped_token(gateway: AIGatewayConfig, run: ReviewRun, user:
)
-def _release_reviewer_token(gateway: AIGatewayConfig | None, token: str) -> None:
+def _release_reviewer_token(gateway: AIGatewayConfig, 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.
+ A failure only logs (the token then expires) and never changes the run's outcome.
"""
try:
- if gateway is None:
- deleted, _ = OAuthAccessToken.objects.filter(token=token).delete()
- outcome = "ok" if deleted else "no such token"
+ 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:
- 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"
+ # 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]:
+def _reviewer_environment(run: ReviewRun) -> tuple[dict[str, str], AIGatewayConfig]:
"""Environment for the in-sandbox reviewer.
The sandbox holds no GitHub token by design, and no long-lived LLM credential either: the only
@@ -284,11 +266,9 @@ def _reviewer_environment(run: ReviewRun) -> tuple[dict[str, str], AIGatewayConf
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.
+ ``AI_GATEWAY_URL`` and ``AI_GATEWAY_API_KEY`` name the Go ai-gateway and the worker's ``phs_``;
+ the token is a per-run ``phe_`` the caller revokes once the sandbox is gone. The sandbox sees
+ the same two names with the token in place of the key.
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
@@ -296,33 +276,20 @@ def _reviewer_environment(run: ReviewRun) -> tuple[dict[str, str], AIGatewayConf
added to _llm_env_secrets so persisted output stays tidy. STAMPHOG_EXTRA_PROPERTIES stamps the
hosted runtime/team/run context onto those events.
"""
- # 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)
- )
+ gateway = resolve_ai_gateway_config()
+ if gateway is None:
+ raise RuntimeError(
+ "AI_GATEWAY_URL and AI_GATEWAY_API_KEY must both be set; hosted reviews require the ai-gateway"
+ )
+ 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"
+ )
+ token = _mint_reviewer_scoped_token(gateway, run, _connected_user(run))
env = {
"STAMPHOG_REPO_DIR": STAMPHOG_SANDBOX_REPO_DIR,
- "AI_GATEWAY_URL": gateway_url,
+ "AI_GATEWAY_URL": gateway.url,
"AI_GATEWAY_API_KEY": token,
}
for key in ("POSTHOG_API_KEY", "POSTHOG_HOST"):
diff --git a/products/stamphog/backend/tests/conftest.py b/products/stamphog/backend/tests/conftest.py
index 03f3efa7933b..8a6f88425016 100644
--- a/products/stamphog/backend/tests/conftest.py
+++ b/products/stamphog/backend/tests/conftest.py
@@ -4,17 +4,15 @@ from dataclasses import dataclass
from typing import Any
import pytest
-from unittest.mock import patch
+from unittest.mock import MagicMock, patch
from django.test import Client, override_settings
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import rsa
-from posthog.models import OAuthApplication
from posthog.models.scoping import team_scope
from posthog.temporal.common.errors import describe_failure
-from posthog.temporal.oauth import ARRAY_APP_CLIENT_ID_DEV, ARRAY_APP_CLIENT_ID_EU, ARRAY_APP_CLIENT_ID_US
from products.stamphog.backend.temporal.activities import (
MarkReviewFailedInput,
@@ -94,6 +92,20 @@ def _generate_app_private_key() -> str:
).decode()
+def _fake_gateway_post(url: str, **kwargs: Any) -> MagicMock:
+ """The ai-gateway's token routes; any other POST through the shared requests module fails loudly."""
+ response = MagicMock(text="")
+ if url.endswith("/v1/tokens"):
+ response.status_code = 201
+ response.json.return_value = {"token": "phe_test_run", "expires_at": "2026-01-01T00:00:00Z", "cap_usd": "5"}
+ elif url.endswith("/v1/tokens/revoke"):
+ response.status_code = 200
+ response.json.return_value = {"revoked": True}
+ else:
+ raise AssertionError(f"unexpected POST through the faked gateway client: {url}")
+ return response
+
+
def _run_activity(activity_fn: Any, arg: Any) -> Any:
"""Run a stamphog activity's plain sync body in-thread.
@@ -166,20 +178,6 @@ def stamphog_chain() -> Iterator[StamphogChain]:
# review-guidance.md is a required trusted policy file — run_review_in_sandbox fails closed without
# it — so seed it for the whole chain; individual tests still set/override policy.yml as they need.
recorder.policy_files[".stamphog/review-guidance.md"] = "Review PostHog PRs against the repo's norms.\n"
- # The review activity mints a real sandbox OAuth token under the Array app, which resolves by
- # region client id — seed every region so get_instance_region()'s value doesn't matter here.
- for client_id in (ARRAY_APP_CLIENT_ID_DEV, ARRAY_APP_CLIENT_ID_US, ARRAY_APP_CLIENT_ID_EU):
- OAuthApplication.objects.get_or_create(
- client_id=client_id,
- defaults={
- "name": "Array Test App",
- "client_type": OAuthApplication.CLIENT_PUBLIC,
- "authorization_grant_type": OAuthApplication.GRANT_AUTHORIZATION_CODE,
- "redirect_uris": "https://app.posthog.com/callback",
- # RS256 is enforced by the `enforce_rs256_algorithm` DB constraint.
- "algorithm": "RS256",
- },
- )
fake_slack = fakes.FakeSlackIntegration
fake_slack.reset(channels=[])
sandbox_writes: list[tuple[str, bytes]] = []
@@ -193,9 +191,12 @@ def stamphog_chain() -> Iterator[StamphogChain]:
STAMPHOG_GITHUB_APP_PRIVATE_KEY=_generate_app_private_key(),
)
)
- # 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"))
+ # The pair selects the Go ai-gateway and its token routes are faked; tests asserting on the
+ # mint re-patch requests.post.
+ stack.enter_context(
+ override_settings(AI_GATEWAY_URL="https://ai-gateway.test/v1", AI_GATEWAY_API_KEY="phs_test_mint")
+ )
+ stack.enter_context(patch("products.stamphog.backend.temporal.activities.requests.post", _fake_gateway_post))
# 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"))
@@ -232,7 +233,7 @@ def stamphog_chain() -> Iterator[StamphogChain]:
stack.enter_context(patch("posthog.team_notifications.slack.SlackIntegration", fake_slack))
stack.enter_context(
patch(
- "products.stamphog.backend.logic.digest.build_anthropic_client",
+ "products.stamphog.backend.logic.digest.build_ai_gateway_anthropic_client",
side_effect=RuntimeError("no gateway in tests"),
)
)
diff --git a/products/stamphog/backend/tests/test_digest.py b/products/stamphog/backend/tests/test_digest.py
index bcfbb5934031..ca635ff2e425 100644
--- a/products/stamphog/backend/tests/test_digest.py
+++ b/products/stamphog/backend/tests/test_digest.py
@@ -9,6 +9,7 @@ from unittest.mock import MagicMock, patch
from django.db import OperationalError
from django.db.models import QuerySet
+from django.test import override_settings
from django.utils import timezone
from parameterized import parameterized
@@ -730,7 +731,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.build_anthropic_client", return_value=client):
+ with patch("products.stamphog.backend.logic.digest.build_ai_gateway_anthropic_client", return_value=client):
summary = summarize_merged_prs(prs)
assert [p.pr_number for p in summary.prs] == [1]
@@ -754,7 +755,7 @@ def test_a_headline_failure_keeps_the_judged_digest() -> None:
client = _recording_llm_client(answers)
- with patch("products.stamphog.backend.logic.digest.build_anthropic_client", return_value=client):
+ with patch("products.stamphog.backend.logic.digest.build_ai_gateway_anthropic_client", return_value=client):
summary = summarize_merged_prs(prs)
assert summary.judged is True
@@ -771,17 +772,18 @@ def test_a_headline_failure_keeps_the_judged_digest() -> None:
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.
+ # output ceiling the shape requires.
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:
+ with patch(
+ "products.stamphog.backend.logic.digest.build_ai_gateway_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"},
@@ -828,7 +830,7 @@ def test_a_merge_that_only_grazed_the_team_never_reaches_the_model(
)
client = _recording_llm_client([selection, json.dumps({"headline": "Something shipped."})])
- with patch("products.stamphog.backend.logic.digest.build_anthropic_client", return_value=client):
+ with patch("products.stamphog.backend.logic.digest.build_ai_gateway_anthropic_client", return_value=client):
summary = summarize_merged_prs([grazed, owned], audiences)
assert ("Swept in" in client.prompts[0]) is not dropped
@@ -879,7 +881,7 @@ def test_a_line_about_another_teams_half_of_a_merge_is_dropped(
)
client = _recording_llm_client([selection, json.dumps({"headline": "Something shipped."})])
- with patch("products.stamphog.backend.logic.digest.build_anthropic_client", return_value=client):
+ with patch("products.stamphog.backend.logic.digest.build_ai_gateway_anthropic_client", return_value=client):
summary = summarize_merged_prs([partly, ours], [audience, _audience(2)])
ours_line = (2, "Our own area changed.")
@@ -973,7 +975,7 @@ def test_a_merge_the_reviewer_wrote_this_team_no_clause_for_never_reaches_the_mo
)
client = _recording_llm_client([selection, json.dumps({"headline": "Something shipped."})])
- with patch("products.stamphog.backend.logic.digest.build_anthropic_client", return_value=client):
+ with patch("products.stamphog.backend.logic.digest.build_ai_gateway_anthropic_client", return_value=client):
summary = summarize_merged_prs([unaddressed, ours], [_audience(3), _audience(2)])
assert "Somebody else's half" not in client.prompts[0]
@@ -1027,7 +1029,8 @@ def test_a_model_outage_posts_a_short_plain_list_and_says_it_judged_nothing() ->
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.build_anthropic_client", side_effect=RuntimeError("gateway down")
+ "products.stamphog.backend.logic.digest.build_ai_gateway_anthropic_client",
+ side_effect=RuntimeError("gateway down"),
):
summary = summarize_merged_prs(prs)
@@ -1037,6 +1040,23 @@ def test_a_model_outage_posts_a_short_plain_list_and_says_it_judged_nothing() ->
assert summary.headline == ""
+@override_settings(
+ AI_GATEWAY_URL="", AI_GATEWAY_API_KEY="", LLM_GATEWAY_URL="http://llm-gateway.test", LLM_GATEWAY_API_KEY="phx_test"
+)
+def test_without_the_ai_gateway_the_digest_never_reaches_the_python_gateway() -> None:
+ # The legacy gateway has no stamphog route, so a process without the Go pair posts the plain list
+ # even when a Python-gateway client would have answered.
+ 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("posthog.llm.gateway_client.get_anthropic_gateway_client", return_value=client) as python_gateway:
+ summary = summarize_merged_prs(prs)
+
+ assert summary.judged is False
+ python_gateway.assert_not_called()
+ assert client.calls == []
+
+
def test_same_pr_number_across_repos_both_survive_summarization() -> None:
# A team digest spans repos, where PR numbers repeat. Keying by bare pr_number collapsed
# acme/a#123 and acme/b#123 into one entry (the dict held one row) and the LLM path could only
@@ -1056,7 +1076,7 @@ def test_same_pr_number_across_repos_both_survive_summarization() -> None:
)
with patch(
- "products.stamphog.backend.logic.digest.build_anthropic_client",
+ "products.stamphog.backend.logic.digest.build_ai_gateway_anthropic_client",
return_value=_recording_llm_client([selection, json.dumps({"headline": "Both repos changed."})]),
):
summary = summarize_merged_prs(prs)
@@ -1182,7 +1202,8 @@ def test_the_headline_reaches_the_channel_as_one_link_free_paragraph(raw_headlin
json.dumps({"headline": raw_headline}),
]
with patch(
- "products.stamphog.backend.logic.digest.build_anthropic_client", return_value=_recording_llm_client(contents)
+ "products.stamphog.backend.logic.digest.build_ai_gateway_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
diff --git a/products/stamphog/backend/tests/test_integration.py b/products/stamphog/backend/tests/test_integration.py
index 58ef74b260ec..32b28fe5bb8a 100644
--- a/products/stamphog/backend/tests/test_integration.py
+++ b/products/stamphog/backend/tests/test_integration.py
@@ -424,58 +424,6 @@ def test_a_retry_finishes_a_notice_the_previous_attempt_never_posted(team, stamp
assert len([w for w in stamphog_chain.recorder.github_writes if w["kind"] == "comment_review"]) == 1
[email protected]_db(databases=PRODUCT_DATABASES)
-def test_sandbox_gets_minted_short_lived_credential_and_closed_egress(
- team, user, stamphog_chain: StamphogChain
-) -> None:
- # The sandbox runs an LLM over untrusted PR content, so it must never hold a long-lived
- # credential: no raw Anthropic key, not the worker's own gateway key — only a per-run OAuth
- # token minted under the connecting user — and its egress must be fenced to the hosts a
- # review needs, so a prompt-injected reviewer has nowhere to exfiltrate to.
- _repo_config(team.id)
- recorder = stamphog_chain.recorder
- head_sha = "sha110a"
- recorder.register_pr(REPO, 110, _pr_object(110, "devex-dev", head_sha), _pr_files())
- 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"}
- # 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]
- env = config.environment_variables
- assert "ANTHROPIC_API_KEY" not in env
- assert env["AI_GATEWAY_API_KEY"] != "phs_worker_shared_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
- # (task:write from the internal bundle) must never ride into the sandbox.
- 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
- assert "sha110a" not in config.outbound_domain_allowlist # sanity: it's a domain list, not env spill
-
-
@pytest.mark.django_db(databases=PRODUCT_DATABASES)
def test_hosted_review_fails_closed_without_connecting_user(team, stamphog_chain: StamphogChain) -> None:
# A repo whose installation was never synced has no identity to mint sandbox credentials
@@ -673,7 +621,6 @@ def test_sandbox_gets_a_scoped_gateway_token_when_the_go_gateway_is_configured(
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
@pytest.mark.django_db(databases=PRODUCT_DATABASES)
@@ -720,33 +667,10 @@ def test_scoped_token_mint_does_not_retry_a_credential_rejection(team, stamphog_
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
-
-
@pytest.mark.django_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.
+ # A key-only rollback or a URL flip ahead of its key leaves the Go URL with no key; hosted runs
+ # have no other credential path, so the run fails before any sandbox exists.
_repo_config(team.id)
event = _register_review(stamphog_chain, 121, "sha121a")
mint = MagicMock()
@@ -759,7 +683,7 @@ def test_a_go_gateway_url_without_a_key_fails_closed(team, user, stamphog_chain:
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 "AI_GATEWAY_API_KEY" 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()
@@ -2411,21 +2335,6 @@ def test_an_ineffective_revoke_is_logged(team, stamphog_chain: StamphogChain) ->
)
[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()
-
-
@pytest.mark.django_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
diff --git a/services/llm-gateway/src/llm_gateway/products/config.py b/services/llm-gateway/src/llm_gateway/products/config.py
index 1807fc8376db..ed2b9f4f2329 100644
--- a/services/llm-gateway/src/llm_gateway/products/config.py
+++ b/services/llm-gateway/src/llm_gateway/products/config.py
@@ -370,27 +370,6 @@ PRODUCTS: Final[dict[str, ProductConfig]] = {
allow_api_keys=True,
credit_bucket=None,
),
- # Stamphog: the sandboxed PR reviewer (Sonnet, OAuth-only in practice) and the daily merged-PR
- # digest summarization (Haiku, server-side via the shared key). Low volume, internal infra.
- # The reviewer runs inside a sandbox over untrusted PR content, so it authenticates with a
- # short-lived server-minted OAuth token under the shared sandbox app — hence the app allowlist.
- # allow_api_keys stays True only for the digest's server-side calls (the shared key never
- # enters a sandbox); it can flip off once the digest mints tokens too.
- # Deliberately unbilled, same posture as review_hog/conversations: reviews and digests are work
- # done by PostHog, not customer-billable usage, and the worker attributes spend per customer team
- # via the team_id header — a credit_bucket here would silently charge customer AI credits for it.
- # The trade-off (any personal API key can reach an unbilled route) is shared by every
- # key-accessible unbilled product in this table and is bounded by the model pins.
- # requires_server_credential closes the OAuth side of that class: reviewer tokens are minted
- # server-side with the internal marker, so a user's own Desktop OAuth token can't ride this route
- # around the posthog_code free-tier gate.
- "stamphog": ProductConfig(
- allowed_application_ids=frozenset({POSTHOG_CODE_US_APP_ID, POSTHOG_CODE_EU_APP_ID, POSTHOG_CODE_DEV_APP_ID}),
- allowed_models=frozenset({"claude-haiku-4-5", "claude-sonnet-5"}),
- allow_api_keys=True,
- credit_bucket=None,
- requires_server_credential=True,
- ),
}
diff --git a/services/llm-gateway/tests/test_model_registry.py b/services/llm-gateway/tests/test_model_registry.py
index 7770ad8f5280..ad8f4602197e 100644
--- a/services/llm-gateway/tests/test_model_registry.py
+++ b/services/llm-gateway/tests/test_model_registry.py
@@ -442,7 +442,6 @@ class TestIsModelAvailable:
("onboarding", False),
("product_analytics", False),
("review_hog", True),
- ("stamphog", False),
],
)
def test_gpt_6_astra_respects_product_allowlists(self, product: str, expected: bool) -> None:
diff --git a/services/llm-gateway/tests/test_product_config.py b/services/llm-gateway/tests/test_product_config.py
index e229778e21ff..7150ec6931f5 100644
--- a/services/llm-gateway/tests/test_product_config.py
+++ b/services/llm-gateway/tests/test_product_config.py
@@ -400,7 +400,6 @@ class TestCheckProductAccess:
[
"llma_labeling",
"product_analytics",
- "stamphog",
"subscriptions",
"warehouse_custom_source_builder",
"warehouse_semantic_enrichment",