import asyncio import logging import time from contextlib import asynccontextmanager from uuid import uuid4 import aiohttp from fastapi import FastAPI, Request from starlette.responses import JSONResponse, Response from yarl import URL from .attachments import AttachmentStore, InvalidMultipart, validate_multipart from .config import Settings, load_settings from .errors import LimitExceeded, MiddlewareError, Overloaded, PluginFailure, PolicyBlocked from .network import safe_headers from .runtime import PluginManager from .sse import decode_sse, encode_sse logger = logging.getLogger("middleware.audit") async def bounded_body(chunks, maximum): data = bytearray() async for chunk in chunks: if len(data) + len(chunk) > maximum: raise LimitExceeded() data.extend(chunk) return bytes(data) async def disconnected(receive): while True: message = await receive() if message["type"] == "http.disconnect": return async def until_disconnect(awaitable, receive): task = asyncio.create_task(awaitable) watch = asyncio.create_task(disconnected(receive)) delivered = False try: done, _ = await asyncio.wait({task, watch}, return_when=asyncio.FIRST_COMPLETED) if watch in done: if task in done and not task.cancelled() and task.exception() is None: result = task.result() if isinstance(result, ProxyStream): await result.close() else: task.cancel() raise asyncio.CancelledError() result = await task delivered = True return result finally: watch.cancel() if not task.done(): task.cancel() await asyncio.gather(task, watch, return_exceptions=True) if not delivered and not task.cancelled() and task.exception() is None: result = task.result() if isinstance(result, ProxyStream): await result.close() def validate_request(value, original, limit): if original.get("kind") == "multipart": return validate_multipart(value, original) if not isinstance(value, dict) or set(value) != set(original): raise PluginFailure() if value["method"] != original["method"] or value["path"] != original["path"]: raise PluginFailure() if not isinstance(value["body"], str): raise PluginFailure() if len(value["body"].encode("utf-8")) > limit: raise LimitExceeded() value["headers"] = safe_headers(value["headers"]) return value def validate_response(value, streaming, limit): if not isinstance(value, dict) or set(value) != {"status", "headers", "body", "streaming"}: raise PluginFailure() if type(value["status"]) is not int or not 200 <= value["status"] <= 599: raise PluginFailure() if value["streaming"] is not streaming: raise PluginFailure() if streaming: if value["body"] is not None: raise PluginFailure() elif not isinstance(value["body"], str): raise PluginFailure() elif len(value["body"].encode("utf-8")) > limit: raise LimitExceeded() headers = safe_headers(value["headers"]) # aiohttp already decompresses upstream responses; never forward stale encoding headers. headers = {k: v for k, v in headers.items() if k.lower() != "content-encoding"} if streaming: headers = { k: v for k, v in headers.items() if k.lower() not in {"content-type", "cache-control", "x-accel-buffering"} } headers.update( { "content-type": "text/event-stream; charset=utf-8", "cache-control": "no-cache", "x-accel-buffering": "no", } ) value["headers"] = headers return value class ProxyStream(Response): """Own the complete ASGI lifetime, including disconnects before the first chunk.""" def __init__(self, upstream, session, value, manager): super().__init__(status_code=value["status"], headers=value["headers"]) self.raw_headers = [(k, v) for k, v in self.raw_headers if k != b"content-length"] self.upstream = upstream self.session = session self.manager = manager async def close(self): self.upstream.close() await self.session.aclose() async def chunks(self): last_event = None maximum = self.manager.settings.limits.max_sse_frame_bytes try: remaining = self.manager.settings.limits.upstream_timeout_seconds - ( time.monotonic() - self.session.started ) async with asyncio.timeout(max(0.001, remaining)): async for event in decode_sse(self.upstream.content.iter_chunked(16384), maximum): for output in await self.session.apply("on_event", event): encoded = encode_sse(output, maximum) last_event = output yield encoded for output in await self.session.end(): encoded = encode_sse(output, maximum) last_event = output yield encoded except asyncio.CancelledError: raise except Exception as exc: error_type = "PolicyBlocked" if isinstance(exc, PolicyBlocked) else "MiddlewareFailure" logger.info( "stream_failure request=%s category=%s", self.session.context["request_id"], error_type, ) # Cancel upstream and release a worker slot before starting the clean error adapter. await self.close() try: event = await self.manager.error_event( self.session.context["request_id"], last_event, error_type, ) yield encode_sse(event, maximum) except Exception: return async def __call__(self, scope, receive, send): async def transmit(): await send( { "type": "http.response.start", "status": self.status_code, "headers": self.raw_headers, } ) async for chunk in self.chunks(): await send({"type": "http.response.body", "body": chunk, "more_body": True}) await send({"type": "http.response.body", "body": b"", "more_body": False}) try: await until_disconnect(transmit(), receive) except (asyncio.CancelledError, OSError): pass finally: await self.close() def create_app(settings: Settings | str = "config.yaml") -> FastAPI: if not isinstance(settings, Settings): settings = load_settings(settings) @asynccontextmanager async def lifespan(app): app.state.ready = False manager = PluginManager(settings) app.state.manager = manager app.state.active_uploads = 0 try: await manager.validate() async with aiohttp.ClientSession( trust_env=False, cookie_jar=aiohttp.DummyCookieJar(), timeout=aiohttp.ClientTimeout(total=settings.limits.upstream_timeout_seconds), ) as client: app.state.client = client app.state.ready = True yield finally: app.state.ready = False await manager.shutdown() app = FastAPI( title="Lua Agent Safety Middleware", lifespan=lifespan, docs_url=None, redoc_url=None, openapi_url=None, ) @app.get("/healthz") async def healthz(): return {"status": "ok"} @app.get("/readyz") async def readyz(): if not getattr(app.state, "ready", False): return JSONResponse({"status": "not_ready"}, status_code=503) return {"status": "ready"} @app.post("/{proxy_path:path}") async def proxy_post(request: Request): request_id = str(uuid4()) attachments = None multipart = request.headers.get("content-type", "").split(";", 1)[0].strip().lower() == ( "multipart/form-data" ) if multipart: if app.state.active_uploads >= settings.limits.max_sessions: return JSONResponse({"error": "Overloaded"}, status_code=503) def release_upload(): app.state.active_uploads -= 1 attachments = AttachmentStore(settings.limits, on_close=release_upload) app.state.active_uploads += 1 try: async with asyncio.timeout(settings.limits.upstream_timeout_seconds): if multipart: if request.headers.get("content-encoding", "identity") != "identity": raise InvalidMultipart() await attachments.receive(request.stream()) text = None else: body = await bounded_body(request.stream(), settings.limits.max_request_bytes) text = body.decode("utf-8") except LimitExceeded: if attachments is not None: await attachments.aclose() return JSONResponse({"error": "RequestTooLarge"}, status_code=413) except InvalidMultipart: await attachments.aclose() return JSONResponse({"error": "InvalidMultipart"}, status_code=400) except UnicodeError: return JSONResponse({"error": "InvalidEncoding"}, status_code=400) except TimeoutError: if attachments is not None: await attachments.aclose() return JSONResponse({"error": "RequestTimeout"}, status_code=408) except BaseException: if attachments is not None: await attachments.aclose() raise async def prepare(): session = None upstream = None body_stream = None handed_off = False try: manager = app.state.manager request_path = request.scope["path"] if attachments is not None: try: await attachments.parse(request.headers) except LimitExceeded: return JSONResponse({"error": "RequestTooLarge"}, status_code=413) session = await manager.open(request_id, path=request_path, attachments=attachments) original = { "method": "POST", "path": request_path, "headers": safe_headers(dict(request.headers)), "body": text, } if attachments is not None: original.update( kind="multipart", files=attachments.files, form=attachments.form ) result = (await session.apply("on_request", original))[0] value = validate_request(result, original, settings.limits.max_request_bytes) raw_path = request.scope.get("raw_path", request_path.encode("utf-8")) base_url = URL(settings.upstream + raw_path.decode("ascii"), encoded=True) query = request.scope["query_string"].decode("ascii") if any(ord(c) <= 32 or ord(c) == 127 for c in query): raise ValueError("invalid query encoding") # with_query(str) would re-escape existing percent encodings (e.g. %2F → %252F). url = URL(str(base_url) + ("?" + query if query else ""), encoded=True) if attachments is not None: body_stream = attachments.raw_chunks() upstream = await app.state.client.post( url, data=body_stream if multipart else value["body"].encode("utf-8"), headers=value["headers"], allow_redirects=False, ) is_stream = ( upstream.headers.get("content-type", "").split(";", 1)[0].strip().lower() == "text/event-stream" ) value = { "status": upstream.status, "headers": dict(upstream.headers), "streaming": is_stream, "body": None if is_stream else ( await bounded_body( upstream.content.iter_chunked(16384), settings.limits.max_response_bytes ) ).decode("utf-8"), } value = (await session.apply("on_response", value))[0] value = validate_response(value, is_stream, settings.limits.max_response_bytes) if is_stream: response = ProxyStream(upstream, session, value, manager) handed_off = True return response if await session.end(): raise PluginFailure() return Response( value["body"].encode("utf-8"), value["status"], headers=value["headers"] ) except Overloaded: return JSONResponse({"error": "Overloaded"}, status_code=503) except PolicyBlocked: return JSONResponse({"error": "PolicyBlocked"}, status_code=403) except InvalidMultipart: return JSONResponse({"error": "InvalidMultipart"}, status_code=400) except (MiddlewareError, aiohttp.ClientError, TimeoutError, UnicodeError, ValueError): logger.info("request_failure request=%s category=MiddlewareFailure", request_id) return JSONResponse({"error": "MiddlewareFailure"}, status_code=502) finally: if body_stream is not None: await body_stream.aclose() if not handed_off: if upstream is not None: upstream.close() if session is not None: await session.aclose() if attachments is not None: await attachments.aclose() async def prepare_with_budget(): async with asyncio.timeout(settings.limits.upstream_timeout_seconds): return await prepare() response = None try: response = await until_disconnect(prepare_with_budget(), request.receive) return response except TimeoutError: return JSONResponse({"error": "MiddlewareFailure"}, status_code=502) finally: if attachments is not None and not isinstance(response, ProxyStream): await attachments.aclose() return app