新增宿主侧精确路径匹配和插件级 match.paths 配置。\n按请求路径固定插件会话链,移除 Lua 插件内的路径判断与 bypass 状态,并迁移现有插件配置和测试。
217 lines
7.6 KiB
Python
217 lines
7.6 KiB
Python
import ipaddress
|
|
from pathlib import Path
|
|
from typing import Literal
|
|
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 LLMLoadConfig(Model):
|
|
device: str = "cpu"
|
|
dtype: Literal["auto", "float16", "bfloat16", "float32"] = "auto"
|
|
revision: str | None = None
|
|
|
|
|
|
class LLMLimits(Model):
|
|
max_input_tokens: int = Field(default=4096, gt=0, le=32768)
|
|
max_new_tokens: int = Field(default=32, gt=0, le=512)
|
|
timeout_seconds: float = Field(default=3, gt=0, le=60)
|
|
max_concurrency: int = Field(default=1, gt=0, le=1)
|
|
queue_size: int = Field(default=8, gt=0, le=1024)
|
|
|
|
|
|
class LLMConfig(Model):
|
|
id: str = Field(pattern=r"^[a-zA-Z0-9_.-]{1,128}$")
|
|
type: Literal["guard"]
|
|
backend: Literal["transformers"] = "transformers"
|
|
file: Path
|
|
enabled: bool = True
|
|
load: LLMLoadConfig = Field(default_factory=LLMLoadConfig)
|
|
limits: LLMLimits = Field(default_factory=LLMLimits)
|
|
|
|
|
|
class PluginLLMAccess(Model):
|
|
allow: list[str] = Field(default_factory=list)
|
|
|
|
|
|
class PluginMatch(Model):
|
|
paths: list[str] = Field(min_length=1)
|
|
|
|
@field_validator("paths")
|
|
@classmethod
|
|
def paths_valid(cls, value: list[str]) -> list[str]:
|
|
if len(value) != len(set(value)):
|
|
raise ValueError("plugin match.paths contains a duplicate path")
|
|
for path in value:
|
|
if not path.startswith("/"):
|
|
raise ValueError("plugin match.paths entries must be absolute paths")
|
|
if any(ord(char) < 0x20 or ord(char) == 0x7F for char in path):
|
|
raise ValueError("plugin match.paths entries must not contain control characters")
|
|
if any(char in path for char in "*?#"):
|
|
raise ValueError("plugin match.paths entries must be exact paths without wildcards")
|
|
return value
|
|
|
|
def matches(self, path: str) -> bool:
|
|
return path in self.paths
|
|
|
|
|
|
class PluginConfig(Model):
|
|
id: str = Field(pattern=r"^[a-zA-Z0-9_-]{1,64}$")
|
|
file: Path
|
|
enabled: bool = True
|
|
match: PluginMatch | None = None
|
|
config: dict = Field(default_factory=dict)
|
|
network: NetworkPolicy = Field(default_factory=NetworkPolicy)
|
|
llm: PluginLLMAccess = Field(default_factory=PluginLLMAccess)
|
|
|
|
@model_validator(mode="after")
|
|
def reject_legacy_path_match(self):
|
|
if "paths" in self.config:
|
|
raise ValueError(f"plugin {self.id}: config.paths is unsupported; use match.paths")
|
|
return self
|
|
|
|
|
|
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)
|
|
llm: list[LLMConfig] = Field(default_factory=list)
|
|
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")
|
|
model_ids = [model.id for model in self.llm]
|
|
if len(model_ids) != len(set(model_ids)):
|
|
raise ValueError("duplicate llm IDs")
|
|
models = {model.id: model for model in self.llm}
|
|
for plugin in self.plugins:
|
|
for model_id in plugin.llm.allow:
|
|
model = models.get(model_id)
|
|
if model is None:
|
|
raise ValueError(f"unknown llm model: {model_id}")
|
|
if not model.enabled:
|
|
raise ValueError(f"disabled llm model: {model_id}")
|
|
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}))
|
|
models = []
|
|
for model in settings.llm:
|
|
file = model.file.resolve()
|
|
if not file.exists():
|
|
raise ValueError(f"llm model path not found: {model.id}")
|
|
models.append(model.model_copy(update={"file": file}))
|
|
return settings.model_copy(update={"plugins": plugins, "llm": models})
|