: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(ingress): let the HMAC scheme take a digest (#103603)
Julian Bezc8357afb6ad1
diff --git a/posthog/ingress/README.md b/posthog/ingress/README.mdindex 116d75de6740..34521ae95806 100644--- a/posthog/ingress/README.md+++ b/posthog/ingress/README.md@@ -50,8 +50,9 @@ An HMAC over raw bytes proves only the signature, so its `facts` are empty and `## Schemes-`verify/schemes.py` holds `HmacSha256` and `SnsSignature`; `verify/jwt.py` holds `BearerJwt`, for a provider that authenticates with a signed token instead of a shared secret.+`verify/schemes.py` holds `HmacSignature` and `SnsSignature`; `verify/jwt.py` holds `BearerJwt`, for a provider that authenticates with a signed token instead of a shared secret.Each class docstring carries its own reasoning.+`HmacSha256` is `HmacSignature` with the default digest, and it is the name to reach for. Only a provider that signs with something else sets `digest`, and everything else about the scheme, `rejects_headers` included, behaves the same whichever digest it carries.A scheme also answers `rejects_headers(headers)`, the part of the check that needs no body: `HmacSha256` refuses a missing or malformed signature header and a missing, malformed or stale timestamp header there, and `BearerJwt` refuses a request that carries no bearer token. The answer is the same INVALID the full check would reach, with the same status, log line and metric outcome, so an unauthenticated caller cannot make an endpoint read a body of up to the request limit for it. A scheme that cannot decide from headers alone answers `False`, which is what `SnsSignature` does, and so does an HMAC scheme whose secret is unset, so an unconfigured endpoint still answers NOT_CONFIGURED.diff --git a/posthog/ingress/test/test_verify.py b/posthog/ingress/test/test_verify.pyindex e63d717cd8af..979fb225eb30 100644--- a/posthog/ingress/test/test_verify.py+++ b/posthog/ingress/test/test_verify.py@@ -14,14 +14,14 @@ from jwt.algorithms import RSAAlgorithmfrom parameterized import parameterizedfrom posthog.ingress.verify.jwt import _JWKS_CLIENTS, SIGNING_KEY_FACT, BearerJwt, _jwks_client-from posthog.ingress.verify.schemes import HmacSha256, SnsSignature, Verification, VerificationOutcome+from posthog.ingress.verify.schemes import HmacSha256, HmacSignature, SnsSignature, Verification, VerificationOutcomeSECRET = "s3cret"BODY = b'{"action":"opened"}'-def _digest(body: bytes = BODY, secret: str = SECRET) -> bytes:- return hmac.digest(secret.encode(), body, "sha256")+def _digest(body: bytes = BODY, secret: str = SECRET, digest: str = "sha256") -> bytes:+ return hmac.digest(secret.encode(), body, digest)class TestHmacSha256(SimpleTestCase):@@ -176,6 +176,56 @@ class TestHmacSha256(SimpleTestCase):scheme.verify(body=BODY, headers={"X-Signature": _digest().hex()})compare.assert_called_once()+ @parameterized.expand([("sha256", "sha256", "sha1"), ("sha1", "sha1", "sha256")])+ def test_the_declared_digest_is_the_one_that_verifies(self, _name: str, declared: str, other: str) -> None:+ scheme = HmacSignature(+ secret_getter=lambda: SECRET,+ signature_header="X-Signature",+ digest=declared, # type: ignore[arg-type]+ )++ self.assertEqual(+ scheme.verify(body=BODY, headers={"X-Signature": _digest(digest=declared).hex()}).outcome,+ VerificationOutcome.VERIFIED,+ )+ self.assertEqual(+ scheme.verify(body=BODY, headers={"X-Signature": _digest(digest=other).hex()}).outcome,+ VerificationOutcome.INVALID,+ )++ def test_the_sha256_name_cannot_be_handed_another_digest(self) -> None:+ named = HmacSha256(secret_getter=lambda: SECRET, signature_header="X-Signature")+ explicit = HmacSignature(secret_getter=lambda: SECRET, signature_header="X-Signature", digest="sha256")++ self.assertEqual(named.digest, explicit.digest)+ # A name that promises SHA-256 and hashes something else is the trap this closes.+ with self.assertRaises(TypeError):+ HmacSha256(secret_getter=lambda: SECRET, signature_header="X-Signature", digest="sha1")++ @parameterized.expand(+ [+ ("missing_header", {}, True),+ ("empty_header", {"X-Signature": ""}, True),+ ("malformed_header", {"X-Signature": "not-a-digest"}, True),+ ("well_formed", {"X-Signature": "0" * 40}, False),+ ]+ )+ def test_headers_alone_decide_the_same_way_for_every_digest(+ self, _name: str, headers: dict[str, str], expected: bool+ ) -> None:+ # A header gate that read the digest would let an unsigned probe make a SHA-1 endpoint+ # read a body of up to the request limit, which the SHA-256 one refuses.+ pattern = re.compile(r"^[0-9a-f]{40}$")+ for digest in ("sha256", "sha1"):+ with self.subTest(digest=digest):+ scheme = HmacSignature(+ secret_getter=lambda: SECRET,+ signature_header="X-Signature",+ signature_pattern=pattern,+ digest=digest,+ )+ self.assertEqual(scheme.rejects_headers(headers), expected)+class TestSnsSignature(SimpleTestCase):def setUp(self) -> None:diff --git a/posthog/ingress/verify/schemes.py b/posthog/ingress/verify/schemes.pyindex 33f769375ae9..c5ffdcba11b6 100644--- a/posthog/ingress/verify/schemes.py+++ b/posthog/ingress/verify/schemes.py@@ -23,6 +23,9 @@ logger = structlog.get_logger(__name__)SignedInput = Literal["body", "v0_timestamp_body"]SignatureEncoding = Literal["hex", "base64"]+# SHA-1 is on this list because one provider signs with it, not because it is a choice worth+# making for a new one. Reach for `HmacSha256` unless the provider leaves no option.+HmacDigest = Literal["sha256", "sha1"]class VerificationOutcome(StrEnum):@@ -64,18 +67,30 @@ def header_value(headers: Mapping[str, str], name: str) -> str | None:return None-def hmac_sha256_signature(+def hmac_signature(secret: str,signed: bytes,*,+ digest: HmacDigest = "sha256",encoding: SignatureEncoding = "hex",prefix: str = "",) -> str:- digest = hmac.digest(secret.encode("utf-8"), signed, "sha256")- encoded = base64.b64encode(digest).decode("ascii") if encoding == "base64" else digest.hex()+ computed = hmac.digest(secret.encode("utf-8"), signed, digest)+ encoded = base64.b64encode(computed).decode("ascii") if encoding == "base64" else computed.hex()return prefix + encoded+def hmac_sha256_signature(+ secret: str,+ signed: bytes,+ *,+ encoding: SignatureEncoding = "hex",+ prefix: str = "",+) -> str:+ """The SHA-256 form, which is what every caller of this module signs with."""+ return hmac_signature(secret, signed, digest="sha256", encoding=encoding, prefix=prefix)++def signatures_match(expected: str, provided: str) -> bool:# Compared as bytes, because compare_digest raises TypeError on a str that holds a# non-ASCII code point, and a header arrives here decoded as latin-1. An unauthenticated@@ -96,16 +111,19 @@ class SignatureScheme(Protocol):@frozen-class HmacSha256:- """HMAC-SHA256 over the raw body, in the shapes the providers here actually send.+class HmacSignature:+ """A keyed HMAC over the raw body, in the shapes the providers here actually send.GitHub sends ``sha256=<hex>``; Slack and Customer.io sign ``v0:{timestamp}:{body}``and pair the signature with a timestamp header they expect to be checked for replay.+ `digest` is the hash under the key, and only a provider that leaves no choice sets it+ to anything but the default."""secret_getter: Callable[[], str | None]signature_header: strprefix: str = ""+ digest: HmacDigest = "sha256"encoding: SignatureEncoding = "hex"signed_input: SignedInput = "body"timestamp_header: str | None = None@@ -129,7 +147,7 @@ class HmacSha256:return bodydef _expected_signature(self, secret: str, signed: bytes) -> str:- return hmac_sha256_signature(secret, signed, encoding=self.encoding, prefix=self.prefix)+ return hmac_signature(secret, signed, digest=self.digest, encoding=self.encoding, prefix=self.prefix)def _headers_fail(self, headers: Mapping[str, str]) -> bool:provided = header_value(headers, self.signature_header)@@ -172,6 +190,18 @@ class HmacSha256:return Verification(outcome=self._outcome(body=body, headers=headers))+@frozen+class HmacSha256(HmacSignature):+ """The SHA-256 form, and the name every provider but one reaches for.++ It exists so that "which digest" is a question only the provider that has to answer it+ ever sees. The digest is fixed here rather than defaulted, so a name that promises+ SHA-256 cannot be handed another one; `HmacSignature` is where a digest is chosen.+ """++ digest: HmacDigest = field(default="sha256", init=False)++@frozenclass SnsSignature:"""AWS SNS message signature plus a topic-ARN allowlist.