feat(中间层): 实现 Lua 插件驱动的安全代理
新增固定上游的 HTTP/SSE 转发、Lua 插件生命周期和请求级进程隔离。 实现逐插件域名与内网白名单、DNS 地址固定、超时取消和受控错误收尾。 提供三个 Lua 示例插件、配置与开发文档、Docker 和 APISIX 部署示例。 通过 65 项测试及静态检查,验证真实 TCP 流式转发、取消、资源限制和 Windows 命令行启动。
This commit is contained in:
commit
d0bb045134
28 files changed
+2764
No files matched your search
@@ -0,0 +1,104 @@
|
||||
"""SSE framing only; application data stays opaque to the host."""
|
||||
|
||||
from collections.abc import AsyncIterable, AsyncIterator
|
||||
|
||||
from .errors import LimitExceeded, PluginFailure
|
||||
|
||||
|
||||
def parse_frame(lines: list[str]) -> dict:
|
||||
event = {"data": "", "comments": []}
|
||||
data = []
|
||||
for line in lines:
|
||||
if line.startswith(":"):
|
||||
event["comments"].append(line[1:])
|
||||
continue
|
||||
name, sep, value = line.partition(":")
|
||||
if sep and value.startswith(" "):
|
||||
value = value[1:]
|
||||
if name == "data":
|
||||
data.append(value)
|
||||
elif name in {"event", "id"}:
|
||||
if name != "id" or "\x00" not in value:
|
||||
event[name] = value
|
||||
elif name == "retry" and value.isascii() and value.isdigit():
|
||||
event["retry"] = int(value)
|
||||
event["data"] = "\n".join(data)
|
||||
event["has_data"] = bool(data)
|
||||
return event
|
||||
|
||||
|
||||
async def decode_sse(chunks: AsyncIterable[bytes], max_frame_bytes: int) -> AsyncIterator[dict]:
|
||||
# Byte-level line framing preserves split UTF-8 without unbounded chunk accumulation.
|
||||
line = bytearray()
|
||||
lines = []
|
||||
frame_size = 0
|
||||
after_cr = False
|
||||
first_line = True
|
||||
async for chunk in chunks:
|
||||
for byte in chunk:
|
||||
frame_size += 1
|
||||
if frame_size > max_frame_bytes:
|
||||
raise LimitExceeded()
|
||||
if after_cr:
|
||||
after_cr = False
|
||||
if byte == 10:
|
||||
continue
|
||||
if byte not in (10, 13):
|
||||
line.append(byte)
|
||||
continue
|
||||
text = bytes(line).decode("utf-8", errors="strict")
|
||||
line.clear()
|
||||
if first_line:
|
||||
text = text.removeprefix("\ufeff")
|
||||
first_line = False
|
||||
after_cr = byte == 13
|
||||
if text:
|
||||
lines.append(text)
|
||||
else:
|
||||
if lines:
|
||||
yield parse_frame(lines)
|
||||
lines = []
|
||||
frame_size = 0
|
||||
# SSE dispatches only complete frames; a partial final frame is not trusted/released.
|
||||
if line or lines:
|
||||
raise PluginFailure()
|
||||
|
||||
|
||||
def encode_sse(event: dict, max_frame_bytes: int) -> bytes:
|
||||
if not isinstance(event, dict) or set(event) - {
|
||||
"event",
|
||||
"id",
|
||||
"data",
|
||||
"comments",
|
||||
"retry",
|
||||
"has_data",
|
||||
}:
|
||||
raise PluginFailure()
|
||||
lines = []
|
||||
comments = event.get("comments", [])
|
||||
if not isinstance(comments, list):
|
||||
raise PluginFailure()
|
||||
for comment in comments:
|
||||
if not isinstance(comment, str) or "\r" in comment or "\n" in comment:
|
||||
raise PluginFailure()
|
||||
lines.append(":" + comment)
|
||||
for field in ("event", "id"):
|
||||
if field in event:
|
||||
value = event[field]
|
||||
if not isinstance(value, str) or any(c in value for c in "\r\n\x00"):
|
||||
raise PluginFailure()
|
||||
lines.append(f"{field}: {value}")
|
||||
if "retry" in event:
|
||||
retry = event["retry"]
|
||||
if type(retry) is not int or retry < 0:
|
||||
raise PluginFailure()
|
||||
lines.append(f"retry: {retry}")
|
||||
if event.get("has_data", "data" in event):
|
||||
data = event.get("data", "")
|
||||
if not isinstance(data, str) or "\r" in data:
|
||||
raise PluginFailure()
|
||||
lines.extend("data: " + part for part in data.split("\n"))
|
||||
encoded = ("\n".join(lines) + "\n\n").encode("utf-8")
|
||||
if len(encoded) > max_frame_bytes:
|
||||
raise LimitExceeded()
|
||||
return encoded
|
||||
Reference in new issue
Block a user