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(proxy): add managed root redirects (#88064)

Reece Jones30df037c6a40
diff --git a/frontend/bin/generate-openapi-types.mjs b/frontend/bin/generate-openapi-types.mjs
index 607d5ae3ea3d..6195cbfc5685 100755
--- a/frontend/bin/generate-openapi-types.mjs
+++ b/frontend/bin/generate-openapi-types.mjs
@@ -22,6 +22,7 @@ const productsDir = path.resolve(repoRoot, 'products')
const productAliases = {
llm_analytics: 'ai_observability',
+ proxy_records: 'platform_features',
}
// Default to temp location (gitignored ephemeral artifact)
diff --git a/frontend/src/layout/navigation/projectNoticeLogic.tsx b/frontend/src/layout/navigation/projectNoticeLogic.tsx
index 6b1ab94bee9a..6fa9816a8059 100644
--- a/frontend/src/layout/navigation/projectNoticeLogic.tsx
+++ b/frontend/src/layout/navigation/projectNoticeLogic.tsx
@@ -275,7 +275,7 @@ export interface projectNoticeLogicMeta {
memberCount: number,
internetConnectionIssue: boolean,
hasProjectNoticeRestriction: boolean,
- proxyRecords: ProxyRecord[] | null,
+ proxyRecords: import('products/platform_features/frontend/generated/api.schemas').ProxyRecordApi[] | null,
effectiveBillingAlert: BillingAlertConfig | null,
currentLocation: {
hash: string
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index 4d34fe999058..d046bf9fadaa 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -280,13 +280,13 @@ export const FEATURE_FLAGS = {
CONDENSED_FILTER_BAR: 'condensed_filter_bar', // owner: @jordanm-posthog #team-web-analytics
CREATE_FORM_TOOL: 'phai-create-form-tool', // owner: @kappa90 #team-posthog-ai
CRM_ITERATION_ONE: 'crm-iteration-one', // owner: @arthurdedeus #team-customer-analytics
+ CUSTOM_FACET_PINNING: 'custom-facet-pinning', // owner: #team-logs — gates pinning custom facets to the logs/tracing facet rails
CUSTOMER_ANALYTICS: 'customer-analytics-roadmap', // owner: @arthurdedeus #team-customer-analytics
CUSTOMER_ANALYTICS_CSP: 'customer-analytics-csp', // owner: @arthurdedeus #team-customer-analytics, gates the Customer analytics > Accounts settings tab (account_group_type_index dropdown)
CUSTOMER_ANALYTICS_FEATURE_REQUESTS: 'customer-analytics-feature-requests',
CUSTOMER_ANALYTICS_JOURNEYS: 'customer-analytics-journeys', // owner: @arthurdedeus #team-customer-analytics
CUSTOMER_ANALYTICS_TRACK_RULES: 'customer-analytics-track-rules', // owner: @arthurdedeus #team-customer-analytics
CUSTOMER_PROFILE_CONFIG_BUTTON: 'customer-profile-config-button', // owner: @arthurdedeus #team-customer-analytics
- CUSTOM_FACET_PINNING: 'custom-facet-pinning', // owner: #team-logs — gates pinning custom facets to the logs/tracing facet rails
DASHBOARD_AI_PROMPT_COMPOSER: 'dashboard-ai-prompt-composer', // owner: @mattp #team-analytics-platform multivariate=control,copy,composer
DASHBOARD_AUTO_PREVIEW_LIMIT: 'dashboard-auto-preview-limit', // owner: @pauldambra #team-product-analytics
DASHBOARD_CUSTOMIZATION: 'dashboard-customization', // owner: @MattPua #team-analytics-platform
@@ -379,6 +379,7 @@ export const FEATURE_FLAGS = {
LOGS_TRANSFORMATIONS: 'logs-transformations', // owner: #team-logs
MANAGED_MIGRATIONS_IAM_ROLE_AUTH: 'managed-migrations-iam-role-auth', // owner: #team-ingestion, gates IAM role auth for S3 batch imports
MANAGED_MIGRATIONS_TRIAL_RUNS: 'managed-migrations-trial-runs', // owner: #team-ingestion, gates trial runs for managed migrations
+ MANAGED_REVERSE_PROXY_ROOT_REDIRECT: 'managed-reverse-proxy-root-redirect', // owner: @reecejones #team-platform-features
MANAGED_VIEWSETS: 'managed-viewsets', // owner: @rafaeelaudibert #team-revenue-analytics
MARKETING_ANALYTICS_AI: 'marketing-analytics-ai', // owner: @jabahamondes #team-web-analytics
MARKETING_ANALYTICS_ATTRIBUTION: 'marketing-analytics-attribution', // owner: @jabahamondes #team-web-analytics — gates the Attribution tab
diff --git a/frontend/src/scenes/settings/environment/ManagedReverseProxy.tsx b/frontend/src/scenes/settings/environment/ManagedReverseProxy.tsx
index c972ea88e6fa..385c7f33bae9 100644
--- a/frontend/src/scenes/settings/environment/ManagedReverseProxy.tsx
+++ b/frontend/src/scenes/settings/environment/ManagedReverseProxy.tsx
@@ -22,6 +22,7 @@ import { CodeSnippet, Language } from 'lib/components/CodeSnippet'
import { DomainConnectBanner } from 'lib/components/DomainConnect'
import { RestrictionScope, useRestrictedArea } from 'lib/components/RestrictedArea'
import { OrganizationMembershipLevel } from 'lib/constants'
+import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'
import { LemonField } from 'lib/lemon-ui/LemonField'
import { LemonMarkdown } from 'lib/lemon-ui/LemonMarkdown'
import { Link } from 'lib/lemon-ui/Link'
@@ -31,7 +32,14 @@ import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'
import { useAttachedContext } from 'products/posthog_ai/frontend/api/logics'
-import { DiagnosticCheckResult, DiagnosticCheckStatus, DiagnosticReport, ProxyRecord, proxyLogic } from './proxyLogic'
+import {
+ DiagnosticCheckResult,
+ DiagnosticCheckStatus,
+ DiagnosticReport,
+ ProxyRecord,
+ canConfigureRootRedirect,
+ proxyLogic,
+} from './proxyLogic'
import { ProxySDKSetup } from './ProxySDKSetup'
const statusText = {
@@ -40,6 +48,7 @@ const statusText = {
}
export function ManagedReverseProxy(): JSX.Element {
+ const rootRedirectEnabled = useFeatureFlag('MANAGED_REVERSE_PROXY_ROOT_REDIRECT')
const {
shouldShowCloudflareOptIn,
formState,
@@ -216,7 +225,9 @@ export function ManagedReverseProxy(): JSX.Element {
columns={columns}
dataSource={proxyRecords}
expandable={{
- expandedRowRender: (record) => <ExpandedRow record={record} />,
+ expandedRowRender: (record) => (
+ <ExpandedRow record={record} rootRedirectEnabled={rootRedirectEnabled} />
+ ),
isRowExpanded: (record) => (expandedRecordIds.includes(record.id) ? true : -1),
onRowExpand: (record) => setRecordExpanded(record.id, true),
onRowCollapse: (record) => setRecordExpanded(record.id, false),
@@ -339,12 +350,19 @@ function CloudflareOptInBanner({
)
}
-const ExpandedRow = ({ record }: { record: ProxyRecord }): JSX.Element => {
- const { diagnosticReports, recordActiveTabs } = useValues(proxyLogic)
- const { setRecordActiveTab } = useActions(proxyLogic)
+const ExpandedRow = ({
+ record,
+ rootRedirectEnabled,
+}: {
+ record: ProxyRecord
+ rootRedirectEnabled: boolean
+}): JSX.Element => {
+ const { diagnosticReports, recordActiveTabs, rootRedirectDrafts, proxyRecordsLoading } = useValues(proxyLogic)
+ const { setRecordActiveTab, setRootRedirectDraft, updateRootRedirect } = useActions(proxyLogic)
const report = diagnosticReports[record.id]
const activeKey = recordActiveTabs[record.id] ?? 'cname'
+ const rootRedirectDraft = rootRedirectDrafts[record.id] ?? record.root_redirect_url ?? ''
const tabs = [
{
@@ -356,6 +374,45 @@ const ExpandedRow = ({ record }: { record: ProxyRecord }): JSX.Element => {
</CodeSnippet>
),
},
+ ...(canConfigureRootRedirect(record, rootRedirectEnabled)
+ ? [
+ {
+ label: 'Root redirect',
+ key: 'root-redirect',
+ content: (
+ <div className="flex flex-col gap-2 max-w-160">
+ <p className="text-secondary">
+ Redirect visits to <code>https://{record.domain}/</code> to another HTTPS URL. This
+ does not affect event ingestion or other proxy paths.
+ </p>
+ <LemonInput
+ type="url"
+ value={rootRedirectDraft}
+ onChange={(value) => setRootRedirectDraft(record.id, value)}
+ placeholder="https://www.example.com/"
+ />
+ <div>
+ <LemonButton
+ type="primary"
+ size="small"
+ onClick={() =>
+ updateRootRedirect({ id: record.id, rootRedirectUrl: rootRedirectDraft })
+ }
+ loading={proxyRecordsLoading}
+ disabledReason={
+ rootRedirectDraft === (record.root_redirect_url ?? '')
+ ? 'No changes to save'
+ : undefined
+ }
+ >
+ Save redirect
+ </LemonButton>
+ </div>
+ </div>
+ ),
+ },
+ ]
+ : []),
...(report
? [
{
diff --git a/frontend/src/scenes/settings/environment/proxyLogic.test.ts b/frontend/src/scenes/settings/environment/proxyLogic.test.ts
index 1459d00f90f6..684041d66492 100644
--- a/frontend/src/scenes/settings/environment/proxyLogic.test.ts
+++ b/frontend/src/scenes/settings/environment/proxyLogic.test.ts
@@ -9,7 +9,7 @@ import { useMocks } from '~/mocks/jest'
import { initKeaTests } from '~/test/init'
import { UserType } from '~/types'
-import { ProxyRecord, proxyLogic } from './proxyLogic'
+import { ProxyRecord, canConfigureRootRedirect, proxyLogic } from './proxyLogic'
const MOCK_IMPERSONATED_USER: UserType = {
...MOCK_DEFAULT_USER,
@@ -21,6 +21,12 @@ const mockProxyRecord = (overrides: Partial<ProxyRecord> = {}): ProxyRecord => (
domain: 't.example.com',
status: 'valid',
target_cname: 'proxy.posthog.com',
+ root_redirect_url: null,
+ root_redirect_supported: true,
+ message: null,
+ created_at: '2026-08-24T00:00:00Z',
+ updated_at: '2026-08-24T00:00:00Z',
+ created_by: 1,
...overrides,
})
@@ -134,3 +140,42 @@ describe('proxyLogic — shouldShowCloudflareOptIn', () => {
})
})
})
+
+describe('proxyLogic — root redirect', () => {
+ it.each<[string, boolean, ProxyRecord, boolean]>([
+ ['supported valid proxy', true, mockProxyRecord(), true],
+ ['supported warning proxy', true, mockProxyRecord({ status: 'warning' }), true],
+ ['legacy proxy', true, mockProxyRecord({ root_redirect_supported: false }), false],
+ ['disabled feature', false, mockProxyRecord(), false],
+ ['proxy that is not ready', true, mockProxyRecord({ status: 'waiting' }), false],
+ ])('allows configuration for a %s when expected', (_name, featureEnabled, record, expected) => {
+ expect(canConfigureRootRedirect(record, featureEnabled)).toBe(expected)
+ })
+
+ it('updates the record from the PATCH response', async () => {
+ const record = mockProxyRecord()
+ const updatedRecord = mockProxyRecord({ root_redirect_url: 'https://www.example.com/' })
+ useMocks({
+ get: {
+ [`/api/organizations/${MOCK_ORGANIZATION_ID}/proxy_records/`]: proxyRecordsResponse([record]),
+ },
+ patch: {
+ [`/api/organizations/${MOCK_ORGANIZATION_ID}/proxy_records/${record.id}/`]: updatedRecord,
+ },
+ })
+ initKeaTests()
+ organizationLogic.mount()
+
+ const logic = proxyLogic()
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+
+ await expectLogic(logic, () => {
+ logic.actions.updateRootRedirect({ id: record.id, rootRedirectUrl: 'https://www.example.com/' })
+ })
+ .toDispatchActions(['updateRootRedirectSuccess'])
+ .toMatchValues({ proxyRecords: [updatedRecord] })
+
+ logic.unmount()
+ })
+})
diff --git a/frontend/src/scenes/settings/environment/proxyLogic.ts b/frontend/src/scenes/settings/environment/proxyLogic.ts
index f55061092816..2f7e388d1753 100644
--- a/frontend/src/scenes/settings/environment/proxyLogic.ts
+++ b/frontend/src/scenes/settings/environment/proxyLogic.ts
@@ -6,7 +6,6 @@ import { loaders } from 'kea-loaders'
import { LemonDialog } from '@posthog/lemon-ui'
-import api from 'lib/api'
import { SetupTaskId } from 'lib/components/ProductSetup'
import { globalSetupLogic } from 'lib/components/ProductSetup/globalSetupLogic'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
@@ -17,50 +16,43 @@ import { userLogic } from 'scenes/userLogic'
import { UserType } from '~/types'
-export type ProxyRecord = {
- id: string
- domain: string
- status: 'waiting' | 'issuing' | 'valid' | 'warning' | 'erroring' | 'deleting' | 'timed_out'
- message?: string
- target_cname: string
-}
-
-export type FormState = 'collapsed' | 'active'
-
-export type DiagnosticCheckStatus = 'passed' | 'warned' | 'failed' | 'skipped'
-export type DiagnosticSummaryStatus = 'healthy' | 'warn' | 'fail'
-export type DiagnosticRemediationType = 'dns' | 'config' | 'wait' | 'retry'
-
-export type DiagnosticDnsRecord = {
- name: string
- type: string
- value: string
-}
+import {
+ proxyRecordsCreate,
+ proxyRecordsDestroy,
+ proxyRecordsDiagnoseCreate,
+ proxyRecordsList,
+ proxyRecordsPartialUpdate,
+ proxyRecordsRetryCreate,
+} from 'products/platform_features/frontend/generated/api'
+import type {
+ DiagnosticCheckResultApi,
+ DiagnosticCheckResultStatusEnumApi,
+ DiagnosticReportApi,
+ DiagnosticReportSummaryStatusEnumApi,
+ DiagnosticRemediationApi,
+ DiagnosticRemediationTypeEnumApi,
+ ProxyRecordApi,
+ ProxyRecordListResponseApi,
+ ProxyRecordStatusEnumApi,
+} from 'products/platform_features/frontend/generated/api.schemas'
-export type DiagnosticRemediation = {
- type: DiagnosticRemediationType
- summary: string
- records: DiagnosticDnsRecord[]
-}
+export type ProxyRecord = ProxyRecordApi
-export type DiagnosticCheckResult = {
- id: string
- name: string
- status: DiagnosticCheckStatus
- detail: string
- remediation?: DiagnosticRemediation | null
-}
+export type FormState = 'collapsed' | 'active'
-export type DiagnosticReportSummary = {
- status: DiagnosticSummaryStatus
- primary_issue: string | null
- next_action: string | null
-}
+export type DiagnosticCheckStatus = DiagnosticCheckResultStatusEnumApi
+export type DiagnosticSummaryStatus = DiagnosticReportSummaryStatusEnumApi
+export type DiagnosticRemediationType = DiagnosticRemediationTypeEnumApi
+export type DiagnosticRemediation = DiagnosticRemediationApi
+export type DiagnosticCheckResult = DiagnosticCheckResultApi
+export type DiagnosticReport = DiagnosticReportApi
-export type DiagnosticReport = {
- ran_at: string
- summary: DiagnosticReportSummary
- checks: DiagnosticCheckResult[]
+export function canConfigureRootRedirect(proxyRecord: ProxyRecord, featureEnabled: boolean): boolean {
+ return (
+ featureEnabled &&
+ proxyRecord.root_redirect_supported &&
+ (proxyRecord.status === 'valid' || proxyRecord.status === 'warning')
+ )
}
export function domainFor(proxyRecord: ProxyRecord | undefined): string {
@@ -145,6 +137,7 @@ export interface proxyLogicValues {
proxyRecordsLoaded: boolean
proxyRecordsLoading: boolean
recordActiveTabs: Record<string, string>
+ rootRedirectDrafts: Record<string, string>
shouldRefreshRecords: boolean
shouldShowCloudflareOptIn: boolean
showCreateRecordErrors: boolean
@@ -172,12 +165,12 @@ export interface proxyLogicActions {
errorObject?: any
}
createRecordSuccess: (
- proxyRecords: any[],
+ proxyRecords: ProxyRecordApi[],
payload?: {
domain: string
}
) => {
- proxyRecords: any[]
+ proxyRecords: ProxyRecordApi[]
payload?: {
domain: string
}
@@ -192,20 +185,30 @@ export interface proxyLogicActions {
}
deleteRecordSuccess: (
proxyRecords: {
+ created_at: string
+ created_by: number
domain: string
id: string
- message?: string | undefined
- status: 'deleting' | 'erroring' | 'issuing' | 'timed_out' | 'valid' | 'waiting' | 'warning'
+ message: string | null
+ root_redirect_supported: boolean
+ root_redirect_url: string | null
+ status: ProxyRecordStatusEnumApi
target_cname: string
+ updated_at: string
}[],
payload?: ProxyRecord[]
) => {
proxyRecords: {
+ created_at: string
+ created_by: number
domain: string
id: string
- message?: string | undefined
- status: 'deleting' | 'erroring' | 'issuing' | 'timed_out' | 'valid' | 'waiting' | 'warning'
+ message: string | null
+ root_redirect_supported: boolean
+ root_redirect_url: string | null
+ status: ProxyRecordStatusEnumApi
target_cname: string
+ updated_at: string
}[]
payload?: ProxyRecord[]
}
@@ -224,7 +227,7 @@ export interface proxyLogicActions {
report: DiagnosticReport
) => {
id: string
- report: DiagnosticReport
+ report: DiagnosticReportApi
}
loadRecords: () => any
loadRecordsFailure: (
@@ -235,10 +238,10 @@ export interface proxyLogicActions {
errorObject?: any
}
loadRecordsSuccess: (
- proxyRecords: ProxyRecord[],
+ proxyRecords: ProxyRecordApi[],
payload?: any
) => {
- proxyRecords: ProxyRecord[]
+ proxyRecords: ProxyRecordApi[]
payload?: any
}
maybeRefreshRecords: () => {
@@ -258,10 +261,10 @@ export interface proxyLogicActions {
errorObject?: any
}
retryRecordSuccess: (
- proxyRecords: ProxyRecord[],
+ proxyRecords: ProxyRecordApi[],
payload?: ProxyRecord[]
) => {
- proxyRecords: ProxyRecord[]
+ proxyRecords: ProxyRecordApi[]
payload?: ProxyRecord[]
}
setCloudflareOptInChecked: (checked: boolean) => {
@@ -303,6 +306,13 @@ export interface proxyLogicActions {
expanded: boolean
id: string
}
+ setRootRedirectDraft: (
+ id: ProxyRecord['id'],
+ rootRedirectUrl: string
+ ) => {
+ id: string
+ rootRedirectUrl: string
+ }
showForm: () => {
value: true
}
@@ -329,16 +339,40 @@ export interface proxyLogicActions {
touchCreateRecordField: (key: string) => {
key: string
}
+ updateRootRedirect: ({ id, rootRedirectUrl }: { id: string; rootRedirectUrl: string }) => {
+ id: string
+ rootRedirectUrl: string
+ }
+ updateRootRedirectFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ updateRootRedirectSuccess: (
+ proxyRecords: ProxyRecordApi[],
+ payload?: {
+ id: string
+ rootRedirectUrl: string
+ }
+ ) => {
+ proxyRecords: ProxyRecordApi[]
+ payload?: {
+ id: string
+ rootRedirectUrl: string
+ }
+ }
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface proxyLogicMeta {
__keaTypeGenInternalSelectorTypes: {
- shouldRefreshRecords: (proxyRecords: ProxyRecord[]) => boolean
+ shouldRefreshRecords: (proxyRecords: ProxyRecordApi[]) => boolean
shouldShowCloudflareOptIn: (
cloudflareOptInAcknowledged: boolean,
proxyRecordsLoaded: boolean,
- proxyRecords: ProxyRecord[],
+ proxyRecords: ProxyRecordApi[],
user: UserType | null
) => boolean
}
@@ -364,6 +398,7 @@ export const proxyLogic = kea<proxyLogicType>([
clearDiagnosticReport: (id: ProxyRecord['id']) => ({ id }),
setRecordExpanded: (id: ProxyRecord['id'], expanded: boolean) => ({ id, expanded }),
setRecordActiveTab: (id: ProxyRecord['id'], tab: string) => ({ id, tab }),
+ setRootRedirectDraft: (id: ProxyRecord['id'], rootRedirectUrl: string) => ({ id, rootRedirectUrl }),
})),
reducers(() => ({
formState: ['collapsed' as FormState, { showForm: () => 'active', collapseForm: () => 'collapsed' }],
@@ -437,25 +472,35 @@ export const proxyLogic = kea<proxyLogicType>([
},
},
],
+ rootRedirectDrafts: [
+ {} as Record<string, string>,
+ {
+ setRootRedirectDraft: (state, { id, rootRedirectUrl }) => ({ ...state, [id]: rootRedirectUrl }),
+ updateRootRedirectSuccess: (state, { payload }) =>
+ payload ? { ...state, [payload.id]: payload.rootRedirectUrl } : state,
+ },
+ ],
})),
loaders(({ values, actions }) => ({
proxyRecords: {
__default: [] as ProxyRecord[],
loadRecords: async () => {
- const response = await api.get(`api/organizations/${values.currentOrganizationId}/proxy_records`)
+ // drf-spectacular correctly describes this custom list response as an object, but
+ // Orval still applies its list-action array heuristic to the generated function.
+ const response = (await proxyRecordsList(
+ values.currentOrganizationId
+ )) as unknown as ProxyRecordListResponseApi
actions.setMaxProxyRecords(response.max_proxy_records)
return response.results
},
createRecord: async ({ domain }: { domain: string }) => {
- const response = await api.create(`api/organizations/${values.currentOrganizationId}/proxy_records`, {
- domain,
- })
+ const response = await proxyRecordsCreate(values.currentOrganizationId, { domain })
lemonToast.success('Record created')
actions.collapseForm()
return [response, ...values.proxyRecords]
},
deleteRecord: async (id: ProxyRecord['id']) => {
- void api.delete(`api/organizations/${values.currentOrganizationId}/proxy_records/${id}`)
+ void proxyRecordsDestroy(values.currentOrganizationId, id)
const newRecords = [...values.proxyRecords].map((r) => ({
...r,
status: r.id === id ? 'deleting' : r.status,
@@ -463,7 +508,7 @@ export const proxyLogic = kea<proxyLogicType>([
return newRecords
},
retryRecord: async (id: ProxyRecord['id']) => {
- await api.create(`api/organizations/${values.currentOrganizationId}/proxy_records/${id}/retry`)
+ await proxyRecordsRetryCreate(values.currentOrganizationId, id)
lemonToast.success('Retry initiated')
return values.proxyRecords.map((r) => ({
...r,
@@ -471,6 +516,13 @@ export const proxyLogic = kea<proxyLogicType>([
message: r.id === id ? undefined : r.message,
})) as ProxyRecord[]
},
+ updateRootRedirect: async ({ id, rootRedirectUrl }: { id: string; rootRedirectUrl: string }) => {
+ const updatedRecord = await proxyRecordsPartialUpdate(values.currentOrganizationId, id, {
+ root_redirect_url: rootRedirectUrl || null,
+ })
+ lemonToast.success(rootRedirectUrl ? 'Root redirect updated' : 'Root redirect removed')
+ return values.proxyRecords.map((record) => (record.id === id ? updatedRecord : record))
+ },
},
})),
selectors(() => ({
@@ -519,9 +571,7 @@ export const proxyLogic = kea<proxyLogicType>([
},
diagnose: async ({ id }) => {
try {
- const report = (await api.create(
- `api/organizations/${values.currentOrganizationId}/proxy_records/${id}/diagnose`
- )) as DiagnosticReport
+ const report = await proxyRecordsDiagnoseCreate(values.currentOrganizationId, id)
actions.diagnoseSuccess(id, report)
} catch (e) {
const message = e instanceof Error ? e.message : String(e)
diff --git a/posthog/api/integration.py b/posthog/api/integration.py
index 5d7bae19addf..cdccc4729270 100644
--- a/posthog/api/integration.py
+++ b/posthog/api/integration.py
@@ -1952,8 +1952,8 @@ class IntegrationViewSet(
raise ValidationError("domain query parameter is required")
# Extract root domain so subdomains (e.g. ph.example.com) resolve correctly
- root_domain, _ = extract_root_domain_and_host(domain)
- result = discover_domain_connect(root_domain)
+ domain_parts = extract_root_domain_and_host(domain)
+ result = discover_domain_connect(domain_parts.root_domain)
return Response(
{
"supported": result is not None,
diff --git a/posthog/api/proxy_record.py b/posthog/api/proxy_record.py
index 331c1436328a..2360986b1bd1 100644
--- a/posthog/api/proxy_record.py
+++ b/posthog/api/proxy_record.py
@@ -1,12 +1,16 @@
import time
import asyncio
import hashlib
+from urllib.parse import urlparse
from django.conf import settings
from django.core.cache import cache
+from django.db import DatabaseError, transaction
+import requests
import posthoganalytics
-from drf_spectacular.utils import extend_schema
+from drf_spectacular.types import OpenApiTypes
+from drf_spectacular.utils import extend_schema, extend_schema_field, extend_schema_serializer
from rest_framework import serializers, status
from rest_framework.decorators import action
from rest_framework.exceptions import NotFound
@@ -16,14 +20,22 @@ from rest_framework.viewsets import ModelViewSet
from posthog.api.proxy_record_diagnostics import diagnose as diagnose_proxy_record
from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.constants import AvailableFeature
+from posthog.domain_connect import extract_root_domain_and_host
from posthog.event_usage import groups
from posthog.exceptions_capture import capture_exception
from posthog.models import ProxyRecord
from posthog.models.organization import Organization
from posthog.models.proxy_record import is_valid_proxy_domain
from posthog.permissions import OrganizationAdminWritePermissions, TimeSensitiveActionPermission
+from posthog.tasks.proxy import reconcile_proxy_root_redirect
from posthog.temporal.common.client import sync_connect
from posthog.temporal.proxy_service import CreateManagedProxyInputs, DeleteManagedProxyInputs
+from posthog.temporal.proxy_service.cloudflare import (
+ CloudflareAPIError,
+ get_custom_hostname_by_domain,
+ update_custom_hostname_metadata,
+)
+from posthog.temporal.proxy_service.common import is_cloudflare_proxy_by_cname
def generate_target_cname(organization_id, domain) -> str:
@@ -58,6 +70,8 @@ class ProxyRecordSerializer(serializers.ModelSerializer):
"id",
"domain",
"target_cname",
+ "root_redirect_url",
+ "root_redirect_supported",
"status",
"message",
"created_at",
@@ -74,6 +88,14 @@ class ProxyRecordSerializer(serializers.ModelSerializer):
read_only=True,
help_text="The CNAME target to add as a DNS record for your domain. Point your domain's CNAME to this value.",
)
+ root_redirect_url = serializers.URLField(
+ read_only=True,
+ allow_null=True,
+ help_text="HTTPS URL that requests to the proxy domain root redirect to, or null when disabled.",
+ )
+ root_redirect_supported = serializers.SerializerMethodField(
+ help_text="Whether this managed proxy supports a redirect from its root URL."
+ )
status = serializers.ChoiceField(
choices=ProxyRecord.Status.choices,
read_only=True,
@@ -95,6 +117,10 @@ class ProxyRecordSerializer(serializers.ModelSerializer):
read_only=True, help_text="ID of the user who created this proxy record."
)
+ @extend_schema_field(OpenApiTypes.BOOL)
+ def get_root_redirect_supported(self, record: ProxyRecord) -> bool:
+ return is_cloudflare_proxy_by_cname(record.target_cname)
+
def validate_domain(self, value: str) -> str:
# The stored value is later used both as a DNS query name and as the authority of a
# URL we request. Those two grammars accept different bytes, so a value that is not a
@@ -106,6 +132,45 @@ class ProxyRecordSerializer(serializers.ModelSerializer):
return value
+class ProxyRecordUpdateSerializer(serializers.Serializer):
+ root_redirect_url = serializers.URLField(
+ allow_blank=True,
+ allow_null=True,
+ max_length=1024,
+ required=True,
+ help_text=(
+ "HTTPS URL that requests to the proxy domain root redirect to, or null to disable the redirect. "
+ "The URL must use the same registrable domain as the managed proxy."
+ ),
+ )
+
+ def validate_root_redirect_url(self, value: str | None) -> str | None:
+ if not value:
+ return None
+
+ parsed_url = urlparse(value)
+ if parsed_url.scheme != "https":
+ raise serializers.ValidationError("Enter a URL that starts with https://.")
+ if parsed_url.username or parsed_url.password:
+ raise serializers.ValidationError("The redirect URL cannot include credentials.")
+
+ record: ProxyRecord = self.context["record"]
+ proxy_hostname = record.domain.rstrip(".")
+ redirect_hostname = (parsed_url.hostname or "").rstrip(".")
+ if redirect_hostname.lower() == proxy_hostname.lower():
+ raise serializers.ValidationError("The redirect URL cannot point to the managed proxy domain.")
+
+ proxy_domain_parts = extract_root_domain_and_host(proxy_hostname, include_private_suffixes=True)
+ redirect_domain_parts = extract_root_domain_and_host(redirect_hostname, include_private_suffixes=True)
+ proxy_root_domain = proxy_domain_parts.root_domain
+ redirect_root_domain = redirect_domain_parts.root_domain
+ if redirect_root_domain.lower() != proxy_root_domain.lower():
+ raise serializers.ValidationError(f"Enter a URL on {proxy_root_domain} or one of its subdomains.")
+
+ return value
+
+
+@extend_schema_serializer(many=False)
class ProxyRecordListResponseSerializer(serializers.Serializer):
results = ProxyRecordSerializer(many=True)
max_proxy_records = serializers.IntegerField(
@@ -191,7 +256,7 @@ class ProxyRecordViewset(TeamAndOrgViewSetMixin, ModelViewSet):
permission_classes = [OrganizationAdminWritePermissions, TimeSensitiveActionPermission]
queryset = ProxyRecord.objects.order_by("-created_at")
pagination_class = None
- http_method_names = ["get", "post", "delete"]
+ http_method_names = ["get", "post", "patch", "delete"]
DEFAULT_MAX_PROXY_RECORDS = 2
@@ -208,7 +273,7 @@ class ProxyRecordViewset(TeamAndOrgViewSetMixin, ModelViewSet):
@extend_schema(
description="List all reverse proxies configured for the organization. "
"Returns proxy records along with the maximum number allowed by the current plan.",
- responses={200: ProxyRecordListResponseSerializer},
+ responses={200: ProxyRecordListResponseSerializer(many=False)},
)
def list(self, request, *args, **kwargs):
queryset = self.organization.proxy_records.order_by("-created_at")
@@ -232,6 +297,69 @@ class ProxyRecordViewset(TeamAndOrgViewSetMixin, ModelViewSet):
serializer = self.get_serializer(record)
return Response(serializer.data)
+ @extend_schema(
+ description="Set or clear the HTTPS redirect for requests to the managed proxy domain root.",
+ request=ProxyRecordUpdateSerializer,
+ responses={200: ProxyRecordSerializer},
+ )
+ def partial_update(self, request, *args, pk=None, **kwargs):
+ reconciliation_required = False
+ try:
+ with transaction.atomic():
+ record = self.organization.proxy_records.select_for_update().get(id=pk)
+
+ if not is_cloudflare_proxy_by_cname(record.target_cname):
+ return Response(
+ {"detail": "Root redirects are only available for Cloudflare-managed proxies."},
+ status=status.HTTP_400_BAD_REQUEST,
+ )
+
+ serializer = ProxyRecordUpdateSerializer(data=request.data, context={"record": record})
+ serializer.is_valid(raise_exception=True)
+ root_redirect_url = serializer.validated_data["root_redirect_url"]
+ previous_root_redirect_url = record.root_redirect_url
+
+ try:
+ hostname = get_custom_hostname_by_domain(record.domain)
+ if hostname is None:
+ return Response(
+ {"detail": "Cloudflare could not find this managed proxy hostname."},
+ status=status.HTTP_502_BAD_GATEWAY,
+ )
+ update_custom_hostname_metadata(hostname, {"root_redirect_url": root_redirect_url or ""})
+ except (CloudflareAPIError, requests.RequestException) as error:
+ capture_exception(error, {"domain": record.domain, "proxy_record_id": str(record.id)})
+ return Response(
+ {"detail": "Cloudflare could not update the root redirect. Please try again."},
+ status=status.HTTP_502_BAD_GATEWAY,
+ )
+
+ record.root_redirect_url = root_redirect_url
+ try:
+ record.save(update_fields=["root_redirect_url", "updated_at"])
+ except DatabaseError:
+ try:
+ update_custom_hostname_metadata(
+ hostname, {"root_redirect_url": previous_root_redirect_url or ""}
+ )
+ except (CloudflareAPIError, requests.RequestException) as rollback_error:
+ reconciliation_required = True
+ capture_exception(rollback_error, {"domain": record.domain, "proxy_record_id": str(record.id)})
+ raise
+ except ProxyRecord.DoesNotExist:
+ raise NotFound()
+ except DatabaseError as error:
+ if reconciliation_required:
+ reconcile_proxy_root_redirect.delay(str(pk))
+ capture_exception(error, {"organization_id": str(self.organization.id), "proxy_record_id": str(pk)})
+ return Response(
+ {"detail": "Could not save the root redirect. Please try again."},
+ status=status.HTTP_502_BAD_GATEWAY,
+ )
+
+ _capture_proxy_event(request, record, "root redirect updated")
+ return Response(ProxyRecordSerializer(record).data)
+
@extend_schema(
description="Create a new managed reverse proxy. "
"Provide the domain you want to proxy through. "
diff --git a/posthog/api/test/test_proxy_record.py b/posthog/api/test/test_proxy_record.py
index 8213d58c86ac..6912e5d6a79c 100644
--- a/posthog/api/test/test_proxy_record.py
+++ b/posthog/api/test/test_proxy_record.py
@@ -1,11 +1,50 @@
+from types import SimpleNamespace
+
from posthog.test.base import APIBaseTest
-from unittest.mock import AsyncMock, patch
+from unittest.mock import AsyncMock, call, patch
+
+from django.db import DatabaseError
+from django.test import SimpleTestCase
from parameterized import parameterized
from rest_framework import status
+from posthog.api.proxy_record import ProxyRecordUpdateSerializer
from posthog.models import ProxyRecord
from posthog.models.organization import Organization, OrganizationMembership
+from posthog.temporal.proxy_service.cloudflare import (
+ CloudflareAPIError,
+ CustomHostname,
+ CustomHostnameSSL,
+ CustomHostnameSSLStatus,
+ CustomHostnameStatus,
+)
+
+
+class TestProxyRecordUpdateSerializer(SimpleTestCase):
+ @parameterized.expand(
+ [
+ ("apex", "e.example.com", "https://example.com/"),
+ ("sibling", "e.example.com", "https://www.example.com/"),
+ ("nested", "e.example.com", "https://technology.info.example.com/welcome"),
+ ("multipart_suffix", "e.example.co.uk", "https://www.example.co.uk/"),
+ ]
+ )
+ def test_accepts_redirects_on_the_proxy_root_domain(self, _name: str, proxy_domain: str, redirect_url: str) -> None:
+ serializer = ProxyRecordUpdateSerializer(
+ data={"root_redirect_url": redirect_url}, context={"record": SimpleNamespace(domain=proxy_domain)}
+ )
+
+ assert serializer.is_valid(), serializer.errors
+
+ def test_rejects_another_registrable_domain_with_the_same_public_suffix(self) -> None:
+ serializer = ProxyRecordUpdateSerializer(
+ data={"root_redirect_url": "https://other.co.uk/"},
+ context={"record": SimpleNamespace(domain="e.example.co.uk")},
+ )
+
+ assert not serializer.is_valid()
+ assert "example.co.uk" in serializer.errors["root_redirect_url"][0]
class TestProxyRecordAPI(APIBaseTest):
@@ -42,6 +81,36 @@ class TestProxyRecordAPI(APIBaseTest):
data = response.json()
assert data["max_proxy_records"] == 2
+ def test_list_reports_root_redirect_support_for_each_proxy(self) -> None:
+ ProxyRecord.objects.bulk_create(
+ [
+ ProxyRecord(
+ organization=self.organization,
+ created_by=self.user,
+ domain="cloudflare.example.com",
+ target_cname="cloudflare.cf-proxy.example.net",
+ ),
+ ProxyRecord(
+ organization=self.organization,
+ created_by=self.user,
+ domain="legacy.example.com",
+ target_cname="legacy.proxy.example.net",
+ ),
+ ]
+ )
+
+ with self.settings(CLOUDFLARE_PROXY_BASE_CNAME="cf-proxy.example.net"):
+ response = self.client.get(f"/api/organizations/{self.organization.id}/proxy_records/")
+
+ assert response.status_code == status.HTTP_200_OK
+ support_by_domain = {
+ record["domain"]: record["root_redirect_supported"] for record in response.json()["results"]
+ }
+ assert support_by_domain == {
+ "cloudflare.example.com": True,
+ "legacy.example.com": False,
+ }
+
@patch("posthog.api.proxy_record.sync_connect")
@patch("posthoganalytics.capture")
def test_create_proxy_record(self, mock_capture, mock_sync_connect):
@@ -108,6 +177,143 @@ class TestProxyRecordAPI(APIBaseTest):
)
assert response.status_code == status.HTTP_400_BAD_REQUEST
+ @patch("posthog.api.proxy_record.update_custom_hostname_metadata")
+ @patch("posthog.api.proxy_record.get_custom_hostname_by_domain")
+ @patch("posthoganalytics.capture")
+ def test_updates_root_redirect_metadata(self, _capture, get_hostname, update_metadata):
+ record = ProxyRecord.objects.create(
+ organization=self.organization,
+ created_by=self.user,
+ domain="proxy.example.com",
+ target_cname="abc.cf-prod-us-proxy.proxyhog.com",
+ status=ProxyRecord.Status.VALID,
+ )
+ hostname = CustomHostname(
+ id="hostname-id",
+ hostname=record.domain,
+ status=CustomHostnameStatus.ACTIVE,
+ ssl=CustomHostnameSSL(status=CustomHostnameSSLStatus.ACTIVE, validation_errors=[]),
+ )
+ get_hostname.return_value = hostname
+
+ with self.settings(CLOUDFLARE_PROXY_BASE_CNAME="cf-prod-us-proxy.proxyhog.com"):
+ response = self.client.patch(
+ f"/api/organizations/{self.organization.id}/proxy_records/{record.id}/",
+ {"root_redirect_url": "https://www.example.com/welcome"},
+ )
+
+ assert response.status_code == status.HTTP_200_OK
+ assert response.json()["root_redirect_url"] == "https://www.example.com/welcome"
+ record.refresh_from_db()
+ assert record.root_redirect_url == "https://www.example.com/welcome"
+ update_metadata.assert_called_once_with(hostname, {"root_redirect_url": "https://www.example.com/welcome"})
+
+ @patch("posthog.api.proxy_record.update_custom_hostname_metadata")
+ @patch("posthog.api.proxy_record.get_custom_hostname_by_domain")
+ @patch("posthog.api.proxy_record.reconcile_proxy_root_redirect.delay")
+ def test_reconciles_root_redirect_when_database_write_and_cloudflare_rollback_fail(
+ self, reconcile_root_redirect, get_hostname, update_metadata
+ ):
+ record = ProxyRecord.objects.create(
+ organization=self.organization,
+ created_by=self.user,
+ domain="proxy.example.com",
+ target_cname="abc.cf-prod-us-proxy.proxyhog.com",
+ root_redirect_url="https://old.example.com/",
+ status=ProxyRecord.Status.VALID,
+ )
+ hostname = CustomHostname(
+ id="hostname-id",
+ hostname=record.domain,
+ status=CustomHostnameStatus.ACTIVE,
+ ssl=CustomHostnameSSL(status=CustomHostnameSSLStatus.ACTIVE, validation_errors=[]),
+ )
+ get_hostname.return_value = hostname
+ update_metadata.side_effect = [None, CloudflareAPIError("rollback failed")]
+
+ with (
+ self.settings(CLOUDFLARE_PROXY_BASE_CNAME="cf-prod-us-proxy.proxyhog.com"),
+ patch("posthog.models.ProxyRecord.save", side_effect=DatabaseError("write failed")),
+ ):
+ response = self.client.patch(
+ f"/api/organizations/{self.organization.id}/proxy_records/{record.id}/",
+ {"root_redirect_url": "https://new.example.com/"},
+ )
+
+ assert response.status_code == status.HTTP_502_BAD_GATEWAY
+ update_metadata.assert_has_calls(
+ [
+ call(hostname, {"root_redirect_url": "https://new.example.com/"}),
+ call(hostname, {"root_redirect_url": "https://old.example.com/"}),
+ ]
+ )
+ reconcile_root_redirect.assert_called_once_with(str(record.id))
+
+ @parameterized.expand(
+ [
+ ("insecure", "proxy.example.com", "http://www.example.com", "https://"),
+ ("credentials", "proxy.example.com", "https://user:[email protected]", "credentials"),
+ ("loop", "proxy.example.com", "https://proxy.example.com/", "managed proxy domain"),
+ ("loop_trailing_dot", "proxy.example.com", "https://proxy.example.com./", "managed proxy domain"),
+ ("unrelated_domain", "proxy.example.com", "https://google.com/", "example.com"),
+ ("root_domain_prefix", "proxy.example.com", "https://example.com.attacker.com/", "example.com"),
+ ("private_suffix", "proxy.victim.dynv6.net", "https://attacker.dynv6.net/", "victim.dynv6.net"),
+ ]
+ )
+ @patch("posthog.api.proxy_record.update_custom_hostname_metadata")
+ @patch("posthog.api.proxy_record.get_custom_hostname_by_domain")
+ def test_rejects_unsafe_root_redirect(
+ self, _name, proxy_domain, redirect_url, expected_error, get_hostname, _update_metadata
+ ):
+ get_hostname.return_value = SimpleNamespace(custom_metadata={})
+ record = ProxyRecord.objects.create(
+ organization=self.organization,
+ created_by=self.user,
+ domain=proxy_domain,
+ target_cname="abc.cf-prod-us-proxy.proxyhog.com",
+ status=ProxyRecord.Status.VALID,
+ )
+
+ with self.settings(CLOUDFLARE_PROXY_BASE_CNAME="cf-prod-us-proxy.proxyhog.com"):
+ response = self.client.patch(
+ f"/api/organizations/{self.organization.id}/proxy_records/{record.id}/",
+ {"root_redirect_url": redirect_url},
+ )
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert response.json()["attr"] == "root_redirect_url"
+ assert expected_error in response.json()["detail"]
+ _update_metadata.assert_not_called()
+
+ @patch("posthog.api.proxy_record.update_custom_hostname_metadata")
+ @patch("posthog.api.proxy_record.get_custom_hostname_by_domain")
+ def test_clears_root_redirect_metadata(self, get_hostname, update_metadata):
+ record = ProxyRecord.objects.create(
+ organization=self.organization,
+ created_by=self.user,
+ domain="proxy.example.com",
+ target_cname="abc.cf-prod-us-proxy.proxyhog.com",
+ root_redirect_url="https://www.example.com/",
+ status=ProxyRecord.Status.VALID,
+ )
+ hostname = CustomHostname(
+ id="hostname-id",
+ hostname=record.domain,
+ status=CustomHostnameStatus.ACTIVE,
+ ssl=CustomHostnameSSL(status=CustomHostnameSSLStatus.ACTIVE, validation_errors=[]),
+ )
+ get_hostname.return_value = hostname
+
+ with self.settings(CLOUDFLARE_PROXY_BASE_CNAME="cf-prod-us-proxy.proxyhog.com"):
+ response = self.client.patch(
+ f"/api/organizations/{self.organization.id}/proxy_records/{record.id}/",
+ {"root_redirect_url": None},
+ )
+
+ assert response.status_code == status.HTTP_200_OK
+ assert response.json()["root_redirect_url"] is None
+ update_metadata.assert_called_once_with(hostname, {"root_redirect_url": ""})
+
def test_diagnose_fails_closed_on_a_stored_domain_that_is_not_a_hostname(self):
# Rows predate write-time validation, so the endpoint has to report a failed check
# rather than raising into the viewset's catch-all and answering 500.
diff --git a/posthog/api/test/test_proxy_record_diagnostics.py b/posthog/api/test/test_proxy_record_diagnostics.py
index cda61d2ae673..b08ea2ebfff8 100644
--- a/posthog/api/test/test_proxy_record_diagnostics.py
+++ b/posthog/api/test/test_proxy_record_diagnostics.py
@@ -1,4 +1,5 @@
import ipaddress
+from dataclasses import replace
from unittest.mock import MagicMock, patch
@@ -135,8 +136,7 @@ class TestCheckCloudflare(TestCase):
@patch("posthog.api.proxy_record_diagnostics.get_custom_hostname_by_domain")
def test_fail_when_hostname_blocked_despite_active_cert(self, _name, status, remediation_word, get_mock):
# An active SSL certificate must not let a blocked or moved hostname pass the check.
- info = _hostname_info(ssl_status=CustomHostnameSSLStatus.ACTIVE)
- info.status = status
+ info = replace(_hostname_info(ssl_status=CustomHostnameSSLStatus.ACTIVE), status=status)
get_mock.return_value = info
result, _ = diagnostics._check_cloudflare(_record())
diff --git a/posthog/domain_connect.py b/posthog/domain_connect.py
index 951f4432ebba..041a100abc3c 100644
--- a/posthog/domain_connect.py
+++ b/posthog/domain_connect.py
@@ -23,6 +23,8 @@ from cryptography.hazmat.primitives.asymmetric.rsa import RSAPrivateKey
from posthog.schema import DomainConnectProviderName
+from posthog.dataclasses import frozen
+
logger = logging.getLogger(__name__)
# Maps _domainconnect TXT record values (provider endpoints) to display names.
@@ -159,8 +161,14 @@ def get_key_id() -> str:
return getattr(settings, "DOMAIN_CONNECT_KEY_ID", "_dcpubkeyv1")
-def extract_root_domain_and_host(full_domain: str) -> tuple[str, str]:
- """Split a full domain into (root_domain, host_prefix).
+@frozen
+class DomainParts:
+ root_domain: str
+ host: str
+
+
+def extract_root_domain_and_host(full_domain: str, *, include_private_suffixes: bool = False) -> DomainParts:
+ """Split a full domain into its root domain and host prefix.
Examples:
"ph.example.com" → ("example.com", "ph")
@@ -170,12 +178,12 @@ def extract_root_domain_and_host(full_domain: str) -> tuple[str, str]:
Uses the Public Suffix List via tldextract for correct TLD handling.
"""
full_domain = full_domain.rstrip(".")
- ext = tldextract.extract(full_domain)
+ ext = tldextract.extract(full_domain, include_psl_private_domains=include_private_suffixes)
if ext.suffix:
root = f"{ext.domain}.{ext.suffix}"
else:
root = ext.domain or full_domain
- return (root, ext.subdomain)
+ return DomainParts(root_domain=root, host=ext.subdomain)
def get_service_id_for_region(service_prefix: str) -> str:
@@ -256,13 +264,13 @@ def resolve_proxy_context(proxy_record_id: str, organization_id: str) -> tuple[s
from posthog.models import ProxyRecord
record = ProxyRecord.objects.get(id=proxy_record_id, organization_id=organization_id)
- root_domain, host = extract_root_domain_and_host(record.domain)
+ domain_parts = extract_root_domain_and_host(record.domain)
service_id = get_service_id_for_region("reverse-proxy")
variables = {
"target": record.target_cname,
}
- return (root_domain, service_id, host, variables)
+ return (domain_parts.root_domain, service_id, domain_parts.host, variables)
def generate_apply_url(
diff --git a/posthog/migrations/1323_proxyrecord_root_redirect_url.py b/posthog/migrations/1323_proxyrecord_root_redirect_url.py
new file mode 100644
index 000000000000..b870aaf7070d
--- /dev/null
+++ b/posthog/migrations/1323_proxyrecord_root_redirect_url.py
@@ -0,0 +1,17 @@
+# Generated by Django 5.2.17 on 2026-08-24 15:31
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("posthog", "1322_organization_read_only_mcp_access"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="proxyrecord",
+ name="root_redirect_url",
+ field=models.URLField(blank=True, max_length=1024, null=True),
+ ),
+ ]
diff --git a/posthog/migrations/max_migration.txt b/posthog/migrations/max_migration.txt
index 3e4dceee97f6..2266cf277bc2 100644
--- a/posthog/migrations/max_migration.txt
+++ b/posthog/migrations/max_migration.txt
@@ -1 +1 @@
-1322_organization_read_only_mcp_access
+1323_proxyrecord_root_redirect_url
diff --git a/posthog/models/proxy_record.py b/posthog/models/proxy_record.py
index 24c249be66f1..c4e531a468ee 100644
--- a/posthog/models/proxy_record.py
+++ b/posthog/models/proxy_record.py
@@ -46,6 +46,7 @@ class ProxyRecord(UUIDTModel):
organization = models.ForeignKey(Organization, on_delete=models.CASCADE, related_name="proxy_records")
domain = models.CharField(max_length=64, unique=True)
target_cname = models.CharField(max_length=256, null=False)
+ root_redirect_url = models.URLField(max_length=1024, null=True, blank=True)
message = models.CharField(max_length=1024, null=True)
class Status(models.TextChoices):
diff --git a/posthog/models/usage_report_events_preagg/sql.py b/posthog/models/usage_report_events_preagg/sql.py
index fb8068d13d12..3beabe1ea82a 100644
--- a/posthog/models/usage_report_events_preagg/sql.py
+++ b/posthog/models/usage_report_events_preagg/sql.py
@@ -31,7 +31,7 @@ USAGE_REPORT_EVENTS_PREAGG_COLUMNS = """
# Slim Kafka engine table schema — only the columns the MV projects.
# JSONEachRow ignores unknown fields, so the events_json topic payloads work as-is.
-_KAFKA_USAGE_REPORT_EVENTS_PREAGG_COLUMNS = """
+KAFKA_USAGE_REPORT_EVENTS_PREAGG_COLUMNS = """
uuid UUID,
event VARCHAR,
properties VARCHAR CODEC(ZSTD(3)),
@@ -92,7 +92,7 @@ def KAFKA_USAGE_REPORT_EVENTS_PREAGG_TABLE_SQL() -> str:
return f"""
CREATE TABLE IF NOT EXISTS {KAFKA_USAGE_REPORT_EVENTS_PREAGG_TABLE}
(
- {_KAFKA_USAGE_REPORT_EVENTS_PREAGG_COLUMNS}
+ {KAFKA_USAGE_REPORT_EVENTS_PREAGG_COLUMNS}
)
ENGINE = {
kafka_engine(
@@ -105,13 +105,10 @@ SETTINGS kafka_skip_broken_messages = 100, kafka_thread_per_consumer = 1, kafka_
"""
-def USAGE_REPORT_EVENTS_PREAGG_MV_SQL() -> str:
+def USAGE_REPORT_EVENTS_PREAGG_MV_SELECT_SQL(source_table: str) -> str:
# Dedup tuple includes `event` (avoids cross-event uuid collisions) but not `date`
# (so day-boundary replays still dedupe).
- return f"""
-CREATE MATERIALIZED VIEW IF NOT EXISTS {USAGE_REPORT_EVENTS_PREAGG_MV}
-TO {WRITABLE_USAGE_REPORT_EVENTS_PREAGG_TABLE}
-AS SELECT
+ return f"""SELECT
toDate(timestamp) AS date,
team_id,
person_mode,
@@ -119,6 +116,13 @@ AS SELECT
event,
uniqExactState((cityHash64(distinct_id), cityHash64(toString(uuid)), cityHash64(event))) AS distinct_events_unique,
sumState(toUInt64(1)) AS event_count
-FROM {KAFKA_USAGE_REPORT_EVENTS_PREAGG_TABLE}
-GROUP BY date, team_id, person_mode, lib, event
+FROM {source_table}
+GROUP BY date, team_id, person_mode, lib, event"""
+
+
+def USAGE_REPORT_EVENTS_PREAGG_MV_SQL() -> str:
+ return f"""
+CREATE MATERIALIZED VIEW IF NOT EXISTS {USAGE_REPORT_EVENTS_PREAGG_MV}
+TO {WRITABLE_USAGE_REPORT_EVENTS_PREAGG_TABLE}
+AS {USAGE_REPORT_EVENTS_PREAGG_MV_SELECT_SQL(KAFKA_USAGE_REPORT_EVENTS_PREAGG_TABLE)}
"""
diff --git a/posthog/models/usage_report_events_preagg/test/test_usage_report_events_preagg_mv.py b/posthog/models/usage_report_events_preagg/test/test_usage_report_events_preagg_mv.py
index 7551106bd545..10ac7760cf39 100644
--- a/posthog/models/usage_report_events_preagg/test/test_usage_report_events_preagg_mv.py
+++ b/posthog/models/usage_report_events_preagg/test/test_usage_report_events_preagg_mv.py
@@ -1,32 +1,27 @@
-"""End-to-end test that produces an event to the dedicated usage-report-preagg Kafka
-table and verifies the usage_report_events_preagg materialized view aggregates it correctly.
-Mirrors the test_kafka_insert pattern in ee/clickhouse/models/test/test_dead_letter_queue.py.
+"""Tests the usage_report_events_preagg materialized view projection: how raw event rows
+aggregate into daily billable counts and which columns they group by.
-Requires a running Kafka broker reachable via settings.KAFKA_PROFILES["default"].
+The projection runs against a plain source table that stands in for the dedicated Kafka
+engine table, so the test is deterministic. Live Kafka transport (the Kafka engine table
+and the materialized view that binds to it) is exercised separately when migration 0251
+runs against the test ClickHouse.
"""
import json
-import time
from datetime import datetime
from uuid import uuid4
from posthog.test.base import ClickhouseTestMixin
-from django.conf import settings
-from django.test import TestCase
-
-from kafka import KafkaProducer
+from django.test import SimpleTestCase
from posthog.clickhouse.client import sync_execute
-from posthog.kafka_client.topics import KAFKA_EVENTS_JSON
from posthog.models.usage_report_events_preagg.sql import (
DISTRIBUTED_USAGE_REPORT_EVENTS_PREAGG_TABLE_SQL,
- KAFKA_USAGE_REPORT_EVENTS_PREAGG_TABLE,
- KAFKA_USAGE_REPORT_EVENTS_PREAGG_TABLE_SQL,
+ KAFKA_USAGE_REPORT_EVENTS_PREAGG_COLUMNS,
SHARDED_USAGE_REPORT_EVENTS_PREAGG_TABLE,
SHARDED_USAGE_REPORT_EVENTS_PREAGG_TABLE_SQL,
- USAGE_REPORT_EVENTS_PREAGG_MV,
- USAGE_REPORT_EVENTS_PREAGG_MV_SQL,
+ USAGE_REPORT_EVENTS_PREAGG_MV_SELECT_SQL,
USAGE_REPORT_EVENTS_PREAGG_TABLE,
WRITABLE_USAGE_REPORT_EVENTS_PREAGG_TABLE,
WRITABLE_USAGE_REPORT_EVENTS_PREAGG_TABLE_SQL,
@@ -37,98 +32,96 @@ from posthog.models.usage_report_events_preagg.sql import (
EVENT_FLOW_TEST_TEAM_ID = 9_999_999
REPLAY_TEST_TEAM_ID = 10_000_000
TEST_DATE = "2026-05-05"
-TEST_EVENT_DAY_TIMESTAMP = f"{TEST_DATE} 12:34:56"
+TEST_EVENT_TIMESTAMP = datetime(2026, 5, 5, 12, 34, 56)
+
+# Plain source table with the Kafka engine table's exact columns. The projection reads
+# from here instead of Kafka, so aggregation is verified without a broker in the loop.
+SOURCE_USAGE_REPORT_EVENTS_PREAGG_TABLE = "test_source_usage_report_events_preagg"
-def _make_event_payload(distinct_id: str, event: str, lib: str, team_id: int) -> dict:
- """Build a minimal event payload that satisfies the dedicated kafka_usage_report_events_preagg JSONEachRow schema."""
+def _make_event_row(distinct_id: str, event: str, lib: str, team_id: int) -> dict:
return {
"uuid": str(uuid4()),
"event": event,
"properties": json.dumps({"$lib": lib}),
- "timestamp": TEST_EVENT_DAY_TIMESTAMP,
+ "timestamp": TEST_EVENT_TIMESTAMP,
"team_id": team_id,
"distinct_id": distinct_id,
"person_mode": "full",
}
-def _wait_for_team_row(
- team_id: int, expected_unique: int, expected_total: int, timeout_seconds: int = 90
-) -> tuple[int, int]:
- """Poll usage_report_events_preagg until BOTH uniqExactMerge >= expected_unique AND
- sumMerge >= expected_total. Both conditions are required because in a replay scenario
- `unique_count` saturates at 1 after the first message lands while `total_count` is
- still climbing — returning early on `unique_count` alone races the second message.
-
- The timeout has to outlast the initial Kafka consumer startup and any broker rebalance.
- Polling stops as soon as both counts are satisfied, so a healthy run does not pay for
- this headroom.
-
- Returns (unique_count, total_count) once both observed, or raises AssertionError on timeout.
- """
- deadline = time.monotonic() + timeout_seconds
- last_seen: tuple[int, int] = (0, 0)
- while time.monotonic() < deadline:
- result = sync_execute(
- f"""
- SELECT
- uniqExactMerge(distinct_events_unique) AS unique_count,
- toInt64(sumMerge(event_count)) AS total_count
- FROM {USAGE_REPORT_EVENTS_PREAGG_TABLE}
- WHERE team_id = %(team_id)s AND date = toDate(%(date)s)
- """,
- {"team_id": team_id, "date": TEST_DATE},
- )
- last_seen = (int(result[0][0] or 0), int(result[0][1] or 0))
- if last_seen[0] >= expected_unique and last_seen[1] >= expected_total:
- return last_seen
- time.sleep(0.5)
- raise AssertionError(
- f"usage_report_events_preagg never reached unique>={expected_unique}, total>={expected_total} "
- f"for team {team_id}; last seen {last_seen}"
- )
-
-
-class TestUsageReportEventsPreaggMV(ClickhouseTestMixin, TestCase):
+class TestUsageReportEventsPreaggMV(ClickhouseTestMixin, SimpleTestCase):
@classmethod
def setUpClass(cls) -> None:
super().setUpClass()
sync_execute(SHARDED_USAGE_REPORT_EVENTS_PREAGG_TABLE_SQL())
sync_execute(DISTRIBUTED_USAGE_REPORT_EVENTS_PREAGG_TABLE_SQL())
sync_execute(WRITABLE_USAGE_REPORT_EVENTS_PREAGG_TABLE_SQL())
- sync_execute(KAFKA_USAGE_REPORT_EVENTS_PREAGG_TABLE_SQL())
- sync_execute(USAGE_REPORT_EVENTS_PREAGG_MV_SQL())
+ sync_execute(
+ f"""
+ CREATE TABLE IF NOT EXISTS {SOURCE_USAGE_REPORT_EVENTS_PREAGG_TABLE}
+ ({KAFKA_USAGE_REPORT_EVENTS_PREAGG_COLUMNS})
+ ENGINE = MergeTree() ORDER BY (team_id, timestamp)
+ """
+ )
@classmethod
def tearDownClass(cls) -> None:
try:
- sync_execute(f"DROP TABLE IF EXISTS {USAGE_REPORT_EVENTS_PREAGG_MV}")
- sync_execute(f"DROP TABLE IF EXISTS {KAFKA_USAGE_REPORT_EVENTS_PREAGG_TABLE}")
+ sync_execute(f"DROP TABLE IF EXISTS {SOURCE_USAGE_REPORT_EVENTS_PREAGG_TABLE}")
sync_execute(f"DROP TABLE IF EXISTS {WRITABLE_USAGE_REPORT_EVENTS_PREAGG_TABLE}")
sync_execute(f"DROP TABLE IF EXISTS {USAGE_REPORT_EVENTS_PREAGG_TABLE}")
sync_execute(f"DROP TABLE IF EXISTS {SHARDED_USAGE_REPORT_EVENTS_PREAGG_TABLE} SYNC")
finally:
super().tearDownClass()
- def test_kafka_event_flows_into_aggregate(self) -> None:
- """Two events with distinct uuids land as 2 unique billable events in the daily agg."""
+ def _project_rows(self, rows: list[dict], team_id: int) -> None:
+ """Insert raw event rows, then run the real MV projection into the writable table."""
+ sync_execute(f"TRUNCATE TABLE {SOURCE_USAGE_REPORT_EVENTS_PREAGG_TABLE}")
sync_execute(
f"DELETE FROM {SHARDED_USAGE_REPORT_EVENTS_PREAGG_TABLE} WHERE team_id = %(t)s",
- {"t": EVENT_FLOW_TEST_TEAM_ID},
+ {"t": team_id},
+ )
+ sync_execute(
+ f"""
+ INSERT INTO {SOURCE_USAGE_REPORT_EVENTS_PREAGG_TABLE}
+ (uuid, event, properties, timestamp, team_id, distinct_id, person_mode) VALUES
+ """,
+ rows,
+ )
+ sync_execute(
+ f"INSERT INTO {WRITABLE_USAGE_REPORT_EVENTS_PREAGG_TABLE} "
+ + USAGE_REPORT_EVENTS_PREAGG_MV_SELECT_SQL(SOURCE_USAGE_REPORT_EVENTS_PREAGG_TABLE)
)
- producer = KafkaProducer(bootstrap_servers=settings.KAFKA_PROFILES["default"].hosts)
- for distinct_id in ("user_a", "user_b"):
- payload = _make_event_payload(distinct_id, event="pageview", lib="web", team_id=EVENT_FLOW_TEST_TEAM_ID)
- producer.send(topic=KAFKA_EVENTS_JSON, value=json.dumps(payload).encode("utf-8"))
- producer.flush()
- unique_count, total_count = _wait_for_team_row(EVENT_FLOW_TEST_TEAM_ID, expected_unique=2, expected_total=2)
+ def _read_counts(self, team_id: int) -> tuple[int, int]:
+ result = sync_execute(
+ f"""
+ SELECT
+ uniqExactMerge(distinct_events_unique) AS unique_count,
+ toInt64(sumMerge(event_count)) AS total_count
+ FROM {USAGE_REPORT_EVENTS_PREAGG_TABLE}
+ WHERE team_id = %(team_id)s AND date = toDate(%(date)s)
+ """,
+ {"team_id": team_id, "date": TEST_DATE},
+ )
+ return int(result[0][0] or 0), int(result[0][1] or 0)
+
+ def test_projection_counts_unique_billable_events(self) -> None:
+ """Two events with distinct uuids land as 2 unique billable events in the daily agg."""
+ rows = [
+ _make_event_row(distinct_id, event="pageview", lib="web", team_id=EVENT_FLOW_TEST_TEAM_ID)
+ for distinct_id in ("user_a", "user_b")
+ ]
+ self._project_rows(rows, EVENT_FLOW_TEST_TEAM_ID)
+
+ unique_count, total_count = self._read_counts(EVENT_FLOW_TEST_TEAM_ID)
self.assertEqual(unique_count, 2)
self.assertEqual(total_count, 2)
- # Verify the MV's grouping columns are populated correctly.
- rows = sync_execute(
+ # Verify the projection's grouping columns are populated correctly.
+ grouped = sync_execute(
f"""
SELECT date, team_id, person_mode, lib, event
FROM {USAGE_REPORT_EVENTS_PREAGG_TABLE}
@@ -137,29 +130,19 @@ class TestUsageReportEventsPreaggMV(ClickhouseTestMixin, TestCase):
""",
{"team_id": EVENT_FLOW_TEST_TEAM_ID, "date": TEST_DATE},
)
- self.assertEqual(len(rows), 1)
- row = rows[0]
+ self.assertEqual(len(grouped), 1)
+ row = grouped[0]
self.assertEqual(row[0], datetime.strptime(TEST_DATE, "%Y-%m-%d").date())
self.assertEqual(row[1], EVENT_FLOW_TEST_TEAM_ID)
self.assertEqual(row[2], "full")
self.assertEqual(row[3], "web")
self.assertEqual(row[4], "pageview")
- def test_kafka_replayed_event_dedupes(self) -> None:
- """Sending the same (distinct_id, uuid) pair twice yields 1 unique billable event but 2 in raw count."""
- sync_execute(
- f"DELETE FROM {SHARDED_USAGE_REPORT_EVENTS_PREAGG_TABLE} WHERE team_id = %(t)s",
- {"t": REPLAY_TEST_TEAM_ID},
- )
- producer = KafkaProducer(bootstrap_servers=settings.KAFKA_PROFILES["default"].hosts)
- payload = _make_event_payload("user_replay", event="pageview", lib="web", team_id=REPLAY_TEST_TEAM_ID)
- # Ship the same payload twice — same uuid, same distinct_id.
- for _ in range(2):
- producer.send(topic=KAFKA_EVENTS_JSON, value=json.dumps(payload).encode("utf-8"))
- producer.flush()
-
- unique_count, total_count = _wait_for_team_row(REPLAY_TEST_TEAM_ID, expected_unique=1, expected_total=2)
+ def test_projection_dedupes_replayed_events(self) -> None:
+ """The same (distinct_id, uuid, event) tuple twice yields 1 unique billable event but 2 in raw count."""
+ row = _make_event_row("user_replay", event="pageview", lib="web", team_id=REPLAY_TEST_TEAM_ID)
+ self._project_rows([row, dict(row)], REPLAY_TEST_TEAM_ID)
+
+ unique_count, total_count = self._read_counts(REPLAY_TEST_TEAM_ID)
self.assertEqual(unique_count, 1, "uniqExactMerge should dedupe identical (distinct_id, uuid, event) tuples")
- # event_count is summed across all rows including replays, so total_count
- # is at least 2. May be larger if the kafka consumer buffered earlier replays.
- self.assertGreaterEqual(total_count, 2)
+ self.assertEqual(total_count, 2, "event_count sums every row, including replays")
diff --git a/posthog/tasks/__init__.py b/posthog/tasks/__init__.py
index 85b2f00f1172..ec3243bd68c0 100644
--- a/posthog/tasks/__init__.py
+++ b/posthog/tasks/__init__.py
@@ -15,6 +15,7 @@ from . import (
llm_prompt_cache,
plugin_server,
process_scheduled_changes,
+ proxy,
push_notifications,
remote_config,
split_person,
@@ -41,6 +42,7 @@ __all__ = [
"llm_prompt_cache",
"plugin_server",
"process_scheduled_changes",
+ "proxy",
"push_notifications",
"remote_config",
"split_person",
diff --git a/posthog/tasks/proxy.py b/posthog/tasks/proxy.py
new file mode 100644
index 000000000000..4c10f2f75879
--- /dev/null
+++ b/posthog/tasks/proxy.py
@@ -0,0 +1,35 @@
+from django.db import DatabaseError
+
+import requests
+from celery import shared_task
+
+from posthog.models import ProxyRecord
+from posthog.scoping_audit import skip_team_scope_audit
+from posthog.tasks.utils import CeleryQueue
+from posthog.temporal.proxy_service.cloudflare import (
+ CloudflareAPIError,
+ get_custom_hostname_by_domain,
+ update_custom_hostname_metadata,
+)
+
+
+@shared_task(
+ ignore_result=True,
+ queue=CeleryQueue.DEFAULT.value,
+ autoretry_for=(CloudflareAPIError, DatabaseError, requests.RequestException),
+ retry_backoff=30,
+ retry_backoff_max=3600,
+ max_retries=10,
+)
+@skip_team_scope_audit
+def reconcile_proxy_root_redirect(proxy_record_id: str) -> None:
+ try:
+ record = ProxyRecord.objects.get(id=proxy_record_id)
+ except ProxyRecord.DoesNotExist:
+ return
+
+ hostname = get_custom_hostname_by_domain(record.domain)
+ if hostname is None:
+ raise CloudflareAPIError("Cloudflare could not find this managed proxy hostname.")
+
+ update_custom_hostname_metadata(hostname, {"root_redirect_url": record.root_redirect_url or ""})
diff --git a/posthog/tasks/test/__snapshots__/test_task_registration.ambr b/posthog/tasks/test/__snapshots__/test_task_registration.ambr
index 69e6880bca0c..eb7f040e47a5 100644
--- a/posthog/tasks/test/__snapshots__/test_task_registration.ambr
+++ b/posthog/tasks/test/__snapshots__/test_task_registration.ambr
@@ -92,6 +92,7 @@
'posthog.tasks.llm_prompt_cache.invalidate_archived_prompt_versions_cache_task',
'posthog.tasks.plugin_server.fatal_plugin_error',
'posthog.tasks.plugin_server.hog_function_state_transition',
+ 'posthog.tasks.proxy.reconcile_proxy_root_redirect',
'posthog.tasks.push_notifications.send_user_push',
'posthog.tasks.remote_config.cleanup_stale_remote_config_expiry_tracking_task',
'posthog.tasks.remote_config.refresh_expiring_remote_config_cache_entries',
diff --git a/posthog/temporal/proxy_service/cloudflare.py b/posthog/temporal/proxy_service/cloudflare.py
index d724038a56dc..0cc62283bf2f 100644
--- a/posthog/temporal/proxy_service/cloudflare.py
+++ b/posthog/temporal/proxy_service/cloudflare.py
@@ -16,6 +16,8 @@ from django.conf import settings
import requests
+from posthog.dataclasses import frozen
+
CLOUDFLARE_API_BASE = "https://api.cloudflare.com/client/v4"
CLOUDFLARE_MIN_TLS_VERSION = "1.2"
@@ -174,7 +176,7 @@ class CustomHostnameSSL:
validation_records: list[dict] = field(default_factory=list)
-@dataclass
+@frozen
class CustomHostname:
"""Information about a Custom Hostname."""
@@ -182,6 +184,7 @@ class CustomHostname:
hostname: str
status: CustomHostnameStatus
ssl: CustomHostnameSSL
+ custom_metadata: dict[str, str] = field(default_factory=dict)
def _get_headers() -> dict[str, str]:
@@ -209,6 +212,7 @@ def _parse_hostname(result: dict) -> "CustomHostname":
certificate_authority=ssl_payload.get("certificate_authority"),
validation_records=ssl_payload.get("validation_records", []),
),
+ custom_metadata=result.get("custom_metadata", {}),
)
@@ -230,7 +234,7 @@ def _handle_response(response: requests.Response) -> dict:
return data
-def create_custom_hostname(domain: str) -> CustomHostname:
+def create_custom_hostname(domain: str, root_redirect_url: str | None = None) -> CustomHostname:
"""
Create a Custom Hostname in Cloudflare for SaaS.
@@ -259,6 +263,7 @@ def create_custom_hostname(domain: str) -> CustomHostname:
"min_tls_version": CLOUDFLARE_MIN_TLS_VERSION,
},
},
+ "custom_metadata": {"root_redirect_url": root_redirect_url or ""},
}
response = requests.post(url, headers=_get_headers(), json=payload, timeout=CLOUDFLARE_API_TIMEOUT_S)
@@ -316,6 +321,19 @@ def get_custom_hostname_by_domain(domain: str) -> t.Optional[CustomHostname]:
return _parse_hostname(results[0])
+def update_custom_hostname_metadata(hostname: CustomHostname, custom_metadata: dict[str, str]) -> CustomHostname:
+ """Replace a Custom Hostname's metadata while preserving keys owned by other features."""
+ url = f"{CLOUDFLARE_API_BASE}/zones/{settings.CLOUDFLARE_ZONE_ID}/custom_hostnames/{hostname.id}"
+ response = requests.patch(
+ url,
+ headers=_get_headers(),
+ json={"custom_metadata": {**hostname.custom_metadata, **custom_metadata}},
+ timeout=CLOUDFLARE_API_TIMEOUT_S,
+ )
+ data = _handle_response(response)
+ return _parse_hostname(data["result"])
+
+
def delete_custom_hostname(hostname_id: str) -> bool:
"""
Delete a Custom Hostname.
diff --git a/posthog/temporal/proxy_service/create.py b/posthog/temporal/proxy_service/create.py
index d8e67ef7e0c0..588855bf2b29 100644
--- a/posthog/temporal/proxy_service/create.py
+++ b/posthog/temporal/proxy_service/create.py
@@ -44,6 +44,7 @@ from posthog.temporal.proxy_service.common import (
activity_send_proxy_created_email,
activity_update_proxy_record,
get_grpc_client,
+ get_record,
record_exists,
update_record,
use_cloudflare_proxy,
@@ -289,11 +290,12 @@ async def create_cloudflare_custom_hostname(inputs: CreateCloudflareProxyInputs)
inputs.domain,
)
- if not await record_exists(inputs.proxy_record_id):
+ record = await get_record(inputs.proxy_record_id)
+ if record is None:
raise RecordDeletedException("proxy record was deleted while creating Cloudflare Custom Hostname")
try:
- result = await asyncio.to_thread(create_custom_hostname, inputs.domain)
+ result = await asyncio.to_thread(create_custom_hostname, inputs.domain, record.root_redirect_url)
logger.info(
"Created Cloudflare Custom Hostname %s for domain %s with status %s",
result.id,
diff --git a/posthog/temporal/proxy_service/test/test_cloudflare.py b/posthog/temporal/proxy_service/test/test_cloudflare.py
index d438b24c8835..d66d9e6fd41a 100644
--- a/posthog/temporal/proxy_service/test/test_cloudflare.py
+++ b/posthog/temporal/proxy_service/test/test_cloudflare.py
@@ -11,6 +11,7 @@ from posthog.temporal.proxy_service.cloudflare import (
_parse_hostname,
create_custom_hostname,
parse_cloudflare_error_code,
+ update_custom_hostname_metadata,
)
# Every status Cloudflare can send, which is a superset of what the enums name. Re-derive with:
@@ -77,12 +78,13 @@ class TestCloudflareAPIErrorIsRateLimited(TestCase):
self.assertEqual(error.is_rate_limited(), expected)
-def _hostname_payload(status="active", ssl_status="active"):
+def _hostname_payload(status="active", ssl_status="active", custom_metadata=None):
return {
"id": "abc123",
"hostname": "p.example.com",
"status": status,
"ssl": {"status": ssl_status, "validation_errors": []},
+ "custom_metadata": custom_metadata or {},
}
@@ -117,17 +119,20 @@ class TestParseHostnameStatuses(SimpleTestCase):
self.assertNotEqual(info.status, CustomHostnameStatus.ACTIVE)
+@override_settings(CLOUDFLARE_API_TOKEN="token", CLOUDFLARE_ZONE_ID="zone")
class TestCreateCustomHostname(SimpleTestCase):
- @override_settings(CLOUDFLARE_API_TOKEN="token", CLOUDFLARE_ZONE_ID="zone")
@patch("posthog.temporal.proxy_service.cloudflare.requests.post")
- def test_sets_minimum_tls_version(self, post):
+ def test_sets_minimum_tls_version_and_redirect_metadata(self, post_request):
response = Mock()
- response.json.return_value = {"success": True, "result": _hostname_payload()}
- post.return_value = response
+ response.json.return_value = {
+ "success": True,
+ "result": _hostname_payload(custom_metadata={"root_redirect_url": "https://example.com/"}),
+ }
+ post_request.return_value = response
- create_custom_hostname("p.example.com")
+ create_custom_hostname("p.example.com", "https://example.com/")
- post.assert_called_once_with(
+ post_request.assert_called_once_with(
"https://api.cloudflare.com/client/v4/zones/zone/custom_hostnames",
headers={"Authorization": "Bearer token", "Content-Type": "application/json"},
json={
@@ -137,10 +142,33 @@ class TestCreateCustomHostname(SimpleTestCase):
"type": "dv",
"settings": {"min_tls_version": "1.2"},
},
+ "custom_metadata": {"root_redirect_url": "https://example.com/"},
},
timeout=8.0,
)
+ @patch("posthog.temporal.proxy_service.cloudflare.requests.patch")
+ def test_preserves_existing_metadata(self, patch_request):
+ hostname = _parse_hostname(_hostname_payload(custom_metadata={"existing": "value"}))
+ response = Mock()
+ response.json.return_value = {
+ "success": True,
+ "result": _hostname_payload(
+ custom_metadata={"existing": "value", "root_redirect_url": "https://example.com/"}
+ ),
+ }
+ patch_request.return_value = response
+
+ updated = update_custom_hostname_metadata(hostname, {"root_redirect_url": "https://example.com/"})
+
+ patch_request.assert_called_once_with(
+ "https://api.cloudflare.com/client/v4/zones/zone/custom_hostnames/abc123",
+ headers={"Authorization": "Bearer token", "Content-Type": "application/json"},
+ json={"custom_metadata": {"existing": "value", "root_redirect_url": "https://example.com/"}},
+ timeout=8.0,
+ )
+ self.assertEqual(updated.custom_metadata["root_redirect_url"], "https://example.com/")
+
class TestParseCloudflareErrorCode(SimpleTestCase):
@parameterized.expand(
diff --git a/posthog/test/test_domain_connect.py b/posthog/test/test_domain_connect.py
index 44ba0f412c0a..1afd5fe9e150 100644
--- a/posthog/test/test_domain_connect.py
+++ b/posthog/test/test_domain_connect.py
@@ -64,11 +64,9 @@ class TestExtractRootDomainAndHost(BaseTest):
]
)
def test_extraction(self, name: str, full_domain: str, expected: tuple[str, str]) -> None:
- self.assertEqual(
- extract_root_domain_and_host(full_domain),
- expected,
- f"Failed for case {name} for domain {full_domain}",
- )
+ domain_parts = extract_root_domain_and_host(full_domain)
+ self.assertEqual(domain_parts.root_domain, expected[0], f"Failed root domain for {name}: {full_domain}")
+ self.assertEqual(domain_parts.host, expected[1], f"Failed host for {name}: {full_domain}")
class TestGetServiceIdForRegion(BaseTest):
diff --git a/products/platform_features/frontend/generated/api.schemas.ts b/products/platform_features/frontend/generated/api.schemas.ts
index ada307f7ec44..c7d8e8d82bdf 100644
--- a/products/platform_features/frontend/generated/api.schemas.ts
+++ b/products/platform_features/frontend/generated/api.schemas.ts
@@ -480,6 +480,194 @@ export interface PaginatedOrganizationPersonalAPIKeyListApi {
results: OrganizationPersonalAPIKeyApi[]
}
+/**
+ * * `waiting` - Waiting
+ * * `issuing` - Issuing
+ * * `valid` - Valid
+ * * `warning` - Warning
+ * * `erroring` - Erroring
+ * * `deleting` - Deleting
+ * * `timed_out` - Timed Out
+ */
+export type ProxyRecordStatusEnumApi = (typeof ProxyRecordStatusEnumApi)[keyof typeof ProxyRecordStatusEnumApi]
+
+export const ProxyRecordStatusEnumApi = {
+ Waiting: 'waiting',
+ Issuing: 'issuing',
+ Valid: 'valid',
+ Warning: 'warning',
+ Erroring: 'erroring',
+ Deleting: 'deleting',
+ TimedOut: 'timed_out',
+} as const
+
+export interface ProxyRecordApi {
+ /** Unique identifier for the proxy record. */
+ readonly id: string
+ /** The custom domain to proxy through, e.g. 'e.example.com'. Must be a valid subdomain you control. */
+ domain: string
+ /** The CNAME target to add as a DNS record for your domain. Point your domain's CNAME to this value. */
+ readonly target_cname: string
+ /**
+ * HTTPS URL that requests to the proxy domain root redirect to, or null when disabled.
+ * @nullable
+ */
+ readonly root_redirect_url: string | null
+ /** Whether this managed proxy supports a redirect from its root URL. */
+ readonly root_redirect_supported: boolean
+ /** Current provisioning status. Values: waiting (DNS verification pending), issuing (SSL certificate being issued), valid (proxy is live and working), warning (proxy has issues but is operational), erroring (proxy setup failed), deleting (removal in progress), timed_out (DNS verification timed out).
+ *
+ * * `waiting` - Waiting
+ * * `issuing` - Issuing
+ * * `valid` - Valid
+ * * `warning` - Warning
+ * * `erroring` - Erroring
+ * * `deleting` - Deleting
+ * * `timed_out` - Timed Out */
+ readonly status: ProxyRecordStatusEnumApi
+ /**
+ * Human-readable status message with details about errors or warnings, if any.
+ * @nullable
+ */
+ readonly message: string | null
+ /** When this proxy record was created. */
+ readonly created_at: string
+ /** When this proxy record was last updated. */
+ readonly updated_at: string
+ /** ID of the user who created this proxy record. */
+ readonly created_by: number
+}
+
+export interface ProxyRecordListResponseApi {
+ results: ProxyRecordApi[]
+ /** Maximum number of proxy records allowed for this organization's current plan. */
+ max_proxy_records: number
+}
+
+export interface PatchedProxyRecordUpdateApi {
+ /**
+ * HTTPS URL that requests to the proxy domain root redirect to, or null to disable the redirect. The URL must use the same registrable domain as the managed proxy.
+ * @maxLength 1024
+ * @nullable
+ */
+ root_redirect_url?: string | null
+}
+
+/**
+ * * `healthy` - healthy
+ * * `warn` - warn
+ * * `fail` - fail
+ */
+export type DiagnosticReportSummaryStatusEnumApi =
+ (typeof DiagnosticReportSummaryStatusEnumApi)[keyof typeof DiagnosticReportSummaryStatusEnumApi]
+
+export const DiagnosticReportSummaryStatusEnumApi = {
+ Healthy: 'healthy',
+ Warn: 'warn',
+ Fail: 'fail',
+} as const
+
+export interface DiagnosticReportSummaryApi {
+ /** Overall outcome: healthy if the proxy is serving requests, warn for non-blocking issues, fail otherwise.
+ *
+ * * `healthy` - healthy
+ * * `warn` - warn
+ * * `fail` - fail */
+ status: DiagnosticReportSummaryStatusEnumApi
+ /**
+ * Check id of the most actionable failure, if any. Null when status is healthy.
+ * @nullable
+ */
+ primary_issue: string | null
+ /**
+ * One-sentence next action the customer should take. Null when nothing's wrong.
+ * @nullable
+ */
+ next_action: string | null
+}
+
+/**
+ * * `passed` - passed
+ * * `warned` - warned
+ * * `failed` - failed
+ * * `skipped` - skipped
+ */
+export type DiagnosticCheckResultStatusEnumApi =
+ (typeof DiagnosticCheckResultStatusEnumApi)[keyof typeof DiagnosticCheckResultStatusEnumApi]
+
+export const DiagnosticCheckResultStatusEnumApi = {
+ Passed: 'passed',
+ Warned: 'warned',
+ Failed: 'failed',
+ Skipped: 'skipped',
+} as const
+
+/**
+ * * `dns` - dns
+ * * `config` - config
+ * * `wait` - wait
+ * * `retry` - retry
+ */
+export type DiagnosticRemediationTypeEnumApi =
+ (typeof DiagnosticRemediationTypeEnumApi)[keyof typeof DiagnosticRemediationTypeEnumApi]
+
+export const DiagnosticRemediationTypeEnumApi = {
+ Dns: 'dns',
+ Config: 'config',
+ Wait: 'wait',
+ Retry: 'retry',
+} as const
+
+export interface DiagnosticDnsRecordApi {
+ /** DNS record name (the hostname the record is set on). */
+ name: string
+ /** DNS record type, e.g. CNAME, CAA, A. */
+ type: string
+ /** DNS record value to set. */
+ value: string
+}
+
+export interface DiagnosticRemediationApi {
+ /** Category of fix. dns: customer must change DNS records. config: customer must adjust their server config (e.g. allow port 80). wait: no action — the system will resolve on its own. retry: hit Retry.
+ *
+ * * `dns` - dns
+ * * `config` - config
+ * * `wait` - wait
+ * * `retry` - retry */
+ type: DiagnosticRemediationTypeEnumApi
+ /** One-line, action-oriented summary of what to do. */
+ summary: string
+ /** DNS records the customer should add (empty when remediation is not DNS-based). */
+ records: DiagnosticDnsRecordApi[]
+}
+
+export interface DiagnosticCheckResultApi {
+ /** Stable identifier for the check (e.g. cname, cloudflare, caa, http_challenge, live_event, cert_expiry). */
+ id: string
+ /** Human-readable check name. */
+ name: string
+ /** passed: ok. warned: degraded but not blocking. failed: blocking. skipped: not run for this state.
+ *
+ * * `passed` - passed
+ * * `warned` - warned
+ * * `failed` - failed
+ * * `skipped` - skipped */
+ status: DiagnosticCheckResultStatusEnumApi
+ /** Customer-facing explanation of the check's outcome. */
+ detail: string
+ /** Concrete remediation steps when the check failed; null when there's nothing actionable. */
+ remediation?: DiagnosticRemediationApi | null
+}
+
+export interface DiagnosticReportApi {
+ /** When this diagnostic report was generated (UTC). */
+ ran_at: string
+ /** Top-level outcome and recommended next action. */
+ summary: DiagnosticReportSummaryApi
+ /** Per-check results in execution order. */
+ checks: DiagnosticCheckResultApi[]
+}
+
export type RoleApiMembersItem = { [key: string]: unknown }
export interface RoleApi {
diff --git a/products/platform_features/frontend/generated/api.ts b/products/platform_features/frontend/generated/api.ts
index 2b3cb4d10ded..8bf872243c88 100644
--- a/products/platform_features/frontend/generated/api.ts
+++ b/products/platform_features/frontend/generated/api.ts
@@ -23,6 +23,7 @@ import type {
CommentApi,
CommentSlackThreadApi,
CommentsListParams,
+ DiagnosticReportApi,
ListParams,
MembersListParams,
OrganizationAIAccessRequestResponseApi,
@@ -45,10 +46,13 @@ import type {
PatchedOrganizationApi,
PatchedOrganizationMemberApi,
PatchedPinnedSceneTabsApi,
+ PatchedProxyRecordUpdateApi,
PatchedRoleApi,
PatchedUserFacetSettingsApi,
PersonalApiKeysListParams,
PinnedSceneTabsApi,
+ ProxyRecordApi,
+ ProxyRecordListResponseApi,
RoleApi,
RoleMembershipApi,
RolesListParams,
@@ -364,6 +368,132 @@ export const personalApiKeysList = async (
})
}
+export const getProxyRecordsListUrl = (organizationId: string) => {
+ return `/api/organizations/${organizationId}/proxy_records/`
+}
+
+/**
+ * List all reverse proxies configured for the organization. Returns proxy records along with the maximum number allowed by the current plan.
+ */
+export const proxyRecordsList = async (
+ organizationId: string,
+ options?: RequestInit
+): Promise<ProxyRecordListResponseApi> => {
+ return apiMutator<ProxyRecordListResponseApi>(getProxyRecordsListUrl(organizationId), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getProxyRecordsCreateUrl = (organizationId: string) => {
+ return `/api/organizations/${organizationId}/proxy_records/`
+}
+
+/**
+ * Create a new managed reverse proxy. Provide the domain you want to proxy through. The response includes the CNAME target you need to add as a DNS record. Once the CNAME is configured, the proxy will be automatically verified and provisioned.
+ */
+export const proxyRecordsCreate = async (
+ organizationId: string,
+ proxyRecordApi: NonReadonly<ProxyRecordApi>,
+ options?: RequestInit
+): Promise<ProxyRecordApi> => {
+ return apiMutator<ProxyRecordApi>(getProxyRecordsCreateUrl(organizationId), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(proxyRecordApi),
+ })
+}
+
+export const getProxyRecordsRetrieveUrl = (organizationId: string, id: string) => {
+ return `/api/organizations/${organizationId}/proxy_records/${id}/`
+}
+
+/**
+ * Get details of a specific reverse proxy by ID. Returns the full configuration including domain, CNAME target, and current provisioning status.
+ */
+export const proxyRecordsRetrieve = async (
+ organizationId: string,
+ id: string,
+ options?: RequestInit
+): Promise<ProxyRecordApi> => {
+ return apiMutator<ProxyRecordApi>(getProxyRecordsRetrieveUrl(organizationId, id), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getProxyRecordsPartialUpdateUrl = (organizationId: string, id: string) => {
+ return `/api/organizations/${organizationId}/proxy_records/${id}/`
+}
+
+/**
+ * Set or clear the HTTPS redirect for requests to the managed proxy domain root.
+ */
+export const proxyRecordsPartialUpdate = async (
+ organizationId: string,
+ id: string,
+ patchedProxyRecordUpdateApi?: PatchedProxyRecordUpdateApi,
+ options?: RequestInit
+): Promise<ProxyRecordApi> => {
+ return apiMutator<ProxyRecordApi>(getProxyRecordsPartialUpdateUrl(organizationId, id), {
+ ...options,
+ method: 'PATCH',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(patchedProxyRecordUpdateApi),
+ })
+}
+
+export const getProxyRecordsDestroyUrl = (organizationId: string, id: string) => {
+ return `/api/organizations/${organizationId}/proxy_records/${id}/`
+}
+
+/**
+ * Delete a reverse proxy. For proxies in 'waiting', 'erroring', or 'timed_out' status, the record is deleted immediately. For active proxies, a deletion workflow is started to clean up the provisioned infrastructure.
+ */
+export const proxyRecordsDestroy = async (organizationId: string, id: string, options?: RequestInit): Promise<void> => {
+ return apiMutator<void>(getProxyRecordsDestroyUrl(organizationId, id), {
+ ...options,
+ method: 'DELETE',
+ })
+}
+
+export const getProxyRecordsDiagnoseCreateUrl = (organizationId: string, id: string) => {
+ return `/api/organizations/${organizationId}/proxy_records/${id}/diagnose/`
+}
+
+/**
+ * Run a deep diagnostic on a reverse proxy. Inspects DNS CNAME alignment, the certificate provider's hostname state, CAA records walked up the customer's DNS tree, HTTP-01 challenge reachability, a live event probe, and certificate expiry. Returns a structured report with each check's status and concrete remediation steps (e.g. exact DNS records to add). Use this to debug why a proxy is stuck or erroring.
+ */
+export const proxyRecordsDiagnoseCreate = async (
+ organizationId: string,
+ id: string,
+ options?: RequestInit
+): Promise<DiagnosticReportApi> => {
+ return apiMutator<DiagnosticReportApi>(getProxyRecordsDiagnoseCreateUrl(organizationId, id), {
+ ...options,
+ method: 'POST',
+ })
+}
+
+export const getProxyRecordsRetryCreateUrl = (organizationId: string, id: string) => {
+ return `/api/organizations/${organizationId}/proxy_records/${id}/retry/`
+}
+
+/**
+ * Retry provisioning a failed reverse proxy. Only available for proxies in 'erroring' or 'timed_out' status. Resets the proxy to 'waiting' status and restarts the provisioning workflow.
+ */
+export const proxyRecordsRetryCreate = async (
+ organizationId: string,
+ id: string,
+ options?: RequestInit
+): Promise<ProxyRecordApi> => {
+ return apiMutator<ProxyRecordApi>(getProxyRecordsRetryCreateUrl(organizationId, id), {
+ ...options,
+ method: 'POST',
+ })
+}
+
export const getRolesListUrl = (organizationId: string, params?: RolesListParams) => {
const normalizedParams = new URLSearchParams()
diff --git a/products/platform_features/frontend/generated/api.zod.ts b/products/platform_features/frontend/generated/api.zod.ts
index ad42d52dfde7..64e7a5392aa4 100644
--- a/products/platform_features/frontend/generated/api.zod.ts
+++ b/products/platform_features/frontend/generated/api.zod.ts
@@ -197,6 +197,30 @@ export const MembersPartialUpdateBody = /* @__PURE__ */ zod.object({
.describe('\* `1` - member\n\* `8` - administrator\n\* `15` - owner'),
})
+/**
+ * Create a new managed reverse proxy. Provide the domain you want to proxy through. The response includes the CNAME target you need to add as a DNS record. Once the CNAME is configured, the proxy will be automatically verified and provisioned.
+ */
+export const ProxyRecordsCreateBody = /* @__PURE__ */ zod.object({
+ domain: zod
+ .string()
+ .describe("The custom domain to proxy through, e.g. 'e.example.com'. Must be a valid subdomain you control."),
+})
+
+/**
+ * Set or clear the HTTPS redirect for requests to the managed proxy domain root.
+ */
+export const proxyRecordsPartialUpdateBodyRootRedirectUrlMax = 1024
+
+export const ProxyRecordsPartialUpdateBody = /* @__PURE__ */ zod.object({
+ root_redirect_url: zod
+ .url()
+ .max(proxyRecordsPartialUpdateBodyRootRedirectUrlMax)
+ .nullish()
+ .describe(
+ 'HTTPS URL that requests to the proxy domain root redirect to, or null to disable the redirect. The URL must use the same registrable domain as the managed proxy.'
+ ),
+})
+
/**
* Role endpoints disclose member records, so they scope them the same way the members list
* does when the org restricts member list visibility.
diff --git a/services/mcp/definitions/proxy-records.yaml b/services/mcp/definitions/proxy-records.yaml
index 7136e7bfa9a3..1a645a5b09f8 100644
--- a/services/mcp/definitions/proxy-records.yaml
+++ b/services/mcp/definitions/proxy-records.yaml
@@ -91,6 +91,9 @@ tools:
List all managed reverse proxies configured for the current organization. Returns each proxy's domain, CNAME
target, provisioning status, and the maximum number of proxies allowed by the current plan. Use this to
check whether a reverse proxy is set up before recommending one.
+ proxy-records-partial-update:
+ operation: proxy_records_partial_update
+ enabled: false
proxy-retry:
operation: proxy_records_retry_create
enabled: true
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 9fb3cd51a285..7532f2aca0d7 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -64119,6 +64119,15 @@ export namespace Schemas {
scopes?: string[];
}
+ export interface PatchedProxyRecordUpdate {
+ /**
+ * HTTPS URL that requests to the proxy domain root redirect to, or null to disable the redirect. The URL must use the same registrable domain as the managed proxy.
+ * @maxLength 1024
+ * @nullable
+ */
+ root_redirect_url?: string | null;
+ }
+
/**
* Request body for editing a review comment's markdown body.
*/
@@ -69254,6 +69263,13 @@ export namespace Schemas {
domain: string;
/** The CNAME target to add as a DNS record for your domain. Point your domain's CNAME to this value. */
readonly target_cname: string;
+ /**
+ * HTTPS URL that requests to the proxy domain root redirect to, or null when disabled.
+ * @nullable
+ */
+ readonly root_redirect_url: string | null;
+ /** Whether this managed proxy supports a redirect from its root URL. */
+ readonly root_redirect_supported: boolean;
/** Current provisioning status. Values: waiting (DNS verification pending), issuing (SSL certificate being issued), valid (proxy is live and working), warning (proxy has issues but is operational), erroring (proxy setup failed), deleting (removal in progress), timed_out (DNS verification timed out).
*
* * `waiting` - Waiting
diff --git a/services/mcp/src/tools/generated/proxy-records.ts b/services/mcp/src/tools/generated/proxy-records.ts
index 2df501065601..7c181af452c3 100644
--- a/services/mcp/src/tools/generated/proxy-records.ts
+++ b/services/mcp/src/tools/generated/proxy-records.ts
@@ -79,13 +79,13 @@ const proxyGet = (): ToolBase<typeof ProxyGetSchema, Schemas.ProxyRecord> => ({
const ProxyListSchema = z.object({})
-const proxyList = (): ToolBase<typeof ProxyListSchema, WithPostHogUrl<Schemas.ProxyRecordListResponse[]>> => ({
+const proxyList = (): ToolBase<typeof ProxyListSchema, WithPostHogUrl<Schemas.ProxyRecordListResponse>> => ({
name: 'proxy-list',
schema: ProxyListSchema,
// eslint-disable-next-line no-unused-vars
handler: async (context: Context, params: z.infer<typeof ProxyListSchema>) => {
const orgId = await context.stateManager.getOrgID()
- const result = await context.api.request<Schemas.ProxyRecordListResponse[]>({
+ const result = await context.api.request<Schemas.ProxyRecordListResponse>({
method: 'GET',
path: `/api/organizations/${encodeURIComponent(String(orgId))}/proxy_records/`,
})