From f580c35cd2066f56440118c2d238f0c9e6d5022e Mon Sep 17 00:00:00 2001 From: Dylan Frankcom Date: Fri, 1 Nov 2024 16:20:19 -0400 Subject: [PATCH] #188481396 : Use ipaddress package to test valid IPV6 addresses (#36) * Use ipaddress package to test valid IPV6, bump ver * Standardize return type --- moesifasgi/client_ip.py | 16 ++++++---------- moesifasgi/middleware.py | 4 ++-- setup.py | 2 +- 3 files changed, 9 insertions(+), 13 deletions(-) diff --git a/moesifasgi/client_ip.py b/moesifasgi/client_ip.py index 29c3ad0..9c87acc 100644 --- a/moesifasgi/client_ip.py +++ b/moesifasgi/client_ip.py @@ -1,6 +1,6 @@ import re - import logging +import ipaddress logger = logging.getLogger(__name__) @@ -12,16 +12,12 @@ def __init__(self): @classmethod def is_ip(cls, value): + # https://docs.python.org/3/library/ipaddress.html#ipaddress.ip_address try: - if not value is None: - ipv4 = r"^(?:(?:\d|[1-9]\d|1\d{2}|2[0-4]\d|25[0-5])\.){3}(?:\d|[1-9]\d|1\d{2}|2[0-4]\d|25[0-5])$" - ipv6 = r"^((?=.*::)(?!.*::.+::)(::)?([\dA-F]{1,4}:(:|\b)|){5}|([\dA-F]{1,4}:){6})((([\dA-F]{1,4}((?!\3)::|:\b|$))|(?!\2\3)){2}|(((2[0-4]|1\d|[1-9])?\d|25[0-5])\.?\b){4})$/i" - return re.match(ipv4, value) or re.match(ipv6, value) - except: - # Ignore any error - pass - - return None + ip = ipaddress.ip_address(value) + return True + except ValueError: + return False def getClientIpFromXForwardedFor(self, value, debug = False): try: diff --git a/moesifasgi/middleware.py b/moesifasgi/middleware.py index 2c15083..2d44f5d 100644 --- a/moesifasgi/middleware.py +++ b/moesifasgi/middleware.py @@ -29,7 +29,7 @@ class MoesifMiddleware(BaseHTTPMiddleware): """ASGI Middleware for recording of request-response""" def __init__(self, settings=None, *args, **kwargs): super().__init__(*args, **kwargs) - + if settings is None: raise Exception('Moesif Application ID is required in settings') self.settings = settings @@ -88,7 +88,7 @@ def schedule_config_job(self): def initialize_config(self): Configuration.BASE_URI = self.settings.get("BASE_URI", "https://api.moesif.net") - Configuration.version = 'moesifasgi-python/1.0.9' + Configuration.version = 'moesifasgi-python/1.0.10' self.LOG_BODY = self.settings.get("LOG_BODY", True) self.app_config = AppConfig() diff --git a/setup.py b/setup.py index c0f13d9..9611408 100644 --- a/setup.py +++ b/setup.py @@ -28,7 +28,7 @@ # Versions should comply with PEP440. For a discussion on single-sourcing # the version across setup.py and the project code, see # https://packaging.python.org/en/latest/single_source_version.html - version='1.0.9', + version='1.0.10', description='Moesif Middleware for Python ASGI based platforms (FastAPI & Others)', long_description=long_description,