From ca6fd457af4475441602ad29e46c3482a970d9a3 Mon Sep 17 00:00:00 2001 From: Joao Santos Date: Tue, 14 Nov 2023 12:03:20 -0300 Subject: [PATCH] handles a JSON body that isn't a SWML callback --- signalwire/request_validator.py | 10 ++++++++- signalwire/tests/test_request_validator.py | 26 ++++++++++++++++++++++ 2 files changed, 35 insertions(+), 1 deletion(-) diff --git a/signalwire/request_validator.py b/signalwire/request_validator.py index f7d1140..2021d39 100644 --- a/signalwire/request_validator.py +++ b/signalwire/request_validator.py @@ -1,5 +1,6 @@ import base64 import hmac +import json from hashlib import sha1 from urllib.parse import urlparse from twilio.request_validator import compare, remove_port, add_port, RequestValidator as TwilioRequestValidator @@ -42,6 +43,13 @@ def validate(self, uri, params, signature): signature ) - return valid_signature_without_port or valid_signature_with_port + if valid_signature_without_port or valid_signature_with_port: + return True + + try: + parsed_params = json.loads(params) + return self.validate_with_compatibility(uri, parsed_params, signature) + except json.JSONDecodeError as e: + return False return self.validate_with_compatibility(uri, params, signature) diff --git a/signalwire/tests/test_request_validator.py b/signalwire/tests/test_request_validator.py index 2daac22..1be2fe3 100644 --- a/signalwire/tests/test_request_validator.py +++ b/signalwire/tests/test_request_validator.py @@ -106,6 +106,32 @@ def test_should_validate_from_signalwire_https_request(self): valid = validator.validate(url, body, signature) self.assertTrue(valid) + def test_should_validate_from_raw_json(self): + from signalwire.request_validator import RequestValidator + + url = 'https://675d-189-71-169-171.ngrok-free.app/voice' + token = 'PSK_V3bF8oyeRNpJWGoRWHNYQMUU' + signature = 'muUMpldcBHlzuXGZ5gbw1ETZCYA=' + body = '''{ + "CallSid": "a97d4e8a-6047-4e2b-be48-fb96b33b5642", + "AccountSid": "6bfbbe86-a901-4197-8759-2a0de1fa319d", + "ApiVersion": "2010-04-01", + "Direction": "outbound-api", + "From": "sip:+17063958228@sip.swire.io", + "To": "sip:jpsantos@joaosantos-2a0de1fa319d.sip.swire.io", + "Timestamp": "Thu, 09 Nov 2023 14:40:55 +0000", + "CallStatus": "no-answer", + "CallbackSource": "call-progress-events", + "HangupDirection": "outbound", + "HangupBy": "sip:+17063958228@sip.swire.io", + "SipResultCode": "487" + }''' + + + validator = RequestValidator(token) + valid = validator.validate(url, body, signature) + self.assertTrue(valid) +