Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix: use workers kv instead of custom metadata for root redirect url (#90523)

Reece Jones5d619951290a
diff --git a/posthog/api/proxy_record.py b/posthog/api/proxy_record.py
index c1885e66e291..e0922d2f46fb 100644
--- a/posthog/api/proxy_record.py
+++ b/posthog/api/proxy_record.py
@@ -33,7 +33,7 @@ from posthog.temporal.proxy_service import CreateManagedProxyInputs, DeleteManag
from posthog.temporal.proxy_service.cloudflare import (
CloudflareAPIError,
get_custom_hostname_by_domain,
- update_custom_hostname_metadata,
+ update_cloudflare_proxy_root_redirect,
)
from posthog.temporal.proxy_service.common import is_cloudflare_proxy_by_cname
@@ -319,7 +319,6 @@ class ProxyRecordViewset(TeamAndOrgViewSetMixin, ModelViewSet):
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)
@@ -328,7 +327,7 @@ class ProxyRecordViewset(TeamAndOrgViewSetMixin, ModelViewSet):
{"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 ""})
+ update_cloudflare_proxy_root_redirect(record.domain, root_redirect_url)
except (CloudflareAPIError, requests.RequestException) as error:
capture_exception(error, {"domain": record.domain, "proxy_record_id": str(record.id)})
return Response(
@@ -340,13 +339,7 @@ class ProxyRecordViewset(TeamAndOrgViewSetMixin, ModelViewSet):
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)})
+ reconciliation_required = True
raise
except ProxyRecord.DoesNotExist:
raise NotFound()
@@ -544,7 +537,7 @@ class ProxyRecordViewset(TeamAndOrgViewSetMixin, ModelViewSet):
ProxyRecord.Status.WAITING,
ProxyRecord.Status.ERRORING,
ProxyRecord.Status.TIMED_OUT,
- ):
+ ) and not is_cloudflare_proxy_by_cname(record.target_cname):
_capture_proxy_event(request, record, "deleted")
record.delete()
else:
@@ -559,6 +552,7 @@ class ProxyRecordViewset(TeamAndOrgViewSetMixin, ModelViewSet):
proxy_record_id=record.id,
domain=record.domain,
target_cname=record.target_cname,
+ root_redirect_url=record.root_redirect_url,
)
workflow_id = f"proxy-delete-{inputs.proxy_record_id}"
asyncio.run(
diff --git a/posthog/api/test/test_proxy_record.py b/posthog/api/test/test_proxy_record.py
index daaf2feda259..dd26a42c19ef 100644
--- a/posthog/api/test/test_proxy_record.py
+++ b/posthog/api/test/test_proxy_record.py
@@ -1,7 +1,7 @@
from types import SimpleNamespace
from posthog.test.base import APIBaseTest
-from unittest.mock import AsyncMock, call, patch
+from unittest.mock import AsyncMock, patch
from django.db import DatabaseError
from django.test import SimpleTestCase
@@ -13,7 +13,6 @@ 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,
@@ -177,10 +176,10 @@ 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.update_cloudflare_proxy_root_redirect")
@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):
+ def test_updates_root_redirect_in_kv(self, _capture, get_hostname, update_redirect):
record = ProxyRecord.objects.create(
organization=self.organization,
created_by=self.user,
@@ -206,13 +205,13 @@ class TestProxyRecordAPI(APIBaseTest):
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"})
+ update_redirect.assert_called_once_with(record.domain, "https://www.example.com/welcome")
- @patch("posthog.api.proxy_record.update_custom_hostname_metadata")
+ @patch("posthog.api.proxy_record.update_cloudflare_proxy_root_redirect")
@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
+ def test_reconciles_root_redirect_when_database_write_fails(
+ self, reconcile_root_redirect, get_hostname, update_redirect
):
record = ProxyRecord.objects.create(
organization=self.organization,
@@ -229,7 +228,6 @@ class TestProxyRecordAPI(APIBaseTest):
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"),
@@ -241,12 +239,7 @@ class TestProxyRecordAPI(APIBaseTest):
)
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/"}),
- ]
- )
+ update_redirect.assert_called_once_with(record.domain, "https://new.example.com/")
reconcile_root_redirect.assert_called_once_with(str(record.id))
@parameterized.expand(
@@ -260,10 +253,10 @@ class TestProxyRecordAPI(APIBaseTest):
("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.update_cloudflare_proxy_root_redirect")
@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
+ self, _name, proxy_domain, redirect_url, expected_error, get_hostname, _update_redirect
):
get_hostname.return_value = SimpleNamespace(custom_metadata={})
record = ProxyRecord.objects.create(
@@ -283,11 +276,11 @@ class TestProxyRecordAPI(APIBaseTest):
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()
+ _update_redirect.assert_not_called()
- @patch("posthog.api.proxy_record.update_custom_hostname_metadata")
+ @patch("posthog.api.proxy_record.update_cloudflare_proxy_root_redirect")
@patch("posthog.api.proxy_record.get_custom_hostname_by_domain")
- def test_clears_root_redirect_metadata(self, get_hostname, update_metadata):
+ def test_clears_root_redirect_in_kv(self, get_hostname, update_redirect):
record = ProxyRecord.objects.create(
organization=self.organization,
created_by=self.user,
@@ -312,7 +305,7 @@ class TestProxyRecordAPI(APIBaseTest):
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": ""})
+ update_redirect.assert_called_once_with(record.domain, None)
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
@@ -582,6 +575,29 @@ class TestProxyRecordAPI(APIBaseTest):
assert response.status_code == status.HTTP_200_OK
assert not ProxyRecord.objects.filter(id=record.id).exists()
+ @patch("posthog.api.proxy_record.sync_connect")
+ @patch("posthoganalytics.capture")
+ def test_destroy_pre_active_cloudflare_proxy_starts_cleanup_workflow(self, _capture, mock_sync_connect):
+ mock_temporal = AsyncMock()
+ mock_sync_connect.return_value = mock_temporal
+ record = ProxyRecord.objects.create(
+ organization=self.organization,
+ created_by=self.user,
+ domain="cloudflare-destroy.example.com",
+ target_cname="abc123.cf-proxy.example.net",
+ status=ProxyRecord.Status.ERRORING,
+ )
+
+ with self.settings(CLOUDFLARE_PROXY_BASE_CNAME="cf-proxy.example.net"):
+ response = self.client.delete(
+ f"/api/organizations/{self.organization.id}/proxy_records/{record.id}/",
+ )
+
+ assert response.status_code == status.HTTP_200_OK
+ record.refresh_from_db()
+ assert record.status == ProxyRecord.Status.DELETING
+ mock_temporal.start_workflow.assert_awaited_once()
+
@parameterized.expand(
[
("valid", ProxyRecord.Status.VALID),
diff --git a/posthog/settings/web.py b/posthog/settings/web.py
index e07d43a8028d..f10a0319d173 100644
--- a/posthog/settings/web.py
+++ b/posthog/settings/web.py
@@ -1091,7 +1091,9 @@ PROXY_BASE_CNAME = get_from_env("PROXY_BASE_CNAME", "")
# Cloudflare for SaaS proxy settings
CLOUDFLARE_PROXY_ENABLED = get_from_env("CLOUDFLARE_PROXY_ENABLED", False, type_cast=str_to_bool)
CLOUDFLARE_API_TOKEN = get_from_env("CLOUDFLARE_API_TOKEN", "")
+CLOUDFLARE_ACCOUNT_ID = get_from_env("CLOUDFLARE_ACCOUNT_ID", "")
CLOUDFLARE_ZONE_ID = get_from_env("CLOUDFLARE_ZONE_ID", "")
+CLOUDFLARE_PROXY_KV_NAMESPACE_ID = get_from_env("CLOUDFLARE_PROXY_KV_NAMESPACE_ID", "")
CLOUDFLARE_WORKER_NAME = get_from_env("CLOUDFLARE_WORKER_NAME", "")
CLOUDFLARE_PROXY_BASE_CNAME = get_from_env("CLOUDFLARE_PROXY_BASE_CNAME", "")
diff --git a/posthog/tasks/proxy.py b/posthog/tasks/proxy.py
index 4c10f2f75879..eea2b90b0c72 100644
--- a/posthog/tasks/proxy.py
+++ b/posthog/tasks/proxy.py
@@ -6,11 +6,7 @@ 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,
-)
+from posthog.temporal.proxy_service.cloudflare import CloudflareAPIError, update_cloudflare_proxy_root_redirect
@shared_task(
@@ -28,8 +24,4 @@ def reconcile_proxy_root_redirect(proxy_record_id: str) -> None:
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 ""})
+ update_cloudflare_proxy_root_redirect(record.domain, record.root_redirect_url)
diff --git a/posthog/temporal/proxy_service/cloudflare.py b/posthog/temporal/proxy_service/cloudflare.py
index 5cbbf22f6871..60e325844eac 100644
--- a/posthog/temporal/proxy_service/cloudflare.py
+++ b/posthog/temporal/proxy_service/cloudflare.py
@@ -11,6 +11,7 @@ import re
import typing as t
from dataclasses import dataclass, field
from enum import Enum
+from urllib.parse import quote
from django.conf import settings
@@ -184,11 +185,10 @@ class CustomHostname:
hostname: str
status: CustomHostnameStatus
ssl: CustomHostnameSSL
- custom_metadata: dict[str, str] = field(default_factory=dict)
def _get_headers() -> dict[str, str]:
- """Get headers for Cloudflare API requests."""
+ """Get headers for Cloudflare zone API requests."""
if not settings.CLOUDFLARE_API_TOKEN or not settings.CLOUDFLARE_ZONE_ID:
raise ValueError("CLOUDFLARE_API_TOKEN and CLOUDFLARE_ZONE_ID must be configured when using Cloudflare proxy")
return {
@@ -197,6 +197,16 @@ def _get_headers() -> dict[str, str]:
}
+def _get_kv_headers() -> dict[str, str]:
+ """Get headers for Cloudflare Workers KV API requests."""
+ if not settings.CLOUDFLARE_API_TOKEN or not settings.CLOUDFLARE_ACCOUNT_ID:
+ raise ValueError("CLOUDFLARE_API_TOKEN and CLOUDFLARE_ACCOUNT_ID must be configured for proxy redirects")
+ return {
+ "Authorization": f"Bearer {settings.CLOUDFLARE_API_TOKEN}",
+ "Content-Type": "application/octet-stream",
+ }
+
+
def _parse_hostname(result: dict) -> "CustomHostname":
"""Build a CustomHostname from a Cloudflare API custom_hostname result object."""
ssl_payload = result.get("ssl", {})
@@ -212,7 +222,6 @@ 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", {}),
)
@@ -234,7 +243,7 @@ def _handle_response(response: requests.Response) -> dict:
return data
-def create_custom_hostname(domain: str, root_redirect_url: str | None = None) -> CustomHostname:
+def create_custom_hostname(domain: str) -> CustomHostname:
"""
Create a Custom Hostname in Cloudflare for SaaS.
@@ -264,8 +273,6 @@ def create_custom_hostname(domain: str, root_redirect_url: str | None = None) ->
},
},
}
- if root_redirect_url:
- payload["custom_metadata"] = {"root_redirect_url": root_redirect_url}
response = requests.post(url, headers=_get_headers(), json=payload, timeout=CLOUDFLARE_API_TIMEOUT_S)
data = _handle_response(response)
@@ -322,17 +329,28 @@ 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,
+def update_cloudflare_proxy_root_redirect(domain: str, redirect_url: str | None) -> None:
+ """Store or remove the root redirect for a managed proxy domain in Workers KV."""
+ namespace_id = settings.CLOUDFLARE_PROXY_KV_NAMESPACE_ID
+ if not namespace_id:
+ raise ValueError("CLOUDFLARE_PROXY_KV_NAMESPACE_ID must be configured for proxy redirects")
+
+ key = quote(domain, safe="")
+ url = (
+ f"{CLOUDFLARE_API_BASE}/accounts/{settings.CLOUDFLARE_ACCOUNT_ID}"
+ f"/storage/kv/namespaces/{namespace_id}/values/{key}"
)
- data = _handle_response(response)
- return _parse_hostname(data["result"])
+ if redirect_url:
+ response = requests.put(
+ url,
+ headers=_get_kv_headers(),
+ data=redirect_url.encode(),
+ timeout=CLOUDFLARE_API_TIMEOUT_S,
+ )
+ else:
+ response = requests.delete(url, headers=_get_kv_headers(), timeout=CLOUDFLARE_API_TIMEOUT_S)
+
+ _handle_response(response)
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 588855bf2b29..4c3a27334fc7 100644
--- a/posthog/temporal/proxy_service/create.py
+++ b/posthog/temporal/proxy_service/create.py
@@ -35,6 +35,7 @@ from posthog.temporal.proxy_service.cloudflare import (
CustomHostnameSSLStatus,
create_custom_hostname,
get_custom_hostname_by_domain,
+ update_cloudflare_proxy_root_redirect,
)
from posthog.temporal.proxy_service.common import (
NonRetriableException,
@@ -295,7 +296,7 @@ async def create_cloudflare_custom_hostname(inputs: CreateCloudflareProxyInputs)
raise RecordDeletedException("proxy record was deleted while creating Cloudflare Custom Hostname")
try:
- result = await asyncio.to_thread(create_custom_hostname, inputs.domain, record.root_redirect_url)
+ result = await asyncio.to_thread(create_custom_hostname, inputs.domain)
logger.info(
"Created Cloudflare Custom Hostname %s for domain %s with status %s",
result.id,
@@ -306,11 +307,19 @@ async def create_cloudflare_custom_hostname(inputs: CreateCloudflareProxyInputs)
if any(err.get("code") == 1406 for err in e.errors):
# Custom hostname already exists
logger.info("Cloudflare Custom Hostname already exists for domain %s", inputs.domain)
- return
- if e.is_rate_limited():
+ elif e.is_rate_limited():
# Rate limited by Cloudflare — re-raise to let Temporal retry with backoff
raise
- raise NonRetriableException(f"Cloudflare API error: {e}") from e
+ else:
+ raise NonRetriableException(f"Cloudflare API error: {e}") from e
+
+ if record.root_redirect_url:
+ try:
+ await asyncio.to_thread(update_cloudflare_proxy_root_redirect, inputs.domain, record.root_redirect_url)
+ except CloudflareAPIError as e:
+ if e.is_rate_limited():
+ raise
+ raise NonRetriableException(f"Cloudflare KV error: {e}") from e
@activity.defn
diff --git a/posthog/temporal/proxy_service/delete.py b/posthog/temporal/proxy_service/delete.py
index 6afdc4999698..23b3618bef4e 100644
--- a/posthog/temporal/proxy_service/delete.py
+++ b/posthog/temporal/proxy_service/delete.py
@@ -3,7 +3,6 @@ import uuid
import typing as t
import asyncio
import datetime as dt
-from dataclasses import dataclass
from django.db import connection
@@ -13,6 +12,7 @@ from asgiref.sync import sync_to_async
from structlog.contextvars import bind_contextvars
from temporalio import activity, workflow
+from posthog.dataclasses import frozen
from posthog.models import ProxyRecord
from posthog.temporal.common.base import PostHogWorkflow
from posthog.temporal.common.logger import get_logger
@@ -20,6 +20,7 @@ from posthog.temporal.proxy_service.cloudflare import (
CloudflareAPIError,
delete_custom_hostname,
get_custom_hostname_by_domain,
+ update_cloudflare_proxy_root_redirect,
)
from posthog.temporal.proxy_service.common import (
NonRetriableException,
@@ -34,7 +35,7 @@ from posthog.temporal.proxy_service.proto import DeleteRequest
LOGGER = get_logger(__name__)
-@dataclass
+@frozen
class DeleteProxyRecordInputs:
organization_id: uuid.UUID
proxy_record_id: uuid.UUID
@@ -47,7 +48,7 @@ class DeleteProxyRecordInputs:
}
-@dataclass
+@frozen
class DeleteManagedProxyInputs:
"""Inputs for the DeleteManagedProxy Workflow and Activity."""
@@ -55,6 +56,7 @@ class DeleteManagedProxyInputs:
proxy_record_id: uuid.UUID
domain: str
target_cname: str = "" # Used to determine if proxy is Cloudflare or legacy
+ root_redirect_url: str | None = None
@property
def properties_to_log(self) -> dict[str, t.Any]:
@@ -153,6 +155,12 @@ async def delete_cloudflare_proxy(inputs: DeleteManagedProxyInputs):
logger.warning("Failed to delete Cloudflare Custom Hostname for domain %s: %s", inputs.domain, e)
errors.append(f"Custom Hostname deletion failed: {e}")
+ try:
+ await asyncio.to_thread(update_cloudflare_proxy_root_redirect, inputs.domain, None)
+ except CloudflareAPIError as e:
+ logger.warning("Failed to delete root redirect for domain %s: %s", inputs.domain, e)
+ errors.append(f"Root redirect deletion failed: {e}")
+
if errors:
raise NonRetriableException(f"Cloudflare API errors: {'; '.join(errors)}")
diff --git a/posthog/temporal/proxy_service/test/test_cloudflare.py b/posthog/temporal/proxy_service/test/test_cloudflare.py
index 058e54255218..9955a257a2df 100644
--- a/posthog/temporal/proxy_service/test/test_cloudflare.py
+++ b/posthog/temporal/proxy_service/test/test_cloudflare.py
@@ -11,7 +11,7 @@ from posthog.temporal.proxy_service.cloudflare import (
_parse_hostname,
create_custom_hostname,
parse_cloudflare_error_code,
- update_custom_hostname_metadata,
+ update_cloudflare_proxy_root_redirect,
)
# Every status Cloudflare can send, which is a superset of what the enums name. Re-derive with:
@@ -119,18 +119,23 @@ class TestParseHostnameStatuses(SimpleTestCase):
self.assertNotEqual(info.status, CustomHostnameStatus.ACTIVE)
-@override_settings(CLOUDFLARE_API_TOKEN="token", CLOUDFLARE_ZONE_ID="zone")
+@override_settings(
+ CLOUDFLARE_API_TOKEN="token",
+ CLOUDFLARE_ZONE_ID="zone",
+ CLOUDFLARE_ACCOUNT_ID="account",
+ CLOUDFLARE_PROXY_KV_NAMESPACE_ID="namespace",
+)
class TestCreateCustomHostname(SimpleTestCase):
@patch("posthog.temporal.proxy_service.cloudflare.requests.post")
- def test_sets_minimum_tls_version_and_redirect_metadata(self, post_request):
+ def test_sets_minimum_tls_version(self, post_request):
response = Mock()
response.json.return_value = {
"success": True,
- "result": _hostname_payload(custom_metadata={"root_redirect_url": "https://example.com/"}),
+ "result": _hostname_payload(),
}
post_request.return_value = response
- create_custom_hostname("p.example.com", "https://example.com/")
+ create_custom_hostname("p.example.com")
post_request.assert_called_once_with(
"https://api.cloudflare.com/client/v4/zones/zone/custom_hostnames",
@@ -142,43 +147,35 @@ 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.post")
- def test_omits_redirect_metadata_when_root_redirect_is_disabled(self, post_request):
- response = Mock()
- response.json.return_value = {"success": True, "result": _hostname_payload()}
- post_request.return_value = response
-
- create_custom_hostname("p.example.com")
-
- request_payload = post_request.call_args.kwargs["json"]
- assert "custom_metadata" not in request_payload
-
- @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"}))
+ @parameterized.expand(
+ [
+ ("set", "https://example.com/", "put"),
+ ("clear", None, "delete"),
+ ]
+ )
+ @patch("posthog.temporal.proxy_service.cloudflare.requests.delete")
+ @patch("posthog.temporal.proxy_service.cloudflare.requests.put")
+ def test_updates_root_redirect_in_kv(self, _name, redirect_url, method, put_request, delete_request):
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
+ response.json.return_value = {"success": True}
+ put_request.return_value = response
+ delete_request.return_value = response
- updated = update_custom_hostname_metadata(hostname, {"root_redirect_url": "https://example.com/"})
+ update_cloudflare_proxy_root_redirect("p.example.com", redirect_url)
- 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,
+ request = put_request if method == "put" else delete_request
+ request.assert_called_once()
+ assert request.call_args.args[0] == (
+ "https://api.cloudflare.com/client/v4/accounts/account/storage/kv/namespaces/namespace/values/p.example.com"
)
- self.assertEqual(updated.custom_metadata["root_redirect_url"], "https://example.com/")
+ if method == "put":
+ assert request.call_args.kwargs["data"] == b"https://example.com/"
+ else:
+ assert put_request.call_count == 0
class TestParseCloudflareErrorCode(SimpleTestCase):
diff --git a/posthog/temporal/proxy_service/test/test_create_workflow.py b/posthog/temporal/proxy_service/test/test_create_workflow.py
index 3a9d3d239a76..ba44b79a4ce6 100644
--- a/posthog/temporal/proxy_service/test/test_create_workflow.py
+++ b/posthog/temporal/proxy_service/test/test_create_workflow.py
@@ -1,7 +1,8 @@
import uuid
+from types import SimpleNamespace
import pytest
-from unittest.mock import patch
+from unittest.mock import AsyncMock, patch
import temporalio.worker
from temporalio import activity
@@ -17,6 +18,7 @@ from posthog.temporal.proxy_service.create import (
CreateManagedProxyWorkflow,
ScheduleMonitorJobInputs,
WaitForDNSRecordsInputs,
+ create_cloudflare_custom_hostname,
)
@@ -82,6 +84,24 @@ def _make_workflow_inputs():
)
+class TestCreateCloudflareCustomHostname:
+ @patch("posthog.temporal.proxy_service.create.update_cloudflare_proxy_root_redirect")
+ @patch("posthog.temporal.proxy_service.create.create_custom_hostname")
+ @patch("posthog.temporal.proxy_service.create.get_record", new_callable=AsyncMock)
+ async def test_skips_kv_when_no_root_redirect_is_configured(self, get_record, create_hostname, update_redirect):
+ inputs = CreateCloudflareProxyInputs(
+ organization_id=uuid.uuid4(),
+ proxy_record_id=uuid.uuid4(),
+ domain="test.example.com",
+ )
+ get_record.return_value = SimpleNamespace(root_redirect_url=None)
+ create_hostname.return_value = SimpleNamespace(id="hostname-id", status=SimpleNamespace(value="active"))
+
+ await create_cloudflare_custom_hostname(inputs)
+
+ update_redirect.assert_not_called()
+
+
@pytest.mark.django_db(transaction=True)
@patch("posthog.temporal.proxy_service.create.use_cloudflare_proxy", return_value=True)
class TestCreateManagedProxyWorkflowErrorHandling:
diff --git a/posthog/temporal/proxy_service/test/test_delete.py b/posthog/temporal/proxy_service/test/test_delete.py
new file mode 100644
index 000000000000..59229324b2cc
--- /dev/null
+++ b/posthog/temporal/proxy_service/test/test_delete.py
@@ -0,0 +1,21 @@
+import uuid
+
+from unittest.mock import patch
+
+from posthog.temporal.proxy_service.delete import DeleteManagedProxyInputs, delete_cloudflare_proxy
+
+
+class TestDeleteCloudflareProxy:
+ @patch("posthog.temporal.proxy_service.delete.update_cloudflare_proxy_root_redirect")
+ @patch("posthog.temporal.proxy_service.delete.get_custom_hostname_by_domain", return_value=None)
+ async def test_clears_kv_even_when_no_root_redirect_is_configured(self, _get_hostname, update_redirect):
+ inputs = DeleteManagedProxyInputs(
+ organization_id=uuid.uuid4(),
+ proxy_record_id=uuid.uuid4(),
+ domain="test.example.com",
+ root_redirect_url=None,
+ )
+
+ await delete_cloudflare_proxy(inputs)
+
+ update_redirect.assert_called_once_with("test.example.com", None)