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:
+111
-12
@@ -15,7 +15,12 @@ from wechat import request_with_user_auth
|
||||
|
||||
bp = Blueprint("share", __name__)
|
||||
|
||||
_shared_return_locks = {}
|
||||
# 同一共享订单的还车请求串行化。key 来自请求体(客户端可控),所以这张表必须
|
||||
# 有 TTL 与容量上限:老写法 setdefault 后永不 release,登录用户每次换一个
|
||||
# order_id 就能在进程里留一把常驻锁(BUG-11)。
|
||||
SHARE_LOCK_TTL_SECONDS = 600 # 空闲锁的保留时间
|
||||
SHARE_LOCK_MAX_ENTRIES = 512 # 硬容量上限
|
||||
_shared_return_locks = {} # key -> {"lock", "last_used", "holders"}
|
||||
_shared_return_locks_guard = threading.Lock()
|
||||
|
||||
DEFAULT_DAILY_LIMIT = 3
|
||||
@@ -23,6 +28,43 @@ DEFAULT_REQUIRE_CARD = 1
|
||||
DEFAULT_CARD_MIN_TIMES = 1
|
||||
|
||||
|
||||
def _prune_share_locks_locked(now):
|
||||
"""回收空闲超过 TTL 的锁(调用方必须持有 _shared_return_locks_guard)。"""
|
||||
for key, entry in list(_shared_return_locks.items()):
|
||||
if entry["holders"]:
|
||||
continue
|
||||
if now - entry["last_used"] >= SHARE_LOCK_TTL_SECONDS:
|
||||
_shared_return_locks.pop(key, None)
|
||||
|
||||
|
||||
def _acquire_share_lock(key):
|
||||
"""取(或建)该 key 的锁并登记占用;建不出来时返回 None(调用方按无锁执行)。"""
|
||||
now = time.time()
|
||||
with _shared_return_locks_guard:
|
||||
_prune_share_locks_locked(now)
|
||||
entry = _shared_return_locks.get(key)
|
||||
if entry is None:
|
||||
if len(_shared_return_locks) >= SHARE_LOCK_MAX_ENTRIES:
|
||||
# 到上限:淘汰最久未用且没人持有的锁。都在用时宁可退化成无锁,
|
||||
# 也不能让字典无限涨(无锁最多退化成并发重复还车,内存涨是永久的)。
|
||||
idle = [(k, e) for k, e in _shared_return_locks.items() if not e["holders"]]
|
||||
if not idle:
|
||||
return None
|
||||
oldest_key = min(idle, key=lambda kv: kv[1]["last_used"])[0]
|
||||
_shared_return_locks.pop(oldest_key, None)
|
||||
entry = {"lock": threading.Lock(), "last_used": now, "holders": 0}
|
||||
_shared_return_locks[key] = entry
|
||||
entry["holders"] += 1
|
||||
entry["last_used"] = now
|
||||
return entry
|
||||
|
||||
|
||||
def _release_share_lock(entry):
|
||||
with _shared_return_locks_guard:
|
||||
entry["holders"] = max(0, entry["holders"] - 1)
|
||||
entry["last_used"] = time.time()
|
||||
|
||||
|
||||
def _partner_display(share_or_none, fallback_email):
|
||||
return (share_or_none or {}).get("owner_remark") or fallback_email
|
||||
|
||||
@@ -33,13 +75,57 @@ def _serialize_shared_return(func):
|
||||
def wrapped(*args, **kwargs):
|
||||
data = request.get_json(silent=True) or {}
|
||||
key = str(data.get("order_id") or data.get("rental_id") or "missing")
|
||||
with _shared_return_locks_guard:
|
||||
lock = _shared_return_locks.setdefault(key, threading.Lock())
|
||||
with lock:
|
||||
entry = _acquire_share_lock(key)
|
||||
if entry is None:
|
||||
# 锁表已满且没有可回收的空闲锁:退化为不加锁,绝不因此无限占内存
|
||||
return func(*args, **kwargs)
|
||||
with entry["lock"]:
|
||||
try:
|
||||
return func(*args, **kwargs)
|
||||
finally:
|
||||
_release_share_lock(entry)
|
||||
return wrapped
|
||||
|
||||
|
||||
def _last_bike_pos(bike_code):
|
||||
"""该车最近一次采集坐标(GCJ02)。拿不到返回 None,不编造。"""
|
||||
if not bike_code:
|
||||
return None
|
||||
try:
|
||||
from timer import _bike_pos_from_history
|
||||
return _bike_pos_from_history(bike_code)
|
||||
except Exception as exc:
|
||||
print(f"[共享] 查询 bike_history 失败: {exc}")
|
||||
return None
|
||||
|
||||
|
||||
def _campus_center():
|
||||
"""校园中心(GCJ02),来自 campus.py 的配置常量;未配置返回 None。"""
|
||||
try:
|
||||
from campus import campus_center
|
||||
return campus_center()
|
||||
except Exception as exc:
|
||||
print(f"[共享] 读取校园中心失败: {exc}")
|
||||
return None
|
||||
|
||||
|
||||
def _fallback_coord(bike_code):
|
||||
"""坐标兜底链:该车最近采集点 → 校园中心;都没有返回 None。
|
||||
|
||||
绝不使用硬编码坐标:旧代码兜底的 (36.67, 116.98) 离校区约 20km,
|
||||
会把还车终点、位置标签和里程统计全部写坏(BUG-17)。
|
||||
"""
|
||||
return _last_bike_pos(bike_code) or _campus_center()
|
||||
|
||||
|
||||
def _has_coord(latitude, longitude) -> bool:
|
||||
"""显式判缺失:0.0 是合法坐标,不能用 `not latitude`。"""
|
||||
for value in (latitude, longitude):
|
||||
if value is None or value == "":
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def _beijing_now():
|
||||
tz = dt.timezone(dt.timedelta(hours=8))
|
||||
return dt.datetime.now(tz)
|
||||
@@ -723,16 +809,22 @@ def shared_unlock():
|
||||
return jsonify({"rtn_code": bike_result.get("rtn_code", 500),
|
||||
"message": bike_result.get("message", "获取车辆信息失败")})
|
||||
|
||||
# 用实时地图坐标(+抖动)作下单起点:优先 /project/map 抓该车当前坐标
|
||||
# 用实时地图坐标(+抖动)作下单起点:优先 /project/map 抓该车当前坐标,
|
||||
# 其次车辆详情自带的坐标,再次该车最近一次 bike_history / 校园中心。
|
||||
# 都拿不到就明确失败 —— 之前这里也写死了 (36.67, 116.98)(BUG-17 第二处)。
|
||||
from routes.rental import _fetch_live_bike_coord, _near_coord
|
||||
bd = bike_result.get("data") or {}
|
||||
live = _fetch_live_bike_coord(owner_user_id, code, bd.get("type"))
|
||||
if live:
|
||||
latitude, longitude = _near_coord(live[0], live[1])
|
||||
elif _has_coord(bd.get("latitude"), bd.get("longitude")):
|
||||
latitude, longitude = _near_coord(bd.get("latitude"), bd.get("longitude"))
|
||||
else:
|
||||
latitude, longitude = _near_coord(
|
||||
bd.get("latitude", 36.67), bd.get("longitude", 116.98)
|
||||
)
|
||||
fallback = _fallback_coord(code)
|
||||
if not fallback:
|
||||
return jsonify({"rtn_code": 400,
|
||||
"message": "缺少定位,请回到地图页再开锁"})
|
||||
latitude, longitude = _near_coord(fallback[0], fallback[1])
|
||||
|
||||
order_result = request_with_user_auth(
|
||||
owner_user_id, "POST", "/record/order",
|
||||
@@ -848,16 +940,23 @@ def share_return():
|
||||
|
||||
owner_user_id = rental["user_id"]
|
||||
bike_code = rental["bike_code"]
|
||||
if not latitude or not longitude:
|
||||
latitude, longitude = 36.67, 116.98
|
||||
|
||||
# 真实还车(owner 凭据):checkLocation → 非还车点则就近停车点
|
||||
from routes.rental import (_try_card_pay_auto, get_nearest_park_point,
|
||||
to_upstream_coords)
|
||||
from timer import _cancel_rental_timers
|
||||
|
||||
# 浏览器上报的是 WGS84,上游/停车区是 GCJ02,入口先统一转一次
|
||||
latitude, longitude = to_upstream_coords(latitude, longitude)
|
||||
# 坐标来源:请求坐标(浏览器 WGS84,入口统一转 GCJ02)→ 该车最近一次
|
||||
# bike_history(已是 GCJ02,不能再转)→ 校园中心(GCJ02)。
|
||||
# 三处都拿不到就明确失败,不再拿一个离校区 20km 的常量糊上去(BUG-17)。
|
||||
if _has_coord(latitude, longitude):
|
||||
latitude, longitude = to_upstream_coords(latitude, longitude)
|
||||
else:
|
||||
fallback = _fallback_coord(bike_code)
|
||||
if not fallback:
|
||||
return jsonify({"rtn_code": 400,
|
||||
"message": "缺少定位,请回到地图页再还车"})
|
||||
latitude, longitude = fallback
|
||||
|
||||
check_result = request_with_user_auth(
|
||||
owner_user_id, "POST", "/record/checkLocation",
|
||||
|
||||
Reference in New Issue
Block a user