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;消费链路探测通过。
148 lines
5.7 KiB
Python
148 lines
5.7 KiB
Python
#!/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
|
||
|
||
from verdict import Verdict # 同目录:判据 + 统一退出码(0 通过 / 1 有失败 / 2 环境问题)
|
||
|
||
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():
|
||
# 判据容器:失败 → exit 1(此前写死 return 0,属假绿)
|
||
v = Verdict("probe_prod(生产上传拒绝路径 / CORS)")
|
||
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]}")
|
||
v.check(f"生产头像:{fn} 应被拒", st != 200, f"status={st}")
|
||
|
||
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]}")
|
||
v.check(f"生产反馈图:{fn} 应{expect}", (st != 200) if expect == "拒" else (st == 200),
|
||
f"status={st}")
|
||
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 白名单 =====")
|
||
# ⚠️ CORS 只作观察:是否回 `access-control-allow-origin` 还取决于浏览器语义与后端实现口径,
|
||
# 写成硬判据容易误报 ⇒ 保持观察输出(误报与假绿同样有害)。
|
||
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 v.exit_code() # 0=判据全过,1=有判据失败
|
||
|
||
|
||
if __name__ == "__main__":
|
||
raise SystemExit(main())
|