: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(checks): warn at startup on settings that fail silently at runtime (#130288)
Rafael Audibert5688d90a6e50
diff --git a/posthog/checks.py b/posthog/checks.pyindex dd76a7e6eb40..9b7d28624965 100644--- a/posthog/checks.py+++ b/posthog/checks.py@@ -16,6 +16,7 @@ check registry without running the check."""import re+import ipaddressfrom collections.abc import Callable, Sequencefrom typing import Any@@ -25,6 +26,7 @@ from django.core.checks import CheckMessage, Error, Warning, registerfrom posthog.models.oauth import oidc_signing_key_configuredfrom posthog.product_db_router import get_product_db_routesfrom posthog.storage.object_storage import is_usable_endpoint+from posthog.utils import parse_crontabCHECK_ID_PATTERN = re.compile(r"^posthog\.[a-z][a-z0-9_]*\.[EW]\d{3}$")@@ -137,3 +139,118 @@ def check_product_db_routes(app_configs: Any, **kwargs: Any) -> list[CheckMessagapp_label_to_database[route.app_label] = route.databasereturn errors+++# Network access++ACCESS_ALLOWED_IP_BLOCK_INVALID = "posthog.access.W001"+ACCESS_TRUSTED_PROXY_NOT_AN_IP = "posthog.access.W002"+++@register_check(ACCESS_ALLOWED_IP_BLOCK_INVALID)+def check_allowed_ip_blocks(app_configs: Any, **kwargs: Any) -> list[CheckMessage]:+ # AllowIPMiddleware parses each block on every request, so one bad entry turns every request+ # outside the always-allowed paths into a 500 while startup succeeds.+ invalid = []+ for block in settings.ALLOWED_IP_BLOCKS:+ try:+ ipaddress.ip_network(block, strict=False)+ except ValueError:+ invalid.append(block)+ if not invalid:+ return []+ return [+ Warning(+ f"ALLOWED_IP_BLOCKS has entries that are not IP networks: {', '.join(repr(b) for b in invalid)}. "+ "Every request outside the always-allowed paths fails with a 500.",+ hint="Use an IP address or CIDR block for each entry, for example 10.0.0.0/8.",+ id=ACCESS_ALLOWED_IP_BLOCK_INVALID,+ )+ ]+++@register_check(ACCESS_TRUSTED_PROXY_NOT_AN_IP)+def check_trusted_proxies(app_configs: Any, **kwargs: Any) -> list[CheckMessage]:+ # get_trusted_client_ip compares each proxy's IP to these entries as exact strings, so an entry+ # that is not a single IP (a CIDR block, a port, brackets) never matches and the client IP is lost.+ if settings.TRUST_ALL_PROXIES or not settings.TRUSTED_PROXIES:+ return []+ invalid = []+ for proxy in (p.strip() for p in settings.TRUSTED_PROXIES.split(",")):+ if not proxy:+ continue+ try:+ ipaddress.ip_address(proxy)+ except ValueError:+ invalid.append(proxy)+ if not invalid:+ return []+ return [+ Warning(+ f"TRUSTED_PROXIES has entries that are not single IP addresses: {', '.join(repr(p) for p in invalid)}. "+ "Requests through them get no client IP, so the IP allowlist rejects them and IP rate limits "+ "share one bucket.",+ hint="List each proxy's IP address. CIDR blocks and ports are not supported.",+ id=ACCESS_TRUSTED_PROXY_NOT_AN_IP,+ )+ ]+++# Scheduled tasks++SCHEDULES_CRON_UNPARSEABLE = "posthog.schedules.W001"++CRON_SCHEDULE_SETTINGS = (+ "CALCULATE_COHORTS_DAY_SCHEDULE",+ "CALCULATE_COHORTS_NIGHT_SCHEDULE",+ "CLEAR_CLICKHOUSE_REMOVED_DATA_SCHEDULE_CRON",+ "CLEAR_CLICKHOUSE_DELETED_PERSON_SCHEDULE_CRON",+ "MATERIALIZE_COLUMNS_SCHEDULE_CRON",+)+++@register_check(SCHEDULES_CRON_UNPARSEABLE)+def check_cron_schedules(app_configs: Any, **kwargs: Any) -> list[CheckMessage]:+ # get_crontab swallows a parse failure and returns None, so the Celery beat job is never scheduled+ # and nothing tells the operator. An empty value is a deliberate opt-out, so only non-empty values count.+ warnings: list[CheckMessage] = []+ for name in CRON_SCHEDULE_SETTINGS:+ schedule = getattr(settings, name, None)+ if not schedule:+ continue+ try:+ parse_crontab(schedule)+ except Exception:+ warnings.append(+ Warning(+ f"{name} is not a valid cron schedule: {schedule!r}. The scheduled task never runs.",+ hint="Use five fields separated by single spaces, for example '0 5 * * SAT'.",+ id=SCHEDULES_CRON_UNPARSEABLE,+ )+ )+ return warnings+++# Temporal++TEMPORAL_CLIENT_TLS_PAIR_INCOMPLETE = "posthog.temporal.W001"+++@register_check(TEMPORAL_CLIENT_TLS_PAIR_INCOMPLETE)+def check_temporal_client_tls(app_configs: Any, **kwargs: Any) -> list[CheckMessage]:+ # The Temporal client enables TLS only when both values are set. With one of them, it connects in+ # plaintext, and a server that requires mutual TLS rejects the first workflow start at request time.+ if bool(settings.TEMPORAL_CLIENT_CERT) == bool(settings.TEMPORAL_CLIENT_KEY):+ return []+ present, missing = (+ ("TEMPORAL_CLIENT_CERT", "TEMPORAL_CLIENT_KEY")+ if settings.TEMPORAL_CLIENT_CERT+ else ("TEMPORAL_CLIENT_KEY", "TEMPORAL_CLIENT_CERT")+ )+ return [+ Warning(+ f"{present} is set but {missing} is not, so the Temporal client connects without TLS.",+ hint=f"Set {missing} too, or unset {present} if the Temporal server does not use mutual TLS.",+ id=TEMPORAL_CLIENT_TLS_PAIR_INCOMPLETE,+ )+ ]diff --git a/posthog/test/test_checks.py b/posthog/test/test_checks.pyindex d3ffdbb8962f..c645c7fb6f76 100644--- a/posthog/test/test_checks.py+++ b/posthog/test/test_checks.py@@ -1,8 +1,20 @@from pathlib import Path+from django.conf import settingsfrom django.test import SimpleTestCase, override_settings-from posthog.checks import check_encryption_salt_keys, check_object_storage_public_endpoint, check_product_db_routes+from parameterized import parameterized++from posthog.checks import (+ check_allowed_ip_blocks,+ check_cron_schedules,+ check_encryption_salt_keys,+ check_object_storage_public_endpoint,+ check_oidc_signing_key,+ check_product_db_routes,+ check_temporal_client_tls,+ check_trusted_proxies,+)from posthog.product_db_router import get_product_db_routesfrom posthog.settings.utils import get_list@@ -84,3 +96,68 @@ class TestProductDBRouteChecks(SimpleTestCase):self.addCleanup(get_product_db_routes.cache_clear)self.assertEqual(check_product_db_routes(None), [])+++class TestSettingWarnings(SimpleTestCase):+ @parameterized.expand(+ [+ (+ "oidc_key_set",+ {"OAUTH2_PROVIDER": {**settings.OAUTH2_PROVIDER, "OIDC_RSA_PRIVATE_KEY": "key"}},+ check_oidc_signing_key,+ [],+ ),+ (+ "oidc_key_missing",+ {"OAUTH2_PROVIDER": {**settings.OAUTH2_PROVIDER, "OIDC_RSA_PRIVATE_KEY": ""}},+ check_oidc_signing_key,+ ["posthog.oauth.W001"],+ ),+ ("ip_blocks_valid", {"ALLOWED_IP_BLOCKS": ["10.0.0.0/8", "192.168.1.5"]}, check_allowed_ip_blocks, []),+ (+ "ip_blocks_invalid",+ {"ALLOWED_IP_BLOCKS": ["10.0.0.0/8", "10.0.0/8"]},+ check_allowed_ip_blocks,+ ["posthog.access.W001"],+ ),+ (+ "trusted_proxies_valid",+ {"TRUSTED_PROXIES": "10.0.0.1, 2001:db8::1,", "TRUST_ALL_PROXIES": False},+ check_trusted_proxies,+ [],+ ),+ (+ "trusted_proxies_cidr",+ {"TRUSTED_PROXIES": "10.0.0.1,10.0.0.0/8", "TRUST_ALL_PROXIES": False},+ check_trusted_proxies,+ ["posthog.access.W002"],+ ),+ (+ "cron_valid",+ {"CALCULATE_COHORTS_DAY_SCHEDULE": "*/2 6-17 * * *", "MATERIALIZE_COLUMNS_SCHEDULE_CRON": ""},+ check_cron_schedules,+ [],+ ),+ (+ "cron_unparseable",+ {"CALCULATE_COHORTS_DAY_SCHEDULE": "*/2 6-17 * *", "MATERIALIZE_COLUMNS_SCHEDULE_CRON": "0 25 * * *"},+ check_cron_schedules,+ ["posthog.schedules.W001", "posthog.schedules.W001"],+ ),+ (+ "temporal_tls_pair_complete",+ {"TEMPORAL_CLIENT_CERT": "cert", "TEMPORAL_CLIENT_KEY": "key"},+ check_temporal_client_tls,+ [],+ ),+ (+ "temporal_tls_key_missing",+ {"TEMPORAL_CLIENT_CERT": "cert", "TEMPORAL_CLIENT_KEY": None},+ check_temporal_client_tls,+ ["posthog.temporal.W001"],+ ),+ ]+ )+ def test_warns_only_on_a_bad_value(self, _name, overrides, check, expected_ids) -> None:+ with override_settings(**overrides):+ assert [message.id for message in check(None)] == expected_idsdiff --git a/posthog/utils.py b/posthog/utils.pyindex d73158793dfe..7038255cf427 100644--- a/posthog/utils.py+++ b/posthog/utils.py@@ -2363,19 +2363,24 @@ def cast_timestamp_or_now(timestamp: Optional[Union[datetime.datetime, str]]) ->return timestamp.strftime("%Y-%m-%d %H:%M:%S.%f")+def parse_crontab(schedule: str) -> crontab:+ """Parse a five-field cron string. Raises for a wrong field count or an invalid field."""+ minute, hour, day_of_month, month_of_year, day_of_week = schedule.strip().split(" ")+ return crontab(+ minute=minute,+ hour=hour,+ day_of_month=day_of_month,+ month_of_year=month_of_year,+ day_of_week=day_of_week,+ )++def get_crontab(schedule: Optional[str]) -> Optional[crontab]:if schedule is None or schedule == "":return Nonetry:- minute, hour, day_of_month, month_of_year, day_of_week = schedule.strip().split(" ")- return crontab(- minute=minute,- hour=hour,- day_of_month=day_of_month,- month_of_year=month_of_year,- day_of_week=day_of_week,- )+ return parse_crontab(schedule)except Exception as err:capture_exception(err)return None