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.

feat(permissions): let task scopes satisfy inbox scopes during the move (#120403)

posthog[bot]cc51d206a26f
diff --git a/frontend/src/lib/oauthScopes.generated.ts b/frontend/src/lib/oauthScopes.generated.ts
index d78d247a7250..253e1d3bb63b 100644
--- a/frontend/src/lib/oauthScopes.generated.ts
+++ b/frontend/src/lib/oauthScopes.generated.ts
@@ -257,3 +257,8 @@ export const OAUTH_SCOPES_HIDDEN = [
'wizard_session:read',
'wizard_session:write',
] as const
+
+// A new scope object mapped to the legacy one it split off (mirrors LEGACY_SCOPE_FALLBACKS
+// in posthog/scopes.py). While old tokens carry only the legacy scope, a held
+// `<legacy>:<action>` satisfies a required `<new>:<action>`.
+export const LEGACY_SCOPE_FALLBACKS: ReadonlyMap<string, string> = new Map([['inbox', 'task']])
diff --git a/posthog/permissions.py b/posthog/permissions.py
index 011246519ef3..0df695e9c0d8 100644
--- a/posthog/permissions.py
+++ b/posthog/permissions.py
@@ -4,6 +4,7 @@ import uuid
from typing import Any, Optional, cast
from django.conf import settings
+from django.core.cache import cache
from django.core.exceptions import ImproperlyConfigured
from django.db.models import Model
@@ -41,6 +42,7 @@ from posthog.scopes import (
MCP_BUILT_IN_AGENT_SCOPE,
APIScopeObject,
APIScopeObjectOrNotSupported,
+ scopes_covered_by_legacy_fallback,
scopes_not_covered,
)
from posthog.session.reauth import sensitive_action_reference, step_up_required
@@ -830,6 +832,32 @@ def get_authenticator_scoped_team_ids(authenticator) -> list[int] | None:
return None
+LEGACY_SCOPE_FALLBACK_EVENT_INTERVAL_SECONDS = 60 * 60
+
+
+def _capture_legacy_scope_fallback(request: Request, view: APIView, required_scope: str, legacy_scope: str) -> None:
+ """Record that a legacy scope satisfied a required scope. The events show which credentials and
+ OAuth apps still depend on the legacy scope, so the entry in LEGACY_SCOPE_FALLBACKS can go."""
+ client = get_authenticator_client(request.successful_authenticator)
+ distinct_id = str(getattr(request.user, "distinct_id", None) or client["client_id"])
+ view_name = type(view).__name__
+ # At most one event per caller, client, scope and view each interval, because this runs on every request.
+ throttle_key = f"legacy_scope_fallback:{distinct_id}:{client['client_id']}:{required_scope}:{view_name}"
+ if not cache.add(throttle_key, True, timeout=LEGACY_SCOPE_FALLBACK_EVENT_INTERVAL_SECONDS):
+ return
+ posthoganalytics.capture(
+ distinct_id=distinct_id,
+ event="api scope fallback used",
+ properties={
+ "required_scope": required_scope,
+ "legacy_scope": legacy_scope,
+ "credential_type": client["credential_type"],
+ "client_id": client["client_id"],
+ "view": view_name,
+ },
+ )
+
+
class APIScopePermission(ScopeBasePermission):
"""
The request is via an API key or OAuth token and the user has the appropriate scopes.
@@ -907,10 +935,15 @@ class APIScopePermission(ScopeBasePermission):
return True
missing_scopes = scopes_not_covered(key_scopes, required_scopes)
+ legacy_covered = scopes_covered_by_legacy_fallback(key_scopes, missing_scopes)
+ missing_scopes = [scope for scope in missing_scopes if scope not in legacy_covered]
if missing_scopes:
self.message = f"API key missing required scope '{missing_scopes[0]}'"
return False
+ for required_scope, legacy_scope in legacy_covered.items():
+ _capture_legacy_scope_fallback(request, view, required_scope, legacy_scope)
+
return True
def _check_project_secret_api_key_team(self, request, view) -> None:
diff --git a/posthog/scopes.py b/posthog/scopes.py
index bbac3d2a6e79..ced1cc5e00b1 100644
--- a/posthog/scopes.py
+++ b/posthog/scopes.py
@@ -459,6 +459,30 @@ def scopes_not_covered(held_scopes: Iterable[str], required_scopes: Iterable[str
return [scope for scope in required_scopes if scope not in covered]
+# A new scope object split off a legacy one, mapped to that legacy object. While old keys and tokens
+# carry only the legacy scope, a held `<legacy>:<action>` satisfies a required `<new>:<action>`.
+# APIScopePermission applies this and records each use, so the entry can go when no caller needs it.
+# Project secret API key issuance does not apply it: a key must not get a scope on the strength of a
+# legacy one. `hogli build:projections` copies this map to the MCP server, which applies it in `hasScope`.
+LEGACY_SCOPE_FALLBACKS: dict[str, str] = {"inbox": "task"}
+
+
+def scopes_covered_by_legacy_fallback(held_scopes: Iterable[str], missing_scopes: Iterable[str]) -> dict[str, str]:
+ """The missing scopes that a legacy scope in LEGACY_SCOPE_FALLBACKS covers, each mapped to that
+ legacy scope. The legacy scope follows the same rule as `scopes_not_covered`: `:write` covers `:read`."""
+ held = frozenset(held_scopes)
+ covered: dict[str, str] = {}
+ for scope in missing_scopes:
+ scope_object, _, action = scope.partition(":")
+ legacy_object = LEGACY_SCOPE_FALLBACKS.get(scope_object)
+ if legacy_object is None:
+ continue
+ legacy_scope = f"{legacy_object}:{action}"
+ if not scopes_not_covered(held, [legacy_scope]):
+ covered[scope] = legacy_scope
+ return covered
+
+
def scopes_within_ceiling(
requested: Iterable[str],
app_scopes: Iterable[str],
diff --git a/posthog/scopes_projection.py b/posthog/scopes_projection.py
index 112d55217022..298d37bb46fe 100755
--- a/posthog/scopes_projection.py
+++ b/posthog/scopes_projection.py
@@ -2,7 +2,7 @@
Writes the same file to two trees: `services/mcp/src/lib/oauth-scopes.generated.ts`
for the MCP server and `frontend/src/lib/oauthScopes.generated.ts` for the web app.
-Each carries two constants:
+Each carries three constants:
- OAUTH_SCOPES_SUPPORTED (from `get_oauth_scopes_supported()`): the MCP server
publishes RFC 9728 protected-resource metadata at
@@ -19,6 +19,9 @@ Each carries two constants:
and in tests to allow tools to require a non-advertised scope on purpose.
The web app's scope pickers never show these objects, and scopes.test.ts
exempts them from the picker rows and groups every other object needs.
+- LEGACY_SCOPE_FALLBACKS: a new scope object mapped to the legacy one it split
+ off. The MCP server applies it in `hasScope` (`src/lib/api.ts`), so a token
+ carrying only the legacy scope still sees and calls tools that require the new one.
Generating both from `posthog/scopes.py` keeps that module the single
authority for scope classification; the TS side is a projection of it.
@@ -48,9 +51,13 @@ def render_oauth_scopes() -> str:
scopes_globals = runpy.run_path(str(SCOPES_PY))
all_scopes: list[str] = scopes_globals["get_oauth_scopes_supported"]()
hidden_scopes: list[str] = sorted(scopes_globals["OAUTH_SCOPES_HIDDEN"])
+ legacy_fallbacks: dict[str, str] = scopes_globals["LEGACY_SCOPE_FALLBACKS"]
body = ",\n".join(f" {json.dumps(s)}" for s in all_scopes)
hidden_body = ",\n".join(f" {json.dumps(s)}" for s in hidden_scopes)
+ fallbacks_body = "".join(
+ f" [{json.dumps(new)}, {json.dumps(legacy)}],\n" for new, legacy in sorted(legacy_fallbacks.items())
+ )
output = (
"// AUTO-GENERATED by posthog/scopes_projection.py from posthog/scopes.py.\n"
"// Regenerate with `hogli build:projections`. Do not edit.\n"
@@ -77,6 +84,13 @@ def render_oauth_scopes() -> str:
"export const OAUTH_SCOPES_HIDDEN = [\n"
f"{hidden_body},\n"
"] as const\n"
+ "\n"
+ "// A new scope object mapped to the legacy one it split off (mirrors LEGACY_SCOPE_FALLBACKS\n"
+ "// in posthog/scopes.py). While old tokens carry only the legacy scope, a held\n"
+ "// `<legacy>:<action>` satisfies a required `<new>:<action>`.\n"
+ "export const LEGACY_SCOPE_FALLBACKS: ReadonlyMap<string, string> = new Map([\n"
+ f"{fallbacks_body}"
+ "])\n"
)
return output
diff --git a/posthog/test/test_permissions.py b/posthog/test/test_permissions.py
index 2a854f90cfee..3b160202e493 100644
--- a/posthog/test/test_permissions.py
+++ b/posthog/test/test_permissions.py
@@ -1,6 +1,7 @@
import json
from datetime import timedelta
from typing import cast
+from uuid import uuid4
from posthog.test.base import BaseTest
from unittest.mock import Mock, PropertyMock, patch
@@ -38,11 +39,13 @@ from posthog.permissions import (
FEATURE_FLAG_REQUIRED_ERROR_CODE,
AccessControlPermission,
ActiveOrganizationPermission,
+ APIScopePermission,
PostHogFeatureFlagPermission,
SharingTokenPermission,
extract_organization,
get_authenticator_client,
)
+from posthog.scopes import scopes_not_covered
from posthog.test.authentication_checks import covers_authentication
from products.access_control.backend.facade.contracts import ObjectAccessRef
@@ -580,6 +583,76 @@ class TestProjectSecretAPIKeyAPIScopePermission(SimpleTestCase):
self.assertIn("does not have access to the requested project", str(ctx.exception.detail))
+class _ScopedView:
+ def __init__(self, scope_object: str, action: str) -> None:
+ self.scope_object = scope_object
+ self.action = action
+
+
+class TestAPIScopePermissionLegacyFallback(SimpleTestCase):
+ def setUp(self) -> None:
+ self.permission = APIScopePermission()
+ capture_patcher = patch("posthog.permissions.posthoganalytics.capture")
+ self.capture = capture_patcher.start()
+ self.addCleanup(capture_patcher.stop)
+
+ def _make_personal_api_key_request(self, scopes: list[str]) -> Mock:
+ authenticator = Mock(spec=PersonalAPIKeyAuthentication)
+ authenticator.personal_api_key = Mock(scopes=scopes, scoped_teams=[], scoped_organizations=[])
+ request = Mock()
+ request.method = "GET"
+ request.successful_authenticator = authenticator
+ # A fresh caller per request, so the per-caller throttle cannot carry over between cases.
+ request.user = Mock(distinct_id=str(uuid4()))
+ return request
+
+ def _view_requiring(self, required_scope: str) -> _ScopedView:
+ scope_object, action = required_scope.split(":")
+ return _ScopedView(scope_object, "create" if action == "write" else "list")
+
+ @parameterized.expand(
+ [
+ ("task_read_satisfies_inbox_read", ["task:read"], "inbox:read", True, "task:read"),
+ ("task_write_satisfies_inbox_read", ["task:write"], "inbox:read", True, "task:read"),
+ ("task_write_satisfies_inbox_write", ["task:write"], "inbox:write", True, "task:write"),
+ ("task_read_does_not_satisfy_inbox_write", ["task:read"], "inbox:write", False, None),
+ ("inbox_read_needs_no_fallback", ["inbox:read"], "inbox:read", True, None),
+ ("fallback_only_covers_mapped_objects", ["task:write"], "insight:read", False, None),
+ ]
+ )
+ def test_task_scopes_satisfy_inbox_scopes(
+ self, _name: str, scopes: list[str], required_scope: str, allowed: bool, legacy_scope: str | None
+ ) -> 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 legacy_scope is None:
+ self.capture.assert_not_called()
+ else:
+ self.capture.assert_called_once()
+ assert self.capture.call_args.kwargs["properties"] == {
+ "required_scope": required_scope,
+ "legacy_scope": legacy_scope,
+ "credential_type": "personal_api_key",
+ "client_id": "personal_api_key",
+ "view": "_ScopedView",
+ }
+
+ def test_fallback_event_is_throttled_per_caller(self) -> None:
+ request = self._make_personal_api_key_request(["task:read"])
+
+ assert self.permission.has_permission(request, self._view_requiring("inbox:read"))
+ assert self.permission.has_permission(request, self._view_requiring("inbox:read"))
+
+ self.capture.assert_called_once()
+
+ def test_project_secret_api_key_issuance_rule_ignores_the_fallback(self) -> None:
+ assert scopes_not_covered(["task:write"], ["inbox:read", "inbox:write"]) == ["inbox:read", "inbox:write"]
+
+
class TestTeamMemberAccessPermission(BaseTest):
"""Direct unit tests for TeamMemberAccessPermission.has_permission method"""
diff --git a/services/mcp/src/lib/api.ts b/services/mcp/src/lib/api.ts
index 0670f18d0de6..029a742bb014 100644
--- a/services/mcp/src/lib/api.ts
+++ b/services/mcp/src/lib/api.ts
@@ -1,3 +1,5 @@
+import { LEGACY_SCOPE_FALLBACKS } from '@/lib/oauth-scopes.generated'
+
const SERVER_MINT_ONLY_SCOPE_OBJECTS = new Set([
'context_layer_internal',
'internal_run',
@@ -7,7 +9,7 @@ const SERVER_MINT_ONLY_SCOPE_OBJECTS = new Set([
'signal_scratchpad_internal',
])
-export const hasScope = (scopes: string[], requiredScope: string): boolean => {
+const holdsScope = (scopes: string[], requiredScope: string): boolean => {
const scopeObject = requiredScope.split(':', 1)[0]
const isServerMintOnly = scopeObject !== undefined && SERVER_MINT_ONLY_SCOPE_OBJECTS.has(scopeObject)
@@ -26,6 +28,17 @@ export const hasScope = (scopes: string[], requiredScope: string): boolean => {
return scopes.includes(requiredScope)
}
+// Mirrors APIScopePermission (`posthog/permissions.py`): a held legacy scope satisfies the new scope object
+// that split off it. The backend records each use, because every MCP call reaches it with the same token.
+export const hasScope = (scopes: string[], requiredScope: string): boolean => {
+ if (holdsScope(scopes, requiredScope)) {
+ return true
+ }
+ const [scopeObject, action] = requiredScope.split(':', 2)
+ const legacyObject = scopeObject !== undefined ? LEGACY_SCOPE_FALLBACKS.get(scopeObject) : undefined
+ return legacyObject !== undefined && holdsScope(scopes, `${legacyObject}:${action}`)
+}
+
export const hasScopes = (scopes: string[], requiredScopes: string[]): boolean => {
return requiredScopes.every((scope) => hasScope(scopes, scope))
}
diff --git a/services/mcp/src/lib/oauth-scopes.generated.ts b/services/mcp/src/lib/oauth-scopes.generated.ts
index d78d247a7250..253e1d3bb63b 100644
--- a/services/mcp/src/lib/oauth-scopes.generated.ts
+++ b/services/mcp/src/lib/oauth-scopes.generated.ts
@@ -257,3 +257,8 @@ export const OAUTH_SCOPES_HIDDEN = [
'wizard_session:read',
'wizard_session:write',
] as const
+
+// A new scope object mapped to the legacy one it split off (mirrors LEGACY_SCOPE_FALLBACKS
+// in posthog/scopes.py). While old tokens carry only the legacy scope, a held
+// `<legacy>:<action>` satisfies a required `<new>:<action>`.
+export const LEGACY_SCOPE_FALLBACKS: ReadonlyMap<string, string> = new Map([['inbox', 'task']])
diff --git a/services/mcp/tests/unit/tool-filtering.test.ts b/services/mcp/tests/unit/tool-filtering.test.ts
index 6e789fdfc5c7..cb3283883934 100644
--- a/services/mcp/tests/unit/tool-filtering.test.ts
+++ b/services/mcp/tests/unit/tool-filtering.test.ts
@@ -645,6 +645,18 @@ describe('server-minted scope matching', () => {
expect(hasScope(['signal_scout_report:write'], 'signal_scout_internal:read')).toBe(false)
})
+ // Keys and tokens issued before the inbox got its own scope carry only `task:*`.
+ it.each([
+ { held: ['task:read'], required: 'inbox:read', allowed: true },
+ { held: ['task:write'], required: 'inbox:read', allowed: true },
+ { held: ['task:write'], required: 'inbox:write', allowed: true },
+ { held: ['task:read'], required: 'inbox:write', allowed: false },
+ { held: ['inbox:read'], required: 'inbox:read', allowed: true },
+ { held: ['task:write'], required: 'insight:read', allowed: false },
+ ])('lets a legacy task scope satisfy an inbox scope: $held -> $required', ({ held, required, allowed }) => {
+ expect(hasScope(held, required)).toBe(allowed)
+ })
+
it('leaves wildcard and write-implies-read intact for user-grantable scopes', () => {
expect(hasScope(['*'], 'insight:read')).toBe(true)
expect(hasScope(['*'], 'insight:write')).toBe(true)