iam_role_keys_sync.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  1. #!/usr/bin/env python3
  2. """把 `src/config/iam_role_keys.toml`(配置真源)幂等地同步到平台 IAM 的角色×权限键。
  3. 鉴权是两层(总则§8.4 纪律 1「网关判权限键,服务判角色」):
  4. · 本脚本只配**第一层**——网关能不能把请求放进来;
  5. · 「只能动负责区域内的」「只能维护本团队」这类判定在服务端 handler,
  6. ⛔ 由本脚本或键面表达(那要 join dim_node_ancestor/bos_data_scope)。
  7. 与旧探针脚本的区别(`temp/role_keys_sync.py`):
  8. · 键面口径进版本管理(`src/config/iam_role_keys.toml`),⛔ 埋在探针的 ROLE_KEYS 里;
  9. · **无幂等短路**:每次都重算「在册 openapi 全集 ∩ 角色模式 − 角色现值」再补差集,
  10. 不会像旧脚本那样 `perm_bound=true` 之后新增接口的键永远补不进去。
  11. 用法:
  12. export SEOH_IAM_TOKEN=<developer 票> # 档一(角色配置)合法身份
  13. export SEOH_PROJECT_ID=... SEOH_TENANT_ID=...
  14. python3 scripts/iam_role_keys_sync.py # 只读差分;有缺口退出码 2
  15. python3 scripts/iam_role_keys_sync.py --apply # 补绑缺失键
  16. python3 scripts/iam_role_keys_sync.py --apply --prune # 另把在册 `bos.*` 的多余键解绑
  17. python3 scripts/iam_role_keys_sync.py --role klt.bos.role.opsMain
  18. python3 scripts/iam_role_keys_sync.py --role-id klt.bos.role.opsMain=377167980045283328
  19. ⚠️ 配置是**下界**:脚本只保证「必须持有的键都在」,多余键默认**只报告不回收**
  20. (非 `bos.*` 的 `resource_metadata.*`/`uos.object.*`/`iam.*` 一律不碰)。
  21. `--prune` 只解绑**在册 openapi 声明过、但配置没要**的 `bos.*` 键——这会改变现网行为,
  22. 先只读看清清单再决定。
  23. ⚠️ `resource_range` 沿用建角约定恒 `"*"`(`bos.*` 为扁平业务键,⛔ 区域树键;
  24. 平台 `bind` 强制显式 range,省略回 `11103`)。
  25. ⚠️ 解绑只能按 `(permission_key, "*")` 精确元组;`role/get@v1` 不回 range,
  26. 若某键当初用的是非 `*` range,解绑失败会被报出,⛔ 静默换 range 重试。
  27. ⚠️ 角色分配(`identity_role/bind@v1`)不在本脚本范围:U-110 冻结中,见 18 册。
  28. """
  29. from __future__ import annotations
  30. import argparse
  31. import json
  32. import os
  33. import re
  34. import ssl
  35. import sys
  36. import tomllib
  37. import urllib.error
  38. import urllib.request
  39. from typing import Any
  40. ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
  41. SPEC = os.path.join(ROOT, "src", "bin", "klt-bos", "openapi.yaml")
  42. CONFIG = os.path.join(ROOT, "src", "config", "iam_role_keys.toml")
  43. LEDGER = os.path.join(ROOT, "temp", "seoh_p5_ledger.json")
  44. IAM_PATH = "/api/system/seoh-iam-role"
  45. OK = 10000
  46. # ── HTTP ─────────────────────────────────────────────────────────────────────
  47. def _ssl_ctx(insecure: bool, ca_cert: str | None) -> ssl.SSLContext:
  48. if insecure:
  49. ctx = ssl.create_default_context()
  50. ctx.check_hostname = False
  51. ctx.verify_mode = ssl.CERT_NONE
  52. return ctx
  53. return ssl.create_default_context(cafile=ca_cert) if ca_cert else ssl.create_default_context()
  54. def call(base: str, path: str, data: dict[str, Any] | None, token: str,
  55. ctx: ssl.SSLContext) -> dict[str, Any]:
  56. body = json.dumps({"data": data or {}}).encode()
  57. req = urllib.request.Request(base.rstrip("/") + IAM_PATH + path, data=body, method="POST")
  58. req.add_header("Content-Type", "application/json")
  59. req.add_header("Authorization", f"Bearer {token}")
  60. req.add_header("X-Seoh-Env", os.environ.get("SEOH_HTTP_ENV", "dev"))
  61. try:
  62. with urllib.request.urlopen(req, context=ctx, timeout=60) as r:
  63. return json.loads(r.read().decode())
  64. except urllib.error.HTTPError as e:
  65. raw = e.read().decode(errors="replace")
  66. try:
  67. return json.loads(raw)
  68. except Exception: # noqa: BLE001
  69. return {"code": f"HTTP{e.code}", "message": raw[:300]}
  70. except Exception as e: # noqa: BLE001
  71. return {"code": -1, "message": f"<transport {e}>"}
  72. # ── 键全集:在册 openapi ──────────────────────────────────────────────────────
  73. def _codes(txt: str, section: str) -> dict[str, str]:
  74. m = re.search(rf"^ {section}:\n([\s\S]*?)(?=^ \S)", txt, re.M)
  75. if not m:
  76. return {}
  77. return dict(re.findall(r"^ (\w+):\n code: '?([\w.]+)'?", m.group(1), re.M))
  78. def declared_keys(spec: str = SPEC) -> set[str]:
  79. """在册路由的权限键全集。
  80. ⚠️ 注册用 openapi 的扩展值是 `$ref`(`#/components/x-resource-types/<k>/code`),
  81. 不是字面量;直接按 `x-resource-type: <字面量>` 抓会一条也抓不到。
  82. """
  83. txt = open(spec, encoding="utf-8").read()
  84. res, act = _codes(txt, "x-resource-types"), _codes(txt, "x-actions")
  85. out: set[str] = set()
  86. for m in re.finditer(
  87. r"x-resource-type:\n +\$ref: '#/components/x-resource-types/(\w+)/code'"
  88. r"\n +x-action:\n +\$ref: '#/components/x-actions/(\w+)/code'"
  89. r"(?:\n +x-version: (\w+))?",
  90. txt,
  91. ):
  92. rcode, acode = res.get(m.group(1)), act.get(m.group(2))
  93. if rcode and acode:
  94. out.add(f"{rcode}.{acode}@{m.group(3) or 'v1'}")
  95. return out
  96. # ── 配置 → 期望键集 ───────────────────────────────────────────────────────────
  97. def expand(patterns: list[str], universe: set[str], role: str) -> set[str]:
  98. """把 `bos.<res>.*` / `bos.<res>.<action>` 展开成具体键。
  99. 过期模式(匹配不到任何在册键)直接失败:保留它只会让「以为配了」变成静默无权限。
  100. """
  101. out: set[str] = set()
  102. stale: list[str] = []
  103. for p in patterns:
  104. if p == "*":
  105. out |= universe
  106. elif p.endswith(".*"):
  107. out |= {k for k in universe if k.startswith(p[:-2] + ".")}
  108. else:
  109. out |= {k for k in universe if k.startswith(p + "@")}
  110. if p != "*" and not any(
  111. k.startswith(p[:-2] + ".") if p.endswith(".*") else k.startswith(p + "@")
  112. for k in universe
  113. ):
  114. stale.append(p)
  115. if stale:
  116. raise SystemExit(f"[{role}] ⛔ 模式匹配不到任何在册键:{stale}")
  117. return out
  118. def desired(conf: dict[str, Any], universe: set[str]) -> dict[str, set[str]]:
  119. common = list((conf.get("defaults") or {}).get("include") or [])
  120. out: dict[str, set[str]] = {}
  121. for role, spec in (conf.get("roles") or {}).items():
  122. keys = set(universe) if spec.get("all") else set()
  123. keys |= expand(list(spec.get("include") or []), universe, role)
  124. keys |= expand(common, universe, f"{role}/defaults")
  125. if not keys:
  126. raise SystemExit(f"[{role}] ⛔ 键面为空:未配 all 也没有 include")
  127. out[role] = keys
  128. return out
  129. # ── 角色 ID 解析 ──────────────────────────────────────────────────────────────
  130. def resolve_role_ids(codes: list[str], base: str, token: str, ctx: ssl.SSLContext,
  131. overrides: dict[str, str]) -> dict[str, str]:
  132. ids: dict[str, str] = {}
  133. missing: list[str] = []
  134. for code in codes:
  135. if code in overrides:
  136. ids[code] = overrides[code]
  137. continue
  138. short = code.rsplit(".", 1)[-1]
  139. if os.path.exists(LEDGER):
  140. try:
  141. rid = (json.load(open(LEDGER, encoding="utf-8")).get(short) or {}).get("role_id")
  142. if rid:
  143. ids[code] = rid
  144. continue
  145. except Exception: # noqa: BLE001
  146. pass
  147. missing.append(code)
  148. for code in list(missing):
  149. short = code.rsplit(".", 1)[-1]
  150. r = call(base, "/role/get_list@v1", {
  151. "pagination": {"page_no": 1, "page_size": 200},
  152. "filters": {"code": short}, **SCOPE,
  153. }, token, ctx)
  154. items = ((r.get("data") or {}).get("items")) or []
  155. for it in items:
  156. if (it.get("code") or "") == code:
  157. ids[code] = it.get("role_id") or it.get("id")
  158. break
  159. if code not in ids:
  160. print(f"[!] 解析不到角色 ID:{code}(role/get_list code={r.get('code')} "
  161. f"msg={str(r.get('message'))[:160]})")
  162. for code in missing:
  163. if code not in ids:
  164. print(f" ↳ 可用 --role-id {code}=<id> 或先跑一次账号侧探针把 role_id 落盘;"
  165. f"⚠️ `role/get_list` 受「调用方须覆盖目标角色全部键」过滤,developer 票可能看不到高权角色")
  166. return ids
  167. # ── 主流程 ───────────────────────────────────────────────────────────────────
  168. SCOPE: dict[str, Any] = {}
  169. SHOW_LIMIT = 20
  170. def _show(keys: list[str], verbose: bool) -> str:
  171. if verbose or len(keys) <= SHOW_LIMIT:
  172. return str(keys)
  173. return f"{keys[:SHOW_LIMIT]} …(共 {len(keys)},加 --verbose 看全量)"
  174. def main() -> int:
  175. ap = argparse.ArgumentParser(description="同步角色×权限键(幂等)")
  176. ap.add_argument("--apply", action="store_true", help="写平台;缺省只读差分")
  177. ap.add_argument("--prune", action="store_true",
  178. help="解绑在册 bos.* 里配置没要的键(改变现网行为,先只读看清单)")
  179. ap.add_argument("--verbose", action="store_true", help="打印完整键清单")
  180. ap.add_argument("--role", action="append", default=[], help="只处理指定角色 code(可重复)")
  181. ap.add_argument("--role-id", action="append", default=[], help="CODE=ID 覆盖(可重复)")
  182. ap.add_argument("--config", default=CONFIG)
  183. ap.add_argument("--spec", default=SPEC)
  184. ap.add_argument("--gateway", default=os.environ.get("SEOH_GATEWAY", "https://127.0.0.1:3000"))
  185. ap.add_argument("--insecure", action="store_true", help="跳过 TLS 校验(仅 dev)")
  186. ap.add_argument("--ca-cert", default=os.environ.get("SEOH_CA_CERT"))
  187. args = ap.parse_args()
  188. token = os.environ.get("SEOH_IAM_TOKEN", "").strip()
  189. if not token:
  190. print("⛔ 缺 SEOH_IAM_TOKEN(developer 票;档一=角色配置的合法身份)")
  191. return 1
  192. project = os.environ.get("SEOH_PROJECT_ID", "").strip()
  193. if not project:
  194. print("⛔ 缺 SEOH_PROJECT_ID(end_user scope 锚点)")
  195. return 1
  196. SCOPE.update({
  197. "scope_type": "end_user", "scope_id": project,
  198. "env": os.environ.get("SEOH_DATA_ENV", "nonprod"),
  199. "stage": os.environ.get("SEOH_STAGE", "dev"),
  200. })
  201. ctx = _ssl_ctx(args.insecure, args.ca_cert)
  202. universe = declared_keys(args.spec)
  203. conf = tomllib.loads(open(args.config, encoding="utf-8").read())
  204. want = desired(conf, universe)
  205. overrides = dict(x.split("=", 1) for x in args.role_id if "=" in x)
  206. roles = args.role or list(want)
  207. unknown = [r for r in roles if r not in want]
  208. if unknown:
  209. print(f"⛔ 配置里没有这些角色:{unknown}")
  210. return 1
  211. print(f"# 在册键 = {len(universe)}({os.path.relpath(args.spec, ROOT)})")
  212. print(f"# 配置 = {os.path.relpath(args.config, ROOT)} 角色 {len(roles)}")
  213. ids = resolve_role_ids(roles, args.gateway, token, ctx, overrides)
  214. drift, failed = 0, 0
  215. for role in roles:
  216. rid = ids.get(role)
  217. if not rid:
  218. failed += 1
  219. continue
  220. g = call(args.gateway, "/role/get@v1", {"role_id": rid, **SCOPE}, token, ctx)
  221. if g.get("code") != OK:
  222. print(f"\n[{role}] ⛔ role/get code={g.get('code')} msg={str(g.get('message'))[:200]}")
  223. failed += 1
  224. continue
  225. have = set(((g.get("data") or {}).get("permission_keys")) or [])
  226. missing = sorted(want[role] - have)
  227. # 「多」只统计**在册 openapi 声明过**的键:平台侧键(resource_metadata.*/
  228. # uos.object.*/iam.*)不归本矩阵管,⛔ 计入漂移、⛔ 交给 --prune。
  229. extra = sorted((have - want[role]) & universe)
  230. foreign = sorted((have - want[role]) - universe)
  231. print(f"\n== {role}({rid}) 现值 {len(have)} 枚 / 期望(下界) {len(want[role])} 枚 ==")
  232. print(f" 缺 {len(missing)}:{_show(missing, args.verbose)}")
  233. print(f" 多(在册 bos.*) {len(extra)}:{_show(extra, args.verbose)}")
  234. if foreign:
  235. print(f" 非本矩阵键 {len(foreign)}:{_show(foreign, args.verbose)}")
  236. if missing:
  237. drift += 1
  238. if not (args.apply and (missing or (args.prune and extra))):
  239. continue
  240. if missing:
  241. b = call(args.gateway, "/role_permission/bind@v1", {
  242. "role_id": rid,
  243. "permission_items": [{"permission_key": k, "resource_range": "*"} for k in missing],
  244. **SCOPE,
  245. }, token, ctx)
  246. print(f" bind → code={b.get('code')} msg={str(b.get('message'))[:220]}")
  247. if b.get("code") != OK:
  248. failed += 1
  249. if args.prune and extra:
  250. print(f" ⚠️ --prune:将解绑 {len(extra)} 枚在册 bos.* 键(改变现网行为)")
  251. u = call(args.gateway, "/role_permission/unbind@v1", {
  252. "role_id": rid,
  253. "permission_items": [{"permission_key": k, "resource_range": "*"} for k in extra],
  254. **SCOPE,
  255. }, token, ctx)
  256. print(f" unbind → code={u.get('code')} msg={str(u.get('message'))[:220]}")
  257. if u.get("code") != OK:
  258. failed += 1
  259. g2 = call(args.gateway, "/role/get@v1", {"role_id": rid, **SCOPE}, token, ctx)
  260. after = set(((g2.get("data") or {}).get("permission_keys")) or [])
  261. print(f" 复读 {len(after)} 枚,+{len(after - have)} / -{len(have - after)}")
  262. if failed:
  263. print(f"\n⛔ 失败 {failed} 项")
  264. return 1
  265. if drift and not args.apply:
  266. print("\n[i] 存在缺口;加 --apply 补绑(只读模式退出码 2)")
  267. return 2
  268. print("\n✅ 下界键齐备(多余的键只报告,⛔ 自动回收)" if not (args.apply and drift)
  269. else "\n✅ 已按配置补齐下界")
  270. return 0
  271. if __name__ == "__main__":
  272. sys.exit(main())