- backend-site/cms.py(新):账号(scrypt 加盐哈希)、服务端会话(只存哈希,30 天滑动,可撤销)、 admin/admin 首次登录强制改密(改密前其它接口一律 403)、CSRF / 来源 / https / 登录冷却、 内容校验、发布写 content/ 与 prices.json / payinfo.json、版本与回滚、传图核验 + 去元数据 + ffmpeg 缩略图 - server.py 把 /api/cms/* 交给 cms.py;admin.py 加 user list/add/passwd/reset/disable/enable/sessions - portal/admin/(新):内容后台页面;门户顶栏加不带字的淡色铅笔入口 - 门户 / 下单页读 content/site.js、order/content/order.js(代码里的数据降级为兜底);?preview=1 预览草稿 - portal/assets/universe/layout.js(新):新点亮的世界线自动排到中圈不挤的位置、补给线接附近的星、已有的都不动 - planets.js:加 10 种卡通预设(类地 / 海洋 / 丛林 / 荒漠 / 冻原 / 熔岩 / 毒雾 / 荒芜岩球 / 冰巨星 / 带环巨星) - galaxy.js:名牌 / 档案卡文字一律转义 - tests/内容后台测试.py(75 条);回归 27 + 数据库 38 照旧全过;端到端浏览器 36 条 - 文档:交接文档-2026-10.md(变更 / 接口 / 部署 7.1b / 测试 / 第 10 节)、内容后台设计.md(实现对照)、星系图交接说明、nginx 片段 ④ Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
339 lines
22 KiB
Python
339 lines
22 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""内容后台(cms.py)测试 —— 数据全是这里现编的,不碰任何真实环境。
|
||
|
||
用法:python3 tests/内容后台测试.py <server.py 所在目录> [仓库根目录]
|
||
· 交付副本里三个 URL 格式串被脱敏弄坏了(http<WIN-PATH>),跑之前先换成能格式化的占位(同另外两份测试);
|
||
· 会在临时目录建数据目录 + 门户 / 下单页目录(从仓库拷 content/ 当初始内容),起一份 server,从 HTTP 层打接口;
|
||
· 需要 ffmpeg 才测得到「缩略图生成」那一条(没有就测「退回用原图」)。
|
||
"""
|
||
import base64, json, os, re, shutil, sqlite3, struct, subprocess, sys, tempfile, threading, time, urllib.request, urllib.error, zlib
|
||
|
||
SRC = os.path.abspath(sys.argv[1])
|
||
REPO = os.path.abspath(sys.argv[2]) if len(sys.argv) > 2 else os.path.abspath(os.path.join(SRC, "..", ".."))
|
||
TMP = tempfile.mkdtemp(prefix="ys-cms-")
|
||
ROOT, PORTAL, ORDER = os.path.join(TMP, "data"), os.path.join(TMP, "www"), os.path.join(TMP, "www", "order")
|
||
os.makedirs(ROOT); os.makedirs(PORTAL); os.makedirs(ORDER)
|
||
shutil.copytree(os.path.join(REPO, "portal", "content"), os.path.join(PORTAL, "content"))
|
||
shutil.copytree(os.path.join(REPO, "order", "content"), os.path.join(ORDER, "content"))
|
||
os.environ.update(YS_ROOT=ROOT, YS_PORTAL_DIR=PORTAL, YS_ORDER_DIR=ORDER)
|
||
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 + ((" —— " + str(detail)[:160]) if detail else ""), flush=True)
|
||
|
||
|
||
srv = S.ThreadingHTTPServer(("127.0.0.1", 0), S.H)
|
||
srv.daemon_threads = True
|
||
threading.Thread(target=srv.serve_forever, daemon=True).start()
|
||
BASE = "http://127.0.0.1:%d/api/cms/" % srv.server_address[1]
|
||
|
||
|
||
class C(object):
|
||
"""一个「浏览器」:自己记 Cookie 和 CSRF。默认走「反代 + https」的请求头。"""
|
||
def __init__(self, ip="203.0.113.10", proto="https", origin=None):
|
||
self.cookie, self.csrf, self.ip, self.proto, self.origin = None, "", ip, proto, origin
|
||
|
||
def req(self, ep, body=None, headers=None, raw=None):
|
||
data = raw if raw is not None else (json.dumps(body).encode() if body is not None else None)
|
||
r = urllib.request.Request(BASE + ep, data=data, method="POST" if data is not None else "GET")
|
||
r.add_header("Content-Type", "application/json")
|
||
r.add_header("Host", "shop.example.com")
|
||
if self.ip:
|
||
r.add_header("X-Real-IP", self.ip)
|
||
if self.proto:
|
||
r.add_header("X-Forwarded-Proto", self.proto)
|
||
if self.origin:
|
||
r.add_header("Origin", self.origin)
|
||
if self.cookie:
|
||
r.add_header("Cookie", "jz_cms=" + self.cookie)
|
||
if data is not None and self.csrf:
|
||
r.add_header("X-CSRF", self.csrf)
|
||
for k, v in (headers or {}).items():
|
||
r.add_header(k, v)
|
||
try:
|
||
with urllib.request.urlopen(r, timeout=60) as resp:
|
||
st, hd, b = resp.status, resp.headers, resp.read()
|
||
except urllib.error.HTTPError as e:
|
||
st, hd, b = e.code, e.headers, e.read()
|
||
for sc in hd.get_all("Set-Cookie") or []:
|
||
m = re.match(r"jz_cms=([^;]*)", sc)
|
||
if m:
|
||
self.cookie = m.group(1) or None
|
||
self.last_cookie = sc
|
||
try:
|
||
j = json.loads(b.decode("utf-8"))
|
||
except ValueError:
|
||
j = {"_raw": b.decode("utf-8", "replace")}
|
||
if isinstance(j, dict) and j.get("csrf"):
|
||
self.csrf = j["csrf"]
|
||
return st, j
|
||
|
||
def login(self, user, pw, remember=True):
|
||
return self.req("login", {"user": user, "password": pw, "remember": remember})
|
||
|
||
|
||
def db():
|
||
return sqlite3.connect(os.path.join(ROOT, "ys.db"))
|
||
|
||
|
||
NEWPW = "Jz-内容后台-2026!"
|
||
# ================================================================== 1. 首次启动 / 初始账号
|
||
rows = db().execute("SELECT username, must_change, pw FROM cms_users").fetchall()
|
||
check("首次启动:自动建了唯一一个初始账号 admin,标了必须改密", len(rows) == 1 and rows[0][0] == "admin" and rows[0][1] == 1, rows and rows[0][:2])
|
||
check("初始密码存的是 scrypt 哈希,不是明文", rows and rows[0][2].startswith(("scrypt$", "pbkdf2$")) and rows[0][2] != "admin", rows and rows[0][2][:10])
|
||
|
||
# ================================================================== 2. 登录
|
||
a = C()
|
||
st, j = a.login("admin", "wrong-pass")
|
||
check("错密码 → 401「账号或密码不对」", st == 401 and j.get("error") == "账号或密码不对", j)
|
||
st, j = C(ip="203.0.113.11").login("nobody", "whatever")
|
||
check("不存在的账号 → 同样的提示(不透露账号在不在)", st == 401 and j.get("error") == "账号或密码不对", j)
|
||
st, j = a.login("admin", "admin")
|
||
check("admin / admin 能登录,回 must_change", st == 200 and j.get("must_change") is True, j)
|
||
ck = getattr(a, "last_cookie", "")
|
||
check("Cookie:HttpOnly + SameSite=Strict + https 下 Secure + 记住我 30 天", all(x in ck for x in ("HttpOnly", "SameSite=Strict", "Secure", "Max-Age=2592000")), ck)
|
||
|
||
# ================================================================== 3. 强制改密前:服务端只放行 me / password / logout
|
||
blocked = []
|
||
for ep, body in (("content", None), ("versions", None), ("audit", None), ("sessions", None), ("draft.js", None), ("draft", {"doc": {}}),
|
||
("publish", {}), ("rollback", {"no": 1}), ("upload", {"data": "x"}), ("discard", {}), ("sessions/revoke", {"others": True})):
|
||
st, j = a.req(ep, body)
|
||
if not (st == 403 and j.get("must_change")):
|
||
blocked.append((ep, st))
|
||
check("改密前:其它 11 个接口一律 403「请先修改初始密码」", not blocked, blocked)
|
||
st, j = a.req("me")
|
||
check("改密前:me 照常能用", st == 200 and j.get("must_change") is True)
|
||
st, j = a.req("password", {"old": "admin", "new": "12345678"})
|
||
check("新密码太常见 → 拒", st == 400 and "常见" in j.get("error", ""), j)
|
||
st, j = a.req("password", {"old": "admin", "new": "short"})
|
||
check("新密码太短 → 拒", st == 400 and "8" in j.get("error", ""), j)
|
||
st, j = a.req("password", {"old": "admin", "new": "admin"})
|
||
check("新密码是 admin → 拒", st == 400, j)
|
||
st, j = a.req("password", {"old": "bad", "new": NEWPW})
|
||
check("旧密码不对 → 拒", st == 400 and "现在的密码" in j.get("error", ""), j)
|
||
old_cookie = a.cookie
|
||
st, j = a.req("password", {"old": "admin", "new": NEWPW})
|
||
check("首次改密成功 → 要求重新登录", st == 200 and j.get("relogin") is True, j)
|
||
a2 = C(); a2.cookie = old_cookie
|
||
st, _ = a2.req("me")
|
||
check("首次改密后:原来那个会话立即作废", st == 401)
|
||
# ⚠️ 不能在本进程里 open() 库文件:POSIX 规定关掉任何一个句柄会释放本进程对这个文件的所有锁,SQLite 的锁会被顺带清掉。
|
||
# 所以用另一个进程(cat)去读。
|
||
raw_db = subprocess.run(["cat", os.path.join(ROOT, "ys.db")] + ([os.path.join(ROOT, "ys.db-wal")] if os.path.exists(os.path.join(ROOT, "ys.db-wal")) else []), capture_output=True).stdout
|
||
check("库文件(含 WAL)里找不到新密码明文", NEWPW.encode("utf-8") not in raw_db)
|
||
st, j = a.login("admin", NEWPW)
|
||
check("新密码登录 → 不再要求改密", st == 200 and j.get("must_change") is False, j)
|
||
|
||
# ================================================================== 4. 安全闸:https / CSRF / 来源 / 爆破
|
||
st, j = C(ip="203.0.113.20", proto="http").login("admin", NEWPW)
|
||
check("经反代但不是 https → 403,不收密码", st == 403 and "https" in j.get("error", ""), j)
|
||
st, j = C(ip="203.0.113.21", proto=None).login("admin", NEWPW)
|
||
check("经反代但没带 X-Forwarded-Proto → 也当成不是 https 拒掉", st == 403, j)
|
||
loc = C(ip=None, proto=None)
|
||
st, j = loc.login("admin", NEWPW)
|
||
check("服务器本机直连(调试)可以 http;这时 Cookie 不带 Secure", st == 200 and "Secure" not in getattr(loc, "last_cookie", ""), getattr(loc, "last_cookie", ""))
|
||
csrf = a.csrf; a.csrf = ""
|
||
st, j = a.req("draft", {"doc": {}})
|
||
check("修改类请求不带 X-CSRF → 403", st == 403, j)
|
||
a.csrf = "forged"
|
||
st, j = a.req("draft", {"doc": {}})
|
||
check("X-CSRF 不对 → 403", st == 403, j)
|
||
a.csrf = csrf
|
||
a.origin = "https://evil.example"
|
||
st, j = a.req("discard", {})
|
||
check("跨站来源(Origin 不是本站)→ 403", st == 403 and "来源" in j.get("error", ""), j)
|
||
a.origin = "https://shop.example.com"
|
||
st, j = a.req("discard", {})
|
||
check("同站来源照常", st == 200, j)
|
||
a.origin = None
|
||
bf = C(ip="198.51.100.66")
|
||
codes = [bf.login("admin", "guess%d" % k)[0] for k in range(7)]
|
||
check("同一 IP 连错 5 次后开始冷却 → 429", codes[:5] == [401] * 5 and 429 in codes[5:], codes)
|
||
st, j = C(ip="198.51.100.77").login("admin", NEWPW)
|
||
check("别的 IP 乱试几次,店主从自己的网络用对密码照常能登(不能一键把人锁在门外)", st == 200, st)
|
||
codes = [C(ip="192.0.2.%d" % k).login("admin", "spread%d" % k)[0] for k in range(22)]
|
||
check("分散在很多 IP 上慢慢试:同一账号合计错满 20 次也冷却", 429 in codes[20:], codes[-4:])
|
||
for k in list(S.CMS.fails): # 清掉冷却记录,后面的用例要正常登录
|
||
S.CMS.fails.pop(k, None)
|
||
|
||
# ================================================================== 5. 内容:读 / 存草稿 / 校验
|
||
st, j = a.req("content")
|
||
check("读内容:第 1 版 = 从网站现有内容文件导入", st == 200 and j.get("version") == 1 and j["published"]["site"]["links"], j.get("version"))
|
||
doc = j["draft"]
|
||
bad = json.loads(json.dumps(doc)); bad["site"]["links"][0]["url"] = "http://example.com/x"
|
||
st, j = a.req("draft", {"doc": bad, "base": 1})
|
||
check("校验:平台链接用 http:// → 拒,并说清是哪一个", st == 400 and "https" in j.get("error", "") and "平台入口第 1 个" in j.get("error", ""), j)
|
||
bad = json.loads(json.dumps(doc)); bad["site"]["links"][0]["url"] = "javascript:alert(1)"
|
||
st, j = a.req("draft", {"doc": bad, "base": 1})
|
||
check("校验:javascript: 链接 → 拒", st == 400, j)
|
||
bad = json.loads(json.dumps(doc)); bad["site"]["gallery"][0]["src"] = "../../etc/passwd"
|
||
st, j = a.req("draft", {"doc": bad, "base": 1})
|
||
check("校验:图片路径想往上跳目录 → 拒", st == 400, j)
|
||
bad = json.loads(json.dumps(doc)); bad["order"]["templates"] = [dict(t, on=False) for t in bad["order"]["templates"]]
|
||
st, j = a.req("draft", {"doc": bad, "base": 1})
|
||
check("校验:模板全部下架 → 拒(至少留一个)", st == 400 and "至少" in j.get("error", ""), j)
|
||
bad = json.loads(json.dumps(doc)); bad["order"]["templates"].append({"k": "notatpl", "n": "x", "s": "", "on": True})
|
||
st, j = a.req("draft", {"doc": bad, "base": 1})
|
||
check("校验:不认识的模板 key → 拒(后台不能新增模板)", st == 400, j)
|
||
bad = json.loads(json.dumps(doc)); bad["site"]["universe"]["items"][1]["look"]["style"] = "unknownstyle"
|
||
st, j = a.req("draft", {"doc": bad, "base": 1})
|
||
check("校验:不认识的星球风格 → 拒", st == 400, j)
|
||
bad = json.loads(json.dumps(doc)); bad["site"]["hero"]["tagline"] = "长" * 200
|
||
st, j = a.req("draft", {"doc": bad, "base": 1})
|
||
check("校验:超长 → 拒,并说清多长", st == 400 and "最多 160" in j.get("error", ""), j)
|
||
|
||
XSS = '</script><script>alert(1)</script><img src=x onerror=alert(2)>'
|
||
good = json.loads(json.dumps(doc))
|
||
good["site"]["hero"]["tagline"] = "首页改一句 " + XSS[:40]
|
||
good["site"]["hero"]["notice"] = {"on": True, "text": "国庆照常营业", "from": "", "to": ""}
|
||
good["site"]["links"][0]["name"] = "哔哩哔哩" + "<b>x</b>"
|
||
good["site"]["universe"]["items"].append({"no": "0005", "name": "新地球", "kind": "原创", "tag": "卡通地球", "desc": XSS, "tags": ["新"], "look": {"style": "earth", "accent": "#7FE0A8", "enter": "push"}})
|
||
good["order"]["templates"][-1]["on"] = False
|
||
good["order"]["prices"] = {"per": 6, "tiers": [{"n": 3, "price": 15, "url": "https://example.com/afdian/3"}]}
|
||
good["order"]["pay"]["note"] = "付款时留言写订单号"
|
||
st, j = a.req("draft", {"doc": good, "base": 1})
|
||
check("存草稿:合格的内容存上,返回改了哪些板块", st == 200 and any(c[0] == "金钻宇宙" for c in j.get("changes", [])), j.get("changes"))
|
||
st, j = a.req("content")
|
||
check("草稿存在库里,网站上(已发布)还是原样", j.get("has_draft") and j["published"]["site"]["hero"]["tagline"] != good["site"]["hero"]["tagline"])
|
||
|
||
# ================================================================== 6. 预览草稿(要登录)
|
||
st, j = C(ip="203.0.113.30").req("draft.js")
|
||
check("预览草稿:没登录 → 401", st == 401)
|
||
st, j = a.req("draft.js")
|
||
body = j.get("_raw", "")
|
||
check("预览草稿:登录了 → 拿到草稿内容 + JZ_PREVIEW", st == 200 and "window.JZ_PREVIEW = true" in body and "新地球" in body)
|
||
check("预览草稿:</script> 被转义,塞不进脚本", "</script>" not in body.split("window.JZ_CONTENT = ", 1)[1].split("window.JZ_PREVIEW")[0], body[:80])
|
||
|
||
# ================================================================== 7. 发布 / 冲突 / 回滚
|
||
st, j = a.req("publish", {"note": "测试发布", "base": 1})
|
||
check("发布 → v2", st == 200 and j.get("version") == 2, j)
|
||
site_js = open(os.path.join(PORTAL, "content", "site.js"), encoding="utf-8").read()
|
||
order_js = open(os.path.join(ORDER, "content", "order.js"), encoding="utf-8").read()
|
||
check("发布写出门户 site.js:有新世界线、</script> 被转义", "新地球" in site_js and "</script>" not in site_js.split("=", 1)[1], site_js[:120])
|
||
check("发布写出 site.json(正本)", json.load(open(os.path.join(PORTAL, "content", "site.json"), encoding="utf-8"))["hero"]["notice"]["on"] is True)
|
||
check("发布写出下单页 order.js:最后一个模板已下架", '"on":false' in order_js)
|
||
pr = json.load(open(S.PRICES_FILE, encoding="utf-8")); pay = json.load(open(S.PAYINFO_FILE, encoding="utf-8"))
|
||
check("价格档位写回 prices.json(server.py 原来的格式)", pr.get("per") == 6 and pr.get("tiers", {}).get("3", {}).get("price") == 15, pr)
|
||
check("付款方式写回 payinfo.json", pay.get("note") == "付款时留言写订单号", pay)
|
||
check("下单页的价格接口立刻反映新档位", S.price_for(3) == 15)
|
||
lit = [x for x in json.loads(site_js.split("window.JZ_CONTENT = ", 1)[1].rsplit(";", 1)[0])["universe"]["UNIVERSES"] if not x.get("empty")]
|
||
check("星系图数据:新世界线没写位置(交给 layout.js 自动排)", any(x["no"] == "0005" for x in lit))
|
||
b = C(ip="203.0.113.40"); b.login("admin", NEWPW)
|
||
st, j = b.req("content")
|
||
d2 = j["draft"]; d2["site"]["hero"]["cta1"] = "看看画"
|
||
st, j = b.req("draft", {"doc": d2, "base": 1}) # 故意拿旧底稿
|
||
st, j = b.req("publish", {"base": 1})
|
||
check("别人已经发布过(底稿是旧版)→ 409 冲突,不静默覆盖", st == 409 and j.get("conflict"), j)
|
||
st, j = b.req("publish", {"base": 2})
|
||
check("刷新到新底稿再发 → v3", st == 200 and j.get("version") == 3, j)
|
||
st, j = a.req("rollback", {"no": 1})
|
||
check("回到 v1 → 记为 v4", st == 200 and j.get("version") == 4, j)
|
||
v1 = json.loads(db().execute("SELECT data FROM cms_versions WHERE no=1").fetchone()[0])
|
||
v4 = json.loads(db().execute("SELECT data FROM cms_versions WHERE no=4").fetchone()[0])
|
||
check("回滚后内容和 v1 一模一样", v1 == v4)
|
||
check("回滚后网站文件也回去了(没有新地球)", "新地球" not in open(os.path.join(PORTAL, "content", "site.js"), encoding="utf-8").read())
|
||
st, j = a.req("versions")
|
||
check("发布记录 4 条,带改动摘要", st == 200 and len(j.get("versions", [])) == 4 and j["versions"][0]["chg"], j.get("versions", [{}])[0])
|
||
|
||
# ================================================================== 8. 传图
|
||
def png(w=64, h=48, tail=b""):
|
||
raw = b"".join(b"\x00" + b"".join(bytes(((x * 3) % 256, (y * 5) % 256, 120, 255)) for x in range(w)) for y in range(h))
|
||
ch = lambda t, d: struct.pack(">I", len(d)) + t + d + struct.pack(">I", zlib.crc32(t + d) & 0xffffffff)
|
||
return b"\x89PNG\r\n\x1a\n" + ch(b"IHDR", struct.pack(">IIBBBBB", w, h, 8, 6, 0, 0, 0)) + ch(b"tEXt", b"Comment\x00secret") + ch(b"IDAT", zlib.compress(raw)) + ch(b"IEND", b"") + tail
|
||
du = lambda b, t="png": "data:image/%s;base64,%s" % (t, base64.b64encode(b).decode())
|
||
st, j = a.req("upload", {"name": "测试.png", "data": du(png())})
|
||
ok_up = st == 200 and j.get("src", "").startswith("uploads/") and os.path.exists(os.path.join(PORTAL, j.get("src", "x")))
|
||
check("传 PNG:存进 uploads/,量好宽高比", ok_up and abs(j.get("r", 0) - 64 / 48) < 0.01, j)
|
||
if ok_up:
|
||
saved = open(os.path.join(PORTAL, j["src"]), "rb").read()
|
||
check("PNG 的文字元数据块被剥掉", b"secret" not in saved)
|
||
has_ff = shutil.which("ffmpeg") is not None
|
||
check("缩略图:有 ffmpeg 就生成 .t.jpg,没有就退回原图", (j["thumb"].endswith(".t.jpg") and os.path.exists(os.path.join(PORTAL, j["thumb"]))) if has_ff else j["thumb"] == j["src"], j.get("thumb"))
|
||
st, j = a.req("upload", {"name": "x.png", "data": du(png(tail=b"hidden-payload"))})
|
||
check("传图:PNG 尾部夹带数据 → 拒", st == 400 and "核验" in j.get("error", ""), j)
|
||
jpeg = b"\xff\xd8" + b"\xff\xe1" + struct.pack(">H", 2 + 20) + b"Exif\x00\x00GPS-LOCATION" + b"\x00" * 2 \
|
||
+ b"\xff\xc0" + struct.pack(">HBHHB", 11, 8, 40, 60, 1) + b"\x01\x11\x00" \
|
||
+ b"\xff\xda" + struct.pack(">HB", 8, 1) + b"\x01\x00\x00\x3f\x00" + b"\x12\x34\x56" + b"\xff\xd9"
|
||
st, j = a.req("upload", {"name": "p.jpg", "data": du(jpeg, "jpeg")})
|
||
saved = open(os.path.join(PORTAL, j["src"]), "rb").read() if st == 200 else b""
|
||
check("传 JPEG:EXIF(含拍摄地点)被剥掉,尺寸读对", st == 200 and b"GPS-LOCATION" not in saved and j.get("w") == 60 and j.get("h") == 40, j)
|
||
st, j = a.req("upload", {"name": "p.jpg", "data": du(jpeg + b"tail", "jpeg")})
|
||
check("传 JPEG:结尾后夹带数据 → 拒", st == 400, j)
|
||
st, j = a.req("upload", {"name": "a.txt", "data": "data:text/plain;base64,aGVsbG8="})
|
||
check("传图:不是图片 → 拒", st == 400, j)
|
||
st, j = a.req("upload", {"name": "big.png", "data": du(b"\x89PNG\r\n\x1a\n" + b"0" * (10 * 1024 * 1024 + 10))})
|
||
check("传图:超过 10MB → 拒", st == 400 and "太大" in j.get("error", ""), j)
|
||
|
||
# ================================================================== 9. 会话管理
|
||
c1, c2 = C(ip="203.0.113.51"), C(ip="203.0.113.52")
|
||
c1.login("admin", NEWPW); c2.login("admin", NEWPW)
|
||
st, j = c1.req("sessions")
|
||
check("设备列表能看到多台,标出这台", st == 200 and len(j.get("sessions", [])) >= 3 and sum(1 for s in j["sessions"] if s.get("cur")) == 1, len(j.get("sessions", [])))
|
||
st, j = c1.req("sessions/revoke", {"others": True})
|
||
st2, _ = c2.req("me"); st3, _ = c1.req("me")
|
||
check("「退出所有其它设备」:别的当场失效,这台还在", st == 200 and st2 == 401 and st3 == 200)
|
||
st, j = c1.req("logout", {})
|
||
st2, _ = c1.req("me")
|
||
check("退出:服务端会话删掉,同一个 Cookie 再用 → 401", st == 200 and st2 == 401)
|
||
c3 = C(ip="203.0.113.53"); c3.login("admin", NEWPW)
|
||
with db() as con:
|
||
con.execute("UPDATE cms_sessions SET expires=? WHERE th=?", (time.time() - 1, S.cms._th(c3.cookie)))
|
||
st, _ = c3.req("me")
|
||
check("会话过期 → 401", st == 401)
|
||
|
||
# ================================================================== 10. 命令行
|
||
env = dict(os.environ, YS_ROOT=ROOT, YS_PORTAL_DIR=PORTAL, YS_ORDER_DIR=ORDER)
|
||
run = lambda *args: subprocess.run([sys.executable, os.path.join(SRC, "admin.py"), "user"] + list(args), capture_output=True, text=True, env=env, cwd=SRC, timeout=120)
|
||
keep = C(ip="203.0.113.60"); keep.login("admin", NEWPW)
|
||
r = run("reset", "admin")
|
||
m = re.search(r"临时密码:(\S+)", r.stdout)
|
||
st, _ = keep.req("me")
|
||
check("命令行 user reset:打印临时密码,原来的会话全部作废", m and st == 401, (r.stdout + r.stderr)[-120:])
|
||
tmp_pw = m.group(1) if m else ""
|
||
st, j = C(ip="203.0.113.61").login("admin", tmp_pw)
|
||
check("用临时密码登录 → 必须改密", st == 200 and j.get("must_change") is True, j)
|
||
check("临时密码没写进日志", tmp_pw and tmp_pw not in (open(S.LOG_FILE, encoding="utf-8").read() if os.path.exists(S.LOG_FILE) else ""))
|
||
r = run("reset", "admin", "--to-admin")
|
||
st, j = C(ip="203.0.113.62").login("admin", "admin")
|
||
check("user reset --to-admin:退回 admin / admin 且必须改密", st == 200 and j.get("must_change") is True, j)
|
||
r = run("add", "editor2", "--email", "ed@example.com", "--temp")
|
||
m = re.search(r"临时密码:(\S+)", r.stdout)
|
||
st, j = C(ip="203.0.113.63").login("ed@example.com", m.group(1) if m else "")
|
||
check("user add --temp:用邮箱也能登,首次必须改密", st == 200 and j.get("must_change") is True and j.get("user") == "editor2", (r.stdout + r.stderr)[-120:])
|
||
r = run("disable", "editor2")
|
||
st, j = C(ip="203.0.113.64").login("editor2", m.group(1) if m else "")
|
||
check("user disable:停用后登不上", st == 401, j)
|
||
r = run("list")
|
||
check("user list 能跑,列出两个账号", r.returncode == 0 and "admin" in r.stdout and "editor2" in r.stdout and "已停用" in r.stdout, r.stdout[-200:])
|
||
r = run("add", "x y")
|
||
check("user add:非法用户名 → 报错退出", r.returncode != 0, (r.stdout + r.stderr)[-80:])
|
||
|
||
# ================================================================== 11. 多个进程同时首次启动:只建一个初始账号
|
||
R2 = tempfile.mkdtemp(prefix="ys-cms-race-")
|
||
probe = "import sys,os;sys.path.insert(0,%r);os.environ['YS_ROOT']=%r;import server" % (SRC, R2)
|
||
ps = [subprocess.Popen([sys.executable, "-c", probe], env=dict(os.environ, YS_ROOT=R2), stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) for _ in range(3)]
|
||
[p.wait(timeout=120) for p in ps]
|
||
n = sqlite3.connect(os.path.join(R2, "ys.db")).execute("SELECT COUNT(*) FROM cms_users").fetchone()[0]
|
||
check("三个进程同时首次启动:只建了一个初始账号", n == 1, n)
|
||
|
||
# ================================================================== 12. 原有接口不受影响
|
||
try:
|
||
with urllib.request.urlopen("http://127.0.0.1:%d/api/status" % srv.server_address[1], timeout=10) as r:
|
||
stj = json.loads(r.read())
|
||
except Exception as e:
|
||
stj = {"err": repr(e)}
|
||
check("下单那边的接口照常(/api/status)", stj.get("ok") is True, stj)
|
||
|
||
srv.shutdown()
|
||
shutil.rmtree(TMP, ignore_errors=True); shutil.rmtree(R2, ignore_errors=True)
|
||
bad = [n for n, ok, _ in RESULTS if not ok]
|
||
print("\n%d 条,失败 %d 条" % (len(RESULTS), len(bad)))
|
||
for n in bad:
|
||
print(" ✗ " + n)
|
||
sys.exit(1 if bad else 0)
|