fix: 缺陷审计批次(231 例)+ 复核补钉(①–⑦)
一、审计修复(另一侧完成,我复核通过) - 认证/限流:_client_ip 归一、限流统一走 rate_limit._SlidingTable(超限只淘汰最旧 key, 不再整表 clear 自毁)、每用户会话上限 10 + 过期清理 - 邮件验证码:锁内原子占位 → 锁外发信 → 成功落码,失败回滚冷却(并发不再双发) - 租赁:rentals 部分唯一索引(同 order_id 只允许一行 expired=0,迁移前先查重)、 开锁幂等落库、Timer 代号机制(取消/重排同临界区)、minutes=null 兜底、 自动还车 30s×6 → 1m/2m/5m/10m 退避 - 安全:ring 四接口登录 + 任务归属校验(Bearer 或 ?token=,校验 sessions 表)、 共享还车坐标不再伪造、代开锁 IntegrityError 兜底、token 配置原子写(fsync + 0600) - 入口鉴权:8 个历史/分析接口未登录 401(HTTP 与 rtn_code 同时给)、 analysis.html 带 Bearer + 未登录门 + 截断提示、历史查询 LIMIT 60000 并回传 truncated - UX 四个 P0:计时条出现、真实单走 /api/order/return 而 reminder 走 /api/rental/return、 定位失败不伪造坐标(三选一弹窗)、地图/配置/脚本失败统一落到可自救失败卡片 - 测试:新增 6 个文件 62 例;既有 test_history_30d 只补登录前置 二、我复核时发现并修掉的 7 处 ① email_verify.record_cooldown 的 expires 写成 now,会被 send_code 开头的 _cleanup_locked 整条删掉 —— 任何人发一次验证码就废掉「未注册邮箱」的冷却, 找回密码又能枚举邮箱是否注册。改为活过冷却窗口,并补 3 例测试 ② timer.py 两处落库(自动续租 INSERT、sync 复活 UPDATE)没防新唯一索引: 撞索引抛 IntegrityError 会让巡检线程退出,该单从此没有计时器/自动还车(上游还在计费)。 新增 _active_rental_id_for_order(),捕获后复用存活行 ③ (0,0) 当合法坐标会先发给上游:/record/return 不校验范围,宽松后端会把车"还"在海里。 新增 _coords_usable(),不可用就跳过原始点;候选列表永远丢掉第 0 项 ④ boot_smoke.py 按旧契约要求 200,加鉴权后永远失败 → HTTPError 401 视为「未登录,预期」 ⑤ 自动还车「不放弃」缺绝对上限:加 AUTO_RETURN_GIVE_UP_SECONDS=6h,到点只告警一次并停手 ⑥ 索引谓词 aligned 到查重口径:COALESCE(expired,0)=0,旧定义自动重建 ⑦ 访问日志脱敏:?token= / ?ticket= / ?access_token= 的值替换为 ***(werkzeug + root logger) 否则容器日志里就是明文会话令牌 配套改写 tests/test_rental_dedup.py::test_return_accepts_zero_coordinates → test_return_treats_zero_coordinates_as_missing(原断言把 (0,0) 当合法值发上游) 三、验证 - python -m pytest -q → 234 passed(基线 231,净增 3) - node 5 套 → 44 pass / 0 fail - 14 个 .py ast.parse、node --check dist/app.js → 全部通过 - boot_smoke.py → exit=0;未登录 /api/history/stats、/api/analysis/overview、 /api/ring_progress/* 实测 401,/api/config 200 - 行为级:传 (0,0) 时上游只收到候选点;合法坐标仍先发上报值;唯一索引拦住重复插入
This commit is contained in:
+188
-18
@@ -24,6 +24,106 @@ BATCH_RING_ALLOWED_EMAILS = {"3146527494@qq.com"}
|
||||
ring_tasks: dict = {}
|
||||
_ring_lock = threading.Lock()
|
||||
|
||||
# 首页静态资源版本号的进程内缓存(BUG-21):只有签名变化才重算 sha256
|
||||
_map_asset_version_lock = threading.Lock()
|
||||
_map_asset_version_cache = {"signature": None, "version": None}
|
||||
|
||||
# 寻车任务生命周期:已完成/失败的任务保留 30 分钟后删除,字典另有硬上限。
|
||||
# 之前只有显式 /api/ring_status_clear 才 pop,前端不调就永久驻留(每条含
|
||||
# 车辆列表与统计),随使用次数线性增长(BUG-20)。
|
||||
RING_TASK_TTL_SECONDS = 30 * 60 # 已结束任务的保留时间
|
||||
RING_TASK_CLEANUP_INTERVAL = 60 # 清理最小间隔:不是每个请求都扫全表
|
||||
RING_TASK_MAX_TASKS = 2000 # 容量硬上限
|
||||
_RING_FINISHED_STATUS = ("completed", "cancelled", "failed")
|
||||
|
||||
_ring_last_cleanup = 0.0
|
||||
|
||||
|
||||
def _ring_cleanup_locked(now=None, force=False):
|
||||
"""清理过期/超额任务(调用方必须持有 _ring_lock)。
|
||||
|
||||
- 已完成/失败任务超过 RING_TASK_TTL_SECONDS 删除;运行中的任务不动,
|
||||
否则正在看进度页的 SSE 会莫名收到「任务不存在」。
|
||||
- 清理按 RING_TASK_CLEANUP_INTERVAL 节流,避免每个请求都全表扫。
|
||||
- 达到容量上限时按创建时间淘汰最老的已结束任务。
|
||||
"""
|
||||
global _ring_last_cleanup
|
||||
now = time.time() if now is None else now
|
||||
over_capacity = len(ring_tasks) >= RING_TASK_MAX_TASKS
|
||||
if not force and not over_capacity and \
|
||||
now - _ring_last_cleanup < RING_TASK_CLEANUP_INTERVAL:
|
||||
return
|
||||
_ring_last_cleanup = now
|
||||
for tid, task in list(ring_tasks.items()):
|
||||
if task.get("status") not in _RING_FINISHED_STATUS:
|
||||
continue
|
||||
ended = float(task.get("last_update") or task.get("created_at") or now)
|
||||
if now - ended >= RING_TASK_TTL_SECONDS:
|
||||
ring_tasks.pop(tid, None)
|
||||
if len(ring_tasks) < RING_TASK_MAX_TASKS:
|
||||
return
|
||||
for tid, task in sorted(ring_tasks.items(),
|
||||
key=lambda kv: float(kv[1].get("created_at") or 0)):
|
||||
if len(ring_tasks) < RING_TASK_MAX_TASKS:
|
||||
break
|
||||
if task.get("status") in _RING_FINISHED_STATUS:
|
||||
ring_tasks.pop(tid, None)
|
||||
|
||||
|
||||
def _ring_task_get(task_id):
|
||||
"""取任务快照,并顺手做一次节流清理(顺带保证过期任务读不到)。"""
|
||||
with _ring_lock:
|
||||
_ring_cleanup_locked()
|
||||
task = ring_tasks.get(task_id)
|
||||
return dict(task) if task else None
|
||||
|
||||
|
||||
def _query_token():
|
||||
"""URL 里的会话 token:`?token=<token>`(EventSource / 新窗口带不了 header)。"""
|
||||
return (request.args.get("token") or "").strip()
|
||||
|
||||
|
||||
def _user_from_request():
|
||||
"""寻车任务鉴权:同时接受 `Authorization: Bearer <token>` 与 `?token=<token>`。
|
||||
|
||||
/ring_progress.html 用 EventSource(浏览器不给带 header)、取消按钮在新窗口
|
||||
打开(同样拿不到前端内存里的 header),所以两个入口都走查询参数。
|
||||
token 出现在 URL 里,因此相关页面/接口统一加 no-store + no-referrer。
|
||||
"""
|
||||
user = get_current_user()
|
||||
if user:
|
||||
return user
|
||||
token = _query_token()
|
||||
if not token:
|
||||
return None
|
||||
conn = get_db()
|
||||
try:
|
||||
row = conn.execute("""
|
||||
SELECT users.id, users.email FROM sessions
|
||||
JOIN users ON sessions.user_id = users.id
|
||||
WHERE sessions.token = ? AND sessions.expires_at > datetime('now', '+8 hours')
|
||||
""", (token,)).fetchone()
|
||||
except Exception as exc:
|
||||
print(f"[寻车] 校验 token 失败: {exc}")
|
||||
row = None
|
||||
finally:
|
||||
conn.close()
|
||||
return dict(row) if row else None
|
||||
|
||||
|
||||
def _ring_owner_guard(task_id, user):
|
||||
"""校验任务归属;返回 (task, error_response)。
|
||||
|
||||
任务里记 owner_user_id,只能操作自己创建的任务,否则任何人都能拿 8 位
|
||||
task_id 读进度、取消别人的任务(BUG-20)。
|
||||
"""
|
||||
task = _ring_task_get(task_id)
|
||||
if not task:
|
||||
return None, (jsonify({"rtn_code": 404, "message": "任务不存在或已过期"}), 404)
|
||||
if task.get("owner_user_id") != user["id"]:
|
||||
return None, (jsonify({"rtn_code": 403, "message": "无权操作他人的寻车任务"}), 403)
|
||||
return task, None
|
||||
|
||||
|
||||
async def ring_single_bike_async(session, bike_code, school_id=10):
|
||||
try:
|
||||
@@ -107,8 +207,14 @@ def api_ring_all():
|
||||
"status": "running", "total": len(codes), "done": 0,
|
||||
"success": 0, "failed": 0, "bikes": [{"code": c} for c in codes],
|
||||
"cancelled": False, "created_at": time.time(), "last_update": time.time(),
|
||||
"owner_user_id": user["id"],
|
||||
}
|
||||
with _ring_lock:
|
||||
_ring_cleanup_locked()
|
||||
if len(ring_tasks) >= RING_TASK_MAX_TASKS:
|
||||
# 清理后仍然满:拒绝新建,而不是让字典无限涨
|
||||
return jsonify({"rtn_code": 429,
|
||||
"message": "寻车任务过多,请稍后再试"}), 429
|
||||
ring_tasks[task_id] = task
|
||||
t = threading.Thread(target=run_ring_task, args=(task_id,), daemon=True)
|
||||
t.start()
|
||||
@@ -118,20 +224,28 @@ def api_ring_all():
|
||||
|
||||
@bp.route("/api/ring_status/<task_id>")
|
||||
def api_ring_status(task_id):
|
||||
with _ring_lock:
|
||||
task = ring_tasks.get(task_id)
|
||||
if not task:
|
||||
return jsonify({"rtn_code": 404, "message": "任务不存在"})
|
||||
return jsonify({"rtn_code": 0, "status": task["status"], "total": task["total"],
|
||||
"done": task["done"], "success": task["success"], "failed": task["failed"]})
|
||||
user = _user_from_request()
|
||||
if not user:
|
||||
return jsonify({"rtn_code": 401, "message": "请先登录"}), 401
|
||||
task, error = _ring_owner_guard(task_id, user)
|
||||
if error:
|
||||
return error
|
||||
return jsonify({"rtn_code": 0, "status": task["status"], "total": task["total"],
|
||||
"done": task["done"], "success": task["success"], "failed": task["failed"]})
|
||||
|
||||
|
||||
@bp.route("/api/ring_cancel/<task_id>", methods=["POST"])
|
||||
def api_ring_cancel(task_id):
|
||||
user = _user_from_request()
|
||||
if not user:
|
||||
return jsonify({"rtn_code": 401, "message": "请先登录"}), 401
|
||||
with _ring_lock:
|
||||
_ring_cleanup_locked()
|
||||
task = ring_tasks.get(task_id)
|
||||
if not task:
|
||||
return jsonify({"rtn_code": 404, "message": "任务不存在"})
|
||||
return jsonify({"rtn_code": 404, "message": "任务不存在或已过期"}), 404
|
||||
if task.get("owner_user_id") != user["id"]:
|
||||
return jsonify({"rtn_code": 403, "message": "无权操作他人的寻车任务"}), 403
|
||||
if task["status"] != "running":
|
||||
return jsonify({"rtn_code": 400, "message": f"任务已是 {task['status']} 状态"})
|
||||
task["cancelled"] = True
|
||||
@@ -145,6 +259,13 @@ def api_ring_progress(task_id):
|
||||
global ring_tasks
|
||||
RING_SSE_MAX_SECONDS = 180 # 单个进度 SSE 最长占用时间
|
||||
|
||||
user = _user_from_request()
|
||||
if not user:
|
||||
return jsonify({"rtn_code": 401, "message": "请先登录"}), 401
|
||||
task, error = _ring_owner_guard(task_id, user)
|
||||
if error:
|
||||
return error
|
||||
|
||||
def _sse(obj):
|
||||
return f"data: {json.dumps(obj, ensure_ascii=False)}\n\n"
|
||||
|
||||
@@ -161,12 +282,13 @@ def api_ring_progress(task_id):
|
||||
return
|
||||
with _ring_lock:
|
||||
task = ring_tasks.get(task_id)
|
||||
if not task:
|
||||
snapshot = dict(task) if task else None
|
||||
if not snapshot:
|
||||
# 任务不存在(如服务重启/多进程不共享)——向前端发明确错误而非静默断开
|
||||
yield _sse({"type": "error", "message": "任务不存在或已结束"})
|
||||
return
|
||||
done = task["done"]
|
||||
status = task["status"]
|
||||
done = snapshot["done"]
|
||||
status = snapshot["status"]
|
||||
if done != last_done or status != last_status:
|
||||
last_done = done
|
||||
last_status = status
|
||||
@@ -174,9 +296,9 @@ def api_ring_progress(task_id):
|
||||
"type": "progress",
|
||||
"status": status,
|
||||
"done": done,
|
||||
"total": task["total"],
|
||||
"success": task["success"],
|
||||
"failed": task["failed"],
|
||||
"total": snapshot["total"],
|
||||
"success": snapshot["success"],
|
||||
"failed": snapshot["failed"],
|
||||
})
|
||||
if status in ("completed", "cancelled"):
|
||||
# 已结束,补发一条 done 事件后关闭
|
||||
@@ -191,16 +313,25 @@ def api_ring_progress(task_id):
|
||||
generate(),
|
||||
mimetype="text/event-stream",
|
||||
headers={
|
||||
"Cache-Control": "no-cache",
|
||||
"Cache-Control": "no-store",
|
||||
"Connection": "keep-alive",
|
||||
"X-Accel-Buffering": "no",
|
||||
"Referrer-Policy": "no-referrer",
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
@bp.route("/api/ring_status_clear/<task_id>", methods=["POST"])
|
||||
def api_ring_status_clear(task_id):
|
||||
user = _user_from_request()
|
||||
if not user:
|
||||
return jsonify({"rtn_code": 401, "message": "请先登录"}), 401
|
||||
with _ring_lock:
|
||||
task = ring_tasks.get(task_id)
|
||||
if not task:
|
||||
return jsonify({"rtn_code": 0, "message": "已清除"})
|
||||
if task.get("owner_user_id") != user["id"]:
|
||||
return jsonify({"rtn_code": 403, "message": "无权操作他人的寻车任务"}), 403
|
||||
ring_tasks.pop(task_id, None)
|
||||
return jsonify({"rtn_code": 0, "message": "已清除"})
|
||||
|
||||
@@ -268,8 +399,9 @@ def api_find_bike():
|
||||
|
||||
@bp.route("/api/config")
|
||||
def api_config():
|
||||
from campus import CAMPUS_CENTER_LAT, CAMPUS_CENTER_LNG
|
||||
return jsonify({
|
||||
"center_lat": 36.531820, "center_lng": 116.780180,
|
||||
"center_lat": CAMPUS_CENTER_LAT, "center_lng": CAMPUS_CENTER_LNG,
|
||||
"scale": 17, "school_name": "山东管理学院",
|
||||
"type_names": {"1": "单车", "3": "电动车", "6": "助力车"},
|
||||
})
|
||||
@@ -464,8 +596,37 @@ MAP_ASSETS = (
|
||||
)
|
||||
|
||||
|
||||
def _map_asset_signature():
|
||||
"""静态资源的 (绝对路径, mtime_ns, size) 签名:任一文件被改就变。
|
||||
|
||||
只做 stat,不读内容 —— 用它判断进程内缓存是否还能用。
|
||||
"""
|
||||
root = Path(current_app.static_folder)
|
||||
signature = []
|
||||
for filename in MAP_ASSETS:
|
||||
path = root / filename
|
||||
try:
|
||||
info = path.stat()
|
||||
signature.append((str(path), info.st_mtime_ns, info.st_size))
|
||||
except OSError:
|
||||
signature.append((str(path), None, None))
|
||||
return tuple(signature)
|
||||
|
||||
|
||||
def _map_asset_version():
|
||||
"""Version the complete map bundle so deployments cannot reuse old dependencies."""
|
||||
"""Version the complete map bundle so deployments cannot reuse old dependencies.
|
||||
|
||||
首页每次请求都要这个版本号,而它要读完约 420KB 静态资源再 sha256(BUG-21)。
|
||||
这里按 (路径, mtime, size) 做进程内缓存:文件没动就直接返回上次的结果,
|
||||
文件一改(含部署覆盖、`touch`)签名就变,立刻重算,不会长期缓存旧 hash。
|
||||
参与版本号的资源必须是页面真正引用的那一套(MAP_ASSETS),不要再抽掉什么
|
||||
—— 少算一个文件就等于那个文件改了但浏览器仍用旧缓存。
|
||||
"""
|
||||
signature = _map_asset_signature()
|
||||
with _map_asset_version_lock:
|
||||
if _map_asset_version_cache["signature"] == signature \
|
||||
and _map_asset_version_cache["version"]:
|
||||
return _map_asset_version_cache["version"]
|
||||
digest = hashlib.sha256()
|
||||
for filename in MAP_ASSETS:
|
||||
digest.update(filename.encode())
|
||||
@@ -473,7 +634,11 @@ def _map_asset_version():
|
||||
digest.update((Path(current_app.static_folder) / filename).read_bytes())
|
||||
except FileNotFoundError:
|
||||
digest.update(b"missing")
|
||||
return digest.hexdigest()[:16]
|
||||
version = digest.hexdigest()[:16]
|
||||
with _map_asset_version_lock:
|
||||
_map_asset_version_cache["signature"] = signature
|
||||
_map_asset_version_cache["version"] = version
|
||||
return version
|
||||
|
||||
|
||||
@bp.route("/")
|
||||
@@ -490,4 +655,9 @@ def analysis_page():
|
||||
|
||||
@bp.route("/ring_progress.html")
|
||||
def ring_progress():
|
||||
return render_template("ring_progress.html")
|
||||
# 进度页把会话 token 放在 URL 查询参数里,别让浏览器缓存页面或把带 token
|
||||
# 的地址通过 Referer 带给第三方(页面内的地图/CDN 请求)。
|
||||
response = current_app.make_response(render_template("ring_progress.html"))
|
||||
response.headers["Cache-Control"] = "no-store"
|
||||
response.headers["Referrer-Policy"] = "no-referrer"
|
||||
return response
|
||||
|
||||
Reference in New Issue
Block a user