支持任意 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 转换及镜像构建未验证。
208 lines
7.1 KiB
Python
208 lines
7.1 KiB
Python
"""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()
|