(20250102) Origin-checking mechanism changed.

This commit is contained in:
2025-01-02 13:35:31 +00:00
parent 6a8238e242
commit 4ba4167d6a
+38 -2
View File
@@ -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
)