feat(附件): 增加请求级文本读取与上传代理
支持任意 POST 路径的 multipart 暂存、原始字节转发和 TXT、DOCX、DOC 文本提取;通过 host.files.read_text 提供请求内受限读取,禁止插件改写附件和上传正文。 增加附件数量、文本、解压、超时和读取次数限制,覆盖断开、异常及清理场景;补充依赖、LibreOffice 镜像安装和插件接口文档,不修改业务 Lua 插件。 验证:全量测试 128 通过、2 个既有失败、1 个跳过;既有失败为 test_example_redacts_cross_event_phone 和 test_network_example_uses_configuration_and_http_result,均缺少插件必填配置。Ruff 静态检查、改动文件格式检查、pip check 和差异检查通过;全仓格式检查保留两处既有问题。当前环境缺少 LibreOffice 和 Docker,真实 DOC 转换及镜像构建未验证。
This commit is contained in:
1 parent
7f0ae69252
commit
8ad4b29e4c
12 files changed
+1233
-15
No files matched your search
@@ -1,5 +1,7 @@
|
||||
FROM python:3.14-slim
|
||||
WORKDIR /service
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends libreoffice-writer \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
COPY pyproject.toml ./
|
||||
COPY middleware ./middleware
|
||||
RUN pip install -i https://pypi.tuna.tsinghua.edu.cn/simple \
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
运行链路:`APISIX → 本服务 → Python Agent`。Python 负责 HTTP/SSE、插件生命周期和网络授权,Lua 负责输入输出内容的业务处理。一个 Lua 文件就是一个插件,配置文件控制启用和执行顺序。
|
||||
|
||||
当前代理 `POST /chat/stream`,兼容现有 Agent 的 `message`、`conversation_id` 请求及自定义 SSE 事件。Python 核心不解析这些业务字段。这里检查的是 Agent 的 HTTP 边界,不能在执行前授权 Agent 内部的工具调用。
|
||||
支持任意路径的 POST 代理,兼容现有 `POST /chat/stream` 的 JSON 请求及自定义 SSE 事件。multipart 上传在当前请求内暂存并提取 TXT/DOCX/DOC 正文,Lua 通过 `host.files.read_text(id)` 审核;通过后按原路径和查询参数转发原始 multipart 字节,由后端保存文件。提取失败或截断时是否阻断由插件决定。Python 核心不解析聊天业务字段。这里检查的是 Agent 的 HTTP 边界,不能在执行前授权 Agent 内部的工具调用。
|
||||
|
||||
## 本地运行
|
||||
|
||||
@@ -18,6 +18,8 @@ Copy-Item config.yaml config.local.yaml
|
||||
|
||||
Linux 安装后使用 `agent-safe-middleware --config config.local.yaml`。默认 Agent 地址为 `http://127.0.0.1:8000`,中间层监听 `8080`。三个示例插件默认关闭,因此初始配置转发原始请求和响应。
|
||||
|
||||
DOC 提取需要 PATH 中存在 `soffice` 或 `libreoffice`(Docker 镜像已安装 LibreOffice Writer);缺失时附件状态为 `failed`。TXT/DOCX 无此依赖。附件读取接口、提取范围和限制见 [插件开发文档](docs/plugins.md#multipart-附件读取)。上传审核插件由使用方配置,并应匹配独立上传路径。
|
||||
|
||||
检查 `GET /healthz` 和 `GET /readyz`。就绪表示配置与插件初始化通过,不表示真实模型、MCP 或上游 Agent 已连通。
|
||||
|
||||
```powershell
|
||||
|
||||
@@ -6,6 +6,13 @@ limits:
|
||||
max_sessions: 4
|
||||
hook_timeout_seconds: 5
|
||||
upstream_timeout_seconds: 120
|
||||
max_attachment_files: 8
|
||||
max_attachment_fields: 128
|
||||
max_attachment_text_bytes: 1048576
|
||||
max_attachment_unpacked_bytes: 33554432
|
||||
max_attachment_zip_entries: 2048
|
||||
attachment_timeout_seconds: 10
|
||||
max_attachment_reads: 64
|
||||
|
||||
llm:
|
||||
- id: guard_model
|
||||
|
||||
+64
-1
@@ -43,7 +43,7 @@ plugins:
|
||||
| `on_end(ctx)` | 无业务参数 | pass、replace、block |
|
||||
| `close(ctx)` | 无业务参数 | 返回值忽略 |
|
||||
|
||||
请求/非流式正文是 UTF-8 字符串;`method`、`path` 不可改变。请求头和正文允许修改。SSE 响应的 body 是 JSON null,不能替换或切换 streaming 模式,应使用 `on_event`。状态码必须为 200–599。
|
||||
普通请求/非流式响应正文是 UTF-8 字符串;`method`、`path` 不可改变。普通请求头和正文允许修改;multipart 请求的限制见下节。SSE 响应的 body 是 JSON null,不能替换或切换 streaming 模式,应使用 `on_event`。状态码必须为 200–599。
|
||||
|
||||
SSE `data` 是原始文本,不是宿主解码的 JSON。`has_data=false` 表示无 data 行,例如心跳注释。多行 data 合并为 `\n`;comments 是注释字符串数组。宿主会规范化 SSE 的行分隔及空格,保持协议语义,不承诺字节一致。缺少完整结束空行、非法 UTF-8 或超大帧会导致流失败。修改 event、id 时不能包含换行或 NUL。
|
||||
|
||||
@@ -71,6 +71,69 @@ return {action='block', reason='internal explanation'}
|
||||
|
||||
非流式响应也调用 `on_end`;此时不能释放 SSE 事件。执行性输出若需要审核,应在请求或完整响应钩子中完成。本层看到的工具生命周期事件不能阻止已经发生的 Agent 内部工具调用。
|
||||
|
||||
## multipart 附件读取
|
||||
|
||||
宿主支持任意路径的 POST,请求按原路径和查询参数转发到固定上游;插件匹配使用 ASGI 解码后的路径,不包含查询参数。上传审核插件应单独配置 `match.paths: [/upload]` 等实际上传路径,避免聊天 JSON 插件尝试解码 multipart。
|
||||
|
||||
收到 `Content-Type: multipart/form-data` 时,宿主在当前请求内暂存原始请求并提取文本,再调用匹配插件的 `on_request`。请求包含:
|
||||
|
||||
| 字段 | 含义 |
|
||||
|---|---|
|
||||
| `method`、`path`、`headers` | POST、解码后的原始路径、经过清理的请求头 |
|
||||
| `kind` | 固定为 `"multipart"`;普通文本/JSON 请求保留原接口,不增加此字段 |
|
||||
| `body` | `host.json.null`,不包含原始二进制 |
|
||||
| `form` | 按顺序排列的普通字段 `{field, value}` 数组,保留重复字段名 |
|
||||
| `files` | 按顺序排列的附件元数据数组,保留同名文件字段 |
|
||||
|
||||
每个文件包含 `id`(当前请求内有效的随机不透明 ID)、`name`(原始文件名)、`field`(表单字段名)、`mime`(客户端声明的 MIME)、`size_bytes`(原文件字节数)、`sha256`(原文件摘要)、`detected_type`(`txt`/`docx`/`doc`/`unknown`)、`extraction_status` 和 `text_bytes`(实际提取文本的 UTF-8 字节数)。类型由扩展名选择提取器,并校验文档签名和结构;文件名和 MIME 均不作为可信内容证据,`failed` 时的类型只表示尝试的提取器。
|
||||
|
||||
`host.files.read_text(id)` 返回该附件提取的文本字符串,不能传服务器路径,也不能跨请求复用 ID。二进制文件不会发送到 Lua 或初始 IPC 消息中;文本仅在显式调用时返回。该能力在本请求的业务钩子和 `close` 期间有效;请求结束、阻断、异常、超时或断开后,临时文件和注册表被清理。不存在长期文件存储或可复用的上传 ID。
|
||||
|
||||
| `extraction_status` | 含义和读取结果 |
|
||||
|---|---|
|
||||
| `complete` | 已完成支持范围内的正文提取 |
|
||||
| `partial` | 达到文本字节上限,返回有效 UTF-8 前缀;不能据此认定整份文档通过审核 |
|
||||
| `failed` | 编码、签名、文档损坏/加密、资源上限、提取超时或转换器不可用等导致失败;返回空字符串 |
|
||||
| `unsupported` | 不支持的扩展名,类型为 `unknown`;返回空字符串 |
|
||||
|
||||
宿主不会因为 `partial`、`failed` 或 `unsupported` 自动拦截,是否允许由插件决定。例如使用方可以编写以下插件,并自行添加关键词或模型审核规则:
|
||||
|
||||
```lua
|
||||
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
|
||||
if file.extraction_status ~= 'complete' then
|
||||
return {action='block'}
|
||||
end
|
||||
local text = host.files.read_text(file.id)
|
||||
-- 在此执行规则或 host.llm 审核,由插件返回 block 或继续。
|
||||
end
|
||||
return {action='pass'}
|
||||
end
|
||||
return plugin
|
||||
```
|
||||
|
||||
multipart 插件可返回 `pass`、`block`,或以 `replace` 修改允许转发的普通请求头。宿主逐插件校验,禁止修改路径、方法、`kind`、`body`、`form`、`files`(包括 ID 和状态),以及 `Content-Type`/边界和 `Content-Encoding`。通过后发送的是原始 multipart 字节,宿主不重新编码表单,不替换文件内容;HTTP 分块方式可变化。后端负责保存文件。
|
||||
|
||||
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,包含边界与普通字段),不是每文件单独限额。附件相关配置:
|
||||
|
||||
| `limits` 字段 | 默认值 | 作用 |
|
||||
|---|---|---|
|
||||
| `max_attachment_files` | 8 | 每请求最大文件数 |
|
||||
| `max_attachment_fields` | 128 | 每请求最大普通字段数 |
|
||||
| `max_attachment_text_bytes` | 1048576 | 每文件最大提取文本 UTF-8 字节数,单次读取也受此限制 |
|
||||
| `max_attachment_unpacked_bytes` | 33554432 | 每份 DOCX 的 ZIP 声明解压总字节数、DOC 转换输出大小 |
|
||||
| `max_attachment_zip_entries` | 2048 | 每份 DOCX 最大 ZIP 成员数 |
|
||||
| `attachment_timeout_seconds` | 10 | 每文件提取和 DOC 转换总超时,超时终止提取进程及转换子进程 |
|
||||
| `max_attachment_reads` | 64 | 整次请求所有插件合计的有效 ID 读取尝试次数 |
|
||||
|
||||
以上配置均须大于零。读取也计入现有每钩子 `max_host_calls_per_hook`,失败以能力调用错误返回,可用 `pcall` 捕获;未捕获则插件失败。上传接收并发受 `max_sessions` 限制,满载返回 503;请求字节/文件/普通字段数量超限返回 413,格式损坏返回 400,接收超时返回 408。解析与审核、上游转发另受 `upstream_timeout_seconds` 总预算约束;提取器在独立进程执行,不阻塞事件循环,不提供操作系统级内存沙箱。
|
||||
|
||||
Docker 镜像安装 LibreOffice Writer;本地运行需将 `soffice` 或 `libreoffice` 放入 PATH。缺失时 DOC 的状态为 `failed`,插件允许后仍原样转发。
|
||||
|
||||
## JSON 数据桥
|
||||
|
||||
`host.json.decode(text)`、`host.json.encode(value)` 保留对象、数组、布尔、数字和 null。JSON null 用 `host.json.null` 表示;不与 Lua nil 混淆。
|
||||
|
||||
@@ -0,0 +1,207 @@
|
||||
"""Request-scoped attachment registry and original multipart storage."""
|
||||
|
||||
import asyncio
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import signal
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from tempfile import TemporaryDirectory
|
||||
from uuid import uuid4
|
||||
|
||||
from starlette.datastructures import UploadFile
|
||||
from starlette.formparsers import MultiPartException, MultiPartParser
|
||||
|
||||
from .errors import LimitExceeded, PluginFailure
|
||||
from .network import safe_headers
|
||||
|
||||
|
||||
class InvalidMultipart(ValueError):
|
||||
pass
|
||||
|
||||
|
||||
class CompleteMultiPartParser(MultiPartParser):
|
||||
complete = False
|
||||
|
||||
def on_end(self):
|
||||
self.complete = True
|
||||
|
||||
|
||||
def validate_multipart(value, original):
|
||||
if not isinstance(value, dict) or set(value) != set(original):
|
||||
raise PluginFailure()
|
||||
for key in original.keys() - {"headers"}:
|
||||
if json.dumps(value[key], sort_keys=True) != json.dumps(original[key], sort_keys=True):
|
||||
raise PluginFailure()
|
||||
value["headers"] = safe_headers(value["headers"])
|
||||
for name in ("content-type", "content-encoding"):
|
||||
before = [v for k, v in original["headers"].items() if k.lower() == name]
|
||||
after = [v for k, v in value["headers"].items() if k.lower() == name]
|
||||
if before != after:
|
||||
raise PluginFailure()
|
||||
return value
|
||||
|
||||
|
||||
async def stop_process(process):
|
||||
if os.name == "nt":
|
||||
if process.returncode is None:
|
||||
killer = await asyncio.create_subprocess_exec(
|
||||
"taskkill",
|
||||
"/PID",
|
||||
str(process.pid),
|
||||
"/T",
|
||||
"/F",
|
||||
stdout=asyncio.subprocess.DEVNULL,
|
||||
stderr=asyncio.subprocess.DEVNULL,
|
||||
)
|
||||
await killer.wait()
|
||||
else:
|
||||
# Also reap a converter left behind by an exited extraction worker.
|
||||
try:
|
||||
os.killpg(process.pid, signal.SIGKILL)
|
||||
except ProcessLookupError:
|
||||
pass
|
||||
await process.wait()
|
||||
|
||||
|
||||
async def extract_file(path, limits):
|
||||
declared_type = path.suffix.lower().lstrip(".")
|
||||
failed = {"text": "", "extraction_status": "failed", "detected_type": declared_type}
|
||||
if declared_type not in {"txt", "doc", "docx"}:
|
||||
return {**failed, "extraction_status": "unsupported", "detected_type": "unknown"}
|
||||
result_path = path.parent / "result.json"
|
||||
try:
|
||||
process = await asyncio.create_subprocess_exec(
|
||||
sys.executable,
|
||||
"-m",
|
||||
"middleware.extract_worker",
|
||||
str(path),
|
||||
declared_type,
|
||||
json.dumps(limits.model_dump()),
|
||||
str(result_path),
|
||||
stdout=asyncio.subprocess.DEVNULL,
|
||||
stderr=asyncio.subprocess.DEVNULL,
|
||||
**({"start_new_session": True} if os.name != "nt" else {}),
|
||||
)
|
||||
except OSError:
|
||||
return failed
|
||||
try:
|
||||
async with asyncio.timeout(limits.attachment_timeout_seconds):
|
||||
await process.wait()
|
||||
if process.returncode or not result_path.exists():
|
||||
return failed
|
||||
if result_path.stat().st_size > 6 * limits.max_attachment_text_bytes + 1024:
|
||||
return failed
|
||||
return json.loads(result_path.read_text(encoding="utf-8"))
|
||||
except (TimeoutError, OSError, ValueError):
|
||||
return failed
|
||||
finally:
|
||||
await stop_process(process)
|
||||
|
||||
|
||||
class AttachmentStore:
|
||||
def __init__(self, limits, on_close=None):
|
||||
self.limits = limits
|
||||
self.directory = TemporaryDirectory(prefix="agent-attachments-")
|
||||
self.raw_path = Path(self.directory.name) / "multipart.bin"
|
||||
self.files = []
|
||||
self.form = []
|
||||
self.texts = {}
|
||||
self.reads = 0
|
||||
self.closed = False
|
||||
self.on_close = on_close
|
||||
|
||||
async def receive(self, chunks):
|
||||
size = 0
|
||||
with self.raw_path.open("wb") as output:
|
||||
async for chunk in chunks:
|
||||
size += len(chunk)
|
||||
if size > self.limits.max_request_bytes:
|
||||
raise LimitExceeded()
|
||||
output.write(chunk)
|
||||
|
||||
async def raw_chunks(self):
|
||||
with self.raw_path.open("rb") as source:
|
||||
while chunk := source.read(65536):
|
||||
yield chunk
|
||||
|
||||
async def parse(self, headers):
|
||||
stream = self.raw_chunks()
|
||||
parser = CompleteMultiPartParser(
|
||||
headers,
|
||||
stream,
|
||||
max_files=self.limits.max_attachment_files,
|
||||
max_fields=self.limits.max_attachment_fields,
|
||||
max_part_size=self.limits.max_request_bytes,
|
||||
)
|
||||
try:
|
||||
form = await parser.parse()
|
||||
except MultiPartException as exc:
|
||||
if "Too many" in exc.message:
|
||||
raise LimitExceeded() from None
|
||||
raise InvalidMultipart() from None
|
||||
finally:
|
||||
await stream.aclose()
|
||||
if not parser.complete:
|
||||
for file in parser._files_to_close_on_error:
|
||||
file.close()
|
||||
await form.close()
|
||||
raise InvalidMultipart()
|
||||
try:
|
||||
for field, item in form.multi_items():
|
||||
if not isinstance(item, UploadFile):
|
||||
self.form.append({"field": field, "value": item})
|
||||
continue
|
||||
file_id = uuid4().hex
|
||||
folder = Path(self.directory.name) / file_id
|
||||
folder.mkdir()
|
||||
# Only the extension is reused; user filenames never become paths.
|
||||
extension = Path(item.filename or "").suffix.lower()
|
||||
path = folder / (
|
||||
"input" + extension if extension in {".txt", ".doc", ".docx"} else "input.bin"
|
||||
)
|
||||
digest = hashlib.sha256()
|
||||
size = 0
|
||||
with path.open("wb") as output:
|
||||
while chunk := await item.read(65536):
|
||||
size += len(chunk)
|
||||
digest.update(chunk)
|
||||
output.write(chunk)
|
||||
extracted = await extract_file(path, self.limits)
|
||||
text = extracted.pop("text")
|
||||
self.texts[file_id] = text
|
||||
self.files.append(
|
||||
{
|
||||
"id": file_id,
|
||||
"name": item.filename or "",
|
||||
"field": field,
|
||||
"mime": item.content_type or "application/octet-stream",
|
||||
"size_bytes": size,
|
||||
"sha256": digest.hexdigest(),
|
||||
"text_bytes": len(text.encode("utf-8")),
|
||||
**extracted,
|
||||
}
|
||||
)
|
||||
finally:
|
||||
await form.close()
|
||||
|
||||
def read_text(self, file_id):
|
||||
if self.closed or not isinstance(file_id, str) or file_id not in self.texts:
|
||||
raise ValueError("unknown attachment")
|
||||
self.reads += 1
|
||||
if self.reads > self.limits.max_attachment_reads:
|
||||
raise LimitExceeded()
|
||||
return self.texts[file_id]
|
||||
|
||||
def close(self):
|
||||
if not self.closed:
|
||||
self.closed = True
|
||||
self.texts.clear()
|
||||
self.files.clear()
|
||||
self.form.clear()
|
||||
try:
|
||||
self.directory.cleanup()
|
||||
finally:
|
||||
if self.on_close is not None:
|
||||
self.on_close()
|
||||
@@ -155,6 +155,13 @@ class Limits(Model):
|
||||
max_sse_frame_bytes: int = Field(default=256 * 1024, gt=0)
|
||||
max_plugin_buffer_bytes: int = Field(default=1024 * 1024, gt=0)
|
||||
max_host_calls_per_hook: int = Field(default=64, gt=0)
|
||||
max_attachment_files: int = Field(default=8, gt=0)
|
||||
max_attachment_fields: int = Field(default=128, gt=0)
|
||||
max_attachment_text_bytes: int = Field(default=1024 * 1024, gt=0)
|
||||
max_attachment_unpacked_bytes: int = Field(default=32 * 1024 * 1024, gt=0)
|
||||
max_attachment_zip_entries: int = Field(default=2048, gt=0)
|
||||
attachment_timeout_seconds: float = Field(default=10, gt=0)
|
||||
max_attachment_reads: int = Field(default=64, gt=0)
|
||||
upstream_timeout_seconds: float = Field(default=120, gt=0)
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,153 @@
|
||||
"""Bounded text extraction in a disposable process; no document bytes enter Lua."""
|
||||
|
||||
import codecs
|
||||
import json
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import zipfile
|
||||
from pathlib import Path
|
||||
|
||||
from docx import Document
|
||||
from docx.table import Table
|
||||
from docx.text.paragraph import Paragraph
|
||||
|
||||
|
||||
class TextBuffer:
|
||||
def __init__(self, maximum):
|
||||
self.maximum = maximum
|
||||
self.parts = []
|
||||
self.size = 0
|
||||
self.partial = False
|
||||
|
||||
def add(self, text):
|
||||
raw = text.encode("utf-8")
|
||||
available = self.maximum - self.size
|
||||
if len(raw) > available:
|
||||
raw = raw[:available].decode("utf-8", errors="ignore").encode("utf-8")
|
||||
self.partial = True
|
||||
self.parts.append(raw.decode("utf-8"))
|
||||
self.size += len(raw)
|
||||
|
||||
def result(self):
|
||||
return "".join(self.parts), "partial" if self.partial else "complete"
|
||||
|
||||
|
||||
def docx_text(path, limits):
|
||||
# Inspect every archive member before python-docx expands any XML.
|
||||
with zipfile.ZipFile(path) as archive:
|
||||
entries = archive.infolist()
|
||||
if (
|
||||
len(entries) > limits["max_attachment_zip_entries"]
|
||||
or sum(entry.file_size for entry in entries) > limits["max_attachment_unpacked_bytes"]
|
||||
):
|
||||
raise ValueError("archive limit")
|
||||
if any(entry.flag_bits & 1 for entry in entries):
|
||||
raise ValueError("encrypted archive")
|
||||
if "word/document.xml" not in archive.namelist():
|
||||
raise ValueError("not a Word document")
|
||||
document = Document(path)
|
||||
buffer = TextBuffer(limits["max_attachment_text_bytes"])
|
||||
|
||||
def blocks(container):
|
||||
for block in container.iter_inner_content():
|
||||
if isinstance(block, Paragraph):
|
||||
buffer.add(block.text + "\n")
|
||||
elif isinstance(block, Table):
|
||||
for row in block.rows:
|
||||
seen = set()
|
||||
for cell in row.cells:
|
||||
# A merged cell appears repeatedly in row.cells.
|
||||
if cell._tc in seen:
|
||||
continue
|
||||
seen.add(cell._tc)
|
||||
blocks(cell)
|
||||
if buffer.partial:
|
||||
return
|
||||
if buffer.partial:
|
||||
return
|
||||
|
||||
blocks(document)
|
||||
return buffer.result()
|
||||
|
||||
|
||||
def extract(path, declared_type, limits):
|
||||
detected = declared_type
|
||||
try:
|
||||
with path.open("rb") as source:
|
||||
signature = source.read(8)
|
||||
if declared_type == "txt":
|
||||
raw = path.read_bytes()
|
||||
if raw.startswith((codecs.BOM_UTF32_LE, codecs.BOM_UTF32_BE)):
|
||||
raise ValueError("unsupported encoding")
|
||||
encoding = (
|
||||
"utf-16"
|
||||
if raw.startswith((codecs.BOM_UTF16_LE, codecs.BOM_UTF16_BE))
|
||||
else "utf-8-sig"
|
||||
)
|
||||
text = raw.decode(encoding, errors="strict")
|
||||
if "\x00" in text:
|
||||
raise ValueError("binary content")
|
||||
buffer = TextBuffer(limits["max_attachment_text_bytes"])
|
||||
buffer.add(text)
|
||||
text, status = buffer.result()
|
||||
elif declared_type == "docx":
|
||||
if not signature.startswith(b"PK"):
|
||||
raise ValueError("invalid docx")
|
||||
text, status = docx_text(path, limits)
|
||||
elif declared_type == "doc":
|
||||
if signature != bytes.fromhex("d0cf11e0a1b11ae1"):
|
||||
raise ValueError("invalid doc")
|
||||
executable = shutil.which("soffice") or shutil.which("libreoffice")
|
||||
if not executable:
|
||||
raise ValueError("converter unavailable")
|
||||
profile = path.parent / "lo-profile"
|
||||
profile.mkdir()
|
||||
(profile / "user").mkdir()
|
||||
(profile / "user" / "registrymodifications.xcu").write_text(
|
||||
'<oor:items xmlns:oor="http://openoffice.org/2001/registry">'
|
||||
'<item oor:path="/org.openoffice.Office.Common/Security/Scripting">'
|
||||
'<prop oor:name="MacroSecurityLevel" oor:op="fuse"><value>3</value></prop>'
|
||||
"</item></oor:items>",
|
||||
encoding="utf-8",
|
||||
)
|
||||
subprocess.run(
|
||||
[
|
||||
executable,
|
||||
f"-env:UserInstallation={profile.as_uri()}",
|
||||
"--headless",
|
||||
"--nologo",
|
||||
"--nodefault",
|
||||
"--norestore",
|
||||
"--convert-to",
|
||||
"docx",
|
||||
"--outdir",
|
||||
str(path.parent),
|
||||
str(path),
|
||||
],
|
||||
check=True,
|
||||
stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL,
|
||||
# The supervisor owns the deadline and kills the entire process tree.
|
||||
)
|
||||
converted = path.with_suffix(".docx")
|
||||
if converted.stat().st_size > limits["max_attachment_unpacked_bytes"]:
|
||||
raise ValueError("conversion limit")
|
||||
text, status = docx_text(converted, limits)
|
||||
else:
|
||||
return {"text": "", "extraction_status": "unsupported", "detected_type": "unknown"}
|
||||
return {"text": text, "extraction_status": status, "detected_type": detected}
|
||||
except Exception:
|
||||
# Never expose parser errors, local paths or document fragments.
|
||||
return {"text": "", "extraction_status": "failed", "detected_type": detected}
|
||||
|
||||
|
||||
def main():
|
||||
path = Path(sys.argv[1])
|
||||
limits = json.loads(sys.argv[3])
|
||||
result = extract(path, sys.argv[2], limits)
|
||||
Path(sys.argv[4]).write_text(json.dumps(result, ensure_ascii=False), encoding="utf-8")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
+69
-8
@@ -9,6 +9,7 @@ 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
|
||||
@@ -63,6 +64,8 @@ async def until_disconnect(awaitable, receive):
|
||||
|
||||
|
||||
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"]:
|
||||
@@ -191,6 +194,7 @@ def create_app(settings: Settings | str = "config.yaml") -> FastAPI:
|
||||
app.state.ready = False
|
||||
manager = PluginManager(settings)
|
||||
app.state.manager = manager
|
||||
app.state.active_uploads = 0
|
||||
try:
|
||||
await manager.validate()
|
||||
async with aiohttp.ClientSession(
|
||||
@@ -223,42 +227,88 @@ def create_app(settings: Settings | str = "config.yaml") -> FastAPI:
|
||||
return JSONResponse({"status": "not_ready"}, status_code=503)
|
||||
return {"status": "ready"}
|
||||
|
||||
@app.post("/chat/stream")
|
||||
async def chat(request: Request):
|
||||
@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:
|
||||
body = await bounded_body(request.stream(), settings.limits.max_request_bytes)
|
||||
text = body.decode("utf-8")
|
||||
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:
|
||||
attachments.close()
|
||||
return JSONResponse({"error": "RequestTooLarge"}, status_code=413)
|
||||
except InvalidMultipart:
|
||||
attachments.close()
|
||||
return JSONResponse({"error": "InvalidMultipart"}, status_code=400)
|
||||
except UnicodeError:
|
||||
return JSONResponse({"error": "InvalidEncoding"}, status_code=400)
|
||||
except TimeoutError:
|
||||
if attachments is not None:
|
||||
attachments.close()
|
||||
return JSONResponse({"error": "RequestTimeout"}, status_code=408)
|
||||
except BaseException:
|
||||
if attachments is not None:
|
||||
attachments.close()
|
||||
raise
|
||||
|
||||
async def prepare():
|
||||
session = None
|
||||
upstream = None
|
||||
body_stream = None
|
||||
handed_off = False
|
||||
try:
|
||||
manager = app.state.manager
|
||||
request_path = request.scope["path"]
|
||||
session = await manager.open(request_id, path=request_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)
|
||||
base_url = URL(settings.upstream + "/chat/stream")
|
||||
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=value["body"].encode("utf-8"),
|
||||
data=body_stream if multipart else value["body"].encode("utf-8"),
|
||||
headers=value["headers"],
|
||||
allow_redirects=False,
|
||||
)
|
||||
@@ -293,23 +343,34 @@ def create_app(settings: Settings | str = "config.yaml") -> FastAPI:
|
||||
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:
|
||||
attachments.close()
|
||||
|
||||
async def prepare_with_budget():
|
||||
async with asyncio.timeout(settings.limits.upstream_timeout_seconds):
|
||||
return await prepare()
|
||||
|
||||
response = None
|
||||
try:
|
||||
return await until_disconnect(prepare_with_budget(), request.receive)
|
||||
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):
|
||||
attachments.close()
|
||||
|
||||
return app
|
||||
+24
-5
@@ -7,6 +7,7 @@ from datetime import UTC, datetime
|
||||
from pathlib import Path
|
||||
from uuid import uuid4
|
||||
|
||||
from .attachments import validate_multipart
|
||||
from .config import Settings
|
||||
from .errors import LimitExceeded, Overloaded, PluginFailure, PolicyBlocked
|
||||
from .llm import LLMRegistry
|
||||
@@ -18,8 +19,9 @@ ADAPTER_ID = "__protocol_adapter__"
|
||||
|
||||
|
||||
class Session:
|
||||
def __init__(self, manager, request_id=None, plugins=None):
|
||||
def __init__(self, manager, request_id=None, plugins=None, attachments=None):
|
||||
self.manager = manager
|
||||
self.attachments = attachments
|
||||
self.plugins = list(manager.plugins if plugins is None else plugins)
|
||||
self.context = {"request_id": request_id or str(uuid4())}
|
||||
self.started = time.monotonic()
|
||||
@@ -86,6 +88,10 @@ class Session:
|
||||
result["value"],
|
||||
self.manager.settings.limits.max_request_bytes,
|
||||
)
|
||||
elif result["kind"] == "files":
|
||||
if self.attachments is None or plugin == ADAPTER_ID:
|
||||
raise PluginFailure()
|
||||
reply["value"] = self.attachments.read_text(result["value"])
|
||||
elif result["kind"] == "log":
|
||||
reply["value"] = None
|
||||
logger.info(
|
||||
@@ -177,6 +183,10 @@ class Session:
|
||||
for item in values:
|
||||
result = await self.invoke(plugin.id, hook, item)
|
||||
output.extend(self.decision(result, item, hook))
|
||||
if hook == "on_request" and self.attachments is not None:
|
||||
for candidate in output:
|
||||
# Validate every stage so later plugins never see forged file metadata.
|
||||
validate_multipart(candidate, item)
|
||||
if hook == "on_event":
|
||||
self.check_events_size(output)
|
||||
values = output
|
||||
@@ -252,8 +262,14 @@ class Session:
|
||||
except Exception:
|
||||
continue
|
||||
finally:
|
||||
await self.kill()
|
||||
self.manager.sessions.discard(self)
|
||||
try:
|
||||
await self.kill()
|
||||
finally:
|
||||
try:
|
||||
if self.attachments is not None:
|
||||
self.attachments.close()
|
||||
finally:
|
||||
self.manager.sessions.discard(self)
|
||||
|
||||
|
||||
class PluginManager:
|
||||
@@ -280,6 +296,7 @@ class PluginManager:
|
||||
limits.max_response_bytes,
|
||||
limits.max_plugin_buffer_bytes,
|
||||
limits.max_sse_frame_bytes,
|
||||
2 * limits.max_attachment_text_bytes,
|
||||
*(p.network.max_response_bytes for p in self.plugins),
|
||||
)
|
||||
+ 65536
|
||||
@@ -295,14 +312,16 @@ class PluginManager:
|
||||
await self.llm.start()
|
||||
self.llm_started = True
|
||||
|
||||
async def open(self, request_id=None, path=None, adapter_only=False, all_plugins=False):
|
||||
async def open(
|
||||
self, request_id=None, path=None, adapter_only=False, all_plugins=False, attachments=None
|
||||
):
|
||||
if self.stopping or len(self.sessions) >= self.settings.limits.max_sessions:
|
||||
raise Overloaded()
|
||||
if path is None and not adapter_only and not all_plugins:
|
||||
raise ValueError("path is required when opening a plugin session")
|
||||
await self.start()
|
||||
plugins = self.plugins if all_plugins else self.plugins_for_path(path)
|
||||
session = Session(self, request_id, plugins)
|
||||
session = Session(self, request_id, plugins, attachments)
|
||||
self.sessions.add(session)
|
||||
try:
|
||||
await session.initialize(adapter_only)
|
||||
|
||||
@@ -62,6 +62,9 @@ class LuaPlugin:
|
||||
self.callback("http", self.to_python(request)),
|
||||
)
|
||||
host["http"] = http
|
||||
files = self.lua.table()
|
||||
files["read_text"] = lambda file_id: self.to_lua(self.callback("files", file_id))
|
||||
host["files"] = files
|
||||
llm = self.lua.table()
|
||||
llm["list"] = lambda: self.to_lua(llm_models or [])
|
||||
llm["call"] = lambda model, request: self.to_lua(
|
||||
|
||||
@@ -12,6 +12,8 @@ dependencies = [
|
||||
"aiohttp==3.14.4",
|
||||
"PyYAML==6.0.3",
|
||||
"lupa==2.8",
|
||||
"python-multipart>=0.0.22,<0.1",
|
||||
"python-docx>=1.2,<2",
|
||||
"uvicorn>=0.35,<1",
|
||||
"torch>=2.2",
|
||||
"transformers>=4.51,<5"
|
||||
|
||||
@@ -0,0 +1,692 @@
|
||||
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})
|
||||
Reference in new issue
Block a user