diff --git a/app/middleware.py b/app/middleware.py index e765f3b..30bdd22 100644 --- a/app/middleware.py +++ b/app/middleware.py @@ -28,13 +28,15 @@ class PatchMalformedJsonMiddleware(BaseHTTPMiddleware): # try to fix json try: j = json.loads(body) - self.__fix_mac_address_list_length(j=j, size=1) + PatchMalformedJsonMiddleware.fix_mac_address_list_length(j=j, size=1) + PatchMalformedJsonMiddleware.fix_ip_address_list_length(j=j, size=1) except json.decoder.JSONDecodeError: logger.warning(f'Malformed json received! Try to fix it.') body = PatchMalformedJsonMiddleware.fix_json(body) logger.debug(f'Fixed JSON: "{body}"') j = json.loads(body) # ensure json is now valid - j = self.__fix_mac_address_list_length(j=j, size=1) + PatchMalformedJsonMiddleware.fix_mac_address_list_length(j=j, size=1) + PatchMalformedJsonMiddleware.fix_ip_address_list_length(j=j, size=1) # set new body request._body = json.dumps(j).encode('utf-8') @@ -42,7 +44,7 @@ class PatchMalformedJsonMiddleware(BaseHTTPMiddleware): return response @staticmethod - def __fix_mac_address_list_length(j: dict, size: int = 1) -> dict: + def fix_mac_address_list_length(j: dict, size: int = 1) -> dict: # reduce "mac_address_list" to environment = j.get('environment', {}) fingerprint = environment.get('fingerprint', {}) @@ -54,6 +56,18 @@ class PatchMalformedJsonMiddleware(BaseHTTPMiddleware): return j + @staticmethod + def fix_ip_address_list_length(j: dict, size: int = 1) -> dict: + # reduce "ip_address_list" to + environment = j.get('environment', {}) + ip_addresses = environment.get('ip_address_list', []) + + if len(ip_addresses) > 0: + logger.info(f'Transforming "ip_address_list" to length of {size}.') + j['environment']['ip_address_list'] = ip_addresses[:size] + + return j + @staticmethod def fix_json(s: str) -> str: s = s.replace('\t', '') diff --git a/test/main.py b/test/main.py index 8f2e2c7..f35f371 100644 --- a/test/main.py +++ b/test/main.py @@ -114,7 +114,21 @@ def test_auth_v1_origin_malformed_json(): # see oscar.krause/fastapi-dls#1 s = '{"environment": {"fingerprint": {"mac_address_list": [ff:ff:ff:ff:ff:ff"]}}' replaced = PatchMalformedJsonMiddleware.fix_json(s) assert replaced == '{"environment": {"fingerprint": {"mac_address_list": ["ff:ff:ff:ff:ff:ff"]}}' - + + +def test_auth_v1_origin_middleware(): # see oscar.krause/fastapi-dls#1 + import json + from middleware import PatchMalformedJsonMiddleware + + # test regex (temporary, until this section is merged into main.py + s = '{"environment": {"fingerprint": {"mac_address_list": ["aa:aa:aa:aa:aa:aa", "bb:bb:bb:bb:bb:bb"]}, "ip_address_list": ["127.0.0.1", "127.0.0.2"]}}' + j = json.loads(s) + PatchMalformedJsonMiddleware.fix_mac_address_list_length(j=j, size=1) + PatchMalformedJsonMiddleware.fix_ip_address_list_length(j=j, size=1) + s = json.dumps(j) + assert s == '{"environment": {"fingerprint": {"mac_address_list": ["aa:aa:aa:aa:aa:aa"]}, "ip_address_list": ["127.0.0.1"]}}' + + def auth_v1_origin_update(): payload = {