Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 19 additions & 5 deletions gateway/platforms/webhook.py
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,20 @@ def _is_loopback_host(host: Optional[str]) -> bool:
return host.strip().lower() in _LOOPBACK_HOSTS


def _hmac_str_equal(provided: str, expected: str) -> bool:
"""Timing-safe equality for two ``str`` values, tolerant of non-ASCII input.

``hmac.compare_digest`` raises ``TypeError`` when given a ``str`` that
contains non-ASCII characters. The ``provided`` value here is an
attacker-controlled signature/token header on a public, unauthenticated
webhook endpoint, so a single non-ASCII byte would otherwise raise out of
the request handler and return a 500 instead of rejecting the request.
Comparing as UTF-8 bytes keeps the constant-time guarantee while making a
hostile header fail closed with a clean rejection.
"""
return hmac.compare_digest(provided.encode(), expected.encode())


def check_webhook_requirements() -> bool:
"""Check if webhook adapter dependencies are available."""
return AIOHTTP_AVAILABLE
Expand Down Expand Up @@ -969,12 +983,12 @@ def _header(name: str) -> str:
expected = "sha256=" + hmac.new(
secret.encode(), body, hashlib.sha256
).hexdigest()
return hmac.compare_digest(gh_sig, expected)
return _hmac_str_equal(gh_sig, expected)

# GitLab: X-Gitlab-Token = <plain secret>
gl_token = request.headers.get("X-Gitlab-Token", "")
if gl_token:
return hmac.compare_digest(gl_token, secret)
return _hmac_str_equal(gl_token, secret)

# Generic V2: X-Webhook-Signature-V2 = <hex HMAC-SHA256 of "<timestamp>.<body>">
# X-Webhook-Timestamp = <unix seconds> (required for V2)
Expand Down Expand Up @@ -1017,7 +1031,7 @@ def _header(name: str) -> str:
expected_v2 = hmac.new(
secret.encode(), signed_content, hashlib.sha256
).hexdigest()
return hmac.compare_digest(v2_sig, expected_v2)
return _hmac_str_equal(v2_sig, expected_v2)

# Generic V1 (legacy): X-Webhook-Signature = <hex HMAC-SHA256 of body>
# (deprecated — no replay protection, since the signature only
Expand All @@ -1041,7 +1055,7 @@ def _header(name: str) -> str:
"'<timestamp>.<body>').",
route_name,
)
return hmac.compare_digest(generic_sig, expected)
return _hmac_str_equal(generic_sig, expected)

# No recognised signature header but secret is configured → reject
logger.debug(
Expand Down Expand Up @@ -1095,7 +1109,7 @@ def _validate_svix_signature(
version, signature = part.split(",", 1)
except ValueError:
continue
if version == "v1" and hmac.compare_digest(signature, expected):
if version == "v1" and _hmac_str_equal(signature, expected):
return True
return False

Expand Down
46 changes: 46 additions & 0 deletions tests/gateway/test_webhook_adapter.py
Original file line number Diff line number Diff line change
Expand Up @@ -166,6 +166,52 @@ def test_validate_no_signature_with_secret_rejects(self):
req = _mock_request(headers={}) # no sig headers at all
assert adapter._validate_signature(req, b"{}", "my-secret") is False

def test_non_ascii_signature_headers_reject_without_raising(self):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This covers GitHub, GitLab, generic V1, and generic V2, but the patch also changes the Svix v1 comparison. Please add a non-ASCII svix-signature case with valid svix-id and timestamp so that branch is regression-tested too.

"""The signature headers are attacker-controlled on a public, unauth
endpoint. A non-ASCII byte in one must be rejected (False), not crash
the handler: hmac.compare_digest raises TypeError on a non-ASCII str."""
adapter = _make_adapter()
body = b'{"action": "opened"}'
secret = "webhook-secret-42"
hostile = "ské-not-a-valid-signature"
for header in (
"X-Hub-Signature-256",
"X-Gitlab-Token",
"X-Webhook-Signature",
):
req = _mock_request(headers={header: hostile})
# Must return False, never raise.
assert adapter._validate_signature(req, body, secret) is False

def test_non_ascii_generic_v2_signature_rejected(self):
"""V2 branch (timestamp-bound) also rejects a non-ASCII signature."""
adapter = _make_adapter()
req = _mock_request(headers={
"X-Webhook-Signature-V2": "ské-bad",
"X-Webhook-Timestamp": str(int(time.time())),
})
assert adapter._validate_signature(req, b"{}", "secret") is False

def test_non_ascii_svix_signature_rejected(self):
"""The Svix branch also runs its `v1,<sig>` comparison through the
hardened helper: a valid svix-id + fresh timestamp reaches the compare,
and a non-ASCII signature must reject rather than raise."""
adapter = _make_adapter()
req = _mock_request(headers={
"svix-id": "msg_2xabc",
"svix-timestamp": str(int(time.time())), # inside the replay window
"svix-signature": "v1,ské-not-a-valid-base64-sig",
})
assert adapter._validate_signature(req, b'{"x":1}', "shh-secret") is False

def test_non_ascii_secret_still_validates_a_matching_token(self):
"""A non-ASCII configured secret must still match its exact GitLab
token value byte for byte (bytes comparison keeps this working)."""
adapter = _make_adapter()
secret = "gl-tökén-välue"
req = _mock_request(headers={"X-Gitlab-Token": secret})
assert adapter._validate_signature(req, b"{}", secret) is True

def test_validate_no_secret_allows_all(self):
"""When the secret is empty/falsy, the validator is never even called
by the handler (secret check is 'if secret and secret != _INSECURE...').
Expand Down
Loading