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:
+92
-32
@@ -263,11 +263,16 @@ def stat_location(loc, user_id=None, fresh=True):
|
||||
# ========== 自动开锁(真实链路) ==========
|
||||
|
||||
def _near_coord(lat, lng, jitter=0.0001):
|
||||
"""车辆坐标附近加随机抖动,模拟真实定位(避免每次上报同一精确点被判远程操作)。"""
|
||||
"""车辆坐标附近加随机抖动,模拟真实定位(避免每次上报同一精确点被判远程操作)。
|
||||
|
||||
坐标缺失/非法时退回**校园中心**(`campus.campus_center()`),不再用
|
||||
历史硬编码 (36.67, 116.98) —— 那个点离校区约 20km,会把起点/还车点写坏。
|
||||
"""
|
||||
try:
|
||||
lat, lng = float(lat), float(lng)
|
||||
except (TypeError, ValueError):
|
||||
lat, lng = 36.67, 116.98
|
||||
from campus import campus_center
|
||||
lat, lng = campus_center()
|
||||
return (lat + random.uniform(-jitter, jitter), lng + random.uniform(-jitter, jitter))
|
||||
|
||||
|
||||
@@ -319,6 +324,73 @@ def _discard_pending_order(user_id: int, order_id, code: str,
|
||||
return False
|
||||
|
||||
|
||||
def _find_active_rental_id(conn, order_id):
|
||||
"""该上游订单号是否已有「未结束」的本地记录;有就返回其 rental_id。
|
||||
|
||||
与 `routes.rental._find_active_rental_id` 同一口径(有意保持一致):
|
||||
空 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 _ensure_subscribe_rental(conn, *, order_id, code, email, user_id,
|
||||
start_time, end_time, duration):
|
||||
"""订阅自动开锁的幂等落库:返回 (rental_id, created)。
|
||||
|
||||
与手动开锁(`routes.rental._insert_unlock_rental`)同源问题:上游同一
|
||||
`order_id` 被重复使用时(规则重跑 / 网关重试 / 上游复用同一单号),绝不能
|
||||
插第二行 rentals 和第二套计时器 —— 否则双份提醒、自动还车打两次、轮次翻倍。
|
||||
`db.py` 的 `idx_rentals_active_order` 是硬兜底,这里先查一次做软复用。
|
||||
"""
|
||||
key = str(order_id).strip() if order_id is not None else ""
|
||||
existing = _find_active_rental_id(conn, key)
|
||||
if existing is not None:
|
||||
return existing, False
|
||||
|
||||
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, renewal_round)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, 0, 'subscribe', 1)
|
||||
""", (numeric_id, key, code, email, user_id, start_time, end_time, duration))
|
||||
return numeric_id, True
|
||||
except sqlite3.IntegrityError:
|
||||
existing = _find_active_rental_id(conn, key)
|
||||
if existing is not None:
|
||||
print(f"[订阅开锁] order_id={key} 已存在未结束记录 rental_id={existing},复用")
|
||||
return existing, False
|
||||
print(f"[订阅开锁] rentals.id={numeric_id} 已被占用,改用自增 id")
|
||||
|
||||
try:
|
||||
cur = conn.execute("""
|
||||
INSERT INTO rentals (order_id, bike_code, email, user_id, start_time,
|
||||
end_time, duration, expired, source, renewal_round)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, 0, 'subscribe', 1)
|
||||
""", (key, code, email, user_id, start_time, end_time, duration))
|
||||
except sqlite3.IntegrityError:
|
||||
existing = _find_active_rental_id(conn, key)
|
||||
if existing is not None:
|
||||
print(f"[订阅开锁] order_id={key} 并发重复,复用 rental_id={existing}")
|
||||
return existing, False
|
||||
raise
|
||||
return int(cur.lastrowid), True
|
||||
|
||||
|
||||
def _try_auto_unlock(user_id: int, bike_code: str) -> dict:
|
||||
"""真实自动开锁:扫码 → 创建订单 → 开锁(全部使用订阅人自己的凭据)。
|
||||
|
||||
@@ -351,8 +423,7 @@ def _try_auto_unlock(user_id: int, bike_code: str) -> dict:
|
||||
if live:
|
||||
lat, lng = _near_coord(live[0], live[1])
|
||||
else:
|
||||
lat, lng = _near_coord(bike_data.get("latitude", 36.67),
|
||||
bike_data.get("longitude", 116.98))
|
||||
lat, lng = _near_coord(bike_data.get("latitude"), bike_data.get("longitude"))
|
||||
|
||||
order = request_with_user_auth(
|
||||
user_id, "POST", "/record/order",
|
||||
@@ -412,36 +483,25 @@ def _try_auto_unlock(user_id: int, bike_code: str) -> dict:
|
||||
row = conn.execute("SELECT email FROM users WHERE id = ?", (user_id,)).fetchone()
|
||||
if row:
|
||||
email = row["email"] or ""
|
||||
try:
|
||||
cur = conn.execute("""
|
||||
INSERT INTO rentals (id, order_id, bike_code, email, user_id, start_time,
|
||||
end_time, duration, expired, source, renewal_round)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, 0, 'subscribe', 1)
|
||||
""", (int(order_id), str(order_id), code, email, user_id,
|
||||
now.strftime("%Y-%m-%d %H:%M:%S"), end.strftime("%Y-%m-%d %H:%M:%S"),
|
||||
duration))
|
||||
rental_id = cur.lastrowid or int(order_id)
|
||||
except sqlite3.IntegrityError:
|
||||
# id 与历史行冲突(极少见):改用自增 id,order_id 仍记录真实订单号。
|
||||
# 一定要用 lastrowid 当 rental_id —— 之前继续用 int(order_id),
|
||||
# 计时器/起点回填会作用到撞冲突的那条旧单上,新车完全没有计时器。
|
||||
cur = conn.execute("""
|
||||
INSERT INTO rentals (order_id, bike_code, email, user_id, start_time,
|
||||
end_time, duration, expired, source, renewal_round)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, 0, 'subscribe', 1)
|
||||
""", (str(order_id), code, email, user_id,
|
||||
now.strftime("%Y-%m-%d %H:%M:%S"), end.strftime("%Y-%m-%d %H:%M:%S"),
|
||||
duration))
|
||||
rental_id = cur.lastrowid
|
||||
start_str = now.strftime("%Y-%m-%d %H:%M:%S")
|
||||
end_str = end.strftime("%Y-%m-%d %H:%M:%S")
|
||||
rental_id, created = _ensure_subscribe_rental(
|
||||
conn, order_id=order_id, code=code, email=email, user_id=user_id,
|
||||
start_time=start_str, end_time=end_str, duration=duration)
|
||||
conn.commit()
|
||||
conn.close()
|
||||
start_rental_timer(rental_id=int(rental_id), email=email, bike_code=code,
|
||||
duration_minutes=duration, user_id=user_id)
|
||||
try:
|
||||
from routes.rental import _record_rental_start
|
||||
_record_rental_start(int(rental_id), lat, lng)
|
||||
except Exception as exc:
|
||||
print(f"[订阅开锁] 回填起点失败: {exc}")
|
||||
if created:
|
||||
start_rental_timer(rental_id=int(rental_id), email=email, bike_code=code,
|
||||
duration_minutes=duration, user_id=user_id)
|
||||
try:
|
||||
from routes.rental import _record_rental_start
|
||||
_record_rental_start(int(rental_id), lat, lng)
|
||||
except Exception as exc:
|
||||
print(f"[订阅开锁] 回填起点失败: {exc}")
|
||||
else:
|
||||
# 同一上游订单已有未结束的本地单(规则重跑/上游复用 order_id):
|
||||
# 复用既有 rental_id,绝不插第二行,也不重排计时器(BUG-03 的订阅侧同源问题)
|
||||
print(f"[订阅开锁] order_id={order_id} 已有未结束记录 rental_id={rental_id},复用不重复落单")
|
||||
except Exception as exc:
|
||||
# 上游已开锁成功,本地记录失败不影响结果,但要留痕
|
||||
print(f"[订阅开锁] 本地落单失败(上游已开锁): {exc}")
|
||||
|
||||
Reference in New Issue
Block a user