security: harden license server and packaging checks

This commit is contained in:
Your Name committed 2026-06-23 23:47:19 +08:00
1 parent 9062ee7204
commit d0166d27d3
5 files changed
+160 -14

No files matched your search

+3
View File
@@ -81,6 +81,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_TRUST_FORWARDED_FOR=1`。
## 自动更新
+37 -4
View File
@@ -20,6 +20,7 @@ from license_server.core import LicenseActionResult, LicenseService, UpdateManif
RATE_LIMIT_WINDOW_SECONDS = 60
RATE_LIMIT_MAX_REQUESTS = 30
ADMIN_LOGIN_RATE_LIMIT_MAX_REQUESTS = 10
VERIFY_LICENSE_RATE_LIMIT_MAX_REQUESTS = 600
ADMIN_CSRF_COOKIE = "dygj_admin_csrf"
ADMIN_SESSION_COOKIE = "dygj_admin_session"
@@ -85,6 +86,15 @@ def admin_token_from_env() -> str:
return str(os.environ.get("DYGJ_LICENSE_ADMIN_TOKEN") or "").strip()
def _env_bool(name: str, default: bool = False) -> bool:
raw = str(os.environ.get(name) or "").strip().lower()
if raw in {"1", "true", "yes", "y", "on"}:
return True
if raw in {"0", "false", "no", "n", "off"}:
return False
return default
def _admin_allowed(request: Request, admin_token: str) -> bool:
expected = str(admin_token or "").strip()
if not expected:
@@ -180,8 +190,10 @@ def _csrf_allowed(request: Request, token: str) -> bool:
def _rate_limit_key(request: Request, scope: str) -> str:
forwarded = str(request.headers.get("x-forwarded-for") or "").split(",", 1)[0].strip()
host = forwarded or (request.client.host if request.client else "unknown")
host = request.client.host if request.client else "unknown"
if getattr(request.app.state, "trust_forwarded_for", False):
forwarded = str(request.headers.get("x-forwarded-for") or "").split(",", 1)[0].strip()
host = forwarded or host
return f"{scope}:{host}"
@@ -413,9 +425,17 @@ def create_app(
service: LicenseService | None = None,
admin_token: str | None = None,
) -> FastAPI:
app = FastAPI(title="Douyin Guaji License Server")
docs_enabled = _env_bool("DYGJ_LICENSE_ENABLE_DOCS", default=False)
app = FastAPI(
title="Douyin Guaji License Server",
docs_url="/docs" if docs_enabled else None,
redoc_url="/redoc" if docs_enabled else None,
openapi_url="/openapi.json" if docs_enabled else None,
)
app.state.license_service = service
app.state.admin_token = admin_token if admin_token is not None else admin_token_from_env()
app.state.secure_cookies = _env_bool("DYGJ_LICENSE_SECURE_COOKIES", default=False)
app.state.trust_forwarded_for = _env_bool("DYGJ_LICENSE_TRUST_FORWARDED_FOR", default=False)
app.state.rate_limit_buckets = {}
app.state.admin_sessions = {}
@@ -482,7 +502,13 @@ def create_app(
return RedirectResponse("/admin/login", status_code=303)
csrf = _csrf_token(request)
response = _admin_page(get_service(), csrf)
response.set_cookie(ADMIN_CSRF_COOKIE, csrf, httponly=True, samesite="lax")
response.set_cookie(
ADMIN_CSRF_COOKIE,
csrf,
httponly=True,
samesite="lax",
secure=bool(app.state.secure_cookies),
)
return response
@app.get("/admin/login")
@@ -491,6 +517,12 @@ def create_app(
@app.post("/admin/login")
def admin_login(request: Request, admin_token: str = Form("")) -> HTMLResponse:
if _rate_limited(
request,
"admin_login",
max_requests=ADMIN_LOGIN_RATE_LIMIT_MAX_REQUESTS,
):
return _login_page("登录尝试过于频繁,请稍后再试。", status_code=429)
expected = str(app.state.admin_token or "").strip()
supplied = str(admin_token or "").strip()
if not expected or not hmac.compare_digest(supplied, expected):
@@ -503,6 +535,7 @@ def create_app(
max_age=ADMIN_SESSION_SECONDS,
httponly=True,
samesite="lax",
secure=bool(app.state.secure_cookies),
)
return response
+28
View File
@@ -46,6 +46,34 @@ def test_distribution_manifest_blocks_source_and_debug_artifacts():
assert "_internal/cv2/__init__.py" not in blocked
def test_distribution_manifest_blocks_project_native_binaries_outside_core_allowlist():
from tools.distribution_manifest import find_distribution_issues
entries = [
"DouyinGuajiGUI.exe",
"web_gui.exe",
"run_cli.exe",
"_internal/base_library.zip",
"_internal/python312.dll",
"_internal/tests/evil.pyd",
"_internal/tools/helper.dll",
"_internal/douyin/fudai/core/compiled.cp312-win_amd64.pyd",
"_internal/numpy/core/runtime.pyd",
"webui/index.html",
"config/README.md",
"logs/.keep",
"pic/.keep",
"state/.keep",
]
issues = find_distribution_issues(entries)
assert "_internal/tests/evil.pyd" in issues
assert "_internal/tools/helper.dll" in issues
assert "_internal/douyin/fudai/core/compiled.cp312-win_amd64.pyd" not in issues
assert "_internal/numpy/core/runtime.pyd" not in issues
def test_distribution_manifest_allows_expected_runtime_shape():
from tools.distribution_manifest import find_distribution_issues
+68
View File
@@ -261,6 +261,74 @@ def test_admin_login_rejects_wrong_token(tmp_path):
assert "管理员 token 不正确" in resp.text
def test_admin_login_is_rate_limited(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.setattr(api, "ADMIN_LOGIN_RATE_LIMIT_MAX_REQUESTS", 2)
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"))
for _ in range(2):
assert client.post("/admin/login", data={"admin_token": "wrong"}).status_code == 403
limited = client.post("/admin/login", data={"admin_token": "wrong"})
assert limited.status_code == 429
assert "登录尝试过于频繁" in limited.text
def test_license_server_secure_defaults_and_forwarded_for_policy(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.setattr(api, "RATE_LIMIT_MAX_REQUESTS", 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"))
assert client.get("/docs").status_code == 404
first = client.post(
"/api/v1/activate",
headers={"x-forwarded-for": "198.51.100.1"},
json={"card_key": "DG-NOPE-NOPE-NOPE", "machine_fingerprint": "machine-api"},
)
second = client.post(
"/api/v1/activate",
headers={"x-forwarded-for": "198.51.100.2"},
json={"card_key": "DG-NOPE-NOPE-NOPE", "machine_fingerprint": "machine-api"},
)
assert first.status_code == 404
assert second.status_code == 429
def test_license_server_can_enable_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_SECURE_COOKIES", "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"),
base_url="https://testserver",
)
login = client.post("/admin/login", data={"admin_token": "secret"}, follow_redirects=False)
csrf = client.get("/admin")
assert "secure" in login.headers["set-cookie"].lower()
assert "secure" in csrf.headers["set-cookie"].lower()
def test_admin_logout_clears_session(tmp_path):
from fastapi.testclient import TestClient
+24 -10
View File
@@ -95,6 +95,23 @@ ALLOWED_RUNTIME_PLACEHOLDERS = {
"state/.keep",
}
INTERNAL_PROJECT_PREFIXES = (
"_internal/douyin/",
"_internal/gui/",
"_internal/operations/",
"_internal/bin/",
"_internal/tools/",
"_internal/tests/",
"_internal/artifacts/",
)
ALLOWED_INTERNAL_PROJECT_PYD_PREFIXES = (
"_internal/douyin/detection/",
"_internal/douyin/fudai/",
"_internal/douyin/reservation/",
"_internal/douyin/stage/",
)
def normalize_entry(entry: str) -> str:
return entry.replace("\\", "/").lstrip("./")
@@ -106,18 +123,15 @@ def is_forbidden_distribution_entry(entry: str, *, allow_license: bool = False)
if lower == "license.dat" and allow_license:
return False
if lower.startswith("_internal/"):
if any(lower.startswith(prefix) for prefix in INTERNAL_PROJECT_PREFIXES):
if lower.endswith(".pyd") and any(
lower.startswith(prefix) for prefix in ALLOWED_INTERNAL_PROJECT_PYD_PREFIXES
):
return False
return True
if lower.endswith((".pyd", ".dll")):
return False
project_bits = {
"_internal/douyin/",
"_internal/gui/",
"_internal/operations/",
"_internal/bin/",
"_internal/tools/",
"_internal/tests/",
"_internal/artifacts/",
}
return any(lower.startswith(prefix) for prefix in project_bits)
return False
if lower in ALLOWED_RUNTIME_PLACEHOLDERS:
return False
if lower in FORBIDDEN_EXACT: