"""Run a synthetic recording webhook and download on loopback with standard Python.""" from base64 import b64encode from contextlib import ExitStack, closing from http.client import HTTPConnection from http.server import BaseHTTPRequestHandler, HTTPServer from io import BytesIO from pathlib import Path from secrets import token_hex from tempfile import TemporaryDirectory from threading import Thread from urllib.parse import parse_qsl, urlencode, urlsplit import hmac import re import sqlite3 import wave ACCOUNT = "ACsampleonly" OTHER_ACCOUNT = "ACothersample" CALL = "CAsamplehttp" EVENT = "recording.completed" CALLBACK_PATH = "/recording-webhook?demo=1" SAMPLE_RATE = 8000 FRAME_COUNT = 56000 def check(condition, message): if not condition: raise AssertionError(message) def signature(key, url, payload): data = url + "".join(name + value for name, value in sorted(payload.items())) return b64encode(hmac.digest(key, data.encode(), "sha256")).decode("ascii") def recording_path(account, call): return f"/v1/accounts/{account}/recordings/{call}" def request(url, method="GET", body=None, headers=None): address = urlsplit(url) check(address.scheme == "http" and address.hostname == "127.0.0.1" and address.port, "This example only requests loopback HTTP URLs") target = address.path + ("?" + address.query if address.query else "") # HTTPConnection uses no proxy and does not follow redirects. with closing(HTTPConnection("127.0.0.1", address.port, timeout=5)) as client: client.request(method, target, body=body, headers=headers or {}) with client.getresponse() as response: return response.status, response.headers, response.read() class Handler(BaseHTTPRequestHandler): def log_message(self, format, *args): pass def reply(self, status, body=b"", **headers): self.send_response(status) self.send_header("Content-Length", str(len(body))) for name, value in headers.items(): self.send_header(name, value) self.end_headers() if body: self.wfile.write(body) def listen(stack, handler): server = stack.enter_context(HTTPServer(("127.0.0.1", 0), handler)) thread = Thread(target=server.serve_forever, kwargs={"poll_interval": 0.05}) thread.start() stack.callback(thread.join) stack.callback(server.shutdown) return f"http://127.0.0.1:{server.server_port}" def main(): signing_key = token_hex(16).encode() owner_auth = f"Bearer {token_hex(16)}" other_auth = f"Bearer {token_hex(16)}" accounts = {owner_auth: ACCOUNT, other_auth: OTHER_ACCOUNT} media_path = f"/recording.wav?fixture={token_hex(16)}" storage_requests = [] frames = b"\x01\x00" * FRAME_COUNT buffer = BytesIO() with wave.open(buffer, "wb") as wav: wav.setparams((1, 2, SAMPLE_RATE, 0, "NONE", "not compressed")) wav.writeframes(frames) with ExitStack() as stack: database = Path(stack.enter_context(TemporaryDirectory())) / "crm.sqlite" with closing(sqlite3.connect(database)) as db, db: db.execute("""CREATE TABLE crm ( account_id TEXT, call_id TEXT, receipts INTEGER, PRIMARY KEY (account_id, call_id) )""") class Storage(Handler): def do_GET(self): storage_requests.append(self.headers.get("Authorization") is not None) if self.path != media_path or storage_requests[-1]: return self.reply(403) self.reply(200, buffer.getvalue(), **{"Content-Type": "audio/wav"}) media_url = listen(stack, Storage) + media_path class TelecomAndReceiver(Handler): def do_POST(self): if self.path != CALLBACK_PATH: return self.reply(404) length = self.headers.get("Content-Length", "") if not length.isdecimal() or len(length) > 4 or not 0 < int(length) <= 4096: return self.reply(400) if self.headers.get_content_type() != "application/x-www-form-urlencoded": return self.reply(400) try: pairs = parse_qsl(self.rfile.read(int(length)).decode(), keep_blank_values=True, strict_parsing=True) except ValueError: return self.reply(400) payload = dict(pairs) if len(payload) != len(pairs): return self.reply(400) supplied = self.headers.get("X-Signature", "").encode() expected = signature(signing_key, callback_url, payload).encode("ascii") if not hmac.compare_digest(supplied, expected): return self.reply(401) if (payload.get("AccountId"), payload.get("CallId"), payload.get("Event")) != (ACCOUNT, CALL, EVENT): return self.reply(403) with closing(sqlite3.connect(database)) as db, db: db.execute("""INSERT INTO crm VALUES (?, ?, 1) ON CONFLICT(account_id, call_id) DO UPDATE SET receipts = receipts + 1""", (payload["AccountId"], payload["CallId"])) receipts = db.execute("SELECT receipts FROM crm").fetchone()[0] # Fail the first response after the row is committed, then accept the retry. self.reply(503 if receipts == 1 else 204) def do_GET(self): path = re.fullmatch(r"/v1/accounts/([^/]+)/recordings/([^/?]+)", self.path) if path is None: return self.reply(404) account = accounts.get(self.headers.get("Authorization")) if account is None: return self.reply(401) requested_account, call = path.groups() if account != requested_account: return self.reply(403) if (account, call) != (ACCOUNT, CALL): return self.reply(404) # The loopback storage URL stands in for a signed cloud URL. self.reply(302, Location=media_url) api = listen(stack, TelecomAndReceiver) callback_url = api + CALLBACK_PATH payload = { "AccountId": ACCOUNT, "CallId": CALL, "Event": EVENT, "Direction": "inbound", "Timestamp": "2026-01-01T00:00:00Z", "From": "00000000000", "To": "07000000000", "RecordingUrl": api + recording_path(ACCOUNT, CALL), "DurationSec": "7", } headers = { "Content-Type": "application/x-www-form-urlencoded", "X-Signature": signature(signing_key, callback_url, payload), } tampered = urlencode({**payload, "DurationSec": "1"}) status, _, _ = request(callback_url, "POST", tampered, headers) check(status == 401, "Modified callback must fail signature verification") body = urlencode(payload) first, _, _ = request(callback_url, "POST", body, headers) retry, _, _ = request(callback_url, "POST", body, headers) check((first, retry) == (503, 204), "Expected one retry after a saved 503 response") with closing(sqlite3.connect(f"{database.as_uri()}?mode=ro", uri=True)) as db: rows = db.execute("SELECT account_id, call_id, receipts FROM crm").fetchall() check(rows == [(ACCOUNT, CALL, 2)], "The two signed deliveries must leave one CRM row") account, call, _ = rows[0] saved_url = api + recording_path(account, call) wrong, wrong_headers, _ = request(saved_url, headers={"Authorization": other_auth}) absent, absent_headers, _ = request(api + recording_path(OTHER_ACCOUNT, call), headers={"Authorization": other_auth}) check(wrong == 403 and absent == 404 and "Location" not in wrong_headers and "Location" not in absent_headers and not storage_requests, "Other-account requests must stop before the media request") redirect, redirect_headers, _ = request(saved_url, headers={"Authorization": owner_auth}) location = redirect_headers.get("Location") check(redirect == 302 and location == media_url and not storage_requests, "Expected the exact fixture Location without following it") status, media_headers, audio = request(location) check(status == 200 and media_headers.get_content_type() == "audio/wav" and storage_requests == [False], "WAV must arrive without a Bearer header on the media request") with wave.open(BytesIO(audio), "rb") as wav: check((wav.getnchannels(), wav.getsampwidth(), wav.getframerate(), wav.getnframes()) == (1, 2, SAMPLE_RATE, FRAME_COUNT), "Unexpected WAV format or frame count") check(wav.readframes(FRAME_COUNT) == frames, "Incomplete or changed PCM frames") print("PASS callback signature: 401 for changed payload, 503 then 204 for identical signed deliveries") print("PASS CRM: one saved row after two delivery attempts") print("PASS recording: other account 403/404, owner 302 then 200 with 56000 PCM frames") if __name__ == "__main__": main()