feat(插件): 读取附件正文并保留日志文本
新增附件读取测试插件并配置上传路径,记录文件名、提取状态及正文。所有插件日志保留参数和级别,按字节限制截断并转义换行,补充运行时和附件集成测试。
This commit is contained in:
1 parent
4e0d46ff5f
commit
016c43f13e
9 files changed
+174
-9
No files matched your search
@@ -0,0 +1,60 @@
|
||||
import io
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
from aiohttp import web
|
||||
from docx import Document
|
||||
from test_attachments import backend, multipart_request
|
||||
from test_proxy import client_for
|
||||
|
||||
from middleware.config import PluginConfig, Settings
|
||||
|
||||
|
||||
@pytest.mark.parametrize("extension", ["txt", "docx", "pdf"])
|
||||
async def test_file_read_log_records_extracted_text_and_forwards_original(extension, caplog):
|
||||
caplog.set_level("INFO", logger="middleware.audit")
|
||||
text = "附件中文正文\n第二行 100%"
|
||||
if extension == "docx":
|
||||
document = Document()
|
||||
document.add_paragraph(text)
|
||||
output = io.BytesIO()
|
||||
document.save(output)
|
||||
content = output.getvalue()
|
||||
elif extension == "pdf":
|
||||
content = b"%PDF-unsupported"
|
||||
else:
|
||||
content = text.encode("utf-8")
|
||||
received = []
|
||||
|
||||
async def handler(request):
|
||||
received.append(await request.read())
|
||||
return web.json_response({"stored": True})
|
||||
|
||||
plugin = PluginConfig(
|
||||
id="file-read-log",
|
||||
file=Path(__file__).resolve().parents[1] / "plugins" / "file_read_log.lua",
|
||||
match={"paths": ["/upload"]},
|
||||
)
|
||||
raw, headers = multipart_request([("file", (f"sample.{extension}", content))])
|
||||
async with backend(handler) as upstream:
|
||||
async with client_for(Settings(upstream=upstream, plugins=[plugin])) 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
|
||||
before = len([r for r in caplog.records if r.getMessage().startswith("plugin_log ")])
|
||||
assert (await client.post("/upload", json={"message": "普通请求"})).status_code == 200
|
||||
records = [r.getMessage() for r in caplog.records if r.getMessage().startswith("plugin_log ")]
|
||||
assert len(records) == before == 1
|
||||
assert "plugin=file-read-log" in records[0]
|
||||
assert "truncated=False" in records[0]
|
||||
logged = json.loads(json.loads(records[0].split(" message=", 1)[1]))
|
||||
expected_text = "" if extension == "pdf" else text + ("\n" if extension == "docx" else "")
|
||||
assert logged == {
|
||||
"name": f"sample.{extension}",
|
||||
"extraction_status": "unsupported" if extension == "pdf" else "complete",
|
||||
"text_bytes": len(expected_text.encode("utf-8")),
|
||||
"text": expected_text,
|
||||
}
|
||||
assert received[0] == raw
|
||||
+50
-2
@@ -224,14 +224,62 @@ async def test_close_failure_does_not_skip_other_plugins(tmp_path, caplog):
|
||||
manager = manager_for(
|
||||
tmp_path,
|
||||
[
|
||||
"return {close=function() host.log.info('raw-secret') end}",
|
||||
"return {close=function() host.log.info('closed') end}",
|
||||
"return {close=function() error('private') end}",
|
||||
],
|
||||
)
|
||||
session = await manager.open(path="/chat/stream")
|
||||
await session.aclose()
|
||||
assert "plugin_log" in caplog.text
|
||||
assert "raw-secret" not in caplog.text
|
||||
assert 'message="closed"' in caplog.text
|
||||
assert "private" not in caplog.text
|
||||
|
||||
|
||||
async def test_plugin_log_preserves_arguments_levels_and_single_line(tmp_path, caplog):
|
||||
caplog.set_level("INFO", logger="middleware.audit")
|
||||
manager = manager_for(
|
||||
tmp_path,
|
||||
[
|
||||
r"""
|
||||
return {on_request=function()
|
||||
host.log.info("中文\n下一行", 42, true, {ok=true})
|
||||
host.log.warning("warning message")
|
||||
host.log.error("error message")
|
||||
end}
|
||||
"""
|
||||
],
|
||||
)
|
||||
session = await manager.open(path="/chat/stream")
|
||||
try:
|
||||
await session.apply("on_request", {})
|
||||
finally:
|
||||
await session.aclose()
|
||||
records = [r for r in caplog.records if r.getMessage().startswith("plugin_log ")]
|
||||
assert [r.levelname for r in records] == ["INFO", "WARNING", "ERROR"]
|
||||
assert json.loads(records[0].getMessage().split(" message=", 1)[1]) == (
|
||||
'中文\n下一行 42 true {"ok":true}'
|
||||
)
|
||||
assert all("\n" not in r.getMessage() for r in records)
|
||||
|
||||
|
||||
async def test_plugin_log_truncation_keeps_valid_unicode(tmp_path, caplog):
|
||||
caplog.set_level("INFO", logger="middleware.audit")
|
||||
manager = manager_for(
|
||||
tmp_path,
|
||||
['return {on_request=function() host.log.info(string.rep("中", 4000)) end}'],
|
||||
max_plugin_buffer_bytes=10001,
|
||||
)
|
||||
session = await manager.open(path="/chat/stream")
|
||||
try:
|
||||
await session.apply("on_request", {})
|
||||
finally:
|
||||
await session.aclose()
|
||||
record = next(
|
||||
r.getMessage() for r in caplog.records if r.getMessage().startswith("plugin_log ")
|
||||
)
|
||||
assert "truncated=True" in record
|
||||
message = json.loads(record.split(" message=", 1)[1])
|
||||
assert message == "中" * 3333
|
||||
|
||||
|
||||
async def test_buffered_json_events_are_rewritten_on_end(tmp_path):
|
||||
|
||||
Reference in new issue
Block a user