adding-project-secret-api-key-auth
БесплатноБез исполняемых скриптовНе проверенHow to gate a PostHog API endpoint with project secret API key (PSAK) auth — a project-scoped, user-less service credential. Use when adding PSAK support to a…
от PostHog★ 41 278 звёзд на GitHubОб этом скилле
Adding project secret API key (PSAK) auth to an endpoint
What a PSAK is
A ProjectSecretAPIKey is a project-scoped, user-less service credential (posthog/models/project_secret_api_key.py). It behaves like a personal API key but survives users leaving the project, carries its own scopes, and authenticates as a synthetic user — not a real User row.
- Token format:
phs_...(Bearer header only — no body fallback). - Scopes are project-wide within their resource type and deliberately ignore object-level access controls (per-resource RBAC).
- The legacy per-team
Team.secret_api_token(alsophs_-prefixed) is retired (#66179): backfilled PSAK mirror rows authenticate those token strings now, and no verifier reads the column.
Keys are managed at POST /api/environments/:id/project_secret_api_keys (label + scopes; plaintext value returned once; roll action to rotate; max 50 per project; wildcard * scope not allowed).
Wiring a viewset action — the checklist
The machinery is shipped but nothing is wired to it yet — the first planned consumer is the endpoints (the product) run action. Four things, all required:
1. Whitelist the scope/action pair
PSAK-assignable scopes are a global allowlist in posthog/scopes/project_secret_api_key.py:
PROJECT_SECRET_API_KEY_ALLOWED_API_SCOPE_ACTION: list[tuple[APIScopeObject, APIScopeActions]] = [("endpoint", "read")]
If your product isn't listed, key creation rejects the scope before auth is ever attempted. Add your (scope_object, action) tuple here first.
Add the same scope to PROJECT_SECRET_API_KEY_ALLOWED_API_SCOPE_ACTION in frontend/src/lib/scopes.tsx. The scope picker in project settings builds its checkboxes from that list, so a backend-only change leaves users with no way to grant the scope. posthog/test/test_scopes.py compares the two lists.
2. Add the authenticator and opt in actions
class MyViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
scope_object = "endpoint"
authentication_classes = [ProjectSecretAPIKeyAuthentication] # extends, TeamAndOrgViewSetMixin keeps session/PAK auth
psak_allowed_actions = ["run"]
psak_allowed_actions is default-deny: APIScopePermission rejects any PSAK request whose action isn't listed ("This action does not support project secret API key access"). List only the programmatic actions — never CRUD that should stay human-driven.
APIScopePermission also enforces team binding automatically: a PSAK only works against view.team == key.team, so PSAK auth only makes sense on project-scoped (/api/environments/:id/...) routes.
3. Use PSAK-aware throttles
PersonalApiKeyRateThrottle subclasses silently bypass PSAK requests (no personal key → no throttling). Use the PSAK-aware pair from posthog/rate_limit.py:
PersonalOrProjectSecretApiKeyRateThrottle— per-key budget (keyedpsak:{key_id}), also still throttles personal keys.ProjectSecretApiKeyTeamRateThrottle— per-team aggregate (keyedpsak-team:{team_id}), caps total PSAK load regardless of how many keys a project mints. Stack it alongside the per-key throttle.
Subclass them to set product-specific scope/rate; remember each throttle keeps its own cache bucket per scope string.
4. Handle the synthetic user
request.user is a ProjectSecretAPIKeyUser (a SyntheticUser, posthog/synthetic_user.py), not a User:
user.idisNone— never use it as a foreign key. Useuser.current_team_id.has_perm()always returnsFalse— Django permission checks silently deny.Skip per-object access-control checks for it (PSAK scopes are project-wide by design):
if is_authenticated_via_project_secret_api_key(request): return # PSAK bypasses object-level RBAC deliberatelyUse
isinstance(user, ProjectSecretAPIKeyUser)only where no request is in scope.report_user_actiondrops synthetic users — if you need analytics for PSAK-authenticated calls, capture explicitly withposthoganalytics.capture(distinct_id=user.distinct_id, ...)and include anauth_methodproperty so both paths emit the same event shape.HogQL system tables:
Database.create_forhides RBAC-scoped system tables the key's scopes don't cover (viareadable_system_table_access_scopes()).
Helpers in posthog/permissions.py when you need to branch: is_authenticated_via_project_secret_api_key(request) and is_service_auth(request) (covers PSAK + legacy team token).
What you get for free
- Query tagging: the authenticator calls
tag_authentication(access_method=AccessMethod.PROJECT_SECRET_API_KEY, api_key_mask=..., api_key_label=...), so ClickHousequery_logattribution works with no per-endpoint code. If you add a new authenticator, tag throughtag_authentication(the single funnel inposthog/clickhouse/query_tagging.py) — not with ad-hoctag_queriescalls. last_used_attracking: updated at most hourly via `.
Установить adding-project-secret-api-key-auth в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
FAQ
Что делает скилл adding-project-secret-api-key-auth?
How to gate a PostHog API endpoint with project secret API key (PSAK) auth — a project-scoped, user-less service credential. Use when adding PSAK support to a viewset action, allowing a new scope for PSAKs, handling synthetic users (ProjectSecretAPIKeyUser), or choosing PSAK-aware rate throttles. Trigger terms: PSAK, ProjectSecretAPIKey, project secret API key, phs_ token, service auth, programmatic endpoint auth.
Как установить скилл adding-project-secret-api-key-auth?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл adding-project-secret-api-key-auth запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
mcp-builder
Guide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when…
от Anthropicclaude-api
Reference for the Claude API / Anthropic SDK — model ids, pricing, params, streaming, tool use, MCP, agents, caching, token counting, model migration. TRIGGER…
от Anthropicalgorithmic-art
Creating algorithmic art using p5.js with seeded randomness and interactive parameter exploration. Use this when users request creating art using code…
от Anthropicmcp-integration
This skill should be used when the user asks to "add MCP server", "integrate MCP", "configure MCP in plugin", "use .mcp.json", "set up Model Context…
от Anthropic