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

153 lines
6.5 KiB
Python
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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
"""C 项补充实测:降权后(uid=pms)Excel 导出(写 ./exports)仍可用
流程:登录 → 创建导出任务 → 轮询任务状态 → 下载文件 → 打印文件落盘信息
退出码(仓库统一约定 0/1/2):
- `0` = 导出链路可用(任务成功 + 下载到 xlsx)
- `1` = **判据失败**:导出链路真的坏了(任务 status=2 / 下载非 xlsx)
- `2` = **环境或夹具问题,本项"未验证"** —— 登录失败、或账号**缺少 `charge_record:export`
权限码**(403)。⚠️ 这一档必须与 1 分开:本探针要回答的是"**降权后能不能往 exports 写文件**",
账号没权限根本走不到那一步,报 1 就是**把夹具缺陷说成产品缺陷**(误报与假绿同样有害)。
实测(2026-09-20)测试库 `pms_dev` **只有 1 个账号且没有任何 user_roles**,
因此这一项在补齐夹具前**恒为"未验证"**,不能算"导出不可用"。
夹具要求(两条路任选):
1. 给测试账号配含 `charge_record:export` 的角色;或
2. 用环境变量给一个超管账号:`PMS_PROBE_PHONE` / `PMS_PROBE_PASSWORD`。
"""
import json
import os
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"
# 允许用环境变量换成"确有 charge_record:export 权限"的账号(默认沿用安全测试账号)
PHONE = os.environ.get("PMS_PROBE_PHONE", "13900000009")
PASSWORD = os.environ.get("PMS_PROBE_PASSWORD", "SecTest#2026")
class Redis:
def __init__(self, url):
u = urlparse(url)
self.sock = socket.create_connection((u.hostname, u.port or 6379), timeout=5)
self.fh = self.sock.makefile("rwb")
if u.password:
self.cmd("AUTH", unquote(u.password))
self.cmd("SELECT", str(int((u.path or "/0").lstrip("/") or 0)))
def _reply(self):
line = self.fh.readline()
if line.startswith(b"$"):
n = int(line[1:])
return None if n == -1 else self.fh.read(n + 2)[:-2].decode()
return line.strip().decode()
def cmd(self, *args):
out = b"*%d\r\n" % len(args)
for a in args:
a = a.encode() if isinstance(a, str) else a
out += b"$%d\r\n%s\r\n" % (len(a), a)
self.fh.write(out)
self.fh.flush()
return self._reply()
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} missing")
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=30) as resp:
return resp.status, resp.read()
except urllib.error.HTTPError as exc:
return exc.code, exc.read()
def main():
redis = Redis(env("REDIS_URL"))
st, body = http("GET", "/api/auth/challenge")
cid = json.loads(body)["data"]["challenge_id"]
x = redis.cmd("GET", f"challenge:{cid}")
st, body = http(
"POST",
"/api/auth/login",
json.dumps(
{"phone": PHONE, "password": PASSWORD, "challenge_id": cid, "captcha_x": int(x)}
).encode(),
{"Content-Type": "application/json"},
)
if st != 200:
print(f"[login] {st} {body.decode()[:200]}")
print(" ⚠️ 未验证(exit 2):登录失败属环境/夹具问题,不是导出链路缺陷")
return 2
token = json.loads(body)["data"]["token"]
auth = {"Authorization": f"Bearer {token}"}
st, body = http("GET", "/api/charge-records/export?start_time=2020-01-01%2000:00:00&end_time=2030-01-01%2000:00:00", headers=auth)
print(f"[export] create -> {st} {body.decode()[:200]}")
if st == 403:
# 关键区分:403 说明**账号没有权限码**,根本没走到"往 exports 写文件"那一步。
# 把它算成失败(退出码 1)会让人以为"降权后导出不可用",是误报。
print(" ⚠️ 未验证(exit 2):账号缺少 charge_record:export 权限,本项无法判定")
print(" 夹具要求见本文件顶部 docstring(配权限 或 设 PMS_PROBE_PHONE/PASSWORD)")
return 2
if st != 200:
print(f" ❌ exit 1:创建导出任务失败(HTTP {st}),非权限问题")
return 1
task_id = json.loads(body)["data"]["task_id"]
# ⚠️ `download_tasks.status` 的**权威语义**(`db/migrate.rs:225` 列注释 +
# `routes/charge_records.rs:435` 的 `mark_task_completed` 写的就是 2):
# 0=排队 1=处理中 2=**完成** 3=失败
# 本脚本此前**把语义搞反了**(等 `status == 1`、把 `status == 2` 判成"导出任务失败"),
# 于是"导出成功"会被报成失败(假红),与 console 端 `DownloadCenter.tsx::statusText`
# 和 `test/schema_alignment_e2e.py` 的口径都不一致。已按权威语义订正。
STATUS_DONE, STATUS_FAILED = 2, 3
file_path = None
for _ in range(20):
time.sleep(1)
st, body = http("GET", f"/api/downloads/{task_id}", headers=auth)
info = json.loads(body)["data"]
cur = info.get("status")
print(f"[export] task={task_id} status={cur} progress={info.get('progress')} file_path={info.get('file_path')}")
if cur == STATUS_DONE:
file_path = info.get("file_path")
break
if cur == STATUS_FAILED:
print(f" ❌ exit 1:导出任务失败(status=3)err={info.get('error_message')!r}")
return 1
else:
print(" ❌ exit 1:120 秒内任务未进入终态(既没完成也没失败)—— 导出链路可能卡住")
return 1
if not file_path:
print(" ❌ exit 1:任务标记完成但没有 file_path —— 落盘环节有问题")
return 1
st, blob = http("GET", f"/api/downloads/{task_id}/file", headers=auth)
print(f"[download] GET /api/downloads/{task_id}/file -> {st} bytes={len(blob)} head={blob[:4]!r}")
if st == 200 and blob[:2] == b"PK":
print(" ✅ exit 0:导出链路可用(降权成 pms 后仍能往 exports/ 落盘并下载)")
return 0
print(" ❌ exit 1:下载失败或不是 xlsx(xlsx 是 zip,魔数应为 PK)")
return 1
if __name__ == "__main__":
sys.exit(main())