From 4ba4167d6a0facdbf17719b6cd0dc2dcfbb4081c Mon Sep 17 00:00:00 2001 From: khushal Date: Thu, 2 Jan 2025 13:35:31 +0000 Subject: [PATCH] (20250102) Origin-checking mechanism changed. --- wsio/finstitutions/trading/tick_out.py | 40 ++++++++++++++++++++++++-- 1 file changed, 38 insertions(+), 2 deletions(-) diff --git a/wsio/finstitutions/trading/tick_out.py b/wsio/finstitutions/trading/tick_out.py index 6516463..2ff3133 100644 --- a/wsio/finstitutions/trading/tick_out.py +++ b/wsio/finstitutions/trading/tick_out.py @@ -82,7 +82,7 @@ from icecream import IceCreamDebugger # Debugging: printer = IceCreamDebugger(prefix = "Tick-Out | ", includeContext = True) -printer.disable() +# printer.disable() # To make API calls: http_client = httpx.AsyncClient( @@ -122,7 +122,7 @@ EVENT_TICKS = "ticks" # For SocketIO: ALLOWED_ORIGINS = [] sio = socketio.AsyncServer( - cors_ALLOWED_ORIGINS = lambda x: any(regex.match(x, origin) for origin in ALLOWED_ORIGINS), + cors_allowed_origins = "*", async_mode = "asgi" ) app = socketio.ASGIApp(sio) @@ -149,6 +149,33 @@ FLAGS = { # ***************************************************************************************************************** +def origin_is_allowed(origin: str) -> bool: + + """ + To check if a given origin is in the allowed list. + :param origin: The origin of your request. + :return: True if allowed, else False. + """ + + # Start by assuming failure: + is_allowed = False + + # Check through all the allowed origins: + for allowed in ALLOWED_ORIGINS: + try: + if regex.match(origin, allowed): + is_allowed = True + break + except Exception as exception: + printer(exception) + + # Done here: + return is_allowed + + +# --------------------------------------------------------------------------------------------------------------------- + + async def send_ticks(ticks: List[dict]) -> None: """ @@ -375,6 +402,12 @@ async def on_connect(sid, environ, *args) -> bool: printer("SOCKET REJECTED: Init. pending.", sid) return False + # Check the origin of the incoming request: + origin = environ.get("HTTP_ORIGIN", "???") + if not origin_is_allowed(origin): + printer("SOCKET REJECTED: Bad origin.", sid, origin) + return False + # Get the session token from the incoming request: session_token = environ.get("HTTP_X_SESSION_TOKEN") if not session_token and len(args) > 0: session_token = args[0].get("X-Session-Token") @@ -440,6 +473,8 @@ async def handle_disconnect(sid, reason) -> None: if __name__ == "__main__": + printer("Main.") + # To get args from the terminal: import argparse @@ -497,3 +532,4 @@ if __name__ == "__main__": host = args.host, port = args.port ) +