| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323 |
- #!/usr/bin/env python3
- """把 `src/config/iam_role_keys.toml`(配置真源)幂等地同步到平台 IAM 的角色×权限键。
- 鉴权是两层(总则§8.4 纪律 1「网关判权限键,服务判角色」):
- · 本脚本只配**第一层**——网关能不能把请求放进来;
- · 「只能动负责区域内的」「只能维护本团队」这类判定在服务端 handler,
- ⛔ 由本脚本或键面表达(那要 join dim_node_ancestor/bos_data_scope)。
- 与旧探针脚本的区别(`temp/role_keys_sync.py`):
- · 键面口径进版本管理(`src/config/iam_role_keys.toml`),⛔ 埋在探针的 ROLE_KEYS 里;
- · **无幂等短路**:每次都重算「在册 openapi 全集 ∩ 角色模式 − 角色现值」再补差集,
- 不会像旧脚本那样 `perm_bound=true` 之后新增接口的键永远补不进去。
- 用法:
- export SEOH_IAM_TOKEN=<developer 票> # 档一(角色配置)合法身份
- export SEOH_PROJECT_ID=... SEOH_TENANT_ID=...
- python3 scripts/iam_role_keys_sync.py # 只读差分;有缺口退出码 2
- python3 scripts/iam_role_keys_sync.py --apply # 补绑缺失键
- python3 scripts/iam_role_keys_sync.py --apply --prune # 另把在册 `bos.*` 的多余键解绑
- python3 scripts/iam_role_keys_sync.py --role klt.bos.role.opsMain
- python3 scripts/iam_role_keys_sync.py --role-id klt.bos.role.opsMain=377167980045283328
- ⚠️ 配置是**下界**:脚本只保证「必须持有的键都在」,多余键默认**只报告不回收**
- (非 `bos.*` 的 `resource_metadata.*`/`uos.object.*`/`iam.*` 一律不碰)。
- `--prune` 只解绑**在册 openapi 声明过、但配置没要**的 `bos.*` 键——这会改变现网行为,
- 先只读看清清单再决定。
- ⚠️ `resource_range` 沿用建角约定恒 `"*"`(`bos.*` 为扁平业务键,⛔ 区域树键;
- 平台 `bind` 强制显式 range,省略回 `11103`)。
- ⚠️ 解绑只能按 `(permission_key, "*")` 精确元组;`role/get@v1` 不回 range,
- 若某键当初用的是非 `*` range,解绑失败会被报出,⛔ 静默换 range 重试。
- ⚠️ 角色分配(`identity_role/bind@v1`)不在本脚本范围:U-110 冻结中,见 18 册。
- """
- from __future__ import annotations
- import argparse
- import json
- import os
- import re
- import ssl
- import sys
- import tomllib
- import urllib.error
- import urllib.request
- from typing import Any
- ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
- SPEC = os.path.join(ROOT, "src", "bin", "klt-bos", "openapi.yaml")
- CONFIG = os.path.join(ROOT, "src", "config", "iam_role_keys.toml")
- LEDGER = os.path.join(ROOT, "temp", "seoh_p5_ledger.json")
- IAM_PATH = "/api/system/seoh-iam-role"
- OK = 10000
- # ── HTTP ─────────────────────────────────────────────────────────────────────
- def _ssl_ctx(insecure: bool, ca_cert: str | None) -> ssl.SSLContext:
- if insecure:
- ctx = ssl.create_default_context()
- ctx.check_hostname = False
- ctx.verify_mode = ssl.CERT_NONE
- return ctx
- return ssl.create_default_context(cafile=ca_cert) if ca_cert else ssl.create_default_context()
- def call(base: str, path: str, data: dict[str, Any] | None, token: str,
- ctx: ssl.SSLContext) -> dict[str, Any]:
- body = json.dumps({"data": data or {}}).encode()
- req = urllib.request.Request(base.rstrip("/") + IAM_PATH + path, data=body, method="POST")
- req.add_header("Content-Type", "application/json")
- req.add_header("Authorization", f"Bearer {token}")
- req.add_header("X-Seoh-Env", os.environ.get("SEOH_HTTP_ENV", "dev"))
- try:
- with urllib.request.urlopen(req, context=ctx, timeout=60) as r:
- return json.loads(r.read().decode())
- except urllib.error.HTTPError as e:
- raw = e.read().decode(errors="replace")
- try:
- return json.loads(raw)
- except Exception: # noqa: BLE001
- return {"code": f"HTTP{e.code}", "message": raw[:300]}
- except Exception as e: # noqa: BLE001
- return {"code": -1, "message": f"<transport {e}>"}
- # ── 键全集:在册 openapi ──────────────────────────────────────────────────────
- def _codes(txt: str, section: str) -> dict[str, str]:
- m = re.search(rf"^ {section}:\n([\s\S]*?)(?=^ \S)", txt, re.M)
- if not m:
- return {}
- return dict(re.findall(r"^ (\w+):\n code: '?([\w.]+)'?", m.group(1), re.M))
- def declared_keys(spec: str = SPEC) -> set[str]:
- """在册路由的权限键全集。
- ⚠️ 注册用 openapi 的扩展值是 `$ref`(`#/components/x-resource-types/<k>/code`),
- 不是字面量;直接按 `x-resource-type: <字面量>` 抓会一条也抓不到。
- """
- txt = open(spec, encoding="utf-8").read()
- res, act = _codes(txt, "x-resource-types"), _codes(txt, "x-actions")
- out: set[str] = set()
- for m in re.finditer(
- r"x-resource-type:\n +\$ref: '#/components/x-resource-types/(\w+)/code'"
- r"\n +x-action:\n +\$ref: '#/components/x-actions/(\w+)/code'"
- r"(?:\n +x-version: (\w+))?",
- txt,
- ):
- rcode, acode = res.get(m.group(1)), act.get(m.group(2))
- if rcode and acode:
- out.add(f"{rcode}.{acode}@{m.group(3) or 'v1'}")
- return out
- # ── 配置 → 期望键集 ───────────────────────────────────────────────────────────
- def expand(patterns: list[str], universe: set[str], role: str) -> set[str]:
- """把 `bos.<res>.*` / `bos.<res>.<action>` 展开成具体键。
- 过期模式(匹配不到任何在册键)直接失败:保留它只会让「以为配了」变成静默无权限。
- """
- out: set[str] = set()
- stale: list[str] = []
- for p in patterns:
- if p == "*":
- out |= universe
- elif p.endswith(".*"):
- out |= {k for k in universe if k.startswith(p[:-2] + ".")}
- else:
- out |= {k for k in universe if k.startswith(p + "@")}
- if p != "*" and not any(
- k.startswith(p[:-2] + ".") if p.endswith(".*") else k.startswith(p + "@")
- for k in universe
- ):
- stale.append(p)
- if stale:
- raise SystemExit(f"[{role}] ⛔ 模式匹配不到任何在册键:{stale}")
- return out
- def desired(conf: dict[str, Any], universe: set[str]) -> dict[str, set[str]]:
- common = list((conf.get("defaults") or {}).get("include") or [])
- out: dict[str, set[str]] = {}
- for role, spec in (conf.get("roles") or {}).items():
- keys = set(universe) if spec.get("all") else set()
- keys |= expand(list(spec.get("include") or []), universe, role)
- keys |= expand(common, universe, f"{role}/defaults")
- if not keys:
- raise SystemExit(f"[{role}] ⛔ 键面为空:未配 all 也没有 include")
- out[role] = keys
- return out
- # ── 角色 ID 解析 ──────────────────────────────────────────────────────────────
- def resolve_role_ids(codes: list[str], base: str, token: str, ctx: ssl.SSLContext,
- overrides: dict[str, str]) -> dict[str, str]:
- ids: dict[str, str] = {}
- missing: list[str] = []
- for code in codes:
- if code in overrides:
- ids[code] = overrides[code]
- continue
- short = code.rsplit(".", 1)[-1]
- if os.path.exists(LEDGER):
- try:
- rid = (json.load(open(LEDGER, encoding="utf-8")).get(short) or {}).get("role_id")
- if rid:
- ids[code] = rid
- continue
- except Exception: # noqa: BLE001
- pass
- missing.append(code)
- for code in list(missing):
- short = code.rsplit(".", 1)[-1]
- r = call(base, "/role/get_list@v1", {
- "pagination": {"page_no": 1, "page_size": 200},
- "filters": {"code": short}, **SCOPE,
- }, token, ctx)
- items = ((r.get("data") or {}).get("items")) or []
- for it in items:
- if (it.get("code") or "") == code:
- ids[code] = it.get("role_id") or it.get("id")
- break
- if code not in ids:
- print(f"[!] 解析不到角色 ID:{code}(role/get_list code={r.get('code')} "
- f"msg={str(r.get('message'))[:160]})")
- for code in missing:
- if code not in ids:
- print(f" ↳ 可用 --role-id {code}=<id> 或先跑一次账号侧探针把 role_id 落盘;"
- f"⚠️ `role/get_list` 受「调用方须覆盖目标角色全部键」过滤,developer 票可能看不到高权角色")
- return ids
- # ── 主流程 ───────────────────────────────────────────────────────────────────
- SCOPE: dict[str, Any] = {}
- SHOW_LIMIT = 20
- def _show(keys: list[str], verbose: bool) -> str:
- if verbose or len(keys) <= SHOW_LIMIT:
- return str(keys)
- return f"{keys[:SHOW_LIMIT]} …(共 {len(keys)},加 --verbose 看全量)"
- def main() -> int:
- ap = argparse.ArgumentParser(description="同步角色×权限键(幂等)")
- ap.add_argument("--apply", action="store_true", help="写平台;缺省只读差分")
- ap.add_argument("--prune", action="store_true",
- help="解绑在册 bos.* 里配置没要的键(改变现网行为,先只读看清单)")
- ap.add_argument("--verbose", action="store_true", help="打印完整键清单")
- ap.add_argument("--role", action="append", default=[], help="只处理指定角色 code(可重复)")
- ap.add_argument("--role-id", action="append", default=[], help="CODE=ID 覆盖(可重复)")
- ap.add_argument("--config", default=CONFIG)
- ap.add_argument("--spec", default=SPEC)
- ap.add_argument("--gateway", default=os.environ.get("SEOH_GATEWAY", "https://127.0.0.1:3000"))
- ap.add_argument("--insecure", action="store_true", help="跳过 TLS 校验(仅 dev)")
- ap.add_argument("--ca-cert", default=os.environ.get("SEOH_CA_CERT"))
- args = ap.parse_args()
- token = os.environ.get("SEOH_IAM_TOKEN", "").strip()
- if not token:
- print("⛔ 缺 SEOH_IAM_TOKEN(developer 票;档一=角色配置的合法身份)")
- return 1
- project = os.environ.get("SEOH_PROJECT_ID", "").strip()
- if not project:
- print("⛔ 缺 SEOH_PROJECT_ID(end_user scope 锚点)")
- return 1
- SCOPE.update({
- "scope_type": "end_user", "scope_id": project,
- "env": os.environ.get("SEOH_DATA_ENV", "nonprod"),
- "stage": os.environ.get("SEOH_STAGE", "dev"),
- })
- ctx = _ssl_ctx(args.insecure, args.ca_cert)
- universe = declared_keys(args.spec)
- conf = tomllib.loads(open(args.config, encoding="utf-8").read())
- want = desired(conf, universe)
- overrides = dict(x.split("=", 1) for x in args.role_id if "=" in x)
- roles = args.role or list(want)
- unknown = [r for r in roles if r not in want]
- if unknown:
- print(f"⛔ 配置里没有这些角色:{unknown}")
- return 1
- print(f"# 在册键 = {len(universe)}({os.path.relpath(args.spec, ROOT)})")
- print(f"# 配置 = {os.path.relpath(args.config, ROOT)} 角色 {len(roles)}")
- ids = resolve_role_ids(roles, args.gateway, token, ctx, overrides)
- drift, failed = 0, 0
- for role in roles:
- rid = ids.get(role)
- if not rid:
- failed += 1
- continue
- g = call(args.gateway, "/role/get@v1", {"role_id": rid, **SCOPE}, token, ctx)
- if g.get("code") != OK:
- print(f"\n[{role}] ⛔ role/get code={g.get('code')} msg={str(g.get('message'))[:200]}")
- failed += 1
- continue
- have = set(((g.get("data") or {}).get("permission_keys")) or [])
- missing = sorted(want[role] - have)
- # 「多」只统计**在册 openapi 声明过**的键:平台侧键(resource_metadata.*/
- # uos.object.*/iam.*)不归本矩阵管,⛔ 计入漂移、⛔ 交给 --prune。
- extra = sorted((have - want[role]) & universe)
- foreign = sorted((have - want[role]) - universe)
- print(f"\n== {role}({rid}) 现值 {len(have)} 枚 / 期望(下界) {len(want[role])} 枚 ==")
- print(f" 缺 {len(missing)}:{_show(missing, args.verbose)}")
- print(f" 多(在册 bos.*) {len(extra)}:{_show(extra, args.verbose)}")
- if foreign:
- print(f" 非本矩阵键 {len(foreign)}:{_show(foreign, args.verbose)}")
- if missing:
- drift += 1
- if not (args.apply and (missing or (args.prune and extra))):
- continue
- if missing:
- b = call(args.gateway, "/role_permission/bind@v1", {
- "role_id": rid,
- "permission_items": [{"permission_key": k, "resource_range": "*"} for k in missing],
- **SCOPE,
- }, token, ctx)
- print(f" bind → code={b.get('code')} msg={str(b.get('message'))[:220]}")
- if b.get("code") != OK:
- failed += 1
- if args.prune and extra:
- print(f" ⚠️ --prune:将解绑 {len(extra)} 枚在册 bos.* 键(改变现网行为)")
- u = call(args.gateway, "/role_permission/unbind@v1", {
- "role_id": rid,
- "permission_items": [{"permission_key": k, "resource_range": "*"} for k in extra],
- **SCOPE,
- }, token, ctx)
- print(f" unbind → code={u.get('code')} msg={str(u.get('message'))[:220]}")
- if u.get("code") != OK:
- failed += 1
- g2 = call(args.gateway, "/role/get@v1", {"role_id": rid, **SCOPE}, token, ctx)
- after = set(((g2.get("data") or {}).get("permission_keys")) or [])
- print(f" 复读 {len(after)} 枚,+{len(after - have)} / -{len(have - after)}")
- if failed:
- print(f"\n⛔ 失败 {failed} 项")
- return 1
- if drift and not args.apply:
- print("\n[i] 存在缺口;加 --apply 补绑(只读模式退出码 2)")
- return 2
- print("\n✅ 下界键齐备(多余的键只报告,⛔ 自动回收)" if not (args.apply and drift)
- else "\n✅ 已按配置补齐下界")
- return 0
- if __name__ == "__main__":
- sys.exit(main())
|