fix: 修复 P0/P1 缺陷,安装器改用国内镜像
23 个文件变更
+1062
-92
fqh@fangqihang.cn
| •Makefile | +9 -3 |
| •internal/appstore/appstore_test.go | +45 -0 |
| •internal/appstore/install.go | +150 -39 |
| •internal/appstore/nginx_group_test.go | +69 -0 |
| •internal/appstore/phpmyadmin.go | +17 -0 |
| •internal/appstore/service.go | +12 -1 |
| •internal/files/service.go | +60 -4 |
| •internal/files/upload_test.go | +74 -0 |
| •internal/httpapi/auth.go | +9 -0 |
| •internal/httpapi/docker.go | +15 -2 |
| •internal/httpapi/files.go | +13 -8 |
| •internal/httpapi/plugins.go | +25 -3 |
| •internal/httpapi/settings.go | +12 -0 |
| •internal/site/site.go | +188 -9 |
| •internal/site/site_options_test.go | +76 -0 |
| •internal/store/models.go | +25 -0 |
| •internal/waf/rule_validate_test.go | +30 -0 |
| •internal/waf/waf.go | +52 -4 |
| •internal/wafgw/gateway.go | +83 -7 |
| •internal/wafgw/gateway_test.go | +25 -11 |
| •internal/webserver/manager.go | +14 -0 |
| •internal/webserver/render.go | +18 -1 |
| •internal/webserver/render_keep_test.go | +41 -0 |
变更内容
diff --git a/Makefile b/Makefile
index 01f67ad..d435811 100644
--- a/Makefile
+++ b/Makefile
@@ -1,10 +1,10 @@
APP := miaopanel
-VERSION ?= 1.2.1
+VERSION ?= 1.2.8
COMMIT := $(shell git rev-parse --short HEAD 2>/dev/null || echo none)
DATE := $(shell date -u +%Y-%m-%dT%H:%M:%SZ)
LDFLAGS := -s -w -X main.version=$(VERSION) -X main.commit=$(COMMIT) -X main.buildDate=$(DATE)
-.PHONY: all web build build-linux-amd64 test fmt clean run
+.PHONY: all web build build-linux-amd64 build-linux-arm64 release test fmt clean run
all: web build
@@ -14,11 +14,17 @@ web:
build:
CGO_ENABLED=0 go build -trimpath -ldflags "$(LDFLAGS)" -o $(APP) .
-# 发布只出 linux/amd64 一个平台,产物带版本号并附带 sha256。
+# 发布出 linux/amd64 与 linux/arm64 两个平台,产物带版本号并附带 sha256。
build-linux-amd64: web
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -trimpath -ldflags "$(LDFLAGS)" -o dist/$(APP)-$(VERSION)-linux-amd64 .
cd dist && sha256sum $(APP)-$(VERSION)-linux-amd64 > $(APP)-$(VERSION)-linux-amd64.sha256
+build-linux-arm64: web
+ CGO_ENABLED=0 GOOS=linux GOARCH=arm64 go build -trimpath -ldflags "$(LDFLAGS)" -o dist/$(APP)-$(VERSION)-linux-arm64 .
+ cd dist && sha256sum $(APP)-$(VERSION)-linux-arm64 > $(APP)-$(VERSION)-linux-arm64.sha256
+
+release: build-linux-amd64 build-linux-arm64
+
test:
go vet ./...
go test ./...
diff --git a/internal/appstore/appstore_test.go b/internal/appstore/appstore_test.go
index 976f2fa..14f3fb7 100644
--- a/internal/appstore/appstore_test.go
+++ b/internal/appstore/appstore_test.go
@@ -121,6 +121,51 @@ func TestNginxScriptHandlesDowngradeAndModuleABI(t *testing.T) {
}
}
+// TestInstallScriptsAvoidSigPipe guards the failure mode seen in the field:
+// a consumer that exits before draining stdin (grep -q, head, "awk ... exit")
+// makes the producer die of SIGPIPE, and `set -o pipefail` turns that into
+// "安装失败: exit status 141" with no hint about the real step. Ubuntu 24.04 +
+// nginx 1.30.6 reproduced it on `apt-cache madison nginx | awk ... exit`.
+func TestInstallScriptsAvoidSigPipe(t *testing.T) {
+ s := testService()
+ ctx := context.Background()
+ check := func(name, script string) {
+ for _, line := range strings.Split(script, "\n") {
+ trimmed := strings.TrimSpace(line)
+ if trimmed == "" || strings.HasPrefix(trimmed, "#") {
+ continue
+ }
+ if strings.Contains(line, "| grep -q") || strings.Contains(line, "|grep -q") ||
+ strings.Contains(line, "| head") || strings.Contains(line, "|head ") {
+ t.Fatalf("%s: consumer exits early on a pipe (%q); use `>/dev/null` after grep or write to a file first", name, trimmed)
+ }
+ // "END { exit !found }" still drains stdin, so only an exit in the
+ // per-record action block is unsafe.
+ if strings.Contains(line, "| awk") && strings.Contains(line, "exit") &&
+ !strings.Contains(line, "END {") {
+ t.Fatalf("%s: awk exits early on a pipe (%q); the producer would take SIGPIPE", name, trimmed)
+ }
+ }
+ }
+ for _, app := range catalog {
+ if app.ID == "python" {
+ continue // resolved from the network at install time
+ }
+ for _, ver := range app.Versions {
+ script, err := s.installScript(ctx, app, ver)
+ if err != nil {
+ t.Fatalf("%s: %v", app.ID, err)
+ }
+ check(app.ID+" install", script)
+ uninstall, err := s.uninstallScript(app, ver)
+ if err != nil {
+ t.Fatalf("%s uninstall: %v", app.ID, err)
+ }
+ check(app.ID+" uninstall", uninstall)
+ }
+ }
+}
+
func TestMySQLUninstallRemovesCorePackage(t *testing.T) {
s := testService()
script, err := s.uninstallScript(mustApp("mysql"), Version{Version: "8.4.13"})
diff --git a/internal/appstore/install.go b/internal/appstore/install.go
index c0b79a8..29b0821 100644
--- a/internal/appstore/install.go
+++ b/internal/appstore/install.go
@@ -22,10 +22,27 @@ import (
var versionRe = regexp.MustCompile(`^[0-9][0-9A-Za-z.+~-]*$`)
+// nginxFpmGroupSnippet fixes the mismatch between nginx.org packages (workers
+// run as "nginx") and distro PHP-FPM (sockets are www-data:www-data 0660).
+// Without the shared group every PHP site answers 502 right after install.
+const nginxFpmGroupSnippet = `
+if id nginx >/dev/null 2>&1; then
+ NGINX_GROUPS=$(id -nG nginx 2>/dev/null | tr ' ' '\n')
+ if ! printf '%%s\n' "$NGINX_GROUPS" | grep -x www-data >/dev/null; then
+ echo "==> 将 nginx 用户加入 www-data 组,否则 PHP-FPM socket 无法连接"
+ usermod -aG www-data nginx
+ systemctl restart nginx 2>/dev/null || true
+ fi
+fi
+`
+
const scriptHeader = `set -euo pipefail
export DEBIAN_FRONTEND=noninteractive
export LANG=C.UTF-8
export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
+# Surface the failing command in the task log; "exit status 1" alone leaves the
+# operator guessing. ERR does not change the exit code.
+trap 'echo "==> 第 $LINENO 行失败: $BASH_COMMAND"' ERR
`
func (s *Service) installScript(ctx context.Context, def AppDef, ver Version) (string, error) {
@@ -158,24 +175,46 @@ if ! curl -fsSL --max-time 20 -o /dev/null "$REPO/dists/$CODENAME/Release"; then
fi
apt-get install -y --no-install-recommends gnupg ca-certificates curl
install -d -m 0755 /usr/share/keyrings
-curl -fsSL https://nginx.org/keys/nginx_signing.key | gpg --dearmor --yes -o /usr/share/keyrings/nginx-archive-keyring.gpg
-printf 'deb [signed-by=/usr/share/keyrings/nginx-archive-keyring.gpg] %%s %%s nginx\n' "$REPO" "$CODENAME" > /etc/apt/sources.list.d/nginx.list
+# Fetch the key into a file first: piping curl into gpg turns a slow or broken
+# download into SIGPIPE (141) once gpg gives up, and pipefail then reports an
+# opaque "exit status 141" instead of a download error.
+KEYRING=/usr/share/keyrings/nginx-archive-keyring.gpg
+# Private temporary paths: a predictable name under /tmp let a local user
+# pre-create a symlink and make root's curl write through it.
+KEY=$(mktemp /tmp/mp-nginx-key.XXXXXX)
+if curl -fsSL --max-time 30 -o "$KEY" https://nginx.org/keys/nginx_signing.key; then
+ if ! gpg --dearmor --yes -o "$KEYRING" "$KEY"; then
+ echo "==> nginx.org 签名密钥格式异常,已停止安装"; rm -f "$KEY"; exit 1
+ fi
+ rm -f "$KEY"
+elif [ -s "$KEYRING" ]; then
+ echo "==> 下载 nginx.org 签名密钥失败,继续使用已有的 $KEYRING"
+else
+ echo "==> 下载 nginx.org 签名密钥失败,请检查服务器能否访问 nginx.org"; exit 1
+fi
+printf 'deb [signed-by=%%s] %%s %%s nginx\n' "$KEYRING" "$REPO" "$CODENAME" > /etc/apt/sources.list.d/nginx.list
apt-get update -qq || echo "==> 警告:apt-get update 有源失败,继续尝试使用现有索引"
-VER=$(apt-cache madison nginx | awk -v v="%s" '$3 ~ "^" v "-" {print $3; exit}')
+# Never pipe apt-cache into a consumer that exits early (awk ... exit, head):
+# apt-cache keeps writing, gets SIGPIPE, and pipefail turns that into exit 141.
+MADISON=$(mktemp /tmp/mp-nginx-madison.XXXXXX)
+apt-cache madison nginx > "$MADISON" 2>/dev/null || true
+VER=$(awk -v v="%s" '$3 ~ "^" v "-" {print $3; exit}' "$MADISON")
if [ -z "$VER" ]; then
# Not every patch level is built for every Debian/Ubuntu release (for
# example 1.30.6 has no bullseye package). Fall back to the newest patch in
# the same minor branch instead of failing the whole install.
- VER=$(apt-cache madison nginx | awk -v v="%s." '$3 ~ "^" v {print $3}' | sort -V | tail -n 1)
+ VER=$(awk -v v="%s." '$3 ~ "^" v {print $3}' "$MADISON" | sort -V | tail -n 1)
if [ -n "$VER" ]; then
echo "==> 目标版本 %s 在当前发行版不可用,改用同分支最新 $VER"
fi
fi
if [ -z "$VER" ]; then
echo "软件源中未找到 nginx %s,可用版本:"
- apt-cache madison nginx | awk '{print " " $3}' | sort -u
+ awk '{print " " $3}' "$MADISON" | sort -u
+ rm -f "$MADISON"
exit 1
fi
+rm -f "$MADISON"
echo "==> 安装 nginx $VER"
# allow-downgrades is required when switching 1.30 -> 1.28; confold keeps the
# operator's nginx.conf instead of prompting during an unattended install.
@@ -204,7 +243,9 @@ php -v
CODENAME="${VERSION_CODENAME:-bookworm}"
echo "==> 配置 Sury PHP 源 ($CODENAME)"
apt-get install -y --no-install-recommends gnupg ca-certificates
-curl -fsSL https://packages.sury.org/php/apt.gpg -o /usr/share/keyrings/sury-php.gpg
+if ! curl -fsSL --max-time 30 -o /usr/share/keyrings/sury-php.gpg https://packages.sury.org/php/apt.gpg; then
+ echo "==> 下载 Sury PHP 源签名密钥失败,请检查服务器能否访问 packages.sury.org"; exit 1
+fi
printf 'deb [signed-by=/usr/share/keyrings/sury-php.gpg] https://packages.sury.org/php/ %%s main\n' "$CODENAME" > /etc/apt/sources.list.d/sury-php.list
apt-get update -qq
CORE="php%s-fpm php%s-cli php%s-common php%s-mysql"
@@ -221,7 +262,7 @@ fi
apt-get install -y --no-install-recommends $EXTRA || echo "部分 PHP 扩展不可用,已跳过"
systemctl enable --now php%s-fpm
php%s -v
-`, version, version, version, version, version, version, version, version, version, version, version,
+`+nginxFpmGroupSnippet, version, version, version, version, version, version, version, version, version, version, version,
version, version, version)
}
@@ -232,8 +273,14 @@ echo "==> 配置 MariaDB 官方源并安装 %s"
if systemctl is-active --quiet mysql || systemctl is-active --quiet mysqld; then
echo "检测到 MySQL 正在运行,请先在应用商店卸载 MySQL"; exit 1
fi
-curl -LsS https://r.mariadb.com/downloads/mariadb_repo_setup -o /tmp/mariadb_repo_setup
-bash /tmp/mariadb_repo_setup --mariadb-server-version="mariadb-%s" --skip-maxscale --skip-tools
+MARIADB_SETUP=$(mktemp /tmp/mp-mariadb-setup.XXXXXX)
+if ! curl -fsSL --max-time 60 -o "$MARIADB_SETUP" https://r.mariadb.com/downloads/mariadb_repo_setup; then
+ echo "==> 下载 MariaDB 源安装脚本失败,请检查服务器能否访问 r.mariadb.com"; rm -f "$MARIADB_SETUP"; exit 1
+fi
+if ! bash "$MARIADB_SETUP" --mariadb-server-version="mariadb-%s" --skip-maxscale --skip-tools; then
+ echo "==> 配置 MariaDB 官方源失败"; rm -f "$MARIADB_SETUP"; exit 1
+fi
+rm -f "$MARIADB_SETUP"
$PKG install -y mariadb-server mariadb-client
systemctl enable --now mariadb
mariadb --version
@@ -244,8 +291,14 @@ echo "==> 配置 MariaDB 官方源并安装 %s"
if systemctl is-active --quiet mysql || systemctl is-active --quiet mysqld; then
echo "检测到 MySQL 正在运行,请先在应用商店卸载 MySQL"; exit 1
fi
-curl -LsS https://r.mariadb.com/downloads/mariadb_repo_setup -o /tmp/mariadb_repo_setup
-bash /tmp/mariadb_repo_setup --mariadb-server-version="mariadb-%s" --skip-maxscale --skip-tools
+MARIADB_SETUP=$(mktemp /tmp/mp-mariadb-setup.XXXXXX)
+if ! curl -fsSL --max-time 60 -o "$MARIADB_SETUP" https://r.mariadb.com/downloads/mariadb_repo_setup; then
+ echo "==> 下载 MariaDB 源安装脚本失败,请检查服务器能否访问 r.mariadb.com"; rm -f "$MARIADB_SETUP"; exit 1
+fi
+if ! bash "$MARIADB_SETUP" --mariadb-server-version="mariadb-%s" --skip-maxscale --skip-tools; then
+ echo "==> 配置 MariaDB 官方源失败"; rm -f "$MARIADB_SETUP"; exit 1
+fi
+rm -f "$MARIADB_SETUP"
apt-get update -qq
if ! apt-get install -y --no-install-recommends mariadb-server mariadb-client; then
echo "==> apt 被中断,修复 dpkg 状态后重试一次"
@@ -315,7 +368,7 @@ echo "==> 检查现有 MySQL/MariaDB"
APT_MYSQL=0
if command -v dpkg >/dev/null 2>&1; then
for pkg in mysql-community-server mysql-community-server-core; do
- if dpkg -s "$pkg" 2>/dev/null | grep -q '^Status: install ok installed'; then
+ if dpkg -s "$pkg" 2>/dev/null | grep '^Status: install ok installed' >/dev/null; then
APT_MYSQL=1
fi
done
@@ -331,7 +384,7 @@ if systemctl is-active --quiet mariadb; then
echo "检测到 MariaDB 正在运行,请先在应用商店卸载 MariaDB"; exit 1
fi
if systemctl is-active --quiet mysql || systemctl is-active --quiet mysqld; then
- if "$ROOT/current/bin/mysql" --version 2>/dev/null | grep -q "Ver $VER" && [ -d "$BASE" ]; then
+ if "$ROOT/current/bin/mysql" --version 2>/dev/null | grep "Ver $VER" >/dev/null && [ -d "$BASE" ]; then
echo "MySQL $VER 已安装"; exit 0
fi
echo "检测到其他 MySQL 实例正在运行,请先停止或卸载"; exit 1
@@ -339,7 +392,7 @@ fi
DATA_EXISTS=0
if [ -d "$DATA" ] && [ -n "$(ls -A "$DATA" 2>/dev/null)" ]; then
- if ls "$DATA" | grep -qE 'aria_log|debian-.*\.flag'; then
+ if ls "$DATA" | grep -E 'aria_log|debian-.*\.flag' >/dev/null; then
echo "检测到 MariaDB 数据目录 $DATA,请先备份并移走"; exit 1
fi
if [ ! -f "$DATA/.mp-version" ]; then
@@ -374,7 +427,9 @@ ensure_compat_link() {
if ldconfig -p 2>/dev/null | awk -v n="$OLD" '$1 == n { found = 1 } END { exit !found }'; then
return 0
fi
- SRC=$(ldconfig -p 2>/dev/null | awk -v n="$NEW" '$1 == n { print $NF; exit }')
+ # awk must drain stdin: exiting on the first match would let ldconfig take
+ # SIGPIPE and, with pipefail, abort the install with exit status 141.
+ SRC=$(ldconfig -p 2>/dev/null | awk -v n="$NEW" '$1 == n && !found { path = $NF; found = 1 } END { if (found) print path }')
if [ -z "$SRC" ] || [ ! -e "$SRC" ]; then
return 0
fi
@@ -589,7 +644,7 @@ if [ -L "$ROOT/current" ] && [ "$(readlink "$ROOT/current")" = "$ROOT/$VER" ]; t
rm -f "$ROOT/current"
fi
for bin in mysql mysqld mysqladmin mysqldump; do
- if [ -L "/usr/local/bin/$bin" ] && readlink "/usr/local/bin/$bin" | grep -q '^/www/server/mysql/'; then
+ if [ -L "/usr/local/bin/$bin" ] && readlink "/usr/local/bin/$bin" | grep '^/www/server/mysql/' >/dev/null; then
rm -f "/usr/local/bin/$bin"
fi
done
@@ -605,7 +660,7 @@ func mysqlInstallScript(d system.Distro, version string) string {
return pkgPreamble(d) + fmt.Sprintf(`
. /etc/os-release
MAJOR="${VERSION_ID%%.*}"
-if mysql --version 2>/dev/null | grep -q "Ver %s" &&
+if mysql --version 2>/dev/null | grep "Ver %s" >/dev/null &&
systemctl cat mysqld >/dev/null 2>&1; then
echo "MySQL %s 已安装"; systemctl enable --now mysqld || true; mysql --version; exit 0
fi
@@ -646,7 +701,7 @@ mysql --version
CODENAME="${VERSION_CODENAME:-bookworm}"
COMP="mysql-8.4-lts"
if [ "%s" = "8.0" ]; then COMP="mysql-8.0"; fi
-if mysql --version 2>/dev/null | grep -q "Ver %s" &&
+if mysql --version 2>/dev/null | grep "Ver %s" >/dev/null &&
systemctl cat mysql >/dev/null 2>&1; then
echo "MySQL %s 已安装"; systemctl enable --now mysql || true; mysql --version; exit 0
fi
@@ -654,7 +709,7 @@ if systemctl is-active --quiet mariadb; then
echo "检测到 MariaDB 正在运行,请先在应用商店卸载 MariaDB"; exit 1
fi
if [ -d /var/lib/mysql ] && [ -n "$(ls -A /var/lib/mysql 2>/dev/null)" ]; then
- if ls /var/lib/mysql | grep -qE 'aria_log|debian-.*\.flag'; then
+ if ls /var/lib/mysql | grep -E 'aria_log|debian-.*\.flag' >/dev/null; then
echo "检测到 MariaDB 数据目录,请先备份并移走后再安装 MySQL"; exit 1
fi
echo "检测到已有 MySQL 数据目录,安装后将直接复用 /var/lib/mysql"
@@ -676,7 +731,16 @@ fi
echo "==> 配置 MySQL 官方 APT 源 ($CODENAME $COMP)"
apt-get install -y --no-install-recommends gnupg ca-certificates
install -d -m 0755 /usr/share/keyrings
-curl -fsSL https://repo.mysql.com/RPM-GPG-KEY-mysql-2025 | gpg --dearmor --yes -o /usr/share/keyrings/mysql.gpg
+# Fetch to a file first: piping curl into gpg reports SIGPIPE (exit 141) under
+# pipefail whenever the download fails, hiding the actual cause.
+MYSQL_KEY=$(mktemp /tmp/mp-mysql-key.XXXXXX)
+if ! curl -fsSL --max-time 30 -o "$MYSQL_KEY" https://repo.mysql.com/RPM-GPG-KEY-mysql-2025; then
+ echo "==> 下载 MySQL 签名密钥失败,请检查服务器能否访问 repo.mysql.com"; rm -f "$MYSQL_KEY"; exit 1
+fi
+if ! gpg --dearmor --yes -o /usr/share/keyrings/mysql.gpg "$MYSQL_KEY"; then
+ echo "==> MySQL 签名密钥格式异常,已停止安装"; rm -f "$MYSQL_KEY"; exit 1
+fi
+rm -f "$MYSQL_KEY"
printf 'deb [signed-by=/usr/share/keyrings/mysql.gpg] http://repo.mysql.com/apt/debian/ %%s %%s\n' "$CODENAME" "$COMP" > /etc/apt/sources.list.d/mysql.list
apt-get update -qq
apt-get install -y mysql-community-server
@@ -690,16 +754,29 @@ func goInstallScript(d system.Distro, version string) string {
ARCH=amd64
case "$(uname -m)" in aarch64|arm64) ARCH=arm64 ;; esac
DIR=/www/server/go/%s
-echo "==> 下载 Go %s ($ARCH)"
+VER=%s
+echo "==> 下载 Go $VER ($ARCH)"
+TMPD=$(mktemp -d /tmp/mp-go.XXXXXX)
+trap 'rm -rf "$TMPD"' EXIT
+GOT=0
+# go.dev is unreachable from many mainland networks; try the official mirror
+# and Aliyun before giving up, and always with a deadline so the task cannot
+# hang for the whole 45 minute budget.
+for BASE in https://go.dev/dl https://golang.google.cn/dl https://mirrors.aliyun.com/golang; do
+ echo "==> 尝试 $BASE"
+ if curl -fSL --no-progress-meter --max-time 180 --connect-timeout 15 --speed-limit 1024 --speed-time 30 --retry 2 -o "$TMPD/go.tar.gz" "$BASE/go${VER}.linux-$ARCH.tar.gz"; then GOT=1; break; fi
+ rm -f "$TMPD/go.tar.gz"
+done
+if [ "$GOT" != "1" ]; then
+ echo "==> 所有 Go 下载源均不可用(go.dev / golang.google.cn / mirrors.aliyun.com),请检查服务器网络"; exit 1
+fi
rm -rf "$DIR"
mkdir -p "$DIR"
-curl -fsSL "https://go.dev/dl/go%s.linux-$ARCH.tar.gz" -o /tmp/go-%s.tar.gz
-tar -xzf /tmp/go-%s.tar.gz -C "$DIR" --strip-components=1
-rm -f /tmp/go-%s.tar.gz
+tar -xzf "$TMPD/go.tar.gz" -C "$DIR" --strip-components=1
ln -sfn "$DIR" /www/server/go/current
if [ ! -e /usr/local/bin/go ]; then ln -s /www/server/go/current/bin/go /usr/local/bin/go; fi
/www/server/go/current/bin/go version
-`, version, version, version, version, version, version)
+`, version, version)
}
func nodeInstallScript(d system.Distro, version string) string {
@@ -708,28 +785,52 @@ ARCH=x64
case "$(uname -m)" in aarch64|arm64) ARCH=arm64 ;; esac
DIR=/www/server/node/%s
echo "==> 下载 Node.js %s ($ARCH)"
+TMPD=$(mktemp -d /tmp/mp-node.XXXXXX)
+trap 'rm -rf "$TMPD"' EXIT
+if ! curl -fSL --no-progress-meter --max-time 180 --connect-timeout 15 --speed-limit 1024 --speed-time 30 --retry 2 -o "$TMPD/node.tar.xz" "https://nodejs.org/dist/v%s/node-v%s-linux-$ARCH.tar.xz"; then
+ echo "==> 下载 Node.js 失败,请检查服务器能否访问 nodejs.org"; exit 1
+fi
rm -rf "$DIR"
mkdir -p "$DIR"
-curl -fsSL "https://nodejs.org/dist/v%s/node-v%s-linux-$ARCH.tar.xz" -o /tmp/node-%s.tar.xz
-tar -xJf /tmp/node-%s.tar.xz -C "$DIR" --strip-components=1
-rm -f /tmp/node-%s.tar.xz
+tar -xJf "$TMPD/node.tar.xz" -C "$DIR" --strip-components=1
ln -sfn "$DIR" /www/server/node/current
for bin in node npm npx; do
if [ ! -e "/usr/local/bin/$bin" ]; then ln -s "/www/server/node/current/bin/$bin" "/usr/local/bin/$bin"; fi
done
/www/server/node/current/bin/node -v
-`, version, version, version, version, version, version, version)
+`, version, version, version, version)
}
func pythonInstallScript(d system.Distro, version, url string) string {
return pkgPreamble(d) + fmt.Sprintf(`
DIR=/www/server/python/%s
echo "==> 下载 Python %s"
+TMPD=$(mktemp -d /tmp/mp-python.XXXXXX)
+trap 'rm -rf "$TMPD"' EXIT
+# GitHub releases are slow or blocked on some networks: a deadline keeps the
+# task from hanging until the 45 minute job timeout.
+PY_URL=%s
+PY_OK=0
+# The releases only live on GitHub, which is slow or unreachable from many
+# mainland networks. Try the public GitHub proxies first and fall back to the
+# origin, keeping a deadline on every attempt.
+for PREFIX in https://gh-proxy.com/ https://ghproxy.net/ ""; do
+ if [ -z "$PREFIX" ]; then
+ echo "==> 尝试 GitHub 直连"
+ else
+ echo "==> 尝试镜像 $PREFIX"
+ fi
+ if curl -fSL --no-progress-meter --max-time 600 --connect-timeout 15 --speed-limit 1024 --speed-time 30 --retry 1 -o "$TMPD/python.tar.gz" "${PREFIX}${PY_URL}"; then
+ PY_OK=1; break
+ fi
+ rm -f "$TMPD/python.tar.gz"
+done
+if [ "$PY_OK" != "1" ]; then
+ echo "==> 所有 Python 下载源均不可用(gh-proxy.com / ghproxy.net / GitHub),请检查服务器网络"; exit 1
+fi
rm -rf "$DIR"
mkdir -p "$DIR"
-curl -fsSL %s -o /tmp/python-%s.tar.gz
-tar -xzf /tmp/python-%s.tar.gz -C "$DIR" --strip-components=1
-rm -f /tmp/python-%s.tar.gz
+tar -xzf "$TMPD/python.tar.gz" -C "$DIR" --strip-components=1
ln -sfn "$DIR" /www/server/python/current
for bin in python3 pip3; do
if [ ! -e "/usr/local/bin/$bin" ] && [ -x "/www/server/python/current/bin/$bin" ]; then
@@ -737,7 +838,7 @@ for bin in python3 pip3; do
fi
done
/www/server/python/current/bin/python3 -V
-`, version, version, shQuote(url), version, version, version)
+`, version, version, shQuote(url))
}
func (s *Service) phpMyAdminInstallScript(d system.Distro, version string) string {
@@ -747,12 +848,15 @@ func (s *Service) phpMyAdminInstallScript(d system.Distro, version string) strin
BASE=%s
DIR=%s
echo "==> 下载 phpMyAdmin %s"
+TMPD=$(mktemp -d /tmp/mp-pma.XXXXXX)
+trap 'rm -rf "$TMPD"' EXIT
+if ! curl -fSL --no-progress-meter --max-time 180 --connect-timeout 15 --speed-limit 1024 --speed-time 30 --retry 2 -o "$TMPD/pma.tar.gz" "https://files.phpmyadmin.net/phpMyAdmin/%s/phpMyAdmin-%s-all-languages.tar.gz"; then
+ echo "==> 下载 phpMyAdmin 失败,请检查服务器能否访问 files.phpmyadmin.net"; exit 1
+fi
mkdir -p "$BASE"
rm -rf "$DIR"
mkdir -p "$DIR"
-curl -fsSL "https://files.phpmyadmin.net/phpMyAdmin/%s/phpMyAdmin-%s-all-languages.tar.gz" -o /tmp/phpmyadmin-%s.tar.gz
-tar -xzf /tmp/phpmyadmin-%s.tar.gz -C "$DIR" --strip-components=1
-rm -f /tmp/phpmyadmin-%s.tar.gz
+tar -xzf "$TMPD/pma.tar.gz" -C "$DIR" --strip-components=1
SECRET=$(head -c 32 /dev/urandom | od -An -tx1 | tr -d ' \n')
mkdir -p "$DIR/tmp"
# PHP-FPM runs as www-data on Debian and apache on RHEL, while panel sites
@@ -777,7 +881,7 @@ chown -R "$WEBUSER:$WEBUSER" "$DIR" 2>/dev/null || true
chmod 1733 "$DIR/tmp"
ln -sfn "$DIR" "$BASE/current"
echo "phpMyAdmin 已安装到 $DIR"
-`, shQuote(base), shQuote(dir), version, version, version, version, version, version)
+`+nginxFpmGroupSnippet, shQuote(base), shQuote(dir), version, version, version)
}
func gitInstallScript(d system.Distro) string {
@@ -813,7 +917,14 @@ if [ "${ID:-}" = "ubuntu" ]; then DOCKER_DISTRO=ubuntu; fi
apt-get update -qq
apt-get install -y --no-install-recommends gnupg ca-certificates
install -d -m 0755 /usr/share/keyrings
-curl -fsSL "https://mirrors.aliyun.com/docker-ce/linux/${DOCKER_DISTRO}/gpg" | gpg --dearmor --yes -o /usr/share/keyrings/docker-archive-keyring.gpg
+DOCKER_KEY=$(mktemp /tmp/mp-docker-key.XXXXXX)
+if ! curl -fsSL --max-time 30 -o "$DOCKER_KEY" "https://mirrors.aliyun.com/docker-ce/linux/${DOCKER_DISTRO}/gpg"; then
+ echo "==> 下载 Docker CE 签名密钥失败,请检查服务器能否访问 mirrors.aliyun.com"; exit 1
+fi
+if ! gpg --dearmor --yes -o /usr/share/keyrings/docker-archive-keyring.gpg "$DOCKER_KEY"; then
+ echo "==> Docker CE 签名密钥格式异常,已停止安装"; rm -f "$DOCKER_KEY"; exit 1
+fi
+rm -f "$DOCKER_KEY"
printf 'deb [arch=%s signed-by=/usr/share/keyrings/docker-archive-keyring.gpg] https://mirrors.aliyun.com/docker-ce/linux/%s %s stable\n' \
"$(dpkg --print-architecture)" "${DOCKER_DISTRO}" "${VERSION_CODENAME:-bookworm}" \
> /etc/apt/sources.list.d/docker.list
@@ -878,7 +989,7 @@ systemctl disable --now mysql mysqld 2>/dev/null || true
# store keep reporting MySQL as installed.
$PKG remove -y mysql-community-server mysql-community-server-core mysql-community-client mysql-community-client-core mysql-community-client-plugins mysql-client mysql-common || true
if command -v dpkg >/dev/null 2>&1; then
- if dpkg -l mysql-community-server-core 2>/dev/null | grep -q '^ii'; then
+ if dpkg -l mysql-community-server-core 2>/dev/null | grep '^ii' >/dev/null; then
echo "MySQL 核心包仍然存在,卸载未完成"; exit 1
fi
elif command -v rpm >/dev/null 2>&1; then
diff --git a/internal/appstore/nginx_group_test.go b/internal/appstore/nginx_group_test.go
new file mode 100644
index 0000000..ec2db3e
--- /dev/null
+++ b/internal/appstore/nginx_group_test.go
@@ -0,0 +1,69 @@
+package appstore
+
+import (
+ "strings"
+ "testing"
+)
+
+// nginx.org packages run workers as "nginx" while PHP-FPM sockets are
+// www-data:www-data 0660: without the shared group every PHP site answers
+// 502 immediately after a fresh install.
+func TestPHPInstallsShareSocketGroupWithNginx(t *testing.T) {
+ scripts := map[string]string{
+ "php": phpInstallScript(testDistro, "8.3"),
+ "phpmyadmin": testService().phpMyAdminInstallScript(testDistro, "5.2.2"),
+ }
+ for name, script := range scripts {
+ if !strings.Contains(script, "usermod -aG www-data nginx") {
+ t.Fatalf("%s script does not add nginx to the www-data group", name)
+ }
+ if strings.Contains(script, "| grep -q") {
+ t.Fatalf("%s script uses grep -q on a pipe", name)
+ }
+ }
+}
+
+// Every key import must fetch to a file first: "curl | gpg" reports SIGPIPE
+// (exit 141) under pipefail whenever the download fails.
+func TestInstallerKeyImportsAvoidPipes(t *testing.T) {
+ scripts := map[string]string{
+ "nginx": nginxInstallScript(testDistro, "1.26.3"),
+ "mysql": mysqlInstallScript(testDistro, "8.4"),
+ "docker": dockerInstallScript(testDistro),
+ "mariadb": mariadbInstallScript(testDistro, "10.11"),
+ }
+ for name, script := range scripts {
+ for _, line := range strings.Split(script, "\n") {
+ if strings.Contains(line, "| gpg") {
+ t.Fatalf("%s script pipes curl into gpg: %s", name, line)
+ }
+ }
+ }
+}
+
+func TestInstallerDownloadsHaveDeadlines(t *testing.T) {
+ // Anything that hangs on a blocked mirror must fail fast instead of
+ // sitting in the 45 minute task budget.
+ scripts := map[string]string{
+ "go": goInstallScript(testDistro, "1.23.4"),
+ "node": nodeInstallScript(testDistro, "20.11.0"),
+ "python": pythonInstallScript(testDistro, "3.12.7", "https://example.com/py.tar.gz"),
+ }
+ for name, script := range scripts {
+ if !strings.Contains(script, "--max-time") {
+ t.Fatalf("%s script has no download deadline", name)
+ }
+ if strings.Contains(script, "-o /tmp/") {
+ t.Fatalf("%s script writes to a predictable /tmp path", name)
+ }
+ }
+ if !strings.Contains(goInstallScript(testDistro, "1.23.4"), "golang.google.cn") {
+ t.Fatal("go installer has no mirror fallback")
+ }
+ py := pythonInstallScript(testDistro, "3.12.7", "https://github.com/astral-sh/python-build-standalone/releases/download/x/y.tar.gz")
+ for _, want := range []string{"gh-proxy.com", "ghproxy.net", "GitHub 直连"} {
+ if !strings.Contains(py, want) {
+ t.Fatalf("python installer has no mainland mirror (%q missing)", want)
+ }
+ }
+}
diff --git a/internal/appstore/phpmyadmin.go b/internal/appstore/phpmyadmin.go
index 3f7efb2..5809315 100644
--- a/internal/appstore/phpmyadmin.go
+++ b/internal/appstore/phpmyadmin.go
@@ -17,6 +17,23 @@ import (
// phpMyAdminPort is the dedicated public port of the companion site.
const phpMyAdminPort = 16520
+// removePhpMyAdminSite drops the companion site created by the installer so an
+// uninstall does not leave a vhost pointing at a deleted directory.
+func (s *Service) removePhpMyAdminSite(ctx context.Context, t *task) error {
+ if s.sites == nil {
+ return nil
+ }
+ st, err := s.sites.BySlug(ctx, "phpmyadmin")
+ if err != nil || st == nil {
+ return nil // nothing to clean up
+ }
+ if err := s.sites.Delete(ctx, st.ID, true); err != nil {
+ return fmt.Errorf("删除 phpMyAdmin 站点失败: %w", err)
+ }
+ t.append("==> 已删除 phpMyAdmin 自动站点(端口 16520)")
+ return nil
+}
+
// ensurePhpMyAdminSite creates a PHP site that exposes phpMyAdmin on
// http://<server-ip>:16520/ right after the archive has been unpacked. The
// site is only created once; a reinstall keeps the existing site.
diff --git a/internal/appstore/service.go b/internal/appstore/service.go
index 35c0889..bc95eab 100644
--- a/internal/appstore/service.go
+++ b/internal/appstore/service.go
@@ -148,7 +148,18 @@ func (s *Service) Uninstall(ctx context.Context, appID, version string) (TaskVie
if err != nil {
return TaskView{}, err
}
- return s.tasks.start(def, ver, "uninstall", script, s.runScript)
+ runner := s.runScript
+ if def.ID == "phpmyadmin" {
+ // The installer creates a site as a side effect; removing only the
+ // files used to leave a broken vhost pointing at a deleted directory.
+ runner = func(runCtx context.Context, t *task, script string) error {
+ if err := s.runScript(runCtx, t, script); err != nil {
+ return err
+ }
+ return s.removePhpMyAdminSite(runCtx, t)
+ }
+ }
+ return s.tasks.start(def, ver, "uninstall", script, runner)
}
// checkDatabaseConflict prevents installing MySQL on top of a running MariaDB
diff --git a/internal/files/service.go b/internal/files/service.go
index 0e11f79..b47bd90 100644
--- a/internal/files/service.go
+++ b/internal/files/service.go
@@ -565,8 +565,58 @@ func (s *Service) Open(p string) (*os.File, fs.FileInfo, error) {
return f, fi, nil
}
-// CreateUpload opens a destination file for streaming upload.
-func (s *Service) CreateUpload(p string) (io.WriteCloser, string, error) {
+// UploadTarget streams a file into a hidden temporary sibling. The existing
+// file is only replaced by Commit, so an interrupted or rejected upload can no
+// longer truncate the destination (an aborted 8 MB upload used to destroy the
+// 29 byte file it was overwriting).
+type UploadTarget struct {
+ svc *Service
+ file *os.File
+ tmpRel string
+ relPath string
+ display string
+ done bool
+}
+
+func (u *UploadTarget) Write(p []byte) (int, error) { return u.file.Write(p) }
+
+// Commit atomically moves the temporary file over the destination.
+func (u *UploadTarget) Commit() error {
+ if u.done {
+ return errors.New("上传已结束")
+ }
+ u.done = true
+ if err := u.file.Sync(); err != nil {
+ u.cleanup()
+ return mapError(err)
+ }
+ if err := u.file.Close(); err != nil {
+ u.cleanup()
+ return mapError(err)
+ }
+ if err := u.svc.root.Rename(u.tmpRel, u.relPath); err != nil {
+ u.cleanup()
+ return mapError(err)
+ }
+ return nil
+}
+
+// Abort drops the temporary file and leaves the destination untouched.
+func (u *UploadTarget) Abort() {
+ if u.done {
+ return
+ }
+ u.done = true
+ u.cleanup()
+}
+
+func (u *UploadTarget) cleanup() {
+ _ = u.file.Close()
+ _ = u.svc.root.Remove(u.tmpRel)
+}
+
+// CreateUpload prepares a streaming upload target for p.
+func (s *Service) CreateUpload(p string) (*UploadTarget, string, error) {
relPath, err := rel(p)
if err != nil {
return nil, "", err
@@ -582,11 +632,17 @@ func (s *Service) CreateUpload(p string) (io.WriteCloser, string, error) {
return nil, "", mapError(err)
}
}
- f, err := s.root.OpenFile(relPath, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0o644)
+ buf := make([]byte, 8)
+ if _, err := rand.Read(buf); err != nil {
+ return nil, "", err
+ }
+ tmpRel := path.Join(path.Dir(relPath), ".mp-upload-"+hex.EncodeToString(buf))
+ f, err := s.root.OpenFile(tmpRel, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0o644)
if err != nil {
return nil, "", mapError(err)
}
- return f, display(relPath), nil
+ return &UploadTarget{svc: s, file: f, tmpRel: tmpRel, relPath: relPath, display: display(relPath)},
+ display(relPath), nil
}
// Search walks the tree looking for names containing q.
diff --git a/internal/files/upload_test.go b/internal/files/upload_test.go
new file mode 100644
index 0000000..040cf2b
--- /dev/null
+++ b/internal/files/upload_test.go
@@ -0,0 +1,74 @@
+package files
+
+import "testing"
+
+// An interrupted upload must never touch the file it was replacing. The old
+// implementation opened the destination with O_TRUNC, so aborting an 8 MB
+// upload destroyed the 29 byte file underneath it.
+func TestUploadAbortLeavesExistingFileIntact(t *testing.T) {
+ s, _ := newService(t)
+ if err := s.Write("/keep.txt", "original"); err != nil {
+ t.Fatal(err)
+ }
+ up, _, err := s.CreateUpload("/keep.txt")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := up.Write([]byte("partial")); err != nil {
+ t.Fatal(err)
+ }
+ up.Abort()
+ got, err := s.Read("/keep.txt")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if got != "original" {
+ t.Fatalf("destination changed to %q after abort", got)
+ }
+}
+
+func TestUploadCommitReplacesTarget(t *testing.T) {
+ s, _ := newService(t)
+ if err := s.Write("/keep.txt", "original"); err != nil {
+ t.Fatal(err)
+ }
+ up, display, err := s.CreateUpload("/keep.txt")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if display != "/keep.txt" {
+ t.Fatalf("display path = %q", display)
+ }
+ if _, err := up.Write([]byte("replacement")); err != nil {
+ t.Fatal(err)
+ }
+ if err := up.Commit(); err != nil {
+ t.Fatal(err)
+ }
+ got, err := s.Read("/keep.txt")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if got != "replacement" {
+ t.Fatalf("commit did not replace target: %q", got)
+ }
+}
+
+// A failed upload must not leave hidden temporary files behind.
+func TestUploadAbortRemovesTempFile(t *testing.T) {
+ s, base := newService(t)
+ up, _, err := s.CreateUpload("/site/new.txt")
+ if err != nil {
+ t.Fatal(err)
+ }
+ up.Abort()
+ list, err := s.List("/site")
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, e := range list.Entries {
+ if len(e.Name) > 10 && e.Name[:10] == ".mp-upload" {
+ t.Fatalf("temp file left behind in %s: %s", base, e.Name)
+ }
+ }
+}
diff --git a/internal/httpapi/auth.go b/internal/httpapi/auth.go
index 1a17fbb..85b6c35 100644
--- a/internal/httpapi/auth.go
+++ b/internal/httpapi/auth.go
@@ -255,6 +255,15 @@ func (s *Server) handle2FASetup(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusBadRequest, Envelope{Code: 400, Msg: "密码错误"})
return
}
+ // Generating a new secret while 2FA is active used to disable it silently
+ // (SetTOTP(secret, false, "")) and wipe the recovery codes, so an operator
+ // who thought they were re-binding their authenticator lost protection.
+ if user.TOTPEnabled {
+ writeJSON(w, http.StatusBadRequest, Envelope{
+ Code: 400, Msg: "两步验证已启用,请先停用后再重新绑定验证器",
+ })
+ return
+ }
secret := security.NewTOTPSecret()
if err := s.db.SetTOTP(r.Context(), user.ID, secret, false, ""); err != nil {
writeErr(w, err)
diff --git a/internal/httpapi/docker.go b/internal/httpapi/docker.go
index 8fb5344..df7483d 100644
--- a/internal/httpapi/docker.go
+++ b/internal/httpapi/docker.go
@@ -1,6 +1,7 @@
package httpapi
import (
+ "context"
"errors"
"net/http"
"strconv"
@@ -108,17 +109,29 @@ func (s *Server) handleDockerCreate(w http.ResponseWriter, r *http.Request) {
return
}
started := time.Now()
+ // A missing image makes "docker run" pull it first, which can block for
+ // minutes. Cap the wait so the UI answers instead of spinning, and tell
+ // the operator to pull the image explicitly.
+ runCtx, cancel := context.WithTimeout(r.Context(), 3*time.Minute)
+ defer cancel()
var result *docker.CreateResult
switch req.Mode {
case "run":
- result, err = svc.CreateFromRun(r.Context(), req.Content)
+ result, err = svc.CreateFromRun(runCtx, req.Content)
case "compose":
- result, err = svc.CreateFromCompose(r.Context(), req.Project, req.Content)
+ result, err = svc.CreateFromCompose(runCtx, req.Project, req.Content)
default:
writeJSON(w, http.StatusBadRequest, Envelope{Code: 400, Msg: "mode 只能是 run 或 compose"})
return
}
if err != nil {
+ if errors.Is(err, context.DeadlineExceeded) {
+ writeJSON(w, http.StatusGatewayTimeout, Envelope{
+ Code: 504,
+ Msg: "创建容器超时:可能是镜像不存在导致在后台拉取,请先在「镜像」中手动拉取后重试",
+ })
+ return
+ }
s.writeDockerError(w, err)
return
}
diff --git a/internal/httpapi/files.go b/internal/httpapi/files.go
index 7e98f4f..4b9e55a 100644
--- a/internal/httpapi/files.go
+++ b/internal/httpapi/files.go
@@ -244,18 +244,21 @@ func (s *Server) handleFileUpload(w http.ResponseWriter, r *http.Request) {
s.writeFileError(w, err)
return
}
- written, copyErr := io.Copy(dst, io.LimitReader(file, files.MaxUploadSize))
- closeErr := dst.Close()
+ // Read one byte past the limit so an upload of exactly MaxUploadSize is
+ // accepted while anything larger is rejected and rolled back.
+ written, copyErr := io.Copy(dst, io.LimitReader(file, files.MaxUploadSize+1))
if copyErr != nil {
+ dst.Abort()
s.writeFileError(w, copyErr)
return
}
- if closeErr != nil {
- s.writeFileError(w, closeErr)
+ if written > files.MaxUploadSize {
+ dst.Abort()
+ s.writeFileError(w, files.ErrTooLarge)
return
}
- if written >= files.MaxUploadSize {
- s.writeFileError(w, files.ErrTooLarge)
+ if err := dst.Commit(); err != nil {
+ s.writeFileError(w, err)
return
}
s.audit(r, "files", "upload", displayPath, "ok", started)
@@ -337,8 +340,10 @@ func (s *Server) handleFileChmod(w http.ResponseWriter, r *http.Request) {
return
}
mode, err := strconv.ParseUint(strings.TrimPrefix(req.Mode, "0o"), 8, 32)
- if err != nil || mode > 0o7777 {
- writeJSON(w, http.StatusBadRequest, Envelope{Code: 400, Msg: "权限格式应为 644 / 0755"})
+ // 0o777 is the ceiling: Go's FileMode cannot carry the setuid/setgid bits,
+ // so accepting 4755 used to answer "ok" while writing 0755 silently.
+ if err != nil || mode > 0o777 {
+ writeJSON(w, http.StatusBadRequest, Envelope{Code: 400, Msg: "权限格式应为 644 / 0755,且不能设置 setuid/setgid 位"})
return
}
started := time.Now()
diff --git a/internal/httpapi/plugins.go b/internal/httpapi/plugins.go
index 0539080..ea0ee63 100644
--- a/internal/httpapi/plugins.go
+++ b/internal/httpapi/plugins.go
@@ -213,6 +213,7 @@ func (s *Server) handlePluginInstall(w http.ResponseWriter, r *http.Request) {
s.writePluginError(w, err)
return
}
+ dropProxyCache(slug)
s.audit(r, "plugins", "install", slug+"@"+req.Version, "started", started)
writeOK(w, task)
}
@@ -241,6 +242,7 @@ func (s *Server) handlePluginUninstall(w http.ResponseWriter, r *http.Request) {
s.writePluginError(w, err)
return
}
+ dropProxyCache(slug)
s.audit(r, "plugins", "uninstall", slug, "started", started)
writeOK(w, task)
}
@@ -357,11 +359,27 @@ func (s *Server) handlePluginEvents(w http.ResponseWriter, r *http.Request) {
writeOK(w, events)
}
+type proxyCacheEntry struct {
+ handler http.Handler
+ at time.Time
+}
+
+// proxyCacheTTL bounds how long a cached handler may outlive the plugin it
+// points at: uninstall, reinstall or an upgrade moves the socket, and a
+// permanent cache kept forwarding to the stale path until a restart.
+const proxyCacheTTL = 30 * time.Second
+
var (
proxyCacheMu sync.Mutex
- proxyCache = map[string]http.Handler{}
+ proxyCache = map[string]proxyCacheEntry{}
)
+func dropProxyCache(slug string) {
+ proxyCacheMu.Lock()
+ delete(proxyCache, slug)
+ proxyCacheMu.Unlock()
+}
+
// handlePluginProxy forwards service plugin API calls to its unix socket.
func (s *Server) handlePluginProxy(w http.ResponseWriter, r *http.Request) {
svc, err := s.pluginService()
@@ -371,8 +389,12 @@ func (s *Server) handlePluginProxy(w http.ResponseWriter, r *http.Request) {
}
slug := r.PathValue("slug")
proxyCacheMu.Lock()
- handler := proxyCache[slug]
+ entry, ok := proxyCache[slug]
proxyCacheMu.Unlock()
+ var handler http.Handler
+ if ok && time.Since(entry.at) < proxyCacheTTL {
+ handler = entry.handler
+ }
if handler == nil {
h, err := svc.ProxyHandler(slug)
if err != nil {
@@ -380,7 +402,7 @@ func (s *Server) handlePluginProxy(w http.ResponseWriter, r *http.Request) {
return
}
proxyCacheMu.Lock()
- proxyCache[slug] = h
+ proxyCache[slug] = proxyCacheEntry{handler: h, at: time.Now()}
proxyCacheMu.Unlock()
handler = h
}
diff --git a/internal/httpapi/settings.go b/internal/httpapi/settings.go
index 90055bc..2f384b8 100644
--- a/internal/httpapi/settings.go
+++ b/internal/httpapi/settings.go
@@ -116,6 +116,12 @@ func (s *Server) handleSettingsEntry(w http.ResponseWriter, r *http.Request) {
return
}
s.setEntry(entry)
+ // Rotating the entry is a credential change: sessions obtained with the old
+ // entry (including Bearer tokens, which ignore the cookie Path) must die,
+ // not just look logged out in the browser.
+ if user, err := requireUser(r); err == nil {
+ _, _ = s.db.DeleteOtherSessions(r.Context(), user.ID, "")
+ }
s.audit(r, "settings", "entry", entry, "ok", started)
// The old cookie Path no longer matches, so the browser must re-login at
// the new prefix. The response tells the UI where to go.
@@ -132,6 +138,12 @@ func validEntry(entry string) bool {
}
return false
}
+ // The SPA serves /assets and /api from the root handler; using one of them
+ // as the entry would shadow the frontend and lock the operator out.
+ switch entry {
+ case "assets", "api", "static", "favicon":
+ return false
+ }
return true
}
diff --git a/internal/site/site.go b/internal/site/site.go
index b105b46..b544209 100644
--- a/internal/site/site.go
+++ b/internal/site/site.go
@@ -5,6 +5,7 @@ import (
"context"
"errors"
"fmt"
+ "net"
"os"
"os/user"
"path/filepath"
@@ -29,6 +30,10 @@ type Service struct {
nginx *webserver.Manager
runner *system.Runner
distro system.Distro
+ // mu serialises create/update/delete. Port allocation reads the database
+ // and only writes the new row after nginx accepted the config, so without
+ // this lock two concurrent creations both pick the same free port.
+ mu sync.Mutex
}
// NewService wires the site service.
@@ -64,6 +69,8 @@ var (
// command is run through `sh -lc` by systemd (product requirement: allow
// simple commands such as "npm start" only).
shellUnsafe = regexp.MustCompile("[;&|<>`$(){}\\[\\]\n\r]")
+ // phpVersionRe keeps the value usable in a fastcgi_pass socket name.
+ phpVersionRe = regexp.MustCompile(`^[0-9]+\.[0-9]+$`)
)
var validKinds = map[string]bool{"static": true, "php": true, "go": true, "node": true, "proxy": true}
@@ -71,6 +78,8 @@ var validKinds = map[string]bool{"static": true, "php": true, "go": true, "node"
// Create validates the input, allocates resources and applies configuration.
// Any failure rolls back every step already performed.
func (s *Service) Create(ctx context.Context, in Input) (*store.Site, error) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
if err := s.cfg.EnsureDirs(); err != nil {
return nil, err
}
@@ -99,18 +108,25 @@ func (s *Service) Create(ctx context.Context, in Input) (*store.Site, error) {
in.Root = s.cfg.SiteRoot(slug)
}
if isApp(in.Kind) {
+ used, err := s.db.PortsInUse(ctx)
+ if err != nil {
+ return nil, err
+ }
if in.Port == 0 {
- used, err := s.db.PortsInUse(ctx)
- if err != nil {
- return nil, err
- }
port, err := system.AllocatePort(8000, 9999, used)
if err != nil {
return nil, err
}
in.Port = port
+ } else if owner, taken := used[in.Port]; taken {
+ return nil, invalid("端口 %d 已被站点 %s 使用", in.Port, owner)
+ }
+ // An explicit upstream wins: proxy sites often point at an existing
+ // service (https, another host, a path prefix) and overwriting it with
+ // 127.0.0.1:Port made those sites silently proxy to the wrong place.
+ if strings.TrimSpace(in.Upstream) == "" {
+ in.Upstream = "http://127.0.0.1:" + strconv.Itoa(in.Port)
}
- in.Upstream = "http://127.0.0.1:" + strconv.Itoa(in.Port)
}
// Go projects only need a binary; when the command is omitted we look for
// an ELF/script in the project directory (same behaviour as the reference
@@ -189,10 +205,15 @@ func (s *Service) Create(ctx context.Context, in Input) (*store.Site, error) {
// Update changes mutable attributes and re-renders configuration.
func (s *Service) Update(ctx context.Context, id int64, in Input) (*store.Site, error) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
st, err := s.db.SiteByID(ctx, id)
if err != nil {
return nil, err
}
+ // A partial client must not silently reset security relevant settings:
+ // every option it did not send keeps the stored value.
+ in.Options = mergeOptions(st.Options, in.Options)
if err := s.validate(ctx, &in, id); err != nil {
return nil, err
}
@@ -232,6 +253,21 @@ func (s *Service) Update(ctx context.Context, id int64, in Input) (*store.Site,
in.Options.ListenPort = st.Options.ListenPort
}
s.ensureGatewayPort(ctx, &in.Options)
+ // Empty values mean "unchanged": an older mobile client that only edits the
+ // remark must not blank the run user (systemd would then run as root) or
+ // the PHP version.
+ if in.PHPVersion == "" {
+ in.PHPVersion = st.PHPVersion
+ }
+ if in.RunUser == "" {
+ in.RunUser = st.RunUser
+ }
+ if in.StartCmd == "" {
+ in.StartCmd = st.StartCmd
+ }
+ if strings.TrimSpace(in.Upstream) == "" {
+ in.Upstream = st.Upstream
+ }
st.Name = in.Name
st.Root = in.Root
st.PHPVersion = in.PHPVersion
@@ -245,10 +281,17 @@ func (s *Service) Update(ctx context.Context, id int64, in Input) (*store.Site,
st.Domains = in.Domains
}
if isApp(st.Kind) {
- if in.Port > 0 {
+ if in.Port > 0 && in.Port != st.Port {
+ used, err := s.db.PortsInUse(ctx)
+ if err != nil {
+ return nil, err
+ }
+ if owner, taken := used[in.Port]; taken && owner != st.Slug {
+ return nil, invalid("端口 %d 已被站点 %s 使用", in.Port, owner)
+ }
st.Port = in.Port
}
- if st.Upstream == "" {
+ if strings.TrimSpace(st.Upstream) == "" {
st.Upstream = "http://127.0.0.1:" + strconv.Itoa(st.Port)
}
}
@@ -289,6 +332,8 @@ func (s *Service) Delete(ctx context.Context, id int64, removeFiles bool) error
_ = s.db.DeleteSSLCert(ctx, id)
_ = os.RemoveAll(filepath.Join(s.cfg.Nginx.CertDir, st.Slug))
_ = os.RemoveAll(s.cfg.SiteLogDir(st.Slug))
+ // The launcher script is panel owned and must not outlive the site.
+ _ = os.Remove(filepath.Join(st.Root, ".mp-start.sh"))
if removeFiles {
root := filepath.Clean(st.Root)
if s.safeToRemove(root) {
@@ -436,6 +481,79 @@ func normalizeDomainList(list []string) []string {
return out
}
+// mergeOptions keeps every stored field the request did not mention, so a
+// partial update cannot silently disable security headers or reset WAF rates.
+func mergeOptions(old, in store.SiteOptions) store.SiteOptions {
+ if len(in.Present) == 0 {
+ // The request carried no options at all (older client, or only the
+ // remark was edited): keep every stored value.
+ return old
+ }
+ out := old
+ if in.Present["https_redirect"] {
+ out.HTTPSRedirect = in.HTTPSRedirect
+ }
+ if in.Present["hsts"] {
+ out.HSTS = in.HSTS
+ }
+ if in.Present["security_headers"] {
+ out.SecurityHead = in.SecurityHead
+ }
+ if in.Present["limit_rate_kb"] {
+ out.LimitRate = in.LimitRate
+ }
+ if in.Present["conn_per_ip"] {
+ out.ConnPerIP = in.ConnPerIP
+ }
+ if in.Present["conn_per_server"] {
+ out.ConnPerServer = in.ConnPerServer
+ }
+ if in.Present["anti_leech"] {
+ out.AntiLeak = in.AntiLeak
+ }
+ if in.Present["anti_leech_hosts"] {
+ out.AntiLeakHosts = in.AntiLeakHosts
+ }
+ if in.Present["ip_mode"] {
+ out.IPMode = in.IPMode
+ }
+ if in.Present["ip_list"] {
+ out.IPList = in.IPList
+ }
+ if in.Present["waf"] {
+ out.WAF = in.WAF
+ }
+ if in.Present["waf_rate"] {
+ out.WAFRate = in.WAFRate
+ }
+ if in.Present["waf_burst"] {
+ out.WAFBurst = in.WAFBurst
+ }
+ if in.Present["gateway_port"] {
+ out.GatewayPort = in.GatewayPort
+ }
+ if in.Present["custom_nginx"] {
+ out.Custom = in.Custom
+ }
+ if in.Present["listen_port"] {
+ out.ListenPort = in.ListenPort
+ }
+ if in.Present["docker_container_id"] {
+ out.DockerContainerID = in.DockerContainerID
+ }
+ if in.Present["docker_container_name"] {
+ out.DockerContainerName = in.DockerContainerName
+ }
+ if in.Present["docker_container_port"] {
+ out.DockerContainerPort = in.DockerContainerPort
+ }
+ if in.Present["docker_host_port"] {
+ out.DockerHostPort = in.DockerHostPort
+ }
+ out.Present = in.Present
+ return out
+}
+
// deriveSlug turns the primary domain into a filesystem and systemd safe name.
func deriveSlug(domain string) string {
domain = strings.TrimPrefix(strings.ToLower(domain), "*.")
@@ -532,6 +650,25 @@ func (s *Service) validateInner(ctx context.Context, in *Input, exceptID int64)
return invalid("启动命令不能包含 shell 元字符")
}
}
+ if in.Kind == "php" && in.PHPVersion != "" && !phpVersionRe.MatchString(in.PHPVersion) {
+ return invalid("PHP 版本格式不正确: %s", in.PHPVersion)
+ }
+ if in.Options.ListenPort != 0 && (in.Options.ListenPort < 1 || in.Options.ListenPort > 65535) {
+ return invalid("监听端口超出范围")
+ }
+ if in.Options.ListenPort == 443 {
+ return invalid("监听端口不能占用 443,HTTPS 固定使用该端口")
+ }
+ for _, ip := range in.Options.IPList {
+ if !validCIDR(ip) {
+ return invalid("IP 列表格式不正确: %s", ip)
+ }
+ }
+ for _, h := range in.Options.AntiLeakHosts {
+ if !validRefererHost(h) {
+ return invalid("防盗链域名格式不正确: %s", h)
+ }
+ }
if in.Kind == "proxy" {
up := strings.TrimSpace(in.Upstream)
if up == "" && in.Port == 0 {
@@ -606,6 +743,37 @@ func fileExists(p string) bool {
return err == nil
}
+func shQuote(s string) string {
+ return "'" + strings.ReplaceAll(s, "'", `'\''`) + "'"
+}
+
+// validCIDR accepts a single address or a CIDR block, which is what the IP
+// control fragments can render safely.
+func validCIDR(s string) bool {
+ s = strings.TrimSpace(s)
+ if s == "" {
+ return false
+ }
+ if strings.Contains(s, "/") {
+ _, _, err := net.ParseCIDR(s)
+ return err == nil
+ }
+ return net.ParseIP(s) != nil
+}
+
+// validRefererHost keeps anti-leech hosts to characters valid_referers can
+// take; anything that could terminate the directive is rejected.
+func validRefererHost(s string) bool {
+ s = strings.TrimSpace(s)
+ if s == "" || len(s) > 255 {
+ return false
+ }
+ if strings.ContainsAny(s, " \t\r\n;\"'{}#\\") {
+ return false
+ }
+ return true
+}
+
// ensureGatewayPort allocates the loopback origin port when deep inspection is
// enabled globally. waf.Apply performs the same allocation in bulk; this keeps
// a site created between two applies from temporarily losing protection.
@@ -669,6 +837,17 @@ func (s *Service) writeUnit(ctx context.Context, st *store.Site) error {
return err
}
}
+ // The command is stored in a script instead of being quoted into
+ // ExecStart: a start command containing a single quote produced an
+ // unbalanced unit file ("Unbalanced quoting") and the site never started,
+ // while the API still reported success. The script lives in the document
+ // root because the panel data dir is 0700 root and the unit runs as an
+ // unprivileged user; nginx refuses to serve ".mp-*" names.
+ startScript := filepath.Join(st.Root, ".mp-start.sh")
+ script := "#!/bin/sh\ncd " + shQuote(workdir) + "\nexec " + st.StartCmd + "\n"
+ if err := fsutil.WriteFileAtomic(startScript, []byte(script), 0o755); err != nil {
+ return err
+ }
memMax := ""
body := fmt.Sprintf(`[Unit]
Description=MiaoPanel site %s
@@ -682,7 +861,7 @@ Group=%s
WorkingDirectory=%s
Environment=PATH=/www/server/node/current/bin:/www/server/go/current/bin:/www/server/python/current/bin:/usr/local/bin:/usr/bin:/bin
EnvironmentFile=-%s
-ExecStart=/bin/sh -lc '%s'
+ExecStart=/bin/sh %s
Restart=always
RestartSec=3
LimitNOFILE=65535
@@ -692,7 +871,7 @@ StandardError=append:%s
[Install]
WantedBy=multi-user.target
-`, st.Slug, st.RunUser, st.RunUser, workdir, envFile, st.StartCmd, memMax, logPath, logPath)
+`, st.Slug, st.RunUser, st.RunUser, workdir, envFile, startScript, memMax, logPath, logPath)
svc := s.serviceFor(st)
if err := svc.WriteUnit(ctx, body); err != nil {
diff --git a/internal/site/site_options_test.go b/internal/site/site_options_test.go
new file mode 100644
index 0000000..093dd1c
--- /dev/null
+++ b/internal/site/site_options_test.go
@@ -0,0 +1,76 @@
+package site
+
+import (
+ "testing"
+
+ "github.com/miaopanel/miaopanel/internal/store"
+)
+
+// A partial update (older mobile client, scripted API call) must not reset the
+// fields it never mentioned: security headers used to disappear silently.
+func TestMergeOptionsKeepsUnsentFields(t *testing.T) {
+ old := store.SiteOptions{
+ SecurityHead: true, HSTS: true, WAF: true, WAFRate: 20, WAFBurst: 40,
+ ListenPort: 16520, GatewayPort: 10000, IPMode: "deny", IPList: []string{"10.0.0.0/8"},
+ }
+ in := store.SiteOptions{ListenPort: 8080, Present: map[string]bool{"listen_port": true}}
+ got := mergeOptions(old, in)
+ if !got.SecurityHead || !got.HSTS || !got.WAF {
+ t.Fatalf("security flags lost: %+v", got)
+ }
+ if got.WAFRate != 20 || got.WAFBurst != 40 {
+ t.Fatalf("WAF rates lost: %+v", got)
+ }
+ if got.GatewayPort != 10000 || got.IPMode != "deny" || len(got.IPList) != 1 {
+ t.Fatalf("other options lost: %+v", got)
+ }
+ if got.ListenPort != 8080 {
+ t.Fatalf("listen_port = %d, want 8080", got.ListenPort)
+ }
+}
+
+func TestMergeOptionsHonoursExplicitZeroAndFalse(t *testing.T) {
+ old := store.SiteOptions{SecurityHead: true, HSTS: true, ListenPort: 16520}
+ in := store.SiteOptions{
+ SecurityHead: false,
+ ListenPort: 0,
+ Present: map[string]bool{"security_headers": true, "hsts": true, "listen_port": true},
+ }
+ got := mergeOptions(old, in)
+ if got.SecurityHead {
+ t.Fatal("explicit false ignored")
+ }
+ if got.HSTS {
+ t.Fatal("explicit false ignored for hsts")
+ }
+ if got.ListenPort != 0 {
+ t.Fatalf("explicit zero ignored: %d", got.ListenPort)
+ }
+}
+
+func TestMergeOptionsWithoutOptionsKeepsEverything(t *testing.T) {
+ old := store.SiteOptions{GatewayPort: 10001, SecurityHead: true, WAF: true, ListenPort: 10121}
+ got := mergeOptions(old, store.SiteOptions{})
+ if got.GatewayPort != 10001 || !got.SecurityHead || !got.WAF || got.ListenPort != 10121 {
+ t.Fatalf("options dropped for a request without options: %+v", got)
+ }
+}
+
+func TestValidateRejectsUnsafePHPVersionAndIPList(t *testing.T) {
+ s := &Service{}
+ cases := []Input{
+ {Name: "a", Kind: "php", Domains: []string{"a.example.com"}, PHPVersion: "8.2-fpm.sock; add_header X 1"},
+ {Name: "b", Kind: "static", Domains: []string{"b.example.com"},
+ Options: store.SiteOptions{IPMode: "deny", IPList: []string{"1.2.3.4; }"}}},
+ {Name: "c", Kind: "static", Domains: []string{"c.example.com"},
+ Options: store.SiteOptions{AntiLeak: true, AntiLeakHosts: []string{"a.com;"}}},
+ {Name: "d", Kind: "static", Domains: []string{"d.example.com"},
+ Options: store.SiteOptions{ListenPort: 443}},
+ }
+ for i, in := range cases {
+ input := in
+ if err := s.validateInner(nil, &input, 0); err == nil {
+ t.Fatalf("case %d accepted unsafe input: %+v", i, in)
+ }
+ }
+}
diff --git a/internal/store/models.go b/internal/store/models.go
index 5f50ae6..9c8affe 100644
--- a/internal/store/models.go
+++ b/internal/store/models.go
@@ -1,5 +1,7 @@
package store
+import "encoding/json"
+
// User is a panel operator account.
type User struct {
ID int64 `json:"id"`
@@ -56,6 +58,29 @@ type SiteOptions struct {
DockerContainerName string `json:"docker_container_name,omitempty"`
DockerContainerPort int `json:"docker_container_port,omitempty"`
DockerHostPort int `json:"docker_host_port,omitempty"`
+ // Present records which JSON keys the current request actually contained.
+ // It lets Update keep the fields a partial client omitted instead of
+ // silently zeroing security_headers and friends. Never persisted.
+ Present map[string]bool `json:"-"`
+}
+
+// UnmarshalJSON tracks the supplied keys so partial updates can be merged.
+func (o *SiteOptions) UnmarshalJSON(data []byte) error {
+ type alias SiteOptions
+ var a alias
+ if err := json.Unmarshal(data, &a); err != nil {
+ return err
+ }
+ keys := map[string]json.RawMessage{}
+ if err := json.Unmarshal(data, &keys); err != nil {
+ return err
+ }
+ *o = SiteOptions(a)
+ o.Present = make(map[string]bool, len(keys))
+ for k := range keys {
+ o.Present[k] = true
+ }
+ return nil
}
// Site is a managed website or application.
diff --git a/internal/waf/rule_validate_test.go b/internal/waf/rule_validate_test.go
new file mode 100644
index 0000000..32e2a4f
--- /dev/null
+++ b/internal/waf/rule_validate_test.go
@@ -0,0 +1,30 @@
+package waf
+
+import "testing"
+
+// A rule with a broken regex used to reach the database, after which every
+// later apply failed until someone deleted the row by hand.
+func TestRuleValidateRejectsBrokenRegex(t *testing.T) {
+ in := RuleInput{Name: "broken", MatchOn: "uri", Op: "regex", Pattern: "foo(#bar", Action: "block"}
+ if err := in.Validate(); err == nil {
+ t.Fatal("broken regex accepted")
+ }
+ ok := RuleInput{Name: "ok", MatchOn: "uri", Op: "regex", Pattern: "^/admin", Action: "block"}
+ if err := ok.Validate(); err != nil {
+ t.Fatalf("valid regex rejected: %v", err)
+ }
+}
+
+func TestSettingsRejectAmbiguousUAKeyword(t *testing.T) {
+ st := Settings{
+ BlockStatus: 444, Rate: 50, Burst: 200, RetentionDays: 7, GatewayThreshold: 8,
+ BadUAExtra: []string{"my bot"},
+ }
+ if err := st.Validate(); err == nil {
+ t.Fatal("keyword with a space accepted")
+ }
+ st.BadUAExtra = []string{"sqlmap"}
+ if err := st.Validate(); err != nil {
+ t.Fatalf("plain keyword rejected: %v", err)
+ }
+}
diff --git a/internal/waf/waf.go b/internal/waf/waf.go
index 9b3f881..82fe3bc 100644
--- a/internal/waf/waf.go
+++ b/internal/waf/waf.go
@@ -8,6 +8,7 @@ import (
"fmt"
"net"
"os"
+ "regexp"
"strconv"
"strings"
"sync"
@@ -163,7 +164,7 @@ func (st *Settings) Validate() error {
}
}
for _, kw := range st.BadUAExtra {
- if len(kw) > 64 || strings.ContainsAny(kw, "\"\\\n;{}") {
+ if len(kw) > 64 || strings.ContainsAny(kw, "\"\\\n\r;{}# \t") {
return fmt.Errorf("UA 关键词不合法: %s", kw)
}
}
@@ -179,11 +180,30 @@ func validIP(s string) bool {
return net.ParseIP(s) != nil
}
-// SaveSettings validates, persists and applies the configuration.
+// SaveSettings validates, persists and applies the configuration. When nginx
+// rejects the rendered result the previous settings are restored, otherwise a
+// failed save would leave the database and the running configuration apart and
+// every later apply would keep failing.
func (s *Service) SaveSettings(ctx context.Context, st Settings) error {
if err := st.Validate(); err != nil {
return err
}
+ old, err := s.Settings(ctx)
+ if err != nil {
+ return err
+ }
+ if err := s.writeSettings(ctx, st); err != nil {
+ return err
+ }
+ if err := s.Apply(ctx); err != nil {
+ _ = s.writeSettings(ctx, old)
+ _ = s.Apply(ctx)
+ return err
+ }
+ return nil
+}
+
+func (s *Service) writeSettings(ctx context.Context, st Settings) error {
pairs := map[string]string{
keyEnabled: boolString(st.Enabled),
keyStatus: strconv.Itoa(st.BlockStatus),
@@ -206,7 +226,7 @@ func (s *Service) SaveSettings(ctx context.Context, st Settings) error {
return err
}
}
- return s.Apply(ctx)
+ return nil
}
func boolString(b bool) string {
@@ -357,6 +377,13 @@ func (r *RuleInput) Validate() error {
if strings.ContainsAny(r.Pattern, "\"\\\n\r;{}") {
return errors.New("匹配内容不能包含引号、反斜杠、分号或花括号")
}
+ if r.Op == "regex" {
+ // Compile before it reaches nginx: a rejected rule that already landed
+ // in the database used to break every later apply.
+ if _, err := regexp.Compile(r.Pattern); err != nil {
+ return fmt.Errorf("正则表达式无效: %v", err)
+ }
+ }
if r.Action != "block" {
return errors.New("当前版本仅支持拦截动作")
}
@@ -386,11 +413,17 @@ func (s *Service) CreateRule(ctx context.Context, in RuleInput) (*store.WAFRule,
return rule, nil
}
-// UpdateRule validates, stores and applies changes.
+// UpdateRule validates, stores and applies changes. A rule nginx refuses is
+// rolled back to its previous value, otherwise the rejected row stays in the
+// database and every subsequent apply fails until it is deleted by hand.
func (s *Service) UpdateRule(ctx context.Context, id int64, in RuleInput) (*store.WAFRule, error) {
if err := in.Validate(); err != nil {
return nil, err
}
+ old, err := s.ruleByID(ctx, id)
+ if err != nil {
+ return nil, err
+ }
rule := &store.WAFRule{
ID: id, Name: in.Name, MatchOn: in.MatchOn, Op: in.Op, Pattern: in.Pattern,
Action: in.Action, Enabled: in.Enabled, Note: in.Note,
@@ -399,11 +432,26 @@ func (s *Service) UpdateRule(ctx context.Context, id int64, in RuleInput) (*stor
return nil, err
}
if err := s.Apply(ctx); err != nil {
+ _ = s.db.UpdateWAFRule(ctx, old)
+ _ = s.Apply(ctx)
return nil, err
}
return rule, nil
}
+func (s *Service) ruleByID(ctx context.Context, id int64) (*store.WAFRule, error) {
+ rules, err := s.db.WAFRules(ctx)
+ if err != nil {
+ return nil, err
+ }
+ for i := range rules {
+ if rules[i].ID == id {
+ return &rules[i], nil
+ }
+ }
+ return nil, store.ErrNotFound
+}
+
// DeleteRule removes a rule and re-renders.
func (s *Service) DeleteRule(ctx context.Context, id int64) error {
if err := s.db.DeleteWAFRule(ctx, id); err != nil {
diff --git a/internal/wafgw/gateway.go b/internal/wafgw/gateway.go
index daa1f85..5812ff0 100644
--- a/internal/wafgw/gateway.go
+++ b/internal/wafgw/gateway.go
@@ -20,6 +20,7 @@ import (
"net/http/httputil"
"net/url"
"regexp"
+ "strconv"
"strings"
"sync"
"sync/atomic"
@@ -53,6 +54,11 @@ type Policy struct {
Burst int
Whitelist []string
Custom []wafengine.CustomRule
+ // Origins maps a site slug to its registered loopback origin. nginx sends
+ // X-MP-Origin, but that header must never decide where the gateway
+ // connects: trusting it turned the listener into a proxy for any internal
+ // address reachable from the panel.
+ Origins map[string]string
}
// Service owns the gateway listener and the policy refresh loop.
@@ -193,6 +199,14 @@ func (s *Service) Reload(ctx context.Context) error {
Enabled: st.Gateway, Strict: st.GatewayStrict, Threshold: st.GatewayThreshold,
BlockStatus: st.BlockStatus, Rate: st.Rate, Burst: st.Burst,
Whitelist: st.Whitelist,
+ Origins: map[string]string{},
+ }
+ if sites, err := s.db.ListSites(ctx); err == nil {
+ for _, site := range sites {
+ if site.Options.GatewayPort > 0 {
+ p.Origins[site.Slug] = fmt.Sprintf("127.0.0.1:%d", site.Options.GatewayPort)
+ }
+ }
}
for _, rule := range rules {
if !rule.Enabled || rule.Action != "block" {
@@ -268,13 +282,12 @@ func (s *Service) ServeHTTP(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusBadRequest, map[string]any{"code": 400, "msg": "缺少站点标识"})
return
}
- target, err := targetFor(r)
+ pol := s.policy.Load()
+ target, err := targetFor(r, pol, slug)
if err != nil {
writeJSON(w, http.StatusBadGateway, map[string]any{"code": 502, "msg": err.Error()})
return
}
-
- pol := s.policy.Load()
ip := clientIP(r)
if pol == nil || !pol.Enabled {
s.forward(w, r, target)
@@ -284,7 +297,7 @@ func (s *Service) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if isStaticPath(r.URL.Path) {
// Static assets are not rate limited and normally do not need body
// inspection, but the query string is still checked by the engine.
- } else if !s.limiter.allow(ip+"|"+slug, pol.Rate, pol.Burst) {
+ } else if !ipWhitelisted(pol.Whitelist, ip) && !s.limiter.allow(ip+"|"+slug, pol.Rate, pol.Burst) {
s.block(w, r, pol, ip, slug, 429, wafengine.Result{
Score: 0,
Hits: []wafengine.Hit{{Module: "cc", Rule: "rate_limit", Score: 0, Location: "remote", Evidence: ip}},
@@ -296,6 +309,19 @@ func (s *Service) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// semaphore applies backpressure instead of letting concurrent uploads
// reserve an unbounded amount of memory.
hasBody := r.Body != nil && r.Method != http.MethodGet && r.Method != http.MethodHead && r.ContentLength != 0
+ // A form or JSON body larger than the inspection window can hide its
+ // payload behind filler bytes, which used to pass untouched. Legitimate
+ // requests of that shape are rare, so treat them as an attack surface
+ // instead of forwarding unscanned bytes. Multipart uploads keep streaming.
+ if hasBody && r.ContentLength > int64(wafengine.MaxBodyScan) {
+ ct := strings.ToLower(r.Header.Get("Content-Type"))
+ if strings.Contains(ct, "application/x-www-form-urlencoded") || strings.Contains(ct, "application/json") {
+ s.block(w, r, pol, ip, slug, http.StatusRequestEntityTooLarge, wafengine.Result{
+ Hits: []wafengine.Hit{{Module: "body", Rule: "oversized_body", Location: "body", Evidence: "body exceeds inspection limit"}},
+ }, "请求体超过检测上限")
+ return
+ }
+ }
releaseInspect := func() {}
if hasBody {
select {
@@ -391,10 +417,19 @@ func (s *Service) health(w http.ResponseWriter) {
})
}
-func targetFor(r *http.Request) (*url.URL, error) {
+func targetFor(r *http.Request, pol *Policy, slug string) (*url.URL, error) {
+ // The registered origin always wins: nginx sets the header from the site
+ // row, and nothing derived from a request header may choose the target.
+ // Previously any local process could point X-MP-Origin at an arbitrary
+ // internal host and use the gateway as a proxy.
+ if pol != nil {
+ if origin := pol.Origins[slug]; origin != "" {
+ return &url.URL{Scheme: "http", Host: origin}, nil
+ }
+ }
if origin := strings.TrimSpace(r.Header.Get("X-MP-Origin")); origin != "" {
- if !strings.Contains(origin, ":") {
- return nil, fmt.Errorf("origin 地址不合法")
+ if !loopbackAuthority(origin) {
+ return nil, fmt.Errorf("origin 必须是本机回环地址")
}
return &url.URL{Scheme: "http", Host: origin}, nil
}
@@ -406,9 +441,50 @@ func targetFor(r *http.Request) (*url.URL, error) {
if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" {
return nil, fmt.Errorf("上游地址不合法")
}
+ if !loopbackAuthority(u.Host) {
+ return nil, fmt.Errorf("上游地址必须是本机回环地址")
+ }
return u, nil
}
+// loopbackAuthority accepts "127.0.0.1:8080" and "[::1]:8080".
+func loopbackAuthority(a string) bool {
+ host, port, err := net.SplitHostPort(a)
+ if err != nil || port == "" {
+ return false
+ }
+ if _, err := strconv.Atoi(port); err != nil {
+ return false
+ }
+ ip := net.ParseIP(host)
+ return ip != nil && ip.IsLoopback()
+}
+
+// ipWhitelisted mirrors the nginx level exemption for the CC limiter: an
+// operator who trusted an address must not be throttled by the gateway.
+func ipWhitelisted(list []string, ip string) bool {
+ addr := net.ParseIP(strings.TrimSpace(ip))
+ if addr == nil {
+ return false
+ }
+ for _, item := range list {
+ item = strings.TrimSpace(item)
+ if item == "" {
+ continue
+ }
+ if strings.Contains(item, "/") {
+ if _, block, err := net.ParseCIDR(item); err == nil && block.Contains(addr) {
+ return true
+ }
+ continue
+ }
+ if v := net.ParseIP(item); v != nil && v.Equal(addr) {
+ return true
+ }
+ }
+ return false
+}
+
func bufferBody(r *http.Request) ([]byte, bool, error) {
if r.Body == nil || r.Method == http.MethodGet || r.Method == http.MethodHead {
return nil, false, nil
diff --git a/internal/wafgw/gateway_test.go b/internal/wafgw/gateway_test.go
index e9fed9e..5d01e5c 100644
--- a/internal/wafgw/gateway_test.go
+++ b/internal/wafgw/gateway_test.go
@@ -8,7 +8,6 @@ import (
"log/slog"
"net/http"
"net/http/httptest"
- "net/url"
"os"
"path/filepath"
"strings"
@@ -266,31 +265,46 @@ func TestGatewayCustomRule(t *testing.T) {
func TestTargetForRejectsInvalid(t *testing.T) {
req := httptest.NewRequest(http.MethodGet, "/", nil)
req.Header.Set("X-MP-Origin", "bad")
- if _, err := targetFor(req); err == nil {
+ if _, err := targetFor(req, nil, "s"); err == nil {
t.Fatal("invalid origin accepted")
}
+ // A forged header must not turn the gateway into an internal proxy.
+ req.Header.Set("X-MP-Origin", "169.254.169.254:80")
+ if _, err := targetFor(req, nil, "s"); err == nil {
+ t.Fatal("non loopback origin accepted")
+ }
req.Header.Set("X-MP-Origin", "")
req.Header.Set("X-MP-Upstream", "file:///etc/passwd")
- if _, err := targetFor(req); err == nil {
+ if _, err := targetFor(req, nil, "s"); err == nil {
t.Fatal("invalid upstream accepted")
}
- u, err := targetFor(httptest.NewRequest(http.MethodGet, "/", nil))
+ req.Header.Set("X-MP-Upstream", "http://10.0.0.5:6379")
+ if _, err := targetFor(req, nil, "s"); err == nil {
+ t.Fatal("non loopback upstream accepted")
+ }
+ u, err := targetFor(httptest.NewRequest(http.MethodGet, "/", nil), nil, "s")
if err == nil || u != nil {
t.Fatal("missing upstream accepted")
}
req = httptest.NewRequest(http.MethodGet, "/", nil)
req.Header.Set("X-MP-Upstream", "http://127.0.0.1:8080")
- u, err = targetFor(req)
+ u, err = targetFor(req, nil, "s")
if err != nil || u.Host != "127.0.0.1:8080" {
t.Fatalf("upstream parse: %v %v", u, err)
}
}
-func TestTargetURLIsLoopbackOnlyByConstruction(t *testing.T) {
- // The gateway trusts X-MP-Origin because it only listens on loopback and
- // nginx overwrites the header. This test documents that assumption.
- u, _ := url.Parse("http://127.0.0.1:10001")
- if u.Hostname() != "127.0.0.1" {
- t.Fatal("unexpected host")
+func TestTargetForPrefersRegisteredOrigin(t *testing.T) {
+ // nginx sets X-MP-Origin from the site row, but nothing stops a local
+ // process from setting it too: the registered origin must win.
+ req := httptest.NewRequest(http.MethodGet, "/", nil)
+ req.Header.Set("X-MP-Origin", "127.0.0.1:9999")
+ pol := &Policy{Origins: map[string]string{"app": "127.0.0.1:10001"}}
+ u, err := targetFor(req, pol, "app")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if u.Host != "127.0.0.1:10001" {
+ t.Fatalf("header overrode the registered origin: %s", u.Host)
}
}
diff --git a/internal/webserver/manager.go b/internal/webserver/manager.go
index 0efbef5..cfd68f6 100644
--- a/internal/webserver/manager.go
+++ b/internal/webserver/manager.go
@@ -266,12 +266,23 @@ func (m *Manager) apply(ctx context.Context, r *Render) error {
return nil
}
+ keep := make(map[string]bool, len(r.Keep))
+ for _, p := range r.Keep {
+ keep[p] = true
+ }
paths := make([]string, 0, len(r.Files))
for p := range r.Files {
paths = append(paths, p)
}
sort.Strings(paths)
for _, p := range paths {
+ if keep[p] {
+ // Operator owned file: create it once, never overwrite it. Skipping
+ // the snapshot too keeps the rollback path from restoring it later.
+ if _, err := os.Stat(p); err == nil {
+ continue
+ }
+ }
if err := snapshot(p); err != nil {
return err
}
@@ -327,6 +338,9 @@ func mergeRender(dst, src *Render) {
dst.Files[k] = v
}
dst.Remove = append(dst.Remove, src.Remove...)
+ // Keep must travel with the files, otherwise ApplyAll (WAF change, panel
+ // restart) overwrites the operator's rewrite and ACME snippets again.
+ dst.Keep = append(dst.Keep, src.Keep...)
}
func (m *Manager) prepare(s *store.Site) error {
diff --git a/internal/webserver/render.go b/internal/webserver/render.go
index 21f8e88..c2e8761 100644
--- a/internal/webserver/render.go
+++ b/internal/webserver/render.go
@@ -21,6 +21,10 @@ import (
type Render struct {
Files map[string][]byte
Remove []string
+ // Keep lists files that are only created when they do not exist yet. The
+ // rewrite and ACME snippets are operator owned: rendering a site must
+ // never replace them (a restart used to wipe every saved rewrite rule).
+ Keep []string
}
func (r *Render) add(path, content string) {
@@ -34,6 +38,10 @@ func (r *Render) del(path string) {
r.Remove = append(r.Remove, path)
}
+func (r *Render) keep(path string) {
+ r.Keep = append(r.Keep, path)
+}
+
// RenderSite computes every configuration file of a site. The global WAF
// configuration is passed in so the renderer stays pure and unit testable.
func RenderSite(cfg *config.Config, s *store.Site, waf WAFConfig) *Render {
@@ -237,9 +245,13 @@ func RenderSite(cfg *config.Config, s *store.Site, waf WAFConfig) *Render {
r.del(cfg.OriginConfPath(s.Slug))
}
- // Files that must exist so that includes never fail.
+ // Files that must exist so that includes never fail, but whose content
+ // belongs to the operator (rewrite rules, ACME challenge files). They are
+ // only written when absent; Apply skips them when they already exist.
r.addIfMissing(cfg.RewritePath(s.Slug), "# rewrite rules (editable)\n")
+ r.keep(cfg.RewritePath(s.Slug))
r.addIfMissing(cfg.WellKnownPath(s.Slug), "# acme challenge include\n")
+ r.keep(cfg.WellKnownPath(s.Slug))
sort.Strings(r.Remove)
return r
@@ -414,6 +426,11 @@ location ~* /(\.git|\.svn|\.idea|\.vscode|\.ssh|node_modules|vendor/bundle)/ {
location ^~ /.mp-trash/ {
deny all;
}
+# Panel owned helper files inside a document root (.mp-start.sh, upload
+# temporary files) must never be served.
+location ~ /\.mp- {
+ deny all;
+}
location ^~ /.well-known/acme-challenge/ {
allow all;
}
diff --git a/internal/webserver/render_keep_test.go b/internal/webserver/render_keep_test.go
new file mode 100644
index 0000000..9d9ec09
--- /dev/null
+++ b/internal/webserver/render_keep_test.go
@@ -0,0 +1,41 @@
+package webserver
+
+import "testing"
+
+// The rewrite and ACME snippets belong to the operator. Rendering must only
+// create them when missing; otherwise a restart or a WAF change wiped every
+// saved rewrite rule.
+func TestRenderMarksOperatorFilesAsKeep(t *testing.T) {
+ cfg := testConfig(t)
+ s := staticSite()
+ r := RenderSite(cfg, s, DefaultWAF())
+ want := map[string]bool{
+ cfg.RewritePath(s.Slug): false,
+ cfg.WellKnownPath(s.Slug): false,
+ }
+ for _, p := range r.Keep {
+ if _, ok := want[p]; ok {
+ want[p] = true
+ }
+ }
+ for p, seen := range want {
+ if !seen {
+ t.Fatalf("%s is not marked keep: it would be overwritten on every render", p)
+ }
+ if _, ok := r.Files[p]; !ok {
+ t.Fatalf("%s must still be rendered for first-time creation", p)
+ }
+ }
+}
+
+func TestRenderDoesNotKeepSiteConf(t *testing.T) {
+ cfg := testConfig(t)
+ s := staticSite()
+ r := RenderSite(cfg, s, DefaultWAF())
+ siteConf := cfg.SiteConfPath(s.Slug)
+ for _, p := range r.Keep {
+ if p == siteConf {
+ t.Fatalf("%s must be rewritten on every render", siteConf)
+ }
+ }
+}