Files
ssw-platform/scripts/check-contract-scan.py
T
admin ce30c5b2f6 feat(pack): 框架固定包 + 加模块一条命令(批次 12 + 12.5)
把「内核怎么知道有这个包」从手写改成生成,漏接直接报错而不是静默 404。

- crates/sspf-plugin:load_static() 收掉装配样板,bootstrap 的 load_packs 缩成一行

- 包统一出口:pub struct Pack + pub const DDLS(生成器不必理解各包常量命名)

- 业务 DDL 跟包走(packs/*/schema/*.sql 经 include_str! 编进二进制)

- packs_gen.rs / modules/mod.rs 5 段 / Cargo.toml / contract.md 三段改由 pack-sync.py 生成

- scripts/new-pack.sh:一条命令产出 5 个后端文件 + 接线 + 可选前端三件套

- scripts/verify.sh 静态闸门一键跑;.workbuddy 记忆与 HANDOFF 见下一提交
2026-11-01 23:04:53 +08:00

1321 lines
55 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
# -*- coding: utf-8 -*-
"""check-contract-scan —— **契约 ↔ 代码** 对账扫描器。
🔴 为什么存在:
`docs/contract.md` 的端点表原先是**散文表格**(§6.1–§6.5),
代码里的路由注册是**另一处**(`routes.rs` / `modules/*.rs`)⇒
加端点、改路径、改守卫 ⇒ 契约与代码**各改各的** ⇒ 漂移没人发现。
本脚本把契约的机器可读区段 `[ENDPOINT]` / `[FACE]` 与**代码里真实注册的路由**
逐条对账,**双向**都查(契约多 / 代码多 / 方法不符 / 归属层不符 / 守卫不符)。
🔴 **只做静态检查**:不启动后端、不发请求。纯 `python3`(macOS 自带)。
用法:
check-contract-scan.py --contract <契约文件> --src <后端 src 目录>
check-contract-scan.py --self-test
输出协议(制表符分隔,逐行一条):
CHECK\t<id>\t<OK|DRIFT>\t<说明>
WARN\t<id>\t<说明> # 推不出守卫之类的「非失败但要看见」
退出码:0 = 扫完(可能有 DRIFT,看输出)/ 2 = 致命错误(契约读不出来等)
"""
import io
import os
import re
import shutil
import sys
import tempfile
HERE = os.path.dirname(os.path.abspath(__file__))
ROOT = os.path.dirname(HERE)
if HERE not in sys.path:
sys.path.insert(0, HERE)
import contract_expect # noqa: E402 (同目录)
# ---------------------------------------------------------------- Rust 源码扫描
# 路由注册:`.route("/api/x", get(handler))`(允许跨行)
# 🔴 路径是**字符串字面量** ⇒ 在 masked 里是空白 ⇒ 只在 masked 里定位 `.route(`,
# 再用**同一偏移**去原文取路径与方法。
ROUTE_CALL_RE = re.compile(r'\.route\(')
# 路由后面的 handler 表达式:`sys::user_list` / `demo_item_list` / `|State(..)| ..`(闭包)
HANDLER_RE = re.compile(r'\s*(?:([A-Za-z_][A-Za-z0-9_]*)::)?([A-Za-z_][A-Za-z0-9_]*)')
# 契约表里 `{param}` ⇒ 代码里的通配
PARAM_RE = re.compile(r'\{[A-Za-z_][A-Za-z0-9_]*\}')
# 测试用的固定路径前缀(**不在契约端点表里** ⇒ 全部扫描都排除)
TEST_PATH_PREFIX = "/api/__test__/"
# 🔴 业务包的路由声明(批次 12 交付物 ①):`PackRoute { … }` —— 纯数据,不认识 axum。
# 注意:`mask_rust` 会把字符串字面量挖空 ⇒ 只能**在 masked 里定位结构**,
# 再用同一偏移去原文取值。
PACK_ROUTE_RE = re.compile(r'PackRoute\s*\{')
# 🔴 一次扫全文的「函数定义」正则(见 `_fn_positions`):
# 每份文件只跑一遍就能拿到**所有** `fn 名字(` 的位置,避免「查一个函数扫一遍全文」。
FN_DEF_RE = re.compile(r'\bfn\s+([A-Za-z_][A-Za-z0-9_]*)\s*\(')
def mask_rust(text):
"""把字符串字面量 / 注释**挖空**(保持长度不变)⇒ 结构扫描不会被注释/字面量骗。
挖空后拿到的偏移量与原文一一对应 ⇒ 需要字面量的值时,用同一偏移去原文里取。
"""
out = list(text)
n = len(text)
def blank(a, b):
for k in range(a, b):
if out[k] != "\n":
out[k] = " "
i = 0
while i < n:
c = text[i]
if c == "/" and i + 1 < n and text[i + 1] == "/":
j = text.find("\n", i)
j = n if j < 0 else j
blank(i, j)
i = j
continue
if c == "/" and i + 1 < n and text[i + 1] == "*":
depth, j = 1, i + 2
while j < n and depth:
if text.startswith("/*", j):
depth += 1
j += 2
elif text.startswith("*/", j):
depth -= 1
j += 2
else:
j += 1
blank(i, j)
i = j
continue
if c == "r" and i + 1 < n and text[i + 1] in '#"':
m = re.match(r'r(#*)"', text[i:])
if m:
hashes = m.group(1)
end = text.find('"' + hashes, i + m.end())
j = n if end < 0 else end + 1 + len(hashes)
blank(i, j)
i = j
continue
if c == '"':
j = i + 1
while j < n:
if text[j] == "\\":
j += 2
continue
if text[j] == '"':
j += 1
break
j += 1
blank(i, j)
i = j
continue
if c == "'":
m = re.match(r"'(\\.|[^\\'])'", text[i:])
if m:
blank(i, i + m.end())
i += m.end()
continue
i += 1 # 生命周期(`'a`)不是字面量 ⇒ 留着
continue
i += 1
return "".join(out)
def read(path):
with io.open(path, encoding="utf-8") as fh:
return fh.read()
def brace_span(masked, start):
"""从 `start`(`{` 的位置)开始做括号配对 ⇒ 返回 body 的 (开, 闭) 区间。"""
depth = 0
i = start
n = len(masked)
while i < n:
c = masked[i]
if c == "{":
depth += 1
elif c == "}":
depth -= 1
if depth == 0:
return start, i + 1
i += 1
return start, n
def find_fn_body(masked, fname):
"""找 `fn <fname>(` 的函数体区间 ⇒ 返回 (start, end) 或 None。
🔴 **带缓存**:反自证要跑 13 次 `analyze`,每次都把**同一批文件**重新
`re.search` 一遍(实测 `re.search` 占单次分析 3.0s / 4.7s)。
缓存键用 `id(masked)`,但**同时把 masked 本体存进缓存值** ⇒
只要缓存项还活着,那个 id 就不可能被别的对象复用 ⇒ **不会脏读**。
"""
key = id(masked)
entry = _FN_CACHE.get(key)
if entry is None or entry[0] is not masked:
entry = (masked, {})
_FN_CACHE[key] = entry
table = entry[1]
# 🔴 必须区分「没查过」与「查过但没有」—— 用哨兵,不能用 `dict.get` 的 None
# (同一个文件要查很多个函数名,`get` 会把「没查到」当成「没查过」⇒ 反复重查)。
if fname in table:
return table[fname]
span = _find_fn_body_uncached(masked, fname)
table[fname] = span
return span
_FN_CACHE = {}
_FN_POS_CACHE = {}
def _fn_positions(masked):
"""一次性扫出文件里所有 `fn <名字>(` 的位置 ⇒ `{名字: 左括号之后的位置}`。
🔴 **为什么需要这张表**(实测数据):原来的 `_find_fn_body_uncached` 每查
一个函数名就在**整份文件**上跑一次 `re.search`。同一个文件常被查十几次
(routes.rs 里几十个 handler 都在里面)⇒ 同一份文件被完整正则扫十几遍。
实测 362 次查找里 `re.search` 累计 1.4s,占单次分析的大头。
⇒ 改成「每份文件只扫一遍」把位置全部拿到,查表 O(1)。
 🔴 同名函数(不同 `impl` 块里各有一份)取**第一个**,与原
`re.search(...)` 的语义一致(`re.search` 也是返回第一个匹配)。
"""
key = id(masked)
entry = _FN_POS_CACHE.get(key)
if entry is not None and entry[0] is masked:
return entry[1]
pos = {}
for m in FN_DEF_RE.finditer(masked):
name = m.group(1)
if name not in pos:
pos[name] = m.end()
_FN_POS_CACHE[key] = (masked, pos)
return pos
def _find_fn_body_uncached(masked, fname):
q = _fn_positions(masked).get(fname)
if q is None:
return None
i = masked.find("{", q)
if i < 0:
return None
return brace_span(masked, i)
def scan_routes(path, owner):
"""扫一个源文件里的 `.route(...)` ⇒ [{path, method, handler_mod, handler_fn, closure}]。"""
orig = read(path)
masked = mask_rust(orig)
out = []
for m in ROUTE_CALL_RE.finditer(masked):
p = m.end()
while p < len(orig) and orig[p] in " \t\r\n":
p += 1
if p >= len(orig) or orig[p] != '"':
continue
q = p + 1
while q < len(orig) and orig[q] != '"':
if orig[q] == "\\":
q += 1
q += 1
if q >= len(orig):
continue
route = orig[p + 1:q]
p = q + 1
while p < len(orig) and orig[p] in " \t\r\n":
p += 1
if p < len(orig) and orig[p] == ",":
p += 1
while p < len(orig) and orig[p] in " \t\r\n":
p += 1
mm = re.match(r"(get|post|put|delete)\s*\(", orig[p:])
if not mm:
continue
if masked[p:p + len(mm.group(1))] != mm.group(1):
continue # 方法名其实落在字符串里(误报)
method = mm.group(1).upper()
after = p + mm.end()
if route.startswith(TEST_PATH_PREFIX):
continue # 仅测试构建存在的端点 ⇒ 不在契约端点表里
rest = orig[after:after + 240]
hm = HANDLER_RE.match(rest)
mod, fn, closure = None, None, True
if hm and hm.group(2):
mod, fn = hm.group(1), hm.group(2)
closure = False
out.append({
"path": route,
"method": method,
"mod": mod,
"fn": fn,
"closure": closure,
"owner": owner,
# 🔴 `source` 区分「路由住在哪」:平台层 / 业务模块(面 A)/ 业务包(面 B)。
# owner 会撞(包与模块同 app_code)⇒ 守卫推导与台账范围**必须**看这个。
"source": "platform" if owner == "platform" else "module",
"const": None,
"file": path,
})
return out, orig, masked
def resolve_const(orig, masked, name):
"""`const NAME: &str = "value";` ⇒ value(取原文里的字面量)。
🔴 **带缓存**(同 [`find_fn_body`] 的理由):本函数在**整份文件**上跑正则,
362 条平台端点的守卫推导会反复查同一批常量名。
"""
key = id(orig)
entry = _CONST_CACHE.get(key)
if entry is None or entry[0] is not orig:
entry = (orig, {})
_CONST_CACHE[key] = entry
table = entry[1]
if name in table:
return table[name]
m = re.search(r"\bconst\s+" + re.escape(name) + r"\b[^=]*=\s*\"([^\"]*)\"", orig)
value = m.group(1) if m else None
table[name] = value
return value
_CONST_CACHE = {}
def guard_of_platform(plat_files, mod, fn):
"""平台层 handler 的守卫 ⇒ 菜单 key / 点权限编码 / 登录 / 无;推不出 ⇒ None。
`plat_files` = {"sys": (orig, masked), "face_b": (orig, masked), ...}
"""
if mod == "auth" and fn == "login_handler":
return "无"
if mod is None:
# routes.rs 里自己定义的 handler(如 `health`)⇒ 没有守卫调用 ⇒ 无
pair = plat_files.get("__routes__")
if not pair:
return None
orig, masked = pair
span = find_fn_body(masked, fn)
if not span:
return None
body = masked[span[0]:span[1]]
if re.search(r"require_(login|module|login_jnpf)\s*\(", body) or re.search(r"\bguard\s*\(", body):
return None
return "无"
pair = plat_files.get(mod)
if not pair:
return None
orig, masked = pair
span = find_fn_body(masked, fn)
if not span:
return None
body = masked[span[0]:span[1]]
if mod == "sys":
m = re.search(r"require_module\(\s*&state\s*,\s*&headers\s*,\s*([A-Z_][A-Z0-9_]*)\s*\)", body)
if m:
return resolve_const(orig, masked, m.group(1))
if re.search(r"require_login(_any)?\s*\(", body):
return "登录"
return None
# 🔴 面 B 的实现文件 2026-10-26 从 `jnpf.rs` 改名为 `face_b.rs`
# ⇒ 这里**两个名字都认**(只认旧名会让整片面 B 的守卫检查静默失效)。
if mod in ("jnpf", "face_b"):
m = re.search(r"guard\(\s*&state\s*,\s*&headers\s*,\s*([A-Z_][A-Z0-9_]*)\s*\)", body)
if m:
return resolve_const(orig, masked, m.group(1))
# 🔴 官方的 `@SaCheckPermission(value={A,B}, mode=OR)` ⇒ 本仓 `guard_any(&[A,B])`:
# 契约里写成 `A|B`(同一个分隔符,**顺序即代码里的顺序**)。
m = re.search(r"guard_any\(\s*&state\s*,\s*&headers\s*,\s*&\[([^\]]*)\]", body)
if m:
codes = []
for name in re.findall(r"\b[A-Z_][A-Z0-9_]*\b", m.group(1)):
value = resolve_const(orig, masked, name)
if value:
codes.append(value)
return "|".join(codes) if codes else None
if re.search(r"require_login_(jnpf|face_b)\s*\(", body):
return "登录"
return None
return None
def guard_of_closure(orig, masked, rest):
"""闭包 handler(只有 `CurrentUser` 一处)⇒ 看它调了谁。"""
if "auth::current_user" in rest:
return "登录"
return None
def guard_of_module(orig, masked):
"""业务模块的守卫 ⇒ 它的 `EntitySpec.module_key`(None ⇒ 仅登录)。
🔴 在 **masked** 里定位 `module_key:`(注释里的假 mention 被挖空了),
再用**同一偏移**去原文取真值(字面量在 masked 里是空格)。
🔴 **spec 搬进包之后本函数会推不出**(批次 12 交付物 ②):
`modules/asset.rs` 现在只做 `pub use sspf_pack_asset::DATA_RESOURCE_SPEC;`
⇒ 文件里**没有 `module_key` 字面量** ⇒ 返回 None ⇒ CC6 只能报「推不出」。
⇒ 这不是「推不出」,是**真源搬走了** ⇒ 必须回落到包里的 spec。
见 [`guard_of_module_with_pack_fallback`]。
"""
for m in re.finditer(r"module_key:", masked):
tail = orig[m.end():m.end() + 60]
if re.match(r"\s*None", tail):
return "登录"
mm = re.match(r'\s*Some\(\s*"([^"]*)"\s*\)', tail)
if mm:
return mm.group(1)
return None
def guard_of_module_with_pack_fallback(orig, masked, app, pack_orig, pack_masked):
"""面 A 的守卫:先看模块文件;**模块只是 re-export 时回落同 app 的包里的 spec**。
🔴 **为什么要回落**(而不是让 CC6 报「推不出」):
「推不出」是给**真的静态分析不了**的情况留的(比如 handler 里做了动态判断)。
而 asset 的 `module_key` 是**确定存在**的 —— 只是住在包里。
把它报成「推不出」⇒ 面 A 的守卫**从此不再被检查**(静默失效)⇒
正是本仓最怕的那类退化:尺子还在跑,但已经瞎了。
🔴 **必须按 `app` 精确匹配,不能取「排序后第一个包」**(2026-11-01 修的真 bug):
只有一个包时「第一个」碰巧等于「同 app 的」⇒ 看起来对;
加第二个包(`probe`)后,`sorted()` 仍从 `asset` 开始 ⇒
**probe 的面 A 守卫被推成 `asset/DataResource`** ⇒ CC6 报「守卫漂移」,
而契约其实是**对的** ⇒ 假飘移 3 条 ⇒ 人会去改对的契约。
⇒ 用 `app` 查对应的包;查不到就老老实实返回 `None`(= 推不出,人工核对)。
"""
key = guard_of_module(orig, masked)
if key is not None:
return key
if app not in pack_orig:
return None
specs = scan_entities(pack_orig[app], pack_masked[app])
if not specs:
return None
return specs[0]["module_key"] if specs[0]["module_key"] else "登录"
def scan_pack_routes(path, owner):
"""扫业务包里的 `PackRoute` 声明 ⇒ [{path, method, entity, …}]。
🔴 **形状与 `.route()` 完全不同**(批次 12 交付物 ①):
业务包**不认识 axum** ⇒ 路由是**纯数据声明**:
pub const DATA_RESOURCE_LIST_ROUTE: PackRoute = PackRoute {
path: "/api/asset/DataResource/List",
method: HttpMethod::Get,
entity: "DataResource",
action: RouteAction::List,
};
⇒ 扫描器要认得 `PackRoute { … }` 这个形状 ⇒ 把路径 / 方法 / 实体抽出来。
⇒ 返回的条目与 `.route()` 扫出来的**同构** ⇒ 下游的 CC2–CC10
一行都不用改(这是「同构」的价值)。
"""
orig = read(path)
masked = mask_rust(orig)
out = []
for m in PACK_ROUTE_RE.finditer(masked):
body = orig[m.start():m.start() + 800]
pm = re.search(r'path:\s*"([^"]+)"', body)
mm = re.search(r"method:\s*HttpMethod::(\w+)", body)
em = re.search(r'entity:\s*"([^"]+)"', body)
am = re.search(r"action:\s*RouteAction::(\w+)", body)
if not (pm and mm and em):
continue
out.append({
"path": pm.group(1),
"method": mm.group(1).upper(),
"mod": None,
"fn": None,
"closure": False,
"owner": owner,
# 🔴 **来源标记**:`pack` / `module` / `platform` ——
# CC6 的守卫推导与 CC10 的台账范围**必须**按来源分派:
# - 包路由是**面 B**(点权限),模块路由是**面 A**(菜单路径)⇒
# 两者**同 app_code 同 owner**(都叫 `asset`)⇒ 只看 owner 会串线。
"source": "pack",
# 常量名(CC8 核对「声明了但没进 *_ROUTES 数组」用)⇒ 找不到就没这项。
"const": _pack_route_const(masked, m.start()),
"entity": em.group(1),
"action": am.group(1) if am else None,
# 🔴 **守卫**(面 B 的点权限编码)—— 与 `.route()` 扫出来的条目**同构**
# ⇒ CC6 的守卫对账对包路由**一行都不用改**。
"guard": _guard_of_pack_route(body),
"file": path,
})
return out, orig, masked
def _pack_route_const(masked, at):
"""从 `PackRoute {` 的位置**往回**找最近的 `const NAME: PackRoute =` ⇒ NAME。
🔴 为什么要常量名:`DATA_RESOURCE_ROUTES` 数组是**按名字**收集这些常量的
⇒ 「声明了常量但忘了加进数组」⇒ 路由**不注册**、**不报错**、**静默 404**。
CC8 用这个名字集合与数组做双向对账 ⇒ 把这个坑变成红的。
"""
back = masked[max(0, at - 200):at]
hits = re.findall(r"const\s+(\w+)\s*:\s*PackRoute\s*=", back)
return hits[-1] if hits else None
def pack_route_array(masked):
"""包的 `const XXX_ROUTES: &[PackRoute] = &[A, B, C];` ⇒ (数组名, [常量名])。
找不到(纯元数据包,没有路由)⇒ `(None, [])`。
"""
m = re.search(r"const\s+(\w+)\s*:\s*&\[PackRoute\]\s*=\s*&\[", masked)
if not m:
return None, []
start = masked.find("[", m.end() - 1)
depth = 0
end = -1
for k in range(start, len(masked)):
if masked[k] == "[":
depth += 1
elif masked[k] == "]":
depth -= 1
if depth == 0:
end = k
break
if end < 0:
return m.group(1), []
names = re.findall(r"\b[A-Za-z_][A-Za-z0-9_]*\b", masked[start:end])
return m.group(1), names
def _guard_of_pack_route(body):
"""`PackRoute { … guard: RouteGuard::EnCode("xxx") … }` ⇒ 守卫字符串。
🔴 `RouteGuard::Login` ⇒ `"登录"`;`EnCode("x")` ⇒ `"x"`;
缺 guard 字段 ⇒ `None`(**旧格式的包** ⇒ 让 CC6 报「推不出守卫」)。
"""
m = re.search(r'guard\s*:\s*RouteGuard::EnCode\(\s*"([^"]*)"\s*\)', body)
if m:
return m.group(1)
if re.search(r"guard\s*:\s*RouteGuard::Login", body):
return "登录"
return None
def guard_of_pack(orig, masked, route):
"""**已废弃**:面 A 的守卫口径(`module_key`)—— 包路由走面 B,见 [`guard_of_pack_entity`]。"""
raise AssertionError("guard_of_pack 已废弃:包路由是面 B,用 guard_of_pack_entity")
# ---------------------------------------------------------------- 业务包的 spec / 菜单
#
# 🔴 **为什么这些解析器住在扫描器里**(而不是 `pack-sync.py` 自己写一份):
# 包里的 `EntitySpec` / `MenuSpec` 会被**两处**消费:
# ① `scripts/pack-sync.py` —— 生成契约表的 `[MODULE]` / `[MENU]` / `[ENDPOINT]`;
# ② 本扫描器 —— 从「实体 ⇒ module_key ⇒ 菜单 en_code」推导面 B 的守卫(CC6)。
# ⇒ 复制一份就会**产生第二份解析器** ⇒ 两份迟早分叉 ⇒
# 生成段与守卫对账的**口径不一致**(一类最难受的漂移:两边都"对",结论相反)。
# ⇒ 真源在这里,`pack-sync.py` 复用。
def const_body(orig, masked, name):
"""`const NAME: T = …;` 的**值部分**(原文)⇒ 找不到返回 None。
🔴 在 masked 里定位结构(避开注释里的假 mention),再用同一偏移去原文取值。
"""
m = re.search(r"\b(?:pub\s+)?const\s+" + re.escape(name) + r"\b[^=]*=", masked)
if not m:
return None
start = m.end()
i = start
while i < len(masked) and masked[i] in " \t\r\n":
i += 1
if i >= len(masked):
return None
if masked[i] == "{":
span = brace_span(masked, i)
return orig[start:span[1]]
if masked[i] == "[":
depth = 0
j = i
while j < len(masked):
if masked[j] == "[":
depth += 1
elif masked[j] == "]":
depth -= 1
if depth == 0:
break
j += 1
return orig[start:j + 1]
# 标量(`&str`)⇒ 找分号
j = orig.find(";", start)
if j < 0:
return None
return orig[start:j]
def str_field(body, field):
"""结构体字面量里的 `field: "value",` ⇒ value。
🔴 `(?<![\\w])` 前缀断言必不可少:`parent_id: "0"` 里的 `id` 也长得像 `id: "…"`
⇒ 不加断言时 `str_field(body, "id")` 会**先命中 `parent_id`** ⇒ 菜单 id 变成 "0"。
"""
m = re.search(r"(?<!\w)" + re.escape(field) + r'\s*:\s*"([^"]*)"', body)
return m.group(1) if m else None
def module_key_of(body):
"""`module_key: None` ⇒ None;`module_key: Some("k")` ⇒ "k"。"""
if re.search(r"module_key\s*:\s*None", body):
return None
m = re.search(r'module_key\s*:\s*Some\(\s*"([^"]*)"\s*\)', body)
return m.group(1) if m else None
def scan_entities(orig, masked):
"""扫包里的 `EntitySpec` 常量 ⇒ [{const, app, entity, table, module_key}]。"""
out = []
for m in re.finditer(r"(?:pub\s+)?const\s+(\w+)\s*:\s*EntitySpec\s*=", masked):
name = m.group(1)
body = const_body(orig, masked, name)
if not body:
continue
app = str_field(body, "app_code")
ent = str_field(body, "entity")
table = str_field(body, "table")
if not (app and ent and table):
continue
out.append({
"const": name,
"app": app,
"entity": ent,
"table": table,
"module_key": module_key_of(body),
})
return out
def scan_menus(orig, masked):
"""扫包里的 `MenuSpec` 常量 ⇒ [{const, id, fullName, enCode, urlAddress, parentId, type, icon, sortCode}]。"""
out = []
for m in re.finditer(r"(?:pub\s+)?const\s+(\w+)\s*:\s*MenuSpec\s*=", masked):
name = m.group(1)
body = const_body(orig, masked, name)
if not body:
continue
mid = str_field(body, "id")
full = str_field(body, "full_name")
en = str_field(body, "en_code")
url = str_field(body, "url_address")
parent = str_field(body, "parent_id")
if not (mid and full and en and url and parent is not None):
continue
tm = re.search(r"menu_type\s*:\s*(-?\d+)", body)
im = re.search(r'icon\s*:\s*Some\(\s*"([^"]*)"\s*\)', body)
sm = re.search(r"sort_code\s*:\s*(-?\d+)", body)
out.append({
"const": name,
"id": mid,
"fullName": full,
"enCode": en,
"urlAddress": url,
"parentId": parent,
"type": tm.group(1) if tm else "",
"icon": im.group(1) if im else "",
"sortCode": sm.group(1) if sm else "0",
})
return out
def guard_of_pack_entity(orig, masked, entity):
"""业务包路由的守卫(面 B)⇒ 该实体 `module_key` 所指菜单的 `f_en_code`。
🔴 **这是 `sspf-plugin` 装载期 `LoadError::GuardMismatch` 在 Python 侧的镜像**:
路由声明的 guard 与菜单 `f_en_code` 不一致 ⇒ 运行时按 en_code 查菜单查不到
⇒ 走「**未映射放行**」分支 ⇒ **任何登录用户都能调** ⇒ 越权且不报错。
⇒ 所以这里**独立推导**一遍(从 spec ⇒ module_key ⇒ 菜单 en_code),
而不是拿路由自己声明的 guard 去比契约(那等于自己比自己,毫无意义)。
`module_key: None` ⇒ 仅需登录(面 B 的未登录码仍是 602,与守卫无关)。
"""
spec = None
for e in scan_entities(orig, masked):
if e["entity"] == entity:
spec = e
break
if spec is None:
return None
key = spec["module_key"]
if key is None:
return "登录"
for m in scan_menus(orig, masked):
if m["urlAddress"] == key:
return m["enCode"]
return None
def parse_str_array(orig, masked, decl_re):
"""从 `const X: [&str; N] = [ "a", "b" ];` 里取字符串数组(原文字面量)。"""
m = re.search(decl_re, masked)
if not m:
return None
i = masked.find("[", m.end())
if i < 0:
return None
j = masked.find("]", i)
if j < 0:
return None
return re.findall(r'"([^"]*)"', orig[i:j])
def path_to_regex(pattern):
"""`/a/{id}/b` ⇒ 正则(`{id}` 当通配)⇒ 用来对钉子测试里的具体路径。
🔴 **带缓存**:CC7 要在「273 条钉子路径 × 364 条平台路由」上做双向覆盖,
每次调用都会重新拼 + 编译正则(实测 98 580 次编译 / 0.86s)。
路径字符串是有限的集合 ⇒ 编译一次就够。
"""
hit = _PATH_RE_CACHE.get(pattern)
if hit is not None:
return hit
parts = []
last = 0
for m in PARAM_RE.finditer(pattern):
parts.append(re.escape(pattern[last:m.start()]))
parts.append("[^/]+")
last = m.end()
parts.append(re.escape(pattern[last:]))
rx = re.compile("^" + "".join(parts) + "$")
_PATH_RE_CACHE[pattern] = rx
return rx
_PATH_RE_CACHE = {}
# ---------------------------------------------------------------- 对账
class Report(object):
def __init__(self):
self.checks = []
self.warns = []
self.infos = []
def add(self, cid, ok, detail):
self.checks.append((cid, "OK" if ok else "DRIFT", detail))
def warn(self, cid, detail):
self.warns.append((cid, detail))
def info(self, cid, detail):
"""**不计入 PASS/FAIL** 的进度信息(例:官方端点覆盖 N/M)。"""
self.infos.append((cid, detail))
def lines(self):
out = []
for cid, status, detail in self.checks:
out.append("CHECK\t%s\t%s\t%s" % (cid, status, detail.replace("\t", " ")))
for cid, detail in self.warns:
out.append("WARN\t%s\t%s" % (cid, detail.replace("\t", " ")))
for cid, detail in self.infos:
out.append("INFO\t%s\t%s" % (cid, detail.replace("\t", " ")))
return out
def scan_code(src_dir, packs_dir=None):
"""扫**代码侧**(平台层 + 业务模块 + 业务包)⇒ 一份可复用的快照。
🔴 **为什么抽出来**(提速的关键,不是缓存而是**不重复劳动**):
反自证要跑 13 次 `analyze`(1 次基线 + 12 例注入漂移)。
每次注入**只改契约文本**,代码侧**一动不动** ⇒ 重扫 13 遍纯属浪费。
实测:抽出后 `check-contract.sh` 从 **55s → 约 12s**。
🔴 **这个快照不会过期**:它只活在**一个进程内**,进程结束即丢
⇒ 不存在「文件改了但缓存还旧」那类脏读(跨进程缓存必须有 mtime 校验,
而进程内快照**天然**没有这个问题)。
"""
# ---- 平台层 ----
routes_path = os.path.join(src_dir, "routes.rs")
plat, plat_orig, plat_masked = scan_routes(routes_path, "platform")
plat_dir = os.path.join(src_dir, "platform")
plat_files = {"__routes__": (plat_orig, plat_masked)}
if os.path.isdir(plat_dir):
for name in sorted(os.listdir(plat_dir)):
if name.endswith(".rs"):
p = os.path.join(plat_dir, name)
o = read(p)
plat_files[name[:-3]] = (o, mask_rust(o))
# ---- 业务模块(面 A)----
mod_dir = os.path.join(src_dir, "modules")
mod_files = []
if os.path.isdir(mod_dir):
for name in sorted(os.listdir(mod_dir)):
if name.endswith(".rs") and name != "mod.rs":
mod_files.append((name[:-3], os.path.join(mod_dir, name)))
biz = []
mod_orig = {}
mod_masked = {}
for app, path in mod_files:
rs, orig, masked = scan_routes(path, app)
biz.extend(rs)
mod_orig[app] = orig
mod_masked[app] = masked
# ---- 业务包(面 B,批次 12 交付物 ①)----
#
# 🔴 **为什么必须扫 `packs/`**:业务包的路由声明在那里
# ⇒ 不扫 ⇒ ① 包路由不在契约端点表里(漏账)
# ② 包路由不在「代码真实路由」里 ⇒ CC2/CC3 判**假漂移**。
# ⇒ 扫 ⇒ 包路由与其它路由**同构** ⇒ 下游 CC2–CC10 一行都不用改。
packs = []
pack_orig = {}
pack_masked = {}
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 not os.path.isfile(lib):
continue
rs, orig, masked = scan_pack_routes(lib, pkg)
packs.extend(rs)
pack_orig[pkg] = orig
pack_masked[pkg] = masked
return {
"plat": plat,
"plat_orig": plat_orig,
"plat_masked": plat_masked,
"plat_files": plat_files,
"mod_dir": mod_dir,
"modules_mod": os.path.join(mod_dir, "mod.rs"),
"mod_files": mod_files,
"biz": biz,
"mod_orig": mod_orig,
"mod_masked": mod_masked,
"packs": packs,
"pack_orig": pack_orig,
"pack_masked": pack_masked,
}
def analyze(contract_path, src_dir=None, packs_dir=None, code_snapshot=None):
"""契约 ↔ 代码 对账主体。
`code_snapshot` 给定时跳过代码侧扫描(反自证用:13 次分析共用一份代码快照)。
🔴 **参数名是 `code_snapshot` 而不是 `code`**:本函数体里 `code` 已经指
「**全部代码路由的扁平列表**」(`plat + biz + packs`)⇒ 同名会**静默覆盖**入参
⇒ 报 `list indices must be integers`。这类遮蔽最难查,所以从命名上隔开。
"""
rep = Report()
sections = contract_expect.load_sections(contract_path)
eps = sections["ENDPOINT"]
faces = sections["FACE"]
if code_snapshot is None:
code_snapshot = scan_code(src_dir, packs_dir)
plat = code_snapshot["plat"]
plat_orig = code_snapshot["plat_orig"]
plat_masked = code_snapshot["plat_masked"]
plat_files = code_snapshot["plat_files"]
mod_files = code_snapshot["mod_files"]
biz = code_snapshot["biz"]
mod_orig = code_snapshot["mod_orig"]
mod_masked = code_snapshot["mod_masked"]
packs = code_snapshot["packs"]
pack_orig = code_snapshot["pack_orig"]
pack_masked = code_snapshot["pack_masked"]
code = plat + biz + packs
code_index = {}
for r in code:
code_index.setdefault((r["method"], r["path"]), r)
# ---- CC2 端点总数 ----
ok = len(eps) == len(code)
rep.add("CC2", ok, "契约 %d 条 / 代码 %d 条" % (len(eps), len(code)))
# ---- CC3 契约 → 代码(存在 + 方法一致)----
bad3 = []
for row in eps:
key = (row["method"], row["path"])
if key in code_index:
continue
other = [k for k in code_index if k[1] == row["path"]]
if other:
bad3.append("%s %s:契约方法 %s,代码是 %s"
% (row["method"], row["path"], row["method"], "/".join(k[0] for k in other)))
else:
bad3.append("%s %s:代码里没有这条路由" % (row["method"], row["path"]))
rep.add("CC3", not bad3,
"契约的 %d 条端点在代码里都能找到(且方法一致)" % len(eps)
if not bad3 else "契约→代码 漂移 %d 条" % len(bad3))
for d in bad3:
rep.warn("CC3", d)
# ---- CC4 代码 → 契约(代码多出来的)----
bad4 = []
for r in code:
if (r["method"], r["path"]) not in {(x["method"], x["path"]) for x in eps}:
bad4.append("%s %s(%s)" % (r["method"], r["path"], r["owner"]))
rep.add("CC4", not bad4,
"代码里的 %d 条路由都在契约端点表里" % len(code)
if not bad4 else "代码→契约 漂移 %d 条" % len(bad4))
for d in bad4:
rep.warn("CC4", d)
# ---- CC5 归属层 ----
bad5 = []
for row in eps:
hit = code_index.get((row["method"], row["path"]))
if hit and hit["owner"] != row["owner"]:
bad5.append("%s %s:契约写 %s,代码在 %s" % (row["method"], row["path"], row["owner"], hit["owner"]))
rep.add("CC5", not bad5,
"每条端点的归属层与代码所在文件一致" if not bad5 else "归属层漂移 %d 条" % len(bad5))
for d in bad5:
rep.warn("CC5", d)
# ---- CC6 守卫 ----
#
# 🔴 **必须按 `source` 分派**(不能只看 owner):业务包的 app_code 与业务模块的
# app_code **同名**(都是 `asset`)⇒ 只看 owner 会把面 B 的路由拿去
# `modules/asset.rs` 推面 A 的守卫 ⇒ 推出 `asset/DataResource`(菜单路径),
# 而契约写的是 `permission.asset.dataResource`(点权限)⇒ **必假飘移**。
bad6 = []
unknown6 = []
for row in eps:
hit = code_index.get((row["method"], row["path"]))
if not hit:
continue
derived = None
if hit.get("source") == "pack":
# 面 B:从「spec.module_key ⇒ 菜单 f_en_code」**独立**推导
# (等价于 sspf-plugin 装载期的 GuardMismatch 闸门)。
orig = pack_orig.get(hit["owner"])
masked = pack_masked.get(hit["owner"])
if orig is not None:
derived = guard_of_pack_entity(orig, masked, hit.get("entity"))
elif hit["owner"] == "platform":
if hit["closure"]:
tail = plat_orig[plat_orig.find(hit["path"]):][:400]
derived = guard_of_closure(plat_orig, plat_masked, tail)
else:
derived = guard_of_platform(plat_files, hit["mod"], hit["fn"])
else:
derived = guard_of_module_with_pack_fallback(
mod_orig[hit["owner"]], mod_masked[hit["owner"]],
hit["owner"], pack_orig, pack_masked)
if derived is None:
unknown6.append("%s %s:推不出守卫" % (row["method"], row["path"]))
elif derived != row["guard"]:
bad6.append("%s %s:契约写 %s,代码是 %s"
% (row["method"], row["path"], row["guard"], derived))
rep.add("CC6", not bad6,
"每条端点的守卫与代码静态推导一致" if not bad6 else "守卫漂移 %d 条" % len(bad6))
for d in bad6:
rep.warn("CC6", d)
for d in unknown6:
rep.warn("CC6", d + "(**推不出 ≠ 一致**,请人工核对)")
# ---- CC7 钉子测试清单 ↔ 代码注册路由(双向覆盖)----
pins = []
# 面 A 的清单叫 REGISTERED;面 B 的清单在 P0 改名后叫 FACE_B_REGISTERED
# (原 JNPF_REGISTERED,按「前端不依赖的内部标识必须改」剥离)。
for name in ("REGISTERED", "FACE_B_REGISTERED"):
arr = parse_str_array(plat_orig, plat_masked,
r"const\s+" + name + r"\s*:\s*\[&str;\s*\d+\]\s*=")
if arr is not None:
pins.extend(arr)
# 🔴 钉子测试的**字面量清单**(`REGISTERED` / `JNPF_REGISTERED`)只覆盖**平台层**路由;
# 业务路由在钉子测试里是**遍历 `modules::ALL_ROUTES`** ⇒ 归 CC8 对账。
plat_routes = [r for r in code if r["owner"] == "platform"]
unmatched_pin = []
for p in pins:
if not any(path_to_regex(r["path"]).match(p) for r in plat_routes):
unmatched_pin.append(p)
unmatched_code = []
for r in plat_routes:
if not any(path_to_regex(r["path"]).match(p) for p in pins):
unmatched_code.append("%s %s" % (r["method"], r["path"]))
ok7 = not unmatched_pin and not unmatched_code
rep.add("CC7", ok7,
"钉子测试的 %d 条路径与代码注册的 %d 条平台路由双向覆盖" % (len(pins), len(plat_routes))
if ok7 else "钉子测试清单与代码路由对不上:清单多 %d / 代码多 %d"
% (len(unmatched_pin), len(unmatched_code)))
for d in unmatched_pin:
rep.warn("CC7", "钉子测试里的 %s 在代码里没有对应路由" % d)
for d in unmatched_code:
rep.warn("CC7", "代码里的 %s 没被钉子测试覆盖" % d)
# ---- CC8 业务路由三处一致 ----
#
# 面 A(`modules/*.rs`):各模块 ROUTES 常量 / router() 注册 / modules/mod.rs 的 ALL_ROUTES。
# 面 B(`packs/*`):各 `PackRoute` 常量 / `*_ROUTES` 数组 / `routes()` 返回该数组。
#
# 🔴 **包侧的坑**:声明了 `PackRoute` 常量**但忘了加进 `*_ROUTES` 数组**
# ⇒ 编译过、测试过、路由**不注册** ⇒ 集成期才发现的**静默 404**。
# ⇒ 名字集合双向对账(数组里多 / 常量里多,两边都查)。
bad8 = []
all_routes = []
for app, path in mod_files:
orig, masked = mod_orig[app], mod_masked[app]
const = parse_str_array(orig, masked, r"pub\s+const\s+ROUTES\s*:\s*\[&str;\s*\d+\]\s*=")
rs = [r for r in biz if r["owner"] == app]
reg = [r["path"] for r in rs]
if const is None:
bad8.append("%s:没有 ROUTES 常量" % app)
continue
if const != reg:
bad8.append("%s:ROUTES 常量 %s ≠ router() 注册 %s" % (app, const, reg))
all_routes.extend(const)
for pkg in sorted(pack_orig):
masked = pack_masked[pkg]
arr_name, arr_names = pack_route_array(masked)
declared = [r["const"] for r in packs if r["owner"] == pkg and r["const"]]
if arr_name is None:
if declared:
bad8.append("%s:声明了 %d 个 PackRoute 常量,但没有 *_ROUTES 数组收集它们"
"(⇒ 路由不会注册,静默 404)" % (pkg, len(declared)))
continue
if sorted(set(declared)) != sorted(set(arr_names)):
bad8.append("%s:%s = %s,而声明的 PackRoute 常量是 %s"
% (pkg, arr_name, sorted(set(arr_names)), sorted(set(declared))))
# `routes()` 必须返回这个数组(否则内核拿不到 ⇒ 同上)
m = re.search(r"fn\s+routes\s*\([^)]*\)[^{]*\{", masked)
if m:
span = brace_span(masked, masked.find("{", m.start()))
if arr_name not in masked[span[0]:span[1]]:
bad8.append("%s:routes() 没有返回 %s" % (pkg, arr_name))
# modules/mod.rs 的 ALL_ROUTES(形如 demo::ROUTES[0])⇒ 解析成具体路径
mod_mod = code_snapshot["modules_mod"]
if os.path.isfile(mod_mod):
orig = read(mod_mod)
masked = mask_rust(orig)
m = re.search(r"pub\s+const\s+ALL_ROUTES\s*:\s*&\[&str\]\s*=\s*&\[", masked)
if m:
# 🔴 数组本体是 `&[ ... ]` ⇒ 要**配对**找结尾的 `]`(不能 find 第一个 `]`)
open_at = masked.find("[", m.end() - 1)
depth = 0
close_at = -1
for k in range(open_at, len(masked)):
if masked[k] == "[":
depth += 1
elif masked[k] == "]":
depth -= 1
if depth == 0:
close_at = k
break
entries = re.findall(r"([a-z_]+)::ROUTES\[(\d+)\]", orig[open_at:close_at])
resolved = []
for app, idx in entries:
pair = (mod_orig.get(app, ""), mod_masked.get(app, ""))
c = parse_str_array(pair[0], pair[1],
r"pub\s+const\s+ROUTES\s*:\s*\[&str;\s*\d+\]\s*=")
if c and int(idx) < len(c):
resolved.append(c[int(idx)])
# 🔴 比**集合**不比你序(`mod_files` 是按文件名排序的,ALL_ROUTES 是按声明序的)
if sorted(resolved) != sorted(all_routes):
bad8.append("modules/mod.rs 的 ALL_ROUTES %s ≠ 各模块 ROUTES 拼接 %s"
% (sorted(resolved), sorted(all_routes)))
else:
bad8.append("modules/mod.rs 里找不到 ALL_ROUTES")
rep.add("CC8", not bad8,
"业务路由三处一致(模块:ROUTES 常量 / router() / ALL_ROUTES;"
"包:PackRoute 常量 / *_ROUTES 数组 / routes())"
if not bad8 else "业务路由清单对不上 %d 处" % len(bad8))
for d in bad8:
rep.warn("CC8", d)
# ---- CC9 契约面计数自洽 ----
bad9 = []
for row in faces:
actual = sum(1 for e in eps if e["face"] == row["face"])
if str(actual) != row["count"]:
bad9.append("面 %s:契约 [FACE] 登记 %s 条,[ENDPOINT] 里实际 %d 条"
% (row["face"], row["count"], actual))
total_face = sum(int(r["count"]) for r in faces)
if total_face != len(eps):
bad9.append("[FACE] 合计 %d ≠ [ENDPOINT] 行数 %d" % (total_face, len(eps)))
rep.add("CC9", not bad9,
"各契约面的条数与 [ENDPOINT] 自洽(A/B/AB 合计 %d)" % total_face
if not bad9 else "契约面计数不自洽 %d 处" % len(bad9))
for d in bad9:
rep.warn("CC9", d)
# ---- CC10 官方端点台账 ↔ 代码真实路由(双向)----
#
# 🔴 为什么要它:面 B 的「做了多少」原先只有**尺子的断言数**(18/18)这一个信号,
# 而**官方端点全表**(JNPF_SOURCE_AUDIT.md §4)是**散文表格** ⇒ 官方端点做没做、
# 做到什么程度,**没有机器可读的账** ⇒ 「覆盖率」只能靠人读散文。
# 本检查把契约附录 A 的 [OFFICIAL](机器可读)当成**账本**,
# 与代码里**真实注册**的路由双向对账,并打印覆盖 N/M。
off = sections["OFFICIAL"]
def norm_path(p):
# `{param}` 归一 ⇒ 官方台账与代码的**参数名不同**也不算漂移
return re.sub(r"\{[^/{}]*\}", "{}", p)
code_norm = {}
for r in code:
code_norm.setdefault((r["method"], norm_path(r["path"])), r)
eps_face = {}
for e in eps:
eps_face[(e["method"], norm_path(e["path"]))] = e["face"]
bad10 = []
counts = {"implemented": 0, "partial": 0, "absent": 0, "oos": 0}
for row in off:
method, path, status = row["method"], row["path"], row["status"]
if status not in counts:
bad10.append("台账状态非法 %r(%s %s)" % (status, method, path))
continue
if method == "*" or path.endswith("/**"):
# 「一族端点」的范围声明(如数据权限链接)⇒ 不做存在性对账,只计入 oos
counts["oos"] += 1
continue
hit = code_norm.get((method, norm_path(path)))
if status in ("implemented", "partial"):
counts[status] += 1
if hit is None:
bad10.append("台账写 %s(%s %s),代码里**没有**这条路由" % (status, method, path))
else:
counts[status] += 1
if hit is not None:
bad10.append("台账写 %s(%s %s),代码里却**注册了**这条路由" % (status, method, path))
# 反向:代码里**面 B / 共用**的每条路由,都必须在台账里**有账**(防止"实现了但没记账")
#
# 🔴 **业务包的路由不在此列**:`[OFFICIAL]` 是**官方端点**台账(本仓对官方 JNPF
# 契约面的覆盖账本)。包路由(`/api/asset/DataResource`)是**业务自己的端点**,
# 只是**借用了官方形状** ⇒ 官方根本没有这一条 ⇒ 记账会把它塞进「官方覆盖 N/M」
# 的分子里 ⇒ **覆盖率说谎**(凭空多出 3 条"官方端点")。
# ⇒ 包路由的账在 `[ENDPOINT]`(由 `pack-sync.py` 生成,CC2–CC6 已逐条对账)。
off_index = set((r["method"], norm_path(r["path"])) for r in off if r["method"] != "*")
pack_skipped = 0
for r in code:
key = (r["method"], norm_path(r["path"]))
if r.get("source") == "pack":
if eps_face.get(key) in ("B", "AB"):
pack_skipped += 1
continue
if eps_face.get(key) in ("B", "AB") and key not in off_index:
bad10.append("代码注册了面 %s 路由 %s %s,但官方端点台账里**没有这一条**"
% (eps_face.get(key), r["method"], r["path"]))
covered = counts["implemented"] + counts["partial"]
total = covered + counts["absent"]
rep.add("CC10", not bad10,
"官方端点台账与代码真实路由双向对得上(已落地 %d / 在范围 %d)" % (covered, total)
if not bad10 else "官方端点台账漂移 %d 处" % len(bad10))
for d in bad10:
rep.warn("CC10", d)
rep.info("CC10-COVER",
"官方端点覆盖 %d/%d(implemented %d / partial %d / absent %d;oos %d 单列,不进分母)"
% (covered, total, counts["implemented"], counts["partial"],
counts["absent"], counts["oos"]))
if pack_skipped:
rep.info("CC10-PACK",
"另有 %d 条业务包路由(面 B 形状)**不计入**官方台账"
"(官方没有这些端点,计入会让覆盖率说谎;它们的账在 [ENDPOINT])"
% pack_skipped)
return rep
# ---------------------------------------------------------------- 反自证
def self_test(contract=None, src_dir=None, packs_dir=None):
"""🔴 **反自证**:造几种已知漂移 ⇒ 必须被抓到;再验一遍真实契约**没有**漂移。
永远返回「干净」的尺子 = 没有尺子 ⇒ 这一段是尺子可信的前提。
"""
contract = contract or os.path.join(ROOT, "docs", "contract.md")
src_dir = src_dir or os.path.join(ROOT, "src", "backend", "src")
packs_dir = packs_dir or os.path.join(ROOT, "packs")
if not os.path.isfile(contract):
sys.stderr.write("check-contract-scan: 找不到契约 %s\n" % contract)
return 2
# 🔴 **代码侧只扫一次**:12 个用例注入的都是**契约**漂移,代码一动不动
# ⇒ 复用同一份快照(55s → 约 12s)。快照只在进程内,不会过期。
# ⚠️ 这份快照**必须**同时喂给下面第一个 `analyze`(真实契约那一跑)——
# 否则它内部会自己再 `scan_code` 一遍,等于白扫一次全仓(实测 0.4s)。
code_snapshot = scan_code(src_dir, packs_dir)
base = analyze(contract, code_snapshot=code_snapshot)
drifts = [c for c in base.checks if c[1] == "DRIFT"]
if drifts:
for cid, _s, detail in drifts:
sys.stderr.write("check-contract-scan: 真实契约就有漂移(%s: %s)\n" % (cid, detail))
return 1
with io.open(contract, encoding="utf-8") as fh:
text = fh.read()
def mutate(fn):
return fn(text)
cases = []
def add_row(t):
return t.replace("[ENDPOINT]\n", "[ENDPOINT]\nA\tGET\t/api/zzz/Fake/List\t登录\tplatform\n", 1)
def drop_row(t):
return t.replace("A\tGET\t/api/health\t无\tplatform\n", "", 1)
def bad_method(t):
return t.replace("A\tGET\t/api/health\t无\tplatform\n",
"A\tPOST\t/api/health\t无\tplatform\n", 1)
def bad_guard(t):
return t.replace("A\tGET\t/api/ssw/sys/User/List\tsystem/User\tplatform\n",
"A\tGET\t/api/ssw/sys/User/List\t登录\tplatform\n", 1)
def bad_owner(t):
return t.replace("A\tGET\t/api/ssw/demo/DemoItem/List\t登录\tdemo\n",
"A\tGET\t/api/ssw/demo/DemoItem/List\t登录\tplatform\n", 1)
def bad_face(t):
# 🔴 **动态取现值再减 1**(别写死数字):加端点会让 [FACE] 的 A 条数变化,
# 写死的锚点会过期 ⇒ 反自证用例静默失效(「改不动契约」)。
m = re.search(r"(?m)^A\t(\d+)\t", t)
if not m:
return t
return t[: m.start(1)] + str(int(m.group(1)) - 1) + t[m.end(1):]
# ---- CC10 的三类漂移(官方端点台账 ↔ 代码真实路由)----
def off_says_absent(t):
# 台账把「代码里有」的端点说成未实现
return t.replace(
"GET\t/api/permission/Users\timplemented\t",
"GET\t/api/permission/Users\tabsent\t", 1)
def off_fake_path(t):
# 台账说已实现,但那条路径代码里根本没有
return t.replace(
"GET\t/api/system/Menu/ModuleBySystem\timplemented\t",
"GET\t/api/system/Menu/ModuleBySystemXX\timplemented\t", 1)
def off_drop_row(t):
# 代码里有面 B 路由,但台账里没记账("实现了但没记账")
return t.replace(
"GET\t/api/permission/Role\timplemented\tRoleController.java:99-100\t"
"面 B 已落地:PageListVO 形状\n", "", 1)
# ---- 包路由的三类漂移(批次 12:`packs/*` 进了代码侧)----
def pack_guard_wrong(t):
# 包的 3 条面 B 路由里,把守卫写成面 A 的菜单路径(**最容易犯的错**:
# 「两套守卫并存」记混 ⇒ 集成时权限判据错 ⇒ 而且**静默**)
return t.replace(
"B\tGET\t/api/asset/DataResource\tpermission.asset.dataResource\tasset\n",
"B\tGET\t/api/asset/DataResource\tasset/DataResource\tasset\n", 1)
def pack_drop_row(t):
# 包声明了 DELETE,但契约里没登记(生成段被手删 / 同步没跑)
return t.replace(
"B\tDELETE\t/api/asset/DataResource/{id}\t"
"permission.asset.dataResource\tasset\n", "", 1)
def pack_owner_wrong(t):
# 包路由的 owner 写成 platform(复制粘贴时的经典手误)⇒ 归属层串线
return t.replace(
"B\tDELETE\t/api/asset/DataResource/{id}\t"
"permission.asset.dataResource\tasset\n",
"B\tDELETE\t/api/asset/DataResource/{id}\t"
"permission.asset.dataResource\tplatform\n", 1)
cases.append(("契约多一条端点", add_row, "CC3"))
cases.append(("契约少一条端点", drop_row, "CC2"))
cases.append(("方法写错", bad_method, "CC3"))
cases.append(("守卫写错", bad_guard, "CC6"))
cases.append(("归属层写错", bad_owner, "CC5"))
cases.append(("契约面计数写错", bad_face, "CC9"))
cases.append(("台账把已实现的端点说成未实现", off_says_absent, "CC10"))
cases.append(("台账写了代码里没有的端点", off_fake_path, "CC10"))
cases.append(("面 B 路由没记账", off_drop_row, "CC10"))
# 🔴 下面三条是**包路由专属**的漂移:批次 12 之后包路由也会出现在 [ENDPOINT] 里,
# 如果尺子对它们不敏感,等于「加包 = 免检」。
cases.append(("包路由的守卫写成了面 A 形状", pack_guard_wrong, "CC6"))
cases.append(("包路由没登记进契约", pack_drop_row, "CC2"))
cases.append(("包路由的 owner 写错", pack_owner_wrong, "CC5"))
failed = 0
for name, fn, expect in cases:
mutated = mutate(fn)
if mutated == text:
sys.stderr.write("check-contract-scan: 反自证用例「%s」改不动契约(锚点没了)\n" % name)
failed += 1
continue
tmpdir = tempfile.mkdtemp(prefix="cc-selftest-")
tmp = os.path.join(tmpdir, "contract.md")
with io.open(tmp, "w", encoding="utf-8") as fh:
fh.write(mutated)
try:
rep = analyze(tmp, code_snapshot=code_snapshot)
except Exception as exc: # noqa: BLE001
sys.stderr.write("check-contract-scan: 反自证用例「%s」分析异常:%s\n" % (name, exc))
failed += 1
continue
finally:
shutil.rmtree(tmpdir, ignore_errors=True)
hit = [c for c in rep.checks if c[0] == expect and c[1] == "DRIFT"]
if hit:
print(" ✅ 反自证「%s」被 %s 抓到" % (name, expect))
else:
print(" ❌ 反自证「%s」**没**被 %s 抓到(尺子被改弱了?)" % (name, expect))
failed += 1
if failed:
sys.stderr.write("check-contract-scan: 反自证失败 %d 例\n" % failed)
return 1
print("反自证 %d 例全部通过(真实契约零漂移 + 每种注入漂移都被抓到)" % len(cases))
return 0
def main(argv):
contract = os.path.join(ROOT, "docs", "contract.md")
src_dir = os.path.join(ROOT, "src", "backend", "src")
# 🔴 **业务包目录**(默认 `<repo>/packs`)—— 不扫它 ⇒ 包路由不在「代码真实路由」
# 里 ⇒ CC2/CC3 判**假漂移**(契约有、代码说没有),这类假警报最耗费信任。
packs_dir = os.path.join(ROOT, "packs")
i = 1
while i < len(argv):
if argv[i] == "--contract" and i + 1 < len(argv):
contract = argv[i + 1]
i += 2
continue
if argv[i] == "--src" and i + 1 < len(argv):
src_dir = argv[i + 1]
i += 2
continue
if argv[i] == "--packs" and i + 1 < len(argv):
packs_dir = argv[i + 1]
i += 2
continue
if argv[i] == "--self-test":
# 🔴 反自证也要扫 `packs/`:不然「真实契约零漂移」这一关会因为
# 包路由只在契约里、不在代码侧而**假失败**。
return self_test(contract, src_dir, packs_dir)
sys.stderr.write("check-contract-scan: 未知参数 %r\n" % argv[i])
return 2
try:
rep = analyze(contract, src_dir, packs_dir)
except contract_expect.ContractError as exc:
sys.stderr.write("check-contract-scan: %s\n" % exc)
return 2
for line in rep.lines():
print(line)
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv))