Files
kefu/wechat_rpa/test_group_sso.py
T
2026-11-03 10:58:43 +08:00

268 lines
14 KiB
Python

"""Isolated management SSO checks; no real .env, credentials, or databases."""
from __future__ import annotations
import copy
import json
import os
import tempfile
import threading
import unittest
from concurrent.futures import ThreadPoolExecutor
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from unittest import mock
from fastapi.testclient import TestClient
import admin_backend as backend
import admin_api
import group_sso
STRONG = "Fixture@2026Only"
IDENTITY = {"client_id": "kefu", "gid": "gid_" + "a" * 32,
"source_admin_id": 7, "account": "admin", "name": "源账号",
"company_id": 2}
CODE = "C" * 43
VERIFIER = "V" * 43
class GroupSSOTests(unittest.TestCase):
def setUp(self):
self.directory = tempfile.TemporaryDirectory()
self.addCleanup(self.directory.cleanup)
self.db = backend.Database(Path(self.directory.name) / "fixture.db")
with mock.patch.object(backend, "load_initial_config", return_value=backend.CONFIG_DEFAULTS.copy()):
self.db.initialize(STRONG)
self.env = mock.patch.dict(os.environ, {"ZYT_GROUP_BASE_URL": "http://127.0.0.1:5173",
"ZYT_GROUP_API_URL": "http://127.0.0.1:8081/adminapi",
"KEFU_PUBLIC_BASE_URL": "http://127.0.0.1:5666"}, clear=True)
self.env.start()
self.addCleanup(self.env.stop)
self.client = TestClient(admin_api.create_app(self.db.path))
self.addCleanup(self.client.close)
def group_login(self, identity=None):
with mock.patch.object(group_sso, "exchange", return_value=copy.deepcopy(identity or IDENTITY)):
return self.client.post("/api/v2/auth/group/exchange", json={"code": CODE, "code_verifier": VERIFIER})
def local_login(self):
response = self.client.post("/api/v2/auth/login", json={"username": "admin", "password": STRONG})
self.assertEqual(response.status_code, 200, response.text)
return {"Authorization": "Bearer " + response.json()["access_token"]}
def test_disabled_and_invalid_configuration_fail_closed(self):
for value in ("", "http://public.example", "https://a.example/?q=x", "https://u:p@a.example",
"https://a.example/#x", "https://a.example/\\x", "https://a.example/%0a", "https://a.example/\nx"):
with self.subTest(value=value), mock.patch.dict(os.environ, {"KEFU_PUBLIC_BASE_URL": value}):
self.assertEqual(self.client.get("/api/v2/auth/group/config").json(), {"enabled": False})
self.assertEqual(self.client.post("/api/v2/auth/group/exchange", json={"code": CODE, "code_verifier": VERIFIER}).status_code, 503)
def test_public_config_is_fixed_and_contains_no_credentials(self):
response = self.client.get("/api/v2/auth/group/config")
self.assertEqual(response.headers["Cache-Control"], "no-store")
self.assertEqual(response.headers["Referrer-Policy"], "no-referrer")
self.assertEqual(response.json(), {
"enabled": True, "client_id": "kefu", "entry": "http://127.0.0.1:5173",
"authorize_url": "http://127.0.0.1:5173/sso/authorize",
"redirect_uri": "http://127.0.0.1:5666/auth/group-login"})
def test_forged_profile_and_invalid_inputs_are_rejected_before_exchange(self):
for body in ({"code": CODE, "code_verifier": VERIFIER, "profile": IDENTITY},
{"code": CODE, "code_verifier": VERIFIER, "redirect_uri": "https://evil.example"},
{"code": "bad", "code_verifier": VERIFIER},
{"code": CODE, "code_verifier": "bad"}):
with mock.patch.object(group_sso, "exchange") as exchange:
response = self.client.post("/api/v2/auth/group/exchange", json=body)
self.assertEqual(response.status_code, 422)
self.assertNotIn(CODE, response.text)
self.assertNotIn(VERIFIER, response.text)
exchange.assert_not_called()
def test_source_admin_name_never_claims_local_admin_and_basic_has_no_business_permissions(self):
response = self.group_login()
self.assertEqual(response.status_code, 200, response.text)
self.assertEqual(response.json()["expires_in"], 8 * 3600)
me = response.json()["user"]
self.assertNotEqual(me["id"], 1)
self.assertEqual(me["role"], "zyt_basic")
self.assertEqual(me["permissions"], [])
self.assertFalse(me["must_change_password"])
headers = {"Authorization": "Bearer " + response.json()["access_token"]}
self.assertEqual(self.client.get("/api/v2/me", headers=headers).status_code, 200)
for path in ("users", "roles", "models", "config", "audit", "desktop-accounts", "archive/stats", "knowledge/overview"):
self.assertEqual(self.client.get("/api/v2/" + path, headers=headers).status_code, 403, path)
self.assertEqual(self.client.post("/api/v2/auth/logout", headers=headers).status_code, 200)
self.assertEqual(self.client.get("/api/v2/me", headers=headers).status_code, 401)
def test_local_username_collision_allocates_independent_binding(self):
name = "zyt_" + "a" * 32
self.db.create_user(name, STRONG, "admin", 1, "fixture")
response = self.group_login()
self.assertEqual(response.status_code, 200, response.text)
self.assertNotEqual(response.json()["user"]["username"], name)
self.assertEqual(self.db.authenticate(name, STRONG)["role"], "admin")
def test_local_role_update_works_and_is_retained_on_next_sso(self):
first = self.group_login().json()
user_id = first["user"]["id"]
headers = {"Authorization": "Bearer " + first["access_token"]}
with self.db.connect() as db:
original = dict(db.execute("SELECT * FROM users WHERE id=?", (user_id,)).fetchone())
updated = self.client.put(f"/api/v2/users/{user_id}", headers=self.local_login(),
json={"role": "operator", "active": True})
self.assertEqual(updated.status_code, 200, updated.text)
self.assertIn("model:write", self.client.get("/api/v2/me", headers=headers).json()["permissions"])
renamed = {**IDENTITY, "account": "renamed", "name": "新姓名"}
repeated = self.group_login(renamed).json()["user"]
self.assertEqual(repeated["role"], "operator")
self.assertEqual(repeated["display_name"], "新姓名")
with self.db.connect() as db:
current = dict(db.execute("SELECT * FROM users WHERE id=?", (user_id,)).fetchone())
for key in ("password_salt", "password_digest", "must_change_password"):
self.assertEqual(original[key], current[key])
entry = next(u for u in updated.json()["users"] if u["id"] == user_id)
self.assertEqual(entry["source_account"], "admin")
self.assertEqual(entry["source_name"], "源账号")
self.assertEqual(entry["identity_source"], "zyt_group")
def test_disabled_user_is_not_revived(self):
user_id = self.group_login().json()["user"]["id"]
self.assertEqual(self.client.put(f"/api/v2/users/{user_id}", headers=self.local_login(),
json={"role": "operator", "active": False}).status_code, 200)
self.assertEqual(self.group_login().status_code, 401)
with self.db.connect() as db:
self.assertEqual(tuple(db.execute("SELECT role,active FROM users WHERE id=?", (user_id,)).fetchone()), ("operator", 0))
def test_group_local_password_is_disabled_and_reset_rejected(self):
user = self.group_login().json()["user"]
response = self.client.put(f'/api/v2/users/{user["id"]}', headers=self.local_login(),
json={"role": "viewer", "active": True, "password": STRONG})
self.assertEqual(response.status_code, 400)
self.assertIsNone(self.db.authenticate(user["username"], STRONG))
def test_local_admin_password_login_and_explicit_reset_remain_valid(self):
headers = self.local_login()
self.assertIn("role:write", self.client.get("/api/v2/me", headers=headers).json()["permissions"])
self.db.create_user("local", STRONG, "viewer", 1, "fixture")
uid = self.db.authenticate("local", STRONG)["id"]
response = self.client.put(f"/api/v2/users/{uid}", headers=headers,
json={"role": "operator", "active": True, "password": STRONG + "new"})
self.assertEqual(response.status_code, 200, response.text)
self.assertIsNotNone(self.db.authenticate("local", STRONG + "new"))
self.assertIsNone(self.db.authenticate("local", STRONG))
def test_fixed_enrollment_role_cannot_gain_permissions(self):
before = {role["code"]: role["permissions"] for role in self.db.roles()}
response = self.client.post("/api/v2/roles", headers=self.local_login(),
json={"code": "zyt_basic", "name": "集团基础用户", "permissions": ["user:write"]})
self.assertEqual(response.status_code, 400)
self.assertIn("集团基础用户不能授予业务权限", response.json()["detail"])
after = {role["code"]: role["permissions"] for role in self.db.roles()}
self.assertEqual(after["zyt_basic"], [])
self.assertEqual(before, after)
def test_identity_ids_must_be_positive_integers_and_not_booleans(self):
for field in ("source_admin_id", "company_id"):
for value in (0, -1, True, False, "2", 2.0, None):
with self.subTest(field=field, value=value), self.assertRaises(group_sso.GroupSSOError):
group_sso.validate_identity({**IDENTITY, field: value})
def test_concurrent_enrollment_creates_exactly_one_user(self):
with ThreadPoolExecutor(max_workers=6) as pool:
ids = list(pool.map(lambda _: self.db.group_sso_user(IDENTITY)["id"], range(12)))
self.assertEqual(len(set(ids)), 1)
with self.db.connect() as db:
self.assertEqual(db.execute("SELECT COUNT(*) FROM group_sso_bindings").fetchone()[0], 1)
def test_callback_response_does_not_reflect_or_log_code(self):
dist = Path(self.directory.name) / "dist"
dist.mkdir()
(dist / "index.html").write_text("<html>synthetic shell</html>", encoding="utf-8")
with mock.patch.object(admin_api, "_frontend_dist", return_value=dist):
app = admin_api.create_app(self.db.path)
scopes = []
async def observe_scope(scope, receive, send):
await app(scope, receive, send)
if scope["type"] == "http":
scopes.append(scope["query_string"])
with TestClient(observe_scope) as client:
response = client.get(f"/auth/group-login?code={CODE}&state={VERIFIER}")
self.assertEqual(response.status_code, 200)
self.assertNotIn(CODE, response.text)
self.assertEqual(scopes, [b""])
self.assertEqual(response.headers["Cache-Control"], "no-store")
self.assertEqual(response.headers["Referrer-Policy"], "no-referrer")
class ExchangeTransportTests(unittest.TestCase):
def setUp(self):
self.requests = []
self.used_codes = set()
self.mode = "ok"
outer = self
class Handler(BaseHTTPRequestHandler):
def log_message(self, *a):
pass
def do_POST(self):
body = json.loads(self.rfile.read(int(self.headers["Content-Length"])))
outer.requests.append((self.path, body))
if outer.mode == "redirect":
self.send_response(302)
self.send_header("Location", "http://127.0.0.1:1/leak")
self.end_headers()
return
if outer.mode == "replayed" or (outer.mode == "ok" and body["code"] in outer.used_codes):
payload = {"code": 0, "msg": "invalid"}
else:
identity = copy.deepcopy(IDENTITY)
if outer.mode == "forged":
identity["role"] = "admin"
if outer.mode == "bool-id":
identity["source_admin_id"] = True
payload = {"code": 1, "data": identity}
if outer.mode == "ok":
outer.used_codes.add(body["code"])
raw = json.dumps(payload).encode() if outer.mode != "oversize" else b"x" * (group_sso.MAX_RESPONSE_BYTES + 2)
self.send_response(200)
self.end_headers()
self.wfile.write(raw)
self.server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
self.worker = threading.Thread(target=self.server.serve_forever, daemon=True)
self.worker.start()
self.addCleanup(self.stop)
self.config = group_sso.GroupSSOConfig("http://127.0.0.1:5173",
f"http://127.0.0.1:{self.server.server_port}/adminapi", "http://127.0.0.1:5666")
def stop(self):
self.server.shutdown()
self.worker.join()
self.server.server_close()
def test_exchange_uses_only_fixed_client_and_callback(self):
self.assertEqual(group_sso.exchange(self.config, CODE, VERIFIER), IDENTITY)
self.assertEqual(self.requests, [("/adminapi/group/sso/exchange", {
"client_id": "kefu", "redirect_uri": "http://127.0.0.1:5666/auth/group-login",
"code": CODE, "code_verifier": VERIFIER})])
def test_redirect_replay_oversize_and_forged_identity_fail_closed(self):
for mode in ("redirect", "replayed", "oversize", "forged", "bool-id"):
self.mode = mode
with self.subTest(mode=mode), self.assertRaises(group_sso.GroupSSOError) as caught:
group_sso.exchange(self.config, CODE, VERIFIER)
self.assertNotIn(CODE, str(caught.exception))
self.assertNotIn(VERIFIER, str(caught.exception))
def test_consumed_code_cannot_be_replayed(self):
self.assertEqual(group_sso.exchange(self.config, CODE, VERIFIER), IDENTITY)
with self.assertRaises(group_sso.GroupSSOError):
group_sso.exchange(self.config, CODE, VERIFIER)
if __name__ == "__main__":
unittest.main()