- user_scopes 由"假开关"做成生效:粒度到项目级(组织隔离 ∧ 项目∈范围,取交集);未配置=不限制(逐字向后兼容);
总管理员豁免;脏数据保守忽略不锁死;配置期校验存在性+归属;逐接口叠加(列表/详情/写操作/Excel 导出落 scope_project_ids);
前端新增"数据范围"弹窗入口。顺带修 GET /api/charge-orders 此前完全没有组织隔离(跨租户泄露)、
GET /api/projects/{id}/cabinets 的 500
- 数据库列类型系统性对齐:扫描并修复 pms_dev 32 项 / pms 18 项漂移(时间列统一 DATETIME,sqlx NaiveDateTime 只兼容 DATETIME);
DECIMAL→BIGINT 与列注释口径拉平;修复生产 GET /api/charge-orders、GET /api/device-logs 必然 500 的根因;
恢复 7 张表丢失的 updated_at ON UPDATE(行为变化,已记入 AGENTS.md);修正 SCHEMA_SQL 前向引用(空库建表必崩);
新增 tools/db_schema_diff.py(漂移检查,退出码可接部署前置)与 test/schema_alignment_e2e.py
- 安全加固四项:上传去 .svg + 魔数嗅探(堵存储型 XSS);登录失败锁定(5次/15分)+challenge 限流+并发闸门+验证码容差收紧;
服务降权 root→pms;nginx 安全头 + limit_req + CORS 白名单收敛
- TCP 连接登录门控(上行+下行同一规则):login 前只放行 auth_str/login(PRE_LOGIN_ALLOWED_ACTS)
- 状态位按归属层级展示:柜级 status1/status2 显示在柜子(含柜门 + 开门按钮,独立动作不联动业务)、
仓体级 batt_status/pow_status 显示在仓体;两端解析函数同源同名
- 能耗报表改实时聚合 charge_records(原 energy_stats 全表只读不写导致报表恒 0)+ 补复合索引
- 组织可见性:新增 GET /api/my-organizations(工厂全量、客户仅本组织)
- 仓体 status 仅表占用,充满/故障由 Redis 通道状态派生
- 订单/占用/队列运维缺口:h5 建单漏单、214 仓体自愈、device:reports 上限、死信 TTL、LimitNOFILE、
每日 mysqldump + 回滚点保留 5 次
- 文档:AGENTS.md 补层级可见性/数据范围/状态位约定/数据库工具/行为变化;docs/API.md 删除废弃 TCP 章节、接口总表对齐 mod.rs
159 lines
5.9 KiB
Python
159 lines
5.9 KiB
Python
#!/usr/bin/env python3
|
||
"""B 项实测探针(直连测试后端 127.0.0.1:3000,X-Real-IP 用于隔离不同"客户端"桶)
|
||
|
||
1. 成功登录清零:2 次错密码 → 计数=2 → 正确密码登录成功 → 计数键被删除
|
||
2. 锁定:5 次错密码 → 第 6 次(以及锁定后的正确密码)都返回统一文案 401
|
||
3. challenge 限流:同一 IP 连打 12 次 → 第 11/12 次 429
|
||
4. 并发闸门:N 个不同 IP 并发请求 challenge → 观察是否被排队/超时(Semaphore=2)
|
||
"""
|
||
import concurrent.futures
|
||
import json
|
||
import socket
|
||
import sys
|
||
import time
|
||
import urllib.error
|
||
import urllib.request
|
||
from urllib.parse import unquote, urlparse
|
||
|
||
BASE = "http://127.0.0.1:3000"
|
||
ENV_FILE = "/data/pms_dev/api-server/.env"
|
||
PHONE = "13900000009"
|
||
GOOD = "SecTest#2026"
|
||
BAD = "WrongPass#1"
|
||
FAIL_KEY = f"auth:fail:phone:{PHONE}"
|
||
|
||
|
||
def read_env(name, path=ENV_FILE):
|
||
with open(path) as fh:
|
||
for line in fh:
|
||
line = line.strip()
|
||
if line.startswith(name + "="):
|
||
return line.split("=", 1)[1].strip()
|
||
raise SystemExit(f"{name} not found in {path}")
|
||
|
||
|
||
class Redis:
|
||
def __init__(self, url):
|
||
u = urlparse(url)
|
||
self.pwd = unquote(u.password or "")
|
||
self.sock = socket.create_connection((u.hostname, u.port or 6379), timeout=5)
|
||
self.fh = self.sock.makefile("rwb")
|
||
if self.pwd:
|
||
self.cmd("AUTH", self.pwd)
|
||
self.cmd("SELECT", str(int((u.path or "/0").lstrip("/") or 0)))
|
||
|
||
def _reply(self):
|
||
line = self.fh.readline()
|
||
if line.startswith(b"+"):
|
||
return line[1:].strip().decode()
|
||
if line.startswith(b"-"):
|
||
raise RuntimeError(line.decode().strip())
|
||
if line.startswith(b":"):
|
||
return int(line[1:])
|
||
if line.startswith(b"$"):
|
||
n = int(line[1:])
|
||
if n == -1:
|
||
return None
|
||
return self.fh.read(n + 2)[:-2].decode()
|
||
raise RuntimeError(f"unexpected reply: {line!r}")
|
||
|
||
def cmd(self, *args):
|
||
out = b"*%d\r\n" % len(args)
|
||
for a in args:
|
||
if isinstance(a, str):
|
||
a = a.encode()
|
||
out += b"$%d\r\n%s\r\n" % (len(a), a)
|
||
self.fh.write(out)
|
||
self.fh.flush()
|
||
return self._reply()
|
||
|
||
|
||
def http(method, path, data=None, headers=None):
|
||
req = urllib.request.Request(BASE + path, data=data, method=method)
|
||
for k, v in (headers or {}).items():
|
||
req.add_header(k, v)
|
||
try:
|
||
with urllib.request.urlopen(req, timeout=20) as resp:
|
||
return resp.status, resp.read()
|
||
except urllib.error.HTTPError as exc:
|
||
return exc.code, exc.read()
|
||
|
||
|
||
def login_attempt(redis, ip, password):
|
||
"""一次完整登录:取 challenge → (从 Redis 读正确 x,模拟人正确拖动)→ 提交"""
|
||
st, body = http("GET", "/api/auth/challenge", headers={"X-Real-IP": ip})
|
||
if st != 200:
|
||
return st, body
|
||
cid = json.loads(body)["data"]["challenge_id"]
|
||
correct_x = redis.cmd("GET", f"challenge:{cid}")
|
||
payload = json.dumps(
|
||
{"phone": PHONE, "password": password, "challenge_id": cid, "captcha_x": int(correct_x)}
|
||
).encode()
|
||
return http("POST", "/api/auth/login", payload, {"Content-Type": "application/json", "X-Real-IP": ip})
|
||
|
||
|
||
def counters(redis, ip):
|
||
return {
|
||
"phone": redis.cmd("GET", FAIL_KEY),
|
||
"ip": redis.cmd("GET", f"auth:fail:ip:{ip}"),
|
||
"phone_ttl": redis.cmd("TTL", FAIL_KEY),
|
||
}
|
||
|
||
|
||
def main():
|
||
redis = Redis(read_env("REDIS_URL"))
|
||
for k in (FAIL_KEY, "auth:fail:ip:10.9.9.4", "auth:fail:ip:10.9.9.5", "auth:fail:ip:10.9.9.6"):
|
||
redis.cmd("DEL", k)
|
||
|
||
print("===== B1 成功登录清零失败计数 =====")
|
||
for i in (1, 2):
|
||
st, body = login_attempt(redis, "10.9.9.4", BAD)
|
||
print(f" 错密码#{i} status={st} body={body.decode()[:120]}")
|
||
print(f" 计数(2 次失败后): {counters(redis, '10.9.9.4')}")
|
||
st, body = login_attempt(redis, "10.9.9.4", GOOD)
|
||
print(f" 正确密码 status={st} body={body.decode()[:120]}")
|
||
print(f" 计数(登录成功后应为 None): {counters(redis, '10.9.9.4')}")
|
||
|
||
print("\n===== B2 连续失败锁定(阈值 5 次 / 15 分钟)=====")
|
||
for i in range(1, 7):
|
||
st, body = login_attempt(redis, "10.9.9.5", BAD)
|
||
print(f" 错密码#{i} status={st} body={body.decode()[:120]} counters={counters(redis, '10.9.9.5')}")
|
||
print(" 锁定后再用【正确密码】尝试(应仍被拒,且文案与密码错误完全一致,不泄露锁定状态):")
|
||
st, body = login_attempt(redis, "10.9.9.7", GOOD)
|
||
print(f" 正确密码 status={st} body={body.decode()[:120]}")
|
||
|
||
print("\n===== B3 challenge 限流(同一 IP 12 次)=====")
|
||
for i in range(1, 13):
|
||
st, body = http("GET", "/api/auth/challenge", headers={"X-Real-IP": "10.9.9.6"})
|
||
print(f" challenge#{i} status={st} body={body.decode()[:80]}")
|
||
|
||
print("\n===== B4 并发闸门(Semaphore=2,不同 IP 并发请求 challenge)=====")
|
||
t0 = time.time()
|
||
st, _ = http("GET", "/api/auth/challenge", headers={"X-Real-IP": "10.9.7.1"})
|
||
single = time.time() - t0
|
||
print(f" 单次 challenge 耗时 {single*1000:.0f} ms")
|
||
n = 40
|
||
t0 = time.time()
|
||
with concurrent.futures.ThreadPoolExecutor(max_workers=n) as pool:
|
||
results = list(
|
||
pool.map(
|
||
lambda i: http("GET", "/api/auth/challenge", headers={"X-Real-IP": f"10.9.8.{i}"})[0],
|
||
range(1, n + 1),
|
||
)
|
||
)
|
||
wall = time.time() - t0
|
||
codes = {}
|
||
for r in results:
|
||
codes[r] = codes.get(r, 0) + 1
|
||
print(f" {n} 并发(不同 IP)耗时 {wall:.2f}s,状态码分布={codes}")
|
||
|
||
print("\n===== 清理测试计数键 =====")
|
||
for k in (FAIL_KEY, "auth:fail:ip:10.9.9.4", "auth:fail:ip:10.9.9.5", "auth:fail:ip:10.9.9.7"):
|
||
redis.cmd("DEL", k)
|
||
print(f" 清理后 phone 计数 = {redis.cmd('GET', FAIL_KEY)}")
|
||
return 0
|
||
|
||
|
||
if __name__ == "__main__":
|
||
sys.exit(main())
|