import asyncio import codecs import io import shutil import subprocess from contextlib import asynccontextmanager from pathlib import Path import httpx import pytest from aiohttp import web from docx import Document from pydantic import ValidationError from test_proxy import client_for, event_list, frame from middleware import proxy from middleware.attachments import AttachmentStore, extract_file from middleware.config import Limits, PluginConfig, Settings from middleware.extract_worker import extract @asynccontextmanager async def backend(handler): app = web.Application() app.router.add_post("/{path:.*}", handler) runner = web.AppRunner(app) await runner.setup() site = web.TCPSite(runner, "127.0.0.1", 0) await site.start() try: yield f"http://127.0.0.1:{site._server.sockets[0].getsockname()[1]}" finally: await runner.cleanup() def multipart_request(files, path="/upload?x=a%2Fb", **kwargs): request = httpx.Request("POST", f"http://middleware{path}", files=files, **kwargs) return request.read(), dict(request.headers) def plugin_settings(tmp_path, upstream, source, **limits): file = tmp_path / "files.lua" file.write_text(source, encoding="utf-8") return Settings( upstream=upstream, limits=Limits(**limits), plugins=[PluginConfig(id="files", file=file, match={"paths": ["/upload", "/文档"]})], ) @pytest.fixture def stores(monkeypatch): stores = [] class RecordingStore(AttachmentStore): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) stores.append(self) monkeypatch.setattr(proxy, "AttachmentStore", RecordingStore) return stores def assert_clean(stores): assert stores for store in stores: assert store.closed assert not store.texts assert not Path(store.directory.name).exists() async def test_upload_lua_read_and_byte_identical_forwarding(tmp_path, stores): received = [] async def handler(request): received.append((request.raw_path, request.headers["Content-Type"], await request.read())) assert request.headers["X-Checked"] == "yes" return web.json_response({"stored": True}) source = """ local id return { on_request=function(ctx,r) assert(r.kind=='multipart' and r.body==host.json.null) assert(#r.files==2 and #r.form==2) assert(r.form[1].field=='tag' and r.form[2].value=='two') local f=r.files[1]; id=f.id assert(f.name=='../说明.txt' and f.field=='file') assert(f.detected_type=='txt' and f.extraction_status=='complete') assert(#f.sha256==64 and f.size_bytes==f.text_bytes) assert(host.files.read_text(id)=='中文秘密') assert(host.files.read_text(r.files[2].id)=='second') assert(not pcall(host.files.read_text,'/etc/passwd')) assert(not pcall(host.files.read_text,{})) r.headers['x-checked']='yes' return {action='replace',value=r} end, on_response=function(ctx,r) assert(host.files.read_text(id)=='中文秘密') end, on_end=function(ctx) assert(host.files.read_text(id)=='中文秘密') end, close=function(ctx) assert(host.files.read_text(id)=='中文秘密') end } """ raw, headers = multipart_request( [ ("tag", (None, "one")), ("tag", (None, "two")), ("file", ("../说明.txt", "中文秘密".encode(), "text/plain")), ("file", ("second.txt", b"second", "text/plain")), ] ) async with backend(handler) as upstream: async with client_for(plugin_settings(tmp_path, upstream, source)) as (client, app): response = await client.post("/upload?x=a%2Fb", content=raw, headers=headers) assert response.status_code == 200 assert response.json() == {"stored": True} assert app.state.active_uploads == 0 assert not app.state.manager.sessions assert received == [("/upload?x=a%2Fb", headers["content-type"], raw)] assert_clean(stores) @pytest.mark.parametrize("encoding", ["utf-8", "utf-8-sig", "utf-16", "utf-16-be"]) async def test_unicode_text_encodings(tmp_path, encoding): path = tmp_path / "input.txt" text = "hello 中文\nnext" content = text.encode(encoding) if encoding == "utf-16-be": content = codecs.BOM_UTF16_BE + content path.write_bytes(content) result = await extract_file(path, Limits()) assert result["extraction_status"] == "complete" assert result["text"] == text def word_document(): document = Document() document.add_paragraph("开头") table = document.add_table(rows=1, cols=2) table.cell(0, 0).text = "表格一" table.cell(0, 1).text = "表格二" document.add_paragraph("结尾") output = io.BytesIO() document.save(output) return output.getvalue() async def test_docx_order_nested_table_and_unicode(tmp_path): path = tmp_path / "input.docx" path.write_bytes(word_document()) result = await extract_file(path, Limits()) assert result["extraction_status"] == "complete" assert result["text"] == "开头\n表格一\n表格二\n结尾\n" async def test_docx_nested_table_and_merged_cells(tmp_path): document = Document() table = document.add_table(rows=1, cols=2) cell = table.cell(0, 0).merge(table.cell(0, 1)) cell.text = "外层" cell.add_table(rows=1, cols=1).cell(0, 0).text = "嵌套" document.add_paragraph("末尾") path = tmp_path / "input.docx" document.save(path) result = await extract_file(path, Limits()) assert result["extraction_status"] == "complete" assert result["text"] == "外层\n嵌套\n\n末尾\n" @pytest.mark.parametrize( ("extension", "content", "status"), [ ("txt", b"\xffbroken", "failed"), ("txt", codecs.BOM_UTF32_LE + b"a\0\0\0", "failed"), ("txt", b"a\0b", "failed"), ("docx", b"not a document", "failed"), ("doc", b"not a document", "failed"), ("pdf", b"%PDF", "unsupported"), ], ) async def test_invalid_and_unsupported_inputs(tmp_path, extension, content, status): path = tmp_path / ("input." + extension) path.write_bytes(content) result = await extract_file(path, Limits()) assert result["extraction_status"] == status assert result["text"] == "" async def test_text_truncation_and_zip_limits(tmp_path): path = tmp_path / "input.txt" path.write_text("你好世界", encoding="utf-8") result = await extract_file(path, Limits(max_attachment_text_bytes=7)) assert result["extraction_status"] == "partial" assert result["text"] == "你好" word = tmp_path / "input.docx" word.write_bytes(word_document()) for limits in [Limits(max_attachment_unpacked_bytes=100), Limits(max_attachment_zip_entries=1)]: assert (await extract_file(word, limits))["extraction_status"] == "failed" # Encrypted flag: avoid a dependency on an Office password encryption package. data = bytearray(word_document()) for offset in range(len(data) - 10): if data[offset : offset + 4] == b"PK\x01\x02": data[offset + 8] |= 1 word.write_bytes(data) assert (await extract_file(word, Limits()))["extraction_status"] == "failed" def test_doc_missing_converter(tmp_path, monkeypatch): path = tmp_path / "input.doc" path.write_bytes(bytes.fromhex("d0cf11e0a1b11ae1")) monkeypatch.setattr(shutil, "which", lambda _: None) assert extract(path, "doc", Limits().model_dump())["extraction_status"] == "failed" @pytest.mark.skipif( not (shutil.which("soffice") or shutil.which("libreoffice")), reason="LibreOffice is not installed", ) async def test_real_doc_conversion(tmp_path): path = tmp_path / "original.docx" path.write_bytes(word_document()) converter = shutil.which("soffice") or shutil.which("libreoffice") subprocess.run( [ converter, "--headless", "--convert-to", "doc:MS Word 97", "--outdir", str(tmp_path), str(path), ], check=True, timeout=30, capture_output=True, ) result = await extract_file(path.with_suffix(".doc"), Limits(attachment_timeout_seconds=30)) assert result["extraction_status"] == "complete" assert "开头" in result["text"] and "表格二" in result["text"] @pytest.mark.parametrize("decision", ["pass", "block"]) async def test_status_is_visible_and_only_plugin_decides(tmp_path, stores, decision): received = [] async def handler(request): received.append(await request.read()) return web.json_response({}) source = """ return {on_request=function(ctx,r) assert(r.files[1].extraction_status=='failed') assert(r.files[2].extraction_status=='unsupported') assert(r.files[3].extraction_status=='partial') assert(host.files.read_text(r.files[1].id)=='') assert(host.files.read_text(r.files[3].id)=='abc') return {action='DECISION'} end} """.replace("DECISION", decision) raw, headers = multipart_request( [ ("file", ("bad.doc", b"broken")), ("file", ("unknown.pdf", b"%PDF")), ("file", ("large.txt", b"abcdef")), ] ) async with backend(handler) as upstream: settings = plugin_settings(tmp_path, upstream, source, max_attachment_text_bytes=3) async with client_for(settings) as (client, _): response = await client.post("/upload", content=raw, headers=headers) assert response.status_code == (200 if decision == "pass" else 403) assert received == ([raw] if decision == "pass" else []) assert_clean(stores) @pytest.mark.parametrize( "mutation", [ "r.files[1].id='forged'", "r.files={}", "r.kind='text'", "r.body='replaced'", "r.path='/elsewhere'", "r.form={}", "r.headers['content-type']='text/plain'", "r.headers['content-encoding']='gzip'", ], ) async def test_multipart_cannot_be_rewritten(tmp_path, stores, mutation): received = [] async def handler(request): received.append(1) return web.json_response({}) source = ( "return {on_request=function(ctx,r) " + mutation + "; return {action='replace',value=r} end}" ) raw, headers = multipart_request([("field", (None, "value")), ("file", ("x.txt", b"ok"))]) async with backend(handler) as upstream: async with client_for(plugin_settings(tmp_path, upstream, source)) as (client, _): assert (await client.post("/upload", content=raw, headers=headers)).status_code == 502 assert not received assert_clean(stores) async def test_invalid_metadata_is_rejected_before_next_plugin(tmp_path, stores): received = [] async def handler(request): received.append(await request.read()) return web.json_response({}) first = tmp_path / "first.lua" first.write_text( "return {on_request=function(ctx,r) r.files[1].name='forged'; " "return {action='replace',value=r} end}", encoding="utf-8", ) second = tmp_path / "second.lua" second.write_text( "return {on_request=function(ctx,r) r.files[1].name='x.txt'; " "return {action='replace',value=r} end}", encoding="utf-8", ) raw, headers = multipart_request([("file", ("x.txt", b"ok"))]) async with backend(handler) as upstream: settings = Settings( upstream=upstream, plugins=[PluginConfig(id="first", file=first), PluginConfig(id="second", file=second)], ) async with client_for(settings) as (client, _): response = await client.post("/upload", content=raw, headers=headers) assert response.status_code == 502 assert not received assert_clean(stores) async def test_read_ids_are_scoped_to_request(tmp_path, stores): async def handler(request): return web.json_response({}) source = """ local id return {on_request=function(ctx,r) local old=r.headers['x-old-id'] if old then assert(not pcall(host.files.read_text,old)) end id=r.files[1].id assert(host.files.read_text(id)=='ok') end,on_response=function(ctx,r) r.headers['x-id']=id return {action='replace',value=r} end} """ raw, headers = multipart_request([("file", ("x.txt", b"ok"))]) async with backend(handler) as upstream: async with client_for(plugin_settings(tmp_path, upstream, source)) as (client, _): first = await client.post("/upload", content=raw, headers=headers) assert first.status_code == 200 second = await client.post( "/upload", content=raw, headers={**headers, "x-old-id": first.headers["x-id"]} ) assert second.status_code == 200 assert second.headers["x-id"] != first.headers["x-id"] assert_clean(stores) async def test_read_limit_cannot_be_bypassed_with_pcall(tmp_path, stores): async def handler(request): return web.json_response({}) source = """ return {on_request=function(ctx,r) assert(host.files.read_text(r.files[1].id)=='ok') for i=1,3 do assert(not pcall(host.files.read_text,r.files[1].id)) end end} """ raw, headers = multipart_request([("file", ("x.txt", b"ok"))]) async with backend(handler) as upstream: async with client_for( plugin_settings(tmp_path, upstream, source, max_attachment_reads=1) ) as (client, _): assert (await client.post("/upload", content=raw, headers=headers)).status_code == 200 assert_clean(stores) @pytest.mark.parametrize( "limits", [ {"max_request_bytes": 10}, {"max_attachment_files": 1}, {"max_attachment_fields": 1}, ], ) async def test_upload_limits(tmp_path, stores, limits): received = [] async def handler(request): received.append(1) return web.json_response({}) raw, headers = multipart_request( [ ("field", (None, "1")), ("field", (None, "2")), ("file", ("x.txt", b"ok")), ("file", ("y.txt", b"ok")), ] ) async with backend(handler) as upstream: async with client_for(Settings(upstream=upstream, limits=Limits(**limits))) as ( client, app, ): assert (await client.post("/any/path", content=raw, headers=headers)).status_code == 413 assert app.state.active_uploads == 0 assert not received assert_clean(stores) async def test_malformed_multipart_is_rejected_and_cleaned(stores): async with client_for(Settings(upstream="http://unused")) as (client, app): for body, content_type in [ (b"broken", "multipart/form-data"), ( b'--x\r\nContent-Disposition: form-data; name="file"; filename="x.txt"\r\n\r\nno end', "multipart/form-data; boundary=x", ), ]: response = await client.post( "/upload", content=body, headers={"content-type": content_type} ) assert response.status_code == 400 assert app.state.active_uploads == 0 assert_clean(stores) async def test_raw_path_and_query_preserved_and_path_match_decoded(tmp_path, stores): seen = [] async def handler(request): seen.append(request.raw_path) return web.json_response({}) source = "return {on_request=function(ctx,r) assert(r.path=='/文档'); assert(#r.files==1) end}" raw, headers = multipart_request([("file", ("x.txt", b"ok"))]) async with backend(handler) as upstream: async with client_for(plugin_settings(tmp_path, upstream, source)) as (client, _): response = await client.post( "/%E6%96%87%E6%A1%A3?q=a%2Fb", content=raw, headers=headers ) assert response.status_code == 200 assert seen == ["/%E6%96%87%E6%A1%A3?q=a%2Fb"] assert_clean(stores) async def test_attachment_readable_during_sse_then_cleaned(tmp_path, stores): from middleware.sse import encode_sse async def handler(request): return web.Response( body=encode_sse(frame("text_delta", 1, {"content": "ok"}), 4096), content_type="text/event-stream", ) source = """ local id return {on_request=function(ctx,r) id=r.files[1].id end, on_event=function(ctx,e) assert(host.files.read_text(id)=='ok') end, on_end=function(ctx) assert(host.files.read_text(id)=='ok') end} """ raw, headers = multipart_request([("file", ("x.txt", b"ok"))]) async with backend(handler) as upstream: async with client_for(plugin_settings(tmp_path, upstream, source)) as (client, app): response = await client.post("/upload", content=raw, headers=headers) assert (await event_list(response.content))[0]["event"] == "text_delta" assert app.state.active_uploads == 0 assert_clean(stores) async def test_extraction_timeout_and_cancellation_reap_process(tmp_path, monkeypatch): from middleware import attachments path = tmp_path / "input.txt" path.write_text("ok", encoding="utf-8") real_create = asyncio.create_subprocess_exec children = [] async def slow_process(*args, **kwargs): import sys process = await real_create(sys.executable, "-c", "import time; time.sleep(60)", **kwargs) children.append(process) return process monkeypatch.setattr(attachments.asyncio, "create_subprocess_exec", slow_process) # Windows stop_process invokes taskkill through the same factory. async def factory(*args, **kwargs): if args[0] == "taskkill": return await real_create(*args, **kwargs) return await slow_process(*args, **kwargs) monkeypatch.setattr(attachments.asyncio, "create_subprocess_exec", factory) result = await extract_file(path, Limits(attachment_timeout_seconds=0.1)) assert result["extraction_status"] == "failed" assert children[0].returncode is not None task = asyncio.create_task(extract_file(path, Limits())) while len(children) < 2: await asyncio.sleep(0.01) task.cancel() with pytest.raises(asyncio.CancelledError): await task assert children[1].returncode is not None @pytest.mark.parametrize("stage", ["receive", "extract", "stream"]) async def test_disconnect_cleans_upload_at_each_stage(tmp_path, stores, monkeypatch, stage): from middleware import attachments from middleware.sse import encode_sse started = asyncio.Event() cancelled = asyncio.Event() async def slow_extract(*args): started.set() try: await asyncio.Event().wait() finally: cancelled.set() if stage == "extract": monkeypatch.setattr(attachments, "extract_file", slow_extract) async def handler(request): await request.read() return web.Response( body=encode_sse(frame("text_delta", 1, {"content": "ok"}), 4096), content_type="text/event-stream", ) raw, headers = multipart_request([("file", ("x.txt", b"ok"))]) queue = asyncio.Queue() await queue.put({"type": "http.request", "body": raw, "more_body": stage == "receive"}) if stage == "receive": await queue.put({"type": "http.disconnect"}) async def send(message): if message["type"] == "http.response.start" and stage == "stream": await queue.put({"type": "http.disconnect"}) scope = { "type": "http", "asgi": {"version": "3.0", "spec_version": "2.4"}, "http_version": "1.1", "method": "POST", "scheme": "http", "path": "/upload", "raw_path": b"/upload", "query_string": b"", "headers": [(k.encode(), v.encode()) for k, v in headers.items()], "server": ("middleware", 80), "client": ("client", 1), } async with backend(handler) as upstream: async with client_for(Settings(upstream=upstream)) as (_, app): task = asyncio.create_task(app(scope, queue.get, send)) if stage == "extract": await asyncio.wait_for(started.wait(), 5) await queue.put({"type": "http.disconnect"}) if stage == "receive": from starlette.requests import ClientDisconnect with pytest.raises(ClientDisconnect): await asyncio.wait_for(task, 5) elif stage == "extract": with pytest.raises(asyncio.CancelledError): await asyncio.wait_for(task, 5) assert cancelled.is_set() else: await asyncio.wait_for(task, 5) assert not app.state.manager.sessions assert app.state.active_uploads == 0 assert_clean(stores) async def test_upstream_failure_closes_partly_consumed_upload(stores, monkeypatch): import aiohttp raw, headers = multipart_request([("file", ("x.txt", b"ok"))]) async with client_for(Settings(upstream="http://unused")) as (client, app): async def fail(*args, data, **kwargs): assert await anext(data) raise aiohttp.ClientConnectionError() monkeypatch.setattr(app.state.client, "post", fail) response = await client.post("/upload", content=raw, headers=headers) assert response.status_code == 502 assert app.state.active_uploads == 0 assert not app.state.manager.sessions assert_clean(stores) async def test_multipart_upstream_response_limit_remains_502(stores): async def handler(request): await request.read() return web.json_response({"long": "x" * 100}) raw, headers = multipart_request([("file", ("x.txt", b"ok"))]) async with backend(handler) as upstream: async with client_for( Settings(upstream=upstream, limits=Limits(max_response_bytes=10)) ) as ( client, app, ): response = await client.post("/upload", content=raw, headers=headers) assert response.status_code == 502 assert app.state.active_uploads == 0 assert_clean(stores) async def test_upload_receive_timeout_cleans_temp_files(stores): async def slow_body(): yield b"--x\r\n" await asyncio.Event().wait() async with client_for( Settings(upstream="http://unused", limits=Limits(upstream_timeout_seconds=0.05)) ) as (client, app): response = await client.post( "/upload", content=slow_body(), headers={"content-type": "multipart/form-data; boundary=x"}, ) assert response.status_code == 408 assert app.state.active_uploads == 0 assert_clean(stores) async def test_upload_intake_is_bounded(stores, monkeypatch): from middleware import attachments started = asyncio.Event() release = asyncio.Event() async def wait_extract(*args): started.set() await release.wait() return {"text": "ok", "extraction_status": "complete", "detected_type": "txt"} monkeypatch.setattr(attachments, "extract_file", wait_extract) async def handler(request): await request.read() return web.json_response({}) raw, headers = multipart_request([("file", ("x.txt", b"ok"))]) async with backend(handler) as upstream: async with client_for(Settings(upstream=upstream, limits=Limits(max_sessions=1))) as ( client, app, ): first = asyncio.create_task(client.post("/upload", content=raw, headers=headers)) try: await asyncio.wait_for(started.wait(), 5) response = await client.post("/upload", content=raw, headers=headers) assert response.status_code == 503 assert app.state.active_uploads == 1 finally: release.set() assert (await first).status_code == 200 assert app.state.active_uploads == 0 assert_clean(stores) def test_attachment_limits_require_positive_values(): for key in [ "max_attachment_files", "max_attachment_fields", "max_attachment_text_bytes", "max_attachment_unpacked_bytes", "max_attachment_zip_entries", "attachment_timeout_seconds", "max_attachment_reads", ]: with pytest.raises(ValidationError): Limits(**{key: 0})