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:
zzy
2026-11-17 09:58:16 +08:00
parent 7a5840e0c3
commit f34ed304bc
59 changed files with 6487 additions and 802 deletions
+222 -57
View File
@@ -21,26 +21,70 @@ from rental_mail import get_rental_mail_context, resolve_return_token
bp = Blueprint("rental", __name__)
_email_return_locks = {}
_email_return_locks_guard = threading.Lock()
_order_return_locks = {}
_order_return_locks_guard = threading.Lock()
# 按 key 复用的「串行锁」表:key 来自客户端(order_id / rental_id),不能无界增长。
# 老的写法是 setdefault(...) 之后永不释放 —— 登录用户每次换个 order_id 就在进程里
# 留一个 Lock(BUG-11)。这里加上限 + TTL,并且只淘汰「当前没人持有」的锁。
_LOCK_REGISTRY_MAX = 256
_LOCK_REGISTRY_TTL = 3600 # 1 小时没用过就允许回收
class _LockRegistry:
"""带上限与 TTL 的按 key 锁表(返回的锁可放心 with 使用)。"""
def __init__(self, max_entries: int = _LOCK_REGISTRY_MAX,
ttl_seconds: int = _LOCK_REGISTRY_TTL):
self._guard = threading.Lock()
self._max_entries = max(1, int(max_entries))
self._ttl = max(1, int(ttl_seconds))
self._items = {} # key -> [lock, last_used_ts]
def get(self, key):
now = time.time()
with self._guard:
entry = self._items.get(key)
if entry is not None:
entry[1] = now
return entry[0]
self._evict_locked(now)
lock = threading.Lock()
self._items[key] = [lock, now]
return lock
def _evict_locked(self, now: float):
"""仅在接近上限时清理:先按 TTL,再按最久未用,且跳过正被持有的锁。"""
if len(self._items) < self._max_entries:
return
for key in [k for k, (lock, ts) in self._items.items()
if not lock.locked() and now - ts > self._ttl]:
self._items.pop(key, None)
if len(self._items) < self._max_entries:
return
idle = sorted(
((k, v) for k, v in self._items.items() if not v[0].locked()),
key=lambda kv: kv[1][1])
for key, _entry in idle[:max(1, len(idle) // 4)]:
self._items.pop(key, None)
def __len__(self):
return len(self._items)
_email_return_locks = _LockRegistry()
_order_return_locks = _LockRegistry()
def _email_return_lock(rental_id: int):
with _email_return_locks_guard:
return _email_return_locks.setdefault(rental_id, threading.Lock())
return _email_return_locks.get(rental_id)
def _serialize_order_return(func):
"""同一订单的重复还车请求串行执行,避免重复调用上游锁车接口。"""
@wraps(func)
def wrapped(*args, **kwargs):
# 只在这里取一次 key(请求体由视图自己再解析一次,Flask 会缓存已解析的 JSON)
data = request.get_json(silent=True) or {}
key = str(data.get("order_id") or "missing")
with _order_return_locks_guard:
lock = _order_return_locks.setdefault(key, threading.Lock())
with lock:
with _order_return_locks.get(key):
return func(*args, **kwargs)
return wrapped
@@ -280,26 +324,55 @@ def _distinct_points(points, min_gap_m=12.0):
return out
_COORD_EPS = 0.01 # 纬度、经度都小于这个值时就当"没有有效坐标"
def _coords_usable(lat, lng) -> bool:
"""这个坐标能不能直接发给上游。
(0,0) 是「前端把 undefined 序列化成 0」的典型产物:我们服务的场景永远不在
几内亚湾,而上游 `/record/return` 并不校验位置范围 —— 宽松实现会把 (0,0)
当合法位置接受,于是车"还"在了海里,后台起点→终点那一列直接变成大西洋坐标。
"""
if lat is None or lng is None:
return False
try:
lat_f, lng_f = float(lat), float(lng)
except (TypeError, ValueError):
return False
if not math.isfinite(lat_f) or not math.isfinite(lng_f):
return False
return not (abs(lat_f) < _COORD_EPS and abs(lng_f) < _COORD_EPS)
def _try_return_candidates(user_id, order_id, code, lat, lng):
"""按「先原坐标,失败再算候选点」的顺序调 `/record/return`。
返回 (结果, 用到的点, 试过的点描述列表)。候选点要等真的失败才算,
否则每次还车都白白多打一次 `/project/map`。
"""
tried = ["你上报的位置"]
result = request_with_user_auth(
user_id, "POST", "/record/return",
data={"order_id": order_id, "longitude": lng, "latitude": lat, "code": code}
)
if result.get("rtn_code") == 0:
return result, (lat, lng), tried
# 「订单信息不存在」换坐标也没用,直接收工
if (result.get("rtn_code") == 204010
or "订单信息不存在" in str(result.get("message") or "")):
return result, (lat, lng), tried
raw_ok = _coords_usable(lat, lng)
tried = ["你上报的位置"] if raw_ok else []
last_result = None
if raw_ok:
result = request_with_user_auth(
user_id, "POST", "/record/return",
data={"order_id": order_id, "longitude": lng, "latitude": lat, "code": code}
)
if result.get("rtn_code") == 0:
return result, (lat, lng), tried
# 「订单信息不存在」换坐标也没用,直接收工
if (result.get("rtn_code") == 204010
or "订单信息不存在" in str(result.get("message") or "")):
return result, (lat, lng), tried
last_result = result
else:
print(f"[还车位置] 上报坐标不可用(lat={lat}, lng={lng}),跳过原始点直接算候选")
last_result = result
for plat, plng, label in _return_candidates(lat, lng, user_id)[1:]:
# _return_candidates 的第 0 项永远是「你上报的位置」,不管上面有没有真发过,
# 都不能再拿它当候选点(否则 (0,0) 会绕过判断,从这个口子又发出去)。
candidates = _return_candidates(lat, lng, user_id)[1:]
for plat, plng, label in candidates:
tried.append(label)
result = request_with_user_auth(
user_id, "POST", "/record/return",
@@ -313,6 +386,8 @@ def _try_return_candidates(user_id, order_id, code, lat, lng):
or "订单信息不存在" in str(result.get("message") or "")):
return result, (plat, plng), tried
print(f"[还车位置] 候选点 {label} 失败: {result.get('message')}")
if last_result is None:
last_result = {"rtn_code": -1, "message": "没有可用的还车位置"}
return last_result, (lat, lng), tried
@@ -579,6 +654,77 @@ def _record_rental_end(order_id: str, user_id: int, latitude, longitude):
conn.close()
def _find_active_rental_id(conn, order_id):
"""该上游订单号是否已有「未结束」的本地记录;有就返回其 rental_id。
同一张单被重复开锁(客户端双击/网关重试/上游复用同一 order_id)时必须复用它,
否则会插出两行 rentals + 两套计时器(BUG-03:重复提醒邮件、重复自动还车、
订单历史轮次翻倍)。空 order_id(本地计时单)不参与判重。
"""
if order_id is None:
return None
key = str(order_id).strip()
if not key:
return None
row = conn.execute(
"SELECT id FROM rentals WHERE order_id = ? AND COALESCE(expired, 0) = 0 "
"ORDER BY id DESC LIMIT 1", (key,)).fetchone()
return int(row["id"]) if row else None
def _insert_unlock_rental(conn, *, order_id, code, email, user_id,
start_time, end_time, duration):
"""幂等落库一条开锁订单,返回 (rental_id, created)。
- 已有同 order_id 的未结束记录 → 直接复用,created=False;
- 没有 → 优先用 `id=order_id`(与历史行为一致,前端/邮件都用这个 id),
`id` 被占用(reminder/sync 自增行漂移)时退回自增 id,order_id 照旧记录;
- 唯一索引(db.py 的 idx_rentals_active_order)兜底:冲突时再复用一次,
绝不插第二行同一 order_id。
"""
existing = _find_active_rental_id(conn, order_id)
if existing is not None:
return existing, False
params_tail = (order_id, code, email, user_id, start_time, end_time, duration)
numeric_id = None
try:
numeric_id = int(order_id)
except (TypeError, ValueError):
numeric_id = None
if numeric_id is not None:
try:
conn.execute("""
INSERT INTO rentals (id, order_id, bike_code, email, user_id, start_time,
end_time, duration, expired, source)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, 0, 'unlock')
""", (numeric_id,) + params_tail)
return numeric_id, True
except sqlite3.IntegrityError:
existing = _find_active_rental_id(conn, order_id)
if existing is not None:
print(f"[开锁] order_id={order_id} 已存在未结束记录 rental_id={existing},复用")
return existing, False
print(f"[开锁] rentals.id={numeric_id} 已被占用,改用自增 id")
cur = None
try:
cur = conn.execute("""
INSERT INTO rentals (order_id, bike_code, email, user_id, start_time, end_time,
duration, expired, source)
VALUES (?, ?, ?, ?, ?, ?, ?, 0, 'unlock')
""", params_tail)
except sqlite3.IntegrityError:
# 并发下另一线程刚好插了同一 order_id(唯一索引挡住):再查一次并复用
existing = _find_active_rental_id(conn, order_id)
if existing is not None:
print(f"[开锁] order_id={order_id} 并发重复,复用 rental_id={existing}")
return existing, False
raise
return int(cur.lastrowid), True
# ========== 订单路由(原样复制自 app.py.bak) ==========
@bp.route("/api/order/unlock", methods=["POST"])
@@ -669,45 +815,61 @@ def order_unlock():
now_beijing = dt.datetime.now(tz)
duration = get_user_rental_settings(user["id"])["rental_duration_minutes"]
end_time = now_beijing + dt.timedelta(minutes=duration)
start_str = now_beijing.strftime("%Y-%m-%d %H:%M:%S")
end_str = end_time.strftime("%Y-%m-%d %H:%M:%S")
conn = get_db()
cursor = conn.cursor()
try:
cursor.execute("""
INSERT INTO rentals (id, order_id, bike_code, email, user_id, start_time, end_time,
duration, expired, source)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, 0, 'unlock')
""", (int(order_id), order_id, code, user["email"], user["id"],
now_beijing.strftime("%Y-%m-%d %H:%M:%S"),
end_time.strftime("%Y-%m-%d %H:%M:%S"), duration))
rental_row_id = int(order_id)
except sqlite3.IntegrityError:
# rentals.id 可能被 reminder/sync 的自增行占用(序列漂移):改用自增 id,
# order_id 仍记录真实上游单号。用 lastrowid 当 rental_id,别把计时器挂到别人单上。
print(f"[开锁] rentals.id={order_id} 已被占用,改用自增 id")
cur2 = conn.execute("""
INSERT INTO rentals (order_id, bike_code, email, user_id, start_time, end_time,
duration, expired, source)
VALUES (?, ?, ?, ?, ?, ?, ?, 0, 'unlock')
""", (order_id, code, user["email"], user["id"],
now_beijing.strftime("%Y-%m-%d %H:%M:%S"),
end_time.strftime("%Y-%m-%d %H:%M:%S"), duration))
rental_row_id = cur2.lastrowid
conn.commit()
conn.close()
rental_row_id, created = _insert_unlock_rental(
conn, order_id=order_id, code=code, email=user["email"],
user_id=user["id"], start_time=start_str, end_time=end_str,
duration=duration)
conn.commit()
finally:
conn.close()
if created:
start_rental_timer(rental_id=int(rental_row_id), email=user["email"],
bike_code=code, duration_minutes=duration, user_id=user["id"])
_record_rental_start(int(rental_row_id), latitude, longitude)
else:
# 同一张单被重复开锁(双击/重放):复用已有行,不新建记录、不重挂计时器,
# 只把剩余时长按库里真实的 end_time 重排一次(幂等,不会叠加提醒)。
print(f"[开锁] order_id={order_id} 已有未结束记录 rental_id={rental_row_id},复用不新建")
try:
conn = get_db()
try:
row = conn.execute(
"SELECT end_time FROM rentals WHERE id = ?", (int(rental_row_id),)).fetchone()
finally:
conn.close()
remaining = _get_remaining_seconds(dict(row)) if row else 0
except Exception as exc:
print(f"[开锁] 复用记录读取剩余时长失败: {exc}")
remaining = 0
if remaining > 0:
start_rental_timer(rental_id=int(rental_row_id), email=user["email"],
bike_code=code, duration_minutes=remaining / 60,
user_id=user["id"])
start_rental_timer(rental_id=int(rental_row_id), email=user["email"],
bike_code=code, duration_minutes=duration, user_id=user["id"])
_record_rental_start(int(rental_row_id), latitude, longitude)
# 带上轮次预估:前端租车条要显示「共N轮 · 预计HH:MM还车」
row = get_db().execute(
"SELECT renewal_round, rounds_override, end_time FROM rentals WHERE id = ?",
(int(rental_row_id),)).fetchone()
conn = get_db()
try:
row = conn.execute(
"SELECT renewal_round, rounds_override, end_time FROM rentals WHERE id = ?",
(int(rental_row_id),)).fetchone()
finally:
conn.close()
summary = _rounds_summary(
dict(row) if row else {"order_id": str(order_id),
"end_time": end_time.strftime("%Y-%m-%d %H:%M:%S")},
"end_time": end_str},
user["id"])
return jsonify({"rtn_code": 0, "message": "开锁成功", "order_id": order_id,
"data": {**summary, "remaining": duration * 60}})
response = {"rtn_code": 0, "message": "开锁成功", "order_id": order_id,
"data": {**summary, "remaining": duration * 60}}
if not created:
response["message"] = "该订单已在计时中(已复用原订单,不会重复计时)"
response["reused"] = True
return jsonify(response)
else:
from wechat import friendly_upstream_message
raw_open_msg = open_result.get("message", "")
@@ -830,7 +992,9 @@ def order_return():
if not order_id:
return jsonify({"rtn_code": 400, "message": "缺少订单ID"})
if not latitude or not longitude:
# 显式判 None:0.0 是合法坐标(赤道/本初子午线;前端把 undefined 序列化成 0 时
# 也应当由上游/停车区判定去拒绝,而不是在这里被当成"没传")。
if latitude is None or longitude is None or latitude == "" or longitude == "":
return jsonify({"rtn_code": 400, "message": "缺少位置信息"})
conn = get_db()
@@ -1094,9 +1258,10 @@ def order_pay_with_card():
@bp.route("/api/rental/start", methods=["POST"])
def rental_start():
"""开始用车计时"""
print(f"[rental/start] Headers: {dict(request.headers)}")
# 注意:这里**不要**再打印 request.headers / user —— 请求头里带着
# `Authorization: Bearer <会话 token>`,打日志等于把 30 天有效的登录凭据写进
# stdout、journald、docker logs(BUG-05)。排障请用 request.path 与响应码。
user = get_current_user()
print(f"[rental/start] User: {user}")
if not user:
return jsonify({"rtn_code": 401, "message": "请先登录"})