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.

chore(ai-research): correct web bot auth bot name (#86941)

Robbiea8f477d81470
diff --git a/docs/internal/web-bot-auth-key-directory.md b/docs/internal/web-bot-auth-key-directory.md
index 11f7790ddb2e..d8b071c1046f 100644
--- a/docs/internal/web-bot-auth-key-directory.md
+++ b/docs/internal/web-bot-auth-key-directory.md
@@ -1,7 +1,7 @@
# 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.
+The directory publishes the public keys for `PostHogImageFetcherBot` and signs each response with the corresponding private keys.
## Configuration
@@ -14,7 +14,9 @@ Move the new key to the first position after consumers have accepted it, then re
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.
+When the variable is present, each web worker schedules validation on a daemon thread.
+ASGI workers schedule validation during lifespan startup.
+WSGI workers schedule validation during the first post-fork request, which includes readiness probes.
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/posthog/test/test_web_bot_auth.py b/posthog/test/test_web_bot_auth.py
index 3dcc3942bdae..f1c5931fd2d5 100644
--- a/posthog/test/test_web_bot_auth.py
+++ b/posthog/test/test_web_bot_auth.py
@@ -130,7 +130,7 @@ def test_the_route_serves_a_signed_directory():
assert response.status_code == 200
assert response["Content-Type"] == CONTENT_TYPE
- assert response["Cache-Control"] == "no-store"
+ assert response["Cache-Control"] == "public, max-age=240"
assert response["Content-Digest"].startswith("sha-256=:")
assert response["Signature-Input"].startswith('sig1=("@authority";req "content-digest")')
assert response["Signature"].startswith("sig1=:")
@@ -229,6 +229,24 @@ def test_startup_validation_reports_invalid_configuration() -> None:
}
+def test_startup_validation_reports_unexpected_loader_errors() -> None:
+ with (
+ patch(
+ "posthog.web_bot_auth_keys.load_web_bot_auth_private_key_configuration",
+ side_effect=RuntimeError("loader failed"),
+ ),
+ patch("posthog.exceptions_capture.capture_exception") as capture_exception,
+ patch("posthog.utils.safe_cache_add", return_value=True),
+ ):
+ validation_thread = validate_web_bot_auth_private_keys_in_background((PEM,))
+ validation_thread.join(timeout=2)
+
+ capture_exception.assert_called_once()
+ captured_error = capture_exception.call_args.args[0]
+ assert isinstance(captured_error, WebBotAuthPrivateKeyConfigurationError)
+ assert str(captured_error) == "WEB_BOT_AUTH_PRIVATE_KEYS could not be validated (RuntimeError)"
+
+
@pytest.mark.parametrize("region", ["EU", "DEV", None])
@override_settings(WEB_BOT_AUTH_PRIVATE_KEYS=[PEM])
def test_the_route_is_absent_outside_the_us(region: str | None):
diff --git a/posthog/web_bot_auth.py b/posthog/web_bot_auth.py
index b6dd7e576466..774d8f206650 100644
--- a/posthog/web_bot_auth.py
+++ b/posthog/web_bot_auth.py
@@ -17,14 +17,17 @@ from posthog.web_bot_auth_keys import load_web_bot_auth_private_key_configuratio
CONTENT_TYPE = "application/http-message-signatures-directory+json"
_TAG = "http-message-signatures-directory"
_SIGNATURE_LIFETIME_SECONDS = 300
+_CACHE_MAX_AGE_SECONDS = 240
-# 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.
+# Covering @authority prevents cross-authority signature replay. Keep its value constant so this
+# endpoint cannot act as a confused deputy and sign a directory for a requester-controlled domain.
+# Otherwise, another site could proxy this route and receive a directory that verifies for its
+# domain but contains our public key.
#
-# 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.
+# PostHog normally hosts public identity metadata on the root posthog.com domain. Web Bot Auth is an
+# exception because its directory response needs a cryptographic signature with creation and
+# expiration timestamps. The root domain runs on Vercel, which only serves static files under
+# /.well-known, so Signature-Agent points to this Django app at us.posthog.com.
_AUTHORITY = "us.posthog.com"
@@ -40,15 +43,15 @@ def public_jwk(key: Ed25519PrivateKey) -> dict[str, str]:
def jwk_thumbprint(jwk: dict[str, str]) -> str:
- """RFC 7638, over the required members only. RFC 8037 appendix A.3 fixes those for Ed25519."""
+ """RFC 7638 requires only these members. RFC 8037, appendix A.3, defines them 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.
+ RFC 9421 section 2.5 defines this signature base. Signature-Input must repeat the parameter bytes,
+ so this function returns the parameters with the base.
"""
params = (
f'("@authority";req "content-digest");alg="ed25519";keyid="{keyid}";nonce="{nonce}";'
@@ -80,17 +83,15 @@ def signed_directory(
"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",
+ "Cache-Control": f"public, max-age={_CACHE_MAX_AGE_SECONDS}",
},
)
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.
+ Cloudflare uses the PostHogImageFetcherBot public key only if the corresponding private key signs
+ this directory response. The signature covers the requested authority and expires after five minutes.
https://developers.cloudflare.com/bots/reference/bot-verification/web-bot-auth/
"""
diff --git a/posthog/wsgi.py b/posthog/wsgi.py
index ebde2d35e2f6..ea42fdde9943 100644
--- a/posthog/wsgi.py
+++ b/posthog/wsgi.py
@@ -18,6 +18,7 @@ from posthog.caching.redis_cluster_connection_factory import prewarm_query_cache
from posthog.continuous_profiling import start_continuous_profiling
from posthog.otel_instrumentation import initialize_otel
from posthog.warehouse_source_prewarm import prewarm_warehouse_source_registry
+from posthog.web_bot_auth_keys import validate_configured_web_bot_auth_private_keys_in_background
from posthog.web_memory_probe import install_memory_probe_handler
from posthog.web_memory_sampler import start_web_memory_sampler
@@ -104,6 +105,7 @@ def application(environ, start_response):
global _prewarmed
if not _prewarmed:
prewarm_query_cache_cluster_in_background()
+ validate_configured_web_bot_auth_private_keys_in_background()
# Start the RSS sampler post-fork, here in the worker. Unit forks workers from a
# prototype that already imported this module, and a thread started pre-fork does
# not survive into the worker — starting it on the worker's first call samples the