Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(signals): use service gateway credentials for scout trials (#112511)

Alex Lebedev9d295821b9ef
diff --git a/docs/internal/scout-online-evals-devbox.md b/docs/internal/scout-online-evals-devbox.md
index 89040e7ad1e9..46830700f7a7 100644
--- a/docs/internal/scout-online-evals-devbox.md
+++ b/docs/internal/scout-online-evals-devbox.md
@@ -14,7 +14,7 @@ Follow the existing [devbox setup](../../.agents/skills/setting-up-devbox/SKILL.
## Configuration
-Deploy support for private scoped tokens (`capture_mode: none`) to every gateway replica before enabling trials. Set these on the backend and Temporal worker:
+Deploy support for private scoped tokens (`capture_mode: none`) to every gateway replica before enabling trials. Configure the local stack as follows; service-specific credentials are described below:
```dotenv
SANDBOX_PROVIDER=docker
@@ -30,7 +30,8 @@ Enable the `scout-trials` feature flag for the `project` group with `id = 2`. A
Switching the flag off blocks new trials, resumes, and queued scout or judge work. Already-running scouts and judge jobs can finish, and saved results remain readable. After re-enabling the flag, resume interrupted trials to recover saved work.
Verify the ports and Docker host mapping. Sandbox URLs and MCP's `POSTHOG_API_BASE_URL` must reach services directly, without the Coder login proxy. Keep `POSTHOG_PUBLIC_URL` and `SITE_URL` on the browser URL.
-Set `SANDBOX_AI_GATEWAY_MINT_KEY` privately to a server credential authorized for team attribution in the intended paying project. The `signals_scout` product must not bill customer credits.
+The backend and scout orchestration worker use their existing `AI_GATEWAY_URL` and `AI_GATEWAY_API_KEY`. Private report checks mint and revoke temporary tokens with that service credential. Only the Tasks worker that provisions sandboxes needs `SANDBOX_AI_GATEWAY_URL` and `SANDBOX_AI_GATEWAY_MINT_KEY`. Both credentials must allow private token creation and team attribution in the intended paying project. The `signals_scout` product must not bill customer credits.
+API-side token calls bypass environment proxies, matching the other service gateway clients. Sandbox token calls keep their existing proxy behavior.
Enable `SCOUT_LIVE_TRIALS_PRIVATE_CAPTURE` only after confirming query/task telemetry and warehouse replicas do not expose trial content to the inspected project. The gateway must acknowledge capture suppression when minting tokens.
This setting also installs the private-trial analytics filter when backend and worker processes start. Leave it enabled while saved trial data remains accessible, even after disabling new launches or the `scout-trials` flag. Deployments without this setting keep their existing analytics callbacks.
Keep the worker and backend on the same code revision; use `TEMPORAL_DISABLE_HOT_RELOAD=1` during paid runs.
diff --git a/products/signals/backend/scout_harness/trial_gateway.py b/products/signals/backend/scout_harness/trial_gateway.py
index b2a0cb6b557f..b90e7a4e65cf 100644
--- a/products/signals/backend/scout_harness/trial_gateway.py
+++ b/products/signals/backend/scout_harness/trial_gateway.py
@@ -1,4 +1,6 @@
-from posthog.llm.gateway_client import GatewayNotConfiguredError, ensure_scout_trial_capture_ready
+from django.conf import settings
+
+from posthog.llm.gateway_client import AIGatewayConfig, GatewayNotConfiguredError, ensure_scout_trial_capture_ready
from posthog.models import User
from products.access_control.backend.facade.user_access_control import UserAccessControl
@@ -26,8 +28,15 @@ def create_trial_gateway_token(run: SignalScoutRun) -> str:
).first()
if actor is None or not UserAccessControl(user=actor, team=task.team).has_project_access:
raise GatewayNotConfiguredError("The scout trial operator no longer has access to this project")
- return mint_private_gateway_token(team_id=run.team_id, user=actor.distinct_id, expires_in_seconds=600)
+ return mint_private_gateway_token(
+ team_id=run.team_id,
+ user=actor.distinct_id,
+ expires_in_seconds=600,
+ gateway_config=AIGatewayConfig(url=settings.AI_GATEWAY_URL, api_key=settings.AI_GATEWAY_API_KEY),
+ )
def revoke_trial_gateway_token(token: str) -> None:
- revoke_private_gateway_token(token)
+ revoke_private_gateway_token(
+ token, gateway_config=AIGatewayConfig(url=settings.AI_GATEWAY_URL, api_key=settings.AI_GATEWAY_API_KEY)
+ )
diff --git a/products/signals/backend/scout_harness/trial_launch.py b/products/signals/backend/scout_harness/trial_launch.py
index 6972084bde99..0107c98cca90 100644
--- a/products/signals/backend/scout_harness/trial_launch.py
+++ b/products/signals/backend/scout_harness/trial_launch.py
@@ -166,8 +166,8 @@ def assert_trial_environment_ready() -> None:
ensure_scout_trial_capture_ready()
except GatewayNotConfiguredError as error:
raise ScoutTrialLaunchError(str(error)) from None
- if not (settings.SANDBOX_AI_GATEWAY_URL and settings.SANDBOX_AI_GATEWAY_MINT_KEY):
- raise ScoutTrialLaunchError("Scout trials require the Go sandbox gateway URL and mint credential.")
+ if not settings.AI_GATEWAY_API_KEY:
+ raise ScoutTrialLaunchError("Scout trials require AI_GATEWAY_API_KEY for private report checks.")
def load_trial_context(team_id: int, context_id: UUID | str) -> TrialContext:
diff --git a/products/signals/backend/test/test_scout_harness.py b/products/signals/backend/test/test_scout_harness.py
index d4ec6950072f..e55a94e3319e 100644
--- a/products/signals/backend/test/test_scout_harness.py
+++ b/products/signals/backend/test/test_scout_harness.py
@@ -1682,6 +1682,7 @@ async def test_successful_run_creates_bridge_row_pointing_at_task_run(
@override_settings(
SCOUT_LIVE_TRIALS_PRIVATE_CAPTURE=True,
AI_GATEWAY_URL="https://gateway.example/v1",
+ AI_GATEWAY_API_KEY="phs_synthetic_api_key",
SANDBOX_AI_GATEWAY_URL="https://gateway.example",
SANDBOX_AI_GATEWAY_MINT_KEY="phs_synthetic_mint_key",
)
diff --git a/products/signals/backend/test/test_scout_trial_evaluation.py b/products/signals/backend/test/test_scout_trial_evaluation.py
index f08b978cb96f..27e7ea2d26fa 100644
--- a/products/signals/backend/test/test_scout_trial_evaluation.py
+++ b/products/signals/backend/test/test_scout_trial_evaluation.py
@@ -98,6 +98,7 @@ WORKFLOW_MODULE = "products.signals.backend.temporal.agentic.scout_trial_evaluat
@override_settings(
SCOUT_LIVE_TRIALS_PRIVATE_CAPTURE=True,
AI_GATEWAY_URL="https://gateway.example/v1",
+ AI_GATEWAY_API_KEY="phs_synthetic_api_key",
SANDBOX_AI_GATEWAY_URL="https://gateway.example",
SANDBOX_AI_GATEWAY_MINT_KEY="phs_synthetic_mint_key",
)
@@ -156,6 +157,7 @@ class TestScoutTrialEvaluationValidation(SimpleTestCase):
@override_settings(
SCOUT_LIVE_TRIALS_PRIVATE_CAPTURE=True,
AI_GATEWAY_URL="https://gateway.example/v1",
+ AI_GATEWAY_API_KEY="phs_synthetic_api_key",
SANDBOX_AI_GATEWAY_URL="https://gateway.example",
SANDBOX_AI_GATEWAY_MINT_KEY="phs_synthetic_mint_key",
)
diff --git a/products/signals/backend/test/test_scout_trial_state.py b/products/signals/backend/test/test_scout_trial_state.py
index 4fac8d0f9c83..e528128486b8 100644
--- a/products/signals/backend/test/test_scout_trial_state.py
+++ b/products/signals/backend/test/test_scout_trial_state.py
@@ -16,7 +16,7 @@ from asgiref.sync import async_to_sync
from parameterized import parameterized
from pydantic import JsonValue
-from posthog.llm.gateway_client import GatewayNotConfiguredError
+from posthog.llm.gateway_client import AIGatewayConfig, GatewayNotConfiguredError
from posthog.models import Team
from posthog.models.scoping import team_scope
@@ -164,7 +164,13 @@ class TestScoutTrialState(APIBaseTest):
assert store.search_memory(key="new", content_max_chars=8)[0].content == "Checkout"
-@override_settings(SCOUT_LIVE_TRIALS_PRIVATE_CAPTURE=True, AI_GATEWAY_URL="https://gateway.example/v1")
+@override_settings(
+ SCOUT_LIVE_TRIALS_PRIVATE_CAPTURE=True,
+ AI_GATEWAY_URL="https://gateway.example/v1",
+ AI_GATEWAY_API_KEY="phs_synthetic_api_key",
+ SANDBOX_AI_GATEWAY_URL=None,
+ SANDBOX_AI_GATEWAY_MINT_KEY=None,
+)
class TestScoutTrialReportCapture(APIBaseTest):
def setUp(self) -> None:
super().setUp()
@@ -230,11 +236,12 @@ class TestScoutTrialReportCapture(APIBaseTest):
def test_gateway_credential_is_narrow_and_revoked_after_safety_failure(self) -> None:
token = create_trial_gateway_token(self.scout_run)
assert token == "phe_synthetic_private_token"
+ gateway_config = AIGatewayConfig(url="https://gateway.example/v1", api_key="phs_synthetic_api_key")
self.gateway_mint.assert_called_once_with(
- team_id=self.team.id, user=self.user.distinct_id, expires_in_seconds=600
+ team_id=self.team.id, user=self.user.distinct_id, expires_in_seconds=600, gateway_config=gateway_config
)
revoke_trial_gateway_token(token)
- self.gateway_revoke.assert_called_once_with(token)
+ self.gateway_revoke.assert_called_once_with(token, gateway_config=gateway_config)
self.gateway_mint.reset_mock()
self.gateway_revoke.reset_mock()
@@ -242,7 +249,7 @@ class TestScoutTrialReportCapture(APIBaseTest):
with self.assertRaisesRegex(RuntimeError, "Synthetic safety failure"):
self._emit()
self.gateway_mint.assert_called_once()
- self.gateway_revoke.assert_called_once_with(token)
+ self.gateway_revoke.assert_called_once_with(token, gateway_config=gateway_config)
@parameterized.expand(["untrusted_run", "revoked_actor", "revoked_membership"])
def test_gateway_credential_rejects_invalid_trial_identity(self, condition: str) -> None:
diff --git a/products/signals/backend/test/test_scout_trials_api.py b/products/signals/backend/test/test_scout_trials_api.py
index f4d5d9128793..eb3660432654 100644
--- a/products/signals/backend/test/test_scout_trials_api.py
+++ b/products/signals/backend/test/test_scout_trials_api.py
@@ -233,8 +233,9 @@ class TestScoutTrialAPI(APIBaseTest):
@override_settings(
SCOUT_LIVE_TRIALS_PRIVATE_CAPTURE=True,
AI_GATEWAY_URL="https://gateway.example/v1",
- SANDBOX_AI_GATEWAY_URL="https://gateway.example",
- SANDBOX_AI_GATEWAY_MINT_KEY="phs_synthetic_mint_key",
+ AI_GATEWAY_API_KEY="phs_synthetic_api_key",
+ SANDBOX_AI_GATEWAY_URL=None,
+ SANDBOX_AI_GATEWAY_MINT_KEY=None,
)
class TestScoutTrialLaunch(APIBaseTest):
def setUp(self) -> None:
@@ -350,8 +351,7 @@ class TestScoutTrialLaunch(APIBaseTest):
[
("SCOUT_LIVE_TRIALS_PRIVATE_CAPTURE", False, "Private capture"),
("AI_GATEWAY_URL", "", "AI_GATEWAY_URL"),
- ("SANDBOX_AI_GATEWAY_URL", "", "Go sandbox gateway"),
- ("SANDBOX_AI_GATEWAY_MINT_KEY", "", "mint credential"),
+ ("AI_GATEWAY_API_KEY", "", "AI_GATEWAY_API_KEY"),
]
)
def test_setup_remains_readable_when_unavailable_and_excludes_inaccessible_models(
diff --git a/products/tasks/backend/facade/gateway.py b/products/tasks/backend/facade/gateway.py
index 249223e9057d..1a86276f36ef 100644
--- a/products/tasks/backend/facade/gateway.py
+++ b/products/tasks/backend/facade/gateway.py
@@ -1,3 +1,4 @@
+from typing import TYPE_CHECKING
from uuid import UUID
from posthog.llm.gateway_client import GatewayNotConfiguredError
@@ -5,8 +6,17 @@ from posthog.llm.gateway_client import GatewayNotConfiguredError
from products.tasks.backend.logic.services.gateway_usage import record_generation_request, schedule_gateway_usage
from products.tasks.backend.models import TaskRun
+if TYPE_CHECKING:
+ from posthog.llm.gateway_client import AIGatewayConfig
-def mint_private_gateway_token(*, team_id: int, user: str | None = None, expires_in_seconds: int | None = None) -> str:
+
+def mint_private_gateway_token(
+ *,
+ team_id: int,
+ user: str | None = None,
+ expires_in_seconds: int | None = None,
+ gateway_config: "AIGatewayConfig | None" = None,
+) -> str:
from products.tasks.backend.temporal.process_task.ai_gateway_token import ( # noqa: PLC0415 -- breaks the Temporal aggregate's import cycle through process_task.utils
mint_scoped_token,
)
@@ -17,18 +27,19 @@ def mint_private_gateway_token(*, team_id: int, user: str | None = None, expires
user=user,
capture_mode="none",
expires_in_seconds=expires_in_seconds,
+ gateway_config=gateway_config,
)
if token is None:
raise GatewayNotConfiguredError("Scout trials require a private AI gateway credential")
return token
-def revoke_private_gateway_token(token: str) -> None:
+def revoke_private_gateway_token(token: str, *, gateway_config: "AIGatewayConfig | None" = None) -> None:
from products.tasks.backend.temporal.process_task.ai_gateway_token import ( # noqa: PLC0415 -- breaks the Temporal aggregate's import cycle through process_task.utils
revoke_scoped_token,
)
- revoke_scoped_token(token)
+ revoke_scoped_token(token, gateway_config=gateway_config)
def accept_generation_request(*, team_id: int, run_id: UUID, request_id: str) -> bool:
diff --git a/products/tasks/backend/temporal/process_task/ai_gateway_token.py b/products/tasks/backend/temporal/process_task/ai_gateway_token.py
index f8820a72ab2b..494ad975f9bb 100644
--- a/products/tasks/backend/temporal/process_task/ai_gateway_token.py
+++ b/products/tasks/backend/temporal/process_task/ai_gateway_token.py
@@ -19,6 +19,7 @@ import requests
from prometheus_client import Counter
from posthog.llm.gateway_client import GatewayNotConfiguredError
+from posthog.security.outbound_proxy import internal_requests
from products.tasks.backend.logic.services.desktop_gateway_token import (
POSTHOG_CODE_PRODUCT,
@@ -40,6 +41,7 @@ from products.tasks.backend.logic.services.run_actor import is_slack_interaction
from products.tasks.backend.logic.services.sandbox_config import MAX_SANDBOX_TTL_SECONDS
if TYPE_CHECKING:
+ from posthog.llm.gateway_client import AIGatewayConfig
from posthog.models.team.team import Team
logger = logging.getLogger(__name__)
@@ -308,14 +310,16 @@ def token_cap_usd(team_id: int, ai_product: str) -> str:
return str(settings.SANDBOX_AI_GATEWAY_TOKEN_CAP_USD)
-def revoke_scoped_token(token: str) -> None:
- base_url = (settings.SANDBOX_AI_GATEWAY_URL or "").rstrip("/").removesuffix("/v1")
- mint_key = settings.SANDBOX_AI_GATEWAY_MINT_KEY
+def revoke_scoped_token(token: str, *, gateway_config: "AIGatewayConfig | None" = None) -> None:
+ gateway_url = gateway_config.url if gateway_config is not None else settings.SANDBOX_AI_GATEWAY_URL
+ base_url = (gateway_url or "").rstrip("/").removesuffix("/v1")
+ mint_key = gateway_config.api_key if gateway_config is not None else settings.SANDBOX_AI_GATEWAY_MINT_KEY
if not base_url or not mint_key:
raise GatewayNotConfiguredError("The AI gateway mint configuration is required to revoke a private token")
+ post = internal_requests.post if gateway_config is not None else requests.post
for attempt in range(_MINT_ATTEMPTS):
try:
- response = requests.post(
+ response = post(
f"{base_url}/v1/tokens/revoke",
json={"token": token},
headers={"Authorization": f"Bearer {mint_key}"},
@@ -348,6 +352,7 @@ def mint_scoped_token(
limit_tier: str | None = None,
capture_mode: Literal["none"] | None = None,
expires_in_seconds: int | None = None,
+ gateway_config: "AIGatewayConfig | None" = None,
) -> str | None:
"""Mint a `phe_` scoped token pinned to (ai_product, obo=team_id), or None on failure.
@@ -357,10 +362,12 @@ def mint_scoped_token(
Retries mint rate limits (429) and transient upstream errors with jittered
backoff. Private callers require an acknowledged capture pin and fail closed on None.
"""
- base_url = (settings.SANDBOX_AI_GATEWAY_URL or "").rstrip("/").removesuffix("/v1")
- mint_key = settings.SANDBOX_AI_GATEWAY_MINT_KEY
+ gateway_url = gateway_config.url if gateway_config is not None else settings.SANDBOX_AI_GATEWAY_URL
+ base_url = (gateway_url or "").rstrip("/").removesuffix("/v1")
+ mint_key = gateway_config.api_key if gateway_config is not None else settings.SANDBOX_AI_GATEWAY_MINT_KEY
if not base_url or not mint_key:
return None
+ post = internal_requests.post if gateway_config is not None else requests.post
body: dict[str, Any] = {
"cap_usd": token_cap_usd(team_id, ai_product),
@@ -382,7 +389,7 @@ def mint_scoped_token(
last_error: str = ""
for attempt in range(_MINT_ATTEMPTS):
try:
- response = requests.post(
+ response = post(
f"{base_url}/v1/tokens",
json=body,
headers={"Authorization": f"Bearer {mint_key}"},
@@ -402,7 +409,7 @@ def mint_scoped_token(
if isinstance(token, str) and token:
if capture_mode is not None and payload.get("capture_mode") != capture_mode:
# Older gateways ignore unknown fields; never use their unprotected token.
- revoke_scoped_token(token)
+ revoke_scoped_token(token, gateway_config=gateway_config)
last_error = "mint response did not acknowledge capture suppression"
break
AI_GATEWAY_TOKEN_MINTS.labels(result="ok").inc()
diff --git a/products/tasks/backend/temporal/process_task/tests/test_ai_gateway_token.py b/products/tasks/backend/temporal/process_task/tests/test_ai_gateway_token.py
index 46853b8fa1fa..b569864c0a96 100644
--- a/products/tasks/backend/temporal/process_task/tests/test_ai_gateway_token.py
+++ b/products/tasks/backend/temporal/process_task/tests/test_ai_gateway_token.py
@@ -12,14 +12,18 @@ from unittest.mock import MagicMock, patch
from django.db import OperationalError
from django.test import override_settings
+import requests
+
from posthog.constants import AvailableFeature
-from posthog.llm.gateway_client import GatewayNotConfiguredError
+from posthog.llm.gateway_client import AIGatewayConfig, GatewayNotConfiguredError
from posthog.models import Organization, Team, User
+from posthog.security.outbound_proxy import internal_requests
from products.signals.backend.scout_harness.suggestions import SUGGESTIONS_AI_STAGE
from products.tasks.backend import model_catalog
from products.tasks.backend.constants import RESERVED_SANDBOX_ENVIRONMENT_VARIABLE_KEYS
from products.tasks.backend.facade.billing import get_task_run_cost
+from products.tasks.backend.facade.gateway import mint_private_gateway_token, revoke_private_gateway_token
from products.tasks.backend.logic.services.desktop_gateway_token import valid_caps
from products.tasks.backend.logic.services.gateway_model_pin import (
DESKTOP_AGENT_MODELS,
@@ -43,7 +47,6 @@ from products.tasks.backend.temporal.process_task.ai_gateway_token import (
mint_refusal,
mint_scoped_token,
resolve_sandbox_ai_product,
- revoke_scoped_token,
sandbox_product_routed,
token_cap_usd,
)
@@ -159,6 +162,18 @@ def mint_settings(settings):
return settings
+ params=[None, AIGatewayConfig(url="https://service-gateway.example.com/v1/", api_key="phs_test_service")],
+ ids=["sandbox-settings", "service-settings"],
+)
+def gateway_config(request: pytest.FixtureRequest, mint_settings: Settings) -> AIGatewayConfig | None:
+ config: AIGatewayConfig | None = request.param
+ if config is not None:
+ mint_settings.SANDBOX_AI_GATEWAY_URL = ""
+ mint_settings.SANDBOX_AI_GATEWAY_MINT_KEY = ""
+ return config
+
+
class TestMintScopedToken:
def _response(self, status_code=201, body=None):
response = MagicMock()
@@ -168,20 +183,19 @@ class TestMintScopedToken:
return response
@pytest.mark.parametrize("private", [False, True])
- def test_mints_pinned_token(self, mint_settings, private: bool) -> None:
- with patch("products.tasks.backend.temporal.process_task.ai_gateway_token.requests.post") as post:
+ def test_mints_pinned_token(self, mint_settings, private: bool, gateway_config: AIGatewayConfig | None) -> None:
+ with patch.object(internal_requests if gateway_config is not None else requests, "post") as post:
post.return_value = self._response(201, {"token": "phe_abc", "capture_mode": "none"})
- assert (
- mint_scoped_token(
- ai_product="signals_scout",
- team_id=123,
- capture_mode="none" if private else None,
- expires_in_seconds=600 if private else None,
- )
- == "phe_abc"
- )
+ token: str | None
+ if private:
+ token = mint_private_gateway_token(team_id=123, expires_in_seconds=600, gateway_config=gateway_config)
+ else:
+ token = mint_scoped_token(ai_product="signals_scout", team_id=123, gateway_config=gateway_config)
+ assert token == "phe_abc"
_, kwargs = post.call_args
- assert post.call_args[0][0] == "https://ai-gateway.dev.posthog.dev/v1/tokens"
+ expected_url = gateway_config.url.rstrip("/") if gateway_config else "https://ai-gateway.dev.posthog.dev/v1"
+ expected_key = gateway_config.api_key if gateway_config else "phs_test_mint"
+ assert post.call_args[0][0] == f"{expected_url}/tokens"
assert kwargs["json"] == {
"cap_usd": "3",
"ttl_seconds": 600 if private else 14400,
@@ -189,39 +203,80 @@ class TestMintScopedToken:
"obo": "123",
**({"capture_mode": "none"} if private else {}),
}
- assert kwargs["headers"] == {"Authorization": "Bearer phs_test_mint"}
+ assert kwargs["headers"] == {"Authorization": f"Bearer {expected_key}"}
assert kwargs["timeout"] == 3
@pytest.mark.parametrize("capture_mode", [None, "default", False])
- def test_private_mint_revokes_an_unacknowledged_token(self, mint_settings, capture_mode: object) -> None:
- with patch("products.tasks.backend.temporal.process_task.ai_gateway_token.requests.post") as post:
+ def test_private_mint_revokes_an_unacknowledged_token(
+ self, mint_settings, capture_mode: object, gateway_config: AIGatewayConfig | None
+ ) -> None:
+ with patch.object(internal_requests if gateway_config is not None else requests, "post") as post:
post.side_effect = [
self._response(201, {"token": "phe_ordinary", "capture_mode": capture_mode}),
self._response(200, {"revoked": True}),
]
- assert mint_scoped_token(ai_product="signals_scout", team_id=123, capture_mode="none") is None
+ assert (
+ mint_scoped_token(
+ ai_product="signals_scout", team_id=123, capture_mode="none", gateway_config=gateway_config
+ )
+ is None
+ )
assert post.call_count == 2
- assert post.call_args.args == ("https://ai-gateway.dev.posthog.dev/v1/tokens/revoke",)
+ expected_url = gateway_config.url.rstrip("/") if gateway_config else "https://ai-gateway.dev.posthog.dev/v1"
+ expected_key = gateway_config.api_key if gateway_config else "phs_test_mint"
+ assert post.call_args.args == (f"{expected_url}/tokens/revoke",)
assert post.call_args.kwargs["json"] == {"token": "phe_ordinary"}
- assert post.call_args.kwargs["headers"] == {"Authorization": "Bearer phs_test_mint"}
+ assert post.call_args.kwargs["headers"] == {"Authorization": f"Bearer {expected_key}"}
@pytest.mark.parametrize("status_code", [200, 403, 503])
- def test_revocation_reports_failure_without_token_details(self, mint_settings, status_code: int) -> None:
+ def test_revocation_reports_failure_without_token_details(
+ self, mint_settings, status_code: int, gateway_config: AIGatewayConfig | None
+ ) -> None:
with (
- patch("products.tasks.backend.temporal.process_task.ai_gateway_token.requests.post") as post,
+ patch.object(internal_requests if gateway_config is not None else requests, "post") as post,
patch("products.tasks.backend.temporal.process_task.ai_gateway_token.time.sleep"),
):
post.return_value = self._response(status_code, {"revoked": status_code == 200})
if status_code == 200:
- revoke_scoped_token("phe_private")
+ revoke_private_gateway_token("phe_private", gateway_config=gateway_config)
else:
with pytest.raises(
GatewayNotConfiguredError, match="^The private AI gateway credential could not be revoked$"
):
- revoke_scoped_token("phe_private")
+ revoke_private_gateway_token("phe_private", gateway_config=gateway_config)
+ expected_url = gateway_config.url.rstrip("/") if gateway_config else "https://ai-gateway.dev.posthog.dev/v1"
+ expected_key = gateway_config.api_key if gateway_config else "phs_test_mint"
+ assert post.call_args.args == (f"{expected_url}/tokens/revoke",)
+ assert post.call_args.kwargs["headers"] == {"Authorization": f"Bearer {expected_key}"}
assert post.call_args.kwargs["json"] == {"token": "phe_private"}
assert post.call_args.kwargs["allow_redirects"] is False
+ def test_service_token_requests_bypass_environment_proxy(
+ self, gateway_config: AIGatewayConfig | None, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ proxy = "http://proxy.example.com:3128"
+ for variable in ("HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "http_proxy", "https_proxy", "all_proxy"):
+ monkeypatch.setenv(variable, proxy)
+ for variable in ("NO_PROXY", "no_proxy"):
+ monkeypatch.delenv(variable, raising=False)
+ minted = requests.Response()
+ minted.status_code = 201
+ minted._content = b'{"token": "phe_test_private", "capture_mode": "none"}'
+ revoked = requests.Response()
+ revoked.status_code = 200
+ revoked._content = b'{"revoked": true}'
+ with patch("requests.adapters.HTTPAdapter.send", side_effect=[minted, revoked]) as send:
+ token = mint_private_gateway_token(team_id=123, gateway_config=gateway_config)
+ revoke_private_gateway_token(token, gateway_config=gateway_config)
+
+ assert send.call_count == 2
+ for call in send.call_args_list:
+ proxies = call.kwargs["proxies"]
+ if gateway_config is not None:
+ assert not proxies
+ else:
+ assert proxies["https"] == proxy
+
def test_review_hog_mint_carries_the_model_pin(self, mint_settings):
with patch("products.tasks.backend.temporal.process_task.ai_gateway_token.requests.post") as post:
post.return_value = self._response(201, {"token": "phe_abc"})