@@ -65,13 +65,15 @@ def create_webhook_signature(payload: Any, timestamp: str, secret: str) -> str:
65
65
Returns:
66
66
The HMAC-SHA256 signature as a hex string
67
67
"""
68
- # Sort keys and use compact JSON format (equivalent to fast-json-stable-stringify)
68
+
69
69
dump = json .dumps (payload , separators = ("," , ":" ), sort_keys = True )
70
70
message = f"{ timestamp } .{ dump } "
71
71
72
72
# Create HMAC-SHA256 signature
73
73
hmac_obj = hmac .new (secret .encode (), message .encode (), hashlib .sha256 )
74
- return hmac_obj .hexdigest ()
74
+ signature = hmac_obj .hexdigest ()
75
+
76
+ return signature
75
77
76
78
77
79
def verify_webhook_event_signature (
@@ -94,20 +96,20 @@ def verify_webhook_event_signature(
94
96
None if the signature is invalid, otherwise the parsed webhook event.
95
97
"""
96
98
try :
97
- # Parse body if it's a string
98
99
if isinstance (body , str ):
99
100
json_data = json .loads (body )
100
101
else :
101
102
json_data = body
102
103
103
- # Try to parse as each webhook type
104
+ # PARSE
105
+
104
106
webhook_event : Optional [Webhook ] = None
105
107
106
- # Try test webhook first
107
- try :
108
- webhook_event = WebhookTest (** json_data )
109
- except Exception :
110
- pass
108
+ if webhook_event is None :
109
+ try :
110
+ webhook_event = WebhookTest (** json_data )
111
+ except Exception :
112
+ pass
111
113
112
114
# Try agent task status update webhook
113
115
if webhook_event is None :
@@ -119,10 +121,12 @@ def verify_webhook_event_signature(
119
121
if webhook_event is None :
120
122
return None
121
123
122
- # Create expected signature
123
- expected_signature = create_webhook_signature (payload = webhook_event .payload , timestamp = timestamp , secret = secret )
124
+ # Verify
125
+
126
+ expected_signature = create_webhook_signature (
127
+ payload = webhook_event .payload .model_dump (), timestamp = timestamp , secret = secret
128
+ )
124
129
125
- # Compare signatures using timing-safe comparison
126
130
if not hmac .compare_digest (signature , expected_signature ):
127
131
return None
128
132
0 commit comments