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:
@@ -0,0 +1,365 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""修复批次B 的回归测试:重复开锁去重、Timer 幂等、minutes 脏值、退避重试、0 坐标。
|
||||
|
||||
全部用临时库(`db.DB_PATH` 切换)+ mock 上游,不打真实微信接口、不发邮件、
|
||||
不启动任何后台线程(`XBCR_DISABLE_BACKGROUND=1`)。
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import sqlite3
|
||||
import tempfile
|
||||
import threading
|
||||
import time
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
from unittest.mock import patch
|
||||
|
||||
os.environ["XBCR_DISABLE_LEASES"] = "1"
|
||||
os.environ["XBCR_DISABLE_BACKGROUND"] = "1"
|
||||
|
||||
from flask import Flask
|
||||
|
||||
import db
|
||||
import timer
|
||||
from routes import rental as rental_routes
|
||||
|
||||
|
||||
ORDER_ID = "9001"
|
||||
BIKE = "50001"
|
||||
|
||||
|
||||
class RecordingTimer:
|
||||
"""替身 Timer:只记账不真起线程(避免测试结束后还有延迟任务去碰真实数据)。"""
|
||||
|
||||
instances = []
|
||||
|
||||
def __init__(self, delay, callback):
|
||||
self.delay = delay
|
||||
self.callback = callback
|
||||
self.cancelled = False
|
||||
RecordingTimer.instances.append(self)
|
||||
|
||||
def start(self):
|
||||
pass
|
||||
|
||||
def cancel(self):
|
||||
self.cancelled = True
|
||||
|
||||
@classmethod
|
||||
def reset(cls):
|
||||
cls.instances = []
|
||||
|
||||
|
||||
def _fake_upstream(order_id=ORDER_ID, return_ok=True, non_deal=None, barrier=None):
|
||||
"""假的微信上游。path -> 固定返回。"""
|
||||
calls = []
|
||||
|
||||
def call(user_id, method, path, params=None, data=None, _silent=False):
|
||||
calls.append((path, data))
|
||||
if path == "/project/bicycle":
|
||||
return {"rtn_code": 0, "data": {"code": BIKE, "latitude": 36.5318,
|
||||
"longitude": 116.7801, "type": "3", "status": 0}}
|
||||
if path == "/project/map":
|
||||
return {"rtn_code": 0, "data": {"bicycleStation": [
|
||||
{"code": BIKE, "latitude": 36.5318, "longitude": 116.7801}]}}
|
||||
if path == "/record/order":
|
||||
if barrier is not None:
|
||||
try:
|
||||
barrier.wait(timeout=5)
|
||||
except threading.BrokenBarrierError:
|
||||
pass
|
||||
return {"rtn_code": 0, "data": {"order_id": order_id}}
|
||||
if path == "/record/qrOrder":
|
||||
return {"rtn_code": 0, "message": "开锁成功"}
|
||||
if path == "/user/info":
|
||||
return {"rtn_code": 0, "data": {"nonDealOrder": non_deal}}
|
||||
if path == "/record/detail":
|
||||
return {"rtn_code": 0, "data": {"minutes": None, "code": BIKE}}
|
||||
if path == "/record/return":
|
||||
if return_ok:
|
||||
return {"rtn_code": 0, "message": "还车成功"}
|
||||
return {"rtn_code": 500, "message": "return rejected"}
|
||||
return {"rtn_code": 0, "data": {}}
|
||||
|
||||
call.calls = calls
|
||||
return call
|
||||
|
||||
|
||||
class RentalDedupTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
handle = tempfile.NamedTemporaryFile(suffix=".db", delete=False)
|
||||
handle.close()
|
||||
self.db_path = Path(handle.name)
|
||||
self._old_db_path = db.DB_PATH
|
||||
db.DB_PATH = self.db_path
|
||||
db.init_db()
|
||||
|
||||
conn = db.get_db()
|
||||
conn.execute("INSERT INTO users (id, email, password_hash) VALUES (?, ?, ?)",
|
||||
(7, "rider@example.test", "x"))
|
||||
conn.execute("""INSERT INTO rentals
|
||||
(id, order_id, bike_code, email, user_id, source, expired,
|
||||
start_time, end_time, duration)
|
||||
VALUES (101, NULL, ?, 'rider@example.test', 7, 'reminder', 0,
|
||||
'2026-01-01 08:00:00', '2099-01-01 00:00:00', 19)""",
|
||||
(BIKE,))
|
||||
conn.commit()
|
||||
conn.close()
|
||||
|
||||
self._reset_timer_state()
|
||||
RecordingTimer.reset()
|
||||
self._timer_patch = patch.object(timer.threading, "Timer", RecordingTimer)
|
||||
self._timer_patch.start()
|
||||
|
||||
def tearDown(self):
|
||||
self._timer_patch.stop()
|
||||
self._reset_timer_state()
|
||||
db.DB_PATH = self._old_db_path
|
||||
self.db_path.unlink(missing_ok=True)
|
||||
|
||||
@staticmethod
|
||||
def _reset_timer_state():
|
||||
timer._active_timers.clear()
|
||||
timer._timer_gen.clear()
|
||||
timer._auto_return_retries.clear()
|
||||
timer._auto_return_alert_levels.clear()
|
||||
timer._auto_return_backoff_until.clear()
|
||||
timer._recover_last_at.clear()
|
||||
timer._last_prune_at[0] = 0.0
|
||||
timer._sweep_last_at[0] = 0.0
|
||||
|
||||
# ---------- 工具 ----------
|
||||
def _app(self):
|
||||
app = Flask(__name__)
|
||||
app.secret_key = "test"
|
||||
app.register_blueprint(rental_routes.bp)
|
||||
return app
|
||||
|
||||
def _rental_rows(self, order_id=ORDER_ID):
|
||||
conn = sqlite3.connect(str(self.db_path))
|
||||
conn.row_factory = sqlite3.Row
|
||||
try:
|
||||
return [dict(r) for r in conn.execute(
|
||||
"SELECT id, order_id, expired, source FROM rentals WHERE order_id = ?",
|
||||
(order_id,)).fetchall()]
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
# ---------- BUG-03 ----------
|
||||
def test_duplicate_unlock_reuses_row_and_keeps_one_timer_set(self):
|
||||
client = self._app().test_client()
|
||||
upstream = _fake_upstream()
|
||||
with patch.object(rental_routes, "get_current_user",
|
||||
return_value={"id": 7, "email": "rider@example.test"}), \
|
||||
patch.object(rental_routes, "get_user_display_name", return_value="骑行人"), \
|
||||
patch.object(rental_routes, "request_with_user_auth", side_effect=upstream):
|
||||
first = client.post("/api/order/unlock", json={"code": BIKE}).get_json()
|
||||
second = client.post("/api/order/unlock", json={"code": BIKE}).get_json()
|
||||
|
||||
self.assertEqual(0, first["rtn_code"])
|
||||
self.assertEqual(0, second["rtn_code"])
|
||||
self.assertTrue(second.get("reused")) # 第二次是复用,不是新建
|
||||
rows = self._rental_rows()
|
||||
self.assertEqual(1, len(rows), rows) # 关键:只有一行
|
||||
self.assertEqual(0, rows[0]["expired"])
|
||||
# 计时器只有一套(同一 rental_id 一个 key,条目数 = 一次「19 分钟」的提醒点数)
|
||||
self.assertEqual([rows[0]["id"]], list(timer._active_timers.keys()))
|
||||
self.assertEqual(3, len(timer._active_timers[rows[0]["id"]]))
|
||||
|
||||
def test_concurrent_unlock_keeps_single_row(self):
|
||||
barrier = threading.Barrier(2)
|
||||
upstream = _fake_upstream(barrier=barrier)
|
||||
results = []
|
||||
|
||||
def tap():
|
||||
client = self._app().test_client()
|
||||
with patch.object(rental_routes, "get_current_user",
|
||||
return_value={"id": 7, "email": "rider@example.test"}), \
|
||||
patch.object(rental_routes, "get_user_display_name", return_value="骑行人"), \
|
||||
patch.object(rental_routes, "request_with_user_auth", side_effect=upstream):
|
||||
results.append(client.post("/api/order/unlock", json={"code": BIKE}).get_json())
|
||||
|
||||
threads = [threading.Thread(target=tap) for _ in range(2)]
|
||||
for t in threads:
|
||||
t.start()
|
||||
for t in threads:
|
||||
t.join()
|
||||
|
||||
self.assertEqual(2, len(results))
|
||||
self.assertTrue(all(r["rtn_code"] == 0 for r in results), results)
|
||||
rows = self._rental_rows()
|
||||
self.assertEqual(1, len(rows), rows)
|
||||
self.assertEqual(1, len(timer._active_timers))
|
||||
|
||||
def test_partial_unique_index_exists_and_blocks_second_active_row(self):
|
||||
conn = sqlite3.connect(str(self.db_path))
|
||||
try:
|
||||
sql = conn.execute(
|
||||
"SELECT sql FROM sqlite_master WHERE type='index' "
|
||||
"AND name='idx_rentals_active_order'").fetchone()
|
||||
self.assertIsNotNone(sql, "缺少 idx_rentals_active_order 部分唯一索引")
|
||||
self.assertIn("UNIQUE", sql[0].upper())
|
||||
self.assertIn("WHERE", sql[0].upper())
|
||||
# 已有一行 expired=2? 不:这里用「一条未结束 + 再插一条未结束」验证拦截
|
||||
conn.execute("""INSERT INTO rentals
|
||||
(id, order_id, bike_code, email, user_id, source, expired,
|
||||
start_time, end_time)
|
||||
VALUES (201, '9101', ?, 'rider@example.test', 7, 'unlock', 0,
|
||||
'2026-01-01 08:00:00', '2099-01-01 00:00:00')""", (BIKE,))
|
||||
conn.commit()
|
||||
with self.assertRaises(sqlite3.IntegrityError):
|
||||
conn.execute("""INSERT INTO rentals
|
||||
(id, order_id, bike_code, email, user_id, source, expired,
|
||||
start_time, end_time)
|
||||
VALUES (202, '9101', ?, 'rider@example.test', 7, 'unlock', 0,
|
||||
'2026-01-01 08:00:00', '2099-01-01 00:00:00')""", (BIKE,))
|
||||
conn.rollback()
|
||||
# 已结束的历史行不受限制(可重复出现在历史里)
|
||||
conn.execute("""INSERT INTO rentals
|
||||
(id, order_id, bike_code, email, user_id, source, expired,
|
||||
start_time, end_time)
|
||||
VALUES (203, '9101', ?, 'rider@example.test', 7, 'unlock', 1,
|
||||
'2026-01-01 07:00:00', '2026-01-01 07:19:00')""", (BIKE,))
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
# ---------- BUG-12 ----------
|
||||
def test_start_rental_timer_is_idempotent_per_generation(self):
|
||||
timer.start_rental_timer(101, "rider@example.test", BIKE, 19, 7)
|
||||
first_gen = timer._timer_gen[101]
|
||||
first_timers = len(timer._active_timers[101])
|
||||
self.assertEqual(3, first_timers) # 5/3/0 分钟
|
||||
|
||||
timer.start_rental_timer(101, "rider@example.test", BIKE, 19, 7)
|
||||
self.assertEqual(first_timers, len(timer._active_timers[101])) # 不叠加
|
||||
self.assertEqual(first_gen + 1, timer._timer_gen[101])
|
||||
# 上一代注册请求必须被丢弃
|
||||
self.assertIsNone(timer._schedule_reminder(
|
||||
101, 60, "5", "rider@example.test", BIKE, 7, gen=first_gen))
|
||||
|
||||
# ---------- BUG-06 ----------
|
||||
def test_check_user_order_tolerates_null_minutes(self):
|
||||
upstream = _fake_upstream(non_deal={"order_id": "9201", "status": 2, "code": BIKE})
|
||||
with patch.object(timer, "get_user_auth", return_value=("token", "access")), \
|
||||
patch.object(timer, "request_with_user_auth", side_effect=upstream), \
|
||||
patch.object(timer, "send_rental_notification"):
|
||||
result = timer._check_user_order(7) # 不得抛异常
|
||||
|
||||
self.assertTrue(result.get("ok"), result)
|
||||
rows = self._rental_rows("9201")
|
||||
self.assertEqual(1, len(rows))
|
||||
conn = sqlite3.connect(str(self.db_path))
|
||||
try:
|
||||
row = conn.execute(
|
||||
"SELECT duration, end_time FROM rentals WHERE order_id = '9201'").fetchone()
|
||||
finally:
|
||||
conn.close()
|
||||
self.assertEqual(19, row[0]) # minutes 缺失按 0 处理,用满时长
|
||||
self.assertIsNotNone(row[1])
|
||||
|
||||
def test_sync_endpoint_returns_200_when_minutes_is_null(self):
|
||||
client = self._app().test_client()
|
||||
upstream = _fake_upstream(non_deal={"order_id": "9202", "status": 2, "code": BIKE})
|
||||
with patch.object(rental_routes, "get_current_user",
|
||||
return_value={"id": 7, "email": "rider@example.test"}), \
|
||||
patch.object(timer, "get_user_auth", return_value=("token", "access")), \
|
||||
patch.object(timer, "request_with_user_auth", side_effect=upstream), \
|
||||
patch.object(timer, "send_rental_notification"):
|
||||
resp = client.post("/api/rental/sync")
|
||||
self.assertEqual(200, resp.status_code)
|
||||
self.assertNotEqual(500, resp.get_json().get("rtn_code"))
|
||||
|
||||
# ---------- BUG-07 ----------
|
||||
def test_retry_delay_backoff_sequence(self):
|
||||
delays = [timer._auto_return_retry_delay(n) for n in range(10)]
|
||||
self.assertEqual([30, 30, 30, 30, 30, 30, 60, 120, 300, 600], delays)
|
||||
self.assertEqual(600, timer._auto_return_retry_delay(50)) # 封顶 10 分钟
|
||||
self.assertEqual(30, timer._auto_return_retry_delay(None)) # 脏值不炸
|
||||
|
||||
def test_backoff_phase_schedules_no_timer_and_alerts_once_per_level(self):
|
||||
timer._auto_return_retries[55] = timer.AUTO_RETURN_MAX_RETRIES
|
||||
with patch.object(timer, "_alert_auto_return_exhausted") as alert, \
|
||||
patch.object(timer, "_schedule_reminder") as schedule:
|
||||
timer._schedule_auto_return_retry(55, "r@example.test", BIKE, 7, "boom")
|
||||
self.assertEqual(1, alert.call_count)
|
||||
schedule.assert_not_called() # 退避阶段不挂 Timer
|
||||
self.assertGreater(timer._auto_return_backoff_until[55], timer._time.time())
|
||||
level_after_first = timer._auto_return_alert_levels[55]
|
||||
self.assertEqual(2, level_after_first) # 首次进入退避 = 档位 2(60s)
|
||||
|
||||
# 已经发过该档位的告警:不再重复发(n=50 时档位已到封顶的 4 档)
|
||||
timer._auto_return_alert_levels[55] = timer._auto_return_alert_level(50)
|
||||
timer._auto_return_retries[55] = 50
|
||||
timer._schedule_auto_return_retry(55, "r@example.test", BIKE, 7, "boom")
|
||||
self.assertEqual(1, alert.call_count)
|
||||
|
||||
# 快保阶段仍然挂 30s Timer
|
||||
timer._auto_return_retries[56] = 1
|
||||
with patch.object(timer, "_alert_auto_return_exhausted") as alert2, \
|
||||
patch.object(timer, "_schedule_reminder") as schedule2:
|
||||
timer._schedule_auto_return_retry(56, "r@example.test", BIKE, 7, "boom")
|
||||
alert2.assert_not_called()
|
||||
self.assertEqual(30, schedule2.call_args.args[1])
|
||||
|
||||
def test_recover_throttle_honours_backoff_until(self):
|
||||
timer._auto_return_backoff_until[77] = timer._time.time() + 120
|
||||
self.assertTrue(timer._recover_throttled(77))
|
||||
timer._auto_return_backoff_until[77] = timer._time.time() - 1
|
||||
self.assertFalse(timer._recover_throttled(77))
|
||||
self.assertNotIn(77, timer._auto_return_backoff_until)
|
||||
|
||||
def test_prune_reclaims_unbounded_state_dicts(self):
|
||||
stale = timer._time.time() - timer._RECOVER_STATE_TTL - 60
|
||||
for i in range(timer._RUNTIME_DICT_MAX + 500):
|
||||
timer._recover_last_at[10_000 + i] = stale
|
||||
timer._auto_return_retries[20_000 + i] = 7
|
||||
timer._auto_return_backoff_until[30_000 + i] = stale
|
||||
timer._prune_runtime_state(force=True)
|
||||
self.assertLess(len(timer._recover_last_at), timer._RUNTIME_DICT_MAX)
|
||||
self.assertLess(len(timer._auto_return_backoff_until), timer._RUNTIME_DICT_MAX)
|
||||
self.assertLess(len(timer._auto_return_retries), timer._RUNTIME_DICT_MAX)
|
||||
|
||||
# ---------- BUG-11 ----------
|
||||
def test_lock_registry_is_bounded(self):
|
||||
registry = rental_routes._LockRegistry(max_entries=8, ttl_seconds=1)
|
||||
for i in range(200):
|
||||
registry.get("order-%d" % i)
|
||||
self.assertLessEqual(len(registry), 8)
|
||||
|
||||
# ---------- BUG-22 ----------
|
||||
def test_return_treats_zero_coordinates_as_missing(self):
|
||||
"""(0,0) 是「前端把 undefined 序列化成 0」的产物,不能当真实位置发给上游。
|
||||
|
||||
上游 /record/return 不校验取值范围,宽松实现会把 (0,0) 当合法位置接受 ——
|
||||
车就"还"在了几内亚湾,后台起点→终点那列变成大西洋坐标。
|
||||
正确行为:不因此报 400(还车照做),但也不把 (0,0) 发给上游,直接用候选点。
|
||||
"""
|
||||
client = self._app().test_client()
|
||||
upstream = _fake_upstream(return_ok=False)
|
||||
with patch.object(rental_routes, "get_current_user",
|
||||
return_value={"id": 7, "email": "rider@example.test"}), \
|
||||
patch.object(rental_routes, "get_user_display_name", return_value="骑行人"), \
|
||||
patch.object(rental_routes, "request_with_user_auth", side_effect=upstream), \
|
||||
patch.object(rental_routes, "_try_card_pay_auto", return_value={}), \
|
||||
patch.object(rental_routes.time, "sleep"):
|
||||
body = client.post("/api/order/return", json={
|
||||
"order_id": ORDER_ID, "code": BIKE,
|
||||
"latitude": 0.0, "longitude": 0.0,
|
||||
}).get_json()
|
||||
|
||||
self.assertNotEqual(400, body.get("rtn_code"), body)
|
||||
self.assertNotEqual("缺少位置信息", body.get("message"))
|
||||
return_payloads = [d for p, d in upstream.calls if p == "/record/return"]
|
||||
self.assertTrue(return_payloads, "没有向上游发起还车")
|
||||
for payload in return_payloads:
|
||||
self.assertFalse(
|
||||
payload["latitude"] == 0 and payload["longitude"] == 0,
|
||||
f"(0,0) 被当成真实坐标发给了上游: {payload}")
|
||||
# 至少要落到一个真实候选点上
|
||||
self.assertGreater(abs(return_payloads[0]["latitude"]), 0.01)
|
||||
self.assertGreater(abs(return_payloads[0]["longitude"]), 0.01)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in New Issue
Block a user