: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): mint gateway tokens for slack repo selection and follow-ups (#103818)
Brandonf7916514e9e8
diff --git a/products/tasks/backend/temporal/process_task/ai_gateway_token.py b/products/tasks/backend/temporal/process_task/ai_gateway_token.pyindex 96a7b04ddcae..38b2f10e3539 100644--- a/products/tasks/backend/temporal/process_task/ai_gateway_token.py+++ b/products/tasks/backend/temporal/process_task/ai_gateway_token.py@@ -65,8 +65,8 @@ _MAX_CAP_DECIMAL_PLACES = 6# `signals_inbox`, so the per-run cap and the product's daily budget bound those two.# review_hog qualifies because validate_origin_product reserves the origin and# the resolver requires the server-stamped `internal` flag; rows predating the-# reservation resolve to posthog_code and cannot mint. slack_app also needs the-# PATCH-protected `interaction_origin` stamp (mint_refusal), older rows included.+# reservation resolve to posthog_code and cannot mint. slack_app needs server+# provenance too (has_slack_provenance), older rows included.MINTABLE_PRODUCTS = frozenset({"review_hog",@@ -130,13 +130,36 @@ def sandbox_product_routed(ai_product: str, ai_stage: str | None, products_csv:return False+def is_slack_origin(origin_product: str | None) -> bool:+ """Whether this origin is the reserved one the Slack app's server flows set."""+ return _ORIGIN_TO_GATEWAY_PRODUCT.get(origin_product or "") == "slack_app"+++def has_slack_provenance(+ state: dict[str, Any] | None, *, internal: bool = False, prior_slack_run: bool = False+) -> bool:+ """Whether a server flow put this run on the Slack product.++ The API refuses the `slack` origin for client tasks and never writes `internal`, so an internal+ run is server-created. A later run of a Slack task has no stamp, so an earlier stamped run counts.+ """+ return is_slack_interaction_state(state) or internal or prior_slack_run++def mint_refusal(- ai_product: str, *, team_id: int, state: dict[str, Any] | None, model: str | None, runtime: str | None+ ai_product: str,+ *,+ team_id: int,+ state: dict[str, Any] | None,+ model: str | None,+ runtime: str | None,+ internal: bool = False,+ prior_slack_run: bool = False,) -> str | None:"""Why a routed run must not mint; a run without a token stays on the Python gateway."""if ai_product != "slack_app":return None- if not is_slack_interaction_state(state):+ if not has_slack_provenance(state, internal=internal, prior_slack_run=prior_slack_run):return "no_slack_provenance"# The Pi harness reads only LLM_GATEWAY_URL.if runtime == "pi":@@ -297,8 +320,13 @@ def mint_scoped_token(*, ai_product: str, team_id: int, user: str | None = None)time.sleep((0.5 * 2**attempt) + random.uniform(0, 0.25))AI_GATEWAY_TOKEN_MINTS.labels(result="error").inc()+ # The deploy's log formatter drops `extra`, so the message carries the fields.+ # nosemgrep: python.lang.security.audit.logging.logger-credential-leak.python-logger-credential-disclosure -- logs product, team id and the mint error, never the token or mint keylogger.warning(- "ai_gateway_token: mint failed, run falls back to the Python gateway",+ "ai_gateway_token: mint failed, run falls back to the Python gateway (ai_product=%s team_id=%s error=%s)",+ ai_product,+ team_id,+ last_error,extra={"ai_product": ai_product, "team_id": team_id, "error": last_error},)return Nonediff --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.pyindex d41fc9aad3c2..92d1e9b5fe10 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@@ -1,4 +1,5 @@import json+import loggingfrom pathlib import Pathimport pytest@@ -464,8 +465,28 @@ class TestProvisioningBoundaries:state={"ai_stage": "scout:logs"},model="claude-sonnet-5",runtime="acp",+ prior_slack_run=False,)+ def test_non_slack_origin_skips_the_prior_run_lookup(self, mint_settings):+ from products.tasks.backend.temporal.process_task import utils++ with patch("products.tasks.backend.models.TaskRun.objects") as runs:+ utils.run_gateway_env_vars(self._ctx(), self._task())+ runs.filter.assert_not_called()++ def test_slack_run_without_its_own_stamp_looks_for_an_earlier_one(self, mint_settings):+ from products.tasks.backend.temporal.process_task import utils++ ctx = self._ctx()+ ctx.origin_product = "slack"+ ctx.state = {"run_source": "manual"}+ with patch("products.tasks.backend.models.TaskRun.objects") as runs:+ runs.filter.return_value.exists.return_value = True+ with patch.object(utils, "ai_gateway_env_vars", return_value={}) as env:+ utils.run_gateway_env_vars(ctx, self._task())+ assert env.call_args.kwargs["prior_slack_run"] is True+def test_subscription_run_does_not_mint_gateway_credentials(self, mint_settings):ctx = self._ctx()ctx.claude_model_access = "own-subscription"@@ -750,9 +771,82 @@ class TestSlackAppMint:assert "interaction_origin" in _PROTECTED_RUN_STATE_KEYS+ def test_internal_slack_helper_run_mints(self, mint_settings):+ env, mint = self._env(mint_settings, state={"ai_stage": "repo_selection"}, internal=True)+ assert env["AI_GATEWAY_TOKEN"] == "phe_abc"+ assert env["AI_GATEWAY_PRODUCT"] == "slack_app"+ mint.assert_called_once()++ def test_run_after_a_stamped_run_mints(self, mint_settings):+ env, mint = self._env(mint_settings, state={"run_source": "manual"}, prior_slack_run=True)+ assert env["AI_GATEWAY_TOKEN"] == "phe_abc"+ mint.assert_called_once()++ def test_unstamped_caller_run_still_does_not_mint(self, mint_settings):+ env, mint = self._env(mint_settings, state={"run_source": "manual"})+ assert "AI_GATEWAY_TOKEN" not in env+ mint.assert_not_called()++ @pytest.mark.parametrize("overrides", [{"runtime": "pi"}, {"model": "zai-org/glm-5.3"}])+ def test_other_gates_still_refuse_an_internal_helper_run(self, mint_settings, overrides):+ env, mint = self._env(mint_settings, state={"ai_stage": "repo_selection"}, internal=True, **overrides)+ assert "AI_GATEWAY_TOKEN" not in env+ mint.assert_not_called()++ def test_internal_does_not_admit_a_non_slack_origin(self, mint_settings):+ mint_settings.SANDBOX_AI_GATEWAY_PRODUCTS = "slack_app,background_agents"+ env, mint = self._env(mint_settings, origin_product="user_created", state=None, internal=True)+ assert "AI_GATEWAY_TOKEN" not in env+ mint.assert_not_called()++ def test_mint_outcomes_name_their_reason_in_the_message(self, mint_settings, caplog):+ with caplog.at_level(logging.INFO):+ self._env(mint_settings, state={"run_source": "manual"})+ skipped = [r for r in caplog.records if "mint skipped" in r.getMessage()]+ assert skipped, "no mint-skipped line was logged"+ assert "no_slack_provenance" in skipped[0].getMessage()+ assert "slack_app" in skipped[0].getMessage()++ def test_mint_failure_names_its_error_in_the_message(self, mint_settings, caplog):+ with patch("products.tasks.backend.temporal.process_task.ai_gateway_token.requests.post") as post:+ post.return_value = MagicMock(status_code=429, text="mint rate limit exceeded")+ with caplog.at_level(logging.WARNING):+ assert mint_scoped_token(ai_product="slack_app", team_id=123) is None+ failed = [r for r in caplog.records if "mint failed" in r.getMessage()]+ assert failed, "no mint-failed line was logged"+ assert "HTTP 429" in failed[0].getMessage()+ assert "slack_app" in failed[0].getMessage()+def test_slack_gates_leave_other_products_alone(self):assert mint_refusal("review_hog", team_id=2, state=None, model="zai-org/glm-5.3", runtime="pi") is None+ # The mocked tests never run the JSON lookup; this one does.+ @pytest.mark.django_db+ def test_earlier_slack_stamp_is_found_in_the_database(self):+ from products.tasks.backend.models import Task, TaskRun+ from products.tasks.backend.temporal.process_task.utils import _task_has_stamped_slack_run++ organization = Organization.objects.create(name="Slack Org")+ team = Team.objects.create(organization=organization, name="Slack Team")+ task = Task.objects.create(+ team=team, title="From Slack", description="thread", origin_product=Task.OriginProduct.SLACK+ )+ unstamped = {"run_source": "manual"}+ assert _task_has_stamped_slack_run(task, "slack", unstamped) is False++ # The run being provisioned is already a row, so matching any run would vouch for every Slack run.+ TaskRun.objects.create(task=task, team=team, status=TaskRun.Status.QUEUED, state=unstamped)+ assert _task_has_stamped_slack_run(task, "slack", unstamped) is False++ TaskRun.objects.create(+ task=task, team=team, status=TaskRun.Status.COMPLETED, state={"interaction_origin": "slack"}+ )+ assert _task_has_stamped_slack_run(task, "slack", unstamped) is True+ other = Task.objects.create(+ team=team, title="Other", description="other", origin_product=Task.OriginProduct.SLACK+ )+ assert _task_has_stamped_slack_run(other, "slack", unstamped) is False+@pytest.mark.django_dbdef test_quota_check_reads_the_team_token(self):organization = Organization.objects.create(name="Quota Org")diff --git a/products/tasks/backend/temporal/process_task/utils.py b/products/tasks/backend/temporal/process_task/utils.pyindex fbba3a37042a..8b464eabf514 100644--- a/products/tasks/backend/temporal/process_task/utils.py+++ b/products/tasks/backend/temporal/process_task/utils.py@@ -53,6 +53,7 @@ from products.tasks.backend.redis import get_tasks_cachefrom products.tasks.backend.temporal.process_task.ai_gateway_token import (AI_GATEWAY_TOKEN_MINTS,MINTABLE_PRODUCTS,+ is_slack_origin,mint_refusal,mint_scoped_token,resolve_sandbox_ai_product,@@ -1358,6 +1359,7 @@ def run_gateway_env_vars(ctx, task) -> dict[str, str]:origin_product=ctx.origin_product,ai_stage=(ctx.state or {}).get("ai_stage"),internal=task.internal,+ prior_slack_run=_task_has_stamped_slack_run(task, ctx.origin_product, ctx.state),distinct_id=ctx.distinct_id,state=ctx.state,model=ctx.model,@@ -1379,6 +1381,19 @@ def run_gateway_env_vars(ctx, task) -> dict[str, str]:return env_vars+def _task_has_stamped_slack_run(task, origin_product: str | None, state: dict | None) -> bool:+ """Whether any run of this task carried the Slack stamp.++ A run started outside Slack gets fresh state, and the stamp is PATCH-protected, so a stamped run+ is server proof for the task.+ """+ from products.tasks.backend.models import TaskRun # noqa: PLC0415++ if not is_slack_origin(origin_product) or is_slack_interaction_state(state):+ return False+ return TaskRun.objects.filter(task_id=task.id, state__interaction_origin="slack").exists()++def _record_pinned_gateway_product(run_id: str, state: dict | None, minted_product: str | None) -> bool:"""Stamp the run with the pinned product of its token. False leaves a pinned run unstamped."""from products.tasks.backend.models import TaskRun # noqa: PLC0415@@ -1407,6 +1422,7 @@ def ai_gateway_env_vars(state: dict[str, Any] | None = None,model: str | None = None,runtime: str | None = None,+ prior_slack_run: bool = False,) -> dict[str, str]:"""Env vars routing listed products to the Go ai-gateway, shared by everyinjection site so the both-or-nothing guard cannot drift per site. Both@@ -1433,11 +1449,24 @@ def ai_gateway_env_vars(if ai_product in MINTABLE_PRODUCTS and sandbox_product_routed(ai_product, ai_stage, settings.SANDBOX_AI_GATEWAY_PRODUCTS):- refusal = mint_refusal(ai_product, team_id=team_id, state=state, model=model, runtime=runtime)+ refusal = mint_refusal(+ ai_product,+ team_id=team_id,+ state=state,+ model=model,+ runtime=runtime,+ internal=internal,+ prior_slack_run=prior_slack_run,+ )if refusal:AI_GATEWAY_TOKEN_MINTS.labels(result="skipped").inc()+ # The deploy's log formatter drops `extra`, so the message carries the fields.+ # nosemgrep: python.lang.security.audit.logging.logger-credential-leak.python-logger-credential-disclosure -- logs product, team id and a refusal code, no credential presentlogger.info(- "ai_gateway_token: mint skipped, run stays on the Python gateway",+ "ai_gateway_token: mint skipped, run stays on the Python gateway (ai_product=%s team_id=%s reason=%s)",+ ai_product,+ team_id,+ refusal,extra={"ai_product": ai_product, "team_id": team_id, "reason": refusal},)return env_vars