Files
ssw-platform/scripts/check-boundary-scan.py
T
admin ecb77b230f 平台包零业务:示例移到技能仓、解绑 example-packs、闸门全部改防回流
- 物理移出 packs/{asset,books,demo,shop}、modules/ 四个面 A 适配器、纯技能副本、
  纯业务测试 crud_it.rs 与 new-pack 脚手架(v0.3.0 tag 完整保留旧形态)。
- 删 example-packs feature / example_packs() / sspf-pack-* 依赖 / packs/* member;
  packs_gen.rs 与 modules/mod.rs 生成段降级为恒空的注入点,装配链一条不删;
  pack-sync.py 把「零包」钉成合法目标态。
- 尺子不再「跳过」:CP1 防回流清单、check-module 三条、AR2/PACK1 正向断言、
  AR17 升级为零业务依赖判据(含注入式反自证)、契约反自证换平台锚点、FACE 零包重算。
- 面 A 冒烟 43→21 条(17 条平台权限闭环 + 4 条业务端点 404);pack_smoke_it 改
  运行时防回流探针;auth/db/batch7/permission/seed/routes 单测换平台内置夹具。
- 契约 [MENU_TREE] 收成 5 条系统菜单、[RULER] 改 21/3;README/CLAUDE/HANDOFF/
  CHANGELOG/contract §5.1/schema.sql/db.rs 注释同步。

验收:cargo test --workspace --no-fail-fast 649 passed / 0 failed / 6 ignored;
verify.sh --smoke 14/14;check-arch 24/24 + 反自证 14/14;
cargo tree -p sspf 无 sspf-pack-*。前端 src/frontend 按要求保留。
2026-11-04 21:54:22 +08:00

287 lines
11 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
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
"""check-boundary-scan.py —— 平台层「零业务知识」扫描器(`check-boundary.sh` 的 CP1 后端)。
🔴 **为什么需要它**:CLAUDE.md 红线 12 要求「加一个业务模块只碰业务层」
⇒ 平台层(`crates/sspf-core/` + `crates/sspf-compat-*/` 等真源)里**不许出现任何业务标识符**
(🔴 M7 起转发壳已删除 ⇒ 平台层只有真源)
(业务表名 / 实体名 / 路由前缀 / 菜单 id / 菜单 url / 菜单 en_code)。
这条规则**只靠人看代码守不住** —— 加模块的人不会主动去看平台层 ⇒ 需要一把尺子。
🔴 **禁止的标识符清单从业务层自己派生**(不是手写常量表):
业务层说了什么 ⇒ 平台层就不许出现什么 ⇒ **加一个业务模块,这把尺子自动变严**,
不会出现「忘了同步常量表 ⇒ 漏检」。
🔴 **只扫「字符串字面量」**(注释不算):
注释里举例说明业务名是**文档行为**(例如解释 CTE 作用域)⇒ 允许;
代码里出现业务标识符才是**耦合** ⇒ 拦。
用法:
python3 scripts/check-boundary-scan.py <modules_dir> <scan_dir> [<scan_dir>...]
退出码:
0 = 干净(平台层零业务标识符)
1 = 发现泄漏(逐条打印 `文件:行号: [种类] token`)
2 = 用法错
"""
import os
import re
import sys
# 🔴 业务层里「哪些字段是业务知识」的抽取规则(与 `EntitySpec` / `MenuSpec` 的字段名对齐)。
SPEC_TABLE_RE = re.compile(r'table:\s*"([^"]+)"')
SPEC_ENTITY_RE = re.compile(r'entity:\s*"([^"]+)"')
SPEC_APP_RE = re.compile(r'app_code:\s*"([^"]+)"')
MENU_BLOCK_RE = re.compile(r'MenuSpec\s*\{(.*?)\n\};', re.DOTALL)
MENU_FIELD_RE = {
# 🔴 `\b` 不可省:否则 `parent_id: "0"` 里的 `id:` 会被当成菜单 id。
"id": re.compile(r'\bid:\s*"([^"]+)"'),
"en_code": re.compile(r'\ben_code:\s*"([^"]+)"'),
"url_address": re.compile(r'\burl_address:\s*"([^"]+)"'),
}
# 🔴 字符串字面量:`r#"..."#` / `r"..."` / `"..."`(普通串的转义 `\"` 不影响子串判定)。
LITERAL_RE = re.compile(r'r(#*)"(.*?)"\1|"((?:[^"\\]|\\.)*)"', re.DOTALL)
# 🔴 **防回流清单**(2026-11-04 清理):示例包已搬到技能仓,本仓业务层恒空。
# 此时「从业务层派生」得不到任何 token ⇒ CP1 若直接放过就变成**假闸门**。
# ⇒ 改用这份固定清单:谁把示例业务写回平台层(表名 / 面 A 前缀),立刻红。
# 🔴 只列**不会误伤平台层**的字面量:不列 `Book` / `Product` / `DataResource`
# 这类通用词(平台层正常代码里可能出现),只列表名与带 app 的路由前缀。
ANTI_REFLUX_TOKENS = [
("业务表名(示例·已迁出)", "demo_item"),
("业务表名(示例·已迁出)", "shop_product"),
("业务表名(示例·已迁出)", "book_shop_book"),
("业务表名(示例·已迁出)", "asset_data_resource"),
("业务路由前缀(示例·已迁出)", "/api/ssw/demo/"),
("业务路由前缀(示例·已迁出)", "/api/ssw/shop/"),
("业务路由前缀(示例·已迁出)", "/api/ssw/books/"),
("业务路由前缀(示例·已迁出)", "/api/ssw/asset/"),
]
def strip_comments(src):
"""去掉 `//` 行注释与 `/* */` 块注释(保留字符串字面量里的内容)。
🔴 逐字符扫描 ⇒ 字符串里的 `//`(如 `"http://x"`)不会被误当注释。
"""
out = []
in_block = False
for line in src.splitlines():
if in_block:
end = line.find("*/")
if end == -1:
continue
line = line[end + 2:]
in_block = False
buf = []
in_str = False
i = 0
n = len(line)
while i < n:
c = line[i]
if in_str:
buf.append(c)
if c == "\\" and i + 1 < n:
buf.append(line[i + 1])
i += 2
continue
if c == '"':
in_str = False
i += 1
continue
if c == '"':
in_str = True
buf.append(c)
i += 1
continue
if line.startswith("//", i):
break
if line.startswith("/*", i):
in_block = True
rest = line[i + 2:]
end = rest.find("*/")
if end == -1:
break
line = rest[end + 2:]
buf = []
i = 0
n = len(line)
in_str = False
continue
buf.append(c)
i += 1
out.append("".join(buf))
return out
def literals_with_lines(path):
"""⇒ [(行号, 字面量内容)](注释已剔除)。"""
with open(path, "r", encoding="utf-8") as fh:
lines = strip_comments(fh.read())
out = []
for idx, line in enumerate(lines, start=1):
for m in LITERAL_RE.finditer(line):
content = m.group(2) if m.group(1) is not None else m.group(3)
if content is not None:
out.append((idx, content))
return out
def business_tokens(modules_dir, packs_dir=None):
"""从业务层派生「平台层不许出现」的标识符清单。
⇒ [(种类, token)],种类用于报错时点名「漏的是哪一类」。
🔴 **业务层现在有两处**(批次 12 交付物 ②「spec 单一真源」):
- `src/backend/src/modules/*.rs` —— **面 A** 的内嵌业务模块
(demo / shop / books);
- `packs/*/src/lib.rs` —— **业务包**(asset 等)。
两处都要扫 ⇒ 否则包里的业务表名 / 实体名会从「禁止清单」里消失
⇒ 平台层就可以写 `asset_data_resource` 而不被抓 ⇒ **尺子变弱**。
"""
tokens = []
seen = set()
def add(kind, value):
if not value:
return
key = (kind, value)
if key in seen:
return
seen.add(key)
tokens.append((kind, value))
sources = []
for name in sorted(os.listdir(modules_dir)):
if not name.endswith(".rs") or name == "mod.rs":
continue
sources.append(os.path.join(modules_dir, name))
# 🔴 **业务包**:包目录里的 `src/lib.rs` 是包声明的所在地。
if packs_dir and os.path.isdir(packs_dir):
for pkg in sorted(os.listdir(packs_dir)):
lib = os.path.join(packs_dir, pkg, "src", "lib.rs")
if os.path.isfile(lib):
sources.append(lib)
for path in sources:
with open(path, "r", encoding="utf-8") as fh:
src = "\n".join(strip_comments(fh.read()))
for m in SPEC_TABLE_RE.finditer(src):
add("业务表名", m.group(1))
for m in SPEC_ENTITY_RE.finditer(src):
add("业务实体名", m.group(1))
for m in SPEC_APP_RE.finditer(src):
add("业务路由前缀", "/api/ssw/{}/".format(m.group(1)))
for m in MENU_BLOCK_RE.finditer(src):
body = m.group(1)
for kind, rx in MENU_FIELD_RE.items():
for f in rx.finditer(body):
add("业务菜单 {}".format(kind), f.group(1))
if not tokens:
# 🔴 平台包零业务:没有业务层可派生 ⇒ 用防回流清单,尺子不失效。
return list(ANTI_REFLUX_TOKENS)
return tokens
def rust_files(root):
"""⇒ root 下全部 `.rs` 文件(递归,按路径排序)。"""
out = []
for dirpath, dirnames, filenames in os.walk(root):
dirnames.sort()
for name in sorted(filenames):
if name.endswith(".rs"):
out.append(os.path.join(dirpath, name))
return out
def main(argv):
if len(argv) >= 2 and argv[1] == "--self-test":
return self_test()
if len(argv) >= 2 and argv[1] == "--tokens":
# 给 `check-boundary.sh` 的 CP1'' 探针用:打印当前禁止清单的 token(每行一个)。
for _kind, tok in business_tokens(os.environ.get("SSW_MODULES_DIR", ".")):
print(tok)
return 0
if len(argv) < 3:
sys.stderr.write(
"用法: python3 scripts/check-boundary-scan.py <modules_dir> <scan_dir> [...]\n"
)
return 2
modules_dir = argv[1]
scan_dirs = argv[2:]
# 🔴 业务包目录(可省略 ⇒ 兼容旧调用;`check-boundary.sh` 会传)。
packs_dir = os.environ.get("SSW_PACKS_DIR") or None
tokens = business_tokens(modules_dir, packs_dir)
violations = []
scanned = 0
for root in scan_dirs:
for path in rust_files(root):
scanned += 1
rel = os.path.relpath(path)
for lineno, content in literals_with_lines(path):
for kind, token in tokens:
if token in content:
violations.append((rel, lineno, kind, token, content.strip()))
for rel, lineno, kind, token, content in violations:
print("{}:{}: [{}] {} ← 字面量: {}".format(rel, lineno, kind, token, content[:120]))
print("scanned_files={} tokens={} violations={}".format(scanned, len(tokens), len(violations)))
return 1 if violations else 0
def self_test():
"""🔴 **反自证**:造一个「平台层泄漏业务表名」的假文件 ⇒ 必须被抓出来。
🔴 **为什么必须有**:一把永远返回「干净」的尺子 = 没有尺子。
自证 = 用同一条规则去抓一个**明知存在**的泄漏 ⇒ 抓到了 ⇒ 规则本身有效。
"""
import tempfile
with tempfile.TemporaryDirectory() as tmp:
mods = os.path.join(tmp, "modules")
plat = os.path.join(tmp, "platform")
os.makedirs(mods)
os.makedirs(plat)
with open(os.path.join(mods, "demo.rs"), "w", encoding="utf-8") as fh:
fh.write(
'pub const DEMO_SPEC: EntitySpec = EntitySpec {\n'
' app_code: "demo",\n'
' entity: "DemoItem",\n'
' table: "demo_item",\n'
'};\n'
)
# 泄漏:平台层里出现了业务表名(**在字符串字面量里**)。
with open(os.path.join(plat, "leak.rs"), "w", encoding="utf-8") as fh:
fh.write('const SQL: &str = "SELECT * FROM demo_item";\n')
# 不泄漏:只在**注释**里提到业务表名(文档行为,允许)。
with open(os.path.join(plat, "doc.rs"), "w", encoding="utf-8") as fh:
fh.write('// 例:SELECT * FROM demo_item\nconst OK: &str = "SELECT 1";\n')
tokens = business_tokens(mods)
# 表名 + 实体名 + 路由前缀(假 spec 里没有 MenuSpec ⇒ 没有菜单那三类)。
if len(tokens) != 3:
print("self-test: token 抽取数不对: {}".format(len(tokens)))
return 1
hits = 0
for path in rust_files(plat):
for _lineno, content in literals_with_lines(path):
for _kind, token in tokens:
if token in content:
hits += 1
if hits != 1:
print("self-test: 应恰好抓到 1 处泄漏,实际 {} 处".format(hits))
return 1
print("self-test: OK(泄漏被抓到、注释里的举例未被误报)")
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv))