12451 471b61d277 fix(test)+fix(deploy)+docs: 探针状态语义反转修复、退出码补齐、文档校订
1) probe_export.py:任务状态语义**搞反了**(导出成功也会被判失败)
   - download_tasks.status 的权威语义是 0 排队 / 1 处理中 / **2 完成** / 3 失败
     (db/migrate.rs:225 列注释;写入侧 charge_records.rs::mark_task_completed 写的就是 2)。
   - 该脚本此前**等 status == 1(处理中)当成功、把 status == 2(完成)判成"导出失败"**
     —— 典型假红。已按权威语义订正,并与另外两处**本来就正确**的口径对齐:
     web/src/pages/charge-records/DownloadCenter.tsx::statusText、
     test/schema_alignment_e2e.py(等 status in (2,3) 再断言 == 2)。
   - 同批修正退出码分类:账号缺 charge_record:export(403)由 exit 1 改为
     **exit 2「未验证」** —— 本项要验证的是"降权成 pms 后能否往 exports/ 落盘",
     没权限根本走不到那一步,报 1 是**把夹具缺陷说成产品缺陷**(误报与假绿同样有害)。
   - 允许用 PMS_PROBE_PHONE / PMS_PROBE_PASSWORD 换成有权限的账号。
   - **C 项结论(由落盘物证直接判定,不依赖该脚本)**:测试环境
     exports/充电记录__-.xlsx 5559 B、生产同类产物 5457 B,属主均为 pms:pms;
     两环境 exports/uploads 目录均 pms:pms,两 api-server 单元均 User=pms/Group=pms
     ⇒ 降权进程确实能落盘。已在 README 写明并给出取证依据。

2) deploy-prod.ps1 的退出码(此前失败的探针只打印 ❌ 就继续,脚本仍以 0 退出)
   - 消费链路探测失败(exit 1)现在**记入失败清单**并以 exit 1 收尾;
     "未验证"(隧道没起)默认仍不计失败(环境问题会误报),
     但新增 **-StrictVerify** 开关供 CI/无人值守使用,打开即 exit 1。
   - 好处:把这条从"打印了 ❌ 却 exit 0"(仓库第 8 条假绿)里摘出来。

3) 统一退出码 0/1/2 落地到本批脚本,并对每个失败路径实测取证:
   - test/tcp_e2e_smoke.py:13/13 通过(含未登录业务报文被静默丢弃);先复位夹具再跑。
   - test/security-hardening/ 新增 verdict.py 判据容器(未跟踪 → 本次入库);
     4 个探针全部按失败→exit 1 改造,并各实测过失败路径。
   - 实测结果(2026-09-20 发布后回归):smoke_prod 4/4 exit 0、
     probe_prod 5/5 exit 0、probe_upload 6/6 exit 0。

4) 工具与文档
   - tools/db.py 默认库由**生产 pms 改为测试 pms_dev**(可用 PMS_MYSQL_DB 覆盖,
     切生产时打印醒目警告)—— "以为在测测试库、实际打生产"的隐患。
   - tools/db_schema_diff.py:连不上必须是 exit 2,绝不伪装成"无漂移"的 0。
   - 新增 tools/dev-tunnel.ps1(入库,SSH 隧道;口令走 PMS_SSH_PASSWORD 环境变量),
     配套 tools/dev-tunnel-run.ps1 自愈启动器**保持 gitignore**(内含口令)。
   - deploy/nginx/nginx.conf 镜像随线上同步(移除 stream 转发;与线上逐字节一致)。
   - AGENTS.md / README.md:补「踩过的坑」第 7/8 条(掐断上游管道会杀被测进程、
     打印 ❌ 却 exit 0 是假绿)、退出码约定、本地开发改 SSH 隧道、
     在线判据口径订正、order_timeout 守门补齐、小程序 vue-tsc 门禁与其抓到的两个真 BUG。

发布验收(本次统一发布,按 device→api 顺序):
- 测试环境与生产环境四服务 active,端口 9000/9001/3000/3001 正确,ERROR 均为 0;
- 生产迁移按判据 grep '更新列注释' 实测对齐 cabinets.status 列注释;
- 结构漂移 python tools/db_schema_diff.py = 0 处漂移 / exit 0(--vs-ddl 两库同样 0);
- schema_alignment_e2e --env dev 全部通过 exit 0;
- 生产域名 /api/pms/cabinets -> 401、/pms/ -> 200;消费链路探测通过。
2026-09-20 04:31:42 +08:00

166 lines
6.9 KiB
Python
Raw Permalink 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
from verdict import Verdict # 同目录:判据 + 统一退出码(0 通过 / 1 有失败 / 2 环境问题)
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():
# 判据容器:失败 → exit 1(见 verdict.py;此前本脚本写死 return 0,属假绿)
v = Verdict("probe_upload(测试环境 uploads 安全)")
redis = Redis(read_env("REDIS_URL"))
token = login(redis)
auth = {"Authorization": f"Bearer {token}"}
print("\n===== 头像上传 /api/auth/avatar/upload =====")
st, _ = try_upload(token, "/api/auth/avatar/upload", "file", "xss.svg", SVG, "image/svg+xml", "A1 svg")
v.check("A1 头像:svg(image/svg+xml)应被拒", st != 200, f"status={st}")
st, _ = try_upload(token, "/api/auth/avatar/upload", "file", "xss.png", SVG, "image/png", "A2 svg-as-png")
v.check("A2 头像:改名 .png 的 SVG(魔数兜底)应被拒", st != 200, f"status={st}")
st, resp = try_upload(token, "/api/auth/avatar/upload", "file", "ok.png", PNG, "image/png", "A3 real-png")
v.check("A3 头像:真 PNG 应通过", st == 200, f"status={st}")
ok_url = json.loads(resp)["data"]["avatar"] if st == 200 else None
print("\n===== 反馈图上传 /api/feedback/upload =====")
st, _ = try_upload(token, "/api/feedback/upload", "file", "xss.svg", SVG, "image/svg+xml", "A4 svg")
v.check("A4 反馈图:svg 应被拒", st != 200, f"status={st}")
st, _ = try_upload(token, "/api/feedback/upload", "file", "xss2.png", SVG, "image/png", "A5 svg-as-png")
v.check("A5 反馈图:改名 .png 的 SVG 应被拒", st != 200, f"status={st}")
fb_st, fb_resp = try_upload(token, "/api/feedback/upload", "file", "ok.png", PNG, "image/png", "A6 real-png")
v.check("A6 反馈图:真 PNG 应通过", fb_st == 200, f"status={fb_st}")
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 v.exit_code() # 0=判据全过,1=有判据失败
if __name__ == "__main__":
sys.exit(main())