Files
xbcr/tests/test_analysis_auth.py
T
zzy f34ed304bc 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) 时上游只收到候选点;合法坐标仍先发上报值;唯一索引拦住重复插入
2026-11-17 09:58:16 +08:00

168 lines
7.5 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""数据分析 / 历史轨迹接口的登录门禁(BUG-02,用户裁决:登录用户才可访问)。
被钉住的 8 个入口:
/api/bike_history、/api/analysis/overview、/api/analysis/heatmap、
/api/history/{stats,bikes,trajectory,all_trajectory,heatmap}
三组断言:
1. 未登录(含 token 已过期)→ HTTP 401 且 body 里 rtn_code=401、不下发 data;
同时钉住限速白名单不再把这些路径当「公开数据接口」。
2. 带 Bearer 登录 → 200 / rtn_code=0。
3. 响应契约:all_trajectory 的 limit 已下压并与 truncated 一起返回;
热力图在 SQL 里做网格聚合(total_points / grid_count / max_count 自洽)。
为什么用子进程:本仓库其它用例(fixture 各自 patch db.DB_PATH)在同进程内会互相踩,
app.py 在 import 期还会重包装 stdout;本文件沿用 tests/test_history_30d.py 的既有做法,
把验证放进独立子进程,父进程零污染。
"""
import os
import subprocess
import sys
import unittest
from pathlib import Path
os.environ["XBCR_DISABLE_BACKGROUND"] = "1"
ROOT = Path(__file__).parent.parent
CHILD = r'''
import os, sys, tempfile
from pathlib import Path
ROOT = Path(r"{root}")
os.environ["XBCR_DISABLE_BACKGROUND"] = "1"
sys.path.insert(0, str(ROOT))
import db as db_mod
handle = tempfile.NamedTemporaryFile(suffix=".db", delete=False)
handle.close()
db_mod.DB_PATH = Path(handle.name)
import app as app_mod
db_mod.init_db()
MODE = sys.argv[1]
TOKEN = "analysis-auth-test-token"
EXPIRED = "analysis-auth-expired-token"
ENDPOINTS = (
"/api/bike_history?code=50001",
"/api/analysis/overview",
"/api/analysis/heatmap",
"/api/history/stats?days=1",
"/api/history/bikes",
"/api/history/trajectory?bike_code=50001&days=3",
"/api/history/all_trajectory?days=1",
"/api/history/heatmap",
)
failures = []
def check(label, cond, detail=""):
print(("[PASS] " if cond else "[FAIL] ") + label + ((" | " + str(detail)) if detail else ""))
if not cond:
failures.append(label)
conn = db_mod.get_db()
conn.executescript("""
INSERT INTO bike_history (bike_code, latitude, longitude, state, status, electric, recorded_at) VALUES
('50001', 36.5318, 116.7801, 1, 0, 85, datetime('now','+8 hours','-10 minutes')),
('50001', 36.5319, 116.7802, 1, 0, 84, datetime('now','+8 hours','-5 minutes')),
('50002', 36.5320, 116.7803, 10, 0, 15, datetime('now','+8 hours','-3 minutes'));
""")
conn.execute("INSERT INTO users (email, password_hash) VALUES (?, ?)", ("analysis@example.com", "x"))
uid = conn.execute("SELECT id FROM users WHERE email = ?", ("analysis@example.com",)).fetchone()[0]
conn.execute(
"INSERT INTO sessions (user_id, token, expires_at, device_name, device_id, user_agent, last_active)"
" VALUES (?, ?, datetime('now','+8 hours','+1 day'), 'pytest', 'pytest-dev', 'pytest', datetime('now','+8 hours'))",
(uid, TOKEN))
conn.execute(
"INSERT INTO sessions (user_id, token, expires_at) VALUES (?, ?, datetime('now','+8 hours','-1 day'))",
(uid, EXPIRED))
conn.commit()
conn.close()
client = app_mod.app.test_client()
AUTH = {"Authorization": "Bearer " + TOKEN}
if MODE == "unauthenticated":
for path in ENDPOINTS:
resp = client.get(path)
body = resp.get_json() or {}
check("未登录 401 | " + path, resp.status_code == 401, resp.status_code)
check(" rtn_code=401 | " + path, body.get("rtn_code") == 401, body.get("rtn_code"))
check(" 不下发 data | " + path, "data" not in body, sorted(body.keys()))
# 有 token 但已过期:同样不算登录
resp = client.get("/api/history/stats", headers={"Authorization": "Bearer " + EXPIRED})
check("过期会话仍是 401", resp.status_code == 401, resp.status_code)
# 限速白名单不再把历史/分析当公开数据(否则登录用户会白挨 429)
prefixes = tuple(app_mod.PUBLIC_DATA_PREFIXES)
check("PUBLIC_DATA_PREFIXES 不含 /api/history", not any(p.startswith("/api/history") for p in prefixes), prefixes)
check("PUBLIC_DATA_PREFIXES 不含 /api/analysis", not any(p.startswith("/api/analysis") for p in prefixes), prefixes)
check("PUBLIC_DATA_PREFIXES 不含 /api/bike_history", "/api/bike_history" not in prefixes, prefixes)
check("LOGGED_IN_EXEMPT_PREFIXES 不含 /api/bike_history", "/api/bike_history" not in app_mod.LOGGED_IN_EXEMPT_PREFIXES, app_mod.LOGGED_IN_EXEMPT_PREFIXES)
elif MODE == "authenticated":
for path in ENDPOINTS:
resp = client.get(path, headers=AUTH)
body = resp.get_json() or {}
check("登录后 200 | " + path, resp.status_code == 200, resp.status_code)
check(" rtn_code=0 | " + path, body.get("rtn_code") == 0, body.get("rtn_code"))
check(" 带 data | " + path, "data" in body, sorted(body.keys()))
elif MODE == "contract":
data = client.get("/api/history/all_trajectory?days=1", headers=AUTH).get_json()["data"]
check("all_trajectory 回传 limit", isinstance(data.get("limit"), int), data.get("limit"))
check("all_trajectory limit 已下压到 6 万以内",
data.get("limit") == app_mod.HISTORY_ALL_TRAJECTORY_LIMIT and data["limit"] <= 60000,
data.get("limit"))
check("all_trajectory truncated 为 bool", isinstance(data.get("truncated"), bool), data.get("truncated"))
check("all_trajectory 3 个点都在", sum(len(v) for v in data["trajectories"].values()) == 3,
{k: len(v) for k, v in data["trajectories"].items()})
heat = client.get("/api/history/heatmap", headers=AUTH).get_json()["data"]
check("heatmap total_points=3", heat["total_points"] == 3, heat["total_points"])
check("heatmap grid_count 与 points 长度一致", heat["grid_count"] == len(heat["points"]),
(heat["grid_count"], len(heat["points"])))
check("heatmap max_count 等于最大格点计数",
heat["max_count"] == max(p["count"] for p in heat["points"]), heat["max_count"])
check("heatmap bounds 非空", heat.get("bounds") is not None, heat.get("bounds"))
check("heatmap 聚合后格点数远小于原始点数", heat["grid_count"] <= heat["total_points"],
(heat["grid_count"], heat["total_points"]))
else:
print("unknown mode: " + MODE)
sys.exit(2)
Path(handle.name).unlink(missing_ok=True)
print("RESULT: " + ("FAIL" if failures else "ALL PASS") + " (" + str(len(failures)) + " failures)")
sys.exit(1 if failures else 0)
'''.replace("{root}", str(ROOT).replace("\\", "\\\\"))
def _run_child(mode: str) -> subprocess.CompletedProcess:
return subprocess.run([sys.executable, "-c", CHILD, mode],
capture_output=True, text=True, timeout=180,
cwd=str(ROOT), encoding="utf-8", errors="replace")
def _assert_child_ok(mode: str) -> None:
r = _run_child(mode)
out = (r.stdout or "") + (r.stderr or "")
print(out[-4000:] if len(out) > 4000 else out)
assert r.returncode == 0, f"子进程校验失败(mode={mode},见上方输出)"
class AnalysisAuthTests(unittest.TestCase):
def test_unauthenticated_requests_are_rejected(self):
"""8 个入口未登录一律 401,且不下发 data;限速白名单同步收紧。"""
_assert_child_ok("unauthenticated")
def test_authenticated_requests_are_served(self):
"""同一个请求带上 Bearer 后 200 / rtn_code=0。"""
_assert_child_ok("authenticated")
def test_response_contract_after_auth(self):
"""all_trajectory 的 limit/truncated、heatmap 的网格聚合口径。"""
_assert_child_ok("contract")