fix(backend): 复查修复(一码两单 / 回调重放 / 跨进程覆盖 / sweep 误删 等)+ 回执

Browse Source
- submit/activate:查码与绑码同锁(redeem_bind),防并发一码两单
- submit:卡密规则按 max(前端 nTotal, 实际模板数) 与模板并集校验;拒未知模板
- 爱发电回调:发码或激活过一律幂等原样回;回调与账本读写串行(HOOK_LOCK)
- LOCK 加跨进程 flock;jsave 唯一临时文件 + fsync + 沿用权限
- admin.py sweep 不删 waiting/working/paid;retry 加锁
- 卡密/订单号/取件码改用 secrets
- redo 换皮肤走 PNG 核验;feedback 限频 + 磁盘闸 + 只收图片
- 下载/取皮肤边读边发;zip 成品 STORED + 同时只打一个包
- H.finish 与 socketserver.finish 重名 → 改名 finish_upload(路径不变)
- 部分失败:记 plan_total/partial,通知金钻,页面说实话
- /claim 新增 terms_v 字段(只增,渲染机无需改)
- ys_local.py:只接受本机页面的 POST(Host/Origin 校验)
- 两份 回执-Claude.md + tests/回执复现测试.py(原版 13/27 失败,改后全过)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
yws
2026-10-05 12:14:02 +00:00
co-authored by Claude Opus 5.5
parent 11eb16ccae
commit 651d21d882
6 changed files with 1164 additions and 116 deletions
@@ -0,0 +1,281 @@
# -*- coding: utf-8 -*-
"""网站后端回归 + 漏洞复现测试(自己造的假皮肤,不碰任何真实数据)。
用法:python3 tests/回执复现测试.py <server.py 所在目录>
(交付副本里三个 URL 格式串被脱敏弄坏了,跑之前要先把它们换成能格式化的占位;线上原版可以直接跑)
· 会在系统临时目录建一份独立数据目录,不碰 <DATA_DIR>;测试机上没有水印字体,预览那一步用「拷一份」代替。
· 在临时目录里起一份 server(随机端口),从 HTTP 层打接口;
· 每条用例各用一份新数据(不复用,免得"第一条就把码用掉");
· 输出每条 PASS / FAIL;对原版跑一遍能看到哪些洞真实存在。
"""
import base64, io, json, os, struct, subprocess, sys, tempfile, threading, time, urllib.request, urllib.error, zipfile, zlib
SRC = os.path.abspath(sys.argv[1])
ROOT = tempfile.mkdtemp(prefix="ys-test-")
os.environ["YS_ROOT"] = ROOT
sys.path.insert(0, SRC)
import server as S # noqa: E402
RESULTS = []
def check(name, cond, detail=""):
RESULTS.append((name, bool(cond), detail))
print(("PASS " if cond else "FAIL ") + name + ((" —— " + detail) if detail else ""), flush=True)
# ------------------------------------------------------------------ 假皮肤
def png(w=64, h=64, tail=b"", extra_chunk=None, seed=0):
raw = b"".join(b"\x00" + b"".join(bytes(((x * 7 + y * 3 + seed) % 256, (x + seed) % 256, y % 256, 255))
for x in range(w)) for y in range(h))
def chunk(t, d):
return struct.pack(">I", len(d)) + t + d + struct.pack(">I", zlib.crc32(t + d) & 0xffffffff)
out = b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", w, h, 8, 6, 0, 0, 0))
if extra_chunk:
out += chunk(*extra_chunk)
out += chunk(b"IDAT", zlib.compress(raw)) + chunk(b"IEND", b"")
return out + tail
def durl(b):
return "data:image/png;base64," + base64.b64encode(b).decode()
# ------------------------------------------------------------------ 起服务
srv = S.ThreadingHTTPServer(("127.0.0.1", 0), S.H)
srv.daemon_threads = True
PORT = srv.server_address[1]
threading.Thread(target=srv.serve_forever, daemon=True).start()
BASE = "http://127.0.0.1:%d" % PORT
def req(method, path, obj=None, headers=None, raw=False, timeout=30):
data = json.dumps(obj).encode() if obj is not None else None
r = urllib.request.Request(BASE + path, data=data, method=method)
r.add_header("Content-Type", "application/json")
for k, v in (headers or {}).items():
r.add_header(k, v)
try:
with urllib.request.urlopen(r, timeout=timeout) as resp:
body = resp.read()
return resp.status, (body if raw else json.loads(body)), dict(resp.headers)
except urllib.error.HTTPError as e:
body = e.read()
try:
return e.code, (body if raw else json.loads(body)), dict(e.headers)
except ValueError:
return e.code, body, dict(e.headers)
WK = {"X-Worker-Token": S.WT}
TERMS = {"v": S.TERMS_VERSION, "agreed": True}
_ip_n = [0]
def new_ip():
"""每条用例换一个来源 IP(X-Real-IP),免得被「同 IP 10 分钟 6 单」的限流串了用例。"""
_ip_n[0] += 1
return {"X-Real-IP": "198.51.100.%d" % _ip_n[0]}
def submit(codes, templates, ip=None, **kw):
body = {"skin": durl(png(seed=len(codes) + len(templates))), "fileName": "test.png", "arm": "classic",
"templates": templates, "res": 1000, "codes": codes, "terms": TERMS}
body.update(kw)
return req("POST", "/api/submit", body, ip or new_ip())
def fake_preview(oid, png_path, out_name, idx=0):
"""测试机没有水印字体 / ffmpeg:预览直接拷一份,只为让「水印闸门」放行。"""
rel = "out/prev_%02d.jpg" % int(idx)
with open(png_path, "rb") as a, open(os.path.join(S.order_dir(oid), rel), "wb") as b:
b.write(a.read())
return rel
S.make_preview = fake_preview
# ================================================================== 1. 正常链路(回归)
code = S.gen_codes(1)[0]
st, j, _ = submit([code], ["stand"])
check("回归:卡密单提交成功", st == 200 and j.get("ok"), str(j)[:120])
oid, tok = j.get("order"), j.get("token")
st, j, _ = req("POST", "/api/claim", {}, WK)
check("回归:渲染机领到这一单", st == 200 and (j.get("order") or {}).get("oid") == oid, str(j)[:120])
claimed = j.get("order") or {}
check("新增字段:claim 带 terms_v(订单同意的条款版本)", claimed.get("terms_v") == S.TERMS_VERSION,
"terms_v=%r" % claimed.get("terms_v"))
st, b, h = req("GET", "/api/skin/%s/s1" % oid, headers=WK, raw=True)
check("回归:渲染机取得到皮肤(流式发送后内容不变)", st == 200 and b[:8] == b"\x89PNG\r\n\x1a\n"
and int(h.get("Content-Length", -1)) == len(b))
big = png(256, 256) + b"" # 成品
for name in ("站立正反.png", "站立正反无压缩.png"):
st, j, _ = req("POST", "/api/finish", {"oid": oid, "total": 2,
"results": [{"tpl": "stand", "name": name, "png": base64.b64encode(big).decode(),
"skin": "s1", "sec": 30}]}, WK)
check("回归:回传两张后订单完成", j.get("done") is True, str(j)[:120])
st, j, _ = req("GET", "/api/order/%s?t=%s" % (oid, tok))
check("回归:订单详情可读、两张文件", st == 200 and len(j.get("files") or []) == 2, str(j.get("state")))
st, j, _ = req("POST", "/api/accept", {"oid": oid, "token": tok})
check("回归:确认收货", j.get("accepted") is True)
st, b, h = req("GET", "/api/dl/%s/0?t=%s" % (oid, tok), raw=True)
check("回归:下载原图(流式)字节一致、带附件头", st == 200 and b == big and "attachment" in h.get("Content-Disposition", ""),
"len=%d" % len(b))
st, b, h = req("GET", "/api/zip/%s?t=%s" % (oid, tok), raw=True)
zok = False
if st == 200:
z = zipfile.ZipFile(io.BytesIO(b))
names = z.namelist()
zok = "小票.txt" in names and len(names) == 3 and z.read(names[1]) == big
check("回归:整单打包 zip 内容完整", zok, "status=%s" % st)
# 网页单(先填后付)→ 用平台卡密激活
st, j, _ = submit([], ["wheat"], pay="prepay")
check("回归:网页下单(待付款)", st == 200 and j.get("prepay") is True, str(j)[:100])
p_oid, p_tok = j.get("order"), j.get("token")
c2 = S.gen_codes(1)[0]
st, j, _ = req("POST", "/api/activate", {"oid": p_oid, "token": p_tok, "code": c2}, new_ip())
check("回归:网页单用卡密激活进队列", j.get("state") == "waiting", str(j)[:100])
# ================================================================== 2. 一码两单(并发提交同一张码)
dup = S.gen_codes(1)[0]
outs = []
def _go():
outs.append(submit([dup], ["stand"]))
ths = [threading.Thread(target=_go) for _ in range(6)]
[t.start() for t in ths]
[t.join() for t in ths]
okn = sum(1 for st, j, _ in outs if st == 200 and j.get("ok"))
check("洞:同一张码并发提交 6 次,只能成 1 单", okn == 1, "成功了 %d 单" % okn)
# ================================================================== 3. 张数 / 锁模板 绕过
c1 = S.gen_codes(1, n_fix=1)[0]
st, j, _ = submit([c1], ["stand", "standb", "wheat", "beach", "boom", "sakura", "airship"], nTotal=1, tplUnion=["stand"])
check("洞:「固定 1 张」的码报 nTotal=1、实际塞 7 个模板 → 必须拒", not (st == 200 and j.get("ok")),
"server 说:%s" % (j.get("error") if isinstance(j, dict) else j))
cl = S.gen_codes(1, tpl="stand", lock_tpl=True, n_max=5)[0]
st, j, _ = submit([cl], ["airship"], nTotal=1, tplUnion=["stand"])
check("洞:锁定「站立正反」的码,报 tplUnion=stand、实际出空艇 → 必须拒", not (st == 200 and j.get("ok")),
"server 说:%s" % (j.get("error") if isinstance(j, dict) else j))
cn = S.gen_codes(1, n_fix=3)[0]
st, j, _ = submit([cn], ["stand", "wheat"], nTotal=3, tplUnion=["stand", "wheat", "beach"])
check("回归:多皮肤单(第 1 张 2 个模板,整单报 3 张)照常能交", st == 200 and j.get("ok"), str(j)[:100])
st, j, _ = submit([S.gen_codes(1)[0]], ["notatpl"])
check("加固:不认识的模板 key 在提交时就拒(不等渲染机报错)", not (st == 200 and j.get("ok")), str(j)[:80])
# ================================================================== 4. 爱发电回调重放
st, j, _ = submit([], ["stand"], pay="prepay")
h_oid, h_tok = j.get("order"), j.get("token")
real = {"out_trade_no": "202610050000000000000000001", "status": 2, "total_amount": "6.00", "show_amount": "6.00",
"remark": "", "custom_order_id": h_oid, "user_id": "u1", "sku_detail": [{"name": "x", "count": 1}],
"plan_title": "渲染", "title": ""}
S.payplatform_find_order = lambda no, pages=3: dict(real) if no == real["out_trade_no"] else None
hook_body = {"ec": 200, "em": "ok", "data": {"type": "order", "order": dict(real)}}
n0 = len(S.load_codes())
st, j1, _ = req("POST", "/api/payplatform-hook", hook_body)
m = S.read_meta(h_oid)
check("回归:回调对上网页单并激活", m and m.get("state") == "waiting", "state=%s" % (m or {}).get("state"))
n1 = len(S.load_codes())
st, j2, _ = req("POST", "/api/payplatform-hook", hook_body) # 原样重放(平台重试 / 别人照抄)
n2 = len(S.load_codes())
c2txt = ((j2 or {}).get("data") or {}).get("content") or ""
check("洞:同一笔付款回调重放,不能再发码", n2 == n1 and "卡密" not in c2txt,
"重放前 %d 张码、重放后 %d 张;返回:%s" % (n1, n2, c2txt[:40].replace("\n", " ")))
# 第二张待付款单 + 用同一笔付款的报文、把 custom_order_id 改成它
st, j, _ = submit([], ["stand"], pay="prepay")
h2 = j.get("order")
forged = json.loads(json.dumps(hook_body))
forged["data"]["order"]["custom_order_id"] = h2
real2 = dict(real)
real2.pop("custom_order_id")
S.payplatform_find_order = lambda no, pages=3: dict(real2) if no == real["out_trade_no"] else None
req("POST", "/api/payplatform-hook", forged)
m2 = S.read_meta(h2)
check("洞:同一笔付款改报文里的订单号,不能再激活另一单", (m2 or {}).get("state") in ("unpaid", "paid"),
"第二单状态=%s" % (m2 or {}).get("state"))
# ================================================================== 5. 重渲换皮肤绕过 PNG 核验
st, j, _ = submit([S.gen_codes(1)[0]], ["stand"])
r_oid, r_tok = j["order"], j["token"]
S.write_meta(r_oid, dict(S.read_meta(r_oid), state="done"))
evil = png(tail=b"<<hidden payload>>")
st, j, _ = req("POST", "/api/redo", {"oid": r_oid, "token": r_tok, "skin": durl(evil), "skin_id": "s1", "all": 1})
saved = b""
try:
saved = open(os.path.join(S.order_dir(r_oid), "skins", "s1.png"), "rb").read()
except OSError:
pass
check("洞:重渲换皮肤夹带尾部数据 → 必须拒、不能落盘", not (st == 200 and j.get("ok")) and b"hidden" not in saved,
"server 说:%s" % (j.get("error") if isinstance(j, dict) else j))
st, j, _ = submit([S.gen_codes(1)[0]], ["stand"])
r2, t2 = j["order"], j["token"]
S.write_meta(r2, dict(S.read_meta(r2), state="done"))
st, j, _ = req("POST", "/api/redo", {"oid": r2, "token": t2, "skin": durl(png(seed=9)), "skin_id": "s1", "all": 1})
check("回归:重渲换一张正常皮肤照常可以", st == 200 and j.get("ok"), str(j)[:80])
# ================================================================== 6. 反馈接口灌盘
ip = new_ip()
codes_ = []
for i in range(7):
st, j, _ = req("POST", "/api/feedback", {"note": "测试 %d" % i, "image": durl(png(seed=i))}, ip)
codes_.append(st)
check("洞:同一 IP 连发 7 条反馈要被限流", 429 in codes_, "状态码:%s" % codes_)
st, j, _ = req("POST", "/api/feedback", {"note": "x", "image": "data:image/png;base64," + base64.b64encode(b"MZ\x90\x00not an image").decode()}, new_ip())
fb = [f for f in os.listdir(os.path.join(ROOT, "feedback")) if not f.endswith(".json")]
check("加固:反馈里的「图片」不是图片就不收", not any(open(os.path.join(ROOT, "feedback", f), "rb").read().startswith(b"MZ") for f in fb))
# ================================================================== 7. 部分失败要响亮
st, j, _ = submit([S.gen_codes(1, n_fix=2)[0]], ["stand", "wheat"], nTotal=2)
q_oid, q_tok = j["order"], j["token"]
for _ in range(5):
st, j, _ = req("POST", "/api/claim", {}, WK)
if (j.get("order") or {}).get("oid") == q_oid:
break
req("POST", "/api/finish", {"oid": q_oid, "total": 4, "results": [{"tpl": "stand", "name": "站立正反.png",
"png": base64.b64encode(big).decode(), "skin": "s1"}]}, WK)
req("POST", "/api/finish", {"oid": q_oid, "close": True, "note": "部分失败:麦田萤火 渲染卡住", "results": []}, WK)
st, j, _ = req("GET", "/api/order/%s?t=%s" % (q_oid, q_tok))
calls = open(S.CALLS_FILE, encoding="utf-8").read() if os.path.exists(S.CALLS_FILE) else ""
check("静默失败:4 个文件只交回 1 个 → 页面要说实话(缺 3 个)+ 呼叫金钻", "有 3 个文件没渲出来" in (j.get("note") or "") and q_oid in calls,
"页面文案:%s" % (j.get("note") or "")[:40])
# ================================================================== 8. sweep 不许删流水线上的单
st, j, _ = submit([S.gen_codes(1)[0]], ["stand"])
w_oid = j["order"]
mm = S.read_meta(w_oid)
mm["created"] = (S.now() - S.timedelta(days=5)).isoformat(timespec="seconds")
S.write_meta(w_oid, mm) # 排队中,但已经是 5 天前的单(渲染机关了几天)
sw = subprocess.run([sys.executable, os.path.join(SRC, "admin.py"), "sweep"], capture_output=True, text=True,
env=dict(os.environ, YS_ROOT=ROOT), cwd=SRC, timeout=60)
check("洞:渲染机关了 5 天,排队中的单不能被 sweep 删掉", os.path.isdir(S.order_dir(w_oid)),
(sw.stdout or sw.stderr).strip()[-80:])
# ================================================================== 9. 跨进程:CLI 发码 与 服务器绑码 同时进行
before = set(S.load_codes())
child = subprocess.Popen([sys.executable, "-c",
"import sys;sys.path.insert(0,%r);import server as S\n"
"for _ in range(40): S.gen_codes(5, batch='cli')" % SRC],
env=dict(os.environ, YS_ROOT=ROOT), cwd=SRC)
mine = S.gen_codes(30, batch="pre")
bound_ok = 0
for c in mine:
st, j, _ = submit([c], ["stand"])
bound_ok += 1 if (st == 200 and j.get("ok")) else 0
child.wait(timeout=300)
after = S.load_codes()
cli_n = sum(1 for c, r in after.items() if r.get("batch") == "cli")
still_active = [c for c in mine if (after.get(c) or {}).get("state") != "bound"]
check("洞:CLI 一边发码、服务器一边下单 —— 发出去的码一张不少", cli_n == 200, "CLI 发了 200 张,文件里有 %d 张" % cli_n)
check("洞:同时进行时,已下单的码不能被改回「可用」", not still_active, "被冲回去的码 %d 张(下单成功 %d 单)" % (len(still_active), bound_ok))
# ================================================================== 汇总
srv.shutdown()
bad = [n for n, ok, _ in RESULTS if not ok]
print("\n%d 条,失败 %d 条" % (len(RESULTS), len(bad)))
for n in bad:
print(" ✗ " + n)