: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
from __future__ import annotations
from collections.abc import Collection
from typing import TYPE_CHECKING, Any, cast, get_args
from uuid import UUID
from django.db import transaction
from posthog.models import OAuthAccessToken
from posthog.temporal.oauth import (
ARRAY_APP_CLIENT_ID_DEV,
ARRAY_APP_CLIENT_ID_EU,
ARRAY_APP_CLIENT_ID_US,
RESEARCH_WITHHELD_SCOPES,
McpScopePreset,
PosthogMcpScopes,
SandboxOAuthApplication,
ScoutScopePosture,
WizardIdentityBlockedError,
create_oauth_access_token_for_user as _create_oauth_access_token_for_user,
create_wizard_oauth_access_token_for_user as _create_wizard_oauth_access_token_for_user,
resolve_scopes,
)
from products.mcp_store.backend.facade.api import is_builtin_agent_enforcement_enabled
from products.tasks.backend.exceptions import OAuthTokenError, TaskInvalidStateError
from products.tasks.backend.logic.services.run_actor import (
get_task_run_credential_user,
is_slack_interaction_state,
loop_owner_eligible_for_credentials,
)
from products.tasks.backend.models import (
INTERACTIVE_SIGNALS_AI_STAGE_BY_ORIGIN,
TASK_OWNERSHIP_VERSION_STATE_KEY,
Task,
TaskRun,
)
if TYPE_CHECKING:
from posthog.models.user import User
__all__ = [
"ARRAY_APP_CLIENT_ID_DEV",
"ARRAY_APP_CLIENT_ID_EU",
"ARRAY_APP_CLIENT_ID_US",
"create_oauth_access_token",
"create_oauth_access_token_for_run",
"create_oauth_access_token_for_user",
"create_wizard_oauth_access_token",
"dispatched_run_scopes",
]
SUBSCRIPTION_RUN_WITHHELD_SCOPES = frozenset({"llm_gateway:read"})
# Every Signals sandbox surface mints under the dedicated Signals OAuth app, so the LLM
# gateway can pin the `signals` product to that app alone. Sharing the Array app would leave
# a Signals token equally valid for `posthog_code` and `background_agents`, and the product
# is a path segment the caller picks, so any per-product budget would be self-selected.
SIGNALS_ORIGIN_PRODUCTS = frozenset(
{
Task.OriginProduct.SIGNAL_REPORT,
Task.OriginProduct.SIGNALS_SCOUT,
Task.OriginProduct.SIGNALS_SCOUT_SUGGESTIONS,
Task.OriginProduct.SIGNALS_CHAT,
}
)
# Signals surfaces a person drives by hand: the Inbox report CTAs ("Create PR" / "Discuss")
# and scout chat. Scheduled scouts run under their own reserved origin and never appear here.
INTERACTIVE_SIGNALS_ORIGIN_PRODUCTS = frozenset(
{
Task.OriginProduct.SIGNAL_REPORT,
Task.OriginProduct.SIGNALS_CHAT,
}
)
def _oauth_application_for_task(task: Task, state: dict[str, Any] | None) -> SandboxOAuthApplication:
if (
task.origin_product in (Task.OriginProduct.SIGNAL_REPORT, Task.OriginProduct.SIGNALS_SCOUT)
and (state or {}).get("billing_product") == "posthog_ai"
):
return "posthog_ai"
profile = task.stored_profile
if profile is not None:
return cast(SandboxOAuthApplication, profile.oauth_app.value)
# Metrics import and feature flag tasks bill the `posthog_ai` gateway product, which accepts only this
# application.
if task.origin_product in (
Task.OriginProduct.POSTHOG_AI,
Task.OriginProduct.METRICS_IMPORT,
Task.OriginProduct.FEATURE_FLAGS,
):
return "posthog_ai"
if task.origin_product in SIGNALS_ORIGIN_PRODUCTS:
return "signals"
return "array"
# Stages `Task.create_run` stamps on person-started signals runs. Any other stage is the
# pipeline's own and marks a self-driving run.
INTERACTIVE_SIGNALS_AI_STAGES = frozenset(INTERACTIVE_SIGNALS_AI_STAGE_BY_ORIGIN.values())
def is_interactive_signals_run(task: Task, state: dict[str, Any] | None) -> bool:
"""Whether *this run* exists because a person pressed something, not because we scheduled it.
Asks the run, not the task. `task.internal` is stamped once at creation and never
recomputed, so it only ever answers for the run that created the task: Signals auto-starts
an implementation task, and a person can later start a second run on that same task from
the report. One task, two runs, two different initiators.
`ai_stage` is stamped server-side once at run creation: the pipeline stamps its own stage
on a run it started, and `Task.create_run` stamps `inbox` / `chat` on a person-started run
so it carries a gateway product. It is absent from the task create serializer and sits in
`_PROTECTED_RUN_STATE_KEYS`, so no caller can set or forge one — the review carve-outs
already trust a pipeline stage as proof a run is self-driving. An interactive stage, or
none at all, keeps the interactive budget and its per-run ceiling as the fail-closed default.
"""
if task.origin_product not in INTERACTIVE_SIGNALS_ORIGIN_PRODUCTS:
return False
stage = (state or {}).get("ai_stage")
return not stage or stage in INTERACTIVE_SIGNALS_AI_STAGES
def _scopes_from_state_value(raw: object) -> PosthogMcpScopes | None:
"""A scope posture as run state holds it after a JSON round trip, or None when it is not one."""
if isinstance(raw, list) and all(isinstance(scope, str) for scope in raw):
return cast(list[str], list(raw))
if isinstance(raw, str) and raw in get_args(McpScopePreset):
return cast(McpScopePreset, raw)
if isinstance(raw, dict):
# `resolve_scopes` reads a posture defensively, so an unknown preset or an extra scope
# outside the grantable allowlist cannot widen it.
return cast(ScoutScopePosture, raw)
return None
def default_run_scopes(origin_product: str, state: dict[str, Any] | None) -> PosthogMcpScopes:
"""The scopes dispatch grants a run whose state records none: full unless the run source
is scoped down, mirroring ``_trigger_task_processing_workflow``.
Signals scout runs are the exception. Their posture (``signal_scout_internal:*`` +
``signal_scout_report:write``) is carried by neither ``"full"`` nor ``"read_only"``, so a scout
on a generic posture loses every ``signals-scout-*`` tool and burns the whole run. Pin
scout-origin runs to the most-capable scout posture; over-granting the report scope to a
non-report scout is harmless because the report endpoints gate on the skill's opt-in. The
suggestion scan only reads. Loop runs persist their real scopes in ``pending_dispatch`` and
carry no run source, so a loop row without them degrades to ``read_only``.
"""
from products.tasks.backend.temporal.process_task.utils import ( # noqa: PLC0415 — keeps temporalio off the import path
mcp_scopes_for_run_source,
parse_run_state,
)
if origin_product == Task.OriginProduct.SIGNALS_SCOUT:
return "signals_scout_reports"
if origin_product in (Task.OriginProduct.SIGNALS_SCOUT_SUGGESTIONS, Task.OriginProduct.LOOP):
return "read_only"
return mcp_scopes_for_run_source(parse_run_state(state).run_source)
def dispatched_run_scopes(task: Task, state: dict[str, Any] | None) -> PosthogMcpScopes:
"""The scopes the run was dispatched with: what ``pending_dispatch`` recorded at creation,
else what dispatch grants a run that recorded none (``default_run_scopes``).
The launch activities receive this value on their input; the provisioning activities do
not, and the token they place in the sandbox environment must carry the same grant as the
MCP session, or a shell fallback runs with less than the run was given. A recorded value
that does not parse fails closed to ``read_only``.
"""
pending = (state or {}).get("pending_dispatch")
raw = pending.get("posthog_mcp_scopes") if isinstance(pending, dict) else None
if raw is None:
return default_run_scopes(task.origin_product, state)
scopes = _scopes_from_state_value(raw)
return scopes if scopes is not None else "read_only"
def _workflow_run_scopes(requested: PosthogMcpScopes, state: dict[str, Any] | None) -> list[str]:
"""Scopes for a workflow-fired run: the request intersected with the run's snapshotted
choice (neither side can widen the other). A snapshot that does not parse narrows to
``read_only`` rather than dropping the leg that stops a widened request."""
resolved = set(resolve_scopes(requested, include_internal_scopes=True))
connectors = ((state or {}).get("config_snapshot") or {}).get("connectors")
raw = connectors.get("posthog_mcp_scopes") if isinstance(connectors, dict) else None
if raw is not None:
snapshot = _scopes_from_state_value(raw)
resolved &= set(resolve_scopes("read_only" if snapshot is None else snapshot, include_internal_scopes=True))
return sorted(resolved)
def _builtin_agent_enforcement(task: Task) -> bool | None:
if Task.mcp_agent_key_for(task.origin_product, task.stored_profile) is None:
return None
return is_builtin_agent_enforcement_enabled(task.team_id)
def _monitoring_result_scope(task: Task, run_id: UUID | str | None) -> bool | None:
if task.origin_product != Task.OriginProduct.SIGNALS_SCOUT or run_id is None:
return None
from products.signals.backend.facade.monitoring import ( # noqa: PLC0415 -- avoids loading Signals during Tasks startup
monitoring_scout_can_submit,
)
return monitoring_scout_can_submit(team_id=task.team_id, task_id=task.id, task_run_id=run_id)
def create_oauth_access_token(
task: Task,
*,
scopes: PosthogMcpScopes = "read_only",
user: User | None = None,
allow_task_creator_fallback: bool = True,
run_state: dict[str, Any] | None = None,
run_id: UUID | str | None = None,
builtin_agent_enforcement: bool | None = None,
monitoring_result_scope: bool | None = None,
) -> str:
"""Create an OAuth access token for the task's sandbox app, scoped to the task's team.
OAuth tokens auto-expire after 6 hours, so no cleanup is needed.
Pass `run_state` so the Signals budget is picked from the run's own provenance
(`is_interactive_signals_run`); omitting it bills a signals run as interactive, which is
the safe default but is never what a pipeline run wants.
"""
actor = user or (task.created_by if allow_task_creator_fallback else None)
if not actor:
raise TaskInvalidStateError(
f"Task {task.id} has no user for sandbox OAuth",
{"task_id": task.id},
cause=RuntimeError(f"Task {task.id} missing sandbox OAuth user"),
)
token_options: dict[str, Any] = {
"scopes": scopes,
"application": _oauth_application_for_task(task, run_state),
"sandbox_task_id": task.id,
}
if builtin_agent_enforcement is None:
builtin_agent_enforcement = _builtin_agent_enforcement(task)
if builtin_agent_enforcement:
# This scope only removes access to the human MCP Store surface. Add it
# even when a legacy task lacks trusted provenance so an old spoofed
# origin fails closed instead of inheriting its creator's connections.
# Keyed to the same rollout flag as the Store facade: a legacy-resolved
# task needs a member-capable token, or every member-proxy call it was
# just granted would 403.
token_options["include_mcp_builtin_agent_scope"] = True
if token_options["application"] == "signals" and is_interactive_signals_run(task, run_state):
token_options["include_interactive_run_scope"] = True
if task.origin_product == Task.OriginProduct.SLACK:
token_options["include_slack_run_scope"] = True
withheld = set(SUBSCRIPTION_RUN_WITHHELD_SCOPES) if run_uses_own_subscription(run_state) else set()
if "internal_run:write" in resolve_scopes(scopes):
# Flat scopes regain shared internal grants when resolved again during minting.
withheld.update(RESEARCH_WITHHELD_SCOPES)
if withheld:
token_options["withhold_scopes"] = sorted(withheld)
if monitoring_result_scope is None:
monitoring_result_scope = _monitoring_result_scope(task, run_id)
if monitoring_result_scope:
token_options["include_monitoring_result_scope"] = True
return create_oauth_access_token_for_user(actor, task.team_id, **token_options)
def run_uses_own_subscription(run_state: dict[str, Any] | None) -> bool:
state = run_state or {}
return any(state.get(f"{adapter}_model_access") == "own-subscription" for adapter in ("claude", "codex"))
def create_oauth_access_token_for_run(
task: Task,
state: dict[str, Any] | None,
*,
scopes: PosthogMcpScopes | None = None,
run_id: str | UUID | None = None,
) -> str:
"""Mint the sandbox OAuth token for a run, resolving the acting user from run state.
Single entry point for the run credential policy: Slack runs fail closed when their
recorded actor can't be validated (never falling back to the task creator), while
other runs keep the creator fallback. Callers must not re-derive this pairing by
hand — passing ``user``/``allow_task_creator_fallback`` separately makes it possible
to mint creator credentials for a Slack run by omitting one kwarg.
``scopes`` defaults to what the run was dispatched with (``dispatched_run_scopes``), so
a caller without the value on its activity input still mints the run's own grant.
Tokens recorded on ``run_id`` may read that run's protected agent context, even when the
sandbox's query scopes are withheld. The binding never grants access to other runs.
"""
if scopes is None:
scopes = dispatched_run_scopes(task, state)
# Only the provisioning activities omit `scopes`, and their token is the one the agent
# server uses to upload the run's own log through `append_log`, which requires
# `task:write`. The research MCP session keeps the withheld posture because
# `start_agent_server` mints its token with explicit scopes.
if scopes == "signals_research":
scopes = [*resolve_scopes(scopes), *RESEARCH_WITHHELD_SCOPES]
elif scopes == "signals_assessment":
# Runtime uploads are bound to this run; the separately minted MCP token stays read-only.
scopes = [*resolve_scopes(scopes), "internal_run:write"]
builtin_agent_enforcement = _builtin_agent_enforcement(task)
monitoring_result_scope = _monitoring_result_scope(task, run_id)
with transaction.atomic():
locked_task = (
Task.objects.select_for_update(of=("self",), no_key=True)
.select_related("created_by", "team")
.get(id=task.id, team_id=task.team_id)
)
run_ownership_version = (state or {}).get(TASK_OWNERSHIP_VERSION_STATE_KEY)
if run_ownership_version != locked_task.ownership_version:
raise TaskInvalidStateError(
f"Task run for {task.id} belongs to a previous task owner",
{"task_id": task.id},
cause=RuntimeError("task run ownership version is stale"),
)
actor_user = get_task_run_credential_user(locked_task, state)
effective_scopes = scopes
trial_origin = locked_task.is_scout_experiment
if trial_origin or "scout_experiment_internal:read" in resolve_scopes(scopes):
if not trial_origin:
raise TaskInvalidStateError(
"The scout trial has no trusted execution context.",
{"task_id": task.id},
cause=RuntimeError("missing scout trial context"),
)
effective_scopes = "signals_scout_experiment"
credential_owner_kind: str | None = None
if locked_task.origin_product == Task.OriginProduct.WORKFLOW:
effective_scopes = _workflow_run_scopes(scopes, state)
credential_owner_kind = "workflow"
elif (state or {}).get("loop_id") is not None:
credential_owner_kind = "loop"
if credential_owner_kind is not None:
credential_owner_id = actor_user.id if actor_user is not None else locked_task.created_by_id
if not loop_owner_eligible_for_credentials(credential_owner_id, locked_task.team):
raise TaskInvalidStateError(
f"{credential_owner_kind.capitalize()} task {locked_task.id} credential owner can no longer access its team",
{"task_id": locked_task.id},
cause=RuntimeError(f"{credential_owner_kind} credential owner is not an active team member"),
)
access_token = create_oauth_access_token(
locked_task,
scopes=effective_scopes,
user=actor_user,
allow_task_creator_fallback=not is_slack_interaction_state(state),
run_state=state,
run_id=run_id,
builtin_agent_enforcement=builtin_agent_enforcement,
monitoring_result_scope=monitoring_result_scope,
)
if run_id is not None:
run = TaskRun.objects.select_for_update().get(
id=run_id, task_id=locked_task.id, team_id=locked_task.team_id
)
token_id = str(OAuthAccessToken.objects.get(token=access_token).id)
run.state = {
**(run.state or {}),
"sandbox_oauth_token_ids": [*(run.state or {}).get("sandbox_oauth_token_ids", []), token_id],
}
run.save(update_fields=["state"])
return access_token
def create_wizard_oauth_access_token(task: Task) -> str:
"""Create the OAuth access token the setup wizard uses inside a cloud wizard run.
Minted under the wizard's own OAuthApplication with the wizard's scopes — kept separate from
the sandbox/agent token (`create_oauth_access_token`) so the two scope sets stay independent.
"""
if not task.created_by:
raise TaskInvalidStateError(
f"Task {task.id} has no created_by user",
{"task_id": task.id},
cause=RuntimeError(f"Task {task.id} missing created_by field"),
)
try:
return _create_wizard_oauth_access_token_for_user(task.created_by, task.team_id)
except WizardIdentityBlockedError as err:
# Fatal: the ban holds until someone edits the flag, so retrying only burns
# attempts against a settled answer.
raise TaskInvalidStateError(str(err), {"team_id": task.team_id}, cause=err) from err
except RuntimeError as err:
raise OAuthTokenError(str(err), {"team_id": task.team_id}, cause=err) from err
def create_oauth_access_token_for_user(
user,
team_id: int,
*,
scopes: PosthogMcpScopes = "read_only",
application: SandboxOAuthApplication = "array",
include_mcp_builtin_agent_scope: bool = False,
include_interactive_run_scope: bool = False,
include_slack_run_scope: bool = False,
include_monitoring_result_scope: bool = False,
sandbox_task_id: UUID | None = None,
withhold_scopes: Collection[str] = (),
) -> str:
"""Create an OAuth access token for a sandbox app, scoped to a specific team."""
try:
token_options: dict[str, Any] = {
"scopes": scopes,
"application": application,
"sandbox_task_id": sandbox_task_id,
}
if include_mcp_builtin_agent_scope:
token_options["include_mcp_builtin_agent_scope"] = True
if include_interactive_run_scope:
token_options["include_interactive_run_scope"] = True
if include_slack_run_scope:
token_options["include_slack_run_scope"] = True
if include_monitoring_result_scope:
token_options["include_monitoring_result_scope"] = True
if withhold_scopes:
token_options["withhold_scopes"] = list(withhold_scopes)
return _create_oauth_access_token_for_user(user, team_id, **token_options)
except RuntimeError as err:
raise OAuthTokenError(str(err), {"team_id": team_id}, cause=err) from err