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

139 lines
5.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 项实测(用服务端 JWT_SECRET 为该用户签发一个临时 token,仅调用上传接口)
安全说明:
- token 只在本次脚本内存在,不落盘、不外传;
- 只打"应被拒绝"的路径(拒绝发生在写盘/写库之前,不改任何数据);
- 反馈图"应通过"路径只写一个我自己的测试文件,脚本末尾删除;
- 头像"应通过"路径不在生产执行(会覆盖真实用户 avatar),已在测试环境用同一 md5 二进制验证。
"""
import base64
import hashlib
import hmac
import json
import os
import time
import urllib.error
import urllib.request
BASE = "http://127.0.0.1:9000" # 直连后端(应用层行为)
DOMAIN = "https://app.anzhizhichong.com" # 走 nginx(看响应头/CORS)
ENV_FILE = "/data/pms/api-server/.env"
UID = 5
PHONE = "13800000003"
SVG = b'<svg xmlns="http://www.w3.org/2000/svg"><script>alert(1)</script></svg>'
PNG = bytes.fromhex(
"89504e470d0a1a0a0000000d49484452000000010000000108060000001f15c489"
"0000000a49444154789c63000100000500010d0a2db40000000049454e44ae426082"
)
def env(name):
with open(ENV_FILE) as fh:
for line in fh:
if line.startswith(name + "="):
return line.split("=", 1)[1].strip()
raise SystemExit(f"{name} not found")
def b64(raw):
return base64.urlsafe_b64encode(raw).rstrip(b"=")
def mint_token(secret, uid, phone):
now = int(time.time())
head = b64(json.dumps({"typ": "JWT", "alg": "HS256"}, separators=(",", ":")).encode())
body = b64(
json.dumps(
{"sub": uid, "phone": phone, "exp": now + 3600, "iat": now}, separators=(",", ":")
).encode()
)
sig = b64(hmac.new(secret.encode(), head + b"." + body, hashlib.sha256).digest())
return (head + b"." + body + b"." + sig).decode()
def http(method, url, data=None, headers=None):
req = urllib.request.Request(url, 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):
b = "----prodprobe" + str(os.getpid())
head = (
f"--{b}\r\n"
f'Content-Disposition: form-data; name="{field}"; filename="{filename}"\r\n'
f"Content-Type: {ctype}\r\n\r\n"
).encode()
return head + content + f"\r\n--{b}--\r\n".encode(), f"multipart/form-data; boundary={b}"
def main():
token = mint_token(env("JWT_SECRET"), UID, PHONE)
auth = {"Authorization": f"Bearer {token}"}
st, _, body = http("GET", BASE + "/api/auth/me", headers=auth)
print(f"[prod-token] GET /api/auth/me -> {st} {body.decode()[:160]}")
if st != 200:
raise SystemExit("临时 token 未被接受,终止")
print("\n===== 生产 头像上传(拒绝路径,不写盘不写库)=====")
for fn, content, ctype in (
("xss.svg", SVG, "image/svg+xml"),
("xss.png", SVG, "image/png"),
):
data, ct = multipart("file", fn, content, ctype)
st, _, body = http(
"POST", BASE + "/api/auth/avatar/upload", data, {**auth, "Content-Type": ct}
)
print(f" avatar filename={fn} -> {st} {body.decode()[:140]}")
print("\n===== 生产 反馈图上传(拒绝路径 + 一个真实 PNG 测试文件)=====")
url = None
for fn, content, ctype, expect in (
("xss.svg", SVG, "image/svg+xml", "拒"),
("xss2.png", SVG, "image/png", "拒"),
("secprobe.png", PNG, "image/png", "过"),
):
data, ct = multipart("file", fn, content, ctype)
st, _, body = http("POST", BASE + "/api/feedback/upload", data, {**auth, "Content-Type": ct})
print(f" feedback filename={fn}(应{expect})-> {st} {body.decode()[:140]}")
if st == 200:
url = json.loads(body)["data"]["url"]
if url:
st, hdrs, blob = http("GET", DOMAIN + url)
print(
f"\n[prod-static] GET {DOMAIN}{url} -> {st} content-type={hdrs.get('content-type')} "
f"nosniff={hdrs.get('x-content-type-options')} bytes={len(blob)}"
)
path = "/data/pms/api-server" + url
if os.path.isfile(path):
os.remove(path)
print(f"[cleanup] 已删除我自己的测试文件 {path}")
print("\n===== 生产 CORS 白名单 =====")
for origin in (
"https://app.anzhizhichong.com",
"https://test.anzhizhichong.com",
"http://localhost:5173",
"https://evil.example.com",
"null",
):
st, hdrs, _ = http("GET", DOMAIN + "/api/pms/health", headers={"Origin": origin})
print(
f" Origin={origin:<32} -> {st} allow-origin="
f"{hdrs.get('access-control-allow-origin', '(无)')}"
)
return 0
if __name__ == "__main__":
raise SystemExit(main())