Repository Public
1# =============================================================================2# SP BOUCHER | INFRASTRUCTURE & AUTOMATION3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# Project : MacLustr Identity7# File : sdk/python/tests/test_webhook.py8# Module : sdk9# Repository : https://git.spboucher.ai/maclustr-identity10# Project Website : https://identity.spboucher.ai11# Created : 2026-12-0112# Last Modified : 2026-12-0113#14# Author : Simon-Pierre Boucher15# Position : Professor of Finance16# Institution : Université du Québec en Outaouais (UQO)17# Organization : SP Boucher18# Website : https://spboucher.ai19# Git : https://git.spboucher.ai20#21# Preferred Contact: admin@spboucher.ai22# Technical Contact: dev@spboucher.ai23# Security/Admin : admin@spboucher.ai24#25# Copyright (c) 202626# Simon-Pierre Boucher27# All rights reserved where applicable. This file is governed by the28# applicable project license, copyright notices and relevant law.29# Existing third-party rights and notices remain unaffected.30#31# License : None specified (no license file in this repository)32#33# Do not embed credentials, private keys, access tokens,34# certificates or confidential personal information.35#36# =============================================================================37# END OF SP BOUCHER SOURCE HEADER38# =============================================================================3940import hashlib41import hmac42import json43import time4445import pytest4647from maclustr_identity import Event, SignatureVerificationError, Verification, VerificationSession, Webhook4849SECRET = "whsec_test_secret"50VER = {"verification_id": "ver_1", "object": "verification", "session_id": "vs_1", "status": "verified", "assurance_level": "sandbox_simulated",51 "method": "document_review", "verification_policy": "identity_document_face_v1", "policy_version": "1.0", "livemode": False, "simulated": True,52 "external_user_id": "user_1", "reasons": [{"code": "simulated", "message": {"fr": "x", "en": "y"}}], "dimensions": {}, "decision_engine": "risk-1.0",53 "created_at": "2026-12-01T09:00:00-05:00", "verified_at": "2026-12-01T09:00:00-05:00", "expires_at": "2027-12-01T09:00:00-05:00", "revoked_at": None,54 "personal_data_deleted_at": None, "a_future_field": 1}55BODY = json.dumps({"id": "evt_1", "object": "event", "type": "verification.verified", "api_version": "2026-12-01", "created": 1, "livemode": False,56 "data": {"object": VER}}, separators=(",", ":")).encode()575859def ref(secret: str, t: int, body: bytes) -> str:60 return hmac.new(secret.encode(), f"{t}.".encode() + body, hashlib.sha256).hexdigest()616263def header(secret: str = SECRET, t: int | None = None, body: bytes = BODY) -> str:64 t = int(time.time()) if t is None else t65 return f"t={t},v1={ref(secret, t, body)}"666768def code(exc: pytest.ExceptionInfo) -> str:69 return exc.value.code707172def test_valid_signature_returns_typed_event():73 event = Webhook.construct_event(BODY, header(), SECRET)74 assert isinstance(event, Event) and event.id == "evt_1" and event.type == "verification.verified"75 assert isinstance(event.object, Verification) and event.verification is event.object and event.session is None76 assert event.verification.verification_id == "ver_1" and event.verification.external_user_id == "user_1"77 assert event.verification.reasons[0].code == "simulated" and event.verification.is_valid78 assert event.verification.raw["a_future_field"] == 1 and event.raw["api_version"] == "2026-12-01"798081def test_session_events_carry_a_session():82 sess = {"id": "vs_1", "object": "verification_session", "status": "created", "livemode": False, "external_user_id": None, "purpose": "p",83 "verification_policy": "identity_document_v1", "policy_version": "1.0", "locale": "fr-CA", "return_url": None, "method": None, "metadata": {},84 "verification_id": None, "created_at": "2026-12-01T09:00:00-05:00", "expires_at": "2026-12-01T10:00:00-05:00", "completed_at": None}85 body = json.dumps({"id": "evt_2", "object": "event", "type": "verification.created", "api_version": "x", "created": 1, "livemode": False, "data": {"object": sess}})86 event = Webhook.construct_event(body, header(body=body.encode()), SECRET)87 assert isinstance(event.session, VerificationSession) and event.verification is None and event.session.status == "created"888990def test_sign_matches_reference_and_accepts_str_and_bytes():91 assert Webhook.sign(BODY, SECRET, 1700000000) == f"t=1700000000,v1={ref(SECRET, 1700000000, BODY)}"92 assert Webhook.construct_event(BODY.decode(), header(), SECRET).id == "evt_1"93 assert Webhook.construct_event(bytearray(BODY), header(), SECRET).id == "evt_1"949596def test_tampered_body_and_wrong_secret_are_rejected():97 with pytest.raises(SignatureVerificationError) as e:98 Webhook.construct_event(BODY + b" ", header(), SECRET)99 assert code(e) == "signature_mismatch"100 with pytest.raises(SignatureVerificationError) as e:101 Webhook.construct_event(BODY, header("whsec_other"), SECRET)102 assert code(e) == "signature_mismatch"103104105def test_expired_and_future_timestamps_are_rejected():106 old = int(time.time()) - 301107 with pytest.raises(SignatureVerificationError) as e:108 Webhook.construct_event(BODY, header(t=old), SECRET)109 assert code(e) == "signature_expired"110 assert Webhook.construct_event(BODY, header(t=old), SECRET, tolerance=600).id == "evt_1"111 with pytest.raises(SignatureVerificationError) as e:112 Webhook.verify_signature(BODY, header(t=int(time.time()) + 1000), SECRET)113 assert code(e) == "signature_expired"114115116def test_rotation_accepts_either_secret():117 t = int(time.time())118 h = f"t={t},v1={ref('whsec_new', t, BODY)},v1={ref('whsec_old', t, BODY)}"119 assert Webhook.construct_event(BODY, h, "whsec_new").id == "evt_1"120 assert Webhook.construct_event(BODY, h, "whsec_old").id == "evt_1"121 with pytest.raises(SignatureVerificationError):122 Webhook.construct_event(BODY, h, "whsec_unrelated")123124125@pytest.mark.parametrize("h", [None, "", "garbage", "t=abc,v1=00", f"t={int(time.time())}", "v1=" + "0" * 64, "t=١٢٣,v1=aa"])126def test_malformed_headers_are_rejected(h):127 with pytest.raises(SignatureVerificationError) as e:128 Webhook.construct_event(BODY, h, SECRET)129 assert code(e) == "signature_header_invalid"130131132def test_header_parsing_and_non_ascii_candidates():133 assert Webhook.parse_header("t=12, v1=aa ,v1=bb,v0=cc") == (12, ["aa", "bb"])134 with pytest.raises(SignatureVerificationError) as e:135 Webhook.construct_event(BODY, f"t={int(time.time())},v1=é", SECRET)136 assert code(e) == "signature_mismatch"137138139def test_parsed_object_and_non_event_payloads_are_rejected():140 with pytest.raises(SignatureVerificationError) as e:141 Webhook.construct_event(json.loads(BODY), header(), SECRET) # type: ignore[arg-type]142 assert code(e) == "payload_not_raw"143 with pytest.raises(SignatureVerificationError) as e:144 Webhook.construct_event(b"[]", header(body=b"[]"), SECRET)145 assert code(e) == "payload_invalid"146 with pytest.raises(SignatureVerificationError) as e:147 Webhook.construct_event(BODY, header(), "")148 assert code(e) == "secret_missing"149150151def test_partial_and_extended_payloads_do_not_raise():152 """An object with missing or extra fields still parses: missing fields are None, extra ones stay in raw."""153 body = json.dumps({"id": "evt_3", "object": "event", "type": "verification.verified",154 "data": {"object": {"object": "verification", "verification_id": "ver_3", "status": "verified", "brand_new": True}}}).encode()155 event = Webhook.construct_event(body, header(body=body), SECRET)156 v = event.verification157 assert v is not None and v.verification_id == "ver_3" and v.session_id is None and v.created_at is None and v.reasons == []158 assert v.raw["brand_new"] is True and v.is_valid and event.created == 0159160161def test_cancelled_event_carries_a_session_and_unknown_events_never_raise():162 sess = {"id": "vs_1", "object": "verification_session", "status": "cancelled", "livemode": False, "verification_id": None, "a_future_field": 1}163 body = json.dumps({"id": "evt_c", "object": "event", "type": "verification.cancelled", "api_version": "2026-12-01", "created": 5, "livemode": False,164 "data": {"object": sess}}).encode()165 e = Webhook.construct_event(body, header(body=body), SECRET)166 assert e.type == "verification.cancelled" and e.session is not None and e.session.status == "cancelled" and e.verification is None167 assert e.session_ended_without_decision and e.session.raw["a_future_field"] == 1168 expired = json.dumps({"id": "evt_e", "object": "event", "type": "verification.expired", "data": {"object": {**sess, "status": "expired"}}}).encode()169 assert Webhook.construct_event(expired, header(body=expired), SECRET).session_ended_without_decision170 future = json.dumps({"id": "evt_f", "object": "event", "type": "verification.something_new", "created": "soon", "data": {"object": {"object": "something_else", "k": 1}}, "extra": 1}).encode()171 f = Webhook.construct_event(future, header(body=future), SECRET)172 assert f.type == "verification.something_new" and f.session is None and f.verification is None and f.object == {"object": "something_else", "k": 1}173 assert f.created == 0 and not f.session_ended_without_decision174 bare = json.dumps({"id": "evt_b", "object": "event", "type": "x", "data": None}).encode()175 b = Webhook.construct_event(bare, header(body=bare), SECRET)176 assert b.object == {} and b.session is None and b.verification is None177 assert not Webhook.construct_event(BODY, header(), SECRET).session_ended_without_decision178 inconclusive = {**VER, "status": "inconclusive", "reasons": [{"code": "review_not_completed", "message": {"fr": "a", "en": "b"}}], "dimensions": {"document": {"status": "pass"}}}179 body = json.dumps({"id": "evt_i", "object": "event", "type": "verification.inconclusive", "data": {"object": inconclusive}}).encode()180 i = Webhook.construct_event(body, header(body=body), SECRET)181 assert i.verification.reason_codes == ["review_not_completed"] and not i.verification.is_valid and "score" not in i.verification.dimensions["document"]182