feat(插件): 读取附件正文并保留日志文本

新增附件读取测试插件并配置上传路径,记录文件名、提取状态及正文。所有插件日志保留参数和级别,按字节限制截断并转义换行,补充运行时和附件集成测试。
This commit is contained in:
starrrLight committed 2026-10-16 14:38:03 +08:00
1 parent 4e0d46ff5f
commit 016c43f13e
9 files changed
+174 -9

No files matched your search

+2
View File
@@ -110,3 +110,5 @@ git diff --check
```
场景 JSON 的 `path` 可包含查询参数,`body` 支持字符串或 JSON 值,SSE 返回体使用 `events` 数组,文件路径相对于场景文件目录。完整字段和示例见 [插件开发文档](docs/plugins.md#json-场景运行器)。
`config.yaml` 已配置 `file-read-log` 测试插件,读取 `/upload` 请求附件的提取正文并写入日志。上面的命令末尾追加 `--verbose`,即可看到 `plugin=file-read-log`、文件名、提取状态和正文;所有插件的 `host.log` 都保留文本,无需开关。
+4
View File
@@ -26,6 +26,10 @@ llm:
queue_size: 8
plugins:
- id: file-read-log
file: plugins/file_read_log.lua
match:
paths: [/upload]
- id: network-review
enabled: false
file: plugins/network_review.lua
+1 -1
View File
@@ -507,7 +507,7 @@ V1 使用版本控制和发布流程管理 Lua 文件、配置及宿主版本。
### 12.2 日志与监控
V1 审计日志只记录本层关联 ID、插件 ID、钩子、耗时、决定和固定错误类别。host.log 的文本参数被丢弃,宿主不默认记录包含查询参数的访问日志。
V1 审计日志记录本层关联 ID、插件 ID、钩子、耗时、决定和固定错误类别。所有插件显式调用 host.log 时同时记录文本参数,并保留 INFO、WARNING、ERROR 级别;文本采用 JSON 字符串编码,超出 max_plugin_buffer_bytes 时按 UTF-8 边界截断并标记。原始异常文本和 traceback 仍不记录,宿主不默认记录包含查询参数的访问日志。
运维应能根据这些元数据识别失败请求、超时插件和会话过载。APISIX、Agent、外部审核服务的日志脱敏需分别配置,不能因中间层脱敏就默认整个链路已脱敏。
+3 -1
View File
@@ -116,6 +116,8 @@ return plugin
multipart 插件可返回 `pass`、`block`,或以 `replace` 修改允许转发的普通请求头。宿主逐插件校验,禁止修改路径、方法、`kind`、`body`、`form`、`files`(包括 ID 和状态),以及 `Content-Type`/边界和 `Content-Encoding`。通过后发送的是原始 multipart 字节,宿主不重新编码表单,不替换文件内容;HTTP 分块方式可变化。后端负责保存文件。
项目提供 `plugins/file_read_log.lua` 测试插件,在 `config.yaml` 中匹配 `/upload`。插件逐个调用 `host.files.read_text(file.id)`,将文件名、提取状态、文本字节数和正文作为 JSON 写入 INFO 日志,然后原样放行;普通 JSON 请求直接放行。提取失败或不支持时会记录状态和空正文,partial 时记录已提取部分。执行场景运行器时追加 `--verbose` 可看到 `plugin=file-read-log` 的日志,正文在 `message` 中(JSON 字符串转义保留换行)。
TXT 仅支持 UTF-8、UTF-8 BOM、带 BOM 的 UTF-16 LE/BE,不猜测其他编码。DOCX 使用 python-docx 按正文顺序提取段落和表格(含嵌套表格);DOC 在独立提取进程内调用无界面 LibreOffice 转换为 DOCX 后复用同一提取逻辑。范围不包含图片 OCR、页眉页脚、批注、修订或嵌入对象;`complete` 只表示该范围内提取完整。原文件的这些内容仍会转发给后端。
整个 multipart 请求受 `limits.max_request_bytes` 限制(默认 2 MiB,包含边界与普通字段),不是每文件单独限额。附件相关配置:
@@ -217,7 +219,7 @@ local result = host.http.request({
请求在 Lua 中表现为同步调用,实际由宿主的异步网络代理执行,不阻塞主事件循环。网络错误抛出可被 `pcall` 捕获的异常;未捕获时插件失败并阻断。插件不得改变白名单、TLS 校验、代理、重定向或超时设置。3xx 直接返回,若自行跟随 Location,新地址也必须满足白名单。宿主不提供凭据,插件若需 API Key,应由管理员在此插件配置中注入,不能放进日志。
`host.log.info(...)`、`warning(...)`、`error(...)` 只生成固定的插件日志标记,不保存文本参数。每钩子最多 64 次宿主调用,限制可配置;日志和 HTTP 都计数。
`host.log.info(...)`、`warning(...)`、`error(...)` 对所有插件保留文本参数,无需额外开关,并分别使用 INFO、WARNING、ERROR 级别输出。多个参数以空格连接,非字符串数据按 JSON 编码;日志包含请求 ID、插件 ID、`truncated` 和 `message`。`message` 使用 JSON 字符串编码,换行和控制字符转义后写在同一条日志中。单条正文受 `limits.max_plugin_buffer_bytes` 的 UTF-8 字节限制,超出时截断到有效字符边界并标记 `truncated=True`;IPC 和宿主调用限制仍适用。日志是否显示由进程日志级别决定,场景运行器使用 `--verbose` 显示 INFO。每钩子最多 64 次宿主调用,限制可配置;日志、附件读取和 HTTP 都计数。插件显式记录的内容会进入日志,原始异常文本和 traceback 仍不记录。
模块加载及所有钩子都有超时与内存限制;配置修改后重启生效,不提供热加载或长期跨请求状态。业务规则应有正常对照测试,避免关键词规则把合法的安全研究或引用内容误判为攻击。
+26 -3
View File
@@ -94,10 +94,33 @@ class Session:
reply["value"] = self.attachments.read_text(result["value"])
elif result["kind"] == "log":
reply["value"] = None
logger.info(
"plugin_log request=%s plugin=%s",
payload = result["value"]
if not isinstance(payload, dict):
raise PluginFailure()
level = payload.get("level")
message = payload.get("message")
levels = {
"info": logging.INFO,
"warning": logging.WARNING,
"error": logging.ERROR,
}
if (
not isinstance(level, str)
or level not in levels
or not isinstance(message, str)
):
raise PluginFailure()
raw = message.encode("utf-8")
max_bytes = self.manager.settings.limits.max_plugin_buffer_bytes
truncated = len(raw) > max_bytes
message = raw[:max_bytes].decode("utf-8", errors="ignore")
logger.log(
levels[level],
"plugin_log request=%s plugin=%s truncated=%s message=%s",
self.context["request_id"],
plugin,
truncated,
json.dumps(message, ensure_ascii=False),
)
elif result["kind"] == "llm":
payload = result["value"]
@@ -151,6 +174,7 @@ class Session:
plugin_ids.append(ADAPTER_ID)
for plugin_id in plugin_ids:
source = self.manager.sources[plugin_id]
config = self.manager.plugins_by_id.get(plugin_id)
await self.rpc(
{
"op": "load",
@@ -160,7 +184,6 @@ class Session:
}
)
self.initialized.append(plugin_id)
config = self.manager.plugins_by_id.get(plugin_id)
result = await self.invoke(plugin_id, "init", config.config if config else {})
if result is not None:
raise PluginFailure()
+9 -2
View File
@@ -75,9 +75,16 @@ class LuaPlugin:
self.lua.eval("setmetatable")(llm, metatable)
host["llm"] = llm
log = self.lua.table()
def write_log(level, *args):
message = " ".join(
value if isinstance(value, str) else json_bytes(self.to_python(value)).decode()
for value in args
)
return self.callback("log", {"level": level, "message": message})
for level in ("info", "warning", "error"):
# Deliberately discard caller-provided text; logs contain metadata only.
log[level] = lambda *_, level=level: self.callback("log", {"level": level})
log[level] = lambda *args, level=level: write_log(level, *args)
host["log"] = log
self.lua.globals()["host"] = host
self.plugin = self.lua.execute(source)
+19
View File
@@ -0,0 +1,19 @@
-- 上传附件读取测试:通过 host.files 读取提取正文,不改写请求或文件。
-- 场景运行器追加 --verbose 即可显示 INFO 日志。
local plugin = {}
function plugin.on_request(ctx, request)
if request.kind ~= "multipart" then return {action = "pass"} end
for _, file in ipairs(request.files or {}) do
local text = host.files.read_text(file.id)
host.log.info(host.json.encode({
name = file.name,
extraction_status = file.extraction_status,
text_bytes = file.text_bytes,
text = text,
}))
end
return {action = "pass"}
end
return plugin
+60
View File
@@ -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
View File
@@ -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):