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(ingress): answer 503 when the secret read hits a dead connection (#102209)

posthog[bot]d76a2a725f48
diff --git a/posthog/ingress/test/test_verify.py b/posthog/ingress/test/test_verify.py
index eb039e5b85ac..16e7025090f5 100644
--- a/posthog/ingress/test/test_verify.py
+++ b/posthog/ingress/test/test_verify.py
@@ -6,6 +6,7 @@ from types import SimpleNamespace
from unittest.mock import patch
+from django.db import InterfaceError, OperationalError
from django.test import SimpleTestCase
import jwt
@@ -114,6 +115,32 @@ class TestHmacSha256(SimpleTestCase):
VerificationOutcome.NOT_CONFIGURED,
)
+ @parameterized.expand(
+ [
+ ("dropped_connection", OperationalError("server closed the connection unexpectedly")),
+ ("closed_connection", InterfaceError("connection already closed")),
+ ]
+ )
+ def test_a_database_failure_reading_the_secret_is_unavailable(self, _name: str, error: Exception) -> None:
+ def secret_getter() -> str:
+ raise error
+
+ scheme = HmacSha256(secret_getter=secret_getter, signature_header="X-Signature")
+
+ self.assertEqual(
+ scheme.verify(body=BODY, headers={"X-Signature": _digest().hex()}).outcome,
+ VerificationOutcome.UNAVAILABLE,
+ )
+
+ def test_any_other_failure_reading_the_secret_still_raises(self) -> None:
+ def secret_getter() -> str:
+ raise ValueError("boom")
+
+ scheme = HmacSha256(secret_getter=secret_getter, signature_header="X-Signature")
+
+ with self.assertRaises(ValueError):
+ scheme.verify(body=BODY, headers={"X-Signature": _digest().hex()})
+
def test_v0_timestamp_input_signs_timestamp_with_body(self) -> None:
timestamp = str(int(time.time()))
scheme = HmacSha256(
diff --git a/posthog/ingress/test/test_views.py b/posthog/ingress/test/test_views.py
index 7c65048bdf3a..019219068055 100644
--- a/posthog/ingress/test/test_views.py
+++ b/posthog/ingress/test/test_views.py
@@ -10,6 +10,7 @@ from unittest.mock import Mock, PropertyMock, patch
from django.core.cache import caches
from django.core.files.uploadedfile import SimpleUploadedFile
+from django.db import OperationalError
from django.http import HttpRequest
from django.test import RequestFactory, SimpleTestCase, override_settings
@@ -414,6 +415,23 @@ class TestWebhookView(SimpleTestCase):
self.assertEqual([call.kwargs["outcome"] for call in observe.call_args_list], ["verify_unavailable"])
self.dispatcher.dispatch.assert_not_called()
+ def test_a_database_failure_reading_the_secret_is_503_rather_than_an_unhandled_500(self) -> None:
+ body = json.dumps({"action": "opened"}).encode()
+ request = self._post(body, {"X-Hub-Signature-256": _github_signature(body), "X-GitHub-Event": "issues"})
+
+ with (
+ patch(
+ "posthog.ingress.github.provider.get_instance_setting",
+ side_effect=OperationalError("server closed the connection unexpectedly"),
+ ),
+ patch("posthog.ingress.views.observe_delivery") as observe,
+ ):
+ response = build_webhook_view(build_github_provider("posthog"))(request)
+
+ self.assertEqual(response.status_code, 503)
+ self.assertEqual([call.kwargs["outcome"] for call in observe.call_args_list], ["verify_unavailable"])
+ self.dispatcher.dispatch.assert_not_called()
+
def test_a_body_deliveries_refuses_is_400_and_reaches_no_consumer(self) -> None:
body = b'{"action":"opened"}'
request = self._post(body, {"X-Hub-Signature-256": _github_signature(body), "X-GitHub-Event": "push"})
diff --git a/posthog/ingress/verify/schemes.py b/posthog/ingress/verify/schemes.py
index 8b321a6da023..fad61fbac132 100644
--- a/posthog/ingress/verify/schemes.py
+++ b/posthog/ingress/verify/schemes.py
@@ -1,9 +1,9 @@
"""Signature schemes: the part of a provider incarnation that decides "this is really them".
-A scheme with a network step answers `UNAVAILABLE` when that step fails on transport rather than
-on the signature, because a fetch that never completed proves nothing about the caller. `BearerJwt`
-does this for a JWKS fetch failure, and `SnsSignature` for a signing certificate its verifier
-could not fetch.
+A scheme whose lookup step fails answers `UNAVAILABLE` rather than judging the signature, because
+a step that never completed proves nothing about the caller. `BearerJwt` does this for a JWKS
+fetch failure, `HmacSha256` for a secret read that the database refuses, and `SnsSignature` for
+a signing certificate its verifier could not fetch.
"""
import re
@@ -16,6 +16,8 @@ from dataclasses import field
from enum import StrEnum
from typing import Any, Literal, Protocol
+from django.db import DatabaseError, InterfaceError
+
import structlog
from posthog.dataclasses import frozen
@@ -166,12 +168,28 @@ class HmacSignature:
def rejects_headers(self, headers: Mapping[str, str]) -> bool:
# An unconfigured endpoint keeps answering NOT_CONFIGURED, whatever the headers carry.
- if not self.secret_getter():
+ try:
+ secret = self.secret_getter()
+ except (DatabaseError, InterfaceError):
+ # Leave a failed read to `_outcome`, which answers UNAVAILABLE for it.
+ return False
+ if not secret:
return False
return self._headers_fail(headers)
def _outcome(self, *, body: bytes, headers: Mapping[str, str]) -> VerificationOutcome:
- secret = self.secret_getter()
+ try:
+ secret = self.secret_getter()
+ except (DatabaseError, InterfaceError) as error:
+ # A getter that keeps its secret in Postgres reads it here, so a dropped connection
+ # leaves the signature unchecked. Letting the error out answers 500, which asks no
+ # sender to come back and leaves the lost delivery uncounted.
+ logger.warning(
+ "ingress_secret_unavailable",
+ signature_header=self.signature_header,
+ error_type=type(error).__name__,
+ )
+ return VerificationOutcome.UNAVAILABLE
if not secret:
return VerificationOutcome.NOT_CONFIGURED
if self._headers_fail(headers):