From ac1d798a36491fdd75068d94eecfea6665f8f43d Mon Sep 17 00:00:00 2001 From: Arksine Date: Sun, 15 Nov 2020 17:13:21 -0500 Subject: [PATCH] authorization: Add wildcards to cors_domians option Signed-off-by: Eric Callahan --- moonraker/authorization.py | 23 ++++++++++++++--------- moonraker/websockets.py | 9 +++------ 2 files changed, 17 insertions(+), 15 deletions(-) diff --git a/moonraker/authorization.py b/moonraker/authorization.py index 808fc36..4c85e9a 100644 --- a/moonraker/authorization.py +++ b/moonraker/authorization.py @@ -8,6 +8,7 @@ import uuid import os import time import ipaddress +import re import logging import tornado from tornado.ioloop import IOLoop, PeriodicCallback @@ -28,8 +29,8 @@ class Authorization: # Get allowed cors domains cors_cfg = config.get('cors_domains', "").strip() - self.cors_domains = [d.strip() for d in cors_cfg.split('\n') - if d.strip()] + self.cors_domains = [d.strip().replace(".", "\\.").replace("*", ".*") + for d in cors_cfg.split('\n')if d.strip()] # Get Trusted Clients self.trusted_ips = [] @@ -182,14 +183,18 @@ class Authorization: return False def check_cors(self, origin, request=None): - if origin in self.cors_domains: - logging.debug(f"CORS Domain Allowed: {origin}") - self._set_cors_headers(origin, request) - elif "*" in self.cors_domains: - self._set_cors_headers("*", request) - else: + if origin is None: return False - return True + for regex in self.cors_domains: + match = re.match(regex, origin) + if match is not None and match.group() == origin: + logging.debug(f"CORS Pattern Matched, origin: {origin} " + f" | pattern: {regex}") + self._set_cors_headers(origin, request) + return True + else: + logging.debug(f"No CORS match for origin: {origin}") + return False def _set_cors_headers(self, origin, request): if request is None: diff --git a/moonraker/websockets.py b/moonraker/websockets.py index 4e4f2fa..aa467e7 100644 --- a/moonraker/websockets.py +++ b/moonraker/websockets.py @@ -315,12 +315,9 @@ class WebSocket(WebSocketHandler): io_loop.spawn_callback(self.wsm.remove_websocket, self) def check_origin(self, origin): - if self.auth.check_cors(origin): - # allow CORS - return True - else: - return super(WebSocket, self).check_origin(origin) - + if not super(WebSocket, self).check_origin(origin): + return self.auth.check_cors(origin) + return True # Check Authorized User def prepare(self): if not self.auth.check_authorized(self.request):