Files
ssw-jnpf-lite-rust/scripts/check-boundary-scan.py
T
adminandClaude Code 96594df72f feat(repo): 平台层/业务层分离收尾 + 六道闸门(把「尺子」变成机器)
**影响**
后端从「平台层里塞业务知识」改成「装配根 + 业务层自带 spec/菜单/路由」;闸门 5 道 → 6 道,
契约尺子 2 条 → 3 条;两把尺子**默认自起隔离后端** ⇒ 不用先起后端就能冒烟(CI 可跑)。
单测 220 passed / 0 failed;静态闸门 93 + 11 + 10 + 4 全绿;面 A 32/32、面 B 18/18 全绿。

**改动**
- 后端:新增 `platform/guard.rs`(生产档弱口令守卫六条判据 + 配置级/库内级两道检查)、
  `platform/menu.rs`(菜单 spec 的类型)、`bootstrap.rs`(装配根:唯一同时认识平台层与业务层的地方);
  业务模块的菜单与路由下沉到 `modules/<app>.rs`,平台层只 `merge(modules::router())` 一次。
- 闸门:新增 `check-boundary.sh`(分层红线 CP1–CP6)、`check-contract.sh`(契约端点表 + 官方端点台账
  ↔ 代码真实路由,CC2–CC10)、`check-citations.sh`(文档引文 `路径:行号` 逐条核对);
  `check-module.sh` 改为从契约期望值派生(63 → 93 条);三把尺子各带反自证用例。
- 契约:`docs/contract.md` 附录 A 扩成机器可读区段(`[ENDPOINT]` / `[FACE]` / `[OFFICIAL]` / `[RULER]` …)
  ⇒ 六把尺子的期望值只有一处;`[OFFICIAL]` 官方端点台账 53 行四态 ⇒ 覆盖 **8/47**(算出来的)。
- 尺子:`scripts/smoke_backend.sh` 让两把契约尺子默认自起隔离后端(显式给了 `B` ⇒ 不自起、不可达即退出码 2)。
- 文档:CLAUDE.md / SKILL.md / README.md / HANDOFF.md / HOWTO_MODULE.md / docs/* 同步到新结构与新闸门;
  裁决 96 → 98 条(P91 尺子自起设计、P92 官方端点覆盖账本)。

Co-Authored-By: Claude Code <[email protected]>
2026-10-27 11:33:25 +08:00

246 lines
8.9 KiB
Python
Raw 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 要求「加一个业务模块只碰业务层」
⇒ 平台层(`src/backend/src/platform/`)里**不许出现任何业务标识符**
(业务表名 / 实体名 / 路由前缀 / 菜单 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)
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):
"""从业务层派生「平台层不许出现」的标识符清单。
⇒ [(种类, token)],种类用于报错时点名「漏的是哪一类」。
"""
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))
for name in sorted(os.listdir(modules_dir)):
if not name.endswith(".rs") or name == "mod.rs":
continue
path = os.path.join(modules_dir, name)
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))
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) < 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:]
tokens = business_tokens(modules_dir)
if not tokens:
sys.stderr.write("业务层没解析出任何标识符(modules_dir 有问题?)\n")
return 2
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))