#!/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 [...] 退出码: 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 [...]\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))