: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
feat(settings): warn about risky scopes when creating a personal API key (#127890)
Rafael Audibert9bd185cf43b9
diff --git a/frontend/src/lib/components/ScopeAccessRow/OAuthScopeList.tsx b/frontend/src/lib/components/ScopeAccessRow/OAuthScopeList.tsxindex 144819958d3d..865c376ee95f 100644--- a/frontend/src/lib/components/ScopeAccessRow/OAuthScopeList.tsx+++ b/frontend/src/lib/components/ScopeAccessRow/OAuthScopeList.tsx@@ -1,4 +1,4 @@-import { IconCheck } from '@posthog/icons'+import { IconCheck, IconWarning } from '@posthog/icons'import { LemonTag, Tooltip } from '@posthog/lemon-ui'import type { OAuthScopeGroup, OAuthScopeRow } from 'lib/oauthScopeRows'@@ -45,20 +45,28 @@ export function OAuthScopeList({</li>))}{requiredScopeRows.map((row) => (- <li key={row.key} className="flex items-center space-x-2">- <IconCheck color="var(--success)" className="shrink-0" />- <span className="font-medium">{row.description}</span>- {row.alreadyGranted ? (- <Tooltip title={`You granted this to ${appName} before`}>- <LemonTag>Already granted</LemonTag>- </Tooltip>- ) : (- !allScopesRequired && (- <Tooltip title={`${appName} requires this permission`}>- <LemonTag>Required</LemonTag>+ <li key={row.key} className="space-y-1">+ <div className="flex items-center space-x-2">+ <IconCheck color="var(--success)" className="shrink-0" />+ <span className="font-medium">{row.description}</span>+ {row.alreadyGranted ? (+ <Tooltip title={`You granted this to ${appName} before`}>+ <LemonTag>Already granted</LemonTag></Tooltip>- )- )}+ ) : (+ !allScopesRequired && (+ <Tooltip title={`${appName} requires this permission`}>+ <LemonTag>Required</LemonTag>+ </Tooltip>+ )+ )}+ </div>+ {row.warning ? (+ <div className="flex items-start gap-2 text-xs italic pl-6">+ <IconWarning className="text-base text-secondary mt-0.5" />+ <span>{row.warning}</span>+ </div>+ ) : null}</li>))}</ul>diff --git a/frontend/src/lib/oauthScopeRows.ts b/frontend/src/lib/oauthScopeRows.tsindex bec50034d11a..bd086ed2aa26 100644--- a/frontend/src/lib/oauthScopeRows.ts+++ b/frontend/src/lib/oauthScopeRows.ts@@ -3,6 +3,7 @@ import {clampScopeLevel,getScopeDescription,groupScopeRows,+ scopeRowWarning,type ScopeAccessLevel,type ScopePickerGroup,type ScopePickerRow,@@ -114,7 +115,7 @@ export function buildOAuthScopeRows(label: key === '*' ? WILDCARD_LABEL : (apiScope?.objectName ?? humanizeScopeKey(key)),description: getScopeDescription(grantedScope) ?? grantedScope,info: apiScope?.info,- warning: value === 'none' ? undefined : apiScope?.warnings?.[value],+ warning: key === '*' ? undefined : scopeRowWarning(apiScope, key, value),muted: value === 'none',disabledReasons,minLevel,diff --git a/frontend/src/lib/oauthScopes.generated.ts b/frontend/src/lib/oauthScopes.generated.tsindex 54e17add791e..6ae4c0dfa70f 100644--- a/frontend/src/lib/oauthScopes.generated.ts+++ b/frontend/src/lib/oauthScopes.generated.ts@@ -278,3 +278,29 @@ export const LEGACY_SCOPE_FALLBACKS: ReadonlyMap<string, string> = new Map([['messaging_preference', 'hog_flow'],['transactional_email', 'hog_flow'],])++// What each risky scope lets a token do (mirrors RISKY_SCOPE_WARNINGS in posthog/scopes.py).+// Scope pickers show it next to the scope, so people add it with care.+export const RISKY_SCOPE_WARNINGS: Readonly<Record<string, string>> = {+ 'access_control:write': 'Changes who can access resources in this project.',+ 'approvals:write': 'Approves or rejects change requests that gate other changes.',+ 'autoresearch:write': 'Starts agent runs that get their own longer-lived token.',+ 'billing:read': "Reads the whole organization's billing details, not just this project's.",+ 'billing:write': "Changes the organization's subscription and payment details.",+ 'hog_flow:write': "Runs workflow code that can use the stored credentials of the project's integrations.",+ 'hog_function:write':+ "Runs code, including on your website, that can use the stored credentials of the project's integrations.",+ 'integration:write': 'Connects and changes third-party integrations and their stored credentials.',+ 'llm_provider_key:write': 'Stores and changes LLM provider API keys.',+ 'organization:write': 'Changes organization settings, including roles and OAuth apps.',+ 'organization_integration:write':+ 'Connects and changes organization-wide integrations and their stored credentials.',+ 'organization_member:write':+ "Invites and removes organization members and changes their roles, so it can give people access beyond this token's scopes.",+ 'sharing_configuration:read':+ 'Reads the access tokens of public sharing links, which keep working after this token expires.',+ 'sharing_configuration:write': 'Creates public sharing links that anyone with the link can open.',+ 'user:read':+ 'Reads the account details of the user the token acts as, including every organization and project they belong to.',+ 'user:write': 'Changes the account of the user the token acts as.',+}diff --git a/frontend/src/lib/scopes.tsx b/frontend/src/lib/scopes.tsxindex 1d8ac98b4605..415e60253ff9 100644--- a/frontend/src/lib/scopes.tsx+++ b/frontend/src/lib/scopes.tsx@@ -1,4 +1,5 @@import { AGENT_USE_CASE_SCOPES } from 'lib/agentScopes.generated'+import { RISKY_SCOPE_WARNINGS } from 'lib/oauthScopes.generated'import type { APIScopeAction, APIScopeObject } from '~/types'@@ -142,6 +143,26 @@ export const riskyScopeWarning = (return warnings.length > 0 ? `Add with care: ${warnings.join(' ')}` : undefined}+/**+ * What a personal API key or OAuth scope row warns about at the picked level: the scope's own note, such as a+ * feature flag it also writes, followed by the backend's risky scope warning.+ */+export function scopeRowWarning(+ apiScope: APIScope | undefined,+ scopeObject: string,+ level: ScopeAccessLevel+): string | JSX.Element | undefined {+ const note = level === 'none' ? undefined : apiScope?.warnings?.[level]+ const risky = riskyScopeWarning(scopeObject, level, RISKY_SCOPE_WARNINGS)+ return note && risky ? (+ <>+ {note} {risky}+ </>+ ) : (+ (note ?? risky)+ )+}+// Scopes whose write action also writes a feature flag as a side effect (survey targeting flag,// early access feature linked flag), so they imply `feature_flag:write`. Single source of truth for// both the picker warning (attached below) and the auto-select in personalAPIKeysLogic, so the rule@@ -288,15 +309,6 @@ export const API_SCOPES: APIScope[] = [objectName: 'Organization member',objectPlural: 'organization members',disabledWhenProjectScoped: true,- warnings: {- write: (- <>- This scope can be used to invite users to your organization,- <br />- effectively <strong>allowing access to other scopes via the added user</strong>.- </>- ),- },},{ key: 'person', objectName: 'Person', objectPlural: 'persons' },{ key: 'customer_profile_config', objectName: 'Customer profile config', objectPlural: 'customer profile configs' },@@ -353,15 +365,6 @@ export const API_SCOPES: APIScope[] = [objectName: 'User',objectPlural: 'users',disabledActions: ['write'],- warnings: {- read: (- <>- This scope allows you to retrieve your own user object.- <br />- Note that the user object <strong>lists all organizations and projects you're in</strong>.- </>- ),- },},{ key: 'signal_scout', objectName: 'Signals agent', objectPlural: 'signals agents' },{diff --git a/frontend/src/scenes/authentication/cli/CLIAuthorize.tsx b/frontend/src/scenes/authentication/cli/CLIAuthorize.tsxindex 805893e7e570..542d446cf499 100644--- a/frontend/src/scenes/authentication/cli/CLIAuthorize.tsx+++ b/frontend/src/scenes/authentication/cli/CLIAuthorize.tsx@@ -7,7 +7,7 @@ import { LemonButton, LemonInput, LemonSelect, Link } from '@posthog/lemon-ui'import { ScopeAccessRow } from 'lib/components/ScopeAccessRow/ScopeAccessRow'import { IconErrorOutline } from 'lib/lemon-ui/icons'import { LemonField } from 'lib/lemon-ui/LemonField'-import type { ScopeAccessLevel } from 'lib/scopes'+import { scopeRowWarning, type ScopeAccessLevel } from 'lib/scopes'import { AuthBanner } from 'scenes/authentication/shared/authScene/AuthBanner'import { AuthCardTitle } from 'scenes/authentication/shared/authScene/AuthCardTitle'import { AUTH_NOTES } from 'scenes/authentication/shared/authScene/authNotes'@@ -177,38 +177,34 @@ export function CLIAuthorize(): JSX.Element {No scopes match "{searchTerm}"</div>) : (- filteredScopes.map(- ({ key, objectName, disabledActions, warnings, info }) => {- const value = (formScopeRadioValues[key] ??- 'none') as ScopeAccessLevel- const disabledReason = (- action: 'read' | 'write'- ): string | undefined =>- disabledActions?.includes(action)- ? 'Does not apply to this resource'- : undefined- return (- <ScopeAccessRow- key={key}- row={{- key,- label: objectName,- info,- value,- warning:- value === 'none'- ? undefined- : warnings?.[value],- disabledReasons: {- read: disabledReason('read'),- write: disabledReason('write'),- },- }}- onChange={setScopeRadioValue}- />- )- }- )+ filteredScopes.map((apiScope) => {+ const { key, objectName, disabledActions, info } = apiScope+ const value = (formScopeRadioValues[key] ??+ 'none') as ScopeAccessLevel+ const disabledReason = (+ action: 'read' | 'write'+ ): string | undefined =>+ disabledActions?.includes(action)+ ? 'Does not apply to this resource'+ : undefined+ return (+ <ScopeAccessRow+ key={key}+ row={{+ key,+ label: objectName,+ info,+ value,+ warning: scopeRowWarning(apiScope, key, value),+ disabledReasons: {+ read: disabledReason('read'),+ write: disabledReason('write'),+ },+ }}+ onChange={setScopeRadioValue}+ />+ )+ }))}</div></>diff --git a/frontend/src/scenes/settings/user/personalAPIKeysLogic.tsx b/frontend/src/scenes/settings/user/personalAPIKeysLogic.tsxindex af1cbf64514d..a97521f7b9d8 100644--- a/frontend/src/scenes/settings/user/personalAPIKeysLogic.tsx+++ b/frontend/src/scenes/settings/user/personalAPIKeysLogic.tsx@@ -20,6 +20,7 @@ import {type ScopePickerGroup,type ScopeAccessLevel,type ScopePickerRow,+ scopeRowWarning,clampScopeLevel,groupScopeRows,scopeMatchesSearch,@@ -307,7 +308,7 @@ export interface personalAPIKeysLogicMeta {__keaTypeGenInternalSelectorTypes: {allowedScopes: (featureFlags: FeatureFlagsSet,- hasAvailableFeature: (feature: AvailableFeature, currentUsage?: number | undefined) => boolean+ hasAvailableFeature: (feature: AvailableFeature, currentUsage?: number | undefined) => boolean // userLogic) => APIScope[]allowedScopeKeys: (allowedScopes: APIScope[]) => Set<string>scopeRows: (@@ -553,7 +554,7 @@ export const personalAPIKeysLogic = kea<personalAPIKeysLogicType>([label: scope.objectName,info: scope.info,value,- warning: value === 'none' ? undefined : scope.warnings?.[value],+ warning: scopeRowWarning(scope, scope.key, value),muted: Boolean(projectScoped),disabledReasons: { read: disabledReason('read'), write: disabledReason('write') },}diff --git a/posthog/scopes_projection.py b/posthog/scopes_projection.pyindex 298d37bb46fe..3b1d6b34096f 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 three constants:+Each carries four constants:- OAUTH_SCOPES_SUPPORTED (from `get_oauth_scopes_supported()`): the MCP serverpublishes RFC 9728 protected-resource metadata at@@ -22,6 +22,8 @@ Each carries three constants:- LEGACY_SCOPE_FALLBACKS: a new scope object mapped to the legacy one it splitoff. The MCP server applies it in `hasScope` (`src/lib/api.ts`), so a tokencarrying only the legacy scope still sees and calls tools that require the new one.+- RISKY_SCOPE_WARNINGS: what each risky scope lets a token do. The web app's scope pickers show it+ next to the scope, so every picker uses the same wording as the workload trust policy screens.Generating both from `posthog/scopes.py` keeps that module the singleauthority for scope classification; the TS side is a projection of it.@@ -52,9 +54,13 @@ def render_oauth_scopes() -> str: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"]+ risky_scope_warnings: dict[str, str] = scopes_globals["RISKY_SCOPE_WARNINGS"]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)+ risky_body = "".join(+ f" {json.dumps(scope)}: {json.dumps(warning)},\n" for scope, warning in sorted(risky_scope_warnings.items())+ )fallbacks_body = "".join(f" [{json.dumps(new)}, {json.dumps(legacy)}],\n" for new, legacy in sorted(legacy_fallbacks.items()))@@ -91,6 +97,12 @@ def render_oauth_scopes() -> str:"export const LEGACY_SCOPE_FALLBACKS: ReadonlyMap<string, string> = new Map([\n"f"{fallbacks_body}""])\n"+ "\n"+ "// What each risky scope lets a token do (mirrors RISKY_SCOPE_WARNINGS in posthog/scopes.py).\n"+ "// Scope pickers show it next to the scope, so people add it with care.\n"+ "export const RISKY_SCOPE_WARNINGS: Readonly<Record<string, string>> = {\n"+ f"{risky_body}"+ "}\n")return outputdiff --git a/posthog/test/test_middleware.py b/posthog/test/test_middleware.pyindex 8abad2dbf47f..28b86e8b948b 100644--- a/posthog/test/test_middleware.py+++ b/posthog/test/test_middleware.py@@ -11,6 +11,7 @@ from unittest.mock import MagicMock, patchfrom django.conf import settingsfrom django.contrib.auth.models import AnonymousUser+from django.contrib.contenttypes.models import ContentTypefrom django.core.cache import cachefrom django.db import connectionfrom django.http import HttpRequest, HttpResponse, HttpResponseRedirect@@ -519,6 +520,9 @@ class TestAutoProjectMiddleware(APIBaseTest):# Reset back to initial team/org for each testself.user.current_team = self.teamself.user.current_organization = self.organization+ # The page load reads a content type through Django's per-process cache. Without a reset, the query+ # counts depend on whether an earlier test in the same process already filled that cache.+ ContentType.objects.clear_cache()def app_context(self, response) -> dict:return response.context["posthog_app_context"]diff --git a/services/mcp/src/lib/oauth-scopes.generated.ts b/services/mcp/src/lib/oauth-scopes.generated.tsindex 54e17add791e..6ae4c0dfa70f 100644--- a/services/mcp/src/lib/oauth-scopes.generated.ts+++ b/services/mcp/src/lib/oauth-scopes.generated.ts@@ -278,3 +278,29 @@ export const LEGACY_SCOPE_FALLBACKS: ReadonlyMap<string, string> = new Map([['messaging_preference', 'hog_flow'],['transactional_email', 'hog_flow'],])++// What each risky scope lets a token do (mirrors RISKY_SCOPE_WARNINGS in posthog/scopes.py).+// Scope pickers show it next to the scope, so people add it with care.+export const RISKY_SCOPE_WARNINGS: Readonly<Record<string, string>> = {+ 'access_control:write': 'Changes who can access resources in this project.',+ 'approvals:write': 'Approves or rejects change requests that gate other changes.',+ 'autoresearch:write': 'Starts agent runs that get their own longer-lived token.',+ 'billing:read': "Reads the whole organization's billing details, not just this project's.",+ 'billing:write': "Changes the organization's subscription and payment details.",+ 'hog_flow:write': "Runs workflow code that can use the stored credentials of the project's integrations.",+ 'hog_function:write':+ "Runs code, including on your website, that can use the stored credentials of the project's integrations.",+ 'integration:write': 'Connects and changes third-party integrations and their stored credentials.',+ 'llm_provider_key:write': 'Stores and changes LLM provider API keys.',+ 'organization:write': 'Changes organization settings, including roles and OAuth apps.',+ 'organization_integration:write':+ 'Connects and changes organization-wide integrations and their stored credentials.',+ 'organization_member:write':+ "Invites and removes organization members and changes their roles, so it can give people access beyond this token's scopes.",+ 'sharing_configuration:read':+ 'Reads the access tokens of public sharing links, which keep working after this token expires.',+ 'sharing_configuration:write': 'Creates public sharing links that anyone with the link can open.',+ 'user:read':+ 'Reads the account details of the user the token acts as, including every organization and project they belong to.',+ 'user:write': 'Changes the account of the user the token acts as.',+}