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:
starrrLight committed 2026-10-15 18:03:23 +08:00
1 parent 7f0ae69252
commit 8ad4b29e4c
12 files changed
+1233 -15

No files matched your search

+207
View File
@@ -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()
+7
View File
@@ -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)
+153
View File
@@ -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
View File
@@ -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
View File
@@ -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)
+3
View File
@@ -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(