: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(tasks): authenticate custom image scans correctly (#73252)
Alessandro Pogliaghifa86afb865d5
diff --git a/posthog/llm/gateway_client.py b/posthog/llm/gateway_client.pyindex 868f2aec6988..96d4a9f35e93 100644--- a/posthog/llm/gateway_client.py+++ b/posthog/llm/gateway_client.py@@ -30,6 +30,7 @@ Product = Literal["subscriptions","signals","review_hog",+ "custom_image_scans","conversations","warehouse_semantic_enrichment","warehouse_custom_source_builder",@@ -41,7 +42,7 @@ def _team_id_header(team_id: int) -> dict[str, str]:return {"x-posthog-property-team_id": str(team_id)}-def get_llm_client(product: Product = "django", team_id: int | None = None) -> OpenAI:+def get_llm_client(product: Product = "django", team_id: int | None = None, api_key: str | None = None) -> OpenAI:"""Get an OpenAI-compatible client for the internal LLM gateway.@@ -89,14 +90,17 @@ def get_llm_client(product: Product = "django", team_id: int | None = None) -> Oteam_id: Optional PostHog team to attribute the captured `$ai_generation` event to.When provided, sent on every request as the `x-posthog-property-team_id` header;when omitted, the event is attributed to the gateway key owner's team.+ api_key: Optional short-lived credential to use instead of `LLM_GATEWAY_API_KEY`.+ Server-only products use this to avoid exposing the shared personal API key."""- if not settings.LLM_GATEWAY_URL or not settings.LLM_GATEWAY_API_KEY:- raise ValueError("LLM_GATEWAY_URL and LLM_GATEWAY_API_KEY must be configured")+ resolved_api_key = api_key or settings.LLM_GATEWAY_API_KEY+ if not settings.LLM_GATEWAY_URL or not resolved_api_key:+ raise ValueError("LLM_GATEWAY_URL and an API key must be configured")base_url = f"{settings.LLM_GATEWAY_URL.rstrip('/')}/{product}/v1"return OpenAI(base_url=base_url,- api_key=settings.LLM_GATEWAY_API_KEY,+ api_key=resolved_api_key,default_headers=_team_id_header(team_id) if team_id is not None else None,http_client=httpx.Client(trust_env=False),)diff --git a/posthog/llm/test_gateway_client.py b/posthog/llm/test_gateway_client.pyindex d50d80200a96..95587d784247 100644--- a/posthog/llm/test_gateway_client.py+++ b/posthog/llm/test_gateway_client.py@@ -31,7 +31,7 @@ class TestGetLlmClient:mock_settings.LLM_GATEWAY_URL = ""mock_settings.LLM_GATEWAY_API_KEY = "test-key"- with pytest.raises(ValueError, match="LLM_GATEWAY_URL and LLM_GATEWAY_API_KEY must be configured"):+ with pytest.raises(ValueError, match="LLM_GATEWAY_URL and an API key must be configured"):get_llm_client(product="django", team_id=1)@patch("posthog.llm.gateway_client.settings")@@ -39,7 +39,7 @@ class TestGetLlmClient:mock_settings.LLM_GATEWAY_URL = "http://gateway:8080"mock_settings.LLM_GATEWAY_API_KEY = ""- with pytest.raises(ValueError, match="LLM_GATEWAY_URL and LLM_GATEWAY_API_KEY must be configured"):+ with pytest.raises(ValueError, match="LLM_GATEWAY_URL and an API key must be configured"):get_llm_client(product="django", team_id=1)@patch("posthog.llm.gateway_client.settings")@@ -52,6 +52,15 @@ class TestGetLlmClient:assert str(client.base_url) == "http://gateway:8080/django/v1/"assert client.api_key == "test-key"+ @patch("posthog.llm.gateway_client.settings")+ def test_uses_explicit_api_key(self, mock_settings):+ mock_settings.LLM_GATEWAY_URL = "http://gateway:8080"+ mock_settings.LLM_GATEWAY_API_KEY = "shared-key"++ client = get_llm_client(product="custom_image_scans", team_id=1, api_key="server-minted-token")++ assert client.api_key == "server-minted-token"+@pytest.mark.parametrize("product,expected_path",[diff --git a/products/tasks/backend/temporal/build_image/activities.py b/products/tasks/backend/temporal/build_image/activities.pyindex 0aa8b6d18cdb..b60ac033e84c 100644--- a/products/tasks/backend/temporal/build_image/activities.py+++ b/products/tasks/backend/temporal/build_image/activities.py@@ -14,6 +14,7 @@ if TYPE_CHECKING:from posthog.llm.gateway_client import Productfrom posthog.temporal.common.utils import asyncify+from posthog.temporal.oauth import create_oauth_access_token_for_userfrom products.tasks.backend.logic.services.image_spec import (SandboxImageSpec,@@ -28,7 +29,7 @@ from products.tasks.backend.temporal.observability import log_activity_executionlogger = logging.getLogger(__name__)SCAN_JUDGE_MODEL = "@cf/zai-org/glm-5.2"-SCAN_JUDGE_PRODUCT: "Product" = "posthog_code"+SCAN_JUDGE_PRODUCT: "Product" = "custom_image_scans"SCAN_JUDGE_SYSTEM_PROMPT = """You are a security judge reviewing a declarative sandbox image spec before it is built and published.@@ -102,7 +103,9 @@ def _get_image(input: ImageBuildActivityInput) -> SandboxCustomImage:return SandboxCustomImage.objects.for_team(input.team_id).get(id=input.image_id)-def _judge_spec_safety(spec_yaml: str, team_id: int, repository: str = "") -> ScanImageSpecOutput:+def _judge_spec_safety(+ spec_yaml: str, team_id: int, repository: str = "", gateway_token: str | None = None+) -> ScanImageSpecOutput:from posthog.llm.gateway_client import get_llm_client # noqa: PLC0415 — keeps the OpenAI SDK off startup pathsrepo_context = (@@ -111,7 +114,7 @@ def _judge_spec_safety(spec_yaml: str, team_id: int, repository: str = "") -> Scif repositoryelse "")- client = get_llm_client(product=SCAN_JUDGE_PRODUCT, team_id=team_id)+ client = get_llm_client(product=SCAN_JUDGE_PRODUCT, team_id=team_id, api_key=gateway_token)response = client.chat.completions.create(model=SCAN_JUDGE_MODEL,messages=[@@ -146,7 +149,17 @@ def scan_image_spec(input: ImageBuildActivityInput) -> ScanImageSpecOutput:image.save(update_fields=["status", "updated_at"])spec = parse_image_spec_json(image.spec)- result = _judge_spec_safety(spec.to_yaml(), input.team_id, repository=image.repository)+ if image.created_by is None or not image.created_by.is_active:+ raise RuntimeError("Custom image creator is unavailable; cannot authorize the security scan")+ gateway_token = create_oauth_access_token_for_user(+ image.created_by,+ input.team_id,+ scopes=["llm_gateway:read", "internal_run:read"],+ include_internal_scopes=False,+ )+ result = _judge_spec_safety(+ spec.to_yaml(), input.team_id, repository=image.repository, gateway_token=gateway_token+ )image.scan_result = {"passed": result.passed, "findings": result.findings}if result.passed:diff --git a/products/tasks/backend/temporal/build_image/test_activities.py b/products/tasks/backend/temporal/build_image/test_activities.pyindex ec35a2ce51c9..edcabb891a90 100644--- a/products/tasks/backend/temporal/build_image/test_activities.py+++ b/products/tasks/backend/temporal/build_image/test_activities.py@@ -37,7 +37,7 @@ def test_security_scan_uses_glm_json_output(mock_get_llm_client: MagicMock) -> Nassert result.passed is Trueassert result.findings == [{"severity": "low", "detail": "Pinned development tool"}]- mock_get_llm_client.assert_called_once_with(product=SCAN_JUDGE_PRODUCT, team_id=42)+ mock_get_llm_client.assert_called_once_with(product=SCAN_JUDGE_PRODUCT, team_id=42, api_key=None)request = mock_get_llm_client.return_value.chat.completions.create.call_args.kwargsassert request["model"] == SCAN_JUDGE_MODELassert request["response_format"] == {"type": "json_object"}diff --git a/services/llm-gateway/src/llm_gateway/config.py b/services/llm-gateway/src/llm_gateway/config.pyindex 568e663c7bd3..3f5088d16f16 100644--- a/services/llm-gateway/src/llm_gateway/config.py+++ b/services/llm-gateway/src/llm_gateway/config.py@@ -31,6 +31,7 @@ DEFAULT_PRODUCT_COST_LIMITS: dict[str, "ProductCostLimit"] = {"posthog_code": ProductCostLimit(limit_usd=5000.0, window_seconds=3600),"background_agents": ProductCostLimit(limit_usd=1000.0, window_seconds=3600),"django": ProductCostLimit(limit_usd=5000.0, window_seconds=86400),+ "custom_image_scans": ProductCostLimit(limit_usd=1000.0, window_seconds=86400),"signals": ProductCostLimit(limit_usd=25000.0, window_seconds=86400),"posthog_ai": ProductCostLimit(limit_usd=5000.0, window_seconds=86400),}diff --git a/services/llm-gateway/src/llm_gateway/modal.py b/services/llm-gateway/src/llm_gateway/modal.pyindex a41a733afe9a..0e4cc153dbd5 100644--- a/services/llm-gateway/src/llm_gateway/modal.py+++ b/services/llm-gateway/src/llm_gateway/modal.py@@ -78,6 +78,10 @@ def _traffic_bucket(user_key: str) -> float:def modal_traffic_fraction(product: str, settings: Settings) -> float:# Legacy product aliases (twig/array) must read their canonical product's fraction.product = _normalize_cost_key(product)+ # Image scans are server-side calls, but they must move between GLM backends with the Code+ # runtime they protect so builds do not depend on a backend that Code has already rolled off.+ if product == "custom_image_scans":+ product = "posthog_code"return settings.glm_modal_product_traffic_fractions.get(product, settings.glm_modal_traffic_fraction)diff --git a/services/llm-gateway/src/llm_gateway/products/config.py b/services/llm-gateway/src/llm_gateway/products/config.pyindex a733640e9fb0..c042ff205be7 100644--- a/services/llm-gateway/src/llm_gateway/products/config.py+++ b/services/llm-gateway/src/llm_gateway/products/config.py@@ -220,6 +220,16 @@ PRODUCTS: Final[dict[str, ProductConfig]] = {# Deliberately unbilled while ReviewHog is an internal alpha.credit_bucket=None,),+ # Server-side security review before a custom sandbox image is built. The Django worker mints a+ # short-lived OAuth token carrying the internal provenance marker; personal API keys and normal+ # Code OAuth tokens cannot spend this unbilled product's budget.+ "custom_image_scans": ProductConfig(+ allowed_application_ids=frozenset({POSTHOG_CODE_US_APP_ID, POSTHOG_CODE_EU_APP_ID, POSTHOG_CODE_DEV_APP_ID}),+ allowed_models=frozenset({"@cf/zai-org/glm-5.2"}),+ allow_api_keys=False,+ credit_bucket=None,+ requires_server_credential=True,+ ),"subscriptions": ProductConfig(allowed_application_ids=None,allowed_models=frozenset({"gpt-4.1-mini"}),@@ -409,10 +419,10 @@ def check_product_access(# shared server-side gateway key still works here. Gated behind the same flag as the# free-tier gate so it stays inert until the Code billing cutover.if (- settings.posthog_code_model_gate_enabled- and config.requires_server_credential+ config.requires_server_credentialand is_oauthand INTERNAL_RUN_SCOPE not in (scopes or [])+ and (settings.posthog_code_model_gate_enabled or resolved_product == "custom_image_scans")):return False, f"Product '{product}' requires a server-minted credential"diff --git a/services/llm-gateway/tests/test_glm_routing.py b/services/llm-gateway/tests/test_glm_routing.pyindex c37664091bc4..2bc6d7748993 100644--- a/services/llm-gateway/tests/test_glm_routing.py+++ b/services/llm-gateway/tests/test_glm_routing.py@@ -155,9 +155,9 @@ async def test_each_surface_routes_to_its_provider_configs(assert handle.call_args.kwargs["provider_config"].endpoint_name == cloudflare_endpoint[email protected]("product", ["twig", "array"])[email protected]("product", ["twig", "array", "custom_image_scans"])async def test_alias_products_ramp_through_canonical_fraction(product: str) -> None:- # twig/array requests must follow posthog_code's per-product ramp end to end.+ # These requests must follow posthog_code's per-product ramp end to end.handle = AsyncMock(return_value={"ok": True})settings = _settings(glm_modal_product_traffic_fractions={"posthog_code": 1.0})_, evaluate = await _send(settings, handle, product=product)diff --git a/services/llm-gateway/tests/test_product_config.py b/services/llm-gateway/tests/test_product_config.pyindex a658b84b30c9..9dba9b864431 100644--- a/services/llm-gateway/tests/test_product_config.py+++ b/services/llm-gateway/tests/test_product_config.py@@ -62,6 +62,16 @@ class TestCheckProductAccess:("django", "personal_api_key", None, "gpt-4.1-mini", True, None),("django", "personal_api_key", None, "claude-3-opus", True, None),("django", "oauth_access_token", "any-app-id", "gpt-4.1-mini", False, "not authorized"),+ # Custom image scans accept only server-minted OAuth credentials.+ ("custom_image_scans", "personal_api_key", None, "@cf/zai-org/glm-5.2", False, "requires OAuth"),+ (+ "custom_image_scans",+ "oauth_access_token",+ POSTHOG_CODE_US_APP_ID,+ "@cf/zai-org/glm-5.2",+ False,+ "server-minted",+ ),# llma_translation allows API keys but only gpt-4.1-mini; OAuth rejected (no app IDs configured)("llma_translation", "personal_api_key", None, "gpt-4.1-mini", True, None),("llma_translation", "personal_api_key", None, "claude-3-opus", False, "not allowed"),