diff --git a/PKG-INFO b/PKG-INFO index 0129894..a75572b 100644 --- a/PKG-INFO +++ b/PKG-INFO @@ -1,30 +1,30 @@ Metadata-Version: 2.1 Name: swh.auth -Version: 0.5.0 +Version: 0.5.1 Summary: Software Heritage Authentication Utilities Home-page: https://forge.softwareheritage.org/source/swh-auth/ Author: Software Heritage developers Author-email: swh-devel@inria.fr License: UNKNOWN Project-URL: Bug Reports, https://forge.softwareheritage.org/maniphest Project-URL: Funding, https://www.softwareheritage.org/donate Project-URL: Source, https://forge.softwareheritage.org/source/swh- Project-URL: Documentation, https://docs.softwareheritage.org/devel/swh-/ Description: .. _swh-auth: Software Heritage - Authentication ================================== Authentication library for SWH (keycloak common utilities) Platform: UNKNOWN Classifier: Programming Language :: Python :: 3 Classifier: Intended Audience :: Developers Classifier: License :: OSI Approved :: GNU General Public License v3 (GPLv3) Classifier: Operating System :: OS Independent Classifier: Development Status :: 3 - Alpha Requires-Python: >=3.7 Description-Content-Type: text/markdown Provides-Extra: django Provides-Extra: testing diff --git a/swh.auth.egg-info/PKG-INFO b/swh.auth.egg-info/PKG-INFO index 0129894..a75572b 100644 --- a/swh.auth.egg-info/PKG-INFO +++ b/swh.auth.egg-info/PKG-INFO @@ -1,30 +1,30 @@ Metadata-Version: 2.1 Name: swh.auth -Version: 0.5.0 +Version: 0.5.1 Summary: Software Heritage Authentication Utilities Home-page: https://forge.softwareheritage.org/source/swh-auth/ Author: Software Heritage developers Author-email: swh-devel@inria.fr License: UNKNOWN Project-URL: Bug Reports, https://forge.softwareheritage.org/maniphest Project-URL: Funding, https://www.softwareheritage.org/donate Project-URL: Source, https://forge.softwareheritage.org/source/swh- Project-URL: Documentation, https://docs.softwareheritage.org/devel/swh-/ Description: .. _swh-auth: Software Heritage - Authentication ================================== Authentication library for SWH (keycloak common utilities) Platform: UNKNOWN Classifier: Programming Language :: Python :: 3 Classifier: Intended Audience :: Developers Classifier: License :: OSI Approved :: GNU General Public License v3 (GPLv3) Classifier: Operating System :: OS Independent Classifier: Development Status :: 3 - Alpha Requires-Python: >=3.7 Description-Content-Type: text/markdown Provides-Extra: django Provides-Extra: testing diff --git a/swh/auth/django/backends.py b/swh/auth/django/backends.py index 29e992c..262475e 100644 --- a/swh/auth/django/backends.py +++ b/swh/auth/django/backends.py @@ -1,201 +1,215 @@ # Copyright (C) 2020-2021 The Software Heritage developers # See the AUTHORS file at the top-level directory of this distribution # License: GNU Affero General Public License version 3, or any later version # See top-level LICENSE file for more information from datetime import datetime import hashlib from typing import Any, Dict, Optional from django.core.cache import cache from django.http import HttpRequest from django.utils import timezone from rest_framework.authentication import BaseAuthentication from rest_framework.exceptions import AuthenticationFailed, ValidationError import sentry_sdk from swh.auth.django.models import OIDCUser from swh.auth.django.utils import ( keycloak_oidc_client, oidc_profile_cache_key, oidc_user_from_decoded_token, oidc_user_from_profile, ) -from swh.auth.keycloak import ExpiredSignatureError, KeycloakOpenIDConnect +from swh.auth.keycloak import ( + ExpiredSignatureError, + KeycloakError, + KeycloakOpenIDConnect, + keycloak_error_message, +) def _update_cached_oidc_profile( oidc_client: KeycloakOpenIDConnect, oidc_profile: Dict[str, Any], user: OIDCUser ) -> None: """ Update cached OIDC profile associated to a user if needed: when the profile is not stored in cache or when the authentication tokens have changed. Args: oidc_client: KeycloakOpenID wrapper oidc_profile: OIDC profile used to authenticate a user user: django model representing the authenticated user """ # put OIDC profile in cache or update it after token renewal cache_key = oidc_profile_cache_key(oidc_client, user.id) if ( cache.get(cache_key) is None or user.access_token != oidc_profile["access_token"] ): # set cache key TTL as refresh token expiration time assert user.refresh_expires_at ttl = int(user.refresh_expires_at.timestamp() - timezone.now().timestamp()) # save oidc_profile in cache cache.set(cache_key, user.oidc_profile, timeout=max(0, ttl)) class OIDCAuthorizationCodePKCEBackend: """ Django authentication backend using Keycloak OpenID Connect authorization code flow with PKCE ("Proof Key for Code Exchange"). To use that backend globally in your django application, proceed as follow: * add ``"swh.auth.django.backends.OIDCAuthorizationCodePKCEBackend"`` to the ``AUTHENTICATION_BACKENDS`` django setting * configure Keycloak URL, realm and client by adding ``SWH_AUTH_SERVER_URL``, ``SWH_AUTH_REALM_NAME`` and ``SWH_AUTH_CLIENT_ID`` in django settings * add ``swh.auth.django.views.urlpatterns`` to your django application URLs * add an HTML link targeting the ``"oidc-login"`` django view in your application views * once a user is logged in, add an HTML link targeting the ``"oidc-logout"`` django view in your application views (a ``next_path`` query parameter can be used to redirect to a view of choice once the user is logged out) """ def authenticate( self, request: HttpRequest, code: str, code_verifier: str, redirect_uri: str ) -> Optional[OIDCUser]: user = None try: oidc_client = keycloak_oidc_client() # try to authenticate user with OIDC PKCE authorization code flow oidc_profile = oidc_client.authorization_code( code, redirect_uri, code_verifier=code_verifier ) # create Django user user = oidc_user_from_profile(oidc_client, oidc_profile) # update cached oidc profile if needed _update_cached_oidc_profile(oidc_client, oidc_profile, user) except Exception as e: sentry_sdk.capture_exception(e) return user def get_user(self, user_id: int) -> Optional[OIDCUser]: # get oidc profile from cache oidc_client = keycloak_oidc_client() oidc_profile = cache.get(oidc_profile_cache_key(oidc_client, user_id)) if oidc_profile: try: user = oidc_user_from_profile(oidc_client, oidc_profile) # update cached oidc profile if needed _update_cached_oidc_profile(oidc_client, oidc_profile, user) # restore auth backend setattr(user, "backend", f"{__name__}.{self.__class__.__name__}") return user except Exception as e: sentry_sdk.capture_exception(e) return None else: return None class OIDCBearerTokenAuthentication(BaseAuthentication): """ Django REST Framework authentication backend using bearer tokens for Keycloak OpenID Connect. It enables to authenticate a Web API user by sending a long-lived OpenID Connect refresh token in HTTP Authorization headers. Long lived refresh tokens can be generated by opening an OpenID Connect session with the following scope: ``openid offline_access``. To use that backend globally in your DRF application, proceed as follow: * add ``"swh.auth.django.backends.OIDCBearerTokenAuthentication"`` to the ``REST_FRAMEWORK["DEFAULT_AUTHENTICATION_CLASSES"]`` django setting. * configure Keycloak URL, realm and client by adding ``SWH_AUTH_SERVER_URL``, ``SWH_AUTH_REALM_NAME`` and ``SWH_AUTH_CLIENT_ID`` in django settings Users will then be able to perform authenticated Web API calls by sending their refresh token in HTTP Authorization headers, for instance: ``curl -H "Authorization: Bearer ${TOKEN}" https://...``. """ def authenticate(self, request): auth_header = request.META.get("HTTP_AUTHORIZATION") if auth_header is None: return None try: auth_type, refresh_token = auth_header.split(" ", 1) except ValueError: raise AuthenticationFailed("Invalid HTTP authorization header format") if auth_type != "Bearer": raise AuthenticationFailed( (f"Invalid or unsupported HTTP authorization" f" type ({auth_type}).") ) try: oidc_client = keycloak_oidc_client() # compute a cache key from the token that does not exceed # memcached key size limit hasher = hashlib.sha1() hasher.update(refresh_token.encode("ascii")) cache_key = f"api_token_{hasher.hexdigest()}" # check if an access token is cached access_token = cache.get(cache_key) if access_token is not None: # attempt to decode access token try: decoded_token = oidc_client.decode_token(access_token) # access token has expired except ExpiredSignatureError: decoded_token = None if access_token is None or decoded_token is None: # get a new access token from authentication provider access_token = oidc_client.refresh_token(refresh_token)["access_token"] # decode access token decoded_token = oidc_client.decode_token(access_token) # compute access token expiration exp = datetime.fromtimestamp(decoded_token["exp"]) ttl = int(exp.timestamp() - timezone.now().timestamp()) # save access token in cache while it is valid cache.set(cache_key, access_token, timeout=max(0, ttl)) # create Django user user = oidc_user_from_decoded_token(decoded_token, oidc_client.client_id) except UnicodeEncodeError as e: sentry_sdk.capture_exception(e) raise ValidationError("Invalid bearer token") + except KeycloakError as ke: + error_msg = keycloak_error_message(ke) + if error_msg == "invalid_grant: Offline user session not found": + error_msg = ( + "Bearer token expired after a long period of inactivity; " + "please generate a new one." + ) + sentry_sdk.capture_exception(ke) + raise AuthenticationFailed(error_msg) except Exception as e: sentry_sdk.capture_exception(e) raise AuthenticationFailed(str(e)) return user, None diff --git a/swh/auth/tests/django/test_drf_bearer_token_auth.py b/swh/auth/tests/django/test_drf_bearer_token_auth.py index 44d1190..7b490b4 100644 --- a/swh/auth/tests/django/test_drf_bearer_token_auth.py +++ b/swh/auth/tests/django/test_drf_bearer_token_auth.py @@ -1,109 +1,151 @@ # Copyright (C) 2020-2021 The Software Heritage developers # See the AUTHORS file at the top-level directory of this distribution # License: GNU Affero General Public License version 3, or any later version # See top-level LICENSE file for more information +import json + from django.contrib.auth.models import AnonymousUser, User +from django.core.cache import cache import pytest from swh.auth.django.models import OIDCUser from swh.auth.django.utils import reverse +from swh.auth.keycloak import KeycloakError + + +@pytest.fixture +def api_client(api_client): + # ensure django cache is cleared before each test + cache.clear() + return api_client @pytest.mark.django_db def test_drf_django_session_auth_success(keycloak_oidc, client): """ Check user gets authenticated when querying the web api through a web browser. """ url = reverse("api-test") client.login(code="", code_verifier="", redirect_uri="") response = client.get(url) assert response.status_code == 200 request = response.wsgi_request # user should be authenticated assert isinstance(request.user, OIDCUser) # check remoter used has not been saved to Django database with pytest.raises(User.DoesNotExist): User.objects.get(username=request.user.username) @pytest.mark.django_db def test_drf_oidc_bearer_token_auth_success(keycloak_oidc, api_client): """ Check user gets authenticated when querying the web api through an HTTP client using bearer token authentication. """ url = reverse("api-test") oidc_profile = keycloak_oidc.login() refresh_token = oidc_profile["refresh_token"] api_client.credentials(HTTP_AUTHORIZATION=f"Bearer {refresh_token}") response = api_client.get(url) assert response.status_code == 200 request = response.wsgi_request # user should be authenticated assert isinstance(request.user, OIDCUser) # check remoter used has not been saved to Django database with pytest.raises(User.DoesNotExist): User.objects.get(username=request.user.username) @pytest.mark.django_db def test_drf_oidc_bearer_token_auth_failure(keycloak_oidc, api_client): url = reverse("api-test") oidc_profile = keycloak_oidc.login() refresh_token = oidc_profile["refresh_token"] # check for failed authentication but with expected token format keycloak_oidc.set_auth_success(False) api_client.credentials(HTTP_AUTHORIZATION=f"Bearer {refresh_token}") response = api_client.get(url) assert response.status_code == 403 request = response.wsgi_request assert isinstance(request.user, AnonymousUser) # check for failed authentication when token format is invalid api_client.credentials(HTTP_AUTHORIZATION="Bearer invalid-token-format-ééàà") response = api_client.get(url) assert response.status_code == 400 request = response.wsgi_request assert isinstance(request.user, AnonymousUser) def test_drf_oidc_auth_invalid_or_missing_authorization_type(keycloak_oidc, api_client): url = reverse("api-test") oidc_profile = keycloak_oidc.login() refresh_token = oidc_profile["refresh_token"] # missing authorization type api_client.credentials(HTTP_AUTHORIZATION=f"{refresh_token}") response = api_client.get(url) assert response.status_code == 403 request = response.wsgi_request assert isinstance(request.user, AnonymousUser) # invalid authorization type api_client.credentials(HTTP_AUTHORIZATION="Foo token") response = api_client.get(url) assert response.status_code == 403 request = response.wsgi_request assert isinstance(request.user, AnonymousUser) + + +@pytest.mark.django_db +def test_drf_oidc_bearer_token_expired_token(keycloak_oidc, api_client): + url = reverse("api-test") + + oidc_profile = keycloak_oidc.login() + refresh_token = oidc_profile["refresh_token"] + + api_client.credentials(HTTP_AUTHORIZATION=f"Bearer {refresh_token}") + + kc_error_dict = { + "error": "invalid_grant", + "error_description": "Offline user session not found", + } + + keycloak_oidc.refresh_token.side_effect = KeycloakError( + error_message=json.dumps(kc_error_dict).encode(), response_code=400 + ) + + response = api_client.get(url) + expected_error_msg = ( + "Bearer token expired after a long period of inactivity; " + "please generate a new one." + ) + + assert response.status_code == 403 + assert expected_error_msg in json.dumps(response.data) + + request = response.wsgi_request + assert isinstance(request.user, AnonymousUser) diff --git a/swh/auth/tests/django/test_views.py b/swh/auth/tests/django/test_views.py index b0df547..ecc34d8 100644 --- a/swh/auth/tests/django/test_views.py +++ b/swh/auth/tests/django/test_views.py @@ -1,282 +1,281 @@ # Copyright (C) 2020-2021 The Software Heritage developers # See the AUTHORS file at the top-level directory of this distribution # License: GNU Affero General Public License version 3, or any later version # See top-level LICENSE file for more information import json from urllib.parse import urljoin, urlparse import uuid from django.contrib.auth.models import AnonymousUser, User from django.http import QueryDict import pytest from swh.auth.django.models import OIDCUser from swh.auth.django.utils import reverse from swh.auth.keycloak import KeycloakError from swh.auth.tests.django.django_asserts import assert_contains from swh.auth.tests.sample_data import CLIENT_ID def _check_oidc_login_code_flow_data( request, response, keycloak_oidc, redirect_uri, scope="openid" ): parsed_url = urlparse(response["location"]) authorization_url = keycloak_oidc.well_known()["authorization_endpoint"] query_dict = QueryDict(parsed_url.query) # check redirect url is valid assert urljoin(response["location"], parsed_url.path) == authorization_url assert "client_id" in query_dict assert query_dict["client_id"] == CLIENT_ID assert "response_type" in query_dict assert query_dict["response_type"] == "code" assert "redirect_uri" in query_dict assert query_dict["redirect_uri"] == redirect_uri assert "code_challenge_method" in query_dict assert query_dict["code_challenge_method"] == "S256" assert "scope" in query_dict assert query_dict["scope"] == scope assert "state" in query_dict assert "code_challenge" in query_dict # check a login_data has been registered in user session assert "login_data" in request.session login_data = request.session["login_data"] assert "code_verifier" in login_data assert "state" in login_data assert "redirect_uri" in login_data assert login_data["redirect_uri"] == query_dict["redirect_uri"] return login_data @pytest.mark.django_db def test_oidc_login_views_success(client, keycloak_oidc): """ Simulate a successful login authentication with OpenID Connect authorization code flow with PKCE. """ # user initiates login process login_url = reverse("oidc-login") # should redirect to Keycloak authentication page in order # for a user to login with its username / password response = client.get(login_url) assert response.status_code == 302 request = response.wsgi_request assert isinstance(request.user, AnonymousUser) login_data = _check_oidc_login_code_flow_data( request, response, keycloak_oidc, redirect_uri=reverse("oidc-login-complete", request=request), ) # once a user has identified himself in Keycloak, he is # redirected to the 'oidc-login-complete' view to # login in Django. # generate authorization code / session state in the same # manner as Keycloak code = f"{str(uuid.uuid4())}.{str(uuid.uuid4())}.{str(uuid.uuid4())}" session_state = str(uuid.uuid4()) login_complete_url = reverse( "oidc-login-complete", query_params={ "code": code, "state": login_data["state"], "session_state": session_state, }, ) # login process finalization, should redirect to root url by default response = client.get(login_complete_url) assert response.status_code == 302 request = response.wsgi_request assert response["location"] == request.build_absolute_uri("/") # user should be authenticated assert isinstance(request.user, OIDCUser) # check remote user has not been saved to Django database with pytest.raises(User.DoesNotExist): User.objects.get(username=request.user.username) @pytest.mark.django_db def test_oidc_logout_view_success(client, keycloak_oidc): """ Simulate a successful logout operation with OpenID Connect. """ # login our test user client.login(code="", code_verifier="", redirect_uri="") keycloak_oidc.authorization_code.assert_called() # user initiates logout next_path = reverse("root") oidc_logout_url = reverse("oidc-logout", query_params={"next_path": next_path}) # should redirect to logout page response = client.get(oidc_logout_url) assert response.status_code == 302 request = response.wsgi_request assert response["location"] == next_path # should have been logged out in Keycloak oidc_profile = keycloak_oidc.login() keycloak_oidc.logout.assert_called_with(oidc_profile["refresh_token"]) # check effective logout in Django assert isinstance(request.user, AnonymousUser) @pytest.mark.django_db def test_oidc_login_view_failure(client, keycloak_oidc): """ Simulate a failed authentication with OpenID Connect. """ keycloak_oidc.set_auth_success(False) # user initiates login process login_url = reverse("oidc-login") # should render an error page response = client.get(login_url) assert response.status_code == 500 request = response.wsgi_request # no users should be logged in assert isinstance(request.user, AnonymousUser) # Simulate possible errors with OpenID Connect in the login complete view. def test_oidc_login_complete_view_no_login_data(client): # user initiates login process login_url = reverse("oidc-login-complete") # should return with error response = client.get(login_url) assert response.status_code == 500 assert_contains( response, "Login process has not been initialized.", status_code=500 ) def test_oidc_login_complete_view_missing_parameters(client): # simulate login process has been initialized session = client.session session["login_data"] = { "code_verifier": "", "state": str(uuid.uuid4()), "redirect_uri": "", "next_path": "", } session.save() # user initiates login process login_url = reverse("oidc-login-complete") # should return with error response = client.get(login_url) assert response.status_code == 400 request = response.wsgi_request assert_contains( response, "Missing query parameters for authentication.", status_code=400 ) # no user should be logged in assert isinstance(request.user, AnonymousUser) def test_oidc_login_complete_wrong_csrf_token(client, keycloak_oidc): # simulate login process has been initialized session = client.session session["login_data"] = { "code_verifier": "", "state": str(uuid.uuid4()), "redirect_uri": "", "next_path": "", } session.save() # user initiates login process login_url = reverse( "oidc-login-complete", query_params={"code": "some-code", "state": "some-state"} ) # should render an error page response = client.get(login_url) assert response.status_code == 400 request = response.wsgi_request assert_contains( response, "Wrong CSRF token, aborting login process.", status_code=400 ) # no user should be logged in assert isinstance(request.user, AnonymousUser) @pytest.mark.django_db def test_oidc_login_complete_wrong_code_verifier(client, keycloak_oidc): keycloak_oidc.set_auth_success(False) # simulate login process has been initialized session = client.session session["login_data"] = { "code_verifier": "", "state": str(uuid.uuid4()), "redirect_uri": "", "next_path": "", } session.save() # check authentication error is reported login_url = reverse( "oidc-login-complete", query_params={"code": "some-code", "state": session["login_data"]["state"]}, ) # should render an error page response = client.get(login_url) - print(response.content) assert response.status_code == 500 request = response.wsgi_request assert_contains(response, "User authentication failed.", status_code=500) # no user should be logged in assert isinstance(request.user, AnonymousUser) @pytest.mark.django_db def test_oidc_logout_view_failure(client, keycloak_oidc): """ Simulate a failed logout operation with OpenID Connect. """ # login our test user client.login(code="", code_verifier="", redirect_uri="") error = "unknown_error" error_message = json.dumps({"error": error}).encode() keycloak_oidc.logout.side_effect = KeycloakError( error_message=error_message, response_code=401 ) # user initiates logout process logout_url = reverse("oidc-logout") # should return with error response = client.get(logout_url) assert response.status_code == 500 request = response.wsgi_request assert_contains(response, error, status_code=500) # user should be logged out from Django anyway assert isinstance(request.user, AnonymousUser)