266 lines
10 KiB
Python
266 lines
10 KiB
Python
"""
|
|
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)]}
|