Conghao97's picture tcftrees's picture
ProgramGen release
d086025
Raw History Blame Contribute Delete
51.5 kB
diff --git a/src/flask_oauth2_validation/__init__.py b/src/flask_oauth2_validation/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..01b48ce9eb368e39b20b4781ac59b976b4a3a97b --- /dev/null +++ b/src/flask_oauth2_validation/__init__.py @@ -0,0 +1 @@ +from .decorator import OAuth2Decorator diff --git a/src/flask_oauth2_validation/decorator.py b/src/flask_oauth2_validation/decorator.py new file mode 100644 index 0000000000000000000000000000000000000000..e1bcf41383e48a45e4abaf425923673240e55a93 --- /dev/null +++ b/src/flask_oauth2_validation/decorator.py @@ -0,0 +1,493 @@ +import base64 +import json +import logging +import requests +import time +import threading + +from flask import Flask, request +from flask_executor import Executor +from functools import wraps +from jwt import JWT, jwk_from_dict +from jwt.exceptions import JWTDecodeError + +from .exceptions import OAuth2Exception +from .exceptions import OAuth2BadRequestException +from .exceptions import OAuth2InsufficientScopeException +from .exceptions import OAuth2InvalidTokenException + + +class OAuth2Decorator(): + """ This Flask view function decorator provides local and remote + OAuth2 (RFC-6749) validation for self-encoded JWT (RFC-7519) based + Bearer (RFC-6750) access tokens. + + The minimal configuration expects the OAUTH2_ISSUER attribute being set + which points to the issuer:: + + app.config['OAUTH2_ISSUER'] = 'https://<your-issuer>/oauth2' + + This would perform local token validation after downloading the public + keys (RFC-7517) from the authorization server (RFC-7800). + + In case you also need to perform remote token validation (RFC-7662) + an OAUTH2_CLIENT_ID and OAUTH2_CLIENT_SECRET need to be configured:: + + app.config['OAUTH2_CLIENT_ID'] = 'your-client-id' + app.config['OAUTH2_CLIENT_SECRET'] = 'your-client-secret' + + In case your authorization server uses rotating public keys an + OAUTH2_JWKS_UPDATE_INTERVAL (in seconds) could be configured to regularly + download the latest public keys from the authorization server:: + + app.config['OAUTH2_JWKS_UPDATE_INTERVAL'] = 3600 + + For a more strict validation it is recommended to configure an + OAUTH2_AUDIENCE to verify the token against:: + + app.config['OAUTH2_AUDIENCE'] = 'api://default' + + """ + + def __init__(self, app: Flask): + """ Reads the app configuration and requests + the Authorization Server Metadata as well as the + authorization servers public keys. + + In case an auto reload of public keys has been + configured a flask executor is being initialized. + Whenever the last update is older than the configured + refresh interval a next incoming request would trigger + an async pubkey update request to the authorization + server. + + In case remote validation is configured a request + will be sent to lookup the supported introspection + auth methods in addition. + """ + + self._logger = logging.getLogger(__name__) + + app.config.setdefault('OAUTH2_ISSUER', None) + app.config.setdefault('OAUTH2_AUDIENCE', None) + app.config.setdefault('OAUTH2_JWKS_UPDATE_INTERVAL', None) + app.config.setdefault('OAUTH2_CLIENT_ID', None) + app.config.setdefault('OAUTH2_CLIENT_SECRET', None) + + # Holds the current requests token in case + # the verification steps where all successful. + self.token = None + + self._jwt = None + self._issuer = None + self._issuer_public_keys = None + self._audience = None + self._jwks_uri = None + self._jwks_update_interval = None + self._jwks_last_update_timestamp = None + self._jwks_update_mutex = threading.Lock() + self._executor = None + self._client_id = None + self._client_secret = None + self._introspection_endpoint = None + self._introspection_auth_method = None + + # We only want to send out the request to the + # authorization server metadata endpoint once + # that's why we cache its response, here. + self._cached_metadata = None + + # The only mandatory value is the issuer URI. + # In case it is the only value we expect it to offer + # Authorization Server Metadata support (RFC-8414). + if not app.config.get('OAUTH2_ISSUER'): + raise TypeError('An OAUTH2_ISSUER config property is required') + self._issuer = app.config.get('OAUTH2_ISSUER') + + # In case we have a client id we assume that we will use the + # introspect endpoint. + self._client_id = app.config.get('OAUTH2_CLIENT_ID') + if self._client_id: + self._client_secret = app.config.get('OAUTH2_CLIENT_SECRET') + if not self._client_secret: + raise TypeError( + 'OAUTH2_CLIENT_SECRET config property required' + ) + + # We are supposed to validate self encoded tokens + # but don't have a pubkey and don't know the jwks_uri. + # Then we need to retrieve it from the authorization + # metadata endpoint + self._jwks_uri = self._lookup_metadata('jwks_uri') + + # If an audience has been defined the JWT + # token 'aud' attribute will be validated + # against it + self._audience = app.config.get('OAUTH2_AUDIENCE') + + # We're looking up the public keys from the + # authorization server and specifying the + # update interval to refresh the keys + # regularly during runtime (if set) + self._lookup_keys() + self._jwks_last_update_timestamp = time.time() + self._jwt = JWT() + self._jwks_update_interval = app.config.get( + 'OAUTH2_JWKS_UPDATE_INTERVAL' + ) + if self._jwks_update_interval: + self._executor = Executor(app, 'oauth2_jwks_update_task') + + # In case we have a client_id and client_secret being set + # we can use the introspection endpoint. + if self._client_id and self._client_secret: + + # We need to look up the introspection endpoint from + # the authorization server metadata. + self._introspection_endpoint = self._lookup_metadata( + 'introspection_endpoint' + ) + + # Determine the auth method the introspection endpoint + # supports (basic or post are implemented so far): + server_supported_auth_methods = self._lookup_metadata( + 'introspection_endpoint_auth_methods_supported' + ) + if 'client_secret_post' in server_supported_auth_methods: + self._introspection_auth_method = 'client_secret_post' + elif 'client_secret_basic' in server_supported_auth_methods: + self._introspection_auth_method = 'client_secret_basic' + else: + raise TypeError( + 'The introspection auth methods are not supported: ' + + ' '.join(server_supported_auth_methods) + ) + + def _lookup_metadata(self, key: str) -> str: + """ Requests metadata information from an authorization endpoint + according to RFC-8414. + """ + try: + if not self._cached_metadata: + metadata_uri = self._issuer + \ + '/.well-known/oauth-authorization-server' + self._logger.debug( + f'Reading metadata from {metadata_uri}', + ) + response = requests.get(metadata_uri) + if not response.status_code == 200: + raise TypeError( + str(response.status_code) + ) + metadata = response.json() + self._cached_metadata = metadata + else: + metadata = self._cached_metadata + if key in metadata: + return metadata[key] + raise TypeError( + 'No attribute ' + + key + + ' found in authorization server metadata' + ) + except BaseException as http_error: + raise TypeError( + 'Cannot request authorization server metadata: ' + + str(http_error) + ) + + def _lookup_keys(self) -> dict: + """ Downloads the public keys from an authorization server + according to RFC-7517. + """ + try: + self._logger.debug( + f'Downloading public keys from {self._jwks_uri}' + ) + response = requests.get(self._jwks_uri) + if not response.status_code == 200: + raise TypeError( + f'Cannot request public keys from {self._jwks_uri}: ' + + str(response.status_code) + ) + jwks_metadata = response.json() + if 'keys' in jwks_metadata: + keys = jwks_metadata['keys'] + retrieved_keys = {} + for key in keys: + if 'kid' in key: + retrieved_keys[key['kid']] = key + self._issuer_public_keys = retrieved_keys + except BaseException as http_error: + raise TypeError( + 'Cannot request public keys from ' + + self._jwks_uri + + ': ' + + str(http_error) + ) + + def _handle_token(self, fn, *args, **kwargs): + """ OAuth2 decorator logic which is being executed + whenever a decorated view function gets invoked. + """ + introspect = kwargs['introspect'] + scopes = kwargs['scopes'] + # In case the decorated view function raises an exception + # it will be stored, here so that we can pass it down in a + # proper way, later. + decorated_exception = None + try: + # First we trigger a pubkey reload in case the time is up. + if self._executor: + self._executor.submit(self._update_keys) + # Then we extract read the Bearer token from the request. + if not request.headers.get('Authorization', None): + return OAuth2BadRequestException( + 'Authorization header missing' + ).response() + token = self._extract_token(request.headers['Authorization']) + if not token: + return OAuth2BadRequestException( + 'Bearer access token missing' + ).response() + # In case we could successfully read a Bearer token from the + # request we can finally validate it. + if self._is_valid(token, introspect, scopes): + kwargs.pop('scopes', None) + kwargs.pop('introspect', None) + try: + # Only invoke the decorated view funtion in case + # the token is valid. + return fn(*args, **kwargs) + except Exception as decorated_error: + # We will handle this exception later after we + # handled our own OAuth2 validation related + # exceptions + decorated_exception = decorated_error + else: + return OAuth2InvalidTokenException( + 'Invalid token' + ).response() + except OAuth2Exception as oauth2_exception: + return oauth2_exception.response() + except BaseException as error: + self._logger.error(str(error)) + return OAuth2InvalidTokenException( + 'Token validation failed' + ).response() + # Finally handle possible exceptions risen from + # the decorated view function. + if decorated_exception: + raise decorated_exception + + def _extract_token(self, authorization_header: str): + """ Extracts the Bearer access token from the HTTP + request header. + """ + if not authorization_header.startswith('Bearer '): + return None + return authorization_header.split(sep=' ')[1] + + def _is_valid(self, token: str, introspect: bool, scopes: list) -> bool: + """ First performs a local validation (always-on). And afterwards + a remote validation if configured. + """ + if introspect and (not self._client_id or not self._client_secret): + raise OAuth2InvalidTokenException('Invalid configuration') + # First perform a local valiation + valid = self._validate_jwt(token, scopes) + if valid and introspect: + # Then in case introspection is required perform a + # remote validation in addition + valid = valid and self._request_introspection(token) + return valid + + def _request_introspection(self, token: str) -> bool: + """ Sends the token introspection request to the + authorization server. + """ + token_parameters = { + 'token': token, + } + # We only support two introspection auth + # methods: client_secret_post ... + if self._introspection_auth_method == 'client_secret_post': + token_parameters['client_id'] = self._client_id + token_parameters['client_secret'] = self._client_secret + token_headers = { + 'Accept': 'application/json', + 'Content-Type': 'application/x-www-form-urlencoded' + } + # ... and client_secret_basic. + if self._introspection_auth_method == 'client_secret_basic': + token_headers['Authentication'] = 'Basic ' + \ + base64.b64encode(bytes( + self._client_id + ':' + self._client_secret, + encoding='utf-8' + )).decode(encoding='utf-8') + response = requests.post( + url=self._introspection_endpoint, + data=token_parameters, + headers=token_headers + ) + if not response.status_code == 200: + self._logger.error( + f'Unexpected introspection status code: {response.status_code}' + ) + return False + token_information = response.json() + return 'active' in token_information \ + and token_information['active'] + + def _validate_jwt(self, token: str, scopes: list) -> bool: + """ Validates a JWT token by first figuring out a matching + public key which must have been downloaded before (during + :func:`~flask_oauth2_validation.OAuth2Decorator.__init__` or + a configured update interval). + + Second we hand over the token to the :mod:`jwt` module which decodes + it and performs basic validations. + + Last we assert that the tokens audience matches the configured ones + and that all possibly expected scopes are present. + """ + pubkey = None + if self._issuer_public_keys: + key_id = self._lookup_key_id(token) + if not key_id: + raise OAuth2BadRequestException( + "No 'kid' attribute found in token header" + ) + if key_id and key_id in self._issuer_public_keys: + pubkey = jwk_from_dict(self._issuer_public_keys[key_id]) + if not pubkey: + raise OAuth2InvalidTokenException( + 'Invalid token signature' + ) + try: + decoded = self._jwt.decode( + token, + pubkey, + do_time_check=True + ) + if 'iss' not in decoded or not self._issuer == decoded['iss']: + raise OAuth2InvalidTokenException( + 'Invalid token issuer' + ) + if self._audience: + if ('aud' not in decoded + or (type(self._audience) == dict + and decoded['aud'] not in self._audience) + or (type(self._audience) == str + and not self._audience == decoded['aud'])): + raise OAuth2InvalidTokenException( + 'Invalid token audience' + ) + if scopes and 'scp' not in decoded: + raise OAuth2InsufficientScopeException( + ' '.join(sorted(set(scopes))) + ) + if scopes and 'scp' in decoded: + decoded_scopes_set = set(decoded['scp']) + if scopes and not set(scopes).issubset(decoded_scopes_set): + raise OAuth2InsufficientScopeException( + ' '.join( + sorted(set(scopes).difference(decoded_scopes_set)) + ) + ) + self.token = decoded + return decoded + except JWTDecodeError as decode_error: + raise OAuth2InvalidTokenException(str(decode_error)) + + def _lookup_key_id(self, token: str) -> str: + """ Extracts the key id from the token header so that + we can match it against the ids of all known downloaded + public keys, later. + """ + try: + header = token.split('.')[0] + # Correct the padding + header += '=' * (4 - len(header) % 4) + jwt_header = json.loads(base64.b64decode(header).decode('utf-8')) + if jwt_header and 'kid' in jwt_header: + return jwt_header['kid'] + except BaseException: + raise OAuth2BadRequestException('Invalid token format') + + def _update_keys(self): + """ Performs an automated update of our known authorization + server public keys based on the configured update interval. + """ + if (self._jwks_update_interval + and self._jwks_last_update_timestamp): + # We only allow one update at a time to not mess up + # our list of pubkeys. This anyhow runs async to the + # requests so it shouldn't be recognizable by our + # clients. + with self._jwks_update_mutex: + now = time.time() + if int(self._jwks_last_update_timestamp) + \ + self._jwks_update_interval < now: + self._jwks_last_update_timestamp = now + try: + self._lookup_keys() + except TypeError as error: + self._logger.error(error) + + def requires_token(self, introspect=False, scopes=[]): + """ To provide OAuth2 token validation to your endpoints simply add the + :class:`~flask_oauth2_validation.OAuth2Decorator` like:: + + from flask_oauth2_validation import OAuth2Decorator + + oauth2 = OAuth2Decorator(app) + + @oauth2.requires_token() + @app.route('/protected') + def protected(): + pass + + This would perform local token validation, only. To enable remote token + validation you need to provide the introspect=True argument:: + + @oauth2.requires_token(introspect=True) + @app.route('/protected') + def protected(): + pass + + In case you require one or multiple scopes to allow execution, add the + `scopes=[...]` argument:: + + @oauth2.requires_token(scopes=['profile', 'email']) + @app.route('/protected') + def protected(): + pass + + To use the token from within your method you can access it via the + OAuth2Decorator object like:: + + @oauth2.requires_token() + @app.route('/protected') + def protected(): + token: dict = oauth2.token + pass + + :param introspect: feature toggle to turn on remote validation + :param scopes: optional list of mandatory scopes + """ + + def decorator(fn): + @wraps(fn) + def decorated(*args, **kwargs): + return self._handle_token( + fn, + *args, + **dict( + kwargs, + scopes=scopes, + introspect=introspect + ) + ) + return decorated + return decorator diff --git a/src/flask_oauth2_validation/exceptions.py b/src/flask_oauth2_validation/exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..cb1067600c58f980def9ed7624333eee2c749198 --- /dev/null +++ b/src/flask_oauth2_validation/exceptions.py @@ -0,0 +1,98 @@ +from flask import make_response + + +class OAuth2Exception(BaseException): + """ Describes an HTTP error response which will be + returned back to the client in case of any validation + error. + + The method `OAuth2Exception.response()` constructs + the Flask `flask.Response` object. + + Error responses have an empty body. A `WWW-Authenticate` + response header will be set containing an error attribute + specifying the actual type of error. Each individual + `OAuth2Exception` subclass sets its own unique value. + Additional attributes may also be set containing further + error details. + """ + + def __init__(self, status_code: int, error: str, error_message: str): + """ Creates an `OAuth2Exception` object. + The `status_code` attributre defines the HTTP status code. + The `error` attribute defines the unique type of error. + And the `error_message` contains individual error details. + """ + self.status_code = status_code + self.error = error + self.error_message = error_message + + def response(self): + """ Assembles an `flask.Response` object including + a `WWW-Authenticate` header. + """ + + response = make_response() + + # In case it has already been set we need to + # drop the Content-Type header as the response + # body will be empty. + response.headers.pop('Content-Type', None) + + response.status_code = self.status_code + response.headers['WWW-Authenticate'] = ' '.join([ + 'Bearer', + 'error="' + self.error + '"', + self._error_description() + ]) + return response + + def _error_description(self): + """ Creates a key-value pair to be added to the + `WWW-Authenticate` header which contains individual + error details. + """ + return 'error_description="' + self.error_message + '"' + + +class OAuth2BadRequestException(OAuth2Exception): + """ Describes an HTTP 400 (bad request) response: + + `WWW-Authenticate: Bearer error="invalid_request" \ + error_description="<msg>"` + """ + + def __init__(self, error_message: str): + super().__init__(400, 'invalid_request', error_message) + + +class OAuth2InvalidTokenException(OAuth2Exception): + """ Describes an HTTP 401 (unauthorized) response: + + `WWW-Authenticate: Bearer error="invalid_token" \ + error_description="<msg>"` + """ + + def __init__(self, error_message: str): + super().__init__(401, 'invalid_token', error_message) + + +class OAuth2InsufficientScopeException(OAuth2Exception): + """ Describes an HTTP 403 (forbidden) response. It contains + a whitespace separated list of scopes required but not granted: + + `WWW-Authenticate: Bearer error="insufficient_scope" \ + scope="<scope1> <scope2> ... <scopeN>"` + """ + + def __init__(self, missing_scope: str): + """ Creates an `OAuth2InsufficientScopeException` object. + The `status_code` attributre defines the HTTP status code. + The `error` attribute defines the unique type of error. + And the `missing_scope` is a list containing required but + not granted scopes. + """ + super().__init__(403, 'insufficient_scope', missing_scope) + + def _error_description(self): + return 'scope="' + self.error_message + '"' diff --git a/tests/conftest.py b/tests/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..541d78494e019792ed09ebd061ab1af3d2c34747 --- /dev/null +++ b/tests/conftest.py @@ -0,0 +1,209 @@ +from flask import Flask +import pytest +import requests_mock + +from functional import test_jwk + + +@pytest.fixture(scope='function') +def test_app(): + with requests_mock.Mocker() as mock: + _register_mock_addresses(mock) + yield _create_flask_app() + + +def _create_flask_app(): + app = Flask(__name__) + app.config['TESTING'] = True + return app + + +def _register_mock_addresses( + mock: requests_mock.Mocker +): + + mock.get( + 'https://unsupported.issuer.local/oauth2' + + '/.well-known/oauth-authorization-server', + status_code=404 + ) + + mock.get( + 'https://missing_jwks.issuer.local/oauth2' + + '/.well-known/oauth-authorization-server', + json={ + 'introspection_endpoint': + 'https://issuer.local/oauth2/introspect', + 'introspection_endpoint_auth_methods_supported': [ + 'client_secret_basic', + 'client_secret_post' + ] + } + ) + + mock.get( + 'https://missing_introspection.issuer.local/oauth2' + + '/.well-known/oauth-authorization-server', + json={ + 'jwks_uri': + 'https://issuer.local/oauth2/keys', + 'introspection_endpoint_auth_methods_supported': [ + 'client_secret_basic', + 'client_secret_post' + ] + } + ) + + mock.get( + 'https://missing_introspection_auth.issuer.local/oauth2' + + '/.well-known/oauth-authorization-server', + json={ + 'jwks_uri': + 'https://issuer.local/oauth2/keys', + 'introspection_endpoint': + 'https://issuer.local/oauth2/introspect', + } + ) + + mock.get( + 'https://issuer.local/oauth2' + + '/.well-known/oauth-authorization-server', + json={ + 'jwks_uri': + 'https://issuer.local/oauth2/keys', + 'introspection_endpoint': + 'https://issuer.local/oauth2/introspect', + 'introspection_endpoint_auth_methods_supported': [ + 'client_secret_basic', + 'client_secret_post' + ] + } + ) + + mock.get( + 'https://basic_introspection.issuer.local/oauth2' + + '/.well-known/oauth-authorization-server', + json={ + 'jwks_uri': + 'https://issuer.local/oauth2/keys', + 'introspection_endpoint': + 'https://basic_introspection.issuer.local/oauth2/introspect', + 'introspection_endpoint_auth_methods_supported': [ + 'client_secret_basic' + ] + } + ) + + mock.get( + 'https://issuer.local/oauth2/keys', + json={ + 'keys': [ + {'kid': 'x'}, + test_jwk, + {'kid': 'z'} + ] + } + ) + + mock.get( + 'https://key_lookup_error.issuer.local/oauth2' + + '/.well-known/oauth-authorization-server', + json={ + 'jwks_uri': + 'https://key_lookup_error.issuer.local/oauth2/keys', + } + ) + + mock.get( + 'https://key_lookup_error.issuer.local/oauth2/keys', + status_code=500 + ) + + mock.get( + 'https://invalid_introspection.issuer.local/oauth2' + + '/.well-known/oauth-authorization-server', + json={ + 'jwks_uri': + 'https://issuer.local/oauth2/keys', + 'introspection_endpoint': + 'https://invalid_introspection.issuer.local/oauth2/introspect', + 'introspection_endpoint_auth_methods_supported': [ + 'client_secret_basic', + 'client_secret_post' + ] + } + ) + + mock.post( + 'https://invalid_introspection.issuer.local/oauth2/introspect', + json={ + 'active': False + } + ) + + mock.post( + 'https://issuer.local/oauth2/introspect', + json={ + 'active': True + } + ) + + mock.post( + 'https://basic_introspection.issuer.local/oauth2/introspect', + json={ + 'active': True + } + ) + + mock.get( + 'https://introspection_error.issuer.local/oauth2' + + '/.well-known/oauth-authorization-server', + json={ + 'jwks_uri': + 'https://issuer.local/oauth2/keys', + 'introspection_endpoint': + 'https://introspection_error.issuer.local/oauth2/introspect', + 'introspection_endpoint_auth_methods_supported': [ + 'client_secret_basic', + 'client_secret_post' + ] + } + ) + + mock.post( + 'https://introspection_error.issuer.local/oauth2/introspect', + status_code=500 + ) + + mock.get( + 'https://unknown_auth.issuer.local/oauth2' + + '/.well-known/oauth-authorization-server', + json={ + 'jwks_uri': + 'https://issuer.local/oauth2/keys', + 'introspection_endpoint': + 'https://unknown_auth.issuer.local/oauth2/introspect', + 'introspection_endpoint_auth_methods_supported': [ + 'client_secret_unknown' + ] + } + ) + + mock.get( + 'https://unknown_pubkey.issuer.local/oauth2' + + '/.well-known/oauth-authorization-server', + json={ + 'jwks_uri': + 'https://unknown_pubkey.issuer.local/oauth2/keys', + } + ) + + mock.get( + 'https://unknown_pubkey.issuer.local/oauth2/keys', + json={ + 'keys': [ + {'kid': 'x'}, + {'kid': 'z'} + ] + } + ) diff --git a/tests/functional/__init__.py b/tests/functional/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b0679e2224cf0aadc5d8a9b0fc7bff02d48bac0d --- /dev/null +++ b/tests/functional/__init__.py @@ -0,0 +1,45 @@ +from typing import Tuple +from jwt.jwk import RSAJWK +from cryptography.hazmat.primitives.asymmetric import rsa +from jwt import JWT + + +def _generate_test_keys() -> Tuple[rsa.RSAPublicKey, rsa.RSAPrivateKey]: + private_key: rsa.RSAPrivateKey = rsa.generate_private_key( + public_exponent=65537, + key_size=2048 + ) + public_key = private_key.public_key() + return public_key, private_key + + +def _generate_test_jwk(public_key: rsa.RSAPublicKey) -> dict: + jwk = RSAJWK(public_key, kid='a', alg='RS256') + return jwk.to_dict(public_only=True) + + +_public_key, _private_key = _generate_test_keys() +_jwt = JWT() + + +test_jwk = _generate_test_jwk(_public_key) + + +def generate_test_token( + payload: dict, + optional_headers={'kid': 'a'}, + key=RSAJWK(_private_key, kid='a', alg='RS256') +) -> str: + return _jwt.encode( + payload=payload, + key=key, + alg='RS256', + optional_headers=optional_headers + ) + + +mocked_keys = { + 'x': {'kid': 'x'}, + 'a': test_jwk, + 'z': {'kid': 'z'} +} diff --git a/tests/functional/test_config.py b/tests/functional/test_config.py new file mode 100644 index 0000000000000000000000000000000000000000..4fc7270c0556275bbb7ba11aeadb13ec04a06aa0 --- /dev/null +++ b/tests/functional/test_config.py @@ -0,0 +1,127 @@ +from flask_oauth2_validation import OAuth2Decorator +import pytest +from . import mocked_keys + + +def test_missing_config(test_app): + with pytest.raises(TypeError) as err: + OAuth2Decorator(test_app) + assert str(err.value) == 'An OAUTH2_ISSUER config property is required' + + +def test_no_metadata_support(test_app): + with pytest.raises(TypeError) as err: + test_app.config['OAUTH2_ISSUER'] = \ + 'https://unsupported.issuer.local/oauth2' + OAuth2Decorator(test_app) + assert str(err.value) == \ + 'Cannot request authorization server metadata: 404' + + +def test_missing_jwks_metadata(test_app): + with pytest.raises(TypeError) as err: + test_app.config['OAUTH2_ISSUER'] = \ + 'https://missing_jwks.issuer.local/oauth2' + OAuth2Decorator(test_app) + assert str(err.value) == \ + 'Cannot request authorization server metadata: ' + \ + 'No attribute jwks_uri found in authorization ' + \ + 'server metadata' + + +def test_missing_introspection_metadata(test_app): + with pytest.raises(TypeError) as err: + test_app.config['OAUTH2_ISSUER'] = \ + 'https://missing_introspection.issuer.local/oauth2' + test_app.config['OAUTH2_CLIENT_ID'] = 'foo-client' + test_app.config['OAUTH2_CLIENT_SECRET'] = 'very-secure' + OAuth2Decorator(test_app) + assert str(err.value) == \ + 'Cannot request authorization server metadata: ' + \ + 'No attribute introspection_endpoint found in ' + \ + 'authorization server metadata' + + +def test_missing_introspection_auth_metadata(test_app): + with pytest.raises(TypeError) as err: + test_app.config['OAUTH2_ISSUER'] = \ + 'https://missing_introspection_auth.issuer.local/oauth2' + test_app.config['OAUTH2_CLIENT_ID'] = 'foo-client' + test_app.config['OAUTH2_CLIENT_SECRET'] = 'very-secure' + OAuth2Decorator(test_app) + assert str(err.value) == \ + 'Cannot request authorization server metadata: ' + \ + 'No attribute introspection_endpoint_auth_methods_supported ' + \ + 'found in authorization server metadata' + + +def test_local_validation(test_app): + test_app.config['OAUTH2_ISSUER'] = 'https://issuer.local/oauth2' + oauth2 = OAuth2Decorator(test_app) + assert oauth2._issuer == 'https://issuer.local/oauth2' + assert oauth2._jwks_uri == 'https://issuer.local/oauth2/keys' + assert oauth2._issuer_public_keys == mocked_keys + assert not oauth2._introspection_endpoint + assert not oauth2._introspection_auth_method + assert not oauth2._client_id + assert not oauth2._client_secret + assert not oauth2._jwks_update_interval + assert not oauth2._executor + + +def test_local_validation_with_pubkey_reload(test_app): + test_app.config['OAUTH2_ISSUER'] = 'https://issuer.local/oauth2' + test_app.config['OAUTH2_JWKS_UPDATE_INTERVAL'] = 1234 + oauth2 = OAuth2Decorator(test_app) + assert oauth2._issuer == 'https://issuer.local/oauth2' + assert oauth2._jwks_uri == 'https://issuer.local/oauth2/keys' + assert oauth2._issuer_public_keys == mocked_keys + assert oauth2._jwks_update_interval == 1234 + assert oauth2._executor + assert not oauth2._introspection_endpoint + assert not oauth2._introspection_auth_method + assert not oauth2._client_id + assert not oauth2._client_secret + + +def test_remote_validation(test_app): + test_app.config['OAUTH2_ISSUER'] = 'https://issuer.local/oauth2' + test_app.config['OAUTH2_CLIENT_ID'] = 'foo-client' + test_app.config['OAUTH2_CLIENT_SECRET'] = 'very-secure' + oauth2 = OAuth2Decorator(test_app) + assert oauth2._issuer == 'https://issuer.local/oauth2' + assert oauth2._jwks_uri == 'https://issuer.local/oauth2/keys' + assert oauth2._issuer_public_keys == mocked_keys + assert oauth2._client_id == 'foo-client' + assert oauth2._client_secret == 'very-secure' + assert oauth2._introspection_endpoint == \ + 'https://issuer.local/oauth2/introspect' + assert oauth2._introspection_auth_method == 'client_secret_post' + assert not oauth2._jwks_update_interval + assert not oauth2._executor + + +def test_remote_validation_with_pubkey_reload(test_app): + test_app.config['OAUTH2_ISSUER'] = 'https://issuer.local/oauth2' + test_app.config['OAUTH2_CLIENT_ID'] = 'foo-client' + test_app.config['OAUTH2_CLIENT_SECRET'] = 'very-secure' + test_app.config['OAUTH2_JWKS_UPDATE_INTERVAL'] = 1234 + oauth2 = OAuth2Decorator(test_app) + assert oauth2._issuer == 'https://issuer.local/oauth2' + assert oauth2._jwks_uri == 'https://issuer.local/oauth2/keys' + assert oauth2._issuer_public_keys == mocked_keys + assert oauth2._client_id == 'foo-client' + assert oauth2._client_secret == 'very-secure' + assert oauth2._introspection_endpoint == \ + 'https://issuer.local/oauth2/introspect' + assert oauth2._introspection_auth_method == 'client_secret_post' + assert oauth2._jwks_update_interval == 1234 + assert oauth2._executor + + +def test_introspection_setup_without_secret(test_app): + test_app.config['OAUTH2_ISSUER'] = 'https://issuer.local/oauth2' + test_app.config['OAUTH2_CLIENT_ID'] = 'foo-client' + with pytest.raises(TypeError) as err: + OAuth2Decorator(test_app) + assert str(err.value) == 'OAUTH2_CLIENT_SECRET config property required' diff --git a/tests/functional/test_validation.py b/tests/functional/test_validation.py new file mode 100644 index 0000000000000000000000000000000000000000..39f82173b7b8691f8014c5ec44a2d7336c680f06 --- /dev/null +++ b/tests/functional/test_validation.py @@ -0,0 +1,510 @@ +import pytest +from flask import Flask, jsonify +from flask_oauth2_validation import OAuth2Decorator +from time import sleep +from jwt.jwk import RSAJWK + +from . import generate_test_token, _generate_test_keys + + +def _expect_requires_token( + app: Flask, + introspect=False, + scopes=[], + issuer='https://issuer.local/oauth2' +): + + app.config['OAUTH2_ISSUER'] = issuer + + oauth2 = OAuth2Decorator(app) + + @app.errorhandler(Exception) + def internal_server_error(e): + return jsonify({'error': str(e)}), 500 + + @app.route('/') + @oauth2.requires_token( + introspect=introspect, + scopes=scopes + ) + def test_me(): + return jsonify({ + 'token': oauth2.token + }), 200 + + @app.route('/raise') + @oauth2.requires_token( + introspect=introspect, + scopes=scopes + ) + def raise_me(): + raise Exception('Exception from decorated method') + + @app.route('/fail') + @oauth2.requires_token( + introspect=introspect, + scopes=scopes + ) + def fail_validation(): + raise BaseException('Raised base exception') + + return app.test_client() + + +def _expect_valid_token(response): + assert 200 == response.status_code + + +def _expect_internal_server_error(response, msg): + assert 500 == response.status_code + assert response.get_json()['error'] == 'Exception from decorated method' + + +def _expect_insufficient_scope(response, scopes): + + assert 403 == response.status_code + + assert response.headers['WWW-Authenticate'] + assert 'Bearer ' + \ + 'error="insufficient_scope" ' + \ + 'scope="'+scopes+'"' \ + == response.headers['WWW-Authenticate'] + + +def _expect_invalid_token(response, msg): + + assert 401 == response.status_code + + assert response.headers['WWW-Authenticate'] + assert 'Bearer ' + \ + 'error="invalid_token" ' + \ + 'error_description="'+msg+'"' \ + == response.headers['WWW-Authenticate'] + + +def _expect_invalid_request(response, msg): + + assert 400 == response.status_code + + assert response.headers['WWW-Authenticate'] + assert 'Bearer ' + \ + 'error="invalid_request" ' + \ + 'error_description="'+msg+'"' \ + == response.headers['WWW-Authenticate'] + + +def test_request_without_headers(test_app): + test_client = _expect_requires_token(test_app) + + response = test_client.get('/') + + _expect_invalid_request(response, 'Authorization header missing') + + +def test_request_with_empty_authorization_header(test_app): + + test_client = _expect_requires_token(test_app) + + response = test_client.get('/', headers={ + 'Authorization': '' + }) + + _expect_invalid_request(response, 'Authorization header missing') + + +def test_request_missing_token(test_app): + + test_client = _expect_requires_token(test_app) + + response = test_client.get('/', headers={ + 'Authorization': 'Bearer' + }) + + _expect_invalid_request(response, 'Bearer access token missing') + + +def test_request_wrong_auth(test_app): + + test_client = _expect_requires_token(test_app) + + response = test_client.get('/', headers={ + 'Authorization': 'Basic asdfasdfasdf' + }) + + _expect_invalid_request(response, 'Bearer access token missing') + + +def test_request_wrong_syntax(test_app): + + test_client = _expect_requires_token(test_app) + + response = test_client.get('/', headers={ + 'Authorization': 'Bearer fooooobaaaar' + }) + + _expect_invalid_request(response, 'Invalid token format') + + +def test_valid_token(test_app): + + test_client = _expect_requires_token(test_app) + + response = test_client.get('/', headers={ + 'Authorization': 'Bearer ' + generate_test_token({ + 'iss': 'https://issuer.local/oauth2', + }) + }) + + _expect_valid_token(response) + + +def test_invalid_token_pubkey_lookup_error(test_app): + + with pytest.raises(TypeError) as error: + + _expect_requires_token( + test_app, + issuer='https://key_lookup_error.issuer.local/oauth2' + ) + + assert str(error.value) == \ + 'Cannot request public keys from ' + \ + 'https: // key_lookup_error.issuer.local/oauth2/keys' + + +def test_invalid_token_header_kid_missing(test_app): + + test_client = _expect_requires_token(test_app) + + response = test_client.get('/', headers={ + 'Authorization': 'Bearer ' + generate_test_token( + { + 'iss': 'https://issuer.local/oauth2' + }, + optional_headers={} + ) + }) + + _expect_invalid_request( + response, "No 'kid' attribute found in token header" + ) + + +def test_invalid_token_corrupt_Header(test_app): + + test_client = _expect_requires_token(test_app) + + response = test_client.get('/', headers={ + 'Authorization': 'Bearer ' + + 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ.' + + 'eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI' + + '6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.' + + 'SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c' + + }) + + _expect_invalid_request( + response, 'Invalid token format' + ) + + +def test_invalid_audience(test_app: Flask): + + test_app.config['OAUTH2_AUDIENCE'] = 'api://default' + + test_client = _expect_requires_token(test_app) + + response = test_client.get('/', headers={ + 'Authorization': 'Bearer ' + generate_test_token({ + 'iss': 'https://issuer.local/oauth2', + 'aud': 'non-matching-audience', + }) + }) + + _expect_invalid_token(response, 'Invalid token audience') + + +def test_valid_audience(test_app: Flask): + + test_app.config['OAUTH2_AUDIENCE'] = 'api://default' + + test_client = _expect_requires_token(test_app) + + response = test_client.get('/', headers={ + 'Authorization': 'Bearer ' + generate_test_token({ + 'iss': 'https://issuer.local/oauth2', + 'aud': 'api://default', + }) + }) + + _expect_valid_token(response) + + +def test_invalid_issuer(test_app: Flask): + + test_client = _expect_requires_token(test_app) + + response = test_client.get('/', headers={ + 'Authorization': 'Bearer ' + generate_test_token({ + 'iss': 'other-issuer', + }) + }) + + _expect_invalid_token(response, 'Invalid token issuer') + + +def test_valid_token_with_scopes(test_app): + + test_client = _expect_requires_token(test_app, scopes=['foo', 'bar']) + + response = test_client.get('/', headers={ + 'Authorization': 'Bearer ' + generate_test_token({ + 'iss': 'https://issuer.local/oauth2', + 'scp': ['foo', 'bar'] + }) + }) + + _expect_valid_token(response) + + +def test_valid_token_missing_scope(test_app): + + test_client = _expect_requires_token(test_app, scopes=['foo', 'bar']) + + response = test_client.get('/', headers={ + 'Authorization': 'Bearer ' + generate_test_token({ + 'iss': 'https://issuer.local/oauth2', + 'scp': ['foo'] + }) + }) + + _expect_insufficient_scope(response, 'bar') + + +def test_valid_token_no_scopes(test_app): + + test_client = _expect_requires_token(test_app, scopes=['foo', 'bar']) + + response = test_client.get('/', headers={ + 'Authorization': 'Bearer ' + generate_test_token({ + 'iss': 'https://issuer.local/oauth2', + }) + }) + + _expect_insufficient_scope(response, 'bar foo') + + +def test_valid_token_introspected_post(test_app): + + test_app.config['OAUTH2_CLIENT_ID'] = 'foo' + test_app.config['OAUTH2_CLIENT_SECRET'] = 'bar' + + test_client = _expect_requires_token( + test_app, + introspect=True + ) + + response = test_client.get('/', headers={ + 'Authorization': 'Bearer ' + generate_test_token({ + 'iss': 'https://issuer.local/oauth2', + }) + }) + + _expect_valid_token(response) + + +def test_valid_token_introspected_basic(test_app): + + test_app.config['OAUTH2_CLIENT_ID'] = 'foo' + test_app.config['OAUTH2_CLIENT_SECRET'] = 'bar' + + test_client = _expect_requires_token( + test_app, + introspect=True, + issuer='https://basic_introspection.issuer.local/oauth2' + ) + + response = test_client.get('/', headers={ + 'Authorization': 'Bearer ' + generate_test_token({ + 'iss': 'https://basic_introspection.issuer.local/oauth2', + }) + }) + + _expect_valid_token(response) + + +def test_valid_token_introspected_unknown_auth(test_app): + + test_app.config['OAUTH2_CLIENT_ID'] = 'foo' + test_app.config['OAUTH2_CLIENT_SECRET'] = 'bar' + + with pytest.raises(TypeError) as error: + + _expect_requires_token( + test_app, + introspect=True, + issuer='https://unknown_auth.issuer.local/oauth2' + ) + + assert str(error.value) == \ + 'The introspection auth methods are not supported: ' + \ + 'client_secret_unknown' + + +def test_invalid_token_introspection_error(test_app): + + test_app.config['OAUTH2_CLIENT_ID'] = 'foo' + test_app.config['OAUTH2_CLIENT_SECRET'] = 'bar' + + test_client = _expect_requires_token( + test_app, + introspect=True, + issuer='https://introspection_error.issuer.local/oauth2' + ) + + response = test_client.get('/', headers={ + 'Authorization': 'Bearer ' + generate_test_token({ + 'iss': 'https://introspection_error.issuer.local/oauth2', + }) + }) + + _expect_invalid_token(response, 'Invalid token') + + +def test_invalid_token_introspected(test_app): + + test_app.config['OAUTH2_CLIENT_ID'] = 'foo' + test_app.config['OAUTH2_CLIENT_SECRET'] = 'bar' + + test_client = _expect_requires_token( + test_app, + introspect=True, + issuer='https://invalid_introspection.issuer.local/oauth2' + ) + + response = test_client.get('/', headers={ + 'Authorization': 'Bearer ' + generate_test_token({ + 'iss': 'https://invalid_introspection.issuer.local/oauth2', + }) + }) + + _expect_invalid_token(response, 'Invalid token') + + +def test_introspect_config_missing(test_app): + + test_client = _expect_requires_token( + test_app, + introspect=True + ) + + response = test_client.get('/', headers={ + 'Authorization': 'Bearer ' + generate_test_token({ + 'iss': 'https://issuer.local/oauth2', + }) + }) + + _expect_invalid_token(response, 'Invalid configuration') + + +def test_expired_token(test_app): + + test_client = _expect_requires_token(test_app) + + response = test_client.get('/', headers={ + 'Authorization': 'Bearer ' + generate_test_token({ + 'iss': 'https://issuer.local/oauth2', + 'iat': 1, + 'exp': 2 + }) + }) + + _expect_invalid_token(response, 'JWT Expired') + + +def test_invalid_token_unknown_pubkey(test_app): + + test_client = _expect_requires_token( + test_app, + issuer='https://unknown_pubkey.issuer.local/oauth2' + ) + + response = test_client.get('/', headers={ + 'Authorization': 'Bearer ' + generate_test_token({ + 'iss': 'https://unknown_pubkey.issuer.local/oauth2' + }) + }) + + _expect_invalid_token(response, 'Invalid token signature') + + +def test_decorated_method_raises_exception(test_app): + + test_client = _expect_requires_token(test_app) + + response = test_client.get('/raise', headers={ + 'Authorization': 'Bearer ' + generate_test_token({ + 'iss': 'https://issuer.local/oauth2' + }) + }) + + _expect_internal_server_error(response, 'Exception from decorated method') + + +def test_decorated_method_raises_base_exception(test_app): + + test_client = _expect_requires_token(test_app) + + response = test_client.get('/fail', headers={ + 'Authorization': 'Bearer ' + generate_test_token({ + 'iss': 'https://issuer.local/oauth2' + }) + }) + + _expect_invalid_token(response, 'Token validation failed') + + +def test_valid_token_with_pubkey_refresh(test_app): + + test_app.config['OAUTH2_JWKS_UPDATE_INTERVAL'] = 1 + + test_client = _expect_requires_token(test_app) + + first_response = test_client.get('/', headers={ + 'Authorization': 'Bearer ' + generate_test_token({ + 'iss': 'https://issuer.local/oauth2', + }) + }) + + _expect_valid_token(first_response) + + sleep(1.1) + + second_response_caused_pubkey_reload = test_client.get('/', headers={ + 'Authorization': 'Bearer ' + generate_test_token({ + 'iss': 'https://issuer.local/oauth2', + }) + }) + + _expect_valid_token(second_response_caused_pubkey_reload) + + # Wait for the async key update to finish + sleep(0.1) + + +def test_invalid_token_wrong_pubkey(test_app): + + _, priv = _generate_test_keys() + + test_client = _expect_requires_token(test_app) + + response = test_client.get('/', headers={ + 'Authorization': 'Bearer ' + generate_test_token( + { + 'iss': 'https://issuer.local/oauth2', + }, + key=RSAJWK(priv, kid='a', alg='RS256') + ) + }) + + _expect_invalid_token(response, 'failed to decode JWT')
diff --git a/src/flask_oauth2_validation/__init__.py b/src/flask_oauth2_validation/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..01b48ce9eb368e39b20b4781ac59b976b4a3a97b
--- /dev/null
+++ b/src/flask_oauth2_validation/__init__.py
@@ -0,0 +1 @@
+from .decorator import OAuth2Decorator
diff --git a/src/flask_oauth2_validation/decorator.py b/src/flask_oauth2_validation/decorator.py
new file mode 100644
index 0000000000000000000000000000000000000000..e1bcf41383e48a45e4abaf425923673240e55a93
--- /dev/null
+++ b/src/flask_oauth2_validation/decorator.py
@@ -0,0 +1,493 @@
+import base64
+import json
+import logging
+import requests
+import time
+import threading
+
+from flask import Flask, request
+from flask_executor import Executor
+from functools import wraps
+from jwt import JWT, jwk_from_dict
+from jwt.exceptions import JWTDecodeError
+
+from .exceptions import OAuth2Exception
+from .exceptions import OAuth2BadRequestException
+from .exceptions import OAuth2InsufficientScopeException
+from .exceptions import OAuth2InvalidTokenException
+
+
+class OAuth2Decorator():
+ """ This Flask view function decorator provides local and remote
+ OAuth2 (RFC-6749) validation for self-encoded JWT (RFC-7519) based
+ Bearer (RFC-6750) access tokens.
+
+ The minimal configuration expects the OAUTH2_ISSUER attribute being set
+ which points to the issuer::
+
+ app.config['OAUTH2_ISSUER'] = 'https://<your-issuer>/oauth2'
+
+ This would perform local token validation after downloading the public
+ keys (RFC-7517) from the authorization server (RFC-7800).
+
+ In case you also need to perform remote token validation (RFC-7662)
+ an OAUTH2_CLIENT_ID and OAUTH2_CLIENT_SECRET need to be configured::
+
+ app.config['OAUTH2_CLIENT_ID'] = 'your-client-id'
+ app.config['OAUTH2_CLIENT_SECRET'] = 'your-client-secret'
+
+ In case your authorization server uses rotating public keys an
+ OAUTH2_JWKS_UPDATE_INTERVAL (in seconds) could be configured to regularly
+ download the latest public keys from the authorization server::
+
+ app.config['OAUTH2_JWKS_UPDATE_INTERVAL'] = 3600
+
+ For a more strict validation it is recommended to configure an
+ OAUTH2_AUDIENCE to verify the token against::
+
+ app.config['OAUTH2_AUDIENCE'] = 'api://default'
+
+ """
+
+ def __init__(self, app: Flask):
+ """ Reads the app configuration and requests
+ the Authorization Server Metadata as well as the
+ authorization servers public keys.
+
+ In case an auto reload of public keys has been
+ configured a flask executor is being initialized.
+ Whenever the last update is older than the configured
+ refresh interval a next incoming request would trigger
+ an async pubkey update request to the authorization
+ server.
+
+ In case remote validation is configured a request
+ will be sent to lookup the supported introspection
+ auth methods in addition.
+ """
+
+ self._logger = logging.getLogger(__name__)
+
+ app.config.setdefault('OAUTH2_ISSUER', None)
+ app.config.setdefault('OAUTH2_AUDIENCE', None)
+ app.config.setdefault('OAUTH2_JWKS_UPDATE_INTERVAL', None)
+ app.config.setdefault('OAUTH2_CLIENT_ID', None)
+ app.config.setdefault('OAUTH2_CLIENT_SECRET', None)
+
+ # Holds the current requests token in case
+ # the verification steps where all successful.
+ self.token = None
+
+ self._jwt = None
+ self._issuer = None
+ self._issuer_public_keys = None
+ self._audience = None
+ self._jwks_uri = None
+ self._jwks_update_interval = None
+ self._jwks_last_update_timestamp = None