fix: harden license server security

This commit is contained in:
Your Name committed 2026-06-19 01:11:10 +08:00
1 parent ec51772cf0
commit a39545ed5d
10 files changed
+313 -88

No files matched your search

+117 -27
View File
@@ -1,6 +1,10 @@
from __future__ import annotations
import base64
import hmac
import os
import secrets
import time
from html import escape
from pathlib import Path
from typing import Any
@@ -9,7 +13,12 @@ from fastapi import FastAPI, Form, Request
from fastapi.responses import HTMLResponse, JSONResponse
from pydantic import BaseModel
from license_server.core import DEV_PRIVATE_KEY_PEM, LicenseActionResult, LicenseService
from license_server.core import LicenseActionResult, LicenseService
RATE_LIMIT_WINDOW_SECONDS = 60
RATE_LIMIT_MAX_REQUESTS = 30
ADMIN_CSRF_COOKIE = "dygj_admin_csrf"
class ActivateRequest(BaseModel):
@@ -37,6 +46,8 @@ def result_response(result: LicenseActionResult) -> JSONResponse:
def _status_for_reason(reason: str) -> int:
if reason == "rate_limited":
return 429
if reason == "not_found":
return 404
if reason in {"revoked", "inactive", "device_limit", "machine_mismatch"}:
@@ -53,7 +64,7 @@ def load_private_key_pem() -> bytes:
raw_pem = str(os.environ.get("DYGJ_LICENSE_PRIVATE_KEY_PEM") or "").strip()
if raw_pem:
return raw_pem.encode("utf-8")
return DEV_PRIVATE_KEY_PEM
raise RuntimeError("missing DYGJ_LICENSE_PRIVATE_KEY_PATH or DYGJ_LICENSE_PRIVATE_KEY_PEM")
def create_service_from_env() -> LicenseService:
@@ -69,24 +80,69 @@ def _admin_allowed(request: Request, admin_token: str) -> bool:
expected = str(admin_token or "").strip()
if not expected:
return False
supplied = str(request.query_params.get("token") or "").strip()
if supplied == expected:
return True
auth = str(request.headers.get("authorization") or "").strip()
return auth == f"Bearer {expected}"
if hmac.compare_digest(auth, f"Bearer {expected}"):
return True
if not auth.lower().startswith("basic "):
return False
try:
decoded = base64.b64decode(auth.split(" ", 1)[1], validate=True).decode("utf-8")
except Exception:
return False
_user, sep, supplied = decoded.partition(":")
if not sep:
return False
return hmac.compare_digest(supplied, expected)
def _admin_forbidden() -> HTMLResponse:
return HTMLResponse("<h1>403</h1><p>需要管理员 token。</p>", status_code=403)
return HTMLResponse(
"<h1>403</h1><p>需要管理员登录。</p>",
status_code=403,
headers={"WWW-Authenticate": 'Basic realm="Douyin License Admin"'},
)
def _csrf_token(request: Request) -> str:
raw = str(request.cookies.get(ADMIN_CSRF_COOKIE) or "").strip()
if len(raw) >= 32:
return raw
return secrets.token_urlsafe(24)
def _csrf_allowed(request: Request, token: str) -> bool:
cookie = str(request.cookies.get(ADMIN_CSRF_COOKIE) or "").strip()
supplied = str(token or "").strip()
return bool(cookie and supplied and hmac.compare_digest(cookie, supplied))
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")
return f"{scope}:{host}"
def _rate_limited(request: Request, scope: str, *, max_requests: int | None = None) -> bool:
threshold = RATE_LIMIT_MAX_REQUESTS if max_requests is None else int(max_requests)
now = time.monotonic()
key = _rate_limit_key(request, scope)
buckets: dict[str, list[float]] = request.app.state.rate_limit_buckets
recent = [ts for ts in buckets.get(key, []) if now - ts < RATE_LIMIT_WINDOW_SECONDS]
if len(recent) >= threshold:
buckets[key] = recent
return True
recent.append(now)
buckets[key] = recent
return False
def _admin_page(
service: LicenseService,
token: str,
csrf_token: str,
message: str = "",
cards: list[str] | None = None,
) -> HTMLResponse:
token_attr = escape(token, quote=True)
csrf_attr = escape(csrf_token, quote=True)
stats = service.stats()
card_rows = service.list_cards(limit=50)
audit_rows = service.audit_logs(limit=30)
@@ -168,7 +224,8 @@ def _admin_page(
{message_html}
<section>
<h2>生成卡密</h2>
<form class="inline" method="post" action="/admin/create?token={token_attr}">
<form class="inline" method="post" action="/admin/create">
<input type="hidden" name="csrf_token" value="{csrf_attr}" />
<label>天数 <input name="days" value="30" /></label>
<label>数量 <input name="count" value="1" /></label>
<label>设备数 <input name="max_devices" value="1" /></label>
@@ -180,14 +237,16 @@ def _admin_page(
<div class="cards">
<section>
<h2>禁用卡密</h2>
<form method="post" action="/admin/revoke?token={token_attr}">
<form method="post" action="/admin/revoke">
<input type="hidden" name="csrf_token" value="{csrf_attr}" />
<label>卡密 <input name="card_key" placeholder="DG-..." /></label>
<button class="danger" type="submit">禁用</button>
</form>
</section>
<section>
<h2>解绑设备</h2>
<form method="post" action="/admin/unbind?token={token_attr}">
<form method="post" action="/admin/unbind">
<input type="hidden" name="csrf_token" value="{csrf_attr}" />
<label>卡密 <input name="card_key" placeholder="DG-..." /></label>
<button class="secondary" type="submit">解绑</button>
</form>
@@ -221,6 +280,7 @@ def create_app(
app = FastAPI(title="Douyin Guaji License Server")
app.state.license_service = service
app.state.admin_token = admin_token if admin_token is not None else admin_token_from_env()
app.state.rate_limit_buckets = {}
def get_service() -> LicenseService:
if app.state.license_service is None:
@@ -232,7 +292,9 @@ def create_app(
return {"ok": True, "service": "douyin-license-server"}
@app.post("/api/v1/activate")
def activate(req: ActivateRequest) -> JSONResponse:
def activate(request: Request, req: ActivateRequest) -> JSONResponse:
if _rate_limited(request, "activate"):
return result_response(LicenseActionResult(False, "rate_limited", "请求过于频繁,请稍后再试"))
return result_response(
get_service().activate(
req.card_key,
@@ -241,7 +303,9 @@ def create_app(
)
@app.post("/api/v1/verify")
def verify(req: VerifyRequest) -> JSONResponse:
def verify(request: Request, req: VerifyRequest) -> JSONResponse:
if _rate_limited(request, "verify"):
return result_response(LicenseActionResult(False, "rate_limited", "请求过于频繁,请稍后再试"))
return result_response(
get_service().verify(
req.card_key,
@@ -253,11 +317,15 @@ def create_app(
def admin(request: Request) -> HTMLResponse:
if not _admin_allowed(request, app.state.admin_token):
return _admin_forbidden()
return _admin_page(get_service(), str(request.query_params.get("token") or ""))
csrf = _csrf_token(request)
response = _admin_page(get_service(), csrf)
response.set_cookie(ADMIN_CSRF_COOKIE, csrf, httponly=True, samesite="lax")
return response
@app.post("/admin/create")
def admin_create(
request: Request,
csrf_token: str = Form(""),
days: int = Form(30),
count: int = Form(1),
max_devices: int = Form(1),
@@ -265,39 +333,61 @@ def create_app(
) -> HTMLResponse:
if not _admin_allowed(request, app.state.admin_token):
return _admin_forbidden()
cards = get_service().create_cards(
days=days,
count=count,
max_devices=max_devices,
customer=customer,
)
csrf = _csrf_token(request)
if not _csrf_allowed(request, csrf_token):
return _admin_page(get_service(), csrf, message="CSRF 校验失败,请刷新后台页面后重试")
try:
cards = get_service().create_cards(
days=days,
count=count,
max_devices=max_devices,
customer=customer,
)
message = f"已生成 {len(cards)} 个卡密,customer={customer}"
except ValueError as exc:
cards = []
message = f"参数错误:{exc}"
return _admin_page(
get_service(),
str(request.query_params.get("token") or ""),
message=f"已生成 {len(cards)} 个卡密,customer={customer}",
csrf,
message=message,
cards=[card.code for card in cards],
)
@app.post("/admin/revoke")
def admin_revoke(request: Request, card_key: str = Form("")) -> HTMLResponse:
def admin_revoke(
request: Request,
csrf_token: str = Form(""),
card_key: str = Form(""),
) -> HTMLResponse:
if not _admin_allowed(request, app.state.admin_token):
return _admin_forbidden()
csrf = _csrf_token(request)
if not _csrf_allowed(request, csrf_token):
return _admin_page(get_service(), csrf, message="CSRF 校验失败,请刷新后台页面后重试")
ok = get_service().revoke(card_key)
msg = "已禁用" if ok else "卡密不存在"
return _admin_page(
get_service(),
str(request.query_params.get("token") or ""),
csrf,
message=msg,
)
@app.post("/admin/unbind")
def admin_unbind(request: Request, card_key: str = Form("")) -> HTMLResponse:
def admin_unbind(
request: Request,
csrf_token: str = Form(""),
card_key: str = Form(""),
) -> HTMLResponse:
if not _admin_allowed(request, app.state.admin_token):
return _admin_forbidden()
csrf = _csrf_token(request)
if not _csrf_allowed(request, csrf_token):
return _admin_page(get_service(), csrf, message="CSRF 校验失败,请刷新后台页面后重试")
count = get_service().unbind(card_key)
return _admin_page(
get_service(),
str(request.query_params.get("token") or ""),
csrf,
message=f"已解绑 {count} 台设备",
)