Files
kefu/wechat_rpa/test_group_access.py
T
2026-11-04 10:14:23 +08:00

342 lines
18 KiB
Python

"""Real FastAPI metadata checks using copied public modules and temporary SQLite.
Run this file with C:/kefu/wechat_rpa/.venv/Scripts/python.exe. No deployed
configuration, database, existing key or server is read or started.
"""
from __future__ import annotations
import atexit
import faulthandler
import hashlib
import hmac
import json
import os
import secrets
import shutil
import sys
import tempfile
import unittest
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
from unittest import mock
MIRROR = Path(__file__).resolve().parent
PROJECT = MIRROR.parents[2]
SOURCE = Path(os.environ.get("IAM_KEFU_SOURCE_ROOT", "C:/kefu")) / "wechat_rpa"
TEST_RUNTIME = PROJECT / ".test-runtime"
TEST_RUNTIME.mkdir(parents=True, exist_ok=True)
RUNTIME = tempfile.TemporaryDirectory(prefix="iam-kefu-metadata-", dir=TEST_RUNTIME)
ISOLATED = Path(RUNTIME.name)
def cleanup_runtime():
os.chdir(TEST_RUNTIME)
RUNTIME.cleanup()
atexit.register(cleanup_runtime)
# Only .py public sources: never .env, JSON settings, DB or an existing key.
for source in SOURCE.glob("*.py"):
shutil.copyfile(source, ISOLATED / source.name)
for name in ("admin_api.py", "admin_backend.py", "rbac.py", "group_sso.py", "group_access.py", "group_authorization.py"):
shutil.copyfile(MIRROR / name, ISOLATED / name)
os.chdir(ISOLATED)
RUNTIME_ENV = {key: value for key, value in os.environ.items()
if key.upper() in {"SYSTEMROOT", "WINDIR", "TEMP", "TMP"}}
os.environ.clear()
os.environ.update(RUNTIME_ENV)
sys.path.insert(0, str(ISOLATED))
from fastapi.testclient import TestClient
import admin_api
import admin_backend as backend
import group_access
import rbac
KEY = bytes.fromhex("12" * 32)
NOW = 1_800_000_000
URL = "/api/v2/group/access-snapshot"
GID = "gid_" + "a" * 32
OTHER_GID = "gid_" + "b" * 32
PASSWORD = "Fixture-Metadata-Password-2026"
class GroupAccessTests(unittest.TestCase):
def setUp(self):
self.directory = tempfile.TemporaryDirectory(dir=ISOLATED)
self.addCleanup(self.directory.cleanup)
self.root = Path(self.directory.name)
self.key_file = self.root / "metadata.key"
self.key_file.write_text(KEY.hex(), encoding="ascii")
self.env = mock.patch.dict(os.environ, {"ZYT_GROUP_METADATA_KEY_FILE": str(self.key_file)}, clear=True)
self.env.start()
self.addCleanup(self.env.stop)
self.db = backend.Database(self.root / "fixture.sqlite")
self.clock = mock.Mock(return_value=NOW)
actual_service = group_access.AccessSnapshot
self.service = actual_service(self.db, clock=self.clock)
with mock.patch.object(backend, "load_initial_config", return_value=backend.CONFIG_DEFAULTS.copy()):
self.db.initialize(PASSWORD)
with mock.patch.object(group_access, "AccessSnapshot", return_value=self.service):
self.client = TestClient(admin_api.create_app(self.db.path))
self.addCleanup(self.client.close)
def body(self, gids=None, catalog=False):
return {"client_id": "kefu", "gids": [GID] if gids is None else gids,
"include_catalog": catalog}
def raw(self, value):
return json.dumps(value, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
def headers(self, raw, *, nonce=None, timestamp=None, key=KEY, path="/group/access-snapshot"):
nonce = nonce or secrets.token_hex(16)
timestamp = str(NOW if timestamp is None else timestamp)
message = f"POST\n{path}\n{timestamp}\n{nonce}\n{hashlib.sha256(raw).hexdigest()}"
return {"Content-Type": "application/json", "X-Group-Timestamp": timestamp,
"X-Group-Nonce": nonce,
"X-Group-Signature": hmac.new(key, message.encode("ascii"), hashlib.sha256).hexdigest()}
def fetch(self, body=None, *, raw=None, **signing):
raw = self.raw(self.body() if body is None else body) if raw is None else raw
headers = self.headers(raw, **signing)
response = self.client.post(URL, content=raw, headers=headers)
if response.status_code == 200:
signed = f"response\n{headers['X-Group-Nonce']}\n{hashlib.sha256(response.content).hexdigest()}"
expected = hmac.new(KEY, signed.encode("ascii"), hashlib.sha256).hexdigest()
self.assertEqual(response.headers["X-Group-Response-Signature"], expected)
self.assertEqual(response.headers.get("Cache-Control"), "no-store")
return response
def enroll(self, gid=GID, source_id=7, account="same-account", name="合成集团用户"):
return self.db.group_sso_user({"client_id": "kefu", "gid": gid,
"source_admin_id": source_id, "account": account, "name": name, "company_id": 2})
def fingerprint(self):
tables = ("users", "roles", "role_permissions", "auth_tokens", "permissions", "group_sso_bindings")
with self.db.connect() as db:
return {table: [tuple(row) for row in db.execute(f"SELECT * FROM {table} ORDER BY rowid")]
for table in tables}
def test_missing_subject_is_not_created_and_names_never_match(self):
self.db.create_user("same-account", PASSWORD, "admin", 1, "fixture")
before = self.fingerprint()
with mock.patch.object(backend.Database, "group_sso_user", side_effect=AssertionError("No enrollment")), \
mock.patch.object(backend.Database, "sync_code_permissions", side_effect=AssertionError("No sync")), \
mock.patch.object(rbac, "seed", side_effect=AssertionError("No seed")), \
mock.patch.object(rbac, "grant", side_effect=AssertionError("No grant")):
response = self.fetch(self.body(catalog=True))
self.assertEqual(response.status_code, 200, response.text)
self.assertEqual(response.json()["subjects"], [{"gid": GID, "found": False}])
self.assertEqual(before, self.fingerprint())
def test_exact_projection_and_signed_raw_utf8_response(self):
self.enroll()
result = self.fetch(self.body(catalog=True))
self.assertEqual(result.status_code, 200, result.text)
data = result.json()
self.assertEqual(set(data), {"version", "client_id", "generated_at", "subjects", "catalog"})
self.assertEqual((data["version"], data["client_id"], data["generated_at"]), (1, "kefu", NOW))
subject = data["subjects"][0]
self.assertEqual(set(subject), {"gid", "found", "source_admin_id", "company_id", "user"})
self.assertEqual(subject["source_admin_id"], 7)
user = subject["user"]
self.assertEqual(set(user), {"id", "username", "source_account", "source_name", "active", "role", "permissions"})
self.assertEqual(set(user["role"]), {"code", "name"})
self.assertEqual(user["role"]["code"], "zyt_basic")
self.assertEqual(user["permissions"], [])
self.assertEqual(user["source_name"], "合成集团用户")
for item in data["catalog"]["permissions"]:
self.assertEqual(set(item), {"code", "name", "group", "page", "kind", "source", "enabled", "sort"})
self.assertIn(item["kind"], {"page", "action"})
self.assertIs(type(item["enabled"]), bool)
for secret in ("password_salt", "password_digest", "auth_tokens", "link_url", "user_count", str(self.key_file), KEY.hex()):
self.assertNotIn(secret, result.text)
def test_binding_identity_and_requested_order_are_exact(self):
first = self.enroll()
second = self.enroll(OTHER_GID, 8, name="同名")
self.db.update_user(int(first["id"]), "operator", True, "", 1, "fixture")
self.db.update_user(int(second["id"]), "viewer", True, "", 1, "fixture")
third = "gid_" + "c" * 32
response = self.fetch(self.body([OTHER_GID, third, GID]))
self.assertEqual(response.status_code, 200)
subjects = response.json()["subjects"]
self.assertEqual([row["gid"] for row in subjects], [OTHER_GID, third, GID])
self.assertEqual(subjects[1], {"gid": third, "found": False})
self.assertEqual(subjects[0]["user"]["role"]["code"], "viewer")
self.assertEqual(subjects[2]["user"]["role"]["code"], "operator")
with self.db.connect() as db:
db.execute("UPDATE group_sso_bindings SET provider='other_provider' WHERE gid=?", (GID,))
db.commit()
self.assertEqual(self.fetch().json()["subjects"], [{"gid": GID, "found": False}])
def test_role_and_active_changes_are_live_and_effective_reader_is_used(self):
user = self.enroll()
user_id = int(user["id"])
self.assertEqual(self.fetch().json()["subjects"][0]["user"]["permissions"], [])
self.db.update_user(user_id, "operator", True, "", 1, "fixture")
expected = sorted(self.db.permissions_for_user(user_id))
self.assertTrue(expected)
with mock.patch.object(backend.Database, "permissions_for_user", wraps=self.db.permissions_for_user) as effective:
actual = self.fetch().json()["subjects"][0]["user"]
effective.assert_called_once_with(user_id)
self.assertEqual(actual["permissions"], expected)
self.assertEqual(actual["role"]["code"], "operator")
self.db.update_user(user_id, "operator", False, "", 1, "fixture")
actual = self.fetch().json()["subjects"][0]["user"]
self.assertFalse(actual["active"])
self.assertEqual(actual["permissions"], [])
self.assertEqual(actual["role"]["code"], "operator")
def test_dynamic_catalog_add_update_delete_and_link_projection(self):
payload = {"code": "fixture:dynamic", "name": "动态测试", "group_name": "合成菜单",
"page_name": "合成页面", "kind": "action", "enabled": True, "sort_order": 14}
self.db.create_permission(payload, 1, "fixture")
catalog = lambda: {row["code"]: row for row in self.fetch(self.body([], True)).json()["catalog"]["permissions"]}
self.assertEqual(catalog()[payload["code"]]["name"], "动态测试")
self.db.update_permission(payload["code"], {**payload, "name": "已更新", "enabled": False}, 1, "fixture")
changed = catalog()[payload["code"]]
self.assertEqual(changed["name"], "已更新")
self.assertFalse(changed["enabled"])
self.db.create_permission({**payload, "code": "link:fixture", "kind": "link",
"link_url": "https://example.invalid/private?secret=fixture", "link_mode": "tab"}, 1, "fixture")
link = catalog()["link:fixture"]
self.assertEqual(link["kind"], "page")
self.assertNotIn("link_url", link)
self.db.delete_permission(payload["code"], 1, "fixture")
self.assertNotIn(payload["code"], catalog())
def test_reading_does_not_change_users_roles_grants_tokens_or_catalog(self):
self.enroll()
self.db.create_token(1, "api", "fixture", 3600)
before = self.fingerprint()
self.assertEqual(self.fetch(self.body(catalog=True)).status_code, 200)
self.assertEqual(self.fetch(self.body([], True)).status_code, 200)
self.assertEqual(self.fetch(self.body([OTHER_GID], False)).status_code, 200)
self.assertEqual(before, self.fingerprint())
def test_no_catalog_requested_does_not_read_it(self):
with mock.patch.object(backend.Database, "permission_catalog", side_effect=AssertionError("No catalog")):
response = self.fetch(self.body([], False))
self.assertEqual(response.status_code, 200)
self.assertEqual(response.json()["subjects"], [])
self.assertIsNone(response.json()["catalog"])
def test_user_bearer_never_substitutes_for_machine_authentication(self):
token, _ = self.db.create_token(1, "api", "fixture", 3600)
response = self.client.post(URL, json=self.body(), headers={"Authorization": "Bearer " + token})
self.assertEqual(response.status_code, 401)
self.assertEqual(response.headers["Cache-Control"], "no-store")
def test_bad_signature_and_body_or_path_tampering_are_rejected_before_parsing(self):
raw = self.raw(self.body())
for key, path, changed in ((b"x" * 32, "/group/access-snapshot", raw),
(KEY, "/api/v2/group/access-snapshot", raw),
(KEY, "/group/access-snapshot", b"not-json")):
with self.subTest(path=path, body=changed):
headers = self.headers(raw, key=key, path=path)
with mock.patch.object(group_access, "parse_request", side_effect=AssertionError("Not authenticated")):
response = self.client.post(URL, content=changed, headers=headers)
self.assertEqual(response.status_code, 401)
def test_clock_window_and_replay(self):
for offset in (-91, 91):
self.assertEqual(self.fetch(timestamp=NOW + offset).status_code, 401)
for offset in (-90, 90):
self.assertEqual(self.fetch(timestamp=NOW + offset).status_code, 200)
nonce = "d" * 32
self.assertEqual(self.fetch(nonce=nonce).status_code, 200)
self.assertEqual(self.fetch(nonce=nonce).status_code, 401)
self.clock.return_value = NOW + 91
self.assertEqual(self.fetch(nonce=nonce, timestamp=NOW + 91).status_code, 200)
def test_replay_cache_full_fails_closed_and_does_not_evict_live_nonces(self):
self.service.max_nonces = 1
self.assertEqual(self.fetch(nonce="1" * 32).status_code, 200)
self.assertEqual(self.fetch(nonce="2" * 32).status_code, 503)
self.assertEqual(self.fetch(nonce="1" * 32).status_code, 401)
def test_concurrent_replay_consumes_nonce_once(self):
raw = self.raw(self.body([], False))
headers = self.headers(raw, nonce="e" * 32)
with ThreadPoolExecutor(max_workers=4) as pool:
statuses = list(pool.map(lambda _: self.client.post(URL, content=raw, headers=headers).status_code,
range(8)))
self.assertEqual(statuses.count(200), 1)
self.assertEqual(statuses.count(401), 7)
def test_invalid_and_missing_key_configuration_fail_closed(self):
for value in ("", str(self.root / "missing.key"), "relative.key"):
with self.subTest(value=value), mock.patch.dict(os.environ, {"ZYT_GROUP_METADATA_KEY_FILE": value}):
self.assertEqual(self.fetch().status_code, 503)
for raw in (b"x" * 64, b"1" * 63, b"1" * 65, b"1" * 64 + b"\n"):
self.key_file.write_bytes(raw)
response = self.fetch()
self.assertEqual(response.status_code, 503)
self.assertNotIn(str(self.key_file), response.text)
def test_public_static_key_location_is_rejected(self):
directory = self.root / "admin-web/apps/web-antd/dist"
directory.mkdir(parents=True, exist_ok=True)
key = directory / ("fixture-" + secrets.token_hex(8) + ".key")
key.write_text(KEY.hex(), encoding="ascii")
with mock.patch.object(group_access, "__file__", str(self.root / "wechat_rpa/group_access.py")), \
mock.patch.dict(os.environ, {"ZYT_GROUP_METADATA_KEY_FILE": str(key)}):
self.assertEqual(self.fetch().status_code, 503)
def test_strict_body_shapes_and_no_duplicate_json_keys(self):
bad = [[], {}, {**self.body(), "role": "admin"}, {**self.body(), "client_id": "hospital"},
{**self.body(), "include_catalog": 1}, {**self.body(), "gids": "bad"},
self.body([GID, GID]), self.body(["gid_" + "A" * 32]), self.body([True]),
self.body(["gid_" + f"{number:032x}" for number in range(101)])]
for value in bad:
with self.subTest(body=value):
self.assertEqual(self.fetch(value).status_code, 422)
for raw in (b'{"client_id":"kefu","client_id":"kefu","gids":[],"include_catalog":false}',
b'{"client_id":"kefu","gids":[],"include_catalog":NaN}', b"\xff", b"not-json"):
self.assertEqual(self.fetch(raw=raw).status_code, 422)
def test_request_and_response_bounds(self):
self.assertEqual(self.fetch(raw=b" " * (16 * 1024 + 1)).status_code, 413)
gids = ["gid_" + f"{number:032x}" for number in range(100)]
self.assertEqual(len(self.fetch(self.body(gids)).json()["subjects"]), 100)
definition = {"code": "test:one", "name": "one", "group_name": "g", "page_name": "p",
"kind": "action", "source": "custom", "enabled": True, "sort_order": 0}
with mock.patch.object(backend.Database, "permission_catalog", return_value=[definition] * 2001):
self.assertEqual(self.fetch(self.body([], True)).status_code, 503)
self.enroll()
with mock.patch.object(backend.Database, "permissions_for_user", return_value={f"test:{i}" for i in range(2001)}):
self.assertEqual(self.fetch().status_code, 503)
with mock.patch.object(backend.Database, "permission_catalog", return_value=[{**definition, "name": "a" * (4 * 1024 * 1024)}]):
self.assertEqual(self.fetch(self.body([], True)).status_code, 503)
def test_duplicate_security_headers_and_query_are_rejected(self):
raw = self.raw(self.body())
headers = list(self.headers(raw).items())
headers.append(("X-Group-Nonce", "f" * 32))
self.assertEqual(self.client.post(URL, content=raw, headers=headers).status_code, 401)
response = self.client.post(URL + "?gid=extra", content=raw, headers=self.headers(raw))
self.assertEqual(response.status_code, 422)
def test_response_signature_changes_with_payload_and_nonce(self):
self.enroll()
first = self.fetch(nonce="1" * 32)
second = self.fetch(nonce="2" * 32)
self.assertEqual(first.content, second.content)
self.assertNotEqual(first.headers["X-Group-Response-Signature"], second.headers["X-Group-Response-Signature"])
self.db.update_user(int(first.json()["subjects"][0]["user"]["id"]), "operator", True, "", 1, "fixture")
third = self.fetch(nonce="3" * 32)
self.assertNotEqual(first.content, third.content)
if __name__ == "__main__":
# A restricted Windows socketpair can hang Python's test event loop before
# the endpoint runs. Bound the process instead of leaving a test stranded.
faulthandler.dump_traceback_later(60, exit=True)
try:
unittest.main(verbosity=2)
finally:
faulthandler.cancel_dump_traceback_later()