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(dx): show the local dev personal API key value in settings (#76950)

Gustavo H. Strassburger81f5a81afb5b
diff --git a/.env.development b/.env.development
index 8b771a39f5be..85ac9b4bc8ed 100644
--- a/.env.development
+++ b/.env.development
@@ -9,6 +9,8 @@
# Core
DEBUG=1
ALLOW_DEV_LOGIN=1
+# shows the seeded dev personal API key's full value in Settings > Personal API keys
+ALLOW_DEV_API_KEY_REVEAL=1
SKIP_SERVICE_VERSION_REQUIREMENTS=1
# Object storage (host-side only — container endpoint is in .env.services)
diff --git a/docs/published/handbook/engineering/developing-locally.md b/docs/published/handbook/engineering/developing-locally.md
index 0e0f30c492a1..ef05050980c4 100644
--- a/docs/published/handbook/engineering/developing-locally.md
+++ b/docs/published/handbook/engineering/developing-locally.md
@@ -378,6 +378,10 @@ Backend side flags are automatically configured in DEBUG mode using the
dev API key created by `manage.py setup_local_api_key`.
If you need to override the key, set the `POSTHOG_PERSONAL_API_KEY` env var.
+That dev key's full value is also shown in [Settings > Personal API keys](http://localhost:8010/settings/user-api-keys), so you can copy it without rerunning the command.
+This needs `DEBUG=1` and `ALLOW_DEV_API_KEY_REVEAL=1`, both of which are already set in `.env.development`.
+No other personal API key is ever shown in full: the dev key is the only one whose value is a repo constant rather than a hash.
+
## Extra: Debugging with VS Code
The PostHog repository includes [VS Code launch options for debugging](https://github.com/PostHog/posthog/blob/master/.vscode/launch.json). Simply go to the `Run and Debug` tab in VS Code, select the desired service you want to debug, and run it. Once it starts up, you can set breakpoints and step through code to see exactly what is happening. There are also debug launch options for frontend and backend tests if you're dealing with a tricky test failure.
diff --git a/frontend/src/scenes/settings/user/PersonalAPIKeys.tsx b/frontend/src/scenes/settings/user/PersonalAPIKeys.tsx
index fe937b03932d..cfa84f026c3d 100644
--- a/frontend/src/scenes/settings/user/PersonalAPIKeys.tsx
+++ b/frontend/src/scenes/settings/user/PersonalAPIKeys.tsx
@@ -17,6 +17,7 @@ import {
Tooltip,
} from '@posthog/lemon-ui'
+import { CopyToClipboardInline } from 'lib/components/CopyToClipboard'
import { ScopeAccessRow } from 'lib/components/ScopeAccessRow/ScopeAccessRow'
import { IconErrorOutline } from 'lib/lemon-ui/icons'
import { LemonButton } from 'lib/lemon-ui/LemonButton'
@@ -535,7 +536,18 @@ function PersonalAPIKeysTable(): JSX.Element {
</div>
)}
renderMaskValue={(key) =>
- key.mask_value ? (
+ key.local_dev_value ? (
+ <CopyToClipboardInline
+ description="personal API key"
+ tooltipMessage="Local development key. Its full value is shown because this instance has DEBUG and ALLOW_DEV_API_KEY_REVEAL set."
+ selectable
+ isValueSensitive
+ iconSize="xsmall"
+ className="font-mono text-xs max-w-60 whitespace-normal"
+ >
+ {key.local_dev_value}
+ </CopyToClipboardInline>
+ ) : key.mask_value ? (
<span className="font-mono ph-no-capture">{key.mask_value}</span>
) : (
<Tooltip title="This key was created before the introduction of previews" placement="right">
diff --git a/frontend/src/types.ts b/frontend/src/types.ts
index e6e86bcc5fc0..fd78d19abb0b 100644
--- a/frontend/src/types.ts
+++ b/frontend/src/types.ts
@@ -531,6 +531,8 @@ export interface PersonalAPIKeyType {
value?: string
is_legacy_hashing: boolean
mask_value?: string | null
+ /** Full value, only present for the seeded local dev key when the backend reveal gate is on. */
+ local_dev_value?: string | null
created_at: string
last_used_at: string | null
last_rolled_at: string | null
diff --git a/hogli.yaml b/hogli.yaml
index 15981efb085e..43a6b52f92bc 100644
--- a/hogli.yaml
+++ b/hogli.yaml
@@ -316,7 +316,8 @@ core:
dev:api-key:
cmd: python manage.py setup_local_api_key
description: Creates a personal API key that's always the same, so you don't need
- to manually create a new one every time you reset the stack.
+ to manually create a new one every time you reset the stack. Its value is also
+ shown in Settings > Personal API keys.
services:
- postgresql
health_checks:
diff --git a/posthog/api/personal_api_key.py b/posthog/api/personal_api_key.py
index f4a1eba61b78..f2f0c63c92fd 100644
--- a/posthog/api/personal_api_key.py
+++ b/posthog/api/personal_api_key.py
@@ -4,12 +4,13 @@ from typing import cast
from django.utils import timezone
import posthoganalytics
-from drf_spectacular.utils import extend_schema
+from drf_spectacular.utils import extend_schema, extend_schema_field
from rest_framework import response, serializers, status, viewsets
from rest_framework.permissions import BasePermission, IsAuthenticated
from posthog.api.utils import action
from posthog.auth import PersonalAPIKeyAuthentication, SessionAuthentication
+from posthog.helpers.dev_api_key import get_local_dev_api_key_value
from posthog.models import PersonalAPIKey, User
from posthog.models.personal_api_key import LEGACY_HASH_PREFIX
from posthog.models.team.team import Team
@@ -71,6 +72,15 @@ def validate_personal_api_key_scopes(
class PersonalAPIKeySerializer(serializers.ModelSerializer):
# Specifying method name because the serializer class already has a get_value method
value = serializers.SerializerMethodField(method_name="get_key_value", read_only=True)
+ local_dev_value = serializers.SerializerMethodField(
+ read_only=True,
+ help_text=(
+ "Full value of the deterministic local-development key seeded by "
+ "`manage.py setup_local_api_key`, so that it can be recovered without rerunning the "
+ "command. Only populated when the instance runs with DEBUG and ALLOW_DEV_API_KEY_REVEAL "
+ "outside a cloud deployment, and only for that one key. Null in every other case."
+ ),
+ )
is_legacy_hashing = serializers.SerializerMethodField(
help_text="Whether this key uses legacy PBKDF2 hashing and should be rolled to upgrade."
)
@@ -94,6 +104,7 @@ class PersonalAPIKeySerializer(serializers.ModelSerializer):
"value",
"is_legacy_hashing",
"mask_value",
+ "local_dev_value",
"created_at",
"last_used_at",
"user_id",
@@ -107,6 +118,7 @@ class PersonalAPIKeySerializer(serializers.ModelSerializer):
"value",
"is_legacy_hashing",
"mask_value",
+ "local_dev_value",
"created_at",
"last_used_at",
"user_id",
@@ -116,6 +128,10 @@ class PersonalAPIKeySerializer(serializers.ModelSerializer):
def get_key_value(self, obj: PersonalAPIKey) -> str:
return getattr(obj, "_value", None) # type: ignore
+ @extend_schema_field(serializers.CharField(allow_null=True))
+ def get_local_dev_value(self, obj: PersonalAPIKey) -> str | None:
+ return get_local_dev_api_key_value(obj)
+
def get_is_legacy_hashing(self, obj: PersonalAPIKey) -> bool:
# Keys created before 2024-02 use PBKDF2 hashing, which is significantly slower per request
return bool(obj.secure_value and obj.secure_value.startswith(LEGACY_HASH_PREFIX))
diff --git a/posthog/api/test/test_personal_api_keys.py b/posthog/api/test/test_personal_api_keys.py
index cc632243aaf6..226e1466fd6b 100644
--- a/posthog/api/test/test_personal_api_keys.py
+++ b/posthog/api/test/test_personal_api_keys.py
@@ -4,6 +4,8 @@ from posthog.test.base import APIBaseTest
from unittest.mock import patch
from django.apps import apps
+from django.conf import settings
+from django.test import override_settings
from django.utils import timezone
from parameterized import parameterized
@@ -13,11 +15,12 @@ from posthog.schema import EventsQuery
from posthog.api.personal_api_key import PersonalAPIKeySerializer
from posthog.constants import AvailableFeature
+from posthog.helpers.dev_api_key import get_local_dev_api_key_value
from posthog.jwt import PosthogJwtAudience, encode_jwt
from posthog.models.organization import Organization
from posthog.models.personal_api_key import LEGACY_PERSONAL_API_KEY_SALT, PersonalAPIKey
from posthog.models.team.team import Team
-from posthog.models.utils import SHA256_HASH_PREFIX, generate_random_token_personal, hash_key_value
+from posthog.models.utils import SHA256_HASH_PREFIX, generate_random_token_personal, hash_key_value, mask_key_value
from products.product_analytics.backend.models.insight import Insight
@@ -57,6 +60,7 @@ class TestPersonalAPIKeysAPI(APIBaseTest):
"scoped_teams": [],
"value": data["value"],
"mask_value": data["mask_value"],
+ "local_dev_value": None,
}
assert data["value"].startswith("phx_") # Personal API key prefix
@@ -239,6 +243,7 @@ class TestPersonalAPIKeysAPI(APIBaseTest):
"scoped_teams": None,
"value": None,
"mask_value": my_key.mask_value,
+ "local_dev_value": None,
}
def test_get_own_personal_api_key(self):
@@ -1169,3 +1174,82 @@ class TestPersonalAPIKeyLLMGatewayFeatureFlag(APIBaseTest):
assert response.status_code == 201
assert response.json()["scopes"] == ["insight:read"]
mock_feature_enabled.assert_not_called()
+
+
+DEV_KEY_UNDER_TEST = "phx_dev_local_key_for_reveal_tests_1234"
+REVEAL_GATES_OPEN = {
+ "DEBUG": True,
+ "ALLOW_DEV_API_KEY_REVEAL": True,
+ "CLOUD_DEPLOYMENT": None,
+ "DEV_API_KEY": DEV_KEY_UNDER_TEST,
+}
+
+
+class TestLocalDevAPIKeyReveal(APIBaseTest):
+ def _dev_key(self) -> PersonalAPIKey:
+ # Unsaved instance: the reveal check only reads secure_value, so no DB round trip is needed.
+ return PersonalAPIKey(secure_value=hash_key_value(DEV_KEY_UNDER_TEST))
+
+ @override_settings(**REVEAL_GATES_OPEN)
+ def test_reveals_the_seeded_dev_key(self):
+ assert get_local_dev_api_key_value(self._dev_key()) == DEV_KEY_UNDER_TEST
+
+ @parameterized.expand(
+ [
+ ("flag_off", {"ALLOW_DEV_API_KEY_REVEAL": False}),
+ ("not_debug", {"DEBUG": False}),
+ ("cloud_deployment", {"CLOUD_DEPLOYMENT": "E2E"}),
+ ]
+ )
+ def test_does_not_reveal_when_a_gate_is_closed(self, _, closed_gate):
+ with override_settings(**{**REVEAL_GATES_OPEN, **closed_gate}):
+ assert get_local_dev_api_key_value(self._dev_key()) is None
+
+ @override_settings(**REVEAL_GATES_OPEN)
+ def test_does_not_reveal_a_key_other_than_the_dev_key(self):
+ other_key = PersonalAPIKey(secure_value=hash_key_value(generate_random_token_personal()))
+ assert get_local_dev_api_key_value(other_key) is None
+
+ @override_settings(**REVEAL_GATES_OPEN)
+ def test_tolerates_dev_api_key_being_undefined(self):
+ # DEV_API_KEY ships with the EE settings, so it is absent entirely in OSS builds.
+ del settings.DEV_API_KEY
+ assert get_local_dev_api_key_value(self._dev_key()) is None
+
+ def test_resolves_the_dev_key_per_call_rather_than_once_at_import(self):
+ rotated_key = "phx_dev_local_rotated_key_for_reveal_5678"
+ with override_settings(**REVEAL_GATES_OPEN):
+ assert get_local_dev_api_key_value(self._dev_key()) == DEV_KEY_UNDER_TEST
+ with override_settings(**{**REVEAL_GATES_OPEN, "DEV_API_KEY": rotated_key}):
+ assert get_local_dev_api_key_value(self._dev_key()) is None
+ rotated = PersonalAPIKey(secure_value=hash_key_value(rotated_key))
+ assert get_local_dev_api_key_value(rotated) == rotated_key
+
+ @override_settings(**REVEAL_GATES_OPEN)
+ def test_api_returns_the_revealed_value_while_leaving_value_unset(self):
+ key = PersonalAPIKey.objects.create(
+ user=self.user,
+ label="Local Development Key",
+ secure_value=hash_key_value(DEV_KEY_UNDER_TEST),
+ mask_value=mask_key_value(DEV_KEY_UNDER_TEST),
+ scopes=["*"],
+ )
+
+ other_key = PersonalAPIKey.objects.create(
+ user=self.user,
+ label="Some other key",
+ secure_value=hash_key_value(generate_random_token_personal()),
+ scopes=["*"],
+ )
+
+ response = self.client.get("/api/personal_api_keys")
+
+ assert response.status_code == 200
+ by_id = {k["id"]: k for k in response.json()}
+ assert by_id[key.id]["local_dev_value"] == DEV_KEY_UNDER_TEST
+ # Resolving the value once per serializer rather than per instance would hand the dev
+ # plaintext to every key in the list.
+ assert by_id[other_key.id]["local_dev_value"] is None
+ # `value` stays the create/roll-only channel that pops the one-time dialog in the UI.
+ assert by_id[key.id]["value"] is None
+ assert by_id[key.id]["mask_value"] == mask_key_value(DEV_KEY_UNDER_TEST)
diff --git a/posthog/helpers/dev_api_key.py b/posthog/helpers/dev_api_key.py
new file mode 100644
index 000000000000..921cbdf5be02
--- /dev/null
+++ b/posthog/helpers/dev_api_key.py
@@ -0,0 +1,30 @@
+from typing import TYPE_CHECKING
+
+from django.conf import settings
+
+from posthog.models.utils import hash_key_value
+
+if TYPE_CHECKING:
+ from posthog.models.personal_api_key import PersonalAPIKey
+
+
+def get_local_dev_api_key_value(key: "PersonalAPIKey") -> str | None:
+ """Return the plaintext of the seeded local-dev key, or None for any other key.
+
+ Personal API keys never persist plaintext, so the only key whose value can be recovered is the
+ deterministic dev key seeded by `manage.py setup_local_api_key`, whose value is the
+ settings.DEV_API_KEY constant. Identifying it means hashing that constant and comparing against
+ the stored hash, which reveals nothing that is not already in the repository.
+ """
+ # The gate is read on every call rather than resolved once at import, so that @override_settings
+ # in tests and a changed env between processes both take effect.
+ if not settings.DEBUG or not settings.ALLOW_DEV_API_KEY_REVEAL or settings.CLOUD_DEPLOYMENT:
+ return None
+ # DEV_API_KEY is defined in ee/settings.py, which OSS builds never load, so this must tolerate
+ # the attribute being absent entirely.
+ dev_api_key = getattr(settings, "DEV_API_KEY", None)
+ if not dev_api_key or not key.secure_value:
+ return None
+ if key.secure_value != hash_key_value(dev_api_key):
+ return None
+ return dev_api_key
diff --git a/posthog/management/commands/setup_local_api_key.py b/posthog/management/commands/setup_local_api_key.py
index 42272c3eea8b..7358355be090 100644
--- a/posthog/management/commands/setup_local_api_key.py
+++ b/posthog/management/commands/setup_local_api_key.py
@@ -18,7 +18,6 @@ from posthog.models import User
from posthog.models.personal_api_key import PersonalAPIKey
from posthog.models.utils import hash_key_value, mask_key_value
-DEV_API_KEY = settings.DEV_API_KEY
DEV_USER_EMAIL = "[email protected]"
DEV_KEY_LABEL = "Local Development Key"
@@ -47,10 +46,14 @@ class Command(BaseCommand):
)
def handle(self, *args, **options):
+ # DEV_API_KEY ships with ee/settings.py, which OSS builds never load.
+ dev_api_key = getattr(settings, "DEV_API_KEY", None)
if not settings.DEBUG:
raise CommandError("This command can only run with DEBUG=True")
if settings.CLOUD_DEPLOYMENT:
raise CommandError("This command cannot run in cloud deployments")
+ if not dev_api_key:
+ raise CommandError("settings.DEV_API_KEY is not configured (it ships with the EE settings)")
email = options["email"]
scopes = options["scopes"]
@@ -74,7 +77,7 @@ class Command(BaseCommand):
return
print(f"User '{email}' not found; using first user '{user.email}'")
- secure_value = hash_key_value(DEV_API_KEY)
+ secure_value = hash_key_value(dev_api_key)
existing_key = PersonalAPIKey.objects.filter(secure_value=secure_value).first()
if existing_key:
@@ -99,7 +102,7 @@ class Command(BaseCommand):
print(f"Updated scopes to {existing_key.scopes} for user '{existing_key.user.email}'")
else:
print(f"API key already exists for user '{existing_key.user.email}'")
- print(f"Key: {DEV_API_KEY}")
+ print(f"Key: {dev_api_key}")
return
PersonalAPIKey.objects.filter(user=user, label=DEV_KEY_LABEL).delete()
@@ -110,7 +113,7 @@ class Command(BaseCommand):
user=user,
label=DEV_KEY_LABEL,
secure_value=secure_value,
- mask_value=mask_key_value(DEV_API_KEY),
+ mask_value=mask_key_value(dev_api_key),
scopes=create_scopes,
)
@@ -124,4 +127,4 @@ class Command(BaseCommand):
print(f"Created personal API key for '{email}'")
if create_scopes:
print(f"Scopes: {', '.join(create_scopes)}")
- print(f"Key: {DEV_API_KEY}")
+ print(f"Key: {dev_api_key}")
diff --git a/posthog/settings/web.py b/posthog/settings/web.py
index 66c0ec291669..1ce3de0226a5 100644
--- a/posthog/settings/web.py
+++ b/posthog/settings/web.py
@@ -1071,6 +1071,9 @@ DEV_DISABLE_NAVIGATION_HOOKS = get_from_env("DEV_DISABLE_NAVIGATION_HOOKS", Fals
# one-click passwordless login on the login page (also requires DEBUG)
ALLOW_DEV_LOGIN = get_from_env("ALLOW_DEV_LOGIN", False, type_cast=str_to_bool)
+# shows the full value of the seeded dev personal API key in the UI (also requires DEBUG)
+ALLOW_DEV_API_KEY_REVEAL = get_from_env("ALLOW_DEV_API_KEY_REVEAL", False, type_cast=str_to_bool)
+
####
# Random/temporary
# Everything that is supposed to be removed eventually