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
+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
|
||||
Reference in new issue
Block a user