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 in-app reverse proxy diagnostics (#57364)

Yasendf0c15e64373
diff --git a/ee/hogai/test/test_tool.py b/ee/hogai/test/test_tool.py
index d52a186140fb..17a29c9e2f64 100644
--- a/ee/hogai/test/test_tool.py
+++ b/ee/hogai/test/test_tool.py
@@ -361,6 +361,7 @@ class TestToolAccessControlDeclarations(BaseTest):
"fix_hogql_query",
"analyze_user_interviews",
"call_mcp_server", # Scoped to user's own MCP installations (team + user filtered) but no protected resources modified
+ "diagnose_proxy", # Explicit OrganizationMembership.Level >= ADMIN check inside _arun_impl; resource-level RBAC doesn't recognize membership level so we can't use get_required_resource_access here
}
def test_all_tools_have_access_control_or_are_exempt(self):
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.json
index f4e87e0ca91f..7e3468537a40 100644
--- a/frontend/src/queries/schema.json
+++ b/frontend/src/queries/schema.json
@@ -3473,7 +3473,8 @@
"finalize_plan",
"call_mcp_server",
"search_llm_traces",
- "run_hog_eval_test"
+ "run_hog_eval_test",
+ "diagnose_proxy"
],
"type": "string"
},
diff --git a/frontend/src/queries/schema/schema-assistant-messages.ts b/frontend/src/queries/schema/schema-assistant-messages.ts
index ba40db0f1cf0..46c3ca0c6936 100644
--- a/frontend/src/queries/schema/schema-assistant-messages.ts
+++ b/frontend/src/queries/schema/schema-assistant-messages.ts
@@ -496,6 +496,7 @@ export type AssistantTool =
| 'call_mcp_server'
| 'search_llm_traces'
| 'run_hog_eval_test'
+ | 'diagnose_proxy'
export enum AgentMode {
ProductAnalytics = 'product_analytics',
diff --git a/frontend/src/scenes/max/max-constants.tsx b/frontend/src/scenes/max/max-constants.tsx
index 3b865f2594bf..cbad80c42c00 100644
--- a/frontend/src/scenes/max/max-constants.tsx
+++ b/frontend/src/scenes/max/max-constants.tsx
@@ -988,6 +988,14 @@ export const TOOL_DEFINITIONS: Record<AssistantTool, ToolDefinition> = {
return toolCall.status === 'completed' ? 'Created alert' : 'Creating alert...'
},
},
+ diagnose_proxy: {
+ name: 'Diagnose reverse proxy',
+ description: 'Diagnose reverse proxy stuck or erroring states',
+ icon: <IconCloud />,
+ displayFormatter: (toolCall) => {
+ return toolCall.status === 'completed' ? 'Diagnosed reverse proxy' : 'Diagnosing reverse proxy...'
+ },
+ },
finalize_plan: {
name: 'Finalize plan',
description: 'Finalize plan',
diff --git a/frontend/src/scenes/settings/environment/ManagedReverseProxy.tsx b/frontend/src/scenes/settings/environment/ManagedReverseProxy.tsx
index fdd2fd9e5f04..6636508293eb 100644
--- a/frontend/src/scenes/settings/environment/ManagedReverseProxy.tsx
+++ b/frontend/src/scenes/settings/environment/ManagedReverseProxy.tsx
@@ -1,8 +1,9 @@
import clsx from 'clsx'
import { useActions, useValues } from 'kea'
import { Form } from 'kea-forms'
+import { useMemo } from 'react'
-import { IconEllipsis, IconInfo } from '@posthog/icons'
+import { IconCheckCircle, IconEllipsis, IconInfo, IconWarning, IconX } from '@posthog/icons'
import {
LemonBanner,
LemonButton,
@@ -25,9 +26,10 @@ import { LemonField } from 'lib/lemon-ui/LemonField'
import { LemonMarkdown } from 'lib/lemon-ui/LemonMarkdown'
import { Link } from 'lib/lemon-ui/Link'
import { isKeyOf } from 'lib/utils'
+import { useMaxTool } from 'scenes/max/useMaxTool'
import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'
-import { ProxyRecord, proxyLogic } from './proxyLogic'
+import { DiagnosticCheckResult, DiagnosticCheckStatus, DiagnosticReport, ProxyRecord, proxyLogic } from './proxyLogic'
import { ProxySDKSetup } from './ProxySDKSetup'
const statusText = {
@@ -36,9 +38,17 @@ const statusText = {
}
export function ManagedReverseProxy(): JSX.Element {
- const { cloudflareOptInAcknowledged, formState, proxyRecords, proxyRecordsLoading, maxProxyRecords } =
- useValues(proxyLogic)
- const { acknowledgeCloudflareOptIn, deleteRecord, retryRecord, showForm } = useActions(proxyLogic)
+ const {
+ cloudflareOptInAcknowledged,
+ formState,
+ proxyRecords,
+ proxyRecordsLoading,
+ maxProxyRecords,
+ diagnoseLoadingIds,
+ expandedRecordIds,
+ } = useValues(proxyLogic)
+ const { acknowledgeCloudflareOptIn, deleteRecord, retryRecord, diagnose, setRecordExpanded, showForm } =
+ useActions(proxyLogic)
const { preflight } = useValues(preflightLogic)
const cloudflareProxyEnabled = preflight?.instance_preferences?.cloudflare_proxy_enabled
@@ -53,6 +63,31 @@ export function ManagedReverseProxy(): JSX.Element {
const recordsWithMessages = proxyRecords.filter((record) => !!record.message)
const validProxyRecords = proxyRecords.filter((record) => record.status === 'valid')
+ // Surface the diagnose_proxy MaxTool while this scene is mounted, with the visible
+ // records as context so Max can resolve "diagnose e.foo.com" to a record id.
+ useMaxTool({
+ identifier: 'diagnose_proxy',
+ active: proxyRecords.length > 0 && !restrictionReason,
+ context: useMemo(
+ () => ({
+ proxy_records: proxyRecords.map((r) => ({
+ id: r.id,
+ domain: r.domain,
+ status: r.status,
+ message: r.message,
+ })),
+ }),
+ [proxyRecords]
+ ),
+ suggestions: useMemo(() => {
+ const erroring = proxyRecords.find((r) => r.status === 'erroring' || r.status === 'timed_out')
+ if (erroring) {
+ return [`Why is ${erroring.domain} erroring?`]
+ }
+ return proxyRecords.length > 0 ? [`Diagnose ${proxyRecords[0].domain}`] : []
+ }, [proxyRecords]),
+ })
+
const columns: LemonTableColumns<ProxyRecord> = [
{
title: 'Domain',
@@ -98,11 +133,17 @@ export function ManagedReverseProxy(): JSX.Element {
width: 20,
className: 'flex justify-center',
render: function Render(_, { id, status }) {
+ const isDiagnosing = diagnoseLoadingIds.includes(id)
return (
status != 'deleting' &&
!restrictionReason && (
<LemonMenu
items={[
+ {
+ label: isDiagnosing ? 'Running diagnostics…' : 'Diagnose',
+ onClick: () => diagnose(id),
+ disabledReason: isDiagnosing ? 'A diagnostic is already running' : undefined,
+ },
...(status === 'erroring' || status === 'timed_out'
? [
{
@@ -161,6 +202,9 @@ export function ManagedReverseProxy(): JSX.Element {
dataSource={proxyRecords}
expandable={{
expandedRowRender: (record) => <ExpandedRow record={record} />,
+ isRowExpanded: (record) => (expandedRecordIds.includes(record.id) ? true : -1),
+ onRowExpand: (record) => setRecordExpanded(record.id, true),
+ onRowCollapse: (record) => setRecordExpanded(record.id, false),
}}
/>
@@ -264,22 +308,40 @@ function CloudflareOptInBanner({
}
const ExpandedRow = ({ record }: { record: ProxyRecord }): JSX.Element => {
+ const { diagnosticReports, recordActiveTabs } = useValues(proxyLogic)
+ const { setRecordActiveTab } = useActions(proxyLogic)
+
+ const report = diagnosticReports[record.id]
+ const activeKey = recordActiveTabs[record.id] ?? 'cname'
+
+ const tabs = [
+ {
+ label: 'CNAME',
+ key: 'cname',
+ content: (
+ <CodeSnippet key={record.id} language={Language.HTTP}>
+ {record.target_cname}
+ </CodeSnippet>
+ ),
+ },
+ ...(report
+ ? [
+ {
+ label: 'Diagnosis',
+ key: 'diagnosis',
+ content: <DiagnosticReportContent report={report} />,
+ },
+ ]
+ : []),
+ ]
+
return (
<div className="pb-4 pr-4 space-y-2">
<LemonTabs
size="small"
- activeKey="cname"
- tabs={[
- {
- label: 'CNAME',
- key: 'cname',
- content: (
- <CodeSnippet key={record.id} language={Language.HTTP}>
- {record.target_cname}
- </CodeSnippet>
- ),
- },
- ]}
+ activeKey={activeKey}
+ onChange={(key) => setRecordActiveTab(record.id, key)}
+ tabs={tabs}
/>
{record.status === 'waiting' && (
<DomainConnectBanner
@@ -394,3 +456,56 @@ const WaitingRecords = (): JSX.Element | null => {
</div>
)
}
+
+const checkStatusIcon = (status: DiagnosticCheckStatus): JSX.Element => {
+ switch (status) {
+ case 'passed':
+ return <IconCheckCircle className="text-success" />
+ case 'warned':
+ return <IconWarning className="text-warning-dark" />
+ case 'failed':
+ return <IconX className="text-danger" />
+ case 'skipped':
+ return <IconInfo className="text-secondary" />
+ }
+}
+
+function DiagnosticReportContent({ report }: { report: DiagnosticReport }): JSX.Element {
+ return (
+ <div className="flex flex-col gap-3">
+ <div className="text-xs text-secondary">Ran {new Date(report.ran_at).toLocaleString()}</div>
+ <div className="flex flex-col gap-2">
+ {report.checks.map((check) => (
+ <DiagnosticCheckRow key={check.id} check={check} />
+ ))}
+ </div>
+ </div>
+ )
+}
+
+function DiagnosticCheckRow({ check }: { check: DiagnosticCheckResult }): JSX.Element {
+ return (
+ <div className="border rounded p-3 flex flex-col gap-2 bg-surface-secondary">
+ <div className="flex items-center gap-2">
+ {checkStatusIcon(check.status)}
+ <span className="font-semibold">{check.name}</span>
+ <span className="text-xs text-secondary capitalize">({check.status})</span>
+ </div>
+ <LemonMarkdown className="text-sm">{check.detail}</LemonMarkdown>
+ {check.remediation && (
+ <div className="border-t pt-2 mt-1 flex flex-col gap-2">
+ <LemonMarkdown className="text-sm font-semibold">{check.remediation.summary}</LemonMarkdown>
+ {check.remediation.records.length > 0 && (
+ <div className="flex flex-col gap-1">
+ {check.remediation.records.map((dnsRecord, i) => (
+ <CodeSnippet key={i} language={Language.HTTP}>
+ {`${dnsRecord.name}\t${dnsRecord.type}\t${dnsRecord.value}`}
+ </CodeSnippet>
+ ))}
+ </div>
+ )}
+ </div>
+ )}
+ </div>
+ )
+}
diff --git a/frontend/src/scenes/settings/environment/proxyLogic.ts b/frontend/src/scenes/settings/environment/proxyLogic.ts
index b034c2e7f365..0f979d0bc599 100644
--- a/frontend/src/scenes/settings/environment/proxyLogic.ts
+++ b/frontend/src/scenes/settings/environment/proxyLogic.ts
@@ -28,6 +28,42 @@ export type ProxyRecord = {
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
+}
+
+export type DiagnosticRemediation = {
+ type: DiagnosticRemediationType
+ summary: string
+ records: DiagnosticDnsRecord[]
+}
+
+export type DiagnosticCheckResult = {
+ id: string
+ name: string
+ status: DiagnosticCheckStatus
+ detail: string
+ remediation?: DiagnosticRemediation | null
+}
+
+export type DiagnosticReportSummary = {
+ status: DiagnosticSummaryStatus
+ primary_issue: string | null
+ next_action: string | null
+}
+
+export type DiagnosticReport = {
+ ran_at: string
+ summary: DiagnosticReportSummary
+ checks: DiagnosticCheckResult[]
+}
+
export function domainFor(proxyRecord: ProxyRecord | undefined): string {
if (!proxyRecord) {
return apiHostOrigin()
@@ -84,6 +120,12 @@ export const proxyLogic = kea<proxyLogicType>([
acknowledgeCloudflareOptIn: true,
setCloudflareOptInChecked: (checked: boolean) => ({ checked }),
setMaxProxyRecords: (maxProxyRecords: number) => ({ maxProxyRecords }),
+ diagnose: (id: ProxyRecord['id']) => ({ id }),
+ diagnoseSuccess: (id: ProxyRecord['id'], report: DiagnosticReport) => ({ id, report }),
+ diagnoseFailure: (id: ProxyRecord['id'], error: string) => ({ id, error }),
+ clearDiagnosticReport: (id: ProxyRecord['id']) => ({ id }),
+ setRecordExpanded: (id: ProxyRecord['id'], expanded: boolean) => ({ id, expanded }),
+ setRecordActiveTab: (id: ProxyRecord['id'], tab: string) => ({ id, tab }),
})),
reducers(() => ({
formState: ['collapsed' as FormState, { showForm: () => 'active', collapseForm: () => 'collapsed' }],
@@ -107,6 +149,46 @@ export const proxyLogic = kea<proxyLogicType>([
setMaxProxyRecords: (_, { maxProxyRecords }) => maxProxyRecords,
},
],
+ diagnosticReports: [
+ {} as Record<string, DiagnosticReport>,
+ {
+ diagnoseSuccess: (state, { id, report }) => ({ ...state, [id]: report }),
+ clearDiagnosticReport: (state, { id }) => {
+ const { [id]: _removed, ...rest } = state
+ return rest
+ },
+ },
+ ],
+ diagnoseLoadingIds: [
+ [] as string[],
+ {
+ diagnose: (state, { id }) => (state.includes(id) ? state : [...state, id]),
+ diagnoseSuccess: (state, { id }) => state.filter((existingId) => existingId !== id),
+ diagnoseFailure: (state, { id }) => state.filter((existingId) => existingId !== id),
+ },
+ ],
+ expandedRecordIds: [
+ [] as string[],
+ {
+ setRecordExpanded: (state, { id, expanded }) => {
+ if (expanded) {
+ return state.includes(id) ? state : [...state, id]
+ }
+ return state.filter((existingId) => existingId !== id)
+ },
+ clearDiagnosticReport: (state, { id }) => state.filter((existingId) => existingId !== id),
+ },
+ ],
+ recordActiveTabs: [
+ {} as Record<string, string>,
+ {
+ setRecordActiveTab: (state, { id, tab }) => ({ ...state, [id]: tab }),
+ clearDiagnosticReport: (state, { id }) => {
+ const { [id]: _removed, ...rest } = state
+ return rest
+ },
+ },
+ ],
})),
loaders(({ values, actions }) => ({
proxyRecords: {
@@ -167,6 +249,23 @@ export const proxyLogic = kea<proxyLogicType>([
actions.loadRecords()
}
},
+ diagnose: async ({ id }) => {
+ try {
+ const report = (await api.create(
+ `api/organizations/${values.currentOrganizationId}/proxy_records/${id}/diagnose`
+ )) as DiagnosticReport
+ actions.diagnoseSuccess(id, report)
+ } catch (e) {
+ const message = e instanceof Error ? e.message : String(e)
+ actions.diagnoseFailure(id, message)
+ lemonToast.error(`Diagnose failed: ${message}`)
+ }
+ },
+ diagnoseSuccess: ({ id }) => {
+ // Auto-expand the row and switch to the Diagnosis tab so the user sees the report immediately.
+ actions.setRecordExpanded(id, true)
+ actions.setRecordActiveTab(id, 'diagnosis')
+ },
})),
forms(({ actions, values }) => ({
createRecord: {
diff --git a/posthog/api/proxy_record.py b/posthog/api/proxy_record.py
index 6ec83cc2493a..49ef1b88fa59 100644
--- a/posthog/api/proxy_record.py
+++ b/posthog/api/proxy_record.py
@@ -3,6 +3,7 @@ import asyncio
import hashlib
from django.conf import settings
+from django.core.cache import cache
import posthoganalytics
from drf_spectacular.utils import extend_schema
@@ -12,6 +13,7 @@ from rest_framework.exceptions import NotFound
from rest_framework.response import Response
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.event_usage import groups
@@ -100,6 +102,77 @@ class ProxyRecordListResponseSerializer(serializers.Serializer):
)
+# --- Diagnose response serializers ---
+# Mirror the dataclasses defined in products/platform_features/backend/proxy/diagnostics.py.
+# These are pure response shapes — drf-spectacular generates frontend types and MCP tool
+# schemas from them, so every field needs help_text and every choice list must be enumerated.
+
+DIAGNOSE_COOLDOWN_SECONDS = 30
+
+DIAGNOSTIC_CHECK_STATUS_CHOICES = ["passed", "warned", "failed", "skipped"]
+DIAGNOSTIC_SUMMARY_STATUS_CHOICES = ["healthy", "warn", "fail"]
+DIAGNOSTIC_REMEDIATION_TYPE_CHOICES = ["dns", "config", "wait", "retry"]
+
+
+class DiagnosticDnsRecordSerializer(serializers.Serializer):
+ name = serializers.CharField(help_text="DNS record name (the hostname the record is set on).")
+ type = serializers.CharField(help_text="DNS record type, e.g. CNAME, CAA, A.")
+ value = serializers.CharField(help_text="DNS record value to set.")
+
+
+class DiagnosticRemediationSerializer(serializers.Serializer):
+ type = serializers.ChoiceField(
+ choices=DIAGNOSTIC_REMEDIATION_TYPE_CHOICES,
+ help_text=(
+ "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."
+ ),
+ )
+ summary = serializers.CharField(help_text="One-line, action-oriented summary of what to do.")
+ records = DiagnosticDnsRecordSerializer(
+ many=True,
+ help_text="DNS records the customer should add (empty when remediation is not DNS-based).",
+ )
+
+
+class DiagnosticCheckResultSerializer(serializers.Serializer):
+ id = serializers.CharField(
+ help_text="Stable identifier for the check (e.g. cname, cloudflare, caa, http_challenge, live_event, cert_expiry)."
+ )
+ name = serializers.CharField(help_text="Human-readable check name.")
+ status = serializers.ChoiceField(
+ choices=DIAGNOSTIC_CHECK_STATUS_CHOICES,
+ help_text="passed: ok. warned: degraded but not blocking. failed: blocking. skipped: not run for this state.",
+ )
+ detail = serializers.CharField(help_text="Customer-facing explanation of the check's outcome.")
+ remediation = DiagnosticRemediationSerializer(
+ allow_null=True,
+ required=False,
+ help_text="Concrete remediation steps when the check failed; null when there's nothing actionable.",
+ )
+
+
+class DiagnosticReportSummarySerializer(serializers.Serializer):
+ status = serializers.ChoiceField(
+ choices=DIAGNOSTIC_SUMMARY_STATUS_CHOICES,
+ help_text="Overall outcome: healthy if the proxy is serving requests, warn for non-blocking issues, fail otherwise.",
+ )
+ primary_issue = serializers.CharField(
+ allow_null=True,
+ help_text="Check id of the most actionable failure, if any. Null when status is healthy.",
+ )
+ next_action = serializers.CharField(
+ allow_null=True,
+ help_text="One-sentence next action the customer should take. Null when nothing's wrong.",
+ )
+
+
+class DiagnosticReportSerializer(serializers.Serializer):
+ ran_at = serializers.DateTimeField(help_text="When this diagnostic report was generated (UTC).")
+ summary = DiagnosticReportSummarySerializer(help_text="Top-level outcome and recommended next action.")
+ checks = DiagnosticCheckResultSerializer(many=True, help_text="Per-check results in execution order.")
+
+
@extend_schema(tags=["reverse_proxy"])
class ProxyRecordViewset(TeamAndOrgViewSetMixin, ModelViewSet):
scope_object = "organization"
@@ -204,6 +277,39 @@ class ProxyRecordViewset(TeamAndOrgViewSetMixin, ModelViewSet):
_capture_proxy_event(request, record, "created")
return Response(serializer.data, status=status.HTTP_201_CREATED)
+ @extend_schema(
+ description=(
+ "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."
+ ),
+ request=None,
+ responses={200: DiagnosticReportSerializer},
+ )
+ @action(methods=["POST"], detail=True)
+ def diagnose(self, request, *args, pk=None, **kwargs):
+ try:
+ record = self.organization.proxy_records.get(id=pk)
+ except ProxyRecord.DoesNotExist:
+ raise NotFound()
+
+ # Per-user, per-record cooldown. Each diagnose makes ~5–10 outbound requests
+ # against the customer's domain (DNS CAA walk, HTTP probes, TLS handshake) plus a
+ # Cloudflare API call. Even gated to admins, repeated calls would amplify
+ # network traffic toward the configured CNAME chain.
+ cooldown_key = f"proxy_records:diagnose:cooldown:{record.id}:{request.user.id}"
+ if not cache.add(cooldown_key, "1", timeout=DIAGNOSE_COOLDOWN_SECONDS):
+ return Response(
+ {"detail": "A diagnostic was just run for this proxy. Please wait a few seconds before trying again."},
+ status=status.HTTP_429_TOO_MANY_REQUESTS,
+ )
+
+ report = diagnose_proxy_record(record)
+ serializer = DiagnosticReportSerializer(report)
+ return Response(serializer.data)
+
@extend_schema(
description="Retry provisioning a failed reverse proxy. "
"Only available for proxies in 'erroring' or 'timed_out' status. "
diff --git a/posthog/api/proxy_record_diagnostics.py b/posthog/api/proxy_record_diagnostics.py
new file mode 100644
index 000000000000..95bd2421ff42
--- /dev/null
+++ b/posthog/api/proxy_record_diagnostics.py
@@ -0,0 +1,609 @@
+"""
+Reverse proxy diagnostics.
+
+Runs a sequence of synchronous checks against a ProxyRecord and returns a structured
+DiagnosticReport. Called from the in-app /diagnose API endpoint when a user clicks
+"Diagnose" on a proxy that's stuck or erroring.
+
+Intentionally not called from the daily monitor workflow — that one stays cheap and
+keeps using its own errors[]/warnings[] aggregation. Diagnostics are deeper and
+on-demand only.
+"""
+
+import ssl as ssl_module
+import json
+import socket
+import datetime as dt
+from dataclasses import dataclass, field
+from typing import Final, Literal, Optional
+
+import dns.name
+import requests
+import structlog
+import dns.resolver
+import dns.exception
+
+from posthog.exceptions_capture import capture_exception
+from posthog.models import ProxyRecord
+from posthog.temporal.proxy_service.cloudflare import (
+ CloudflareAPIError,
+ CustomHostnameInfo,
+ CustomHostnameSSLStatus,
+ get_custom_hostname_by_domain,
+)
+
+# --- Customer-facing message helpers ---
+# All user-visible strings live here so copy can be reviewed in one place. Functions
+# return PostHog-flavored sentences without leaking vendor terminology (no mentions of
+# Cloudflare, pki.goog, pending_validation, etc.) into the customer surface.
+
+# Cloudflare's `ssl.certificate_authority` field → CAA-record issuer string.
+# Used by the CAA tree-walk check to determine which issuer must be authorized.
+CA_TO_CAA_ISSUER: Final[dict[str, str]] = {
+ "google": "pki.goog",
+ "lets_encrypt": "letsencrypt.org",
+ "ssl_com": "ssl.com",
+ "digicert": "digicert.com",
+}
+
+# Issuers we want a customer to whitelist when they need to fix CAA records. Listing
+# all three keeps them covered if Cloudflare rotates which CA actually issues their cert.
+DEFAULT_ALLOWED_CAA_ISSUERS: Final[tuple[str, ...]] = (
+ "pki.goog",
+ "letsencrypt.org",
+ "ssl.com",
+)
+
+
+def _msg_caa_blocking(domain: str, restricting_zone: str, allowed: list[str], required_issuer: str) -> str:
+ allowed_str = ", ".join(f"`{i}`" for i in allowed) if allowed else "no issuers"
+ return (
+ f"Your DNS provider's CAA records on `{restricting_zone}` allow only {allowed_str}, "
+ f"which prevents our certificate authority from issuing a certificate for `{domain}`. "
+ f"Add a CAA record authorizing `{required_issuer}` to your DNS to unblock issuance."
+ )
+
+
+def _msg_cname_missing(domain: str) -> str:
+ return f"`{domain}` doesn't have a CNAME DNS record yet. Add the record below at your DNS provider."
+
+
+def _msg_cname_mismatch(domain: str, actual: str) -> str:
+ return (
+ f"`{domain}` is pointing to `{actual}` instead of the expected target. "
+ "Update the CNAME record below at your DNS provider."
+ )
+
+
+def _msg_http_challenge_unreachable(domain: str) -> str:
+ return (
+ f"We can't reach the verification challenge URL on `{domain}`. "
+ "Confirm your domain is publicly accessible on port 80 with no redirects to HTTPS, "
+ "no firewall blocking, and no other CDN in front."
+ )
+
+
+def _msg_http_challenge_wrong_body(domain: str) -> str:
+ return (
+ f"The verification challenge URL on `{domain}` returned the wrong content. "
+ "This usually means another CDN or proxy is intercepting traffic before it reaches us. "
+ "Check whether you have a different reverse proxy configured for this domain."
+ )
+
+
+def _msg_cloudflare_hostname_missing(domain: str) -> str:
+ return f"We don't have a record of this proxy on our side for `{domain}`. Hit Retry to recreate it."
+
+
+def _msg_pending_issuance(domain: str) -> str:
+ return (
+ f"Verification succeeded for `{domain}` but the certificate hasn't been issued yet. "
+ "Wait up to an hour. Hit Retry if it stays this way."
+ )
+
+
+def _msg_cert_expiring_soon(domain: str, days_remaining: int) -> str:
+ return (
+ f"The TLS certificate for `{domain}` expires in {days_remaining} days and isn't being renewed. "
+ "Hit Retry to start a fresh issuance."
+ )
+
+
+LOGGER = structlog.get_logger(__name__)
+
+CheckStatus = Literal["passed", "warned", "failed", "skipped"]
+SummaryStatus = Literal["healthy", "warn", "fail"]
+RemediationType = Literal["dns", "config", "wait", "retry"]
+
+# Per-check timeout. Total budget for diagnose() is ~5s; six checks share it,
+# but most return quickly when there's no network call.
+CHECK_TIMEOUT_S = 3.0
+DNS_QUERY_TIMEOUT_S = 1.0
+CERT_EXPIRY_WARN_DAYS = 14
+
+
+@dataclass
+class DnsRecord:
+ name: str
+ type: str
+ value: str
+
+
+@dataclass
+class Remediation:
+ type: RemediationType
+ summary: str
+ records: list[DnsRecord] = field(default_factory=list)
+
+
+@dataclass
+class CheckResult:
+ id: str
+ name: str
+ status: CheckStatus
+ detail: str
+ remediation: Optional[Remediation] = None
+
+
+@dataclass
+class ReportSummary:
+ status: SummaryStatus
+ primary_issue: Optional[str]
+ next_action: Optional[str]
+
+
+@dataclass
+class DiagnosticReport:
+ ran_at: dt.datetime
+ summary: ReportSummary
+ checks: list[CheckResult]
+
+
+def diagnose(record: ProxyRecord) -> DiagnosticReport:
+ """Run the full diagnostic pipeline against a proxy record."""
+ log = LOGGER.bind(
+ proxy_record_id=str(record.id),
+ organization_id=str(record.organization_id),
+ domain=record.domain,
+ )
+ log.info("Starting proxy diagnostics")
+
+ checks: list[CheckResult] = []
+
+ cname_check = _check_cname(record)
+ checks.append(cname_check)
+
+ cloudflare_check, hostname_info = _check_cloudflare(record)
+ checks.append(cloudflare_check)
+
+ ssl_active = hostname_info is not None and hostname_info.ssl.status == CustomHostnameSSLStatus.ACTIVE
+
+ if ssl_active:
+ checks.append(_skip("caa", "CAA records", "Skipped — certificate is already active."))
+ else:
+ checks.append(_check_caa(record, hostname_info))
+
+ if ssl_active:
+ checks.append(_skip("http_challenge", "HTTP-01 challenge", "Skipped — certificate is already active."))
+ elif hostname_info is None or not hostname_info.ssl.http_url:
+ checks.append(_skip("http_challenge", "HTTP-01 challenge", "Skipped — no challenge URL available."))
+ else:
+ checks.append(_check_http_challenge(record, hostname_info))
+
+ if not ssl_active:
+ checks.append(_skip("live_event", "Live event probe", "Skipped — certificate is not active yet."))
+ checks.append(_skip("cert_expiry", "Certificate expiry", "Skipped — certificate is not active yet."))
+ else:
+ live_check = _check_live_event(record)
+ checks.append(live_check)
+ if live_check.status == "passed":
+ checks.append(_check_cert_expiry(record))
+ else:
+ checks.append(_skip("cert_expiry", "Certificate expiry", "Skipped — live event probe failed."))
+
+ summary = _build_summary(checks)
+ log.info("Diagnostics complete", primary_issue=summary.primary_issue, status=summary.status)
+ return DiagnosticReport(ran_at=dt.datetime.now(dt.UTC), summary=summary, checks=checks)
+
+
+def _skip(check_id: str, name: str, detail: str) -> CheckResult:
+ return CheckResult(id=check_id, name=name, status="skipped", detail=detail)
+
+
+def _build_summary(checks: list[CheckResult]) -> ReportSummary:
+ by_id = {c.id: c for c in checks}
+ live_event = by_id.get("live_event")
+
+ if live_event is not None and live_event.status == "passed":
+ cert = by_id.get("cert_expiry")
+ if cert is not None and cert.status == "failed":
+ return ReportSummary(status="warn", primary_issue="cert_expiry", next_action=cert.detail)
+ return ReportSummary(status="healthy", primary_issue=None, next_action=None)
+
+ # Walk in priority order: things the customer can act on first, then fallthrough.
+ priority = ("cname", "caa", "http_challenge", "cloudflare", "live_event", "cert_expiry")
+ for check_id in priority:
+ c = by_id.get(check_id)
+ if c is None or c.status not in ("failed", "warned"):
+ continue
+ next_action = c.remediation.summary if c.remediation else c.detail
+ return ReportSummary(
+ status="fail" if c.status == "failed" else "warn",
+ primary_issue=check_id,
+ next_action=next_action,
+ )
+
+ return ReportSummary(status="healthy", primary_issue=None, next_action=None)
+
+
+def _check_cname(record: ProxyRecord) -> CheckResult:
+ try:
+ resolver = dns.resolver.Resolver()
+ resolver.lifetime = DNS_QUERY_TIMEOUT_S
+ cnames = resolver.resolve(record.domain, "CNAME")
+ actual = cnames[0].target.to_text(omit_final_dot=False)
+ if actual.lower() == record.target_cname.lower():
+ return CheckResult(
+ id="cname",
+ name="DNS CNAME",
+ status="passed",
+ detail=f"`{record.domain}` is correctly configured.",
+ )
+ return CheckResult(
+ id="cname",
+ name="DNS CNAME",
+ status="failed",
+ detail=_msg_cname_mismatch(record.domain, actual),
+ remediation=Remediation(
+ type="dns",
+ summary=f"Update the CNAME record for `{record.domain}` to the value below.",
+ records=[DnsRecord(name=record.domain, type="CNAME", value=record.target_cname)],
+ ),
+ )
+ except (dns.resolver.NXDOMAIN, dns.resolver.NoAnswer):
+ return CheckResult(
+ id="cname",
+ name="DNS CNAME",
+ status="failed",
+ detail=_msg_cname_missing(record.domain),
+ remediation=Remediation(
+ type="dns",
+ summary=f"Add the CNAME record below for `{record.domain}`.",
+ records=[DnsRecord(name=record.domain, type="CNAME", value=record.target_cname)],
+ ),
+ )
+ except dns.exception.DNSException as e:
+ return CheckResult(
+ id="cname",
+ name="DNS CNAME",
+ status="warned",
+ detail=f"Couldn't resolve DNS for `{record.domain}` ({e.__class__.__name__}).",
+ )
+
+
+def _check_cloudflare(record: ProxyRecord) -> tuple[CheckResult, Optional[CustomHostnameInfo]]:
+ try:
+ info = get_custom_hostname_by_domain(record.domain)
+ except CloudflareAPIError as e:
+ capture_exception(e, {"proxy_record_id": str(record.id), "domain": record.domain})
+ return (
+ CheckResult(
+ id="cloudflare",
+ name="Cloudflare custom hostname",
+ status="failed",
+ detail=f"Couldn't reach our certificate provider: {e}.",
+ ),
+ None,
+ )
+
+ if info is None:
+ return (
+ CheckResult(
+ id="cloudflare",
+ name="Cloudflare custom hostname",
+ status="failed",
+ detail=_msg_cloudflare_hostname_missing(record.domain),
+ remediation=Remediation(type="retry", summary="Hit Retry to recreate the proxy."),
+ ),
+ None,
+ )
+
+ ssl_status = info.ssl.status
+ if ssl_status == CustomHostnameSSLStatus.ACTIVE:
+ return (
+ CheckResult(
+ id="cloudflare",
+ name="Cloudflare custom hostname",
+ status="passed",
+ detail=f"Certificate is active for `{record.domain}`.",
+ ),
+ info,
+ )
+
+ if ssl_status in (CustomHostnameSSLStatus.PENDING_VALIDATION, CustomHostnameSSLStatus.INITIALIZING):
+ return (
+ CheckResult(
+ id="cloudflare",
+ name="Cloudflare custom hostname",
+ status="warned",
+ detail=(
+ f"Certificate verification is pending for `{record.domain}`. "
+ "If this persists, the CAA records or HTTP challenge checks below explain why."
+ ),
+ ),
+ info,
+ )
+
+ if ssl_status == CustomHostnameSSLStatus.PENDING_ISSUANCE:
+ return (
+ CheckResult(
+ id="cloudflare",
+ name="Cloudflare custom hostname",
+ status="warned",
+ detail=_msg_pending_issuance(record.domain),
+ remediation=Remediation(type="wait", summary="Wait up to an hour. Hit Retry if it stays this way."),
+ ),
+ info,
+ )
+
+ if ssl_status == CustomHostnameSSLStatus.PENDING_DEPLOYMENT:
+ return (
+ CheckResult(
+ id="cloudflare",
+ name="Cloudflare custom hostname",
+ status="warned",
+ detail=f"Certificate issued for `{record.domain}` but not yet deployed to our edge.",
+ remediation=Remediation(type="wait", summary="Wait a few minutes for deployment."),
+ ),
+ info,
+ )
+
+ return (
+ CheckResult(
+ id="cloudflare",
+ name="Cloudflare custom hostname",
+ status="failed",
+ detail=f"Unexpected certificate status: {ssl_status.value}.",
+ remediation=Remediation(type="retry", summary="Hit Retry to start a fresh provisioning attempt."),
+ ),
+ info,
+ )
+
+
+def _check_caa(record: ProxyRecord, hostname_info: Optional[CustomHostnameInfo]) -> CheckResult:
+ """
+ Walk up the DNS tree from `record.domain` to apex, looking for the first non-empty
+ set of CAA records. Per RFC 8659, the first non-empty CAA result wins — climbing
+ stops there. If those records don't authorize the CA Cloudflare uses, surface a
+ remediation block listing CAA records the customer should add.
+ """
+ if hostname_info is not None and hostname_info.ssl.certificate_authority:
+ ca_field = hostname_info.ssl.certificate_authority
+ required_issuer = CA_TO_CAA_ISSUER.get(ca_field, "pki.goog")
+ else:
+ required_issuer = "pki.goog"
+
+ name = dns.name.from_text(record.domain)
+ resolver = dns.resolver.Resolver()
+ resolver.lifetime = DNS_QUERY_TIMEOUT_S
+
+ while name != dns.name.root:
+ try:
+ answer = resolver.resolve(name, "CAA")
+ except dns.resolver.NoAnswer:
+ name = name.parent()
+ continue
+ except (dns.resolver.NXDOMAIN, dns.exception.DNSException):
+ name = name.parent()
+ continue
+
+ allowed = _extract_caa_issuers(answer)
+ zone = name.to_text(omit_final_dot=True)
+ if any(i.lower() == required_issuer.lower() for i in allowed):
+ return CheckResult(
+ id="caa",
+ name="CAA records",
+ status="passed",
+ detail=f"CAA records on `{zone}` authorize `{required_issuer}`.",
+ )
+ return CheckResult(
+ id="caa",
+ name="CAA records",
+ status="failed",
+ detail=_msg_caa_blocking(record.domain, zone, allowed, required_issuer),
+ remediation=Remediation(
+ type="dns",
+ summary=f"Add a CAA record on `{zone}` authorizing `{required_issuer}`.",
+ records=[DnsRecord(name=zone, type="CAA", value=f'0 issue "{i}"') for i in DEFAULT_ALLOWED_CAA_ISSUERS],
+ ),
+ )
+
+ return CheckResult(
+ id="caa",
+ name="CAA records",
+ status="passed",
+ detail="No CAA records found in the DNS chain — issuance is unrestricted.",
+ )
+
+
+def _extract_caa_issuers(answer: dns.resolver.Answer) -> list[str]:
+ """Extract issuer hostnames from CAA `issue`/`issuewild` records, dropping any parameters."""
+ issuers: list[str] = []
+ for rdata in answer:
+ tag = getattr(rdata, "tag", b"")
+ if isinstance(tag, str):
+ tag = tag.encode()
+ value = getattr(rdata, "value", b"")
+ if isinstance(value, bytes):
+ value = value.decode("utf-8", errors="replace")
+ if tag.lower() in (b"issue", b"issuewild"):
+ issuer = value.split(";")[0].strip()
+ if issuer:
+ issuers.append(issuer)
+ return issuers
+
+
+def _check_http_challenge(record: ProxyRecord, hostname_info: CustomHostnameInfo) -> CheckResult:
+ challenge_url = hostname_info.ssl.http_url
+ expected_body = hostname_info.ssl.http_body
+ if not challenge_url or not expected_body:
+ return _skip("http_challenge", "HTTP-01 challenge", "No challenge URL available.")
+
+ try:
+ response = requests.get(challenge_url, timeout=CHECK_TIMEOUT_S, allow_redirects=False)
+ except requests.exceptions.RequestException as e:
+ return CheckResult(
+ id="http_challenge",
+ name="HTTP-01 challenge",
+ status="failed",
+ detail=_msg_http_challenge_unreachable(record.domain) + f" ({e.__class__.__name__})",
+ remediation=Remediation(
+ type="config",
+ summary=f"Confirm `{record.domain}` accepts HTTP requests on port 80 with no redirects.",
+ ),
+ )
+
+ if response.status_code != 200:
+ return CheckResult(
+ id="http_challenge",
+ name="HTTP-01 challenge",
+ status="failed",
+ detail=_msg_http_challenge_unreachable(record.domain) + f" (Got HTTP {response.status_code}.)",
+ )
+
+ if response.text.strip() != expected_body.strip():
+ return CheckResult(
+ id="http_challenge",
+ name="HTTP-01 challenge",
+ status="failed",
+ detail=_msg_http_challenge_wrong_body(record.domain),
+ )
+
+ return CheckResult(
+ id="http_challenge",
+ name="HTTP-01 challenge",
+ status="passed",
+ detail="Challenge URL responded with the expected verification token.",
+ )
+
+
+def _check_live_event(record: ProxyRecord) -> CheckResult:
+ try:
+ # Same dummy payload the daily monitor uses (posthog/temporal/proxy_service/monitor.py
+ # check_proxy_is_live). PostHog's capture endpoint accepts unknown api_keys and returns
+ # 2xx — team_id resolution happens later in the ingestion pipeline — so a working proxy
+ # forwards this to a 2xx response. allow_redirects=False is a security boundary: an org
+ # admin controlling the customer's domain could otherwise redirect us to internal
+ # targets (cloud metadata, management APIs). Same protection as _check_http_challenge.
+ response = requests.post(
+ f"https://{record.domain}/i/v0/e/",
+ headers={"Content-Type": "application/json"},
+ data=json.dumps({"event": "test", "api_key": "test", "distinct_id": "test"}),
+ timeout=CHECK_TIMEOUT_S,
+ allow_redirects=False,
+ )
+ except requests.exceptions.SSLError:
+ return CheckResult(
+ id="live_event",
+ name="Live event probe",
+ status="failed",
+ detail=f"TLS connection to `{record.domain}` failed.",
+ )
+ except requests.exceptions.ConnectionError as e:
+ return CheckResult(
+ id="live_event",
+ name="Live event probe",
+ status="failed",
+ detail=f"Couldn't connect to `{record.domain}` ({e.__class__.__name__}).",
+ )
+ except requests.exceptions.RequestException as e:
+ return CheckResult(
+ id="live_event",
+ name="Live event probe",
+ status="warned",
+ detail=f"Live probe failed unexpectedly ({e.__class__.__name__}).",
+ )
+
+ if response.status_code >= 500:
+ return CheckResult(
+ id="live_event",
+ name="Live event probe",
+ status="failed",
+ detail=f"Live probe got HTTP {response.status_code} — proxy is up but failing.",
+ )
+ if response.status_code >= 400:
+ return CheckResult(
+ id="live_event",
+ name="Live event probe",
+ status="warned",
+ detail=f"Live probe got HTTP {response.status_code} — unexpected for a test event.",
+ )
+
+ return CheckResult(
+ id="live_event",
+ name="Live event probe",
+ status="passed",
+ detail=f"Sent a test event to `{record.domain}` successfully.",
+ )
+
+
+def _check_cert_expiry(record: ProxyRecord) -> CheckResult:
+ try:
+ ctx = ssl_module.create_default_context()
+ ctx.minimum_version = ssl_module.TLSVersion.TLSv1_2
+ # Outer `with` on the raw socket guarantees the file descriptor closes
+ # even if wrap_socket() raises before the inner context manager takes
+ # ownership; closing twice is safe.
+ with socket.create_connection((record.domain, 443), timeout=CHECK_TIMEOUT_S) as sock:
+ with ctx.wrap_socket(sock, server_hostname=record.domain) as wrapped:
+ cert = wrapped.getpeercert()
+ except (TimeoutError, OSError, ssl_module.SSLError) as e:
+ return CheckResult(
+ id="cert_expiry",
+ name="Certificate expiry",
+ status="warned",
+ detail=f"Couldn't fetch the certificate to inspect expiry ({e.__class__.__name__}).",
+ )
+
+ if not cert or "notAfter" not in cert:
+ return CheckResult(
+ id="cert_expiry",
+ name="Certificate expiry",
+ status="warned",
+ detail="Certificate fetched but expiry could not be determined.",
+ )
+
+ not_after = cert["notAfter"]
+ if not isinstance(not_after, str):
+ return CheckResult(
+ id="cert_expiry",
+ name="Certificate expiry",
+ status="warned",
+ detail="Certificate fetched but expiry has an unexpected type.",
+ )
+ try:
+ expires_at = dt.datetime.strptime(not_after, "%b %d %H:%M:%S %Y %Z").replace(tzinfo=dt.UTC)
+ except ValueError:
+ return CheckResult(
+ id="cert_expiry",
+ name="Certificate expiry",
+ status="warned",
+ detail="Certificate fetched but expiry could not be parsed.",
+ )
+ days_remaining = (expires_at - dt.datetime.now(dt.UTC)).days
+
+ if days_remaining < CERT_EXPIRY_WARN_DAYS:
+ return CheckResult(
+ id="cert_expiry",
+ name="Certificate expiry",
+ status="failed",
+ detail=_msg_cert_expiring_soon(record.domain, days_remaining),
+ remediation=Remediation(type="retry", summary="Hit Retry to start a fresh issuance."),
+ )
+
+ return CheckResult(
+ id="cert_expiry",
+ name="Certificate expiry",
+ status="passed",
+ detail=f"Certificate is valid for {days_remaining} more days.",
+ )
diff --git a/posthog/api/test/test_proxy_record.py b/posthog/api/test/test_proxy_record.py
index be17ba7fba0e..6edbeb291eb0 100644
--- a/posthog/api/test/test_proxy_record.py
+++ b/posthog/api/test/test_proxy_record.py
@@ -376,3 +376,129 @@ class TestProxyRecordAPI(APIBaseTest):
f"/api/organizations/{self.organization.id}/proxy_records/{record.id}/",
)
assert response.status_code == status.HTTP_403_FORBIDDEN
+
+ @patch("posthog.api.proxy_record.diagnose_proxy_record")
+ def test_diagnose_returns_report(self, mock_diagnose):
+ import datetime as dt
+
+ from posthog.api.proxy_record_diagnostics import (
+ CheckResult,
+ DiagnosticReport,
+ DnsRecord,
+ Remediation,
+ ReportSummary,
+ )
+
+ record = ProxyRecord.objects.create(
+ organization=self.organization,
+ created_by=self.user,
+ domain="diagnose.example.com",
+ target_cname="abc123.proxy.posthog.com",
+ status=ProxyRecord.Status.ERRORING,
+ )
+ mock_diagnose.return_value = DiagnosticReport(
+ ran_at=dt.datetime(2026, 5, 2, 12, 0, 0, tzinfo=dt.UTC),
+ summary=ReportSummary(status="fail", primary_issue="caa", next_action="Authorize pki.goog in CAA."),
+ checks=[
+ CheckResult(id="cname", name="DNS CNAME", status="passed", detail="ok"),
+ CheckResult(
+ id="caa",
+ name="CAA records",
+ status="failed",
+ detail="CAA blocks pki.goog.",
+ remediation=Remediation(
+ type="dns",
+ summary="Add a CAA record authorizing pki.goog.",
+ records=[DnsRecord(name="example.com", type="CAA", value='0 issue "pki.goog"')],
+ ),
+ ),
+ ],
+ )
+
+ response = self.client.post(
+ f"/api/organizations/{self.organization.id}/proxy_records/{record.id}/diagnose/",
+ )
+
+ assert response.status_code == status.HTTP_200_OK, response.content
+ data = response.json()
+ assert data["summary"]["status"] == "fail"
+ assert data["summary"]["primary_issue"] == "caa"
+ assert "pki.goog" in data["summary"]["next_action"]
+ assert len(data["checks"]) == 2
+ caa_check = next(c for c in data["checks"] if c["id"] == "caa")
+ assert caa_check["status"] == "failed"
+ assert caa_check["remediation"]["type"] == "dns"
+ assert caa_check["remediation"]["records"][0]["type"] == "CAA"
+ mock_diagnose.assert_called_once()
+ # confirms the diagnose function was invoked with our specific record
+ called_with = mock_diagnose.call_args[0][0]
+ assert called_with.id == record.id
+
+ def test_diagnose_returns_404_for_unknown_id(self):
+ response = self.client.post(
+ f"/api/organizations/{self.organization.id}/proxy_records/00000000-0000-0000-0000-000000000000/diagnose/",
+ )
+ assert response.status_code == status.HTTP_404_NOT_FOUND
+
+ def test_diagnose_returns_404_for_other_org_record(self):
+ other_org = Organization.objects.create(name="Other Org Diagnose")
+ record = ProxyRecord.objects.create(
+ organization=other_org,
+ created_by=self.user,
+ domain="other-diagnose.example.com",
+ target_cname="abc123.proxy.posthog.com",
+ status=ProxyRecord.Status.VALID,
+ )
+ response = self.client.post(
+ f"/api/organizations/{self.organization.id}/proxy_records/{record.id}/diagnose/",
+ )
+ assert response.status_code == status.HTTP_404_NOT_FOUND
+
+ def test_non_admin_cannot_diagnose_proxy_record(self):
+ self.organization_membership.level = OrganizationMembership.Level.MEMBER
+ self.organization_membership.save()
+
+ record = ProxyRecord.objects.create(
+ organization=self.organization,
+ created_by=self.user,
+ domain="noadmindiagnose.example.com",
+ target_cname="abc123.proxy.posthog.com",
+ status=ProxyRecord.Status.ERRORING,
+ )
+
+ response = self.client.post(
+ f"/api/organizations/{self.organization.id}/proxy_records/{record.id}/diagnose/",
+ )
+ assert response.status_code == status.HTTP_403_FORBIDDEN
+
+ @patch("posthog.api.proxy_record.diagnose_proxy_record")
+ def test_diagnose_rate_limits_repeated_calls_per_record(self, mock_diagnose):
+ import datetime as dt
+
+ from django.core.cache import cache
+
+ from posthog.api.proxy_record_diagnostics import DiagnosticReport, ReportSummary
+
+ cache.clear()
+ mock_diagnose.return_value = DiagnosticReport(
+ ran_at=dt.datetime(2026, 5, 5, 12, 0, 0, tzinfo=dt.UTC),
+ summary=ReportSummary(status="healthy", primary_issue=None, next_action=None),
+ checks=[],
+ )
+ record = ProxyRecord.objects.create(
+ organization=self.organization,
+ created_by=self.user,
+ domain="ratelimit.example.com",
+ target_cname="abc123.proxy.posthog.com",
+ status=ProxyRecord.Status.VALID,
+ )
+
+ first = self.client.post(f"/api/organizations/{self.organization.id}/proxy_records/{record.id}/diagnose/")
+ assert first.status_code == status.HTTP_200_OK
+
+ second = self.client.post(f"/api/organizations/{self.organization.id}/proxy_records/{record.id}/diagnose/")
+ assert second.status_code == status.HTTP_429_TOO_MANY_REQUESTS
+ assert "wait" in second.json()["detail"].lower()
+
+ # Sanity: diagnose function only called once despite two requests.
+ assert mock_diagnose.call_count == 1
diff --git a/posthog/api/test/test_proxy_record_diagnostics.py b/posthog/api/test/test_proxy_record_diagnostics.py
new file mode 100644
index 000000000000..500e93953d4e
--- /dev/null
+++ b/posthog/api/test/test_proxy_record_diagnostics.py
@@ -0,0 +1,272 @@
+from unittest.mock import MagicMock, patch
+
+from django.test import TestCase
+
+import requests
+import dns.resolver
+from parameterized import parameterized
+
+from posthog.api import proxy_record_diagnostics as diagnostics
+from posthog.temporal.proxy_service.cloudflare import (
+ CloudflareAPIError,
+ CustomHostnameInfo,
+ CustomHostnameSSL,
+ CustomHostnameSSLStatus,
+ CustomHostnameStatus,
+)
+
+
+def _record(domain: str = "e.example.com", target: str = "abc.cf-prod-eu-proxy.europehog.com."):
+ """Build a minimal ProxyRecord-like stub. Avoids hitting the DB.
+
+ `target` includes the trailing FQDN dot to match the production data shape:
+ `generate_target_cname` produces `{digest}.{CLOUDFLARE_PROXY_BASE_CNAME}` where the
+ env var ends with a dot.
+ """
+ rec = MagicMock()
+ rec.id = "00000000-0000-0000-0000-000000000001"
+ rec.organization_id = "00000000-0000-0000-0000-000000000002"
+ rec.domain = domain
+ rec.target_cname = target
+ return rec
+
+
+def _hostname_info(
+ ssl_status: CustomHostnameSSLStatus = CustomHostnameSSLStatus.PENDING_VALIDATION,
+ http_url: str | None = "http://e.example.com/.well-known/acme-challenge/tok",
+ http_body: str | None = "tok.body",
+ certificate_authority: str | None = "google",
+) -> CustomHostnameInfo:
+ return CustomHostnameInfo(
+ id="hostname-id",
+ hostname="e.example.com",
+ status=CustomHostnameStatus.ACTIVE,
+ ssl=CustomHostnameSSL(
+ status=ssl_status,
+ validation_errors=[],
+ http_url=http_url,
+ http_body=http_body,
+ certificate_authority=certificate_authority,
+ validation_records=[],
+ ),
+ )
+
+
+def _caa_rdata(tag: bytes, issuer: str):
+ """Mimic a dnspython CAA rdata object."""
+ rd = MagicMock()
+ rd.tag = tag
+ rd.value = issuer.encode()
+ return rd
+
+
+class TestCheckCname(TestCase):
+ @patch("posthog.api.proxy_record_diagnostics.dns.resolver.Resolver")
+ def test_pass_when_cname_matches(self, ResolverMock):
+ cname = MagicMock()
+ cname.target.to_text.return_value = "abc.cf-prod-eu-proxy.europehog.com."
+ ResolverMock.return_value.resolve.return_value = [cname]
+
+ result = diagnostics._check_cname(_record())
+
+ self.assertEqual(result.status, "passed")
+ self.assertIsNone(result.remediation)
+
+ @patch("posthog.api.proxy_record_diagnostics.dns.resolver.Resolver")
+ def test_fail_when_cname_mismatches(self, ResolverMock):
+ cname = MagicMock()
+ cname.target.to_text.return_value = "wrong.example.net."
+ ResolverMock.return_value.resolve.return_value = [cname]
+
+ result = diagnostics._check_cname(_record())
+
+ self.assertEqual(result.status, "failed")
+ self.assertIn("wrong.example.net", result.detail)
+ assert result.remediation is not None
+ self.assertEqual(result.remediation.records[0].type, "CNAME")
+
+ @patch("posthog.api.proxy_record_diagnostics.dns.resolver.Resolver")
+ def test_fail_when_cname_missing_nxdomain(self, ResolverMock):
+ ResolverMock.return_value.resolve.side_effect = dns.resolver.NXDOMAIN()
+
+ result = diagnostics._check_cname(_record())
+
+ self.assertEqual(result.status, "failed")
+ self.assertIn("doesn't have a CNAME", result.detail)
+
+
+class TestCheckCloudflare(TestCase):
+ @patch("posthog.api.proxy_record_diagnostics.get_custom_hostname_by_domain")
+ def test_pass_when_ssl_active(self, get_mock):
+ get_mock.return_value = _hostname_info(ssl_status=CustomHostnameSSLStatus.ACTIVE)
+ result, info = diagnostics._check_cloudflare(_record())
+ self.assertEqual(result.status, "passed")
+ self.assertIsNotNone(info)
+
+ @patch("posthog.api.proxy_record_diagnostics.get_custom_hostname_by_domain")
+ def test_warn_when_pending_validation(self, get_mock):
+ get_mock.return_value = _hostname_info(ssl_status=CustomHostnameSSLStatus.PENDING_VALIDATION)
+ result, info = diagnostics._check_cloudflare(_record())
+ self.assertEqual(result.status, "warned")
+ self.assertIn("verification is pending", result.detail.lower())
+
+ @patch("posthog.api.proxy_record_diagnostics.get_custom_hostname_by_domain")
+ def test_fail_when_hostname_missing(self, get_mock):
+ get_mock.return_value = None
+ result, info = diagnostics._check_cloudflare(_record())
+ self.assertEqual(result.status, "failed")
+ assert result.remediation is not None
+ self.assertEqual(result.remediation.type, "retry")
+ self.assertIsNone(info)
+
+ @patch("posthog.api.proxy_record_diagnostics.get_custom_hostname_by_domain")
+ def test_fail_when_api_errors(self, get_mock):
+ get_mock.side_effect = CloudflareAPIError("boom")
+ with patch("posthog.api.proxy_record_diagnostics.capture_exception"):
+ result, info = diagnostics._check_cloudflare(_record())
+ self.assertEqual(result.status, "failed")
+ self.assertIn("certificate provider", result.detail.lower())
+
+
+class TestCheckCaa(TestCase):
+ @patch("posthog.api.proxy_record_diagnostics.dns.resolver.Resolver")
+ def test_pass_when_no_caa_records(self, ResolverMock):
+ ResolverMock.return_value.resolve.side_effect = dns.resolver.NoAnswer()
+ result = diagnostics._check_caa(_record(), _hostname_info())
+ self.assertEqual(result.status, "passed")
+ self.assertIn("unrestricted", result.detail.lower())
+
+ @patch("posthog.api.proxy_record_diagnostics.dns.resolver.Resolver")
+ def test_pass_when_caa_authorizes_required_issuer(self, ResolverMock):
+ ResolverMock.return_value.resolve.return_value = [_caa_rdata(b"issue", "pki.goog")]
+ result = diagnostics._check_caa(_record(), _hostname_info(certificate_authority="google"))
+ self.assertEqual(result.status, "passed")
+ self.assertIn("pki.goog", result.detail)
+
+ @patch("posthog.api.proxy_record_diagnostics.dns.resolver.Resolver")
+ def test_fail_when_caa_blocks_required_issuer(self, ResolverMock):
+ ResolverMock.return_value.resolve.return_value = [_caa_rdata(b"issue", "digicert.com")]
+ result = diagnostics._check_caa(_record(), _hostname_info(certificate_authority="google"))
+ self.assertEqual(result.status, "failed")
+ self.assertIn("digicert.com", result.detail)
+ self.assertIn("pki.goog", result.detail)
+ assert result.remediation is not None
+ self.assertEqual(result.remediation.type, "dns")
+ self.assertGreater(len(result.remediation.records), 0)
+
+
+class TestCheckHttpChallenge(TestCase):
+ @patch("posthog.api.proxy_record_diagnostics.requests.get")
+ def test_pass_when_body_matches(self, get_mock):
+ get_mock.return_value = MagicMock(status_code=200, text="tok.body")
+ result = diagnostics._check_http_challenge(_record(), _hostname_info())
+ self.assertEqual(result.status, "passed")
+
+ @patch("posthog.api.proxy_record_diagnostics.requests.get")
+ def test_fail_when_body_mismatch(self, get_mock):
+ get_mock.return_value = MagicMock(status_code=200, text="other content")
+ result = diagnostics._check_http_challenge(_record(), _hostname_info())
+ self.assertEqual(result.status, "failed")
+ self.assertIn("wrong content", result.detail.lower())
+
+ @patch("posthog.api.proxy_record_diagnostics.requests.get")
+ def test_fail_when_unreachable(self, get_mock):
+ get_mock.side_effect = requests.exceptions.ConnectionError("refused")
+ result = diagnostics._check_http_challenge(_record(), _hostname_info())
+ self.assertEqual(result.status, "failed")
+ assert result.remediation is not None
+ self.assertEqual(result.remediation.type, "config")
+
+ @patch("posthog.api.proxy_record_diagnostics.requests.get")
+ def test_fail_when_non_200(self, get_mock):
+ get_mock.return_value = MagicMock(status_code=404, text="")
+ result = diagnostics._check_http_challenge(_record(), _hostname_info())
+ self.assertEqual(result.status, "failed")
+ self.assertIn("404", result.detail)
+
+
+class TestCheckLiveEvent(TestCase):
+ @parameterized.expand(
+ [
+ ("ssl_error", requests.exceptions.SSLError("bad cert"), "failed", "tls"),
+ ("conn_error", requests.exceptions.ConnectionError("refused"), "failed", "connect"),
+ ]
+ )
+ @patch("posthog.api.proxy_record_diagnostics.requests.post")
+ def test_request_exceptions(self, _name, exc, expected_status, expected_substr, post_mock):
+ post_mock.side_effect = exc
+ result = diagnostics._check_live_event(_record())
+ self.assertEqual(result.status, expected_status)
+ self.assertIn(expected_substr, result.detail.lower())
+
+ @patch("posthog.api.proxy_record_diagnostics.requests.post")
+ def test_5xx_is_fail(self, post_mock):
+ post_mock.return_value = MagicMock(status_code=502)
+ result = diagnostics._check_live_event(_record())
+ self.assertEqual(result.status, "failed")
+
+ @patch("posthog.api.proxy_record_diagnostics.requests.post")
+ def test_4xx_is_warn(self, post_mock):
+ post_mock.return_value = MagicMock(status_code=403)
+ result = diagnostics._check_live_event(_record())
+ self.assertEqual(result.status, "warned")
+
+ @patch("posthog.api.proxy_record_diagnostics.requests.post")
+ def test_2xx_is_pass(self, post_mock):
+ post_mock.return_value = MagicMock(status_code=200)
+ result = diagnostics._check_live_event(_record())
+ self.assertEqual(result.status, "passed")
+
+
+class TestDiagnoseOrchestrator(TestCase):
+ """End-to-end orchestrator with all external deps mocked."""
+
+ @patch("posthog.api.proxy_record_diagnostics._check_cert_expiry")
+ @patch("posthog.api.proxy_record_diagnostics.requests.post")
+ @patch("posthog.api.proxy_record_diagnostics.get_custom_hostname_by_domain")
+ @patch("posthog.api.proxy_record_diagnostics.dns.resolver.Resolver")
+ def test_healthy_when_ssl_active_and_live_passes(self, ResolverMock, get_mock, post_mock, cert_mock):
+ cname = MagicMock()
+ cname.target.to_text.return_value = "abc.cf-prod-eu-proxy.europehog.com."
+ ResolverMock.return_value.resolve.return_value = [cname]
+ get_mock.return_value = _hostname_info(ssl_status=CustomHostnameSSLStatus.ACTIVE)
+ post_mock.return_value = MagicMock(status_code=200)
+ cert_mock.return_value = diagnostics.CheckResult(
+ id="cert_expiry", name="Certificate expiry", status="passed", detail="ok"
+ )
+
+ report = diagnostics.diagnose(_record())
+
+ self.assertEqual(report.summary.status, "healthy")
+ self.assertIsNone(report.summary.primary_issue)
+ ids = [c.id for c in report.checks]
+ self.assertEqual(ids, ["cname", "cloudflare", "caa", "http_challenge", "live_event", "cert_expiry"])
+
+ @patch("posthog.api.proxy_record_diagnostics.requests.get")
+ @patch("posthog.api.proxy_record_diagnostics.get_custom_hostname_by_domain")
+ @patch("posthog.api.proxy_record_diagnostics.dns.resolver.Resolver")
+ def test_caa_failure_surfaces_as_primary_issue(self, ResolverMock, get_mock, http_get_mock):
+ # CNAME query returns the right target; CAA query returns a blocking record.
+ cname = MagicMock()
+ cname.target.to_text.return_value = "abc.cf-prod-eu-proxy.europehog.com."
+
+ def resolve_side_effect(name, rdtype):
+ if rdtype == "CNAME":
+ return [cname]
+ if rdtype == "CAA":
+ return [_caa_rdata(b"issue", "digicert.com")]
+ raise dns.resolver.NoAnswer()
+
+ ResolverMock.return_value.resolve.side_effect = resolve_side_effect
+ get_mock.return_value = _hostname_info(ssl_status=CustomHostnameSSLStatus.PENDING_VALIDATION)
+ http_get_mock.return_value = MagicMock(status_code=200, text="tok.body")
+
+ report = diagnostics.diagnose(_record())
+
+ self.assertEqual(report.summary.status, "fail")
+ self.assertEqual(report.summary.primary_issue, "caa")
+ # next_action is the fix (authorize pki.goog), not the cause
+ self.assertIn("pki.goog", report.summary.next_action or "")
+ # the underlying cause is in the check's detail
+ caa_check = next(c for c in report.checks if c.id == "caa")
+ self.assertIn("digicert.com", caa_check.detail)
diff --git a/posthog/schema.py b/posthog/schema.py
index 1e8aac0610a2..992dfc45c6f8 100644
--- a/posthog/schema.py
+++ b/posthog/schema.py
@@ -719,6 +719,7 @@ class AssistantTool(StrEnum):
CALL_MCP_SERVER = "call_mcp_server"
SEARCH_LLM_TRACES = "search_llm_traces"
RUN_HOG_EVAL_TEST = "run_hog_eval_test"
+ DIAGNOSE_PROXY = "diagnose_proxy"
class AssistantToolCall(BaseModel):
diff --git a/posthog/temporal/proxy_service/cloudflare.py b/posthog/temporal/proxy_service/cloudflare.py
index eb3c0c83c158..c7050be4dac6 100644
--- a/posthog/temporal/proxy_service/cloudflare.py
+++ b/posthog/temporal/proxy_service/cloudflare.py
@@ -8,7 +8,7 @@ This module provides functions to interact with Cloudflare's API for:
"""
import typing as t
-from dataclasses import dataclass
+from dataclasses import dataclass, field
from enum import Enum
from django.conf import settings
@@ -21,7 +21,7 @@ CLOUDFLARE_API_BASE = "https://api.cloudflare.com/client/v4"
class CloudflareAPIError(Exception):
"""Exception raised when Cloudflare API returns an error."""
- def __init__(self, message: str, errors: t.Optional[list[dict]] = None):
+ def __init__(self, message: str, errors: t.Optional[list[dict]] = None) -> None:
super().__init__(message)
self.errors = errors or []
@@ -57,6 +57,12 @@ class CustomHostnameSSL:
status: CustomHostnameSSLStatus
validation_errors: list[dict]
+ # Optional fields populated by Cloudflare's response and used by diagnostics.
+ # Not all SSL configurations expose these (e.g. ACTIVE certs lack a challenge URL).
+ http_url: t.Optional[str] = None
+ http_body: t.Optional[str] = None
+ certificate_authority: t.Optional[str] = None
+ validation_records: list[dict] = field(default_factory=list)
@dataclass
@@ -79,6 +85,24 @@ def _get_headers() -> dict[str, str]:
}
+def _parse_hostname(result: dict) -> "CustomHostnameInfo":
+ """Build a CustomHostnameInfo from a Cloudflare API custom_hostname result object."""
+ ssl_payload = result.get("ssl", {})
+ return CustomHostnameInfo(
+ id=result["id"],
+ hostname=result["hostname"],
+ status=CustomHostnameStatus(result["status"]),
+ ssl=CustomHostnameSSL(
+ status=CustomHostnameSSLStatus(ssl_payload["status"]),
+ validation_errors=ssl_payload.get("validation_errors", []),
+ http_url=ssl_payload.get("http_url"),
+ http_body=ssl_payload.get("http_body"),
+ certificate_authority=ssl_payload.get("certificate_authority"),
+ validation_records=ssl_payload.get("validation_records", []),
+ ),
+ )
+
+
def _handle_response(response: requests.Response) -> dict:
"""Handle Cloudflare API response and raise errors if needed."""
try:
@@ -127,17 +151,7 @@ def create_custom_hostname(domain: str) -> CustomHostnameInfo:
response = requests.post(url, headers=_get_headers(), json=payload, timeout=30)
data = _handle_response(response)
-
- result = data["result"]
- return CustomHostnameInfo(
- id=result["id"],
- hostname=result["hostname"],
- status=CustomHostnameStatus(result["status"]),
- ssl=CustomHostnameSSL(
- status=CustomHostnameSSLStatus(result["ssl"]["status"]),
- validation_errors=result["ssl"].get("validation_errors", []),
- ),
- )
+ return _parse_hostname(data["result"])
def get_custom_hostname(hostname_id: str) -> t.Optional[CustomHostnameInfo]:
@@ -161,17 +175,7 @@ def get_custom_hostname(hostname_id: str) -> t.Optional[CustomHostnameInfo]:
return None
data = _handle_response(response)
- result = data["result"]
-
- return CustomHostnameInfo(
- id=result["id"],
- hostname=result["hostname"],
- status=CustomHostnameStatus(result["status"]),
- ssl=CustomHostnameSSL(
- status=CustomHostnameSSLStatus(result["ssl"]["status"]),
- validation_errors=result["ssl"].get("validation_errors", []),
- ),
- )
+ return _parse_hostname(data["result"])
def get_custom_hostname_by_domain(domain: str) -> t.Optional[CustomHostnameInfo]:
@@ -197,16 +201,7 @@ def get_custom_hostname_by_domain(domain: str) -> t.Optional[CustomHostnameInfo]
if not results:
return None
- result = results[0]
- return CustomHostnameInfo(
- id=result["id"],
- hostname=result["hostname"],
- status=CustomHostnameStatus(result["status"]),
- ssl=CustomHostnameSSL(
- status=CustomHostnameSSLStatus(result["ssl"]["status"]),
- validation_errors=result["ssl"].get("validation_errors", []),
- ),
- )
+ return _parse_hostname(results[0])
def delete_custom_hostname(hostname_id: str) -> bool:
diff --git a/posthog/temporal/proxy_service/create.py b/posthog/temporal/proxy_service/create.py
index ac6a04f23ac5..9223c47ea3de 100644
--- a/posthog/temporal/proxy_service/create.py
+++ b/posthog/temporal/proxy_service/create.py
@@ -419,6 +419,33 @@ async def schedule_monitor_job(inputs: ScheduleMonitorJobInputs):
# This is not an error - the schedule already exists
+# ProxyRecord.message is max_length=1024 — keep persisted failure descriptions well under that.
+_MAX_FAILURE_MESSAGE_LEN = 800
+
+
+def _truncate(message: str) -> str:
+ if len(message) <= _MAX_FAILURE_MESSAGE_LEN:
+ return message
+ return message[: _MAX_FAILURE_MESSAGE_LEN - 1] + "…"
+
+
+def _describe_activity_failure(error: ActivityError) -> str:
+ """Build a short, human-readable failure summary for ProxyRecord.message from a Temporal ActivityError.
+
+ Without this, create-time failures persist status=erroring with message=NULL, which forces
+ debugging through Temporal UI / worker logs even when the underlying cause is obvious.
+ """
+ activity_type = getattr(getattr(error, "activity_type", None), "name", None) or "activity"
+ cause = getattr(error, "cause", None)
+ cause_message = getattr(cause, "message", None) or str(cause) if cause else str(error)
+ return _truncate(f"{activity_type}: {cause_message}")
+
+
+def _describe_workflow_failure(error: BaseException) -> str:
+ """Build a short, human-readable failure summary for non-ActivityError exceptions in the workflow."""
+ return _truncate(f"{error.__class__.__name__}: {error}")
+
+
@workflow.defn(name="create-proxy")
class CreateManagedProxyWorkflow(PostHogWorkflow):
"""A Temporal Workflow to create a Managed reverse Proxy."""
@@ -635,6 +662,7 @@ class CreateManagedProxyWorkflow(PostHogWorkflow):
organization_id=inputs.organization_id,
proxy_record_id=inputs.proxy_record_id,
status=ProxyRecord.Status.ERRORING.value,
+ message=_describe_activity_failure(e),
),
start_to_close_timeout=dt.timedelta(seconds=60),
retry_policy=temporalio.common.RetryPolicy(
@@ -676,6 +704,7 @@ class CreateManagedProxyWorkflow(PostHogWorkflow):
organization_id=inputs.organization_id,
proxy_record_id=inputs.proxy_record_id,
status=ProxyRecord.Status.ERRORING.value,
+ message=_describe_workflow_failure(e),
),
start_to_close_timeout=dt.timedelta(seconds=60),
retry_policy=temporalio.common.RetryPolicy(
diff --git a/products/platform_features/backend/max_tools.py b/products/platform_features/backend/max_tools.py
new file mode 100644
index 000000000000..12e3b3f53fc7
--- /dev/null
+++ b/products/platform_features/backend/max_tools.py
@@ -0,0 +1,158 @@
+from typing import Any
+
+from asgiref.sync import sync_to_async
+from pydantic import BaseModel, Field
+
+from posthog.api.proxy_record_diagnostics import diagnose
+from posthog.exceptions_capture import capture_exception
+from posthog.models import ProxyRecord
+from posthog.models.organization import OrganizationMembership
+
+from ee.hogai.tool import MaxTool
+
+DIAGNOSE_PROXY_TOOL_DESCRIPTION = """
+Run a deep diagnostic on a managed reverse proxy that's stuck or erroring.
+
+# When to use
+- User asks why a reverse proxy isn't working / is stuck
+- User mentions an erroring or timed-out proxy
+- User mentions a managed proxy domain by name and reports it's not live
+- The proxy settings page shows a record in 'erroring', 'warning', or 'timed_out' state
+
+# What it checks
+- Customer DNS CNAME alignment with the expected proxy target
+- Cloudflare custom hostname state (active / pending_validation / pending_issuance / etc.)
+- CAA records walked up the customer's DNS tree (most common stuck-validation cause)
+- HTTP-01 challenge URL reachability and content
+- Live event probe to the customer's proxy domain
+- Certificate expiry
+
+# Output
+Returns a structured report. Each check has a status (pass / warn / fail / skip) and a
+customer-facing detail string. Failed checks include a remediation block with the exact
+DNS records the customer should add.
+
+# Identifying the proxy
+- Pass `proxy_record_id` (UUID) when known. The user-visible settings page lists records.
+- When the user names a proxy by domain (e.g. "diagnose e.example.com"), look up the
+ record in the contextual `proxy_records` list provided to you and pass its id.
+""".strip()
+
+
+DIAGNOSE_PROXY_CONTEXT_PROMPT_TEMPLATE = """
+The user is currently viewing the managed reverse proxy settings. Records on this page:
+
+{proxy_records}
+
+<system_reminder>
+When the user asks to diagnose a proxy, pick the matching record's `id` from the list above and
+pass it as `proxy_record_id` to `diagnose_proxy`. If the user doesn't specify which proxy, ask
+them — only diagnose the one they mean.
+</system_reminder>
+""".strip()
+
+
+class DiagnoseProxyToolArgs(BaseModel):
+ proxy_record_id: str = Field(
+ description="UUID of the ProxyRecord to diagnose. Must belong to the current organization.",
+ )
+
+
+class DiagnoseProxyTool(MaxTool):
+ name: str = "diagnose_proxy"
+ description: str = DIAGNOSE_PROXY_TOOL_DESCRIPTION
+ args_schema: type[BaseModel] = DiagnoseProxyToolArgs
+ context_prompt_template: str = DIAGNOSE_PROXY_CONTEXT_PROMPT_TEMPLATE
+
+ # Permission: matches the underlying DRF endpoint's OrganizationAdminWritePermissions.
+ # We can't use get_required_resource_access([("organization", "admin")]) here because
+ # MaxTool's resource-level RBAC doesn't recognize OrganizationMembership.Level — owners
+ # would fail the check. Instead we do an explicit membership-level check below.
+
+ async def _arun_impl(self, proxy_record_id: str) -> tuple[str, dict[str, Any]]:
+ if not await sync_to_async(self._is_org_admin_or_owner)():
+ return (
+ "You need to be an organization admin to run a proxy diagnostic. Ask an admin to run it for you.",
+ {"error": "permission_denied"},
+ )
+
+ try:
+ record = await sync_to_async(self._get_record)(proxy_record_id)
+ except ProxyRecord.DoesNotExist:
+ return f"No reverse proxy with id `{proxy_record_id}` was found in this organization.", {
+ "error": "not_found",
+ "proxy_record_id": proxy_record_id,
+ }
+
+ try:
+ report = await sync_to_async(diagnose)(record)
+ except Exception as e:
+ capture_exception(e, {"team_id": self._team.id, "proxy_record_id": proxy_record_id})
+ return f"Diagnose failed unexpectedly: {e}", {
+ "error": "diagnose_failed",
+ "proxy_record_id": proxy_record_id,
+ "details": str(e),
+ }
+
+ return _format_report(record, report), _serialize_report(record, report)
+
+ def _is_org_admin_or_owner(self) -> bool:
+ membership = OrganizationMembership.objects.filter(
+ organization_id=self._team.organization_id,
+ user=self._user,
+ ).first()
+ return membership is not None and membership.level >= OrganizationMembership.Level.ADMIN
+
+ def _get_record(self, proxy_record_id: str) -> ProxyRecord:
+ return ProxyRecord.objects.get(id=proxy_record_id, organization_id=self._team.organization_id)
+
+
+def _format_report(record: ProxyRecord, report: Any) -> str:
+ """Build a markdown summary the LLM can directly relay to the user."""
+ lines = [f"**Diagnosed `{record.domain}`** — {report.summary.status}"]
+ if report.summary.next_action:
+ lines.append("")
+ lines.append(f"_Next action:_ {report.summary.next_action}")
+ lines.append("")
+ for check in report.checks:
+ marker = {"passed": "✓", "warned": "!", "failed": "×", "skipped": "–"}.get(check.status, "?")
+ lines.append(f"- {marker} **{check.name}** ({check.status}): {check.detail}")
+ if check.remediation:
+ lines.append(f" - _Fix:_ {check.remediation.summary}")
+ for dns_record in check.remediation.records:
+ lines.append(f" - `{dns_record.name} {dns_record.type} {dns_record.value}`")
+ return "\n".join(lines)
+
+
+def _serialize_report(record: ProxyRecord, report: Any) -> dict[str, Any]:
+ """Return the full structured report so downstream UIs can render it."""
+ return {
+ "proxy_record_id": str(record.id),
+ "domain": record.domain,
+ "ran_at": report.ran_at.isoformat(),
+ "summary": {
+ "status": report.summary.status,
+ "primary_issue": report.summary.primary_issue,
+ "next_action": report.summary.next_action,
+ },
+ "checks": [
+ {
+ "id": check.id,
+ "name": check.name,
+ "status": check.status,
+ "detail": check.detail,
+ "remediation": (
+ {
+ "type": check.remediation.type,
+ "summary": check.remediation.summary,
+ "records": [
+ {"name": r.name, "type": r.type, "value": r.value} for r in check.remediation.records
+ ],
+ }
+ if check.remediation
+ else None
+ ),
+ }
+ for check in report.checks
+ ],
+ }
diff --git a/services/mcp/definitions/proxy-records.yaml b/services/mcp/definitions/proxy-records.yaml
index 2de3dae2de4a..7136e7bfa9a3 100644
--- a/services/mcp/definitions/proxy-records.yaml
+++ b/services/mcp/definitions/proxy-records.yaml
@@ -45,6 +45,23 @@ tools:
Delete a managed reverse proxy. For proxies still being set up (waiting, erroring, timed_out), the record is
removed immediately. For active proxies, a cleanup workflow is started to remove the provisioned
infrastructure.
+ proxy-diagnose:
+ operation: proxy_records_diagnose_create
+ enabled: true
+ scopes:
+ - organization:write
+ annotations:
+ readOnly: true
+ destructive: false
+ idempotent: false
+ title: Diagnose reverse proxy
+ description: >
+ Run a deep diagnostic on a reverse proxy that's stuck or erroring. Inspects the customer's CNAME, the
+ certificate provider's hostname state, CAA records walked up the DNS tree (the most common stuck-validation
+ cause), HTTP-01 challenge reachability, a live event probe, and certificate expiry. Returns a structured
+ report with each check's status and concrete remediation steps — including the exact DNS records the
+ customer should add when CAA blocks issuance. Use this when proxy-get returns an erroring or timed_out
+ status, or whenever a user asks why their proxy isn't working.
proxy-get:
operation: proxy_records_retrieve
enabled: true
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index a8c72c572f71..ede3711c4e2b 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -3659,6 +3659,21 @@
"readOnlyHint": false
}
},
+ "proxy-diagnose": {
+ "description": "Run a deep diagnostic on a reverse proxy that's stuck or erroring. Inspects the customer's CNAME, the certificate provider's hostname state, CAA records walked up the DNS tree (the most common stuck-validation cause), HTTP-01 challenge reachability, a live event probe, and certificate expiry. Returns a structured report with each check's status and concrete remediation steps — including the exact DNS records the customer should add when CAA blocks issuance. Use this when proxy-get returns an erroring or timed_out status, or whenever a user asks why their proxy isn't working.",
+ "category": "Reverse proxy",
+ "feature": "reverse_proxy",
+ "summary": "Diagnose reverse proxy",
+ "title": "Diagnose reverse proxy",
+ "required_scopes": ["organization:write"],
+ "new_mcp": true,
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": false,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ }
+ },
"proxy-get": {
"description": "Get full details of a specific reverse proxy by ID. Returns the domain, CNAME target (the DNS record value the user needs to configure), current provisioning status, and any error or warning messages. Use this to debug why a proxy isn't working or to check DNS verification status.",
"category": "Reverse proxy",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index acb33b57b797..1b5127ef6858 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -4017,6 +4017,21 @@
"readOnlyHint": false
}
},
+ "proxy-diagnose": {
+ "description": "Run a deep diagnostic on a reverse proxy that's stuck or erroring. Inspects the customer's CNAME, the certificate provider's hostname state, CAA records walked up the DNS tree (the most common stuck-validation cause), HTTP-01 challenge reachability, a live event probe, and certificate expiry. Returns a structured report with each check's status and concrete remediation steps — including the exact DNS records the customer should add when CAA blocks issuance. Use this when proxy-get returns an erroring or timed_out status, or whenever a user asks why their proxy isn't working.",
+ "category": "Reverse proxy",
+ "feature": "reverse_proxy",
+ "summary": "Diagnose reverse proxy",
+ "title": "Diagnose reverse proxy",
+ "required_scopes": ["organization:write"],
+ "new_mcp": true,
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": false,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ }
+ },
"proxy-get": {
"description": "Get full details of a specific reverse proxy by ID. Returns the domain, CNAME target (the DNS record value the user needs to configure), current provisioning status, and any error or warning messages. Use this to debug why a proxy isn't working or to check DNS verification status.",
"category": "Reverse proxy",
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 5308c6295af5..b72b6e4585f8 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -15081,6 +15081,121 @@ export namespace Schemas {
Tablet: 'Tablet',
} as const;
+ /**
+ * * `passed` - passed
+ * `warned` - warned
+ * `failed` - failed
+ * `skipped` - skipped
+ */
+ export type DiagnosticCheckResultStatusEnum = typeof DiagnosticCheckResultStatusEnum[keyof typeof DiagnosticCheckResultStatusEnum];
+
+
+ export const DiagnosticCheckResultStatusEnum = {
+ Passed: 'passed',
+ Warned: 'warned',
+ Failed: 'failed',
+ Skipped: 'skipped',
+ } as const;
+
+ /**
+ * * `dns` - dns
+ * `config` - config
+ * `wait` - wait
+ * `retry` - retry
+ */
+ export type DiagnosticRemediationTypeEnum = typeof DiagnosticRemediationTypeEnum[keyof typeof DiagnosticRemediationTypeEnum];
+
+
+ export const DiagnosticRemediationTypeEnum = {
+ Dns: 'dns',
+ Config: 'config',
+ Wait: 'wait',
+ Retry: 'retry',
+ } as const;
+
+ export interface DiagnosticDnsRecord {
+ /** 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 DiagnosticRemediation {
+ /** 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: DiagnosticRemediationTypeEnum;
+ /** 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: DiagnosticDnsRecord[];
+ }
+
+ export interface DiagnosticCheckResult {
+ /** 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: DiagnosticCheckResultStatusEnum;
+ /** Customer-facing explanation of the check's outcome. */
+ detail: string;
+ /** Concrete remediation steps when the check failed; null when there's nothing actionable. */
+ remediation?: DiagnosticRemediation | null;
+ }
+
+ /**
+ * * `healthy` - healthy
+ * `warn` - warn
+ * `fail` - fail
+ */
+ export type DiagnosticReportSummaryStatusEnum = typeof DiagnosticReportSummaryStatusEnum[keyof typeof DiagnosticReportSummaryStatusEnum];
+
+
+ export const DiagnosticReportSummaryStatusEnum = {
+ Healthy: 'healthy',
+ Warn: 'warn',
+ Fail: 'fail',
+ } as const;
+
+ export interface DiagnosticReportSummary {
+ /** Overall outcome: healthy if the proxy is serving requests, warn for non-blocking issues, fail otherwise.
+
+ * `healthy` - healthy
+ * `warn` - warn
+ * `fail` - fail */
+ status: DiagnosticReportSummaryStatusEnum;
+ /**
+ * 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;
+ }
+
+ export interface DiagnosticReport {
+ /** When this diagnostic report was generated (UTC). */
+ ran_at: string;
+ /** Top-level outcome and recommended next action. */
+ summary: DiagnosticReportSummary;
+ /** Per-check results in execution order. */
+ checks: DiagnosticCheckResult[];
+ }
+
/**
* * `Up` - Up
* `Down` - Down
diff --git a/services/mcp/src/generated/proxy-records/api.ts b/services/mcp/src/generated/proxy-records/api.ts
index 639e64715368..8cfd8c796b10 100644
--- a/services/mcp/src/generated/proxy-records/api.ts
+++ b/services/mcp/src/generated/proxy-records/api.ts
@@ -3,7 +3,7 @@
* MCP service uses these Zod schemas for generated tool handlers.
* To regenerate: hogli build:openapi
*
- * PostHog API - MCP 5 enabled ops
+ * PostHog API - MCP 6 enabled ops
* OpenAPI spec version: 1.0.0
*/
import * as zod from 'zod'
@@ -60,6 +60,18 @@ export const ProxyRecordsDestroyParams = /* @__PURE__ */ zod.object({
),
})
+/**
+ * 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 ProxyRecordsDiagnoseCreateParams = /* @__PURE__ */ zod.object({
+ id: zod.string().describe('A UUID string identifying this proxy record.'),
+ organization_id: zod
+ .string()
+ .describe(
+ "ID of the organization you're trying to access. To find the ID of the organization, make a call to /api/organizations/."
+ ),
+})
+
/**
* 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.
*/
diff --git a/services/mcp/src/tools/generated/proxy-records.ts b/services/mcp/src/tools/generated/proxy-records.ts
index 7e686a8635b4..2df501065601 100644
--- a/services/mcp/src/tools/generated/proxy-records.ts
+++ b/services/mcp/src/tools/generated/proxy-records.ts
@@ -5,6 +5,7 @@ import type { Schemas } from '@/api/generated'
import {
ProxyRecordsCreateBody,
ProxyRecordsDestroyParams,
+ ProxyRecordsDiagnoseCreateParams,
ProxyRecordsRetrieveParams,
ProxyRecordsRetryCreateParams,
} from '@/generated/proxy-records/api'
@@ -46,6 +47,21 @@ const proxyDelete = (): ToolBase<typeof ProxyDeleteSchema, unknown> => ({
},
})
+const ProxyDiagnoseSchema = ProxyRecordsDiagnoseCreateParams.omit({ organization_id: true })
+
+const proxyDiagnose = (): ToolBase<typeof ProxyDiagnoseSchema, Schemas.DiagnosticReport> => ({
+ name: 'proxy-diagnose',
+ schema: ProxyDiagnoseSchema,
+ handler: async (context: Context, params: z.infer<typeof ProxyDiagnoseSchema>) => {
+ const orgId = await context.stateManager.getOrgID()
+ const result = await context.api.request<Schemas.DiagnosticReport>({
+ method: 'POST',
+ path: `/api/organizations/${encodeURIComponent(String(orgId))}/proxy_records/${encodeURIComponent(String(params.id))}/diagnose/`,
+ })
+ return result
+ },
+})
+
const ProxyGetSchema = ProxyRecordsRetrieveParams.omit({ organization_id: true })
const proxyGet = (): ToolBase<typeof ProxyGetSchema, Schemas.ProxyRecord> => ({
@@ -95,6 +111,7 @@ const proxyRetry = (): ToolBase<typeof ProxyRetrySchema, Schemas.ProxyRecord> =>
export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {
'proxy-create': proxyCreate,
'proxy-delete': proxyDelete,
+ 'proxy-diagnose': proxyDiagnose,
'proxy-get': proxyGet,
'proxy-list': proxyList,
'proxy-retry': proxyRetry,
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/common/proxy-diagnose.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/common/proxy-diagnose.json
new file mode 100644
index 000000000000..fce98411e0d5
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/common/proxy-diagnose.json
@@ -0,0 +1,11 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {
+ "id": {
+ "description": "A UUID string identifying this proxy record.",
+ "type": "string"
+ }
+ },
+ "required": ["id"],
+ "type": "object"
+}
diff --git a/tach.toml b/tach.toml
index c7e81ec83fab..a21be1776e7c 100644
--- a/tach.toml
+++ b/tach.toml
@@ -341,6 +341,8 @@ layer = "modules"
[[modules]]
path = "products.platform_features"
depends_on = [
+ "ee",
+ "posthog",
]
layer = "modules"