""" backend/tests/test_auth_common.py 用途:验证可复制认证公共模块的身份、配置、Casdoor HTTP 请求和错误安全边界。 依赖:pytest、Flask 测试应用、公共 auth common/casdoor 模块。 逻辑:不访问 HXOPS User 表,确保公共目录可以脱离业务模型独立工作。 """ from __future__ import annotations import pytest from app.core.errors import AppError from app.services.auth.casdoor.client import CasdoorClient, get_casdoor_client from app.services.auth.casdoor.config import CasdoorConfig, casdoor_config_from_flask from app.services.auth.casdoor.errors import raise_auth_error from app.services.auth.casdoor.identity import identity_from_claims from app.services.auth.common import AuthIdentity, IdentityValidationError, identity_key class FakeResponse: """提供 CasdoorClient 单测所需的最小 requests.Response 行为。""" def __init__(self, data, *, ok=True, status_code=200): self._data = data self.ok = ok self.status_code = status_code def json(self): """返回构造时注入的 JSON 数据。""" return self._data def raise_for_status(self): """模拟 discovery 请求的 HTTP 状态检查。""" if not self.ok: raise RuntimeError(f'HTTP {self.status_code}') class FakeHttp: """记录 CasdoorClient 请求,避免单测访问真实 Casdoor。""" def __init__(self): self.posts = [] self.gets = [] def get(self, url, **kwargs): """按 URL 返回 discovery 或 userinfo 测试响应。""" self.gets.append((url, kwargs)) if url.endswith('/.well-known/openid-configuration'): return FakeResponse({ 'token_endpoint': 'https://casdoor.test/token', 'userinfo_endpoint': 'https://casdoor.test/userinfo', }) return FakeResponse({ 'iss': 'https://casdoor.test', 'sub': 'subject-1', 'preferred_username': 'alice', }) def post(self, url, **kwargs): """记录 token 请求并返回固定 token 集合。""" self.posts.append((url, kwargs)) return FakeResponse({ 'access_token': 'casdoor-access', 'refresh_token': 'casdoor-refresh', 'token_type': 'Bearer', 'expires_in': 3600, }) def test_identity_key_requires_stable_identity(): """公共身份必须使用 issuer + subject 作为稳定键,不能接受缺失 subject 的资料。""" identity = AuthIdentity(issuer='https://casdoor.test', subject='subject-1', username='alice') assert identity_key(identity) == ('https://casdoor.test', 'subject-1') with pytest.raises(IdentityValidationError): identity_key(AuthIdentity(issuer='https://casdoor.test', subject='', username='alice')) def test_identity_from_claims_validates_issuer_and_normalizes_fields(): """Casdoor claims 转换后保留稳定身份和可变资料,并拒绝错误 issuer。""" identity = identity_from_claims({ 'iss': 'https://casdoor.test/', 'sub': 'subject-1', 'preferred_username': 'alice', 'employeeId': 'E1001', 'displayName': 'Alice Zhang', 'email': 'alice@example.com', 'affiliation': 'IT', }, expected_issuer='https://casdoor.test') assert identity.username == 'alice' assert identity.display_name == 'Alice Zhang' assert identity.employee_id == 'E1001' assert identity.department == 'IT' with pytest.raises(IdentityValidationError): identity_from_claims({ 'iss': 'https://evil.test', 'sub': 'subject-1', 'preferred_username': 'alice', }, expected_issuer='https://casdoor.test') def test_identity_from_claims_uses_configured_issuer_when_userinfo_omits_iss(): """Casdoor userinfo 可省略 iss,但服务端可信 issuer 仍必须来自 discovery 对齐配置。""" identity = identity_from_claims({ 'sub': 'subject-1', 'preferred_username': 'alice', }, expected_issuer='https://casdoor.test') assert identity.issuer == 'https://casdoor.test' assert identity.subject == 'subject-1' def test_identity_from_claims_reads_employee_id_from_casdoor_properties(): """Casdoor 将自定义工号放在 properties 时,公共解析器仍输出 employee_id。""" identity = identity_from_claims({ 'sub': 'subject-1', 'preferred_username': '26040006', 'properties': {'employee_id': '26040006'}, }, expected_issuer='https://casdoor.test') assert identity.employee_id == '26040006' def test_casdoor_config_repr_does_not_expose_secret(app): """配置对象可诊断但不得在 repr 中泄漏 Casdoor client_secret。""" app.config.update( CASDOOR_BASE_URL='https://casdoor.test/', CASDOOR_CLIENT_ID='peer-client', CASDOOR_CLIENT_SECRET='top-secret-value', AUTH_JWT_ISSUER='https://casdoor.test', CASDOOR_SCOPE='openid profile email', CASDOOR_HTTP_TIMEOUT_SECONDS=9, ) config = casdoor_config_from_flask() assert config.base_url == 'https://casdoor.test' assert config.timeout_seconds == 9 assert 'top-secret-value' not in repr(config) def test_casdoor_server_endpoints_follow_base_url_when_issuer_uses_expired_https(): """公网 HTTPS 证书不可用时,换票和 userinfo 改走 CASDOOR_BASE_URL,浏览器授权地址保持原域名。""" http = FakeHttp() http.get = lambda url, **kwargs: FakeResponse({ 'issuer': 'https://auth.example.com', 'authorization_endpoint': 'https://auth.example.com/login/oauth/authorize', 'token_endpoint': 'https://auth.example.com/api/login/oauth/access_token', 'userinfo_endpoint': 'https://auth.example.com/api/userinfo', 'jwks_uri': 'https://auth.example.com/.well-known/jwks', }) if url.endswith('/.well-known/openid-configuration') else FakeResponse({}) client = CasdoorClient(CasdoorConfig( base_url='http://192.168.100.230:8870', client_id='peer-client', client_secret='peer-secret', issuer='https://auth.example.com', ), http_session=http) metadata = client.oidc_metadata() # 后端换票不能再访问过期证书上的 HTTPS 域名。 assert metadata['token_endpoint'] == 'http://192.168.100.230:8870/api/login/oauth/access_token' assert metadata['userinfo_endpoint'] == 'http://192.168.100.230:8870/api/userinfo' assert metadata['jwks_uri'] == 'http://192.168.100.230:8870/.well-known/jwks' # 浏览器授权仍使用 discovery 原地址。 assert metadata['authorization_endpoint'] == 'https://auth.example.com/login/oauth/authorize' client.password_login('alice', 'user-password') assert http.posts[0][0] == 'http://192.168.100.230:8870/api/login/oauth/access_token' def test_casdoor_password_client_request_is_framework_independent(): """公共客户端按配置发送 password grant,不依赖 HXOPS User 或数据库。""" http = FakeHttp() client = CasdoorClient(CasdoorConfig( base_url='https://casdoor.test', client_id='peer-client', client_secret='peer-secret', issuer='https://casdoor.test', timeout_seconds=7, ), http_session=http) result = client.password_login('alice', 'user-password') assert result.access_token == 'casdoor-access' _, request = http.posts[0] assert request['data']['grant_type'] == 'password' assert request['data']['client_id'] == 'peer-client' assert request['data']['password'] == 'user-password' assert request['timeout'] == 7 def test_flask_casdoor_client_is_reused_until_config_changes(app): """Flask 适配器复用 discovery 缓存,并在服务配置变化后创建新客户端。""" app.config.update( CASDOOR_BASE_URL='https://casdoor.test', CASDOOR_CLIENT_ID='peer-client-cache', CASDOOR_CLIENT_SECRET='peer-secret-cache', AUTH_JWT_ISSUER='https://casdoor.test', CASDOOR_HTTP_TIMEOUT_SECONDS=8, ) first = get_casdoor_client() second = get_casdoor_client() assert first is second app.config['CASDOOR_CLIENT_ID'] = 'peer-client-changed' third = get_casdoor_client() assert third is not first @pytest.mark.parametrize( ('source', 'context', 'code', 'status'), [ ({'error': 'invalid_grant'}, 'password', 'CASDOOR_INVALID_CREDENTIALS', 401), ({'error': 'invalid_client'}, 'password', 'CASDOOR_CONFIG_ERROR', 503), ({'error': 'access_denied'}, 'code', 'CASDOOR_ACCESS_DENIED', 403), ({'error': 'unsupported_grant_type'}, 'refresh', 'AUTH.CASDOOR_REFRESH_UNSUPPORTED', 400), ], ) def test_casdoor_error_mapping_is_stable(app, source, context, code, status): """公共错误映射保持现有 HXOPS 业务码,供平级服务复制后统一处理。""" with pytest.raises(AppError) as captured: raise_auth_error(source, context=context) assert captured.value.code == code assert captured.value.http_status == status