117 lines
5.6 KiB
Python
117 lines
5.6 KiB
Python
"""Generate a reviewable business-resource inventory from PMS code; never enable endpoints."""
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
import json
|
|
from pathlib import Path
|
|
import re
|
|
|
|
|
|
def _body(text: str, opening: int) -> tuple[str, int]:
|
|
depth = 0
|
|
quote = None
|
|
escaped = False
|
|
for index in range(opening, len(text)):
|
|
char = text[index]
|
|
if quote:
|
|
if escaped:
|
|
escaped = False
|
|
elif char == "\\":
|
|
escaped = True
|
|
elif char == quote:
|
|
quote = None
|
|
continue
|
|
if char in "\"'":
|
|
quote = char
|
|
elif char == "{":
|
|
depth += 1
|
|
elif char == "}":
|
|
depth -= 1
|
|
if depth == 0:
|
|
return text[opening + 1:index], index + 1
|
|
return "", len(text)
|
|
|
|
|
|
def discover(root: Path) -> dict:
|
|
source_root = root / "ruoyi-admin/src/main/java"
|
|
if not source_root.is_dir() or not (root / "pom.xml").is_file():
|
|
raise ValueError("Expected a PMS repository root")
|
|
files = sorted(source_root.rglob("*Controller.java"))
|
|
candidates = []
|
|
for file in files:
|
|
text = file.read_text(encoding="utf-8-sig")
|
|
class_match = re.search(r"public\s+class\s+(\w+)", text)
|
|
if not class_match:
|
|
continue
|
|
prefix = text[:class_match.start()]
|
|
mappings = re.findall(r"@RequestMapping\s*\([^)]*\"([^\"]+)\"[^)]*\)", prefix)
|
|
base = mappings[-1] if mappings else ""
|
|
imports = {name.rsplit(".", 1)[-1]: name for name in re.findall(r"import\s+([\w.]+);", text)}
|
|
fields = {name: kind for kind, name in re.findall(r"private\s+(I\w+Service)\s+(\w+)\s*;", text)}
|
|
prior_end = class_match.end()
|
|
signature = re.compile(r"public\s+([\w<>?, .\[\]]+)\s+(\w+)\s*\(([^)]*)\)\s*(?:throws\s+[\w, ]+)?\s*\{")
|
|
for method in signature.finditer(text, class_match.end()):
|
|
body, ending = _body(text, method.end() - 1)
|
|
annotations = text[prior_end:method.start()]
|
|
prior_end = ending
|
|
returned, name, parameters = method.groups()
|
|
if not ("TableDataInfo" in returned or returned.strip().startswith("List<")):
|
|
continue
|
|
calls = re.findall(r"(\w+)\.(select\w+)\s*\(\s*(\w+)\s*\)", body)
|
|
call = next((item for item in calls if item[0] in fields), None)
|
|
if not call:
|
|
continue
|
|
variable, read_method, parameter = call
|
|
param = re.search(r"\b(\w+)\s+" + re.escape(parameter) + r"\b", parameters)
|
|
entity = imports.get(param.group(1), "") if param else ""
|
|
permissions = re.findall(r'@RequiresPermissions\s*\((.*?)\)', annotations, re.S)
|
|
permission_names = re.findall(r'"([^"]+)"', permissions[-1]) if permissions else []
|
|
mapping = re.findall(r'@(Post|Get|Request)Mapping\s*\((.*?)\)', annotations, re.S)
|
|
method_path = ""
|
|
http = "UNKNOWN"
|
|
if mapping:
|
|
http = mapping[-1][0].upper()
|
|
paths = re.findall(r'"([^"]*)"', mapping[-1][1])
|
|
method_path = paths[0] if paths else ""
|
|
entity_fields = []
|
|
if entity:
|
|
entity_file = source_root / (entity.replace(".", "/") + ".java")
|
|
if entity_file.is_file():
|
|
content = entity_file.read_text(encoding="utf-8-sig")
|
|
for field in re.finditer(r"private\s+(?!static\b)([\w<>?, .\[\]]+)\s+(\w+)\s*;", content):
|
|
before = content[max(0, field.start() - 220):field.start()]
|
|
before = before.rsplit(";", 1)[-1]
|
|
labels = re.findall(r'@Excel\s*\(\s*name\s*=\s*"([^"]+)"', before)
|
|
entity_fields.append({"name": field.group(2), "type": field.group(1).strip(), "label_candidate": labels[-1] if labels else field.group(2)})
|
|
risky = bool(re.search(r"\.\s*(insert|update|delete|remove|save|resolve)\w*\s*\(", body))
|
|
candidates.append({
|
|
"candidate_id": class_match.group(1) + "." + name,
|
|
"reviewed": False, "executable": False,
|
|
"controller": str(file.relative_to(root)).replace("\\", "/"),
|
|
"http_method": http, "path": base + method_path,
|
|
"source_service": imports.get(fields[variable], fields[variable]),
|
|
"source_method": read_method, "entity": entity,
|
|
"permissions_candidate": permission_names,
|
|
"fields_candidate": entity_fields,
|
|
"review_required": ["业务名称及同义词", "字段白名单及敏感字段", "行级可见范围", "关联关系", "是否存在读取副作用", "筛选是否真正作用于查询"],
|
|
"has_write_calls": risky,
|
|
})
|
|
return {"controller_count": len(files), "candidate_count": len(candidates),
|
|
"notice": "候选清单来自静态代码扫描,不是授权目录;不会被运行时加载或自动执行。", "candidates": candidates}
|
|
|
|
|
|
def main() -> None:
|
|
parser = argparse.ArgumentParser()
|
|
parser.add_argument("--pms-root", type=Path, required=True)
|
|
parser.add_argument("--output", type=Path, required=True)
|
|
args = parser.parse_args()
|
|
result = discover(args.pms_root.resolve())
|
|
args.output.parent.mkdir(parents=True, exist_ok=True)
|
|
args.output.write_text(json.dumps(result, ensure_ascii=False, indent=2), encoding="utf-8")
|
|
print(json.dumps({"controllers": result["controller_count"], "candidates": result["candidate_count"],
|
|
"automatically_enabled": 0, "output": str(args.output)}, ensure_ascii=False))
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|