feat(auth): 重构统一认证并支持平级服务无感登录

This commit is contained in:
sophie committed 2026-07-28 09:15:41 +08:00
1 parent d79def5519
commit ca312ea751
64 files changed
+3713 -449

No files matched your search

+1 -1
View File
@@ -118,7 +118,7 @@ def create_app(config_name='default'):
return wrapped_resp
def _should_return_json_error() -> bool:
if request.path.startswith('/api/'):
if request.path.startswith('/api/') or request.path == '/.well-known/jwks.json':
return True
accepted = request.headers.get('Accept', '')
return 'application/json' in accepted.lower()
+3
View File
@@ -26,6 +26,7 @@ def register_blueprints(app: Flask) -> None:
from app.api.internal_jobs import internal_jobs_bp
from app.api.maintenance import maintenance_bp
from app.api.speech import speech_bp
from app.api.sso import sso_bp, sso_well_known_bp
from app.api.training import training_admin_bp, training_user_bp
from app.api.agent_runtime_context_tools import agent_runtime_context_bp
@@ -61,6 +62,8 @@ def register_blueprints(app: Flask) -> None:
app.register_blueprint(agent_runtime_context_bp, url_prefix='/api/agent-runtime-context')
app.register_blueprint(maintenance_tool_bp, url_prefix='/api/maintenance')
app.register_blueprint(speech_bp, url_prefix='/api/speech')
app.register_blueprint(sso_bp, url_prefix='/api/sso')
app.register_blueprint(sso_well_known_bp)
app.register_blueprint(training_admin_bp, url_prefix='/api/admin')
app.register_blueprint(files_bp, url_prefix='/api/files')
app.register_blueprint(procurement_contract_bp, url_prefix='/api/procurement-contract')
+66
View File
@@ -0,0 +1,66 @@
"""
backend/app/api/sso.py
Purpose: Expose peer-service discovery, short-lived assertion issuance, and public JWKS APIs.
Dependencies: JWT current-user resolver, SSO services, and Flask Blueprint.
Flow: Authenticated browsers request audience-bound assertions; peer-service backends verify them using JWKS.
"""
from __future__ import annotations
from flask import Blueprint, g, jsonify, request
from app.core.auth.jwt import get_current_user
from app.core.errors import AppError, UnauthorizedError, ValidationError
from app.services.auth.sso import build_jwks, issue_assertion, list_applications
sso_bp = Blueprint('sso', __name__)
sso_well_known_bp = Blueprint('sso_well_known', __name__)
def _require_active_user():
"""Resolve an active Bearer-authenticated user and retain verified JWT claims."""
authorization = str(request.headers.get('Authorization') or '').strip()
scheme, _, token = authorization.partition(' ')
if scheme.lower() != 'bearer' or not token.strip():
raise UnauthorizedError('Bearer token is required')
user = get_current_user()
if user is None:
raise UnauthorizedError('Unauthorized')
claims = dict(getattr(g, 'jwt_claims', None) or {})
if not claims:
raise UnauthorizedError('Verified Bearer token is required')
if user.status != 'active':
raise AppError(code='AUTH.ACCOUNT_DISABLED', message='Account is disabled', http_status=403)
return user, claims
@sso_bp.route('/apps', methods=['GET'])
def list_sso_apps():
"""Return enabled application navigation metadata to authenticated HXOPS users."""
_require_active_user()
return jsonify({'items': [application.public_payload() for application in list_applications()]})
@sso_bp.route('/apps/<string:app_key>/assertions', methods=['POST'])
def create_sso_assertion(app_key: str):
"""Issue a short-lived RS256 assertion and return the registered peer callback URL."""
user, claims = _require_active_user()
data = request.get_json(silent=True) or {}
if not isinstance(data, dict):
raise ValidationError('JSON body is required')
return jsonify(issue_assertion(
app_key=app_key,
user=user,
claims=claims,
state=data.get('state'),
))
@sso_well_known_bp.route('/.well-known/jwks.json', methods=['GET'])
def sso_jwks():
"""Publish active and rotation-window product SSO public keys for offline peer verification."""
response = jsonify(build_jwks())
response.headers['Cache-Control'] = 'public, max-age=300'
return response
+89 -112
View File
@@ -14,7 +14,6 @@ from app.services.agent_registry.serialization import serialize_registry_fields
from app.services.wecom_notify import mark_wecom_message_opened, send_wecom_event_message
from app.services.wecom_crypto import sha1_hex, decrypt_wecom_aes, extract_encrypt_field
from app.core.auth.jwt import get_current_user as _auth_current_user
from app.core.auth.jwt import issue_local_access_token
from sqlalchemy.exc import DatabaseError, IntegrityError, OperationalError
from sqlalchemy import and_, or_, inspect, insert
from datetime import datetime, timedelta
@@ -38,6 +37,8 @@ from app.core.errors import (
raise_for_status,
)
from app.services.auth import casdoor_service as _casdoor_svc
from app.services.auth.casdoor import get_casdoor_client
from app.services.auth.hxops.login_service import HxopsLoginService
from app.services.auth import wecom_auth_service as _wecom_svc
user_bp = Blueprint('user', __name__)
_WECOM_ACCESS_TOKEN_CACHE = _wecom_svc.ACCESS_TOKEN_CACHE
@@ -47,7 +48,6 @@ _PASSWORD_RESET_RATE_CACHE = {}
_PASSWORD_RESET_GENERIC_MESSAGE = 'If the account exists and WeCom is bound, a reset link has been sent to your WeCom.'
_ALLOWED_WECOM_MATCH_FIELDS = {'employee_id', 'mobile', 'email'}
_LOGIN_AUDIT_COLUMNS_CACHE = None
_CASDOOR_OIDC_CACHE = {'value': None, 'expires_at': None}
def _token_brief(token: str) -> str:
if not token:
@@ -174,84 +174,91 @@ def _consume_casdoor_state(state: str):
return _clean_str(payload.get('redirect_uri'))
def _get_casdoor_oidc_metadata():
now = datetime.utcnow()
cached = _CASDOOR_OIDC_CACHE.get('value')
exp = _CASDOOR_OIDC_CACHE.get('expires_at')
if cached and exp and (exp > now):
return cached
base = (current_app.config.get('CASDOOR_BASE_URL') or '').rstrip('/')
if not base:
raise RuntimeError('CASDOOR_BASE_URL is not configured')
resp = requests.get(f'{base}/.well-known/openid-configuration', timeout=8)
resp.raise_for_status()
data = resp.json() or {}
_CASDOOR_OIDC_CACHE['value'] = data
_CASDOOR_OIDC_CACHE['expires_at'] = now + timedelta(minutes=10)
return data
"""兼容旧调用点:委托公共 CasdoorClient 获取 discovery 文档。"""
return get_casdoor_client().oidc_metadata()
def _resolve_user_from_casdoor_claims(claims: dict):
username = _clean_str(claims.get('preferred_username')) or _clean_str(claims.get('name'))
email = _clean_str(claims.get('email'))
current_app.logger.info('[casdoor_login] claims preferred_username=%s name=%s email=%s sub=%s', _clean_str(claims.get('preferred_username')), _clean_str(claims.get('name')), email, _clean_str(claims.get('sub')))
user = None
if username:
user = db.session.query(User).filter_by(username=username).first()
if not user and email:
user = db.session.query(User).filter_by(email=email).first()
if not user:
raise WeComLoginError(error='No local user matched Casdoor identity. Please contact admin to provision account.', error_code='CASDOOR_USER_NOT_FOUND', status_code=403)
if user.status != 'active':
raise WeComLoginError(error='Account is disabled', error_code='ACCOUNT_DISABLED', status_code=403)
return user
"""兼容旧调用点:通过公共身份对象映射 HXOPS 用户。"""
from app.services.auth.casdoor.identity import identity_from_claims
from app.services.auth.common import IdentityValidationError
from app.services.auth.hxops.user_resolver import HxopsIdentityMappingError, resolve_hxops_user
try:
identity = identity_from_claims(
claims,
expected_issuer=str(current_app.config.get('AUTH_JWT_ISSUER') or ''),
)
return resolve_hxops_user(identity)
except IdentityValidationError as exc:
raise AppError(
code='AUTH.CASDOOR_IDENTITY_INVALID',
message='Casdoor identity is missing issuer or subject',
http_status=401,
) from exc
except HxopsIdentityMappingError as exc:
raise WeComLoginError(error=str(exc), error_code=exc.code, status_code=exc.status) from exc
def _issue_casdoor_api_token(user: User, claims: dict) -> str:
"""
为已通过 Casdoor 认证的用户签发 HXOPS API 会话 JWT。
Args:
user: 已映射成功的 HXOPS 本地用户。
claims: Casdoor ID token 或 userinfo 返回的可信身份声明。
Returns:
HXOPS 本地签名 JWT,其中保留 Casdoor issuer/subject 供跨系统 SSO 使用。
Raises:
AppError: Casdoor 未返回稳定 subject,不能建立可复用身份。
"""
from app.services.auth.casdoor.identity import identity_from_claims
from app.services.auth.common import IdentityValidationError
from app.services.auth.hxops.session_token import issue_hxops_access_token
try:
identity = identity_from_claims(
claims,
expected_issuer=str(current_app.config.get('AUTH_JWT_ISSUER') or claims.get('iss') or ''),
)
except IdentityValidationError as exc:
raise AppError(
code='AUTH.CASDOOR_IDENTITY_INVALID',
message='Casdoor identity is missing issuer or subject',
http_status=401,
) from exc
return issue_hxops_access_token(user, identity)
def _casdoor_exchange_code(code: str, redirect_uri: str):
meta = _get_casdoor_oidc_metadata()
token_endpoint = meta.get('token_endpoint')
if not token_endpoint:
raise RuntimeError('Casdoor token endpoint missing')
payload = {'grant_type': 'authorization_code', 'code': code, 'client_id': current_app.config.get('CASDOOR_CLIENT_ID') or '', 'client_secret': current_app.config.get('CASDOOR_CLIENT_SECRET') or '', 'redirect_uri': redirect_uri or (current_app.config.get('CASDOOR_REDIRECT_URI') or '')}
resp = requests.post(token_endpoint, data=payload, timeout=8)
data = resp.json() or {}
if not resp.ok or not data.get('access_token'):
_raise_casdoor_auth_error(data, context='code')
return data
"""兼容旧测试替换点:委托公共客户端执行 authorization code grant。"""
return get_casdoor_client().authorization_code_login(code, redirect_uri).as_dict()
def _casdoor_refresh_token(refresh_token: str):
meta = _get_casdoor_oidc_metadata()
token_endpoint = meta.get('token_endpoint')
payload = {'grant_type': 'refresh_token', 'refresh_token': refresh_token, 'client_id': current_app.config.get('CASDOOR_CLIENT_ID') or '', 'client_secret': current_app.config.get('CASDOOR_CLIENT_SECRET') or ''}
resp = requests.post(token_endpoint, data=payload, timeout=8)
data = resp.json() or {}
if not resp.ok or not data.get('access_token'):
_raise_casdoor_auth_error(data, context='refresh')
return data
"""兼容旧测试替换点:委托公共客户端执行 refresh grant。"""
return get_casdoor_client().refresh(refresh_token).as_dict()
def _casdoor_userinfo(access_token: str):
meta = _get_casdoor_oidc_metadata()
userinfo_endpoint = meta.get('userinfo_endpoint')
if not userinfo_endpoint:
raise RuntimeError('Casdoor userinfo endpoint missing')
resp = requests.get(userinfo_endpoint, headers={'Authorization': f'Bearer {access_token}'}, timeout=8)
data = resp.json() or {}
if not resp.ok:
raise RuntimeError(f'Casdoor userinfo failed: {data}')
return data
"""兼容旧测试替换点:委托公共客户端读取 userinfo。"""
return get_casdoor_client().userinfo(access_token)
def _casdoor_password_login(username: str, password: str):
"""
Resource-owner password login against Casdoor token endpoint.
Requires the Casdoor application to enable password grant.
"""
meta = _get_casdoor_oidc_metadata()
token_endpoint = meta.get('token_endpoint')
if not token_endpoint:
raise RuntimeError('Casdoor token endpoint missing')
payload = {'grant_type': 'password', 'username': username, 'password': password, 'client_id': current_app.config.get('CASDOOR_CLIENT_ID') or '', 'client_secret': current_app.config.get('CASDOOR_CLIENT_SECRET') or '', 'scope': current_app.config.get('CASDOOR_SCOPE') or 'openid profile email'}
resp = requests.post(token_endpoint, data=payload, timeout=8)
data = resp.json() or {}
if not resp.ok or not data.get('access_token'):
_raise_casdoor_auth_error(data, context='password')
return data
return get_casdoor_client().password_login(username, password).as_dict()
def _hxops_login_service() -> HxopsLoginService:
"""创建使用当前兼容代理的登录服务,使既有 monkeypatch 测试和调用方式保持有效。"""
return HxopsLoginService(
password_login=_casdoor_password_login,
authorization_code_login=_casdoor_exchange_code,
refresh_token=_casdoor_refresh_token,
userinfo=_casdoor_userinfo,
write_login_audit=_write_login_audit,
)
def _is_casdoor_login_mode() -> bool:
return (current_app.config.get('AUTH_LOGIN_MODE') or 'casdoor').lower() == 'casdoor'
@@ -753,24 +760,9 @@ def casdoor_password_login():
if not username or not password:
raise ValidationError('Username and password are required')
try:
token_data = _casdoor_password_login(username, password)
access_token = token_data.get('access_token')
refresh_token = token_data.get('refresh_token')
id_token = token_data.get('id_token')
expires_in = int(token_data.get('expires_in') or 3600)
claims = None
if id_token:
try:
claims = _decode_jwt(id_token)
except Exception:
claims = None
if claims is None:
claims = _casdoor_userinfo(access_token)
user = _resolve_user_from_casdoor_claims(claims)
_write_login_audit('casdoor', 'success', user=user)
result = _hxops_login_service().password(username, password)
db.session.commit()
api_bearer_token = id_token or access_token
return jsonify({'id': user.id, 'username': user.username, 'role': user.role, 'default_agent_id': user.default_agent_id, 'feature_permissions': user.get_feature_permissions(), 'source': 'casdoor', 'access_token': api_bearer_token, 'refresh_token': refresh_token, 'id_token': id_token, 'token_type': token_data.get('token_type') or 'Bearer', 'expires_in': expires_in})
return jsonify(result.login_payload())
except WeComLoginError:
db.session.rollback()
raise
@@ -853,7 +845,7 @@ def casdoor_login():
"role": "<local role>",
"default_agent_id": <int|null>,
"source": "casdoor",
"access_token": "<casdoor access token>",
"access_token": "<HXOPS API session JWT>",
"refresh_token": "<casdoor refresh token>",
"id_token": "<casdoor id token|nullable>",
"token_type": "Bearer",
@@ -881,26 +873,10 @@ def casdoor_login():
current_app.logger.warning('[casdoor_login] invalid_state state=%s', state[:24] if state else '')
raise ValidationError('Invalid or expired Casdoor state')
try:
token_data = _casdoor_exchange_code(code, redirect_uri)
access_token = token_data.get('access_token')
refresh_token = token_data.get('refresh_token')
id_token = token_data.get('id_token')
expires_in = int(token_data.get('expires_in') or 3600)
current_app.logger.info('[casdoor_login] token_exchange_ok redirect_uri=%s access=%s refresh=%s id=%s', redirect_uri, _token_brief(access_token), _token_brief(refresh_token), _token_brief(id_token))
claims = None
if id_token:
try:
claims = _decode_jwt(id_token)
except Exception:
claims = None
if claims is None:
claims = _casdoor_userinfo(access_token)
user = _resolve_user_from_casdoor_claims(claims)
current_app.logger.info('[casdoor_login] user_resolved username=%s id=%s', user.username, user.id)
_write_login_audit('casdoor', 'success', user=user)
result = _hxops_login_service().authorization_code(code, redirect_uri)
current_app.logger.info('[casdoor_login] user_resolved username=%s id=%s', result.user.username, result.user.id)
db.session.commit()
api_bearer_token = id_token or access_token
return jsonify({'id': user.id, 'username': user.username, 'role': user.role, 'default_agent_id': user.default_agent_id, 'feature_permissions': user.get_feature_permissions(), 'source': 'casdoor', 'access_token': api_bearer_token, 'refresh_token': refresh_token, 'id_token': id_token, 'token_type': token_data.get('token_type') or 'Bearer', 'expires_in': expires_in})
return jsonify(result.login_payload())
except WeComLoginError:
db.session.rollback()
current_app.logger.warning('[casdoor_login] business_reject')
@@ -927,7 +903,7 @@ def casdoor_refresh():
Response 200:
{
"access_token": "<new access token>",
"access_token": "<new HXOPS API session JWT>",
"refresh_token": "<possibly rotated refresh token>",
"id_token": "<optional id token>",
"token_type": "Bearer",
@@ -946,14 +922,15 @@ def casdoor_refresh():
raise ValidationError('refresh_token is required')
current_app.logger.info('[casdoor_refresh] start refresh=%s', _token_brief(refresh_token))
try:
token_data = _casdoor_refresh_token(refresh_token)
access_token = token_data.get('access_token')
id_token = token_data.get('id_token')
next_refresh = token_data.get('refresh_token') or refresh_token
expires_in = int(token_data.get('expires_in') or 3600)
current_app.logger.info('[casdoor_refresh] token_refresh_ok access=%s id=%s next_refresh=%s', _token_brief(access_token), _token_brief(id_token), _token_brief(next_refresh))
api_bearer_token = id_token or access_token
return jsonify({'access_token': api_bearer_token, 'refresh_token': next_refresh, 'id_token': id_token, 'token_type': token_data.get('token_type') or 'Bearer', 'expires_in': expires_in})
result = _hxops_login_service().refresh(refresh_token)
current_app.logger.info(
'[casdoor_refresh] token_refresh_ok next_refresh=%s user_id=%s',
_token_brief(result.refresh_token),
result.user.id,
)
return jsonify(result.refresh_payload())
except AppError:
raise
except Exception as e:
message = str(e)
if 'unsupported_grant_type' in message or 'refresh_token is not supported' in message:
+23 -2
View File
@@ -294,8 +294,23 @@ def get_current_user() -> Optional[User]:
return None
def issue_local_access_token(user: User) -> str:
"""签发本地 HS256 JWT(密码登录兼容)。"""
def issue_local_access_token(
user: User,
*,
casdoor_issuer: str | None = None,
casdoor_subject: str | None = None,
) -> str:
"""
签发 HXOPS API 会话 JWT。
Args:
user: 已完成认证并映射到 HXOPS 的本地用户。
casdoor_issuer: Casdoor 身份签发者;仅 Casdoor 登录成功后写入。
casdoor_subject: Casdoor 稳定用户 subject;必须与 issuer 同时提供。
Returns:
由 HXOPS SECRET_KEY 签名、供本站 API 使用的 HS256 JWT。
"""
now = datetime.now(timezone.utc)
exp_hours = int(current_app.config.get('AUTH_LOCAL_JWT_EXPIRES_HOURS') or 12)
payload = {
@@ -310,5 +325,11 @@ def issue_local_access_token(user: User) -> str:
'iss': (current_app.config.get('AUTH_LOCAL_JWT_ISSUER') or 'hxops-backend'),
'aud': (current_app.config.get('AUTH_LOCAL_JWT_AUDIENCE') or 'hxops-frontend'),
}
normalized_issuer = str(casdoor_issuer or '').strip()
normalized_subject = str(casdoor_subject or '').strip()
if normalized_issuer and normalized_subject:
# 标准 iss/sub 仍属于 HXOPS 会话;Casdoor 身份单独保存,避免混淆两个信任域。
payload['casdoor_iss'] = normalized_issuer
payload['casdoor_sub'] = normalized_subject
secret = current_app.config.get('SECRET_KEY')
return jwt.encode(payload, secret, algorithm='HS256')
+12 -1
View File
@@ -76,6 +76,7 @@ def _backend_path(env_key: str, *parts: str) -> str:
class Config:
ENV_NAME = ACTIVE_ENV_NAME
SQLALCHEMY_TRACK_MODIFICATIONS = False
SECRET_KEY = os.getenv('SECRET_KEY')
# 配置最大上传文件大小(200MB)
@@ -327,7 +328,7 @@ class Config:
# Login mode switch: "casdoor" (default) or "password".
# casdoor: login form credentials are sent to Casdoor token endpoint (no redirect page for users).
# password: keep legacy local username/password login.
AUTH_LOGIN_MODE = os.getenv('AUTH_LOGIN_MODE').strip().lower()
AUTH_LOGIN_MODE = (os.getenv('AUTH_LOGIN_MODE') or 'casdoor').strip().lower()
AUTH_ALLOW_LOCAL_JWT = os.getenv('AUTH_ALLOW_LOCAL_JWT', 'true').lower() == 'true'
# JWT 的签发者(iss)校验值,后端用它确认“这个 token 是谁发的”
AUTH_JWT_ISSUER = os.getenv('AUTH_JWT_ISSUER')
@@ -338,6 +339,7 @@ class Config:
CASDOOR_BASE_URL = os.getenv('CASDOOR_BASE_URL')
CASDOOR_CLIENT_ID = os.getenv('CASDOOR_CLIENT_ID')
CASDOOR_CLIENT_SECRET = os.getenv('CASDOOR_CLIENT_SECRET')
CASDOOR_HTTP_TIMEOUT_SECONDS = int(os.getenv('CASDOOR_HTTP_TIMEOUT_SECONDS', '8') or '8')
# Fallback when authorize-url request omits redirect_uri; OAuth flow sends browser origin + /casdoor-callback.
# Casdoor Application must whitelist every origin users hit, e.g. IP and domain on port 8881.
CASDOOR_REDIRECT_URI = os.getenv('CASDOOR_REDIRECT_URI')
@@ -347,6 +349,15 @@ class Config:
# WeCom as Casdoor IdP: provider Name from Casdoor Providers page (used with default_provider=wecom on authorize-url).
CASDOOR_WECOM_PROVIDER_HINT = os.getenv('CASDOOR_WECOM_PROVIDER_HINT').strip()
CASDOOR_WECOM_SILENT_SIGNIN = os.getenv('CASDOOR_WECOM_SILENT_SIGNIN', 'false').lower() == 'true'
# Product SSO: HXOPS signs short-lived, audience-bound RS256 assertions for registered peer services.
SSO_ENABLED = os.getenv('SSO_ENABLED', 'false').lower() == 'true'
SSO_APPS_JSON = os.getenv('SSO_APPS_JSON', '[]')
SSO_ASSERTION_TTL_SECONDS = int(os.getenv('SSO_ASSERTION_TTL_SECONDS', '60') or '60')
SSO_ISSUER = os.getenv('SSO_ISSUER', '').strip()
SSO_SIGNING_ALGORITHM = os.getenv('SSO_SIGNING_ALGORITHM', 'RS256').strip().upper()
SSO_SIGNING_KEY_ID = os.getenv('SSO_SIGNING_KEY_ID', '').strip()
SSO_PRIVATE_KEY_PATH = os.getenv('SSO_PRIVATE_KEY_PATH', '').strip()
SSO_ADDITIONAL_PUBLIC_KEYS_JSON = os.getenv('SSO_ADDITIONAL_PUBLIC_KEYS_JSON', '[]')
AUTH_LOCAL_JWT_ISSUER = os.getenv('AUTH_LOCAL_JWT_ISSUER')
AUTH_LOCAL_JWT_AUDIENCE = os.getenv('AUTH_LOCAL_JWT_AUDIENCE')
AUTH_LOCAL_JWT_EXPIRES_HOURS = int(os.getenv('AUTH_LOCAL_JWT_EXPIRES_HOURS', '12'))
@@ -0,0 +1,20 @@
"""
backend/app/services/auth/casdoor/__init__.py
用途:导出不依赖 HXOPS User 模型的 Casdoor 认证公共能力。
依赖:config、client、identity、errors。
逻辑:HXOPS 与平级服务可复制本目录,并用各自配置适配器创建 CasdoorClient。
"""
from .client import CasdoorClient, CasdoorTokenResult, get_casdoor_client
from .config import CasdoorConfig, casdoor_config_from_flask
from .identity import identity_from_claims
__all__ = [
'CasdoorClient',
'CasdoorConfig',
'CasdoorTokenResult',
'casdoor_config_from_flask',
'get_casdoor_client',
'identity_from_claims',
]
+170
View File
@@ -0,0 +1,170 @@
"""
backend/app/services/auth/casdoor/client.py
用途:封装 Casdoor OAuth/OIDC HTTP 通信,供 HXOPS 与平级服务复制复用。
依赖:requests、CasdoorConfig、Casdoor 错误映射。
逻辑:所有 grant 和 userinfo 请求集中在此;模块不依赖 HXOPS User、数据库或业务权限。
"""
from __future__ import annotations
from dataclasses import dataclass
from datetime import datetime, timedelta, timezone
from threading import Lock
from typing import Any
import requests
from .config import CasdoorConfig, casdoor_config_from_flask
from .errors import raise_auth_error
_CLIENT_CACHE_LOCK = Lock()
_CLIENT_CACHE_CONFIG: CasdoorConfig | None = None
_CLIENT_CACHE_VALUE: CasdoorClient | None = None
@dataclass(frozen=True)
class CasdoorTokenResult:
"""Casdoor token endpoint 返回的标准字段和原始扩展字段。"""
access_token: str
refresh_token: str | None
id_token: str | None
token_type: str
expires_in: int
raw: dict[str, Any]
def as_dict(self) -> dict[str, Any]:
"""返回兼容现有 HXOPS 路由和测试的 token 字典。"""
return dict(self.raw)
class CasdoorClient:
"""无业务模型依赖的 Casdoor OAuth/OIDC 客户端。"""
def __init__(self, config: CasdoorConfig, *, http_session=requests):
"""
创建客户端并注入配置和 HTTP 实现。
Args:
config: 当前服务自己的 Casdoor Application 配置。
http_session: 兼容 requests 的 HTTP 对象,测试可注入替身。
"""
self.config = config
self._http = http_session
self._metadata: dict[str, Any] | None = None
self._metadata_expires_at: datetime | None = None
self._metadata_lock = Lock()
def oidc_metadata(self) -> dict[str, Any]:
"""读取并缓存 OIDC discovery 文档 10 分钟。"""
now = datetime.now(timezone.utc)
if self._metadata and self._metadata_expires_at and self._metadata_expires_at > now:
return dict(self._metadata)
with self._metadata_lock:
now = datetime.now(timezone.utc)
if self._metadata and self._metadata_expires_at and self._metadata_expires_at > now:
return dict(self._metadata)
response = self._http.get(
f'{self.config.base_url}/.well-known/openid-configuration',
timeout=self.config.timeout_seconds,
)
response.raise_for_status()
data = response.json() or {}
if not isinstance(data, dict):
raise RuntimeError('Casdoor OIDC metadata is invalid')
self._metadata = data
self._metadata_expires_at = now + timedelta(minutes=10)
return dict(data)
def _token_endpoint(self) -> str:
"""从 discovery 文档读取 token endpoint,缺失时安全失败。"""
endpoint = str(self.oidc_metadata().get('token_endpoint') or '').strip()
if not endpoint:
raise RuntimeError('Casdoor token endpoint missing')
return endpoint
def _token_request(self, payload: dict[str, Any], *, context: str) -> CasdoorTokenResult:
"""执行 token endpoint 请求并统一解析成功或失败结果。"""
response = self._http.post(
self._token_endpoint(),
data=payload,
timeout=self.config.timeout_seconds,
)
try:
data = response.json() or {}
except ValueError as exc:
raise RuntimeError(f'Casdoor token request failed: HTTP {response.status_code}') from exc
if not response.ok or not data.get('access_token'):
raise_auth_error(data, context=context)
return CasdoorTokenResult(
access_token=str(data['access_token']),
refresh_token=str(data['refresh_token']) if data.get('refresh_token') else None,
id_token=str(data['id_token']) if data.get('id_token') else None,
token_type=str(data.get('token_type') or 'Bearer'),
expires_in=int(data.get('expires_in') or 3600),
raw=dict(data),
)
def password_login(self, username: str, password: str) -> CasdoorTokenResult:
"""使用当前服务自己的 Casdoor Application 执行 password grant。"""
return self._token_request({
'grant_type': 'password',
'username': username,
'password': password,
'client_id': self.config.client_id,
'client_secret': self.config.client_secret,
'scope': self.config.scope,
}, context='password')
def authorization_code_login(self, code: str, redirect_uri: str) -> CasdoorTokenResult:
"""将浏览器返回的 authorization code 兑换为 Casdoor token。"""
return self._token_request({
'grant_type': 'authorization_code',
'code': code,
'client_id': self.config.client_id,
'client_secret': self.config.client_secret,
'redirect_uri': redirect_uri,
}, context='code')
def refresh(self, refresh_token: str) -> CasdoorTokenResult:
"""使用 Casdoor refresh token 获取新 token 集合。"""
return self._token_request({
'grant_type': 'refresh_token',
'refresh_token': refresh_token,
'client_id': self.config.client_id,
'client_secret': self.config.client_secret,
}, context='refresh')
def userinfo(self, access_token: str) -> dict[str, Any]:
"""使用 Casdoor access token 获取可信用户声明。"""
endpoint = str(self.oidc_metadata().get('userinfo_endpoint') or '').strip()
if not endpoint:
raise RuntimeError('Casdoor userinfo endpoint missing')
response = self._http.get(
endpoint,
headers={'Authorization': f'Bearer {access_token}'},
timeout=self.config.timeout_seconds,
)
try:
data = response.json() or {}
except ValueError as exc:
raise RuntimeError(f'Casdoor userinfo failed: HTTP {response.status_code}') from exc
if not response.ok or not isinstance(data, dict):
raise RuntimeError(f'Casdoor userinfo failed: HTTP {response.status_code}')
return data
def get_casdoor_client() -> CasdoorClient:
"""复用当前配置对应的进程内客户端,配置变化时自动替换缓存实例。"""
global _CLIENT_CACHE_CONFIG, _CLIENT_CACHE_VALUE
config = casdoor_config_from_flask()
if _CLIENT_CACHE_VALUE is not None and _CLIENT_CACHE_CONFIG == config:
return _CLIENT_CACHE_VALUE
with _CLIENT_CACHE_LOCK:
if _CLIENT_CACHE_VALUE is None or _CLIENT_CACHE_CONFIG != config:
_CLIENT_CACHE_CONFIG = config
_CLIENT_CACHE_VALUE = CasdoorClient(config)
return _CLIENT_CACHE_VALUE
@@ -0,0 +1,68 @@
"""
backend/app/services/auth/casdoor/config.py
用途:定义纯 Casdoor 客户端配置及 HXOPS Flask 配置适配器。
依赖:dataclasses、flask.current_app、app.core.errors。
逻辑:公共客户端只接收 CasdoorConfig;不同服务只需替换配置适配器。
"""
from __future__ import annotations
from dataclasses import dataclass
from flask import current_app
from app.core.errors import AppError
@dataclass(frozen=True)
class CasdoorConfig:
"""Casdoor OAuth/OIDC 客户端运行参数,secret 不参与 repr。"""
base_url: str
client_id: str
client_secret: str
issuer: str
scope: str = 'openid profile email'
timeout_seconds: int = 8
def __repr__(self) -> str:
"""输出可诊断但不包含 client_secret 的配置摘要。"""
return (
'CasdoorConfig('
f'base_url={self.base_url!r}, client_id={self.client_id!r}, '
f'issuer={self.issuer!r}, scope={self.scope!r}, '
f'timeout_seconds={self.timeout_seconds!r})'
)
def casdoor_config_from_flask() -> CasdoorConfig:
"""
从当前 Flask 应用读取并校验 Casdoor 客户端配置。
Returns:
可交给 CasdoorClient 的不可变配置。
Raises:
AppError: 基础地址、客户端凭据或 issuer 未配置。
"""
base_url = str(current_app.config.get('CASDOOR_BASE_URL') or '').strip().rstrip('/')
client_id = str(current_app.config.get('CASDOOR_CLIENT_ID') or '').strip()
client_secret = str(current_app.config.get('CASDOOR_CLIENT_SECRET') or '')
issuer = str(current_app.config.get('AUTH_JWT_ISSUER') or '').strip().rstrip('/')
scope = str(current_app.config.get('CASDOOR_SCOPE') or 'openid profile email').strip()
timeout_seconds = int(current_app.config.get('CASDOOR_HTTP_TIMEOUT_SECONDS') or 8)
if not base_url or not client_id or not client_secret or not issuer:
raise AppError(
code='CASDOOR_CONFIG_ERROR',
message='Authentication service is not configured. Please contact the administrator.',
http_status=503,
)
return CasdoorConfig(
base_url=base_url,
client_id=client_id,
client_secret=client_secret,
issuer=issuer,
scope=scope or 'openid profile email',
timeout_seconds=max(1, timeout_seconds),
)
+106
View File
@@ -0,0 +1,106 @@
"""
backend/app/services/auth/casdoor/errors.py
用途:把 Casdoor OAuth/OIDC 失败转换为稳定业务错误码。
依赖:标准库解析工具、flask.current_app、app.core.errors。
逻辑:CasdoorClient 将失败响应交给本模块,API 层只处理统一 AppError。
"""
from __future__ import annotations
import ast
import json
import re
from flask import current_app
from app.core.errors import AppError, ValidationError
def clean_str(value) -> str | None:
"""去除字符串首尾空白,空值统一返回 None。"""
if value is None:
return None
return str(value).strip() or None
def extract_error_payload(source) -> dict:
"""从 Casdoor 响应字典或异常文本中提取可识别错误字段。"""
if isinstance(source, dict):
return source
text = str(source or '')
match = re.search(r'\{.*\}', text, re.DOTALL)
if match:
try:
parsed = ast.literal_eval(match.group(0))
if isinstance(parsed, dict):
return parsed
except (SyntaxError, ValueError):
pass
try:
parsed = json.loads(text)
return parsed if isinstance(parsed, dict) else {}
except (json.JSONDecodeError, TypeError):
return {}
def is_password_error(message: str) -> bool:
"""判断 Casdoor 错误是否表示用户名或密码无效。"""
lowered = (message or '').lower()
return 'invalid_grant' in lowered or 'password login failed' in lowered or 'incorrect password' in lowered
def raise_auth_error(source, *, context: str, status_code: int = 401) -> None:
"""
将 Casdoor 登录、授权码和刷新失败映射为稳定错误。
Args:
source: Casdoor JSON 错误体或捕获的异常。
context: ``password``、``code``、``refresh`` 或 ``verify``。
status_code: 未识别错误的默认 HTTP 状态码。
Raises:
AppError: 所有失败均转换为统一认证错误,不返回原始 token 或 secret。
"""
data = extract_error_payload(source)
raw = str(source or '')
oauth_error = (clean_str(data.get('error')) or '').lower()
if not oauth_error and 'invalid_grant' in raw.lower():
oauth_error = 'invalid_grant'
if not oauth_error and 'invalid_client' in raw.lower():
oauth_error = 'invalid_client'
if oauth_error == 'invalid_grant' or is_password_error(raw):
if context in {'password', 'verify'}:
raise AppError(code='CASDOOR_INVALID_CREDENTIALS', message='Incorrect username or password', http_status=401)
raise AppError(code='CASDOOR_CODE_EXPIRED', message='Login session expired, please sign in again', http_status=401)
if oauth_error in {'invalid_client', 'unauthorized_client'}:
raise AppError(
code='CASDOOR_CONFIG_ERROR',
message='Authentication service is misconfigured. Please contact the administrator.',
http_status=503,
details={'casdoor_error': oauth_error},
)
if oauth_error == 'access_denied':
raise AppError(code='CASDOOR_ACCESS_DENIED', message='Login was cancelled or denied', http_status=403)
if oauth_error == 'unsupported_grant_type':
raise AppError(
code='AUTH.CASDOOR_REFRESH_UNSUPPORTED',
message='Casdoor refresh token is not supported by current application config',
http_status=400,
)
lowered_raw = raw.lower()
if 'token endpoint missing' in lowered_raw or 'casdoor_base_url is not configured' in lowered_raw:
raise AppError(
code='CASDOOR_CONFIG_ERROR',
message='Authentication service is not configured. Please contact the administrator.',
http_status=503,
)
if 'invalid or expired casdoor state' in lowered_raw:
raise ValidationError('Invalid or expired Casdoor state')
current_app.logger.warning('[casdoor] unmapped auth error context=%s payload=%s', context, data)
raise AppError(
code='CASDOOR_AUTH_FAILED',
message='Authentication failed, please try again',
http_status=status_code,
details={'casdoor_error': oauth_error or None},
)
@@ -0,0 +1,59 @@
"""
backend/app/services/auth/casdoor/identity.py
用途:将 Casdoor ID token/userinfo claims 转换为统一 AuthIdentity。
依赖:hmac、typing、services.auth.common.identity。
逻辑:严格绑定预期 issuer,提取稳定 subject 与可变用户资料,不访问业务数据库。
"""
from __future__ import annotations
import hmac
from collections.abc import Mapping
from typing import Any
from app.services.auth.common import AuthIdentity, IdentityValidationError, require_stable_identity
def _claim_text(claims: Mapping[str, Any], *keys: str) -> str | None:
"""按优先级读取第一个非空 claim 并转换为去空白字符串。"""
for key in keys:
value = claims.get(key)
if value is not None and str(value).strip():
return str(value).strip()
return None
def identity_from_claims(
claims: Mapping[str, Any],
*,
expected_issuer: str,
) -> AuthIdentity:
"""
将可信 Casdoor claims 转换为跨服务统一身份。
Args:
claims: 已验证 ID token 或通过 HTTPS 从 userinfo 获取的声明。
expected_issuer: 当前服务配置的可信 Casdoor issuer。
Returns:
不包含角色和业务权限的 AuthIdentity。
Raises:
IdentityValidationError: issuer 不匹配或缺少稳定 subject/username。
"""
trusted_issuer = str(expected_issuer or '').strip().rstrip('/')
claim_issuer = str(claims.get('iss') or trusted_issuer).strip().rstrip('/')
if not trusted_issuer or not claim_issuer or not hmac.compare_digest(claim_issuer, trusted_issuer):
raise IdentityValidationError('Casdoor identity issuer does not match the trusted issuer')
identity = AuthIdentity(
issuer=trusted_issuer,
subject=_claim_text(claims, 'sub') or '',
username=_claim_text(claims, 'preferred_username', 'name') or '',
display_name=_claim_text(claims, 'display_name', 'displayName', 'real_name', 'realName', 'name'),
email=_claim_text(claims, 'email'),
phone_number=_claim_text(claims, 'phone_number', 'phone'),
employee_id=_claim_text(claims, 'employee_id', 'employeeId'),
department=_claim_text(claims, 'department', 'affiliation'),
)
return require_stable_identity(identity)
+53 -321
View File
@@ -1,373 +1,105 @@
"""
backend/app/services/auth/casdoor_service.py
用途:Casdoor IdP 用户同步与 OAuth 错误映射(管理端创建/改密、用户域登录共用)。
依赖:flask.current_app、requests、app.core.errors。
逻辑:由 services/admin/user_service、api/user 登录路由调用。
用途:为历史调用点保留 Casdoor 错误与 HXOPS 用户同步兼容门面。
依赖:公共 casdoor.errors、HXOPS casdoor_user_sync。
逻辑:新代码按职责导入分层模块;旧路由、管理端和测试可继续替换本文件函数。
"""
from __future__ import annotations
import ast
import json
import re
from typing import Any
import requests
from flask import current_app
from app.core.errors import AppError, ConflictError, ValidationError
from app.models import User
def clean_str(value) -> str | None:
"""Trim 字符串;空串返回 None。"""
if value is None:
return None
if isinstance(value, str):
value = value.strip()
return value or None
return str(value).strip() or None
from app.services.auth.casdoor.errors import (
clean_str,
extract_error_payload,
is_password_error,
raise_auth_error,
)
from app.services.auth.hxops import casdoor_user_sync as _sync
def is_casdoor_configured() -> bool:
"""Casdoor 基础配置是否齐全。"""
if not clean_str(current_app.config.get('CASDOOR_ORGANIZATION')):
return False
base = (current_app.config.get('CASDOOR_BASE_URL') or '').rstrip('/')
client_id = current_app.config.get('CASDOOR_CLIENT_ID') or ''
client_secret = current_app.config.get('CASDOOR_CLIENT_SECRET') or ''
return bool(base and client_id and client_secret)
"""兼容入口:检查 Casdoor 用户同步配置。"""
return _sync.is_casdoor_configured()
def casdoor_user_owner() -> str:
"""返回 Casdoor organization owner。"""
owner = clean_str(current_app.config.get('CASDOOR_ORGANIZATION'))
if not owner:
raise RuntimeError('CASDOOR_ORGANIZATION is not configured')
return owner
def extract_error_payload(source) -> dict:
"""从 Casdoor 响应或异常文本解析 JSON 错误体。"""
if isinstance(source, dict):
return source
text = str(source or '')
match = re.search(r'\{.*\}', text, re.DOTALL)
if match:
try:
parsed = ast.literal_eval(match.group(0))
if isinstance(parsed, dict):
return parsed
except (SyntaxError, ValueError):
pass
try:
parsed = json.loads(text)
if isinstance(parsed, dict):
return parsed
except (json.JSONDecodeError, TypeError):
pass
return {}
"""兼容入口:返回 Casdoor organization owner。"""
return _sync.casdoor_user_owner()
def is_user_exists_error(message: str) -> bool:
lowered = (message or '').lower()
return 'already exist' in lowered or 'duplicate' in lowered or 'has existed' in lowered
def is_password_error(message: str) -> bool:
lowered = (message or '').lower()
return 'invalid_grant' in lowered or 'password login failed' in lowered or 'incorrect password' in lowered
"""兼容入口:判断 IdP 用户已存在错误。"""
return _sync.is_user_exists_error(message)
def is_user_missing_error(message: str) -> bool:
lowered = (message or '').lower()
return (
"doesn't exist" in lowered
or 'does not exist' in lowered
or 'user not found' in lowered
or 'no such user' in lowered
)
"""兼容入口:判断 IdP 用户不存在错误。"""
return _sync.is_user_missing_error(message)
def raise_user_not_in_idp(source=None) -> None:
data = extract_error_payload(source)
msg_text = clean_str(data.get('msg') or data.get('error_description') or data.get('message'))
raise AppError(
code='CASDOOR_USER_NOT_IN_IDP',
message='Your account has not been registered in the authentication system. Please contact the administrator.',
http_status=409,
details={'technical': msg_text or str(source or '')[:300]},
)
"""兼容入口:抛出 IdP 缺失用户业务错误。"""
_sync.raise_user_not_in_idp(source)
def raise_add_user_error(source) -> None:
"""将 Casdoor add-user 失败映射为稳定业务错误码。"""
data = extract_error_payload(source)
msg_text = clean_str(data.get('msg') or data.get('error_description') or data.get('message'))
lowered = (msg_text or str(source or '')).lower()
if is_user_exists_error(lowered):
raise ConflictError(
'Username already exists in Casdoor',
code='USER.USERNAME_EXISTS',
details={'field': 'username', 'technical': msg_text},
)
if any(token in lowered for token in ('too short', 'too weak', 'password policy', 'at least')):
raise AppError(code='CASDOOR_PASSWORD_POLICY', message='Password does not meet security requirements', http_status=400)
raise AppError(
code='CASDOOR_ADD_USER_FAILED',
message='Failed to create user in authentication system. Please try again or contact the administrator.',
http_status=502,
details={'technical': msg_text or str(source or '')[:300]},
)
"""兼容入口:映射 Casdoor 新增用户错误。"""
_sync.raise_add_user_error(source)
def raise_update_user_error(source) -> None:
"""将 Casdoor update-user 失败映射为稳定业务错误码。"""
data = extract_error_payload(source)
msg_text = clean_str(data.get('msg') or data.get('error_description') or data.get('message'))
lowered = (msg_text or str(source or '')).lower()
if is_user_missing_error(lowered):
raise_user_not_in_idp(source)
if is_user_exists_error(lowered) or ('email' in lowered and 'already' in lowered):
raise ConflictError(
'Email already exists in Casdoor',
code='USER.EMAIL_EXISTS',
details={'field': 'email', 'technical': msg_text},
)
raise AppError(
code='CASDOOR_UPDATE_USER_FAILED',
message='Failed to update user in authentication system. Please try again or contact the administrator.',
http_status=502,
details={'technical': msg_text or str(source or '')[:300]},
)
"""兼容入口:映射 Casdoor 更新用户错误。"""
_sync.raise_update_user_error(source)
def raise_set_password_error(source) -> None:
"""将 Casdoor set-password 失败映射为稳定业务错误码。"""
data = extract_error_payload(source)
msg_text = clean_str(data.get('msg') or data.get('error_description') or data.get('message'))
lowered = (msg_text or str(source or '')).lower()
if is_password_error(lowered) or 'old password' in lowered or 'current password' in lowered:
raise AppError(code='CASDOOR_INVALID_CREDENTIALS', message='Incorrect current password', http_status=401)
if any(token in lowered for token in ('too short', 'too weak', 'password policy', 'at least')):
raise AppError(code='CASDOOR_PASSWORD_POLICY', message='New password does not meet security requirements', http_status=400)
if is_user_missing_error(lowered):
raise_user_not_in_idp(source)
raise AppError(
code='CASDOOR_SET_PASSWORD_FAILED',
message='Failed to change password. Please try again or contact the administrator.',
http_status=502,
details={'technical': msg_text or str(source)[:300]},
)
"""兼容入口:映射 Casdoor 修改密码错误。"""
_sync.raise_set_password_error(source)
def raise_auth_error(source, *, context: str, status_code: int = 401) -> None:
"""Map Casdoor OAuth/API failures to stable business error codes."""
data = extract_error_payload(source)
raw = str(source or '')
oauth_error = clean_str(data.get('error')).lower()
if not oauth_error and 'invalid_grant' in raw.lower():
oauth_error = 'invalid_grant'
if not oauth_error and 'invalid_client' in raw.lower():
oauth_error = 'invalid_client'
if oauth_error == 'invalid_grant' or is_password_error(raw):
if context in ('password', 'verify'):
raise AppError(code='CASDOOR_INVALID_CREDENTIALS', message='Incorrect username or password', http_status=401)
raise AppError(code='CASDOOR_CODE_EXPIRED', message='Login session expired, please sign in again', http_status=401)
if oauth_error in ('invalid_client', 'unauthorized_client'):
raise AppError(
code='CASDOOR_CONFIG_ERROR',
message='Authentication service is misconfigured. Please contact the administrator.',
http_status=503,
details={'casdoor_error': oauth_error},
)
if oauth_error == 'access_denied':
raise AppError(code='CASDOOR_ACCESS_DENIED', message='Login was cancelled or denied', http_status=403)
if 'token endpoint missing' in raw.lower() or 'casdoor_base_url is not configured' in raw.lower() or 'casdoor is not configured' in raw.lower():
raise AppError(
code='CASDOOR_CONFIG_ERROR',
message='Authentication service is not configured. Please contact the administrator.',
http_status=503,
)
if 'invalid or expired casdoor state' in raw.lower():
raise ValidationError('Invalid or expired Casdoor state')
current_app.logger.warning('[casdoor] unmapped auth error context=%s payload=%s raw=%s', context, data, raw[:500])
raise AppError(
code='CASDOOR_AUTH_FAILED',
message='Authentication failed, please try again',
http_status=status_code,
details={'casdoor_error': oauth_error or None, 'technical': raw[:300]},
)
def build_user_profile_payload(**kwargs) -> dict[str, Any]:
"""兼容入口:构造不含密码的 Casdoor 用户资料。"""
return _sync.build_user_profile_payload(**kwargs)
def build_user_profile_payload(
*,
username: str,
email: str,
real_name=None,
phone_number=None,
status='active',
department=None,
) -> dict:
"""组装 Casdoor 用户资料字段(不含 password)。"""
display_name = clean_str(real_name) or username
payload = {
'owner': casdoor_user_owner(),
'name': username,
'email': email or '',
'displayName': display_name,
'realName': clean_str(real_name) or '',
'phone': clean_str(phone_number) or '',
'isForbidden': clean_str(status) not in (None, 'active'),
}
department_value = clean_str(department)
if department_value:
payload['affiliation'] = department_value
return payload
def build_user_payload(**kwargs) -> dict[str, Any]:
"""兼容入口:构造 Casdoor 创建用户请求体。"""
return _sync.build_user_payload(**kwargs)
def build_user_payload(
*,
username: str,
password: str,
email: str,
real_name=None,
phone_number=None,
status='active',
department=None,
) -> dict:
"""组装 Casdoor add-user 请求体。"""
payload = build_user_profile_payload(
username=username,
email=email,
real_name=real_name,
phone_number=phone_number,
status=status,
department=department,
)
payload['password'] = password
return payload
def casdoor_add_user(user_payload: dict[str, Any]) -> None:
"""兼容入口:调用 Casdoor 创建用户。"""
_sync.casdoor_add_user(user_payload)
def casdoor_add_user(user_payload: dict) -> None:
"""调用 Casdoor /api/add-user 创建 IdP 用户。"""
base = (current_app.config.get('CASDOOR_BASE_URL') or '').rstrip('/')
client_id = current_app.config.get('CASDOOR_CLIENT_ID') or ''
client_secret = current_app.config.get('CASDOOR_CLIENT_SECRET') or ''
if not base or not client_id or not client_secret:
raise RuntimeError('Casdoor is not configured')
url = f'{base}/api/add-user'
resp = requests.post(url, json=user_payload, auth=(client_id, client_secret), timeout=8)
try:
data = resp.json() or {}
except ValueError:
raise RuntimeError(f'Casdoor add-user failed: HTTP {resp.status_code} {resp.text[:200]}')
if data.get('status') != 'ok':
raise_add_user_error(data)
def casdoor_update_user(user_payload: dict) -> None:
"""调用 Casdoor /api/update-user 更新 IdP 用户资料。"""
base = (current_app.config.get('CASDOOR_BASE_URL') or '').rstrip('/')
client_id = current_app.config.get('CASDOOR_CLIENT_ID') or ''
client_secret = current_app.config.get('CASDOOR_CLIENT_SECRET') or ''
if not base or not client_id or not client_secret:
raise RuntimeError('Casdoor is not configured')
url = f'{base}/api/update-user'
resp = requests.post(url, json=user_payload, auth=(client_id, client_secret), timeout=8)
try:
data = resp.json() or {}
except ValueError:
raise RuntimeError(f'Casdoor update-user failed: HTTP {resp.status_code} {resp.text[:200]}')
if data.get('status') != 'ok':
raise_update_user_error(data)
def casdoor_update_user(user_payload: dict[str, Any]) -> None:
"""兼容入口:调用 Casdoor 更新用户。"""
_sync.casdoor_update_user(user_payload)
def casdoor_set_password(user_owner: str, user_name: str, old_password: str, new_password: str) -> None:
"""调用 Casdoor /api/set-password。"""
base = (current_app.config.get('CASDOOR_BASE_URL') or '').rstrip('/')
client_id = current_app.config.get('CASDOOR_CLIENT_ID') or ''
client_secret = current_app.config.get('CASDOOR_CLIENT_SECRET') or ''
if not base or not client_id or not client_secret:
raise RuntimeError('Casdoor is not configured')
url = f'{base}/api/set-password'
resp = requests.post(
url,
files={
'userOwner': (None, user_owner),
'userName': (None, user_name),
'oldPassword': (None, old_password),
'newPassword': (None, new_password),
},
auth=(client_id, client_secret),
timeout=8,
)
try:
data = resp.json() or {}
except ValueError:
raise RuntimeError(f'Casdoor set-password failed: HTTP {resp.status_code} {resp.text[:200]}')
if data.get('status') != 'ok':
raise_set_password_error(data)
"""兼容入口:调用 Casdoor 修改密码。"""
_sync.casdoor_set_password(user_owner, user_name, old_password, new_password)
def sync_create_user(
*,
username: str,
password: str,
email: str,
real_name=None,
phone_number=None,
status='active',
department=None,
) -> None:
"""管理端创建用户时同步至 Casdoor。"""
if not is_casdoor_configured():
return
payload = build_user_payload(
username=username,
password=password,
email=email,
real_name=real_name,
phone_number=phone_number,
status=status,
department=department,
)
casdoor_add_user(payload)
def sync_create_user(**kwargs) -> None:
"""兼容入口:同步创建用户,并保留旧模块 monkeypatch 替换点。"""
_sync.sync_create_user(**kwargs, add_user=casdoor_add_user)
def sync_admin_set_password(user: User, new_password: str) -> None:
"""管理端重设密码时同步 Casdoor(无旧密码)。"""
if not is_casdoor_configured():
return
user_owner = casdoor_user_owner()
try:
casdoor_set_password(user_owner, user.username, '', new_password)
except RuntimeError as exc:
if is_user_missing_error(str(exc)):
raise_user_not_in_idp(exc)
raise_set_password_error(exc)
"""兼容入口:同步管理员改密,并保留旧模块 monkeypatch 替换点。"""
_sync.sync_admin_set_password(user, new_password, set_password=casdoor_set_password)
def sync_update_user(user: User, *, new_password: str | None = None) -> None:
"""管理端编辑用户时同步 Casdoor:仅改密;IdP 无账号则 add-user 补建。"""
if not is_casdoor_configured() or not new_password:
return
def _provision_missing_user_in_casdoor():
sync_create_user(
username=user.username,
password=new_password,
email=user.email,
real_name=user.real_name,
phone_number=user.phone_number,
status=user.status,
department=user.department,
)
try:
sync_admin_set_password(user, new_password)
except AppError as exc:
if exc.code == 'CASDOOR_USER_NOT_IN_IDP':
_provision_missing_user_in_casdoor()
return
raise
"""兼容入口:同步用户改密或补建 IdP 账号,并保留测试替换点。"""
_sync.sync_update_user(
user,
new_password=new_password,
set_password=casdoor_set_password,
add_user=casdoor_add_user,
)
@@ -0,0 +1,16 @@
"""
backend/app/services/auth/common/__init__.py
用途:导出不依赖 HXOPS 数据模型的认证公共类型。
依赖:common.identity。
逻辑:Casdoor 客户端、HXOPS 登录和 SSO 模块通过本入口共享统一身份对象。
"""
from .identity import AuthIdentity, IdentityValidationError, identity_key, require_stable_identity
__all__ = [
'AuthIdentity',
'IdentityValidationError',
'identity_key',
'require_stable_identity',
]
@@ -0,0 +1,69 @@
"""
backend/app/services/auth/common/identity.py
用途:定义跨认证来源通用、可复制的稳定身份对象。
依赖:Python dataclasses;不依赖 Flask、SQLAlchemy 或 HXOPS User。
逻辑:Casdoor claims 先转换为 AuthIdentity,业务系统再按 issuer + subject 映射自己的用户。
"""
from __future__ import annotations
from dataclasses import dataclass
class IdentityValidationError(ValueError):
"""身份缺少跨服务稳定键时抛出,调用方负责映射为自身错误契约。"""
@dataclass(frozen=True)
class AuthIdentity:
"""认证系统返回的稳定身份和可变展示资料,不包含任何业务权限。"""
issuer: str
subject: str
username: str
display_name: str | None = None
email: str | None = None
phone_number: str | None = None
employee_id: str | None = None
department: str | None = None
def require_stable_identity(identity: AuthIdentity) -> AuthIdentity:
"""
校验跨服务身份必须具备 issuer、subject 和 username。
Args:
identity: 待校验的认证身份。
Returns:
去除稳定键首尾空白后的不可变身份对象。
Raises:
IdentityValidationError: 缺少稳定身份键或用户名。
"""
issuer = str(identity.issuer or '').strip()
subject = str(identity.subject or '').strip()
username = str(identity.username or '').strip()
if not issuer or not subject:
raise IdentityValidationError('Identity issuer and subject are required')
if not username:
raise IdentityValidationError('Identity username is required')
if issuer == identity.issuer and subject == identity.subject and username == identity.username:
return identity
return AuthIdentity(
issuer=issuer,
subject=subject,
username=username,
display_name=identity.display_name,
email=identity.email,
phone_number=identity.phone_number,
employee_id=identity.employee_id,
department=identity.department,
)
def identity_key(identity: AuthIdentity) -> tuple[str, str]:
"""返回业务系统建立外部身份映射时使用的唯一键 ``(issuer, subject)``。"""
stable = require_stable_identity(identity)
return stable.issuer, stable.subject
@@ -0,0 +1,20 @@
"""
backend/app/services/auth/hxops/__init__.py
用途:导出依赖 HXOPS User、数据库和会话契约的认证编排能力。
依赖:user_resolver、session_token、login_service、casdoor_user_sync。
逻辑:API 路由调用本包;平级服务不复制本目录。
"""
from .login_service import HxopsLoginService, LoginResult
from . import casdoor_user_sync
from .session_token import issue_hxops_access_token
from .user_resolver import resolve_hxops_user
__all__ = [
'HxopsLoginService',
'LoginResult',
'casdoor_user_sync',
'issue_hxops_access_token',
'resolve_hxops_user',
]
@@ -0,0 +1,315 @@
"""
backend/app/services/auth/hxops/casdoor_user_sync.py
用途:集中实现 HXOPS 用户创建和改密到 Casdoor 的管理端同步。
依赖:Flask 配置、requests、HXOPS User 模型、公共 Casdoor 错误解析。
逻辑:管理端事务调用本模块;HTTP 失败映射为稳定 AppError,由上层决定回滚。
"""
from __future__ import annotations
from typing import Any, Callable
import requests
from flask import current_app
from app.core.errors import AppError, ConflictError
from app.models import User
from app.services.auth.casdoor.errors import clean_str, extract_error_payload, is_password_error
AddUserOperation = Callable[[dict[str, Any]], None]
SetPasswordOperation = Callable[[str, str, str, str], None]
def is_casdoor_configured() -> bool:
"""检查用户同步所需的 organization、地址和客户端凭据是否齐全。"""
if not clean_str(current_app.config.get('CASDOOR_ORGANIZATION')):
return False
base = str(current_app.config.get('CASDOOR_BASE_URL') or '').rstrip('/')
client_id = current_app.config.get('CASDOOR_CLIENT_ID') or ''
client_secret = current_app.config.get('CASDOOR_CLIENT_SECRET') or ''
return bool(base and client_id and client_secret)
def casdoor_user_owner() -> str:
"""返回 Casdoor organization owner,缺失时阻止构造无效用户请求。"""
owner = clean_str(current_app.config.get('CASDOOR_ORGANIZATION'))
if not owner:
raise RuntimeError('CASDOOR_ORGANIZATION is not configured')
return owner
def is_user_exists_error(message: str) -> bool:
"""判断 Casdoor 错误文本是否表示用户名或用户记录已存在。"""
lowered = (message or '').lower()
return 'already exist' in lowered or 'duplicate' in lowered or 'has existed' in lowered
def is_user_missing_error(message: str) -> bool:
"""判断 Casdoor 错误文本是否表示 IdP 中不存在目标用户。"""
lowered = (message or '').lower()
return (
"doesn't exist" in lowered
or 'does not exist' in lowered
or 'user not found' in lowered
or 'no such user' in lowered
)
def raise_user_not_in_idp(source=None) -> None:
"""将 IdP 缺失用户转换为稳定业务错误,避免上层解析供应商文本。"""
data = extract_error_payload(source)
msg_text = clean_str(data.get('msg') or data.get('error_description') or data.get('message'))
raise AppError(
code='CASDOOR_USER_NOT_IN_IDP',
message='Your account has not been registered in the authentication system. Please contact the administrator.',
http_status=409,
details={'technical': msg_text or str(source or '')[:300]},
)
def raise_add_user_error(source) -> None:
"""将 Casdoor add-user 失败映射为稳定业务错误码。"""
data = extract_error_payload(source)
msg_text = clean_str(data.get('msg') or data.get('error_description') or data.get('message'))
lowered = (msg_text or str(source or '')).lower()
if is_user_exists_error(lowered):
raise ConflictError(
'Username already exists in Casdoor',
code='USER.USERNAME_EXISTS',
details={'field': 'username', 'technical': msg_text},
)
if any(token in lowered for token in ('too short', 'too weak', 'password policy', 'at least')):
raise AppError(code='CASDOOR_PASSWORD_POLICY', message='Password does not meet security requirements', http_status=400)
raise AppError(
code='CASDOOR_ADD_USER_FAILED',
message='Failed to create user in authentication system. Please try again or contact the administrator.',
http_status=502,
details={'technical': msg_text or str(source or '')[:300]},
)
def raise_update_user_error(source) -> None:
"""将 Casdoor update-user 失败映射为稳定业务错误码。"""
data = extract_error_payload(source)
msg_text = clean_str(data.get('msg') or data.get('error_description') or data.get('message'))
lowered = (msg_text or str(source or '')).lower()
if is_user_missing_error(lowered):
raise_user_not_in_idp(source)
if is_user_exists_error(lowered) or ('email' in lowered and 'already' in lowered):
raise ConflictError(
'Email already exists in Casdoor',
code='USER.EMAIL_EXISTS',
details={'field': 'email', 'technical': msg_text},
)
raise AppError(
code='CASDOOR_UPDATE_USER_FAILED',
message='Failed to update user in authentication system. Please try again or contact the administrator.',
http_status=502,
details={'technical': msg_text or str(source or '')[:300]},
)
def raise_set_password_error(source) -> None:
"""将 Casdoor set-password 失败映射为稳定业务错误码。"""
data = extract_error_payload(source)
msg_text = clean_str(data.get('msg') or data.get('error_description') or data.get('message'))
lowered = (msg_text or str(source or '')).lower()
if is_password_error(lowered) or 'old password' in lowered or 'current password' in lowered:
raise AppError(code='CASDOOR_INVALID_CREDENTIALS', message='Incorrect current password', http_status=401)
if any(token in lowered for token in ('too short', 'too weak', 'password policy', 'at least')):
raise AppError(code='CASDOOR_PASSWORD_POLICY', message='New password does not meet security requirements', http_status=400)
if is_user_missing_error(lowered):
raise_user_not_in_idp(source)
raise AppError(
code='CASDOOR_SET_PASSWORD_FAILED',
message='Failed to change password. Please try again or contact the administrator.',
http_status=502,
details={'technical': msg_text or str(source)[:300]},
)
def build_user_profile_payload(
*,
username: str,
email: str,
real_name=None,
phone_number=None,
status='active',
department=None,
) -> dict[str, Any]:
"""组装 Casdoor 用户资料字段,不包含任何密码。"""
payload: dict[str, Any] = {
'owner': casdoor_user_owner(),
'name': username,
'email': email or '',
'displayName': clean_str(real_name) or username,
'realName': clean_str(real_name) or '',
'phone': clean_str(phone_number) or '',
'isForbidden': clean_str(status) not in (None, 'active'),
}
department_value = clean_str(department)
if department_value:
payload['affiliation'] = department_value
return payload
def build_user_payload(
*,
username: str,
password: str,
email: str,
real_name=None,
phone_number=None,
status='active',
department=None,
) -> dict[str, Any]:
"""组装 Casdoor add-user 请求体,并只在创建场景附加明文密码。"""
payload = build_user_profile_payload(
username=username,
email=email,
real_name=real_name,
phone_number=phone_number,
status=status,
department=department,
)
payload['password'] = password
return payload
def _management_config() -> tuple[str, str, str, int]:
"""读取 Casdoor 管理 API 配置,返回地址、凭据和 HTTP 超时。"""
base = str(current_app.config.get('CASDOOR_BASE_URL') or '').rstrip('/')
client_id = str(current_app.config.get('CASDOOR_CLIENT_ID') or '')
client_secret = str(current_app.config.get('CASDOOR_CLIENT_SECRET') or '')
timeout = max(1, int(current_app.config.get('CASDOOR_HTTP_TIMEOUT_SECONDS') or 8))
if not base or not client_id or not client_secret:
raise RuntimeError('Casdoor is not configured')
return base, client_id, client_secret, timeout
def casdoor_add_user(user_payload: dict[str, Any]) -> None:
"""调用 Casdoor `/api/add-user` 创建 IdP 用户。"""
base, client_id, client_secret, timeout = _management_config()
response = requests.post(
f'{base}/api/add-user',
json=user_payload,
auth=(client_id, client_secret),
timeout=timeout,
)
try:
data = response.json() or {}
except ValueError as exc:
raise RuntimeError(f'Casdoor add-user failed: HTTP {response.status_code} {response.text[:200]}') from exc
if data.get('status') != 'ok':
raise_add_user_error(data)
def casdoor_update_user(user_payload: dict[str, Any]) -> None:
"""调用 Casdoor `/api/update-user` 更新 IdP 用户资料。"""
base, client_id, client_secret, timeout = _management_config()
response = requests.post(
f'{base}/api/update-user',
json=user_payload,
auth=(client_id, client_secret),
timeout=timeout,
)
try:
data = response.json() or {}
except ValueError as exc:
raise RuntimeError(f'Casdoor update-user failed: HTTP {response.status_code} {response.text[:200]}') from exc
if data.get('status') != 'ok':
raise_update_user_error(data)
def casdoor_set_password(user_owner: str, user_name: str, old_password: str, new_password: str) -> None:
"""调用 Casdoor `/api/set-password` 修改或由管理员覆盖用户密码。"""
base, client_id, client_secret, timeout = _management_config()
response = requests.post(
f'{base}/api/set-password',
files={
'userOwner': (None, user_owner),
'userName': (None, user_name),
'oldPassword': (None, old_password),
'newPassword': (None, new_password),
},
auth=(client_id, client_secret),
timeout=timeout,
)
try:
data = response.json() or {}
except ValueError as exc:
raise RuntimeError(f'Casdoor set-password failed: HTTP {response.status_code} {response.text[:200]}') from exc
if data.get('status') != 'ok':
raise_set_password_error(data)
def sync_create_user(
*,
username: str,
password: str,
email: str,
real_name=None,
phone_number=None,
status='active',
department=None,
add_user: AddUserOperation | None = None,
) -> None:
"""管理端创建 HXOPS 用户时同步 Casdoor;未配置 IdP 时保持原有跳过行为。"""
if not is_casdoor_configured():
return
payload = build_user_payload(
username=username,
password=password,
email=email,
real_name=real_name,
phone_number=phone_number,
status=status,
department=department,
)
(add_user or casdoor_add_user)(payload)
def sync_admin_set_password(
user: User,
new_password: str,
*,
set_password: SetPasswordOperation | None = None,
) -> None:
"""管理端无旧密码重设 Casdoor 密码,并将缺失用户转换为稳定错误。"""
if not is_casdoor_configured():
return
try:
(set_password or casdoor_set_password)(casdoor_user_owner(), user.username, '', new_password)
except RuntimeError as exc:
if is_user_missing_error(str(exc)):
raise_user_not_in_idp(exc)
raise_set_password_error(exc)
def sync_update_user(
user: User,
*,
new_password: str | None = None,
set_password: SetPasswordOperation | None = None,
add_user: AddUserOperation | None = None,
) -> None:
"""同步管理端改密;IdP 缺失账号时用新密码补建,资料编辑仍不主动同步。"""
if not is_casdoor_configured() or not new_password:
return
try:
sync_admin_set_password(user, new_password, set_password=set_password)
except AppError as exc:
if exc.code != 'CASDOOR_USER_NOT_IN_IDP':
raise
sync_create_user(
username=user.username,
password=new_password,
email=user.email,
real_name=user.real_name,
phone_number=user.phone_number,
status=user.status,
department=user.department,
add_user=add_user,
)
@@ -0,0 +1,196 @@
"""
backend/app/services/auth/hxops/login_service.py
用途:统一编排 HXOPS 的 Casdoor 密码登录、授权码登录和刷新流程。
依赖:Casdoor token/identity 公共模块、HXOPS 用户映射、HXOPS API Token。
逻辑:Casdoor token -> claims -> AuthIdentity -> HXOPS User -> 本地 API JWT;路由仅负责参数和事务边界。
"""
from __future__ import annotations
from dataclasses import dataclass
from typing import Any, Callable
from flask import current_app
from app.core.auth.jwt import _decode_jwt
from app.core.errors import AppError
from app.models import User
from app.services.auth.casdoor.client import CasdoorTokenResult
from app.services.auth.casdoor.identity import identity_from_claims
from app.services.auth.common import AuthIdentity, IdentityValidationError
from .session_token import issue_hxops_access_token
from .user_resolver import HxopsIdentityMappingError, resolve_hxops_user
TokenOperation = Callable[..., CasdoorTokenResult | dict[str, Any]]
UserinfoOperation = Callable[[str], dict[str, Any]]
AuditOperation = Callable[..., None]
@dataclass(frozen=True)
class LoginResult:
"""HXOPS 登录接口所需的用户、Token 和原响应有效期数据。"""
user: User
identity: AuthIdentity
access_token: str
refresh_token: str | None
id_token: str | None
token_type: str
expires_in: int
def login_payload(self) -> dict[str, Any]:
"""生成与现有 password/code 登录接口完全一致的扁平响应。"""
return {
'id': self.user.id,
'username': self.user.username,
'role': self.user.role,
'default_agent_id': self.user.default_agent_id,
'feature_permissions': self.user.get_feature_permissions(),
'source': 'casdoor',
'access_token': self.access_token,
'refresh_token': self.refresh_token,
'id_token': self.id_token,
'token_type': self.token_type,
'expires_in': self.expires_in,
}
def refresh_payload(self) -> dict[str, Any]:
"""生成与现有 refresh 接口完全一致的 Token 响应。"""
return {
'access_token': self.access_token,
'refresh_token': self.refresh_token,
'id_token': self.id_token,
'token_type': self.token_type,
'expires_in': self.expires_in,
}
def _normalize_token_result(source: CasdoorTokenResult | dict[str, Any]) -> CasdoorTokenResult:
"""兼容重构期间旧字典替身和新的 CasdoorTokenResult。"""
if isinstance(source, CasdoorTokenResult):
return source
data = dict(source or {})
access_token = str(data.get('access_token') or '')
if not access_token:
raise AppError(code='CASDOOR_AUTH_FAILED', message='Authentication failed, please try again', http_status=401)
return CasdoorTokenResult(
access_token=access_token,
refresh_token=str(data['refresh_token']) if data.get('refresh_token') else None,
id_token=str(data['id_token']) if data.get('id_token') else None,
token_type=str(data.get('token_type') or 'Bearer'),
expires_in=int(data.get('expires_in') or 3600),
raw=data,
)
class HxopsLoginService:
"""把公共 Casdoor 能力与 HXOPS 用户、审计和 API JWT 组合起来。"""
def __init__(
self,
*,
password_login: TokenOperation,
authorization_code_login: TokenOperation,
refresh_token: TokenOperation,
userinfo: UserinfoOperation,
write_login_audit: AuditOperation | None = None,
decode_id_token: Callable[[str], dict[str, Any]] = _decode_jwt,
):
"""
注入 Casdoor 操作和可选审计函数,便于路由兼容与单元测试。
Args:
password_login: 执行 password grant 的函数。
authorization_code_login: 执行 code grant 的函数。
refresh_token: 执行 refresh grant 的函数。
userinfo: 读取 Casdoor userinfo 的函数。
write_login_audit: HXOPS 登录审计函数;公共模块不感知请求对象。
decode_id_token: 现有 Casdoor JWKS 验证函数。
"""
self._password_login = password_login
self._authorization_code_login = authorization_code_login
self._refresh_token = refresh_token
self._userinfo = userinfo
self._write_login_audit = write_login_audit
self._decode_id_token = decode_id_token
def _identity_from_token(self, token: CasdoorTokenResult, *, prefer_id_token: bool) -> AuthIdentity:
"""优先验证 ID token,失败或缺失时回退 HTTPS userinfo。"""
claims: dict[str, Any] | None = None
if prefer_id_token and token.id_token:
try:
claims = self._decode_id_token(token.id_token)
except Exception:
claims = None
if claims is None:
claims = self._userinfo(token.access_token)
try:
return identity_from_claims(
claims,
expected_issuer=str(current_app.config.get('AUTH_JWT_ISSUER') or ''),
)
except IdentityValidationError as exc:
current_app.logger.warning(
'[casdoor_login] invalid stable identity reason=%s claim_keys=%s',
str(exc),
sorted(str(key) for key in claims.keys()),
)
raise AppError(
code='AUTH.CASDOOR_IDENTITY_INVALID',
message='Casdoor identity is missing issuer or subject',
http_status=401,
) from exc
def _complete_login(
self,
token_source: CasdoorTokenResult | dict[str, Any],
*,
prefer_id_token: bool,
fallback_refresh_token: str | None = None,
audit_success: bool = False,
) -> LoginResult:
"""完成身份解析、本地用户映射和 HXOPS API Token 签发。"""
token = _normalize_token_result(token_source)
identity = self._identity_from_token(token, prefer_id_token=prefer_id_token)
try:
user = resolve_hxops_user(identity)
except HxopsIdentityMappingError as exc:
raise AppError(code=exc.code, message=str(exc), http_status=exc.status) from exc
if audit_success and self._write_login_audit:
self._write_login_audit('casdoor', 'success', user=user)
return LoginResult(
user=user,
identity=identity,
access_token=issue_hxops_access_token(user, identity),
refresh_token=token.refresh_token or fallback_refresh_token,
id_token=token.id_token,
token_type=token.token_type,
expires_in=token.expires_in,
)
def password(self, username: str, password: str) -> LoginResult:
"""通过 Casdoor password grant 登录 HXOPS。"""
return self._complete_login(
self._password_login(username, password),
prefer_id_token=True,
audit_success=True,
)
def authorization_code(self, code: str, redirect_uri: str) -> LoginResult:
"""通过 Casdoor authorization code 登录 HXOPS。"""
return self._complete_login(
self._authorization_code_login(code, redirect_uri),
prefer_id_token=True,
audit_success=True,
)
def refresh(self, refresh_token: str) -> LoginResult:
"""刷新 Casdoor token 后重新确认身份并签发 HXOPS API JWT。"""
return self._complete_login(
self._refresh_token(refresh_token),
prefer_id_token=False,
fallback_refresh_token=refresh_token,
)
@@ -0,0 +1,31 @@
"""
backend/app/services/auth/hxops/session_token.py
用途:为 HXOPS 本地 API 签发包含 Casdoor 稳定身份引用的会话 JWT。
依赖:User、AuthIdentity、app.core.auth.jwt 现有签发函数。
逻辑:保留现有 HS256 claims 和有效期;只调整调用边界,不改变 Token 契约。
"""
from __future__ import annotations
from app.core.auth.jwt import issue_local_access_token
from app.models import User
from app.services.auth.common import AuthIdentity
def issue_hxops_access_token(user: User, identity: AuthIdentity | None = None) -> str:
"""
签发 HXOPS API 会话 JWT,保持重构前 claims 完全兼容。
Args:
user: 已映射并检查 active 的 HXOPS 用户。
identity: 可选 Casdoor 稳定身份;存在时写入 casdoor_iss/casdoor_sub。
Returns:
由 HXOPS SECRET_KEY 签名的本站 Bearer Token。
"""
return issue_local_access_token(
user,
casdoor_issuer=identity.issuer if identity else None,
casdoor_subject=identity.subject if identity else None,
)
@@ -0,0 +1,57 @@
"""
backend/app/services/auth/hxops/user_resolver.py
用途:将统一 AuthIdentity 映射为 HXOPS 本地 User。
依赖:Flask 日志、SQLAlchemy session、User、AuthIdentity。
逻辑:当前阶段保持原用户名优先、邮箱回退规则,并统一检查本地用户状态。
"""
from __future__ import annotations
from flask import current_app
from app.extensions import db
from app.models import User
from app.services.auth.common import AuthIdentity
class HxopsIdentityMappingError(Exception):
"""HXOPS 本地用户无法映射或状态不允许登录。"""
def __init__(self, message: str, *, code: str, status: int):
super().__init__(message)
self.code = code
self.status = status
def resolve_hxops_user(identity: AuthIdentity) -> User:
"""
按现有规则将认证身份映射到 HXOPS 用户。
Args:
identity: 已验证 Casdoor issuer/subject 的统一身份。
Returns:
状态为 active 的 HXOPS User。
Raises:
HxopsIdentityMappingError: 用户未同步到 HXOPS 或账号已禁用。
"""
current_app.logger.info(
'[casdoor_login] identity username=%s email=%s subject=%s',
identity.username,
identity.email,
identity.subject,
)
user = db.session.query(User).filter_by(username=identity.username).first()
if user is None and identity.email:
user = db.session.query(User).filter_by(email=identity.email).first()
if user is None:
raise HxopsIdentityMappingError(
'No local user matched Casdoor identity. Please contact admin to provision account.',
code='CASDOOR_USER_NOT_FOUND',
status=403,
)
if user.status != 'active':
raise HxopsIdentityMappingError('Account is disabled', code='ACCOUNT_DISABLED', status=403)
return user
+18
View File
@@ -0,0 +1,18 @@
"""
backend/app/services/auth/sso/__init__.py
Purpose: Export the reusable HXOPS-to-peer-service SSO signing surface.
Dependencies: application registry and assertion signing modules.
Flow: API routes import this package; peer services consume the documented assertion/JWKS contract.
"""
from .application_registry import SsoApplication, get_application, list_applications
from .assertion_service import build_jwks, issue_assertion
__all__ = [
'SsoApplication',
'build_jwks',
'get_application',
'issue_assertion',
'list_applications',
]
@@ -0,0 +1,149 @@
"""
backend/app/services/auth/sso/application_registry.py
Purpose: Parse and validate peer services allowed to receive HXOPS SSO assertions.
Dependencies: Flask configuration, JSON, URL parsing, and AppError.
Flow: Assertion routes resolve app metadata here so browser-provided callback URLs are never trusted.
"""
from __future__ import annotations
import json
import re
from dataclasses import dataclass
from urllib.parse import urlparse
from flask import current_app
from app.core.errors import AppError, NotFoundError
_APP_KEY_RE = re.compile(r'^[a-z0-9][a-z0-9_-]{1,63}$')
@dataclass(frozen=True)
class SsoApplication:
"""Registered peer-service metadata safe for server-controlled SSO routing."""
key: str
display_name: str
login_url: str
callback_url: str
audience: str
enabled: bool = True
def public_payload(self) -> dict[str, str]:
"""Return fields safe for authenticated HXOPS navigation components."""
return {
'key': self.key,
'display_name': self.display_name,
'login_url': self.login_url,
}
def _validate_http_url(value: str, *, field: str) -> str:
"""
Validate an application URL from server configuration.
Args:
value: Absolute browser or callback URL.
field: Configuration field name used in diagnostics.
Returns:
Normalized URL without surrounding whitespace.
Raises:
AppError: URL is missing, malformed, or uses HTTP outside development/testing.
"""
normalized = str(value or '').strip()
parsed = urlparse(normalized)
if parsed.scheme not in {'http', 'https'} or not parsed.netloc:
raise AppError(
code='AUTH.SSO_CONFIG_ERROR',
message=f'Invalid SSO application {field}',
http_status=503,
)
env_name = str(current_app.config.get('ENV_NAME') or current_app.config.get('FLASK_ENV') or '').lower()
if parsed.scheme != 'https' and env_name not in {'dev', 'development', 'test', 'testing'}:
raise AppError(
code='AUTH.SSO_CONFIG_ERROR',
message=f'SSO application {field} must use HTTPS',
http_status=503,
)
return normalized
def list_applications() -> list[SsoApplication]:
"""
Parse the enabled SSO application registry from ``SSO_APPS_JSON``.
Returns:
Valid enabled application definitions.
Raises:
AppError: Configuration is invalid. Fail closed to avoid open redirects.
"""
if not bool(current_app.config.get('SSO_ENABLED', False)):
return []
raw = current_app.config.get('SSO_APPS_JSON') or '[]'
try:
items = json.loads(raw) if isinstance(raw, str) else raw
except (TypeError, ValueError) as exc:
raise AppError(
code='AUTH.SSO_CONFIG_ERROR',
message='SSO application registry is invalid',
http_status=503,
) from exc
if not isinstance(items, list):
raise AppError(
code='AUTH.SSO_CONFIG_ERROR',
message='SSO application registry must be a JSON array',
http_status=503,
)
applications: list[SsoApplication] = []
seen_keys: set[str] = set()
seen_audiences: set[str] = set()
for item in items:
if not isinstance(item, dict) or not bool(item.get('enabled', True)):
continue
key = str(item.get('key') or '').strip().lower()
audience = str(item.get('audience') or key).strip()
display_name = str(item.get('display_name') or key).strip()
if (
not _APP_KEY_RE.fullmatch(key)
or not _APP_KEY_RE.fullmatch(audience.lower())
or audience != audience.lower()
or not display_name
):
raise AppError(
code='AUTH.SSO_CONFIG_ERROR',
message='SSO application identity configuration is incomplete',
http_status=503,
)
if key in seen_keys or audience in seen_audiences:
raise AppError(
code='AUTH.SSO_CONFIG_ERROR',
message='SSO application keys and audiences must be unique',
http_status=503,
)
applications.append(SsoApplication(
key=key,
display_name=display_name,
login_url=_validate_http_url(item.get('login_url'), field='login_url'),
callback_url=_validate_http_url(item.get('callback_url'), field='callback_url'),
audience=audience,
enabled=True,
))
seen_keys.add(key)
seen_audiences.add(audience)
return applications
def get_application(app_key: str) -> SsoApplication:
"""Resolve one enabled application by its server-controlled key."""
normalized = str(app_key or '').strip().lower()
for application in list_applications():
if application.key == normalized:
return application
raise NotFoundError('SSO application not found', code='AUTH.SSO_APP_NOT_FOUND')
@@ -0,0 +1,265 @@
"""
backend/app/services/auth/sso/assertion_service.py
Purpose: Sign peer-service-specific short-lived login assertions and publish their verification key.
Dependencies: application registry, PyJWT, cryptography, Flask configuration, and User.
Flow: The SSO API authenticates an HXOPS user, this module signs an audience-bound JWT, and peers verify it through JWKS.
"""
from __future__ import annotations
import base64
import json
import secrets
from datetime import datetime, timedelta, timezone
from pathlib import Path
from typing import Any
from urllib.parse import urlparse
import jwt
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import rsa
from flask import current_app
from app.core.errors import AppError, ValidationError
from app.models import User
from app.services.auth.casdoor.identity import identity_from_claims
from app.services.auth.common import IdentityValidationError
from .application_registry import get_application
def _config_error(message: str) -> AppError:
"""Build a fail-closed SSO configuration error without leaking key material."""
return AppError(code='AUTH.SSO_CONFIG_ERROR', message=message, http_status=503)
def _read_signing_key() -> rsa.RSAPrivateKey:
"""
Load the configured RSA private key used only for product SSO assertions.
Returns:
Parsed RSA private key.
Raises:
AppError: The path is absent, unreadable, invalid, or not an RSA private key.
"""
raw_path = str(current_app.config.get('SSO_PRIVATE_KEY_PATH') or '').strip()
if not raw_path:
raise _config_error('SSO signing private key is not configured')
try:
key_bytes = Path(raw_path).read_bytes()
private_key = serialization.load_pem_private_key(key_bytes, password=None)
except (OSError, ValueError, TypeError) as exc:
raise _config_error('SSO signing private key cannot be loaded') from exc
if not isinstance(private_key, rsa.RSAPrivateKey):
raise _config_error('SSO signing key must be an RSA private key')
return private_key
def _issuer() -> str:
"""Return the configured absolute SSO issuer after environment-aware URL validation."""
issuer = str(current_app.config.get('SSO_ISSUER') or '').strip().rstrip('/')
parsed = urlparse(issuer)
if parsed.scheme not in {'http', 'https'} or not parsed.netloc:
raise _config_error('SSO issuer must be an absolute URL')
env_name = str(current_app.config.get('ENV_NAME') or current_app.config.get('FLASK_ENV') or '').lower()
if parsed.scheme != 'https' and env_name not in {'dev', 'development', 'test', 'testing'}:
raise _config_error('SSO issuer must use HTTPS')
return issuer
def _ttl_seconds() -> int:
"""Validate the short assertion lifetime; values outside 10-60 seconds fail closed."""
try:
ttl_seconds = int(current_app.config.get('SSO_ASSERTION_TTL_SECONDS') or 60)
except (TypeError, ValueError) as exc:
raise _config_error('SSO assertion TTL is invalid') from exc
if ttl_seconds < 10 or ttl_seconds > 60:
raise _config_error('SSO assertion TTL must be between 10 and 60 seconds')
return ttl_seconds
def _algorithm() -> str:
"""Enforce the single supported asymmetric signing algorithm and reject downgrade configuration."""
algorithm = str(current_app.config.get('SSO_SIGNING_ALGORITHM') or 'RS256').strip().upper()
if algorithm != 'RS256':
raise _config_error('SSO signing algorithm must be RS256')
return algorithm
def _key_id() -> str:
"""Return the stable public key identifier embedded in JWT and JWKS metadata."""
key_id = str(current_app.config.get('SSO_SIGNING_KEY_ID') or '').strip()
if not key_id or len(key_id) > 128:
raise _config_error('SSO signing key ID is not configured')
return key_id
def _identity_claims(user: User, claims: dict[str, Any]) -> dict[str, Any]:
"""
Build the portable Casdoor identity claims without HXOPS business permissions.
Args:
user: Active HXOPS user mapped from the authenticated Casdoor identity.
claims: Verified HXOPS API JWT claims containing ``casdoor_iss/casdoor_sub``.
Returns:
Stable identity plus mutable display attributes safe for peer-service user mapping.
"""
expected_issuer = str(current_app.config.get('AUTH_JWT_ISSUER') or '').strip()
try:
identity = identity_from_claims({
'iss': claims.get('casdoor_iss'),
'sub': claims.get('casdoor_sub'),
'preferred_username': user.username,
'name': user.real_name or user.username,
'email': user.email,
'phone_number': user.phone_number,
'employee_id': user.employee_id,
'department': user.department,
}, expected_issuer=expected_issuer)
except IdentityValidationError as exc:
raise AppError(
code='AUTH.SSO_IDENTITY_UNSUPPORTED',
message='Current login is not backed by a Casdoor identity',
http_status=403,
) from exc
return {
'sub': identity.subject,
'identity_issuer': identity.issuer,
'preferred_username': identity.username,
'name': identity.display_name,
'email': identity.email,
'phone_number': identity.phone_number,
'employee_id': identity.employee_id,
'department': identity.department,
}
def issue_assertion(*, app_key: str, user: User, claims: dict[str, Any], state: Any) -> dict[str, Any]:
"""
Sign a peer-service-specific login assertion for an active HXOPS user.
Args:
app_key: Server-registered target service key.
user: Current active HXOPS user.
claims: Verified HXOPS API JWT claims with Casdoor identity references.
state: Opaque signed state created by the peer service and returned unchanged.
Returns:
Registered callback URL, RS256 assertion, original state, and expiry seconds.
"""
if user.status != 'active':
raise AppError(code='AUTH.ACCOUNT_DISABLED', message='Account is disabled', http_status=403)
normalized_state = str(state or '').strip()
if not normalized_state or len(normalized_state) > 4096:
raise ValidationError('state is required and must not exceed 4096 characters')
application = get_application(app_key)
ttl_seconds = _ttl_seconds()
now = datetime.now(timezone.utc)
payload = {
'iss': _issuer(),
'aud': application.audience,
**_identity_claims(user, claims),
'iat': int(now.timestamp()),
'nbf': int((now - timedelta(seconds=5)).timestamp()),
'exp': int((now + timedelta(seconds=ttl_seconds)).timestamp()),
'jti': secrets.token_urlsafe(24),
}
try:
assertion = jwt.encode(
payload,
_read_signing_key(),
algorithm=_algorithm(),
headers={'kid': _key_id(), 'typ': 'JWT'},
)
except AppError:
raise
except Exception as exc:
current_app.logger.exception('[sso] failed to sign assertion app=%s', application.key)
raise AppError(
code='AUTH.SSO_ASSERTION_ISSUE_FAILED',
message='Failed to issue an SSO assertion',
http_status=503,
retryable=True,
) from exc
current_app.logger.info(
'[sso] assertion issued app=%s user_id=%s subject=%s ttl=%s',
application.key,
user.id,
payload['sub'],
ttl_seconds,
)
return {
'post_url': application.callback_url,
'assertion': assertion,
'state': normalized_state,
'expires_in': ttl_seconds,
}
def _base64url_uint(value: int) -> str:
"""Encode an RSA integer using the unpadded base64url form required by JWK."""
raw = value.to_bytes(max(1, (value.bit_length() + 7) // 8), 'big')
return base64.urlsafe_b64encode(raw).rstrip(b'=').decode('ascii')
def _public_jwk(public_key: rsa.RSAPublicKey, *, key_id: str) -> dict[str, str]:
"""Convert one trusted RSA public key to the minimal signing JWK contract."""
numbers = public_key.public_numbers()
return {
'kty': 'RSA',
'kid': key_id,
'use': 'sig',
'alg': _algorithm(),
'n': _base64url_uint(numbers.n),
'e': _base64url_uint(numbers.e),
}
def _additional_public_jwks(active_key_id: str) -> list[dict[str, str]]:
"""
Load verification-only public keys retained during a signing-key rotation window.
Returns:
Additional JWK entries configured as ``[{"kid", "public_key_path"}]``.
Raises:
AppError: JSON, key IDs, paths, or public key material are invalid.
"""
raw = current_app.config.get('SSO_ADDITIONAL_PUBLIC_KEYS_JSON') or '[]'
try:
items = json.loads(raw) if isinstance(raw, str) else raw
except (TypeError, ValueError) as exc:
raise _config_error('Additional SSO public keys configuration is invalid') from exc
if not isinstance(items, list):
raise _config_error('Additional SSO public keys must be a JSON array')
jwks: list[dict[str, str]] = []
seen_key_ids = {active_key_id}
for item in items:
if not isinstance(item, dict):
raise _config_error('Additional SSO public key entry is invalid')
key_id = str(item.get('kid') or '').strip()
path = str(item.get('public_key_path') or '').strip()
if not key_id or len(key_id) > 128 or not path or key_id in seen_key_ids:
raise _config_error('Additional SSO public key identity is invalid or duplicated')
try:
public_key = serialization.load_pem_public_key(Path(path).read_bytes())
except (OSError, ValueError, TypeError) as exc:
raise _config_error('Additional SSO public key cannot be loaded') from exc
if not isinstance(public_key, rsa.RSAPublicKey):
raise _config_error('Additional SSO public key must be RSA')
jwks.append(_public_jwk(public_key, key_id=key_id))
seen_key_ids.add(key_id)
return jwks
def build_jwks() -> dict[str, list[dict[str, str]]]:
"""Build JWKS with the active signing key plus verification-only rotation keys."""
active_key_id = _key_id()
active_jwk = _public_jwk(_read_signing_key().public_key(), key_id=active_key_id)
return {'keys': [active_jwk, *_additional_public_jwks(active_key_id)]}
@@ -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 且本地库成功入库。
+177
View File
@@ -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
+167
View File
@@ -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'
+316
View File
@@ -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