test: 给令牌白名单与额度后扣钉测试;README 记录三条加固规则
This commit is contained in:
@@ -402,3 +402,19 @@ python tests/smoke_http.py # 39 项 HTTP 冒烟(真起服务
|
||||
|
||||
**改模板的流程**:改 xlsx → `python gen_kpt.py` → 重新打开工作台(不需要重编译)。
|
||||
**没标 kp 的题**:只能拿到通用三步。所以 OCR 切出来的题要按题干关键词归类,归不上就留空。
|
||||
|
||||
### 四点十七、令牌、额度与测试目录(2026-11-18 加固)
|
||||
|
||||
三条规则,都是被真实审查意见逼出来的:
|
||||
|
||||
1. **令牌只允许出现在三个链接接口的 query 里** —— `/api/export/csv`、`/api/print/weekly`、
|
||||
`/api/papers/{pid}/clean`。别的接口一律走 `Authorization: Bearer`,因为反代的 access log
|
||||
会把 URL 原样记下来,令牌进了日志就等于泄漏。规则在 `app.py` 的 `QUERY_TOKEN_PATHS`。
|
||||
2. **订阅额度发成功才扣** —— 一次性订阅是用户点一次才给一条,先扣后发、发失败就成了
|
||||
「付了没拿到」。现在 `_peek_grant()` 只看不扣,`send_subscribe` 成功后才 `_mark_grant_used()`;
|
||||
失败会进 `notifications_tick()` 返回的 `failed[]` 并写 `skipped_reason`,额度留到下次。
|
||||
3. **测试不许写进仓库** —— `tests/_tmpdir.py` 的 `workdir()` 会依次试
|
||||
`QINGLING_TEST_TMP` → 系统临时目录 → `tests/_tmp`,每个候选都真建一次 sqlite 才采用。
|
||||
CI、只读挂载、沙箱里跑测试不会再因为 PermissionError 挂掉。
|
||||
|
||||
当前规模:**140 个单测 + 82 项 HTTP 冒烟**(39 + 22 + 21)。
|
||||
|
||||
+8
-3
@@ -1244,14 +1244,19 @@ def notifications_tick(conn, on: str | None = None) -> dict:
|
||||
" VALUES (?,?,?,?,?,?)",
|
||||
(c["id"], "daily", json.dumps({**payload, "wx": res}, ensure_ascii=False),
|
||||
f"{d}T{c['remind_at']}:00", now() if delivered else None,
|
||||
None if delivered else f"发送失败({res['errcode']}):{res['errmsg']}"))
|
||||
None if delivered else "发送失败({}):{}".format(
|
||||
res.get("errcode") or "unknown",
|
||||
res.get("message") or res.get("errmsg") or "没有返回原因")))
|
||||
conn.execute("UPDATE subscribe_grants SET notification_id=? WHERE id=?",
|
||||
(cur.lastrowid, grant))
|
||||
if delivered:
|
||||
made.append({"child_id": c["id"], **payload, "channel": channel})
|
||||
else:
|
||||
skipped.append({"child_id": c["id"], "reason": f"微信发送失败:{res['errmsg']}"})
|
||||
need.append({"child_id": c["id"], "guardian_id": gid, "why": res["errmsg"]})
|
||||
skipped.append({"child_id": c["id"],
|
||||
"reason": "微信发送失败:{}".format(
|
||||
res.get("errmsg") or res.get("message") or "没有返回原因")})
|
||||
need.append({"child_id": c["id"], "guardian_id": gid,
|
||||
"why": res.get("errmsg") or res.get("message") or "发送失败"})
|
||||
return {"date": d, "queued": made, "skipped": skipped, "need_subscribe": need,
|
||||
"failed": fails, "wx_mode": wechat.mode()}
|
||||
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""这一轮加固的两条规则,各自钉一个测试。
|
||||
|
||||
1) 令牌只允许出现在「要贴到新标签页/发给他人的链接」的 query 上;
|
||||
2) 一次性订阅额度必须是「发成功了才扣」——发失败要留着,下次还能用。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
sys.path.insert(0, str(ROOT))
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||
from _tmpdir import workdir as _workdir # noqa: E402
|
||||
|
||||
from backend import app as appmod # noqa: E402
|
||||
from backend import db as dbm # noqa: E402
|
||||
from backend import services as svc # noqa: E402
|
||||
from backend import wechat # noqa: E402
|
||||
|
||||
|
||||
class QueryTokenTest(unittest.TestCase):
|
||||
def test_link_endpoints_allow_query_token(self):
|
||||
for p in ("/api/export/csv", "/api/print/weekly", "/api/papers/p_1/clean"):
|
||||
self.assertTrue(appmod.query_token_ok(p), p)
|
||||
|
||||
def test_other_endpoints_reject_query_token(self):
|
||||
for p in ("/api/today", "/api/me", "/api/mistakes",
|
||||
"/api/export/csv2", "/api/papers/p_1", "/apipapers/x"):
|
||||
self.assertFalse(appmod.query_token_ok(p), p)
|
||||
|
||||
|
||||
class GrantTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.conn = dbm.connect(_workdir("hardening") / f"{self._testMethodName}.db")
|
||||
dbm.init_db(self.conn)
|
||||
self.login = svc.login(self.conn, "demo")
|
||||
self.gid = self.login["guardian_id"]
|
||||
svc.give_consent(self.conn, self.gid, "v1")
|
||||
child = svc.create_child(self.conn, self.gid, "皮皮", 2)
|
||||
self.cid = child["id"]
|
||||
self.tmpl = svc.subscribe_template("daily")
|
||||
svc.record_subscribe(self.conn, self.gid, [self.tmpl])
|
||||
# 给这个孩子排几道今天到期的题,提醒才有东西可发
|
||||
paper = svc.create_paper(self.conn, self.gid, self.cid, "math")
|
||||
ids = [q["id"] for q in paper["questions"]]
|
||||
imp = svc.import_mistakes(self.conn, self.gid, self.cid, ids[:3])
|
||||
for m in imp["created"]:
|
||||
self.conn.execute(
|
||||
"UPDATE mistakes SET status='queued', next_due=? WHERE id=?",
|
||||
(dbm.today(), m["mistake_id"]))
|
||||
|
||||
def tearDown(self):
|
||||
self.conn.close()
|
||||
|
||||
def _grants_left(self):
|
||||
return self.conn.execute(
|
||||
"SELECT COUNT(*) c FROM subscribe_grants WHERE guardian_id=? AND used_at IS NULL",
|
||||
(self.gid,)).fetchone()["c"]
|
||||
|
||||
def test_send_failure_keeps_the_grant(self):
|
||||
before = self._grants_left()
|
||||
origin = wechat.send_subscribe
|
||||
wechat.send_subscribe = lambda openid, payload: {"sent": False, "dev": False, "message": "模拟失败"}
|
||||
try:
|
||||
res = svc.notifications_tick(self.conn)
|
||||
finally:
|
||||
wechat.send_subscribe = origin
|
||||
self.assertEqual(self._grants_left(), before, "发失败了不该扣额度")
|
||||
self.assertTrue(res["failed"], "失败要出现在返回值里,不能悄悄吞掉")
|
||||
|
||||
def test_send_success_consumes_the_grant(self):
|
||||
before = self._grants_left()
|
||||
origin = wechat.send_subscribe
|
||||
wechat.send_subscribe = lambda openid, payload: {"sent": True, "dev": False}
|
||||
try:
|
||||
res = svc.notifications_tick(self.conn)
|
||||
finally:
|
||||
wechat.send_subscribe = origin
|
||||
self.assertTrue(res["queued"], "发出去了要记账")
|
||||
self.assertEqual(self._grants_left(), before - 1)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in New Issue
Block a user