67 lines
2.5 KiB
Python
67 lines
2.5 KiB
Python
"""
|
|
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
|