removed "PatchMalformedJsonMiddleware" because its not working on driver site

ref. oscar.krause/fastapi-dls#1
This commit is contained in:
Oscar Krause 2024-12-02 08:37:01 +01:00
parent 991a35ef1a
commit ea8a66d449
5 changed files with 0 additions and 105 deletions

View File

@ -48,7 +48,6 @@ package() {
install -Dm755 "$srcdir/$pkgname/app/main.py" "$pkgdir/opt/$pkgname/main.py" install -Dm755 "$srcdir/$pkgname/app/main.py" "$pkgdir/opt/$pkgname/main.py"
install -Dm755 "$srcdir/$pkgname/app/orm.py" "$pkgdir/opt/$pkgname/orm.py" install -Dm755 "$srcdir/$pkgname/app/orm.py" "$pkgdir/opt/$pkgname/orm.py"
install -Dm755 "$srcdir/$pkgname/app/util.py" "$pkgdir/opt/$pkgname/util.py" install -Dm755 "$srcdir/$pkgname/app/util.py" "$pkgdir/opt/$pkgname/util.py"
install -Dm755 "$srcdir/$pkgname/app/middleware.py" "$pkgdir/opt/$pkgname/middleware.py"
install -Dm644 "$srcdir/$pkgname.default" "$pkgdir/etc/default/$pkgname" install -Dm644 "$srcdir/$pkgname.default" "$pkgdir/etc/default/$pkgname"
install -Dm644 "$srcdir/$pkgname.service" "$pkgdir/usr/lib/systemd/system/$pkgname.service" install -Dm644 "$srcdir/$pkgname.service" "$pkgdir/usr/lib/systemd/system/$pkgname.service"
install -Dm644 "$srcdir/$pkgname.tmpfiles" "$pkgdir/usr/lib/tmpfiles.d/$pkgname.conf" install -Dm644 "$srcdir/$pkgname.tmpfiles" "$pkgdir/usr/lib/tmpfiles.d/$pkgname.conf"

View File

@ -430,7 +430,6 @@ After first success you have to replace `--issue` with `--renew`.
| `ALLOTMENT_REF` | `20000000-0000-0000-0000-000000000001` | Allotment identification uuid | | `ALLOTMENT_REF` | `20000000-0000-0000-0000-000000000001` | Allotment identification uuid |
| `INSTANCE_KEY_RSA` | `<app-dir>/cert/instance.private.pem` | Site-wide private RSA key for singing JWTs \*3 | | `INSTANCE_KEY_RSA` | `<app-dir>/cert/instance.private.pem` | Site-wide private RSA key for singing JWTs \*3 |
| `INSTANCE_KEY_PUB` | `<app-dir>/cert/instance.public.pem` | Site-wide public key \*3 | | `INSTANCE_KEY_PUB` | `<app-dir>/cert/instance.public.pem` | Site-wide public key \*3 |
| `SUPPORT_MALFORMED_JSON` | `false` | Support parsing for mal formatted "mac_address_list" ([Issue](https://git.collinwebdesigns.de/oscar.krause/fastapi-dls/-/issues/1)) |
\*1 For example, if the lease period is one day and the renewal period is 20%, the client attempts to renew its license \*1 For example, if the lease period is one day and the renewal period is 20%, the client attempts to renew its license
every 4.8 hours. If network connectivity is lost, the loss of connectivity is detected during license renewal and the every 4.8 hours. If network connectivity is lost, the loss of connectivity is detected during license renewal and the

View File

@ -96,11 +96,6 @@ app.add_middleware(
allow_methods=['*'], allow_methods=['*'],
allow_headers=['*'], allow_headers=['*'],
) )
if bool(env('SUPPORT_MALFORMED_JSON', False)):
from middleware import PatchMalformedJsonMiddleware
logger.info(f'Enabled "PatchMalformedJsonMiddleware"!')
app.add_middleware(PatchMalformedJsonMiddleware, enabled=True)
# Helper # Helper

View File

@ -1,75 +0,0 @@
import json
import logging
import re
from starlette.middleware.base import BaseHTTPMiddleware
from starlette.requests import Request
logger = logging.getLogger(__name__)
class PatchMalformedJsonMiddleware(BaseHTTPMiddleware):
# see oscar.krause/fastapi-dls#1
REGEX = r'(\"mac_address_list\"\:\s?\[)([\w\d])'
def __init__(self, app, enabled: bool):
super().__init__(app)
self.enabled = enabled
async def dispatch(self, request: Request, call_next):
body = await request.body()
content_type = request.headers.get('Content-Type')
if self.enabled and content_type == 'application/json':
logger.debug(f'Using Request-Patch because "PatchMalformedJsonMiddleware" is enabled!')
body = body.decode()
# try to fix json
try:
j = json.loads(body)
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
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')
response = await call_next(request)
return response
@staticmethod
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', {})
mac_address = fingerprint.get('mac_address_list', [])
if len(mac_address) > 0:
logger.info(f'Transforming "mac_address_list" to length of {size}.')
j['environment']['fingerprint']['mac_address_list'] = mac_address[:size]
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', '')
s = s.replace('\n', '')
return re.sub(PatchMalformedJsonMiddleware.REGEX, r'\1"\2', s)

View File

@ -18,7 +18,6 @@ sys.path.append('../app')
from app import main from app import main
from app.util import load_key from app.util import load_key
# main.app.add_middleware(PatchMalformedJsonMiddleware, enabled=True)
client = TestClient(main.app) client = TestClient(main.app)
ORIGIN_REF, ALLOTMENT_REF, SECRET = str(uuid4()), '20000000-0000-0000-0000-000000000001', 'HelloWorld' ORIGIN_REF, ALLOTMENT_REF, SECRET = str(uuid4()), '20000000-0000-0000-0000-000000000001', 'HelloWorld'
@ -107,28 +106,6 @@ def test_auth_v1_origin():
assert response.json().get('origin_ref') == ORIGIN_REF assert response.json().get('origin_ref') == ORIGIN_REF
def test_auth_v1_origin_malformed_json(): # see oscar.krause/fastapi-dls#1
from middleware import PatchMalformedJsonMiddleware
# test regex (temporary, until this section is merged into main.py
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(): def auth_v1_origin_update():
payload = { payload = {