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.

refactor(oauth): raise InsufficientScope from hand-written scope checks (#128333)

Rafael Audibert2655df6d18a3
diff --git a/posthog/api/posthog_connection.py b/posthog/api/posthog_connection.py
index 6c6c01c8fe57..8a4664145209 100644
--- a/posthog/api/posthog_connection.py
+++ b/posthog/api/posthog_connection.py
@@ -39,6 +39,7 @@ from posthog.auth import (
is_mcp_request,
)
from posthog.clickhouse.query_tagging import tag_queries
+from posthog.exceptions import InsufficientScope
from posthog.integrations import IntegrationManager, IntegrationNotFound, IntegrationRecord
from posthog.models.integration import posthog_connect_base_url
from posthog.oauth_provenance import SANDBOX_ORIGIN_HEADER, is_sandbox_origin_request
@@ -113,9 +114,11 @@ def _enforce_caller_covers_connection_scopes(request: Request, integration: Inte
# A legacy `task:*` key may use a connection granted the `inbox:*` scopes split off it, as the target accepts it.
missing -= set(scopes_covered_by_legacy_fallback(caller_scopes, missing))
if missing:
- raise PermissionDenied(
- "Your API key must carry the scopes this connection was granted to use it. "
- f"Missing: {', '.join(sorted(missing))}."
+ missing_scopes = sorted(missing)
+ raise InsufficientScope(
+ missing_scopes,
+ detail="Your API key must carry the scopes this connection was granted to use it. "
+ f"Missing: {', '.join(missing_scopes)}.",
)
diff --git a/posthog/api/project_secret_api_key.py b/posthog/api/project_secret_api_key.py
index f33cc4de5a8d..00e5f13add25 100644
--- a/posthog/api/project_secret_api_key.py
+++ b/posthog/api/project_secret_api_key.py
@@ -16,6 +16,7 @@ from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.api.shared import UserBasicSerializer
from posthog.api.utils import action
from posthog.auth import PersonalAPIKeyAuthentication, SessionAuthentication
+from posthog.exceptions import InsufficientScope
from posthog.llm.wizard_blocklist import WIZARD_BLOCKED_DETAIL
from posthog.models import Organization, User
from posthog.models.project_secret_api_key import ProjectSecretAPIKey, RevokedTeamSecretToken
@@ -48,9 +49,10 @@ def _enforce_caller_holds_scopes(request: Request, scopes: Iterable[str]) -> Non
issue one with scopes it lacks."""
missing = scopes_caller_lacks(request, scopes)
if missing:
- raise PermissionDenied(
- "Your API key or OAuth token can only issue a project secret API key with scopes it has. "
- f"Use a key or token that has these scopes: {', '.join(missing)}."
+ raise InsufficientScope(
+ missing,
+ detail="Your API key or OAuth token can only issue a project secret API key with scopes it has. "
+ f"Use a key or token that has these scopes: {', '.join(missing)}.",
)
diff --git a/posthog/exceptions.py b/posthog/exceptions.py
index 725bbacdccac..0a7f96b133fd 100644
--- a/posthog/exceptions.py
+++ b/posthog/exceptions.py
@@ -1,4 +1,5 @@
import random
+from collections.abc import Sequence
from typing import Any, Optional, Protocol, TypedDict
from django.http.request import HttpRequest
@@ -12,6 +13,12 @@ from rest_framework.response import Response
from posthog.clickhouse.query_tagging import get_query_tags
from posthog.cloud_utils import is_cloud
from posthog.exceptions_capture import capture_exception
+from posthog.scopes import (
+ INTERNAL_API_SCOPE_OBJECTS,
+ scopes_covered_by_legacy_fallback,
+ scopes_not_covered,
+ scopes_within_ceiling,
+)
logger = structlog.get_logger(__name__)
@@ -70,15 +77,17 @@ class PaidFeatureException(APIException):
class InsufficientScope(PermissionDenied):
- """A missing-scope 403 that carries an RFC 6750 section 3.1 `insufficient_scope` challenge.
+ """A 403 for a token that lacks a scope the request needs.
- `scope` names every scope the request requires, not only the missing ones. The MCP step-up
- flow has the client union the challenge with the scopes it holds and ask the user for that.
+ Raise it wherever code finds a missing scope. The exception handler decides if the response
+ carries an RFC 6750 section 3.1 `insufficient_scope` challenge, so callers never check the token type.
+ `required_scopes` are the scopes the request requires. The MCP step-up flow has the client union
+ them with the scopes it holds, so a check that guards one extra scope can name only that scope.
"""
- def __init__(self, detail: str, required_scopes: list[str]) -> None:
- super().__init__(detail=detail)
- self.auth_header = f'Bearer error="insufficient_scope", scope="{" ".join(required_scopes)}"'
+ def __init__(self, required_scopes: Sequence[str], detail: str | None = None) -> None:
+ super().__init__(detail=detail or f"API key missing required scope '{required_scopes[0]}'")
+ self.required_scopes = list(required_scopes)
class Conflict(APIException):
@@ -259,7 +268,30 @@ def exception_handler(exc: Exception, context: ExceptionContext) -> Optional[Res
# attacker-controlled origin.
metadata_url = absolute_uri("/.well-known/oauth-protected-resource")
response["WWW-Authenticate"] = f'Bearer resource_metadata="{metadata_url}"'
- elif response is not None and (auth_header := getattr(exc, "auth_header", None)):
- # DRF's own handler honors `auth_header`, but drf-exceptions-hog drops it.
- response["WWW-Authenticate"] = auth_header
+ elif response is not None and isinstance(exc, InsufficientScope):
+ if challenge := _insufficient_scope_challenge(context.get("request"), exc.required_scopes):
+ response["WWW-Authenticate"] = challenge
return response
+
+
+def _insufficient_scope_challenge(request: object, required_scopes: Sequence[str]) -> str | None:
+ """Only tokens from step-up apps get the challenge. Every other caller gets the same 403 without it."""
+ from posthog.auth import OAuthAccessTokenAuthentication # noqa: PLC0415 - posthog.auth needs the app registry
+
+ authenticator = getattr(request, "successful_authenticator", None)
+ if not isinstance(authenticator, OAuthAccessTokenAuthentication) or not authenticator.access_token.supports_step_up:
+ return None
+ # Internal scopes cannot be granted at consent, so a challenge naming one could never succeed.
+ if any(scope.split(":", 1)[0] in INTERNAL_API_SCOPE_OBJECTS for scope in required_scopes):
+ return None
+ # Consent drops a scope outside the app's ceiling, so the client would re-consent and still lack it.
+ # Only the scopes the token lacks matter: a held or legacy-covered scope needs no new grant.
+ held = str(authenticator.access_token.scope or "").split()
+ lacking = scopes_not_covered(held, required_scopes)
+ lacking = [scope for scope in lacking if scope not in scopes_covered_by_legacy_fallback(held, lacking)]
+ application = authenticator.access_token.application
+ if application is None or not scopes_within_ceiling(
+ lacking, application.ceiling_scopes, allow_wildcard_under_empty_ceiling=True
+ ):
+ return None
+ return f'Bearer error="insufficient_scope", scope="{" ".join(required_scopes)}"'
diff --git a/posthog/permissions.py b/posthog/permissions.py
index 4898f7674cbb..bb6e5705a092 100644
--- a/posthog/permissions.py
+++ b/posthog/permissions.py
@@ -977,16 +977,7 @@ class APIScopePermission(ScopeBasePermission):
missing_scopes = scopes_missing_after_legacy_fallback(request, view, key_scopes, required_scopes)
if missing_scopes:
- self.message = f"API key missing required scope '{missing_scopes[0]}'"
- # Internal scopes cannot be granted at consent, so a challenge naming one could never succeed.
- if (
- isinstance(authenticator, OAuthAccessTokenAuthentication)
- and authenticator.access_token.supports_step_up
- and scope_object != "INTERNAL"
- and not action_targets_internal
- ):
- raise InsufficientScope(detail=self.message, required_scopes=required_scopes)
- return False
+ raise InsufficientScope(required_scopes, detail=f"API key missing required scope '{missing_scopes[0]}'")
return True
diff --git a/posthog/test/test_permissions.py b/posthog/test/test_permissions.py
index b6c45e261d34..eb8a0aa74722 100644
--- a/posthog/test/test_permissions.py
+++ b/posthog/test/test_permissions.py
@@ -28,6 +28,7 @@ from posthog.auth import (
TeamSecretTokenAuthentication,
)
from posthog.constants import AvailableFeature
+from posthog.exceptions import InsufficientScope
from posthog.jwt import PosthogJwtAudience, encode_jwt
from posthog.models import Organization, Team, User
from posthog.models.oauth import OAuthAccessToken, OAuthApplication
@@ -566,8 +567,9 @@ class TestProjectSecretAPIKeyAPIScopePermission(SimpleTestCase):
view.psak_allowed_actions = ["create"]
view.team = Mock(id=1)
- self.assertFalse(self.permission.has_permission(request, view))
- self.assertIn("missing required scope 'endpoint:write'", self.permission.message)
+ with self.assertRaises(InsufficientScope) as ctx:
+ self.permission.has_permission(request, view)
+ self.assertIn("missing required scope 'endpoint:write'", str(ctx.exception.detail))
def test_team_check_denies_when_psak_team_differs(self):
from rest_framework.exceptions import PermissionDenied
@@ -625,10 +627,12 @@ class TestAPIScopePermissionLegacyFallback(SimpleTestCase):
) -> None:
request = self._make_personal_api_key_request(scopes)
- assert self.permission.has_permission(request, self._view_requiring(required_scope)) is allowed
-
- if not allowed:
- assert self.permission.message == f"API key missing required scope '{required_scope}'"
+ if allowed:
+ assert self.permission.has_permission(request, self._view_requiring(required_scope))
+ else:
+ with self.assertRaises(InsufficientScope) as ctx:
+ self.permission.has_permission(request, self._view_requiring(required_scope))
+ assert ctx.exception.detail == f"API key missing required scope '{required_scope}'"
if legacy_scope is None:
self.capture.assert_not_called()
else:
@@ -1059,11 +1063,32 @@ class TestOAuthAccessTokenAPIScopePermission(BaseTest):
"API key missing required scope 'signal_scratchpad_internal:write'",
None,
),
+ (
+ "step_up_legacy_covered_scope_outside_app_ceiling",
+ True,
+ "GET",
+ f"signals/scout/runs/{uuid4()}/emissions/reports/",
+ "API key missing required scope 'signal_scout:read'",
+ 'Bearer error="insufficient_scope", scope="signal_scout:read inbox:read"',
+ "task:read",
+ ["task:read", "signal_scout:read"],
+ ),
]
)
def test_missing_scope_challenge_names_every_required_scope(
- self, _name, supports_step_up, method, path, expected_detail, expected_challenge
+ self,
+ _name,
+ supports_step_up,
+ method,
+ path,
+ expected_detail,
+ expected_challenge,
+ token_scope="feature_flag:read",
+ app_scopes=(),
):
+ self.oauth_application.scopes = list(app_scopes)
+ self.oauth_application.save()
+ self.access_token.scope = token_scope
self.access_token.supports_step_up = supports_step_up
self.access_token.save()
@@ -1073,6 +1098,44 @@ class TestOAuthAccessTokenAPIScopePermission(BaseTest):
self.assertEqual(response.json()["detail"], expected_detail)
self.assertEqual(response.headers.get("WWW-Authenticate"), expected_challenge)
+ @parameterized.expand(
+ [
+ ("step_up", True, [], 'Bearer error="insufficient_scope", scope="task:write"'),
+ ("no_step_up", False, [], None),
+ ("step_up_scope_outside_app_ceiling", True, ["inbox:write"], None),
+ ]
+ )
+ def test_scope_check_inside_a_view_gets_the_same_challenge(
+ self, _name, supports_step_up, app_scopes, expected_challenge
+ ):
+ self.oauth_application.scopes = app_scopes
+ self.oauth_application.save()
+ self.access_token.scope = "inbox:write"
+ self.access_token.supports_step_up = supports_step_up
+ self.access_token.save()
+
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/signals/onboarding/complete/",
+ json.dumps(
+ {
+ "step": "github",
+ "sources": [],
+ "scanner_ids": [],
+ "suggestions": [],
+ "automatic_implementation": True,
+ "implementation_priority": "P1",
+ }
+ ),
+ content_type="application/json",
+ headers={"authorization": f"Bearer {self.access_token.token}"},
+ )
+
+ self.assertEqual(response.status_code, 403, response.content)
+ self.assertEqual(
+ response.json()["detail"], "Turning on automatic implementation requires the task:write scope."
+ )
+ self.assertEqual(response.headers.get("WWW-Authenticate"), expected_challenge)
+
def test_allows_action_with_required_scopes(self):
"""OAuth token can access endpoints that match its scopes"""
response = self._do_request(f"/api/projects/{self.team.id}/feature_flags/my_flags")
diff --git a/products/ai_observability/backend/api/offline_experiment_reads.py b/products/ai_observability/backend/api/offline_experiment_reads.py
index d5962ae934d3..69e7c24d56bf 100644
--- a/products/ai_observability/backend/api/offline_experiment_reads.py
+++ b/products/ai_observability/backend/api/offline_experiment_reads.py
@@ -8,7 +8,7 @@ from drf_spectacular.utils import OpenApiParameter
from prometheus_client import Counter
from rest_framework import serializers, viewsets
from rest_framework.decorators import action
-from rest_framework.exceptions import APIException, PermissionDenied
+from rest_framework.exceptions import APIException
from rest_framework.request import Request
from rest_framework.response import Response
@@ -16,6 +16,7 @@ from posthog.api.mixins import ValidatedRequest, validated_request
from posthog.api.monitoring import monitor
from posthog.api.pagination import page_link
from posthog.api.statement_timeout import statement_timeout
+from posthog.exceptions import InsufficientScope
from posthog.permissions import get_authenticator_scopes
from products.ai_observability.backend.api.metrics import llma_track_latency
@@ -112,7 +113,7 @@ class OfflineEvaluationReadViewSet(OfflineEvaluationViewSet):
{"*", "llm_analytics:read", "llm_analytics:write"}.intersection(scopes)
)
if query is not None and (query.scorer_definition_id or query.scorer_version_ids) and not can_read_scores:
- raise PermissionDenied("Scorer filters require llm_analytics:read.")
+ raise InsufficientScope(["llm_analytics:read"], detail="Scorer filters require llm_analytics:read.")
return OfflineEvaluationReadService(
team_id=self.team_id, user_access_control=self.user_access_control, can_read_scores=can_read_scores
)
diff --git a/products/alerts/backend/presentation/views/alert.py b/products/alerts/backend/presentation/views/alert.py
index 59f4629c8ba5..284ede3341bf 100644
--- a/products/alerts/backend/presentation/views/alert.py
+++ b/products/alerts/backend/presentation/views/alert.py
@@ -19,7 +19,7 @@ from pydantic import (
)
from rest_framework import serializers, status, viewsets
from rest_framework.decorators import action
-from rest_framework.exceptions import APIException, PermissionDenied, ValidationError
+from rest_framework.exceptions import APIException, ValidationError
from rest_framework.response import Response
from posthog.schema import (
@@ -42,7 +42,7 @@ from posthog.api.scoped_related_fields import TeamScopedPrimaryKeyRelatedField
from posthog.api.shared import SearchMatchTypeSerializerMixin, UserBasicSerializer
from posthog.email import is_email_available
from posthog.event_usage import get_request_analytics_properties
-from posthog.exceptions import as_drf_validation_error
+from posthog.exceptions import InsufficientScope, as_drf_validation_error
from posthog.exceptions_capture import capture_exception
from posthog.helpers.impersonation import is_impersonated
from posthog.helpers.trigram_search import (
@@ -430,9 +430,10 @@ def _require_write_scope_for_charged_simulation(request, detector_config: Any) -
# Session auth carries no scopes; it is gated by team membership and access control.
if key_scopes is None or "*" in key_scopes or "alert:write" in key_scopes:
return
- raise PermissionDenied(
- "Simulating the AI detector makes a model call, so it needs the 'alert:write' scope. "
- "A statistical detector simulates with 'alert:read'."
+ raise InsufficientScope(
+ ["alert:write"],
+ detail="Simulating the AI detector makes a model call, so it needs the 'alert:write' scope. "
+ "A statistical detector simulates with 'alert:read'.",
)
@@ -444,7 +445,7 @@ def _require_metrics_scope_for_programmatic_auth(context: dict[str, Any], insigh
if insight.alertable_query_kind != NodeKind.METRICS_QUERY:
return
if _token_lacks_metrics_scope(context["request"]):
- raise PermissionDenied("API key missing required scope 'metrics:read'")
+ raise InsufficientScope(["metrics:read"])
class AlertConfigUnion(RootModel):
diff --git a/products/customer_analytics/backend/presentation/views/views.py b/products/customer_analytics/backend/presentation/views/views.py
index cbf7cb415c29..5da85ada978e 100644
--- a/products/customer_analytics/backend/presentation/views/views.py
+++ b/products/customer_analytics/backend/presentation/views/views.py
@@ -42,7 +42,7 @@ from posthog.api.routing import PathParameter, TeamAndOrgViewSetMixin
from posthog.api.tagged_item import TaggedItemViewSetMixin
from posthog.auth import SessionAuthentication, is_mcp_request
from posthog.event_usage import report_user_action
-from posthog.exceptions import Conflict
+from posthog.exceptions import Conflict, InsufficientScope
from posthog.helpers.impersonation import is_impersonated
from posthog.models import OrganizationMembership
from posthog.models.team import Team
@@ -237,7 +237,8 @@ def _has_group_scope(request: Request, *, write: bool) -> bool:
def _assert_group_scope(request: Request, *, write: bool) -> None:
if not _has_group_scope(request, write=write):
- raise PermissionDenied(f"This action requires the `group:{'write' if write else 'read'}` API scope.")
+ scope = f"group:{'write' if write else 'read'}"
+ raise InsufficientScope([scope], detail=f"This action requires the `{scope}` API scope.")
class AccountTrackRuleThrottle(UserRateThrottle):
diff --git a/products/signals/backend/presentation/onboarding.py b/products/signals/backend/presentation/onboarding.py
index 80736a4229fe..b52acbbeb4c9 100644
--- a/products/signals/backend/presentation/onboarding.py
+++ b/products/signals/backend/presentation/onboarding.py
@@ -15,6 +15,7 @@ from rest_framework.views import APIView
from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.auth import OAuthAccessTokenAuthentication, PersonalAPIKeyAuthentication, SessionAuthentication
+from posthog.exceptions import InsufficientScope
from posthog.models.user import User
from posthog.oauth_provenance import is_sandbox_oauth_request
from posthog.permissions import APIScopePermission, get_authenticator_scopes
@@ -199,7 +200,10 @@ class InboxOnboardingViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
if "signal_scout:write" in allowed:
allowed.add("signal_scout:read")
if not required.issubset(allowed):
- raise PermissionDenied("Your API key does not have permission to access these scout choices.")
+ raise InsufficientScope(
+ sorted(required - allowed),
+ detail="Your API key does not have permission to access these scout choices.",
+ )
canonical_team = self.team.parent_team or self.team
user = cast(User, request.user)
access = UserAccessControl(user=user, team=canonical_team)
@@ -241,7 +245,9 @@ class InboxOnboardingViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
if any(source["source_product"] == "signals_scout" for source in serializer.validated_data["sources"]):
self._check_scout_access(request)
if serializer.validated_data["automatic_implementation"] and not credential_may_start_tasks(request):
- raise PermissionDenied("Turning on automatic implementation requires the task:write scope.")
+ raise InsufficientScope(
+ ["task:write"], detail="Turning on automatic implementation requires the task:write scope."
+ )
try:
return Response(self._service().complete(dict(serializer.data)))
except InboxOnboardingPermissionError as error:
diff --git a/products/signals/backend/scout_harness/serializers.py b/products/signals/backend/scout_harness/serializers.py
index d7a69470c618..8b9c5e15b616 100644
--- a/products/signals/backend/scout_harness/serializers.py
+++ b/products/signals/backend/scout_harness/serializers.py
@@ -23,11 +23,11 @@ from drf_spectacular.types import OpenApiTypes
from drf_spectacular.utils import extend_schema_field
from pydantic import ValidationError as PydanticValidationError
from rest_framework import serializers
-from rest_framework.exceptions import PermissionDenied
from rest_framework.fields import empty
from posthog.api.shared import UserBasicSerializer
from posthog.event_usage import groups
+from posthog.exceptions import InsufficientScope
from posthog.models.team.team import Team
from posthog.models.user import User
from posthog.permissions import get_authenticator_scopes, scopes_missing_after_legacy_fallback
@@ -3030,12 +3030,12 @@ def _validate_output_destinations(value: dict, context: dict) -> dict:
key_scopes = get_authenticator_scopes(getattr(request, "successful_authenticator", None))
if key_scopes is not None and "*" not in key_scopes:
if not any(scope in key_scopes for scope in ("integration:read", "integration:write")):
- raise PermissionDenied("API key missing required scope 'integration:read'")
+ raise InsufficientScope(["integration:read"])
# Delivery pushes report titles/summaries to the channel — content the report API gates
# behind `inbox` scope — so a scoped key without it must not be able to route that content
# out via a destination.
if scopes_missing_after_legacy_fallback(request, context.get("view"), key_scopes, ["inbox:read"]):
- raise PermissionDenied("API key missing required scope 'inbox:read'")
+ raise InsufficientScope(["inbox:read"])
return {"slack": slack, **({"webhook": webhook} if webhook else {}), **inbox}
diff --git a/products/signals/backend/scout_harness/views.py b/products/signals/backend/scout_harness/views.py
index 5d6c8be08d43..fc494b703e04 100644
--- a/products/signals/backend/scout_harness/views.py
+++ b/products/signals/backend/scout_harness/views.py
@@ -56,6 +56,7 @@ from posthog.clickhouse.query_tagging import tag_queries
# password-only user in a 2FA-enforced org read scout runs/scratchpad without
# completing 2FA.
from posthog.dataclasses import frozen
+from posthog.exceptions import InsufficientScope
from posthog.models.organization import OrganizationMembership
from posthog.models.team.team import Team
from posthog.models.user import User
@@ -3085,8 +3086,9 @@ def assert_can_grant_scout_write_scopes(
if token_scopes is not None and "*" not in token_scopes:
missing = scopes_missing_after_legacy_fallback(request, None, token_scopes, sorted(added_scopes))
if missing:
- raise exceptions.PermissionDenied(
- f"This API key does not carry {', '.join(missing)}, so it cannot grant that access to a scout."
+ raise InsufficientScope(
+ missing,
+ detail=f"This API key does not carry {', '.join(missing)}, so it cannot grant that access to a scout.",
)
level = UserPermissions(user=user, team=team).current_team.effective_membership_level
if level is not None and level >= OrganizationMembership.Level.ADMIN:
diff --git a/products/workflows/backend/presentation/views/hog_flow.py b/products/workflows/backend/presentation/views/hog_flow.py
index 2ee37b09a7c7..5c9af73266e6 100644
--- a/products/workflows/backend/presentation/views/hog_flow.py
+++ b/products/workflows/backend/presentation/views/hog_flow.py
@@ -63,6 +63,7 @@ from posthog.auth import InternalAPIAuthentication
from posthog.clickhouse.query_tagging import Feature, tag_queries
from posthog.dataclasses import frozen
from posthog.event_usage import AGENT_EVENT_SOURCES, EventSource, get_event_source, report_user_action
+from posthog.exceptions import InsufficientScope
from posthog.exceptions_capture import capture_exception
from posthog.helpers.impersonation import is_impersonated
from posthog.models import Team, User
@@ -723,14 +724,23 @@ def _strip_replay_vision_code(inputs: Any) -> None:
analysis.pop(key, None)
+def _replay_vision_missing_scopes(request: Request | None) -> list[str]:
+ """The scopes a token must add to save or run a Replay Vision step."""
+ scopes = get_authenticator_scopes(getattr(request, "successful_authenticator", None))
+ if scopes is None or "*" in scopes:
+ return []
+ return [accepted[0] for accepted in _REPLAY_VISION_STEP_SCOPES if not any(s in scopes for s in accepted)]
+
+
+def _replay_vision_scope_message(scope: str) -> str:
+ return f"The Replay Vision step needs a key with the {scope} scope."
+
+
def _replay_vision_step_error(request: Request | None, team: Team, inputs: Any) -> str | None:
"""Why the caller may not save or live-test a Replay Vision step with these inputs, or None."""
_strip_replay_vision_code(inputs)
- scopes = get_authenticator_scopes(getattr(request, "successful_authenticator", None))
- if scopes is not None and "*" not in scopes:
- for accepted in _REPLAY_VISION_STEP_SCOPES:
- if not any(scope in scopes for scope in accepted):
- return f"The Replay Vision step needs a key with the {accepted[0]} scope."
+ if missing_scopes := _replay_vision_missing_scopes(request):
+ return _replay_vision_scope_message(missing_scopes[0])
user = getattr(request, "user", None)
if user is None or not user.is_authenticated or isinstance(user, SyntheticUser):
return None
@@ -6553,10 +6563,13 @@ class HogFlowViewSet(
def _require_replay_vision_caller_access(self, request: Request, actions: Any) -> None:
# A live test or a manual run starts the Replay Vision step as the workflow's owner, on sessions the caller
# can pick, so the caller needs the access that saving the step needs.
+ missing_scopes = _replay_vision_missing_scopes(request)
for step in actions if isinstance(actions, list) else []:
config = (step.get("config") or {}) if isinstance(step, dict) else {}
if config.get("template_id") != _REPLAY_VISION_TEMPLATE_ID:
continue
+ if missing_scopes:
+ raise InsufficientScope(missing_scopes, detail=_replay_vision_scope_message(missing_scopes[0]))
error = _replay_vision_step_error(request, self.team, config.get("inputs"))
if error is not None:
raise exceptions.PermissionDenied(error)