12451 ee92102f3c feat(scope)+fix(db)+feat(security): 数据范围(项目级)生效、库列类型对齐、安全加固、状态位分层展示、能耗实时聚合
- 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
2026-09-20 02:44:51 +08:00

156 lines
6.0 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
"""A 项实测探针(在服务器上直接打测试后端 127.0.0.1:3000)
1. 登录拿 token(challenge 的正确 x 从测试 Redis db6 读取,模拟"人正确拖动滑块")
2. POST /api/auth/avatar/upload 传 xss.svg(含 <script>)→ 期望 400 拒绝
3. POST /api/auth/avatar/upload 传 xss.png(SVG 内容、改名 .png)→ 期望 400(魔数兜底)
4. POST /api/auth/avatar/upload 传真 PNG → 期望 200,返回 url
5. POST /api/feedback/upload 同样三连(反馈图上传同源直出)
6. GET 上传后的真实图片 URL → 状态码 / Content-Type / X-Content-Type-Options
"""
import json
import os
import re
import socket
import sys
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"
PASSWORD = "SecTest#2026"
SVG = b'<svg xmlns="http://www.w3.org/2000/svg"><script>alert(1)</script></svg>'
PNG = bytes.fromhex(
"89504e470d0a1a0a0000000d49484452000000010000000108060000001f15c489"
"0000000a49444154789c63000100000500010d0a2db40000000049454e44ae426082"
)
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:
"""极简 RESP 客户端(服务器没装 redis-cli)"""
def __init__(self, url):
u = urlparse(url)
self.pwd = unquote(u.password or "")
self.host, self.port, self.db = u.hostname, u.port or 6379, int((u.path or "/0").lstrip("/") or 0)
self.sock = socket.create_connection((self.host, self.port), timeout=5)
self.fh = self.sock.makefile("rwb")
if self.pwd:
self.cmd("AUTH", self.pwd)
self.cmd("SELECT", str(self.db))
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
data = self.fh.read(n + 2)
return data[:-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, base=BASE):
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, dict(resp.headers), resp.read()
except urllib.error.HTTPError as exc:
return exc.code, dict(exc.headers), exc.read()
def multipart(field, filename, content, ctype):
boundary = "----secprobe" + str(os.getpid())
head = (
f"--{boundary}\r\n"
f'Content-Disposition: form-data; name="{field}"; filename="{filename}"\r\n'
f"Content-Type: {ctype}\r\n\r\n"
).encode()
body = head + content + f"\r\n--{boundary}--\r\n".encode()
return body, f"multipart/form-data; boundary={boundary}"
def login(redis):
st, _, body = http("GET", "/api/auth/challenge")
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()
st, _, body = http("POST", "/api/auth/login", payload, {"Content-Type": "application/json"})
print(f"[login] status={st} body={body.decode()[:220]}")
if st != 200:
raise SystemExit("login failed, cannot continue")
return json.loads(body)["data"]["token"]
def try_upload(token, path, field, filename, content, ctype, label):
body, ct = multipart(field, filename, content, ctype)
st, _, resp = http(
"POST", path, body, {"Content-Type": ct, "Authorization": f"Bearer {token}"}
)
print(f"[{label}] {path} filename={filename} -> status={st} body={resp.decode()[:200]}")
return st, resp
def main():
redis = Redis(read_env("REDIS_URL"))
token = login(redis)
auth = {"Authorization": f"Bearer {token}"}
print("\n===== 头像上传 /api/auth/avatar/upload =====")
try_upload(token, "/api/auth/avatar/upload", "file", "xss.svg", SVG, "image/svg+xml", "A1 svg")
try_upload(token, "/api/auth/avatar/upload", "file", "xss.png", SVG, "image/png", "A2 svg-as-png")
st, resp = try_upload(token, "/api/auth/avatar/upload", "file", "ok.png", PNG, "image/png", "A3 real-png")
ok_url = json.loads(resp)["data"]["avatar"] if st == 200 else None
print("\n===== 反馈图上传 /api/feedback/upload =====")
try_upload(token, "/api/feedback/upload", "file", "xss.svg", SVG, "image/svg+xml", "A4 svg")
try_upload(token, "/api/feedback/upload", "file", "xss2.png", SVG, "image/png", "A5 svg-as-png")
fb_st, fb_resp = try_upload(token, "/api/feedback/upload", "file", "ok.png", PNG, "image/png", "A6 real-png")
print("\n===== 上传后静态访问(直连 :3000,验证 nosniff 由 nginx 加,这里看后端 Content-Type)=====")
for url in filter(None, [ok_url, json.loads(fb_resp)["data"]["url"] if fb_st == 200 else None]):
st, hdrs, body = http("GET", url)
print(f"[A7] GET {url} -> status={st} content-type={hdrs.get('content-type')} bytes={len(body)}")
print("\n===== 目录落盘检查 =====")
for d in ("/data/pms_dev/api-server/uploads/avatars", "/data/pms_dev/api-server/uploads/feedback"):
if os.path.isdir(d):
print(f"{d}: {sorted(os.listdir(d))}")
return 0
if __name__ == "__main__":
sys.exit(main())