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

+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)]}