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,140 @@
|
||||
import ipaddress
|
||||
from pathlib import Path
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
import yaml
|
||||
from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
|
||||
|
||||
|
||||
def normalize_domain(value: str) -> str:
|
||||
value = value.rstrip(".").lower()
|
||||
try:
|
||||
value = value.encode("idna").decode("ascii")
|
||||
except UnicodeError:
|
||||
raise ValueError("invalid domain") from None
|
||||
labels = value.split(".")
|
||||
if len(value) > 253 or any(
|
||||
not label
|
||||
or len(label) > 63
|
||||
or label.startswith("-")
|
||||
or label.endswith("-")
|
||||
or not all(c.isascii() and (c.isalnum() or c == "-") for c in label)
|
||||
for label in labels
|
||||
):
|
||||
raise ValueError("invalid domain")
|
||||
try:
|
||||
ipaddress.ip_address(value)
|
||||
except ValueError:
|
||||
return value
|
||||
raise ValueError("IP literals are not domains")
|
||||
|
||||
|
||||
class Model(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid", frozen=True)
|
||||
|
||||
|
||||
class NetworkRule(Model):
|
||||
domain: str
|
||||
scheme: str = "https"
|
||||
ports: list[int] = Field(default_factory=lambda: [443], min_length=1)
|
||||
cidrs: list[str] = Field(default_factory=list)
|
||||
|
||||
@field_validator("domain")
|
||||
@classmethod
|
||||
def domain_valid(cls, value: str) -> str:
|
||||
wildcard = value.startswith("*.")
|
||||
return ("*." if wildcard else "") + normalize_domain(value[2:] if wildcard else value)
|
||||
|
||||
@field_validator("scheme")
|
||||
@classmethod
|
||||
def scheme_valid(cls, value: str) -> str:
|
||||
if value not in {"https", "http"}:
|
||||
raise ValueError("only http/https are supported")
|
||||
return value
|
||||
|
||||
@field_validator("ports")
|
||||
@classmethod
|
||||
def ports_valid(cls, value: list[int]) -> list[int]:
|
||||
if any(not 1 <= port <= 65535 for port in value):
|
||||
raise ValueError("invalid port")
|
||||
return value
|
||||
|
||||
@field_validator("cidrs")
|
||||
@classmethod
|
||||
def cidrs_valid(cls, value: list[str]) -> list[str]:
|
||||
for item in value:
|
||||
ipaddress.ip_network(item, strict=True)
|
||||
return value
|
||||
|
||||
def matches(self, hostname: str, scheme: str, port: int) -> bool:
|
||||
domain = self.domain
|
||||
domain_match = (
|
||||
hostname.endswith(domain[1:]) if domain.startswith("*.") else hostname == domain
|
||||
)
|
||||
return domain_match and scheme == self.scheme and port in self.ports
|
||||
|
||||
|
||||
class NetworkPolicy(Model):
|
||||
allow: list[NetworkRule] = Field(default_factory=list)
|
||||
timeout_seconds: float = Field(default=3, gt=0, le=60)
|
||||
max_response_bytes: int = Field(default=1024 * 1024, gt=0)
|
||||
|
||||
|
||||
class PluginConfig(Model):
|
||||
id: str = Field(pattern=r"^[a-zA-Z0-9_-]{1,64}$")
|
||||
file: Path
|
||||
enabled: bool = True
|
||||
config: dict = Field(default_factory=dict)
|
||||
network: NetworkPolicy = Field(default_factory=NetworkPolicy)
|
||||
|
||||
|
||||
class Limits(Model):
|
||||
max_sessions: int = Field(default=4, gt=0)
|
||||
hook_timeout_seconds: float = Field(default=5, gt=0)
|
||||
lua_memory_bytes: int = Field(default=32 * 1024 * 1024, gt=0)
|
||||
max_request_bytes: int = Field(default=2 * 1024 * 1024, gt=0)
|
||||
max_response_bytes: int = Field(default=2 * 1024 * 1024, gt=0)
|
||||
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)
|
||||
upstream_timeout_seconds: float = Field(default=120, gt=0)
|
||||
|
||||
|
||||
class Settings(Model):
|
||||
upstream: str
|
||||
listen_host: str = "0.0.0.0"
|
||||
listen_port: int = Field(default=8080, ge=1, le=65535)
|
||||
limits: Limits = Field(default_factory=Limits)
|
||||
plugins: list[PluginConfig] = Field(default_factory=list)
|
||||
|
||||
@field_validator("upstream")
|
||||
@classmethod
|
||||
def upstream_valid(cls, value: str) -> str:
|
||||
url = urlsplit(value)
|
||||
if url.scheme not in {"http", "https"} or not url.hostname or url.username is not None:
|
||||
raise ValueError("invalid fixed upstream URL")
|
||||
if url.query or url.fragment:
|
||||
raise ValueError("upstream cannot contain query or fragment")
|
||||
_ = url.port
|
||||
return value.rstrip("/")
|
||||
|
||||
@model_validator(mode="after")
|
||||
def plugins_valid(self):
|
||||
ids = [p.id for p in self.plugins]
|
||||
if len(ids) != len(set(ids)):
|
||||
raise ValueError("duplicate plugin IDs")
|
||||
return self
|
||||
|
||||
|
||||
def load_settings(path: str | Path) -> Settings:
|
||||
path = Path(path).resolve()
|
||||
with path.open(encoding="utf-8") as file:
|
||||
raw = yaml.safe_load(file)
|
||||
settings = Settings.model_validate(raw)
|
||||
plugins = []
|
||||
for plugin in settings.plugins:
|
||||
file = (path.parent / plugin.file).resolve()
|
||||
if not file.is_file():
|
||||
raise ValueError(f"plugin file not found: {plugin.id}")
|
||||
plugins.append(plugin.model_copy(update={"file": file}))
|
||||
return settings.model_copy(update={"plugins": plugins})
|
||||
Reference in new issue
Block a user