A more robust logic to detect the webserver local bind address

This commit is contained in:
Fabio Manganiello 2022-09-30 03:10:37 +02:00
parent 3ed10092ae
commit 82ab7face2
Signed by untrusted user: blacklight
GPG key ID: D90FBA7F76362774

View file

@ -35,13 +35,15 @@ def logger():
'format': '%(asctime)-15s|%(levelname)5s|%(name)s|%(message)s', 'format': '%(asctime)-15s|%(levelname)5s|%(name)s|%(message)s',
} }
level = (Config.get('backend.http') or {}).get('logging') or \ level = (Config.get('backend.http') or {}).get('logging') or (
(Config.get('logging') or {}).get('level') Config.get('logging') or {}
).get('level')
filename = (Config.get('backend.http') or {}).get('filename') filename = (Config.get('backend.http') or {}).get('filename')
if level: if level:
log_args['level'] = getattr(logging, level.upper()) \ log_args['level'] = (
if isinstance(level, str) else level getattr(logging, level.upper()) if isinstance(level, str) else level
)
if filename: if filename:
log_args['filename'] = filename log_args['filename'] = filename
@ -65,6 +67,7 @@ def get_message_response(msg):
# noinspection PyProtectedMember # noinspection PyProtectedMember
def get_http_port(): def get_http_port():
from platypush.backend.http import HttpBackend from platypush.backend.http import HttpBackend
http_conf = Config.get('backend.http') http_conf = Config.get('backend.http')
return http_conf.get('port', HttpBackend._DEFAULT_HTTP_PORT) return http_conf.get('port', HttpBackend._DEFAULT_HTTP_PORT)
@ -72,6 +75,7 @@ def get_http_port():
# noinspection PyProtectedMember # noinspection PyProtectedMember
def get_websocket_port(): def get_websocket_port():
from platypush.backend.http import HttpBackend from platypush.backend.http import HttpBackend
http_conf = Config.get('backend.http') http_conf = Config.get('backend.http')
return http_conf.get('websocket_port', HttpBackend._DEFAULT_WEBSOCKET_PORT) return http_conf.get('websocket_port', HttpBackend._DEFAULT_WEBSOCKET_PORT)
@ -89,17 +93,13 @@ def send_message(msg, wait_for_response=True):
if isinstance(msg, Request) and wait_for_response: if isinstance(msg, Request) and wait_for_response:
response = get_message_response(msg) response = get_message_response(msg)
logger().debug('Processing response on the HTTP backend: {}'. logger().debug('Processing response on the HTTP backend: {}'.format(response))
format(response))
return response return response
def send_request(action, wait_for_response=True, **kwargs): def send_request(action, wait_for_response=True, **kwargs):
msg = { msg = {'type': 'request', 'action': action}
'type': 'request',
'action': action
}
if kwargs: if kwargs:
msg['args'] = kwargs msg['args'] = kwargs
@ -113,8 +113,10 @@ def _authenticate_token():
if 'X-Token' in request.headers: if 'X-Token' in request.headers:
user_token = request.headers['X-Token'] user_token = request.headers['X-Token']
elif 'Authorization' in request.headers and request.headers['Authorization'].startswith('Bearer '): elif 'Authorization' in request.headers and request.headers[
user_token = request.headers['Authorization'][len('Bearer '):] 'Authorization'
].startswith('Bearer '):
user_token = request.headers['Authorization'][7:]
elif 'token' in request.args: elif 'token' in request.args:
user_token = request.args.get('token') user_token = request.args.get('token')
else: else:
@ -176,7 +178,10 @@ def _authenticate_csrf_token():
if user is None: if user is None:
return False return False
return session.csrf_token is None or request.form.get('csrf_token') == session.csrf_token return (
session.csrf_token is None
or request.form.get('csrf_token') == session.csrf_token
)
def authenticate(redirect_page='', skip_auth_methods=None, check_csrf_token=False): def authenticate(redirect_page='', skip_auth_methods=None, check_csrf_token=False):
@ -208,7 +213,9 @@ def authenticate(redirect_page='', skip_auth_methods=None, check_csrf_token=Fals
if session_auth_ok: if session_auth_ok:
return f(*args, **kwargs) return f(*args, **kwargs)
return redirect('/login?redirect=' + (redirect_page or request.url), 307) return redirect(
'/login?redirect=' + (redirect_page or request.url), 307
)
# CSRF token check # CSRF token check
if check_csrf_token: if check_csrf_token:
@ -217,15 +224,22 @@ def authenticate(redirect_page='', skip_auth_methods=None, check_csrf_token=Fals
return abort(403, 'Invalid or missing csrf_token') return abort(403, 'Invalid or missing csrf_token')
if n_users == 0 and 'session' not in skip_methods: if n_users == 0 and 'session' not in skip_methods:
return redirect('/register?redirect=' + (redirect_page or request.url), 307) return redirect(
'/register?redirect=' + (redirect_page or request.url), 307
)
if ('http' not in skip_methods and http_auth_ok) or \ if (
('token' not in skip_methods and token_auth_ok) or \ ('http' not in skip_methods and http_auth_ok)
('session' not in skip_methods and session_auth_ok): or ('token' not in skip_methods and token_auth_ok)
or ('session' not in skip_methods and session_auth_ok)
):
return f(*args, **kwargs) return f(*args, **kwargs)
return Response('Authentication required', 401, return Response(
{'WWW-Authenticate': 'Basic realm="Login required"'}) 'Authentication required',
401,
{'WWW-Authenticate': 'Basic realm="Login required"'},
)
return wrapper return wrapper
@ -233,42 +247,57 @@ def authenticate(redirect_page='', skip_auth_methods=None, check_csrf_token=Fals
def get_routes(): def get_routes():
routes_dir = os.path.join( routes_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'routes')
os.path.dirname(os.path.abspath(__file__)), 'routes')
routes = [] routes = []
base_module = '.'.join(__name__.split('.')[:-1]) base_module = '.'.join(__name__.split('.')[:-1])
for path, dirs, files in os.walk(routes_dir): for path, _, files in os.walk(routes_dir):
for f in files: for f in files:
if f.endswith('.py'): if f.endswith('.py'):
mod_name = '.'.join( mod_name = '.'.join(
(base_module + '.' + os.path.join(path, f).replace( (
os.path.dirname(__file__), '')[1:].replace(os.sep, '.')).split('.') base_module
[:(-2 if f == '__init__.py' else -1)]) + '.'
+ os.path.join(path, f)
.replace(os.path.dirname(__file__), '')[1:]
.replace(os.sep, '.')
).split('.')[: (-2 if f == '__init__.py' else -1)]
)
try: try:
mod = importlib.import_module(mod_name) mod = importlib.import_module(mod_name)
if hasattr(mod, '__routes__'): if hasattr(mod, '__routes__'):
routes.extend(mod.__routes__) routes.extend(mod.__routes__)
except Exception as e: except Exception as e:
logger().warning('Could not import routes from {}/{}: {}: {}'. logger().warning(
format(path, f, type(e), str(e))) 'Could not import routes from {}/{}: {}: {}'.format(
path, f, type(e), str(e)
)
)
return routes return routes
def get_local_base_url(): def get_local_base_url():
http_conf = Config.get('backend.http') or {} http_conf = Config.get('backend.http') or {}
return '{proto}://localhost:{port}'.format( bind_address = http_conf.get('bind_address')
if not bind_address or bind_address == '0.0.0.0':
bind_address = 'localhost'
return '{proto}://{host}:{port}'.format(
proto=('https' if http_conf.get('ssl_cert') else 'http'), proto=('https' if http_conf.get('ssl_cert') else 'http'),
port=get_http_port()) host=bind_address,
port=get_http_port(),
)
def get_remote_base_url(): def get_remote_base_url():
http_conf = Config.get('backend.http') or {} http_conf = Config.get('backend.http') or {}
return '{proto}://{host}:{port}'.format( return '{proto}://{host}:{port}'.format(
proto=('https' if http_conf.get('ssl_cert') else 'http'), proto=('https' if http_conf.get('ssl_cert') else 'http'),
host=get_ip_or_hostname(), port=get_http_port()) host=get_ip_or_hostname(),
port=get_http_port(),
)
# vim:sw=4:ts=4:et: # vim:sw=4:ts=4:et: