fix: harden license server and web gui security

This commit is contained in:
Your Name committed 2026-06-28 09:24:22 +08:00
1 parent 7c6189fd5e
commit ee3424cd9e
9 files changed
+357 -11

No files matched your search

+21
View File
@@ -2,12 +2,33 @@ import json
from http.server import BaseHTTPRequestHandler
SECURITY_HEADERS = (
("X-Content-Type-Options", "nosniff"),
("Referrer-Policy", "no-referrer"),
("X-Frame-Options", "DENY"),
)
def send_security_headers(handler: BaseHTTPRequestHandler) -> None:
for key, value in SECURITY_HEADERS:
handler.send_header(key, value)
def send_html_security_headers(handler: BaseHTTPRequestHandler) -> None:
send_security_headers(handler)
handler.send_header(
"Content-Security-Policy",
"default-src 'self'; img-src 'self' data:; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline'; object-src 'none'; base-uri 'none'; frame-ancestors 'none'",
)
def send_json(handler: BaseHTTPRequestHandler, obj, status: int = 200) -> None:
data = json.dumps(obj, ensure_ascii=False).encode("utf-8")
handler.send_response(status)
handler.send_header("Content-Type", "application/json; charset=utf-8")
handler.send_header("Cache-Control", "no-store")
handler.send_header("Content-Length", str(len(data)))
send_security_headers(handler)
handler.end_headers()
try:
handler.wfile.write(data)
+4
View File
@@ -21,6 +21,7 @@ from gui.web_gui_pkg import (
write_config,
proc_runner_ops as _proc_ops,
)
from gui.web_gui_pkg.request_parsing import send_html_security_headers, send_security_headers
BASE_DIR = (
path_config.PROJECT_ROOT
@@ -111,6 +112,7 @@ def _send_html(handler, html: str, status: int = 200) -> None:
handler.send_header("Content-Type", "text/html; charset=utf-8")
handler.send_header("Content-Length", str(len(data)))
handler.send_header("Cache-Control", "no-store")
send_html_security_headers(handler)
handler.end_headers()
handler.wfile.write(data)
@@ -355,6 +357,7 @@ def handle_get(handler, u, runner, csrf_token: str) -> None:
handler.send_header("Content-Type", "image/png")
handler.send_header("Content-Length", str(len(_EMPTY_PNG_BYTES)))
handler.send_header("Cache-Control", "no-store")
send_security_headers(handler)
handler.end_headers()
handler.wfile.write(_EMPTY_PNG_BYTES)
return
@@ -372,6 +375,7 @@ def handle_get(handler, u, runner, csrf_token: str) -> None:
handler.send_header("Content-Type", ctype)
handler.send_header("Content-Length", str(len(data)))
handler.send_header("Cache-Control", "no-store")
send_security_headers(handler)
handler.end_headers()
handler.wfile.write(data)
return
+7
View File
@@ -3,6 +3,8 @@ from http import HTTPStatus
from http.server import BaseHTTPRequestHandler
from typing import Callable
from gui.web_gui_pkg.request_parsing import send_html_security_headers, send_security_headers
def serve_static(
handler: BaseHTTPRequestHandler,
@@ -60,6 +62,7 @@ def serve_static(
handler.send_response(HTTPStatus.NOT_MODIFIED)
handler.send_header("ETag", etag)
handler.send_header("Cache-Control", cache_control)
send_security_headers(handler)
handler.end_headers()
return
except Exception:
@@ -68,6 +71,10 @@ def serve_static(
handler.send_header("Content-Type", ctype)
handler.send_header("Content-Length", str(len(data)))
handler.send_header("Cache-Control", cache_control)
if ext == ".html":
send_html_security_headers(handler)
else:
send_security_headers(handler)
if etag:
handler.send_header("ETag", etag)
handler.end_headers()
+10 -1
View File
@@ -126,7 +126,9 @@ export DYGJ_LICENSE_ADMIN_TOKEN="$(cat secrets/admin_token.txt)"
不要把管理员 token 放到 URL 里,避免进入浏览器历史、访问日志或截图。
生产环境默认关闭 `/docs`、`/redoc` 和 `/openapi.json`;确实需要临时查看时设置 `DYGJ_LICENSE_ENABLE_DOCS=1`。
如果服务通过 HTTPS 访问,建议设置 `DYGJ_LICENSE_SECURE_COOKIES=1`。
生产环境建议显式设置 `DYGJ_LICENSE_PUBLIC_BASE_URL=https://你的域名`,服务会用它生成兑换链接和更新下载地址。
设置 HTTPS 的 `DYGJ_LICENSE_PUBLIC_BASE_URL` 后,后台 Cookie 会默认带 `Secure`;如需手动覆盖,可设置 `DYGJ_LICENSE_SECURE_COOKIES=1`。
服务端会校验 Host 头,默认允许 `dy.absfan.cn`、`127.0.0.1`、`localhost` 和测试域名;自定义域名可设置 `DYGJ_LICENSE_ALLOWED_HOSTS=你的域名,备用域名`。
只有在前面有可信反向代理时,才设置 `DYGJ_LICENSE_TRUST_FORWARDED_FOR=1`。
## 自动更新
@@ -144,6 +146,13 @@ http://服务器IP:18100/admin
- 生成 `/api/v1/update/manifest`
- 使用服务端私钥给 manifest 签名
默认上传大小限制:完整安装包最大 700 MB,差量包最大 250 MB。需要调整时设置:
```bash
export DYGJ_LICENSE_MAX_INSTALLER_UPLOAD_MB=700
export DYGJ_LICENSE_MAX_DELTA_UPLOAD_MB=250
```
如果要发布差量更新,再上传 `DouyinGuaji-旧版本_to_新版本_delta.zip`,并填写来源版本和目标版本。新客户端会优先下载匹配自己当前版本的差量包;没有匹配差量包时,才回退下载完整安装包。
生成差量包示例:
+131 -10
View File
@@ -6,15 +6,17 @@ import hashlib
import json
import os
import secrets
import tempfile
import time
from html import escape
from pathlib import Path
from typing import Any
from urllib.parse import urljoin
from urllib.parse import urljoin, urlparse
from fastapi import FastAPI, File, Form, Request, UploadFile
from fastapi.responses import FileResponse, HTMLResponse, JSONResponse, RedirectResponse, Response
from pydantic import BaseModel
from starlette.middleware.trustedhost import TrustedHostMiddleware
from license_server.core import LicenseActionResult, LicenseService, UpdateManifest
@@ -28,6 +30,9 @@ REDEEM_CLAIM_RATE_LIMIT_MAX_REQUESTS = 60
ADMIN_CSRF_COOKIE = "dygj_admin_csrf"
ADMIN_SESSION_COOKIE = "dygj_admin_session"
ADMIN_SESSION_SECONDS = 12 * 60 * 60
DEFAULT_MAX_INSTALLER_UPLOAD_BYTES = 700 * 1024 * 1024
DEFAULT_MAX_DELTA_UPLOAD_BYTES = 250 * 1024 * 1024
UPLOAD_CHUNK_BYTES = 1024 * 1024
class ActivateRequest(BaseModel):
@@ -115,6 +120,84 @@ def _env_bool(name: str, default: bool = False) -> bool:
return default
def _env_int(name: str, default: int) -> int:
raw = str(os.environ.get(name) or "").strip()
if not raw:
return int(default)
try:
value = int(raw)
except ValueError:
return int(default)
return value if value > 0 else int(default)
def _configured_public_base_url() -> str:
return str(os.environ.get("DYGJ_LICENSE_PUBLIC_BASE_URL") or "").strip()
def _default_secure_cookies() -> bool:
return _configured_public_base_url().lower().startswith("https://")
def _allowed_hosts_from_env() -> list[str]:
raw = str(os.environ.get("DYGJ_LICENSE_ALLOWED_HOSTS") or "").strip()
hosts = [h.strip() for h in raw.split(",") if h.strip()]
configured = _configured_public_base_url()
if configured:
parsed = urlparse(configured)
if parsed.hostname:
hosts.append(parsed.hostname)
hosts.extend(["dy.absfan.cn", "127.0.0.1", "localhost", "testserver"])
result: list[str] = []
for host in hosts:
if host and host not in result:
result.append(host)
return result
async def _save_upload_to_temp(
upload: UploadFile,
*,
upload_dir: Path,
max_bytes: int,
suffix: str,
) -> Path:
upload_dir.mkdir(parents=True, exist_ok=True)
tmp_name = ""
total = 0
try:
with tempfile.NamedTemporaryFile(
"wb",
delete=False,
dir=str(upload_dir),
suffix=suffix,
) as tmp:
tmp_name = tmp.name
while True:
chunk = await upload.read(UPLOAD_CHUNK_BYTES)
if not chunk:
break
total += len(chunk)
if total > max_bytes:
raise ValueError(f"上传文件超过大小限制(最大 {max_bytes // (1024 * 1024)} MB)")
tmp.write(chunk)
if total <= 0:
raise ValueError("上传文件为空")
return Path(tmp_name)
except Exception:
if tmp_name:
try:
Path(tmp_name).unlink(missing_ok=True)
except Exception:
pass
raise
finally:
try:
await upload.close()
except Exception:
pass
def _admin_allowed(request: Request, admin_token: str) -> bool:
expected = str(admin_token or "").strip()
if not expected:
@@ -243,7 +326,7 @@ def _rate_limited(request: Request, scope: str, *, max_requests: int | None = No
def _public_base_url(request: Request) -> str:
configured = str(os.environ.get("DYGJ_LICENSE_PUBLIC_BASE_URL") or "").strip()
configured = _configured_public_base_url()
if configured:
return configured.rstrip("/")
return str(request.base_url).rstrip("/")
@@ -487,13 +570,22 @@ def create_app(
redoc_url="/redoc" if docs_enabled else None,
openapi_url="/openapi.json" if docs_enabled else None,
)
app.add_middleware(TrustedHostMiddleware, allowed_hosts=_allowed_hosts_from_env())
app.state.license_service = service
app.state.admin_token = admin_token if admin_token is not None else admin_token_from_env()
app.state.external_api_token = (
external_api_token if external_api_token is not None else external_api_token_from_env()
)
app.state.secure_cookies = _env_bool("DYGJ_LICENSE_SECURE_COOKIES", default=False)
app.state.secure_cookies = _env_bool("DYGJ_LICENSE_SECURE_COOKIES", default=_default_secure_cookies())
app.state.trust_forwarded_for = _env_bool("DYGJ_LICENSE_TRUST_FORWARDED_FOR", default=False)
app.state.max_installer_upload_bytes = _env_int(
"DYGJ_LICENSE_MAX_INSTALLER_UPLOAD_MB",
DEFAULT_MAX_INSTALLER_UPLOAD_BYTES // (1024 * 1024),
) * 1024 * 1024
app.state.max_delta_upload_bytes = _env_int(
"DYGJ_LICENSE_MAX_DELTA_UPLOAD_MB",
DEFAULT_MAX_DELTA_UPLOAD_BYTES // (1024 * 1024),
) * 1024 * 1024
app.state.rate_limit_buckets = {}
app.state.admin_sessions = {}
@@ -664,7 +756,10 @@ document.getElementById("claim").addEventListener("click", async () => {{
}});
const data = await resp.json();
if (data.ok) {{
result.innerHTML = "兑换成功,卡密:<code>" + data.card_key + "</code>";
result.textContent = "兑换成功,卡密:";
const code = document.createElement("code");
code.textContent = data.card_key || "";
result.appendChild(code);
}} else {{
result.textContent = data.message || data.reason || "兑换失败";
}}
@@ -831,18 +926,31 @@ document.getElementById("claim").addEventListener("click", async () => {{
csrf = _csrf_token(request)
if not _csrf_allowed(request, csrf_token):
return _admin_page(get_service(), csrf, message="CSRF 校验失败,请刷新后台页面后重试")
tmp_path: Path | None = None
try:
content = await installer.read()
manifest = get_service().publish_update(
service = get_service()
tmp_path = await _save_upload_to_temp(
installer,
upload_dir=service.update_dir / ".uploads",
max_bytes=app.state.max_installer_upload_bytes,
suffix=".exe.upload",
)
manifest = service.publish_update_file(
version=version,
filename=installer.filename or "",
content=content,
file_path=tmp_path,
force=str(force).strip() not in {"0", "false", "False", "否"},
notes=notes,
)
msg = f"已发布更新 V{manifest.version},文件={manifest.filename}"
except Exception as exc:
msg = f"发布更新失败:{exc}"
finally:
if tmp_path is not None:
try:
tmp_path.unlink(missing_ok=True)
except Exception:
pass
return _admin_page(get_service(), csrf, message=msg)
@app.post("/admin/update/publish-delta")
@@ -858,18 +966,31 @@ document.getElementById("claim").addEventListener("click", async () => {{
csrf = _csrf_token(request)
if not _csrf_allowed(request, csrf_token):
return _admin_page(get_service(), csrf, message="CSRF 校验失败,请刷新后台页面后重试")
tmp_path: Path | None = None
try:
content = await delta_file.read()
manifest = get_service().publish_delta_update(
service = get_service()
tmp_path = await _save_upload_to_temp(
delta_file,
upload_dir=service.update_dir / ".uploads",
max_bytes=app.state.max_delta_upload_bytes,
suffix=".zip.upload",
)
manifest = service.publish_delta_update_file(
from_version=from_version,
to_version=to_version,
filename=delta_file.filename or "",
content=content,
file_path=tmp_path,
)
delta = manifest.delta or {}
msg = f"已发布差量更新 {delta.get('from_version')} -> {delta.get('to_version')},文件={delta.get('filename')}"
except Exception as exc:
msg = f"发布差量更新失败:{exc}"
finally:
if tmp_path is not None:
try:
tmp_path.unlink(missing_ok=True)
except Exception:
pass
return _admin_page(get_service(), csrf, message=msg)
@app.post("/admin/update/disable")
+94
View File
@@ -5,6 +5,7 @@ import hashlib
import json
import re
import secrets
import shutil
import sqlite3
from dataclasses import dataclass
from datetime import datetime, timedelta, timezone
@@ -186,6 +187,14 @@ def sha256_bytes(data: bytes) -> str:
return hashlib.sha256(data).hexdigest()
def sha256_file(path: str | Path) -> str:
digest = hashlib.sha256()
with Path(path).open("rb") as f:
for chunk in iter(lambda: f.read(1024 * 1024), b""):
digest.update(chunk)
return digest.hexdigest()
def _bounded_int(value: int, *, name: str, minimum: int, maximum: int) -> int:
parsed = int(value)
if parsed < minimum or parsed > maximum:
@@ -587,6 +596,42 @@ class LicenseService:
)
return manifest
def publish_update_file(
self,
*,
version: str,
filename: str,
file_path: str | Path,
force: bool = True,
notes: str = "",
) -> UpdateManifest:
version = str(version or "").strip().lstrip("Vv")
if not re.fullmatch(r"\d+(?:\.\d+){0,3}", version):
raise ValueError("version must look like 3.3.4")
source = Path(file_path)
if not source.is_file() or source.stat().st_size <= 0:
raise ValueError("installer file is empty")
safe_filename = sanitize_update_filename(filename, version=version)
if not safe_filename.lower().endswith(".exe"):
raise ValueError("installer must be an .exe file")
target = self.update_dir / safe_filename
shutil.copyfile(source, target)
manifest = UpdateManifest(
enabled=True,
version=version,
filename=safe_filename,
sha256=sha256_file(target),
force=bool(force),
notes=str(notes or "").strip()[:500],
published_at=iso_utc(utcnow()),
delta=None,
)
self.update_manifest_path.write_text(
json.dumps(manifest.__dict__, ensure_ascii=False, indent=2),
encoding="utf-8",
)
return manifest
def publish_delta_update(
self,
*,
@@ -635,6 +680,55 @@ class LicenseService:
)
return manifest
def publish_delta_update_file(
self,
*,
from_version: str,
to_version: str,
filename: str,
file_path: str | Path,
) -> UpdateManifest:
existing = self.load_update_manifest()
if not existing.enabled:
raise ValueError("publish full installer before delta")
to_version = str(to_version or "").strip().lstrip("Vv")
from_version = str(from_version or "").strip().lstrip("Vv")
if existing.version != to_version:
raise ValueError("delta target version must match current manifest version")
if not re.fullmatch(r"\d+(?:\.\d+){0,3}", from_version):
raise ValueError("from_version must look like 3.3.4")
source = Path(file_path)
if not source.is_file() or source.stat().st_size <= 0:
raise ValueError("delta file is empty")
safe_filename = sanitize_delta_filename(filename, from_version=from_version, to_version=to_version)
if not safe_filename.lower().endswith(".zip"):
raise ValueError("delta must be a .zip file")
target = self.update_dir / safe_filename
shutil.copyfile(source, target)
delta = {
"schema": 1,
"from_version": from_version,
"to_version": to_version,
"filename": safe_filename,
"sha256": sha256_file(target),
"size": target.stat().st_size,
}
manifest = UpdateManifest(
enabled=existing.enabled,
version=existing.version,
filename=existing.filename,
sha256=existing.sha256,
force=existing.force,
notes=existing.notes,
published_at=existing.published_at,
delta=delta,
)
self.update_manifest_path.write_text(
json.dumps(manifest.__dict__, ensure_ascii=False, indent=2),
encoding="utf-8",
)
return manifest
def disable_update(self) -> UpdateManifest:
existing = self.load_update_manifest()
manifest = UpdateManifest(
+66
View File
@@ -181,6 +181,37 @@ def test_admin_can_publish_update_and_download_installer(tmp_path):
assert download.content == payload
def test_admin_publish_update_rejects_oversized_upload(tmp_path, monkeypatch):
from fastapi.testclient import TestClient
from license_server import api
from license_server.core import LicenseService
from tests.license_test_keys import TEST_PRIVATE_KEY_PEM
monkeypatch.setenv("DYGJ_LICENSE_MAX_INSTALLER_UPLOAD_MB", "1")
service = LicenseService(db_path=tmp_path / "license.db", private_key_pem=TEST_PRIVATE_KEY_PEM)
client = TestClient(api.create_app(service=service, admin_token="secret"))
client.post("/admin/login", data={"admin_token": "secret"}, follow_redirects=False)
payload = b"x" * (1024 * 1024 + 1)
published = client.post(
"/admin/update/publish",
cookies={api.ADMIN_CSRF_COOKIE: "csrf-token"},
data={
"csrf_token": "csrf-token",
"version": "3.3.4",
"notes": "oversized",
"force": "1",
},
files={"installer": ("DouyinGuaji-3.3.4-Setup.exe", payload, "application/octet-stream")},
)
manifest = client.get("/api/v1/update/manifest").json()
assert published.status_code == 200
assert "超过大小限制" in published.text
assert manifest["enabled"] is False
def test_admin_can_publish_delta_update_and_download_zip(tmp_path):
from fastapi.testclient import TestClient
@@ -229,6 +260,41 @@ def test_admin_can_publish_delta_update_and_download_zip(tmp_path):
assert download.content == delta_payload
def test_license_server_rejects_untrusted_host(tmp_path):
from fastapi.testclient import TestClient
from license_server import api
from license_server.core import LicenseService
from tests.license_test_keys import TEST_PRIVATE_KEY_PEM
service = LicenseService(db_path=tmp_path / "license.db", private_key_pem=TEST_PRIVATE_KEY_PEM)
client = TestClient(api.create_app(service=service), base_url="https://evil.example")
resp = client.get("/api/v1/health")
assert resp.status_code == 400
def test_public_https_base_url_enables_secure_admin_cookies(tmp_path, monkeypatch):
from fastapi.testclient import TestClient
from license_server import api
from license_server.core import LicenseService
from tests.license_test_keys import TEST_PRIVATE_KEY_PEM
monkeypatch.setenv("DYGJ_LICENSE_PUBLIC_BASE_URL", "https://dy.absfan.cn")
service = LicenseService(db_path=tmp_path / "license.db", private_key_pem=TEST_PRIVATE_KEY_PEM)
client = TestClient(
api.create_app(service=service, admin_token="secret"),
base_url="https://dy.absfan.cn",
)
login = client.post("/admin/login", data={"admin_token": "secret"}, follow_redirects=False)
assert login.status_code == 303
assert "secure" in login.headers["set-cookie"].lower()
def test_admin_page_shows_stats_cards_and_audit_logs(tmp_path):
from fastapi.testclient import TestClient
+3
View File
@@ -280,3 +280,6 @@ class TestRequestParsing:
assert dummy.status == 200
assert dummy.header_finished is True
assert ("X-Content-Type-Options", "nosniff") in dummy.headers
assert ("Referrer-Policy", "no-referrer") in dummy.headers
assert ("X-Frame-Options", "DENY") in dummy.headers
+21
View File
@@ -619,6 +619,27 @@ def test_rejects_non_local_get_api_requests(monkeypatch):
assert obj.get("error") == "Local access only"
def test_license_gate_html_has_security_headers(monkeypatch):
monkeypatch.setattr(routes, "check_license", lambda: SimpleNamespace(ok=False))
monkeypatch.setattr(
routes,
"render_license_gate_html",
lambda token: "<!doctype html><html><body>gate</body></html>", # noqa: ARG005
)
handler = _DummyHandler()
runner = _DummyRunner()
u = SimpleNamespace(path="/", query="")
routes.handle_get(handler, u, runner, "token")
headers = dict(handler.response_headers)
assert handler.response_status == 200
assert headers["X-Content-Type-Options"] == "nosniff"
assert headers["Referrer-Policy"] == "no-referrer"
assert headers["X-Frame-Options"] == "DENY"
assert "Content-Security-Policy" in headers
def test_rejects_non_local_pic_requests(monkeypatch):
handler = _DummyHandler()
handler.client_address = ("192.168.1.50", 55555)