317 lines
12 KiB
Python
317 lines
12 KiB
Python
"""
|
|
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
|