: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(ai-research): serve the web bot auth key directory (#83235)
Robbiec952d7f1f9c4
diff --git a/docs/internal/web-bot-auth-key-directory.md b/docs/internal/web-bot-auth-key-directory.mdnew file mode 100644index 000000000000..a5429af271e5--- /dev/null+++ b/docs/internal/web-bot-auth-key-directory.md@@ -0,0 +1,17 @@+# Web Bot Auth key directory++PostHog Cloud US serves the Web Bot Auth key directory at `/.well-known/http-message-signatures-directory`.+The directory publishes the public keys for `PostHogSessionReplayBot` and signs each response with the corresponding private keys.++## Configuration++Set `WEB_BOT_AUTH_PRIVATE_KEYS` to a comma-separated list of unencrypted Ed25519 private keys in PKCS8 PEM format.+Encode PEM line breaks as literal `\n` sequences when the secret store requires a single-line value.+During key rotation, include the old and new keys until consumers have accepted the new key.++Leave the variable unset outside PostHog Cloud US.+The endpoint returns `404` when the variable is unset or the deployment is not in the US region.++When the variable is present, each production ASGI worker schedules validation on a daemon thread during lifespan startup.+An empty or invalid value does not stop startup.+PostHog Error Tracking receives a sanitized configuration error, and the endpoint returns `503` without exposing key material.diff --git a/owners.yaml b/owners.yamlindex 2934d70544b5..9c93e447720c 100644--- a/owners.yaml+++ b/owners.yaml@@ -87,6 +87,13 @@ rules:owners: team-data-stack- match: '/posthog/settings/email.py'owners: team-platform-features+ - match:+ - '/docs/internal/web-bot-auth-key-directory.md'+ - '/posthog/settings/web_bot_auth.py'+ - '/posthog/test/test_web_bot_auth.py'+ - '/posthog/web_bot_auth.py'+ - '/posthog/web_bot_auth_keys.py'+ owners: ai-research- match: '/posthog/test/test_feature_flag_analytics.py'owners: team-feature-flags- match: '/services/llm-gateway/'diff --git a/posthog/asgi.py b/posthog/asgi.pyindex 397ff30b415d..93a7980694db 100644--- a/posthog/asgi.py+++ b/posthog/asgi.py@@ -115,6 +115,12 @@ def lifetime_wrapper(func):message_type = message.get("type")if message_type == "lifespan.startup":+ if settings.WEB_BOT_AUTH_PRIVATE_KEYS_ENV_VAR_PRESENT:+ from posthog.web_bot_auth_keys import ( # noqa: PLC0415+ validate_configured_web_bot_auth_private_keys_in_background,+ )++ validate_configured_web_bot_auth_private_keys_in_background()# No-op unless PREWARM_WAREHOUSE_SOURCE_REGISTRY is set; never raises,# so a broken catalog can't fail startup and trigger a respawn loop.prewarm_warehouse_source_registry()diff --git a/posthog/settings/__init__.py b/posthog/settings/__init__.pyindex fc9056f2a34c..4a5170638b10 100644--- a/posthog/settings/__init__.py+++ b/posthog/settings/__init__.py@@ -44,6 +44,7 @@ from posthog.settings.statsd import *from posthog.settings.object_storage import *from posthog.settings.temporal import *from posthog.settings.web import *+from posthog.settings.web_bot_auth import *from posthog.settings.data_warehouse import *from posthog.settings.managed_migrations import *from posthog.settings.session_replay import *diff --git a/posthog/settings/web_bot_auth.py b/posthog/settings/web_bot_auth.pynew file mode 100644index 000000000000..bf5074659064--- /dev/null+++ b/posthog/settings/web_bot_auth.py@@ -0,0 +1,7 @@+import os++from posthog.settings.utils import get_list++# US-only, PEM, multiple keys allowed (comma-separated)+WEB_BOT_AUTH_PRIVATE_KEYS_ENV_VAR_PRESENT = "WEB_BOT_AUTH_PRIVATE_KEYS" in os.environ+WEB_BOT_AUTH_PRIVATE_KEYS = get_list(os.getenv("WEB_BOT_AUTH_PRIVATE_KEYS", ""))diff --git a/posthog/test/test_asgi_lifespan.py b/posthog/test/test_asgi_lifespan.pyindex 2665dae9cd25..d53b8f9f3b01 100644--- a/posthog/test/test_asgi_lifespan.py+++ b/posthog/test/test_asgi_lifespan.py@@ -137,6 +137,20 @@ async def test_lifespan_startup_skips_source_registry_prewarm_when_disabled() ->assert driver.sent == [{"type": "lifespan.startup.complete"}, {"type": "lifespan.shutdown.complete"}]+async def test_lifespan_startup_schedules_web_bot_auth_key_validation() -> None:+ driver = _LifespanDriver([{"type": "lifespan.startup"}, {"type": "lifespan.shutdown"}])++ with override_settings(WEB_BOT_AUTH_PRIVATE_KEYS_ENV_VAR_PRESENT=True):+ with mock.patch(+ "posthog.web_bot_auth_keys.validate_configured_web_bot_auth_private_keys_in_background"+ ) as validate_keys:+ await driver.run()++ validate_keys.assert_called_once_with()+ assert driver.sent == [{"type": "lifespan.startup.complete"}, {"type": "lifespan.shutdown.complete"}]++@pytest.mark.asyncioasync def test_lifespan_startup_prewarms_source_registry_before_reporting_ready() -> None:driver = _LifespanDriver([{"type": "lifespan.startup"}, {"type": "lifespan.shutdown"}])diff --git a/posthog/test/test_web_bot_auth.py b/posthog/test/test_web_bot_auth.pynew file mode 100644index 000000000000..3dcc3942bdae--- /dev/null+++ b/posthog/test/test_web_bot_auth.py@@ -0,0 +1,236 @@+import json+import base64+import hashlib++import pytest+from unittest.mock import patch++from django.test import Client, override_settings++from cryptography.exceptions import InvalidSignature+from cryptography.hazmat.primitives import serialization+from cryptography.hazmat.primitives.asymmetric import ec+from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey+from posthoganalytics.contexts import get_capture_exception_code_variables_context++from posthog.web_bot_auth import CONTENT_TYPE, jwk_thumbprint, public_jwk, signature_base, signed_directory+from posthog.web_bot_auth_keys import (+ WebBotAuthPrivateKeyConfigurationError,+ load_web_bot_auth_private_key_configuration,+ validate_web_bot_auth_private_keys_in_background,+)++PEM = (+ Ed25519PrivateKey.generate()+ .private_bytes(+ encoding=serialization.Encoding.PEM,+ format=serialization.PrivateFormat.PKCS8,+ encryption_algorithm=serialization.NoEncryption(),+ )+ .decode()+)+NON_ED25519_PEM = (+ ec.generate_private_key(ec.SECP256R1())+ .private_bytes(+ encoding=serialization.Encoding.PEM,+ format=serialization.PrivateFormat.PKCS8,+ encryption_algorithm=serialization.NoEncryption(),+ )+ .decode()+)+++def dictionary_member(header: str, label: str) -> str:+ return next(member.removeprefix(f"{label}=") for member in header.split(", ") if member.startswith(f"{label}="))+++def verify_at(authority: str, headers: dict[str, str], key: Ed25519PrivateKey, label: str = "sig1") -> bool:+ params = dictionary_member(headers["Signature-Input"], label)+ base = (+ f'"@authority";req: {authority}\n"content-digest": {headers["Content-Digest"]}\n"@signature-params": {params}'+ )+ signature = base64.b64decode(dictionary_member(headers["Signature"], label).removeprefix(":").removesuffix(":"))+ try:+ key.public_key().verify(signature, base.encode())+ except InvalidSignature:+ return False+ return True+++def test_thumbprint_matches_the_rfc_8037_vector():+ # A thumbprint over the wrong members, or with spaces in the JSON, produces a keyid that no+ # verifier can match to the published key, and nothing else in the response looks wrong.+ jwk = {"kty": "OKP", "crv": "Ed25519", "x": "11qYAYKxCrfVS_7TyWQHOg7hcvPapiMlrwIaaPcHURo"}++ assert jwk_thumbprint(jwk) == "kPrK_qmxVWaYVA9wwBF6Iuo3vVzz7TxHCTwXBygrS4k"+++def test_the_directory_names_the_key_it_is_signed_with():+ key = serialization.load_pem_private_key(PEM.encode(), password=None)+ assert isinstance(key, Ed25519PrivateKey)++ body, headers = signed_directory([key], 1750105829, "AAAA")++ assert json.loads(body)["keys"] == [public_jwk(key)]+ assert f'keyid="{jwk_thumbprint(public_jwk(key))}"' in headers["Signature-Input"]+++ "authority,expected",+ [("us.posthog.com", True), ("evil.example", False), ("posthog.com", False)],+)+def test_the_signature_only_verifies_at_the_authority_it_covers(authority: str, expected: bool):+ # This is the whole point of signing the directory. If the signature verified wherever the+ # response was served, any site that proxies this route would hold a directory that verifies on+ # that site while carrying our key, and could register as its operator.+ key = serialization.load_pem_private_key(PEM.encode(), password=None)+ assert isinstance(key, Ed25519PrivateKey)++ _, headers = signed_directory([key], 1750105829, "AAAA")++ assert verify_at(authority, headers, key) is expected+++def test_the_signature_covers_the_parameters_it_publishes():+ # The base and the header are built together for this reason: a mismatch in one character makes+ # every signature fail verification while both halves look correct on their own.+ signature_base_value = signature_base("thumb", "AAAA", 1750105829, "sha-256=:AAAA:")++ assert signature_base_value.value.endswith(f'"@signature-params": {signature_base_value.parameters}')+ assert signature_base_value.parameters.startswith('("@authority";req "content-digest")')+ assert 'tag="http-message-signatures-directory"' in signature_base_value.parameters+ assert "expires=1750106129" in signature_base_value.parameters+++def test_the_signature_covers_the_directory_content():+ key = serialization.load_pem_private_key(PEM.encode(), password=None)+ assert isinstance(key, Ed25519PrivateKey)++ body, headers = signed_directory([key], 1750105829, "AAAA")+ expected_digest = f"sha-256=:{base64.b64encode(hashlib.sha256(body.encode()).digest()).decode()}:"++ assert headers["Content-Digest"] == expected_digest+ assert verify_at("us.posthog.com", headers, key) is True+ assert verify_at("us.posthog.com", {**headers, "Content-Digest": "sha-256=:AAAA:"}, key) is False+++def test_the_directory_supports_overlapping_keys_during_rotation():+ keys = [Ed25519PrivateKey.generate(), Ed25519PrivateKey.generate()]++ body, headers = signed_directory(keys, 1750105829, "AAAA")++ assert json.loads(body)["keys"] == [public_jwk(key) for key in keys]+ assert verify_at("us.posthog.com", headers, keys[0], "sig1") is True+ assert verify_at("us.posthog.com", headers, keys[1], "sig2") is True+++@override_settings(WEB_BOT_AUTH_PRIVATE_KEYS=[PEM], CLOUD_DEPLOYMENT="US")+def test_the_route_serves_a_signed_directory():+ response = Client().get("/.well-known/http-message-signatures-directory")++ assert response.status_code == 200+ assert response["Content-Type"] == CONTENT_TYPE+ assert response["Cache-Control"] == "no-store"+ assert response["Content-Digest"].startswith("sha-256=:")+ assert response["Signature-Input"].startswith('sig1=("@authority";req "content-digest")')+ assert response["Signature"].startswith("sig1=:")+++@override_settings(WEB_BOT_AUTH_PRIVATE_KEYS=[PEM], ALLOWED_HOSTS=["*"], CLOUD_DEPLOYMENT="US")+def test_the_route_ignores_the_host_it_was_asked_on():+ # Reading the authority off the request looks harmless and is the change to guard against. A+ # signer that trusted the Host would hand any site proxying here a directory that verifies there.+ key = serialization.load_pem_private_key(PEM.encode(), password=None)+ assert isinstance(key, Ed25519PrivateKey)++ response = Client().get("/.well-known/http-message-signatures-directory", HTTP_HOST="evil.example")++ headers = {+ "Content-Digest": response["Content-Digest"],+ "Signature-Input": response["Signature-Input"],+ "Signature": response["Signature"],+ }+ assert verify_at("us.posthog.com", headers, key) is True+ assert verify_at("evil.example", headers, key) is False+++@override_settings(WEB_BOT_AUTH_PRIVATE_KEYS=[], CLOUD_DEPLOYMENT="US")+def test_the_route_is_absent_where_no_key_is_configured():+ # Self-hosted holds no key. A 500 there would read as a broken deployment.+ assert Client().get("/.well-known/http-message-signatures-directory").status_code == 404+++ "configured_keys,expected_error_message",+ [+ pytest.param([], "is present but contains no keys", id="empty"),+ pytest.param(["not a PEM"], "entry 1 could not be loaded (ValueError)", id="malformed-pem"),+ pytest.param([NON_ED25519_PEM], "entry 1 is not an Ed25519 private key", id="non-ed25519-key"),+ pytest.param(+ [PEM, "not a PEM"],+ "entry 2 could not be loaded (ValueError)",+ id="mixed-valid-and-invalid-keys",+ ),+ ],+)+def test_invalid_key_configuration_is_rejected(configured_keys: list[str], expected_error_message: str) -> None:+ configuration = load_web_bot_auth_private_key_configuration(+ tuple(configured_keys),+ require_at_least_one=True,+ )++ assert configuration.private_keys == ()+ assert configuration.validation_error is not None+ assert expected_error_message in str(configuration.validation_error)+++@override_settings(CLOUD_DEPLOYMENT="US")+def test_flattened_private_key_configuration_is_supported() -> None:+ with override_settings(WEB_BOT_AUTH_PRIVATE_KEYS=[PEM.replace("\n", "\\n")]):+ response = Client().get("/.well-known/http-message-signatures-directory")++ assert response.status_code == 200++[email protected]("configured_keys", [[], ["not a PEM"]], ids=["empty", "malformed-pem"])+@override_settings(WEB_BOT_AUTH_PRIVATE_KEYS_ENV_VAR_PRESENT=True, CLOUD_DEPLOYMENT="US")+def test_the_route_is_unavailable_when_key_configuration_is_invalid(configured_keys: list[str]) -> None:+ with override_settings(WEB_BOT_AUTH_PRIVATE_KEYS=configured_keys):+ assert Client().get("/.well-known/http-message-signatures-directory").status_code == 503+++def test_startup_validation_reports_invalid_configuration() -> None:+ code_variable_capture_settings: list[bool | None] = []++ def record_capture_exception_context(*args: object, **kwargs: object) -> None:+ code_variable_capture_settings.append(get_capture_exception_code_variables_context())++ with (+ patch(+ "posthog.exceptions_capture.capture_exception",+ side_effect=record_capture_exception_context,+ ) as capture_exception,+ patch("posthog.utils.safe_cache_add", return_value=True),+ ):+ validation_thread = validate_web_bot_auth_private_keys_in_background(("not a PEM",))+ validation_thread.join(timeout=2)++ assert validation_thread.daemon is True+ assert validation_thread.is_alive() is False+ capture_exception.assert_called_once()+ captured_error = capture_exception.call_args.args[0]+ assert isinstance(captured_error, WebBotAuthPrivateKeyConfigurationError)+ assert captured_error.__traceback__ is None+ assert code_variable_capture_settings == [False]+ assert capture_exception.call_args.kwargs["additional_properties"] == {+ "component": "web_bot_auth_key_directory",+ "configured_key_count": 1,+ "setting": "WEB_BOT_AUTH_PRIVATE_KEYS",+ }++[email protected]("region", ["EU", "DEV", None])+@override_settings(WEB_BOT_AUTH_PRIVATE_KEYS=[PEM])+def test_the_route_is_absent_outside_the_us(region: str | None):+ with override_settings(CLOUD_DEPLOYMENT=region):+ assert Client().get("/.well-known/http-message-signatures-directory").status_code == 404diff --git a/posthog/urls.py b/posthog/urls.pyindex 9f5d4b88c2b2..8f23249c744c 100644--- a/posthog/urls.py+++ b/posthog/urls.py@@ -47,6 +47,7 @@ from posthog.models import Userfrom posthog.models.instance_setting import get_instance_settingfrom posthog.oauth2_urls import urlpatterns as oauth2_urlsfrom posthog.temporal.codec_server import decode_payloads+from posthog.web_bot_auth import http_message_signatures_directoryfrom products.ai_observability.backend.api.personal_spend import PersonalSpendEUProxyViewSetfrom products.canvas.backend.artifacts import canvas_artifact@@ -672,6 +673,7 @@ urlpatterns = [opt_slash_path("report", report.get_csp_event), # CSP violation reportsopt_slash_path("robots.txt", robots_txt),opt_slash_path(".well-known/security.txt", security_txt),+ opt_slash_path(".well-known/http-message-signatures-directory", http_message_signatures_directory),# authopt_slash_path("logout", authentication.logout, name="logout"),path(diff --git a/posthog/web_bot_auth.py b/posthog/web_bot_auth.pynew file mode 100644index 000000000000..b6dd7e576466--- /dev/null+++ b/posthog/web_bot_auth.py@@ -0,0 +1,121 @@+import json+import time+import base64+import hashlib+import secrets+from collections.abc import Sequence++from django.conf import settings+from django.http import HttpRequest, HttpResponse, HttpResponseNotFound++from cryptography.hazmat.primitives import serialization+from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey++from posthog.dataclasses import frozen+from posthog.web_bot_auth_keys import load_web_bot_auth_private_key_configuration++CONTENT_TYPE = "application/http-message-signatures-directory+json"+_TAG = "http-message-signatures-directory"+_SIGNATURE_LIFETIME_SECONDS = 300++# Signed as a constant, never read from the request. The signature covers the authority, so a signer+# that signed whichever Host it was handed would give any site proxying this route a directory that+# verifies on that site while carrying our key. Preventing exactly that is what this signature is for.+#+# This is the origin the bot names in Signature-Agent, and it is us.posthog.com rather than+# posthog.com because Vercel reserves /.well-known and will not rewrite it, so posthog.com cannot+# serve a response it computes per request.+_AUTHORITY = "us.posthog.com"+++@frozen+class SignatureBase:+ parameters: str+ value: str+++def public_jwk(key: Ed25519PrivateKey) -> dict[str, str]:+ raw = key.public_key().public_bytes(serialization.Encoding.Raw, serialization.PublicFormat.Raw)+ return {"kty": "OKP", "crv": "Ed25519", "x": base64.urlsafe_b64encode(raw).decode().rstrip("=")}+++def jwk_thumbprint(jwk: dict[str, str]) -> str:+ """RFC 7638, over the required members only. RFC 8037 appendix A.3 fixes those for Ed25519."""+ canonical = json.dumps({"crv": jwk["crv"], "kty": jwk["kty"], "x": jwk["x"]}, separators=(",", ":"))+ return base64.urlsafe_b64encode(hashlib.sha256(canonical.encode()).digest()).decode().rstrip("=")+++def signature_base(keyid: str, nonce: str, created_at_seconds: int, content_digest: str) -> SignatureBase:+ """+ RFC 9421 section 2.5. Returns the parameters alongside the base, because Signature-Input must+ repeat them byte for byte and building them twice invites the two copies to differ.+ """+ params = (+ f'("@authority";req "content-digest");alg="ed25519";keyid="{keyid}";nonce="{nonce}";'+ f'tag="{_TAG}";created={created_at_seconds};expires={created_at_seconds + _SIGNATURE_LIFETIME_SECONDS}'+ )+ return SignatureBase(+ parameters=params,+ value=f'"@authority";req: {_AUTHORITY}\n"content-digest": {content_digest}\n"@signature-params": {params}',+ )+++def signed_directory(+ keys: Sequence[Ed25519PrivateKey], created_at_seconds: int, nonce: str+) -> tuple[str, dict[str, str]]:+ jwks = [public_jwk(key) for key in keys]+ body = json.dumps({"keys": jwks})+ content_digest = f"sha-256=:{base64.b64encode(hashlib.sha256(body.encode()).digest()).decode()}:"+ signature_inputs: list[str] = []+ signatures: list[str] = []+ for index, (key, jwk) in enumerate(zip(keys, jwks, strict=True), start=1):+ label = f"sig{index}"+ signature_base_value = signature_base(jwk_thumbprint(jwk), nonce, created_at_seconds, content_digest)+ signature_inputs.append(f"{label}={signature_base_value.parameters}")+ signatures.append(f"{label}=:{base64.b64encode(key.sign(signature_base_value.value.encode())).decode()}:")+ return (+ body,+ {+ "Content-Type": CONTENT_TYPE,+ "Content-Digest": content_digest,+ "Signature-Input": ", ".join(signature_inputs),+ "Signature": ", ".join(signatures),+ # A cached copy outlives its own signature, so every reader must reach this view.+ "Cache-Control": "no-store",+ },+ )+++def http_message_signatures_directory(request: HttpRequest) -> HttpResponse:+ """+ The Web Bot Auth key directory for PostHogSessionReplayBot. A stored file cannot serve this:+ Cloudflare uses a key only when the response carries a signature made with that key, covering+ the authority asked for and expiring minutes later.++ https://developers.cloudflare.com/bots/reference/bot-verification/web-bot-auth/+ """+ # The signature covers _AUTHORITY, so only the US deployment can serve this directory.+ if (settings.CLOUD_DEPLOYMENT or "").upper() != "US":+ return HttpResponseNotFound()++ try:+ configuration = load_web_bot_auth_private_key_configuration(+ tuple(settings.WEB_BOT_AUTH_PRIVATE_KEYS),+ require_at_least_one=settings.WEB_BOT_AUTH_PRIVATE_KEYS_ENV_VAR_PRESENT,+ )+ except Exception:+ return HttpResponse(status=503)+ if configuration.validation_error is not None:+ return HttpResponse(status=503)+ if not configuration.private_keys:+ return HttpResponseNotFound()++ body, headers = signed_directory(+ configuration.private_keys,+ int(time.time()),+ base64.b64encode(secrets.token_bytes(32)).decode(),+ )+ response = HttpResponse(body, content_type=CONTENT_TYPE)+ for name, value in headers.items():+ response[name] = value+ return responsediff --git a/posthog/web_bot_auth_keys.py b/posthog/web_bot_auth_keys.pynew file mode 100644index 000000000000..18e3b8b6a3d9--- /dev/null+++ b/posthog/web_bot_auth_keys.py@@ -0,0 +1,123 @@+import hashlib+import threading+from dataclasses import field+from functools import lru_cache++from django.conf import settings++import structlog+import posthoganalytics+from cryptography.exceptions import UnsupportedAlgorithm+from cryptography.hazmat.primitives import serialization+from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey++from posthog.dataclasses import frozen++logger = structlog.get_logger(__name__)++_VALIDATION_ERROR_CAPTURE_TTL_SECONDS = 3600+++class WebBotAuthPrivateKeyConfigurationError(ValueError):+ pass+++@frozen+class WebBotAuthPrivateKeyConfiguration:+ private_keys: tuple[Ed25519PrivateKey, ...] = field(repr=False)+ validation_error: WebBotAuthPrivateKeyConfigurationError | None = field(default=None, repr=False)+++@lru_cache(maxsize=1)+def load_web_bot_auth_private_key_configuration(+ private_key_pems: tuple[str, ...], *, require_at_least_one: bool+) -> WebBotAuthPrivateKeyConfiguration:+ if require_at_least_one and not private_key_pems:+ return WebBotAuthPrivateKeyConfiguration(+ private_keys=(),+ validation_error=WebBotAuthPrivateKeyConfigurationError(+ "WEB_BOT_AUTH_PRIVATE_KEYS is present but contains no keys"+ ),+ )++ private_keys: list[Ed25519PrivateKey] = []+ for key_index, private_key_pem in enumerate(private_key_pems, start=1):+ try:+ private_key = serialization.load_pem_private_key(+ private_key_pem.replace("\\n", "\n").encode(), password=None+ )+ except (TypeError, ValueError, UnsupportedAlgorithm) as error:+ return WebBotAuthPrivateKeyConfiguration(+ private_keys=(),+ validation_error=WebBotAuthPrivateKeyConfigurationError(+ f"WEB_BOT_AUTH_PRIVATE_KEYS entry {key_index} could not be loaded ({type(error).__name__})"+ ),+ )+ if not isinstance(private_key, Ed25519PrivateKey):+ return WebBotAuthPrivateKeyConfiguration(+ private_keys=(),+ validation_error=WebBotAuthPrivateKeyConfigurationError(+ f"WEB_BOT_AUTH_PRIVATE_KEYS entry {key_index} is not an Ed25519 private key"+ ),+ )+ private_keys.append(private_key)++ return WebBotAuthPrivateKeyConfiguration(private_keys=tuple(private_keys))+++def _validate_and_capture_web_bot_auth_private_key_configuration(private_key_pems: tuple[str, ...]) -> None:+ try:+ configuration = load_web_bot_auth_private_key_configuration(private_key_pems, require_at_least_one=True)+ if configuration.validation_error is None:+ return+ validation_error = configuration.validation_error+ except Exception as error:+ validation_error = WebBotAuthPrivateKeyConfigurationError(+ f"WEB_BOT_AUTH_PRIVATE_KEYS could not be validated ({type(error).__name__})"+ )++ try:+ from posthog.exceptions_capture import capture_exception # noqa: PLC0415+ from posthog.utils import safe_cache_add # noqa: PLC0415++ validation_error_digest = hashlib.sha256(str(validation_error).encode()).hexdigest()+ if not safe_cache_add(+ f"web_bot_auth_private_key_validation_error:{validation_error_digest}",+ True,+ timeout=_VALIDATION_ERROR_CAPTURE_TTL_SECONDS,+ ):+ return++ with posthoganalytics.new_context():+ posthoganalytics.set_capture_exception_code_variables_context(False)+ capture_exception(+ validation_error,+ additional_properties={+ "component": "web_bot_auth_key_directory",+ "configured_key_count": len(private_key_pems),+ "setting": "WEB_BOT_AUTH_PRIVATE_KEYS",+ },+ )+ except Exception:+ logger.exception("web_bot_auth_private_key_validation_capture_failed")+++def validate_web_bot_auth_private_keys_in_background(private_key_pems: tuple[str, ...]) -> threading.Thread:+ thread = threading.Thread(+ target=_validate_and_capture_web_bot_auth_private_key_configuration,+ args=(private_key_pems,),+ name="validate-web-bot-auth-private-keys",+ daemon=True,+ )+ thread.start()+ return thread+++def validate_configured_web_bot_auth_private_keys_in_background() -> threading.Thread | None:+ if not settings.WEB_BOT_AUTH_PRIVATE_KEYS_ENV_VAR_PRESENT:+ return None+ try:+ return validate_web_bot_auth_private_keys_in_background(tuple(settings.WEB_BOT_AUTH_PRIVATE_KEYS))+ except Exception:+ logger.exception("web_bot_auth_private_key_validation_scheduling_failed")+ return None