Files
mtusi2026lab7/security_middleware.py
T

34 lines
1.7 KiB
Python

"""Bound small non-upload request bodies before JSON parsing."""
import asyncio
import json
import uuid
class BodyGuard:
def __init__(self,app,instance_id):self.app=app;self.instance_id=instance_id
async def __call__(self,scope,receive,send):
if scope['type']!='http' or (scope['method']=='POST' and scope['path'].endswith('/attachments')):
return await self.app(scope,receive,send)
body=bytearray();status=None
try:
async with asyncio.timeout(10):
while True:
message=await receive()
if message['type']=='http.disconnect':return
body.extend(message.get('body',b''))
if len(body)>65536:status=413;break
if not message.get('more_body'):break
except TimeoutError:status=400
if status:
rid=uuid.uuid4().hex;code='payload_too_large' if status==413 else 'invalid_request'
payload=json.dumps({'error':{'code':code,'message':'request body limit exceeded','request_id':rid}}).encode()
await send({'type':'http.response.start','status':status,'headers':[(b'content-type',b'application/json'),(b'x-request-id',rid.encode()),(b'x-instance-id',self.instance_id.encode()),(b'content-length',str(len(payload)).encode())]})
await send({'type':'http.response.body','body':payload});return
scope.setdefault('state',{})['body_size']=len(body)
delivered=False
async def replay():
nonlocal delivered
if not delivered:
delivered=True;return {'type':'http.request','body':bytes(body),'more_body':False}
return await receive()
await self.app(scope,replay,send)