adding-project-secret-api-key-auth
Skill727 starsChanged yesterdayMITView on GitHub
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.
- Reads credentials
We split this skill into the rules it gives an agent
4 rules. About 0 are common, 0 are distinctive, and 4 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈0
Distinctive · estimate
This author's own choices. Worth a look.
4
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- could be automatic: a setting could enforce it
- Very specific: line 14
Do not confuse with TeamSecretTokenAuthentication — that validates the legacy per-team Team.secret_api_token (also phs_-prefixed) and is …
- Very specific: line 30
If your product isn't listed, key creation rejects the scope before auth is ever attempted.
- Very specific: line 32
Add the same scope to PROJECT_SECRET_API_KEY_ALLOWED_API_SCOPE_ACTION in frontend/src/lib/scopes.tsx.
- Very specific: line 69
Use isinstance(user, ProjectSecretAPIKeyUser) only where no request is in scope.
≈ “Common” is an estimate: at least 1 in 5 of the 308,232 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
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, unlike the legacy token). - Scopes are project-wide within their resource type and deliberately ignore object-level access controls (per-resource RBAC).
- Do not confuse with
TeamSecretTokenAuthentication— that validates the legacy per-teamTeam.secret_api_token(alsophs_-prefixed) and is only for feature-flag local evaluation and similar pre-PSAK surfaces. It is pegged for migrating to PSAK at some point.
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.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.update()(bypassesModelActivityMixinso routine auth doesn't spam the activity log).- Activity logging on key create/update/roll/delete.
Calling a PSAK-gated endpoint
curl -s https://us.posthog.com/api/environments/<project_id>/<your_action_path>/ \
-H "Authorization: Bearer phs_<key>" \
-H "Content-Type: application/json" \
-d '{...}'Testing
Mirror the PSAK sections of posthog/api/test/test_authentication.py, posthog/test/test_permissions.py, and posthog/test/test_rate_limit.py. Cover at minimum:
- allowed action with correct scope → 200
- action not in
psak_allowed_actions→ 403 - missing/wrong scope → 403
- key from another team's project → 403
- non-PSAK auth on the same action still works
Other versions1 project uses a version of this.
Word for word · 1
- PostHog/posthog★ 40k100% same
Edited · 0
None found.
Wrote their own version · 0
None found.
How matches are found. Word for word: the exact same text. Edited: shares passages with this file (“99% same” means 99% of its five-word phrases also appear here; 10% or more counts). Their own version: similar meaning, or, weakest, the same name. We can’t tell which project had it first. Projects are counted among the 200 most-starred candidates, and mentions are links to the repository we found, up to 50 per site, so both counts are a floor.
In this repository124 other files it gives its agents.
- AGENTS.mdAGENTS.md
- common/AGENTS.mdAGENTS.md
- hog/AGENTS.mdAGENTS.md
- proto/AGENTS.mdAGENTS.md
- rust/AGENTS.mdAGENTS.md
- .cursor/rules/django-python.mdcCursor rule
- .cursor/rules/react-typescript.mdcCursor rule
- .cursor/rules/rust.mdcCursor rule
- adding-activity-loggingSkill
- adding-api-scopesSkill
- adding-inbound-webhooksSkill
- adding-inbox-sourcesSkill
- adding-ingestion-warningsSkill
- adding-mcp-store-serversSkill
- adding-personhog-rpcSkill
- adding-product-alertingSkill
- adding-today-highlightsSkill
- adopting-generated-api-typesSkill
- analyzing-experiment-precompute-canarySkill
- analyzing-experiment-query-performanceSkill
- analyzing-insights-across-teamsSkill
- announcing-behavior-changesSkill
- auditing-llm-gateway-paritySkill
- auditing-warehouse-source-coverageSkill
- authenticating-to-clickhouseSkill
- authoring-ci-workflowsSkill
- building-product-empty-statesSkill
- building-the-toolbarSkill
- clickhouse-migrationsSkill
- debugging-ci-failuresSkill
- debugging-local-replaySkill
- debugging-local-task-agent-runsSkill
- debugging-mcp-analyticsSkill
- debugging-signals-pipelineSkill
- debugging-table-access-deniedSkill
- depot-ciSkill
- depot-container-buildsSkill
- depot-github-runnersSkill
- developing-subscriptionsSkill
- django-migrationsSkill
- django-startup-timeSkill
- documenting-warehouse-sourcesSkill
- editing-agents-mdSkill
- establishing-code-ownershipSkill
- extending-hobby-smoke-testsSkill
- extending-personhog-test-harnessSkill
- finding-llm-gateway-migration-candidatesSkill
- fixing-flaky-testsSkill
- formatting-slack-messagesSkill
- gating-production-deploysSkill
- gating-sensitive-actionsSkill
- generating-clickhouse-query-performance-reportsSkill
- hogliSkill
- implementing-mcp-toolsSkill
- implementing-mcp-ui-appsSkill
- implementing-warehouse-sourcesSkill
- improving-drf-endpointsSkill
- improving-mcp-toolsSkill
- ingestion-pipeline-doctor-nodejsSkill
- instrumenting-first-party-metricsSkill
- The first 60 shown.
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
Reviews can't be read right now.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

