feat(auth): 重构统一认证并支持平级服务无感登录
This commit is contained in:
1 parent
d79def5519
commit
ca312ea751
64 files changed
+3713
-449
No files matched your search
@@ -8,6 +8,7 @@ tests/test_admin_create_user_casdoor.py
|
||||
import pytest
|
||||
|
||||
from app import db
|
||||
from app.core.auth.jwt import issue_local_access_token
|
||||
from app.models import User
|
||||
from app.api import user as user_api
|
||||
from app.services.auth import casdoor_service
|
||||
@@ -24,6 +25,21 @@ NEW_USER_PAYLOAD = {
|
||||
}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def admin_headers(app):
|
||||
"""为 Casdoor 用户同步接口生成真实 HXOPS 管理员 JWT,避免依赖旧认证请求头。"""
|
||||
app.config['SECRET_KEY'] = 'test-casdoor-sync-secret-at-least-32-bytes'
|
||||
admin = User(username='casdoor-sync-admin', email='casdoor-sync-admin@example.com', role='admin', status='active')
|
||||
admin.set_password('test-admin-password')
|
||||
db.session.add(admin)
|
||||
db.session.commit()
|
||||
token = issue_local_access_token(admin)
|
||||
return {
|
||||
'Authorization': f'Bearer {token}',
|
||||
'Content-Type': 'application/json',
|
||||
}
|
||||
|
||||
|
||||
def test_admin_create_user_syncs_casdoor(client, admin_headers, monkeypatch):
|
||||
"""
|
||||
Casdoor 已配置时,管理端创建用户应调用 add-user 且本地库成功入库。
|
||||
|
||||
@@ -0,0 +1,177 @@
|
||||
"""
|
||||
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',
|
||||
'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.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_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_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
|
||||
@@ -0,0 +1,167 @@
|
||||
"""
|
||||
backend/tests/test_casdoor_api_session.py
|
||||
|
||||
用途:验证 Casdoor 认证成功后返回 HXOPS 本地 API 会话 JWT,并保留稳定 Casdoor 身份引用。
|
||||
依赖:Flask 测试客户端、User 模型、user API 的 Casdoor 调用替身。
|
||||
逻辑:模拟 password grant/userinfo,随后使用返回 token 访问受保护 API,防止登录后首个请求立即 401。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import jwt
|
||||
import pytest
|
||||
|
||||
from app import db
|
||||
from app.api import user as user_api
|
||||
from app.core.errors import AppError
|
||||
from app.models import User
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def casdoor_user(app):
|
||||
"""创建能被 Casdoor userinfo 映射的 active HXOPS 用户。"""
|
||||
user = User(username='casdoor-session', email='casdoor-session@example.com', role='user', status='active')
|
||||
db.session.add(user)
|
||||
db.session.commit()
|
||||
return user
|
||||
|
||||
|
||||
def test_password_login_returns_hxops_api_session(client, app, casdoor_user, monkeypatch):
|
||||
"""密码由 Casdoor 校验,但浏览器使用 HXOPS 签名 JWT 调用本站 API。"""
|
||||
app.config.update(
|
||||
AUTH_LOGIN_MODE='casdoor',
|
||||
AUTH_JWT_ISSUER='https://casdoor.example.com',
|
||||
AUTH_LOCAL_JWT_ISSUER='hxops-backend',
|
||||
AUTH_LOCAL_JWT_AUDIENCE='hxops-frontend',
|
||||
AUTH_ALLOW_LOCAL_JWT=True,
|
||||
SECRET_KEY='test-session-secret',
|
||||
)
|
||||
monkeypatch.setattr(user_api, '_casdoor_password_login', lambda username, password: {
|
||||
'access_token': 'opaque-casdoor-access-token',
|
||||
'refresh_token': 'casdoor-refresh-token',
|
||||
'expires_in': 3600,
|
||||
})
|
||||
monkeypatch.setattr(user_api, '_casdoor_userinfo', lambda token: {
|
||||
'iss': 'https://casdoor.example.com',
|
||||
'sub': 'casdoor-subject-session',
|
||||
'preferred_username': casdoor_user.username,
|
||||
'email': casdoor_user.email,
|
||||
})
|
||||
|
||||
login = client.post('/api/user/casdoor/password-login', json={
|
||||
'username': casdoor_user.username,
|
||||
'password': 'correct-password',
|
||||
})
|
||||
assert login.status_code == 200
|
||||
body = login.get_json()
|
||||
data = body.get('data') if body.get('success') is True else body
|
||||
api_token = data['access_token']
|
||||
assert api_token != 'opaque-casdoor-access-token'
|
||||
|
||||
claims = jwt.decode(
|
||||
api_token,
|
||||
app.config['SECRET_KEY'],
|
||||
algorithms=['HS256'],
|
||||
issuer='hxops-backend',
|
||||
audience='hxops-frontend',
|
||||
)
|
||||
assert claims['casdoor_iss'] == 'https://casdoor.example.com'
|
||||
assert claims['casdoor_sub'] == 'casdoor-subject-session'
|
||||
|
||||
home = client.get('/api/user/home', headers={'Authorization': f'Bearer {api_token}'})
|
||||
assert home.status_code == 200
|
||||
|
||||
|
||||
def test_authorization_code_login_returns_hxops_api_session(client, app, casdoor_user, monkeypatch):
|
||||
"""授权码回调复用统一登录编排,并签发可访问 HXOPS API 的本地 JWT。"""
|
||||
app.config.update(
|
||||
AUTH_JWT_ISSUER='https://casdoor.example.com',
|
||||
AUTH_LOCAL_JWT_ISSUER='hxops-backend',
|
||||
AUTH_LOCAL_JWT_AUDIENCE='hxops-frontend',
|
||||
AUTH_ALLOW_LOCAL_JWT=True,
|
||||
SECRET_KEY='test-code-session-secret-at-least-32-bytes',
|
||||
)
|
||||
monkeypatch.setattr(user_api, '_casdoor_exchange_code', lambda code, redirect_uri: {
|
||||
'access_token': 'code-opaque-casdoor-access-token',
|
||||
'refresh_token': 'code-casdoor-refresh-token',
|
||||
'expires_in': 3600,
|
||||
})
|
||||
monkeypatch.setattr(user_api, '_casdoor_userinfo', lambda token: {
|
||||
'iss': 'https://casdoor.example.com',
|
||||
'sub': 'casdoor-subject-code-session',
|
||||
'preferred_username': casdoor_user.username,
|
||||
'email': casdoor_user.email,
|
||||
})
|
||||
with app.app_context():
|
||||
state = user_api._issue_casdoor_state('https://hxops.example.com/auth/callback')
|
||||
|
||||
login = client.post('/api/user/casdoor/login', json={
|
||||
'code': 'authorization-code',
|
||||
'state': state,
|
||||
})
|
||||
assert login.status_code == 200
|
||||
body = login.get_json()
|
||||
data = body.get('data') if body.get('success') is True else body
|
||||
assert data['refresh_token'] == 'code-casdoor-refresh-token'
|
||||
|
||||
claims = jwt.decode(
|
||||
data['access_token'],
|
||||
app.config['SECRET_KEY'],
|
||||
algorithms=['HS256'],
|
||||
issuer='hxops-backend',
|
||||
audience='hxops-frontend',
|
||||
)
|
||||
assert claims['casdoor_sub'] == 'casdoor-subject-code-session'
|
||||
|
||||
home = client.get('/api/user/home', headers={'Authorization': f"Bearer {data['access_token']}"})
|
||||
assert home.status_code == 200
|
||||
|
||||
|
||||
def test_refresh_returns_new_hxops_api_session(client, app, casdoor_user, monkeypatch):
|
||||
"""Casdoor refresh 成功后重新映射用户并签发新的 HXOPS API 会话。"""
|
||||
app.config.update(
|
||||
AUTH_JWT_ISSUER='https://casdoor.example.com',
|
||||
AUTH_LOCAL_JWT_ISSUER='hxops-backend',
|
||||
AUTH_LOCAL_JWT_AUDIENCE='hxops-frontend',
|
||||
AUTH_ALLOW_LOCAL_JWT=True,
|
||||
SECRET_KEY='test-session-secret-at-least-32-bytes',
|
||||
)
|
||||
monkeypatch.setattr(user_api, '_casdoor_refresh_token', lambda refresh_token: {
|
||||
'access_token': 'next-opaque-casdoor-access-token',
|
||||
'refresh_token': 'next-casdoor-refresh-token',
|
||||
'expires_in': 3600,
|
||||
})
|
||||
monkeypatch.setattr(user_api, '_casdoor_userinfo', lambda token: {
|
||||
'iss': 'https://casdoor.example.com',
|
||||
'sub': 'casdoor-subject-session',
|
||||
'preferred_username': casdoor_user.username,
|
||||
'email': casdoor_user.email,
|
||||
})
|
||||
|
||||
refreshed = client.post('/api/user/casdoor/refresh', json={
|
||||
'refresh_token': 'old-casdoor-refresh-token',
|
||||
})
|
||||
assert refreshed.status_code == 200
|
||||
body = refreshed.get_json()
|
||||
data = body.get('data') if body.get('success') is True else body
|
||||
api_token = data['access_token']
|
||||
assert api_token != 'next-opaque-casdoor-access-token'
|
||||
assert data['refresh_token'] == 'next-casdoor-refresh-token'
|
||||
|
||||
home = client.get('/api/user/home', headers={'Authorization': f'Bearer {api_token}'})
|
||||
assert home.status_code == 200
|
||||
|
||||
|
||||
def test_refresh_preserves_structured_casdoor_error(client, monkeypatch):
|
||||
"""刷新 grant 的稳定 AppError 应原样返回,不能被路由兜底包装成通用 401。"""
|
||||
def unsupported_refresh(_refresh_token):
|
||||
raise AppError(
|
||||
code='AUTH.CASDOOR_REFRESH_UNSUPPORTED',
|
||||
message='Casdoor refresh token is not supported by current application config',
|
||||
http_status=400,
|
||||
)
|
||||
|
||||
monkeypatch.setattr(user_api, '_casdoor_refresh_token', unsupported_refresh)
|
||||
response = client.post('/api/user/casdoor/refresh', json={'refresh_token': 'unsupported-token'})
|
||||
assert response.status_code == 400
|
||||
assert response.get_json()['error']['code'] == 'AUTH.CASDOOR_REFRESH_UNSUPPORTED'
|
||||
@@ -0,0 +1,316 @@
|
||||
"""
|
||||
backend/tests/test_sso.py
|
||||
|
||||
用途:验证 HXOPS 面向产品内平级服务的 RS256 assertion、应用注册表和 JWKS 契约。
|
||||
依赖:Flask 测试客户端、User、PyJWT、cryptography 与临时 RSA 密钥。
|
||||
逻辑:模拟带 Casdoor 身份引用的 HXOPS 会话,断言 JWT 受众、有效期、身份字段和公钥发布均符合协议。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
|
||||
import jwt
|
||||
import pytest
|
||||
from cryptography.hazmat.primitives import serialization
|
||||
from cryptography.hazmat.primitives.asymmetric import rsa
|
||||
from flask import g
|
||||
|
||||
from app import db
|
||||
from app.models import User
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def active_user(app):
|
||||
"""创建可签发平级服务登录 assertion 的 active HXOPS 用户。"""
|
||||
user = User(
|
||||
username='sso-user',
|
||||
email='sso-user@example.com',
|
||||
real_name='SSO User',
|
||||
employee_id='E1001',
|
||||
phone_number='13800000001',
|
||||
department='IT',
|
||||
role='user',
|
||||
status='active',
|
||||
)
|
||||
db.session.add(user)
|
||||
db.session.commit()
|
||||
return user
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def sso_keys(tmp_path):
|
||||
"""生成仅供当前测试使用的当前私钥、旧公钥文件和公钥对象。"""
|
||||
private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
|
||||
private_key_path = tmp_path / 'hxops-sso-private.pem'
|
||||
private_key_path.write_bytes(private_key.private_bytes(
|
||||
encoding=serialization.Encoding.PEM,
|
||||
format=serialization.PrivateFormat.PKCS8,
|
||||
encryption_algorithm=serialization.NoEncryption(),
|
||||
))
|
||||
old_private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
|
||||
old_public_key_path = tmp_path / 'hxops-sso-old-public.pem'
|
||||
old_public_key_path.write_bytes(old_private_key.public_key().public_bytes(
|
||||
encoding=serialization.Encoding.PEM,
|
||||
format=serialization.PublicFormat.SubjectPublicKeyInfo,
|
||||
))
|
||||
return private_key_path, private_key.public_key(), old_public_key_path
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def sso_config(app, sso_keys):
|
||||
"""启用一个使用测试地址和独立 audience 的产品内平级服务。"""
|
||||
private_key_path, public_key, old_public_key_path = sso_keys
|
||||
app.config.update(
|
||||
SSO_ENABLED=True,
|
||||
ENV_NAME='test',
|
||||
AUTH_JWT_ISSUER='https://casdoor.example.com',
|
||||
SSO_ASSERTION_TTL_SECONDS=60,
|
||||
SSO_ISSUER='http://hxops.test',
|
||||
SSO_SIGNING_ALGORITHM='RS256',
|
||||
SSO_SIGNING_KEY_ID='hxops-sso-test-key',
|
||||
SSO_PRIVATE_KEY_PATH=str(private_key_path),
|
||||
SSO_ADDITIONAL_PUBLIC_KEYS_JSON=json.dumps([{
|
||||
'kid': 'hxops-sso-old-key',
|
||||
'public_key_path': str(old_public_key_path),
|
||||
}]),
|
||||
SSO_APPS_JSON=json.dumps([{
|
||||
'key': 'peer-service',
|
||||
'display_name': 'Peer Service',
|
||||
'login_url': 'http://peer.test/auth/hxops/start',
|
||||
'callback_url': 'http://peer.test/auth/hxops/callback',
|
||||
'audience': 'peer-service',
|
||||
'enabled': True,
|
||||
}]),
|
||||
)
|
||||
return public_key
|
||||
|
||||
|
||||
def _bearer_user(monkeypatch, user, *, claims=None):
|
||||
"""模拟已验证 HXOPS API JWT,并把 Casdoor 稳定身份引用挂到 Flask g。"""
|
||||
resolved_claims = claims if claims is not None else {
|
||||
'casdoor_iss': 'https://casdoor.example.com',
|
||||
'casdoor_sub': 'casdoor-subject-1001',
|
||||
}
|
||||
|
||||
def resolve_user():
|
||||
g.jwt_claims = resolved_claims
|
||||
return user
|
||||
|
||||
monkeypatch.setattr('app.api.sso.get_current_user', resolve_user)
|
||||
|
||||
|
||||
def _data(response):
|
||||
"""兼容是否启用成功 envelope,提取实际 API 数据。"""
|
||||
body = response.get_json()
|
||||
return body.get('data') if body.get('success') is True else body
|
||||
|
||||
|
||||
def _error_code(response):
|
||||
"""从统一错误 envelope 中提取业务错误码。"""
|
||||
return (response.get_json().get('error') or {}).get('code')
|
||||
|
||||
|
||||
def _issue(client, monkeypatch, user, *, state='peer-signed-state'):
|
||||
"""签发一枚测试 assertion,供声明与错误分支测试复用。"""
|
||||
_bearer_user(monkeypatch, user)
|
||||
return client.post(
|
||||
'/api/sso/apps/peer-service/assertions',
|
||||
headers={'Authorization': 'Bearer verified-token'},
|
||||
json={'state': state},
|
||||
)
|
||||
|
||||
|
||||
def test_apps_requires_bearer_header(client, sso_config):
|
||||
"""平级服务目录不接受匿名请求或 legacy 用户头。"""
|
||||
response = client.get('/api/sso/apps')
|
||||
assert response.status_code == 401
|
||||
assert _error_code(response) == 'AUTH.UNAUTHORIZED'
|
||||
|
||||
|
||||
def test_assertion_is_rs256_audience_bound_and_contains_no_permissions(
|
||||
client,
|
||||
active_user,
|
||||
sso_config,
|
||||
monkeypatch,
|
||||
):
|
||||
"""签发结果可被公开密钥验证,且只包含共享身份、不包含 HXOPS 权限。"""
|
||||
response = _issue(client, monkeypatch, active_user)
|
||||
assert response.status_code == 200
|
||||
result = _data(response)
|
||||
assert result['post_url'] == 'http://peer.test/auth/hxops/callback'
|
||||
assert result['state'] == 'peer-signed-state'
|
||||
assert result['expires_in'] == 60
|
||||
|
||||
header = jwt.get_unverified_header(result['assertion'])
|
||||
assert header['alg'] == 'RS256'
|
||||
assert header['kid'] == 'hxops-sso-test-key'
|
||||
claims = jwt.decode(
|
||||
result['assertion'],
|
||||
sso_config,
|
||||
algorithms=['RS256'],
|
||||
issuer='http://hxops.test',
|
||||
audience='peer-service',
|
||||
)
|
||||
|
||||
# 关键断言:稳定 Casdoor 身份进入 token,本地用户主键和业务权限不得泄漏。
|
||||
assert claims['sub'] == 'casdoor-subject-1001'
|
||||
assert claims['identity_issuer'] == 'https://casdoor.example.com'
|
||||
assert claims['preferred_username'] == active_user.username
|
||||
assert claims['name'] == active_user.real_name
|
||||
assert claims['exp'] - claims['iat'] == 60
|
||||
assert claims['nbf'] <= claims['iat']
|
||||
assert claims['jti']
|
||||
assert 'user_id' not in claims
|
||||
assert 'role' not in claims
|
||||
assert 'feature_permissions' not in claims
|
||||
|
||||
|
||||
def test_each_assertion_has_a_unique_jti(client, active_user, sso_config, monkeypatch):
|
||||
"""同一用户连续签发的 assertion 使用不同 jti,便于平级服务按需增加防重放。"""
|
||||
first = _data(_issue(client, monkeypatch, active_user))['assertion']
|
||||
second = _data(_issue(client, monkeypatch, active_user))['assertion']
|
||||
first_claims = jwt.decode(first, sso_config, algorithms=['RS256'], audience='peer-service')
|
||||
second_claims = jwt.decode(second, sso_config, algorithms=['RS256'], audience='peer-service')
|
||||
assert first_claims['jti'] != second_claims['jti']
|
||||
|
||||
|
||||
def test_jwks_publishes_matching_public_key(client, sso_config):
|
||||
"""公开 JWKS 同时发布当前和旧公钥,且响应不包含任何私钥参数。"""
|
||||
response = client.get('/.well-known/jwks.json')
|
||||
assert response.status_code == 200
|
||||
body = _data(response)
|
||||
assert response.headers['Cache-Control'] == 'public, max-age=300'
|
||||
assert len(body['keys']) == 2
|
||||
jwk = next(item for item in body['keys'] if item['kid'] == 'hxops-sso-test-key')
|
||||
old_jwk = next(item for item in body['keys'] if item['kid'] == 'hxops-sso-old-key')
|
||||
assert jwk['kid'] == 'hxops-sso-test-key'
|
||||
assert jwk['alg'] == 'RS256'
|
||||
assert jwk['kty'] == 'RSA'
|
||||
assert jwk['use'] == 'sig'
|
||||
assert jwk['n']
|
||||
assert jwk['e'] == 'AQAB'
|
||||
assert old_jwk['alg'] == 'RS256'
|
||||
assert old_jwk['n'] != jwk['n']
|
||||
assert 'd' not in jwk
|
||||
assert 'p' not in jwk
|
||||
assert 'q' not in jwk
|
||||
|
||||
|
||||
def test_assertion_requires_casdoor_identity(client, active_user, sso_config, monkeypatch):
|
||||
"""缺少 casdoor_iss/casdoor_sub 的 HXOPS 本地登录态不能跨服务签发身份。"""
|
||||
_bearer_user(monkeypatch, active_user, claims={'username': active_user.username})
|
||||
response = client.post(
|
||||
'/api/sso/apps/peer-service/assertions',
|
||||
headers={'Authorization': 'Bearer local-token'},
|
||||
json={'state': 'peer-signed-state'},
|
||||
)
|
||||
assert response.status_code == 403
|
||||
assert _error_code(response) == 'AUTH.SSO_IDENTITY_UNSUPPORTED'
|
||||
|
||||
|
||||
def test_local_issuer_subject_cannot_impersonate_casdoor(
|
||||
client,
|
||||
active_user,
|
||||
sso_config,
|
||||
monkeypatch,
|
||||
):
|
||||
"""HXOPS API JWT 自身的标准 iss/sub 不能冒充 Casdoor 身份引用。"""
|
||||
_bearer_user(monkeypatch, active_user, claims={
|
||||
'iss': 'hxops-backend',
|
||||
'sub': str(active_user.id),
|
||||
})
|
||||
response = client.post(
|
||||
'/api/sso/apps/peer-service/assertions',
|
||||
headers={'Authorization': 'Bearer local-token'},
|
||||
json={'state': 'peer-signed-state'},
|
||||
)
|
||||
assert response.status_code == 403
|
||||
assert _error_code(response) == 'AUTH.SSO_IDENTITY_UNSUPPORTED'
|
||||
|
||||
|
||||
@pytest.mark.parametrize('state', ['', 'x' * 4097])
|
||||
def test_assertion_rejects_invalid_state(client, active_user, sso_config, monkeypatch, state):
|
||||
"""state 必须存在且受长度限制,避免放大请求或意外持久化不可信数据。"""
|
||||
response = _issue(client, monkeypatch, active_user, state=state)
|
||||
assert response.status_code == 400
|
||||
assert _error_code(response) == 'VALIDATION.INVALID_PARAM'
|
||||
|
||||
|
||||
def test_assertion_rejects_unknown_application(client, active_user, sso_config, monkeypatch):
|
||||
"""浏览器不能通过未注册 app key 指定任意 callback 或 audience。"""
|
||||
_bearer_user(monkeypatch, active_user)
|
||||
response = client.post(
|
||||
'/api/sso/apps/not-registered/assertions',
|
||||
headers={'Authorization': 'Bearer verified-token'},
|
||||
json={'state': 'peer-signed-state'},
|
||||
)
|
||||
assert response.status_code == 404
|
||||
assert _error_code(response) == 'AUTH.SSO_APP_NOT_FOUND'
|
||||
|
||||
|
||||
def test_application_registry_rejects_duplicate_audience(client, app, active_user, sso_config, monkeypatch):
|
||||
"""两个平级服务不能共享 audience,避免一个服务接受签给另一个服务的 assertion。"""
|
||||
app.config['SSO_APPS_JSON'] = json.dumps([
|
||||
{
|
||||
'key': 'peer-service-a',
|
||||
'display_name': 'Peer Service A',
|
||||
'login_url': 'http://peer-a.test/auth/hxops/start',
|
||||
'callback_url': 'http://peer-a.test/auth/hxops/callback',
|
||||
'audience': 'shared-audience',
|
||||
},
|
||||
{
|
||||
'key': 'peer-service-b',
|
||||
'display_name': 'Peer Service B',
|
||||
'login_url': 'http://peer-b.test/auth/hxops/start',
|
||||
'callback_url': 'http://peer-b.test/auth/hxops/callback',
|
||||
'audience': 'shared-audience',
|
||||
},
|
||||
])
|
||||
_bearer_user(monkeypatch, active_user)
|
||||
response = client.get('/api/sso/apps', headers={'Authorization': 'Bearer verified-token'})
|
||||
assert response.status_code == 503
|
||||
assert _error_code(response) == 'AUTH.SSO_CONFIG_ERROR'
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
('config_key', 'config_value'),
|
||||
[
|
||||
('SSO_ASSERTION_TTL_SECONDS', 61),
|
||||
('SSO_SIGNING_ALGORITHM', 'HS256'),
|
||||
('SSO_PRIVATE_KEY_PATH', ''),
|
||||
],
|
||||
)
|
||||
def test_assertion_fails_closed_for_invalid_signing_config(
|
||||
client,
|
||||
app,
|
||||
active_user,
|
||||
sso_config,
|
||||
monkeypatch,
|
||||
config_key,
|
||||
config_value,
|
||||
):
|
||||
"""TTL、算法或私钥配置错误时返回 503,不使用普通 API JWT 密钥降级。"""
|
||||
app.config[config_key] = config_value
|
||||
response = _issue(client, monkeypatch, active_user)
|
||||
assert response.status_code == 503
|
||||
assert _error_code(response) == 'AUTH.SSO_CONFIG_ERROR'
|
||||
|
||||
|
||||
def test_jwks_fails_closed_for_duplicate_rotation_key_id(client, app, sso_config):
|
||||
"""旧验证公钥不得复用当前 kid,避免平级服务选择到含义不明确的公钥。"""
|
||||
app.config['SSO_ADDITIONAL_PUBLIC_KEYS_JSON'] = json.dumps([{
|
||||
'kid': 'hxops-sso-test-key',
|
||||
'public_key_path': 'unused',
|
||||
}])
|
||||
response = client.get('/.well-known/jwks.json', headers={'Accept': 'application/json'})
|
||||
assert response.status_code == 503
|
||||
assert _error_code(response) == 'AUTH.SSO_CONFIG_ERROR'
|
||||
|
||||
|
||||
def test_legacy_ticket_and_exchange_routes_are_removed(client, sso_config):
|
||||
"""旧 Redis ticket 协议路由必须彻底下线,避免两个认证契约并存。"""
|
||||
ticket_response = client.post('/api/sso/apps/peer-service/tickets')
|
||||
exchange_response = client.post('/api/sso/exchange')
|
||||
assert ticket_response.status_code == 404
|
||||
assert exchange_response.status_code == 404
|
||||
Reference in new issue
Block a user