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.

fix(auth): harden local OAuth dev-login (token scope + DEBUG guard) (#64591)

Tom Piccirello1522d762ac6b
diff --git a/frontend/src/lib/api.test.ts b/frontend/src/lib/api.test.ts
index a617df64102c..8f20b41010ec 100644
--- a/frontend/src/lib/api.test.ts
+++ b/frontend/src/lib/api.test.ts
@@ -6,6 +6,9 @@ import type { ApiError } from 'lib/api'
import { NodeKind } from '~/queries/schema/schema-general'
import { PropertyFilterType, PropertyOperator } from '~/types'
+// Mirrors SESSION_KEY in lib/oauth/oauthClient — the localStorage key its real getStoredSession reads.
+const OAUTH_SESSION_KEY = 'ph_oauth_session'
+
describe('API helper', () => {
let fakeFetch: jest.Mock<any, any>
@@ -167,6 +170,39 @@ describe('API helper', () => {
} satisfies Partial<ApiError>)
})
+ describe('OAuth mode auth headers', () => {
+ beforeEach(() => {
+ window.localStorage.setItem(
+ OAUTH_SESSION_KEY,
+ JSON.stringify({
+ backendHost: 'https://us.posthog.com',
+ clientId: 'client',
+ accessToken: 'oauth-token',
+ refreshToken: 'refresh',
+ expiresAt: 9999999999999,
+ })
+ )
+ })
+
+ afterEach(() => {
+ window.localStorage.removeItem(OAUTH_SESSION_KEY)
+ })
+
+ it('attaches the bearer token to requests routed to the OAuth backend host', async () => {
+ await api.get('/api/projects/2/insights/')
+ const [url, options] = fakeFetch.mock.calls[0]
+ expect(url).toEqual('https://us.posthog.com/api/projects/2/insights/')
+ expect(options.headers.Authorization).toEqual('Bearer oauth-token')
+ })
+
+ it('does not attach the bearer token to same-origin requests left on the local instance', async () => {
+ await api.get('/some/local/path')
+ const [url, options] = fakeFetch.mock.calls[0]
+ expect(url).toEqual('/some/local/path/')
+ expect(options.headers.Authorization).toBeUndefined()
+ })
+ })
+
describe('organizationFeatureFlags', () => {
it('builds correct URL for organization feature flags', () => {
const apiRequest = new ApiRequest()
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.ts
index 151fb84ddeec..4ab82a0ce1fc 100644
--- a/frontend/src/lib/api.ts
+++ b/frontend/src/lib/api.ts
@@ -2121,13 +2121,15 @@ const prepareUrl = (url: string): string => {
}
/**
- * Bearer auth header for standalone OAuth mode; empty when served by Django (session auth).
+ * Bearer auth header for standalone OAuth mode, attached only to requests bound for the OAuth
+ * backend host (the remote region). Requests that `prepareUrl` left on the local origin (non-`/api`
+ * paths) must not carry the remote region's token. Empty when served by Django (session auth).
* Synchronous so requests still dispatch synchronously — an expired token is handled by the
- * 401 → refresh → retry path in handleFetch.
+ * 401 → refresh → retry path in handleFetch. Pass the already-`prepareUrl`'d request URL.
*/
-function oauthAuthHeaders(): Record<string, string> {
+function oauthAuthHeaders(url: string): Record<string, string> {
const session = getStoredSession()
- return session ? { Authorization: `Bearer ${session.accessToken}` } : {}
+ return session && url.startsWith(session.backendHost) ? { Authorization: `Bearer ${session.accessToken}` } : {}
}
/**
@@ -6973,7 +6975,7 @@ const api = {
headers: {
...objectClean(options?.headers ?? {}),
...tracingHeaders({ includeDistinctId: true }),
- ...oauthAuthHeaders(),
+ ...oauthAuthHeaders(url),
...authHeaders,
},
})
@@ -6999,7 +7001,7 @@ const api = {
...(isFormData ? {} : { 'Content-Type': 'application/json' }),
'X-CSRFToken': getCookie(CSRF_COOKIE_NAME) || '',
...tracingHeaders(),
- ...oauthAuthHeaders(),
+ ...oauthAuthHeaders(url),
},
body: isFormData ? data : JSON.stringify(data),
signal: options?.signal,
@@ -7036,7 +7038,7 @@ const api = {
...(isFormData ? {} : { 'Content-Type': 'application/json' }),
'X-CSRFToken': getCookie(CSRF_COOKIE_NAME) || '',
...tracingHeaders(),
- ...oauthAuthHeaders(),
+ ...oauthAuthHeaders(url),
},
body: data ? (isFormData ? data : JSON.stringify(data)) : undefined,
signal: options?.signal,
@@ -7055,7 +7057,7 @@ const api = {
'Content-Type': 'application/x-www-form-urlencoded',
'X-CSRFToken': getCookie(CSRF_COOKIE_NAME) || '',
...tracingHeaders(),
- ...oauthAuthHeaders(),
+ ...oauthAuthHeaders(url),
},
})
)
diff --git a/posthog/settings/base_variables.py b/posthog/settings/base_variables.py
index 36db72f40607..96d62d6ff05c 100644
--- a/posthog/settings/base_variables.py
+++ b/posthog/settings/base_variables.py
@@ -3,7 +3,7 @@ import sys
import structlog
-from posthog.settings.utils import get_from_env, str_to_bool
+from posthog.settings.utils import assert_debug_not_in_production, get_from_env, str_to_bool
logger = structlog.get_logger(__name__)
@@ -79,3 +79,6 @@ if DEBUG and not TEST and not IS_INTERACTIVE_SHELL:
"Be sure to unset DEBUG if this is supposed to be a PRODUCTION ENVIRONMENT!",
]
)
+
+# Hard stop: DEBUG must never run on a deployed cloud env (US/EU/DEV) — it relaxes auth and exposes debug surfaces.
+assert_debug_not_in_production(debug=DEBUG, cloud_deployment=CLOUD_DEPLOYMENT, test=TEST)
diff --git a/posthog/settings/utils.py b/posthog/settings/utils.py
index 8bcedebaaf32..a65249e49bbd 100644
--- a/posthog/settings/utils.py
+++ b/posthog/settings/utils.py
@@ -6,7 +6,28 @@ from django.core.exceptions import ImproperlyConfigured
from posthog.utils import str_to_bool
-__all__ = ["generate_rsa_private_key_pem", "get_from_env", "get_list", "str_to_bool"]
+__all__ = [
+ "assert_debug_not_in_production",
+ "generate_rsa_private_key_pem",
+ "get_from_env",
+ "get_list",
+ "str_to_bool",
+]
+
+
+def assert_debug_not_in_production(*, debug: bool, cloud_deployment: Optional[str], test: bool) -> None:
+ """Refuse to boot with DEBUG enabled on a deployed cloud environment (US/EU/DEV).
+
+ DEBUG relaxes authentication (e.g. the dev OAuth login bypass in posthog/views.py) and exposes
+ debugging surfaces, so it must never run on PostHog Cloud US/EU or the hosted dev/staging env.
+ TEST is excluded because the suite runs with DEBUG=1 (see posthog/settings/overrides.py). E2E is
+ not listed: it runs only in automated tests and never sets DEBUG, so the guard can't fire there.
+ """
+ if debug and not test and (cloud_deployment or "").upper() in ("US", "EU", "DEV"):
+ raise ImproperlyConfigured(
+ f"DEBUG must not be enabled on deployed cloud environments (CLOUD_DEPLOYMENT={cloud_deployment!r}). "
+ "Unset DEBUG."
+ )
def generate_rsa_private_key_pem() -> str:
diff --git a/posthog/test/test_settings_debug_guard.py b/posthog/test/test_settings_debug_guard.py
new file mode 100644
index 000000000000..e6dc6a6fa551
--- /dev/null
+++ b/posthog/test/test_settings_debug_guard.py
@@ -0,0 +1,29 @@
+from unittest import TestCase
+
+from django.core.exceptions import ImproperlyConfigured
+
+from parameterized import parameterized
+
+from posthog.settings.utils import assert_debug_not_in_production
+
+
+class TestAssertDebugNotInProduction(TestCase):
+ @parameterized.expand([("US",), ("us",), ("EU",), ("eu",), ("DEV",), ("dev",)])
+ def test_raises_when_debug_enabled_on_deployed_cloud(self, cloud_deployment):
+ with self.assertRaises(ImproperlyConfigured):
+ assert_debug_not_in_production(debug=True, cloud_deployment=cloud_deployment, test=False)
+
+ @parameterized.expand(
+ [
+ ("debug_off_on_us", False, "US", False),
+ ("debug_off_on_eu", False, "EU", False),
+ ("debug_off_on_dev", False, "DEV", False),
+ ("debug_on_local_unset", True, None, False),
+ ("debug_on_local_explicit", True, "LOCAL", False),
+ # E2E runs only in automated tests and never sets DEBUG, so it is intentionally not blocked.
+ ("debug_on_e2e", True, "E2E", False),
+ ("debug_on_dev_but_running_tests", True, "DEV", True),
+ ]
+ )
+ def test_does_not_raise(self, _name, debug, cloud_deployment, test):
+ assert_debug_not_in_production(debug=debug, cloud_deployment=cloud_deployment, test=test)