fix: 堵住 /api/dev/* 公网入口,修会话过期时间与上传孤儿文件
安全(P0) - app.py: QINGLING_ENV=prod 时不注册 /api/dev/*(6 条)与短信登录(2 条), 请求落到 404;路由数 dev 57 / prod 49 - deploy: compose 默认 QINGLING_ENV=prod;Caddyfile 对 /api/dev/* 与 /api/auth/sms-* 再兜一层 404(就算环境变量被改回 dev,公网也打不到) - app.py: 生产环境不再把异常原文回给前端;CORS 生产默认不发 Access-Control-Allow-Origin(需要跨域用 QINGLING_CORS 配置) 正确性 - services: sessions.expires_at 从「创建时刻」改成「创建 + 7 天」(4 处: login / login_ticket / login_phone / _session_payload),并新增 purge_expired_sessions(),挂在 health 上顺手清理(这张表从没清过) - services: create_paper_from_image 在 OCR 抛异常、或退回演示题库时删掉 未入库的原图与擦除页,不再留孤儿文件;papers 表新增 image_path 并在 建卷时写入 - services: 新增 cleanup_uploads()/sweep_uploads(),按「文件名主干 = papers.id」清掉 90 天前没人引用的上传文件(每天最多扫一次) - app.py: 请求体按 Content-Length 限 16MB(直连 8000 时没有 Caddy 兜底), 坏 Content-Length 回 400 而不是 500 - app.py: paper_clean 按真实后缀回 Content-Type(TextIn 擦除结果是 .jpg, 以前一律当 png 发) 部署 - Dockerfile 安装 Pillow:没有它 img_w=img_h=0,「小图先拦一道」和 「图太小就不做 TextIn 擦除」在容器里会静默失效 - README/上线清单:补 prod 路由数与 /api/dev 验收项 验证 - python -m unittest(5 个模块)91 passed - 冒烟:prod 下 4 个 dev/sms 接口 404、routes=49、20MB 请求 413、 坏 Content-Length 400、expires_at=created+7d、health 清理过期会话、 清完旧令牌仍有效、papers.image_path 存在 - uploads 清理:孤儿文件删掉、被引用的原图与擦除页保留、新文件不动
This commit is contained in:
+47
-10
@@ -33,10 +33,27 @@ WORKBENCH = ROOT / "prototype" / "workbench" / "index.html"
|
||||
BRAND_DIR = ROOT / "brand"
|
||||
ROUTES: list[tuple[str, re.Pattern, object, str]] = []
|
||||
|
||||
# 生产环境(QINGLING_ENV=prod)不注册这两组路由:
|
||||
# /api/dev/* 能清库、能签年卡、能伪造扫码登录,只该在本地存在;
|
||||
# /api/auth/sms-* 这一版没接短信服务商,验证码是随响应回显的,
|
||||
# 线上等于「任意手机号都能直接注册并登录」。
|
||||
PROD = os.environ.get("QINGLING_ENV", "dev").strip().lower() in ("prod", "production")
|
||||
DEV_ONLY_PREFIXES = ("/api/dev/", "/api/auth/sms-")
|
||||
MAX_BODY = 16 * 1024 * 1024 # 与 Caddy 的 request_body max_size 对齐
|
||||
CORS_ORIGINS = [o.strip() for o in
|
||||
(os.environ.get("QINGLING_CORS") or ("*" if not PROD else "")).split(",")
|
||||
if o.strip()]
|
||||
|
||||
|
||||
def route(method: str, pattern: str, auth: str = "parent"):
|
||||
"""auth: parent | child_ok | none"""
|
||||
"""auth: parent | child_ok | none
|
||||
|
||||
生产环境里 DEV_ONLY_PREFIXES 命中的路由直接不注册——请求会落到 404,
|
||||
而不是「注册了但返回 403」,这样连「这个接口存在」都不泄漏。
|
||||
"""
|
||||
def deco(fn):
|
||||
if PROD and pattern.startswith(DEV_ONLY_PREFIXES):
|
||||
return fn
|
||||
ROUTES.append((method, re.compile("^" + pattern + "$"), fn, auth))
|
||||
return fn
|
||||
return deco
|
||||
@@ -69,8 +86,10 @@ class Ctx:
|
||||
|
||||
@route("GET", "/api/health", auth="none")
|
||||
def health(ctx: Ctx, **kw):
|
||||
try: # 顺手清理过期的删号申请(一次索引查询,很便宜)
|
||||
try: # 顺手清理过期的删号申请与会话(各一次索引查询,很便宜)
|
||||
svc.purge_due(ctx.conn)
|
||||
svc.purge_expired_sessions(ctx.conn)
|
||||
svc.sweep_uploads(ctx.conn) # 上传目录按 90 天清,内部自己限每天一次
|
||||
except Exception:
|
||||
pass
|
||||
return {"ok": True, "service": "qingling-primary", "version": "1.2.0", "time": dbm.now(),
|
||||
@@ -262,7 +281,8 @@ def paper_clean(ctx: Ctx, pid: str, **kw):
|
||||
fp = ROOT / row["clean_path"]
|
||||
if not fp.exists():
|
||||
raise ApiError(404, "NO_CLEAN", "干净页文件不在了")
|
||||
return ("png", fp.read_bytes())
|
||||
# TextIn 擦除出来的是 .jpg,别一律当 png 发
|
||||
return ("png" if fp.suffix.lower() == ".png" else "jpg", fp.read_bytes())
|
||||
|
||||
|
||||
@route("GET", r"/api/papers/(?P<pid>[^/]+)", auth="parent")
|
||||
@@ -476,11 +496,16 @@ class App(BaseHTTPRequestHandler):
|
||||
self.send_response(status)
|
||||
self.send_header("Content-Type", ctype)
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.send_header("Access-Control-Allow-Origin", "*")
|
||||
self.send_header("Access-Control-Allow-Headers", "Content-Type, Authorization")
|
||||
self.send_header("Access-Control-Allow-Methods", "GET, POST, PATCH, DELETE, OPTIONS")
|
||||
# 让 file:// 打开的原型也能访问本机服务(Chrome 的 Private Network Access)
|
||||
self.send_header("Access-Control-Allow-Private-Network", "true")
|
||||
# 开发默认 *(file:// 打开的原型要能访问本机服务);生产默认不发这个头,
|
||||
# 需要跨域就把域名写进 QINGLING_CORS。
|
||||
if CORS_ORIGINS:
|
||||
origin = self.headers.get("Origin") or ""
|
||||
if "*" in CORS_ORIGINS or origin in CORS_ORIGINS:
|
||||
self.send_header("Access-Control-Allow-Origin", "*" if "*" in CORS_ORIGINS else origin)
|
||||
self.send_header("Access-Control-Allow-Headers", "Content-Type, Authorization")
|
||||
self.send_header("Access-Control-Allow-Methods", "GET, POST, PATCH, DELETE, OPTIONS")
|
||||
# 让 file:// 打开的原型也能访问本机服务(Chrome 的 Private Network Access)
|
||||
self.send_header("Access-Control-Allow-Private-Network", "true")
|
||||
for k, v in (extra or {}).items():
|
||||
self.send_header(k, v)
|
||||
self.end_headers()
|
||||
@@ -491,7 +516,15 @@ class App(BaseHTTPRequestHandler):
|
||||
self._send(status, body, "application/json; charset=utf-8")
|
||||
|
||||
def _read_body(self) -> tuple[dict, bytes]:
|
||||
n = int(self.headers.get("Content-Length") or 0)
|
||||
try:
|
||||
n = int(self.headers.get("Content-Length") or 0)
|
||||
except (TypeError, ValueError):
|
||||
raise ApiError(400, "BAD_LENGTH", "Content-Length 不是数字")
|
||||
if n < 0:
|
||||
raise ApiError(400, "BAD_LENGTH", "Content-Length 不能是负数")
|
||||
if n > MAX_BODY:
|
||||
# 直连 8000 时没有 Caddy 的 16MB 兜底,这里自己拦一道
|
||||
raise ApiError(413, "BODY_TOO_LARGE", f"请求体太大了(上限 {MAX_BODY // (1024 * 1024)}MB)")
|
||||
raw = self.rfile.read(n) if n else b""
|
||||
if not raw:
|
||||
return {}, raw
|
||||
@@ -601,6 +634,8 @@ class App(BaseHTTPRequestHandler):
|
||||
{"Cache-Control": "no-store"})
|
||||
if isinstance(result, tuple) and result and result[0] == "png":
|
||||
return self._send(200, result[1], "image/png", {"Cache-Control": "no-store"})
|
||||
if isinstance(result, tuple) and result and result[0] == "jpg":
|
||||
return self._send(200, result[1], "image/jpeg", {"Cache-Control": "no-store"})
|
||||
if isinstance(result, tuple) and result and result[0] == "csv":
|
||||
name = result[2] if len(result) > 2 else "export.csv"
|
||||
return self._send(200, ("\ufeff" + result[1]).encode("utf-8"),
|
||||
@@ -614,7 +649,9 @@ class App(BaseHTTPRequestHandler):
|
||||
pass
|
||||
except Exception as e: # noqa: BLE001
|
||||
traceback.print_exc()
|
||||
self._json(500, {"ok": False, "error": {"code": "INTERNAL", "message": str(e)}})
|
||||
# 生产环境不把异常原文回给前端(会带出 SQL 和路径)
|
||||
msg = "服务器内部错误,稍后再试" if PROD else str(e)
|
||||
self._json(500, {"ok": False, "error": {"code": "INTERNAL", "message": msg}})
|
||||
finally:
|
||||
try:
|
||||
conn.close()
|
||||
|
||||
Reference in New Issue
Block a user