diff --git a/credentials/apps/core/tests/test_utils.py b/credentials/apps/core/tests/test_utils.py index 15cef32e1..ffe2a96f3 100644 --- a/credentials/apps/core/tests/test_utils.py +++ b/credentials/apps/core/tests/test_utils.py @@ -1,11 +1,33 @@ """Test core.utils.""" from unittest import mock +from urllib.parse import parse_qs, urlparse +import ddt +import jwt +from auth_backends.backends import EdXOAuth2 from django.test import TestCase +from django.urls import reverse from credentials.apps.core.tests.factories import UserFactory -from credentials.apps.core.utils import update_full_name +from credentials.apps.core.tests.mixins import SiteMixin +from credentials.apps.core.utils import update_full_name, update_is_active + + +def _lms_access_token(user, email_verified): + """Build an access token like the LMS's. The LMS sets `email_verified` to its own `user.is_active`.""" + return jwt.encode( + { + "preferred_username": user.username, + "email": user.email, + "user_id": 123, + "administrator": False, + "superuser": False, + "email_verified": email_verified, + }, + "lms-secret", + algorithm="HS256", + ) class UtilsTests(TestCase): @@ -28,3 +50,94 @@ def test_update_full_name_happy_path(self): update_full_name(strategy, {"full_name": "Bort"}, self.user) self.assertEqual(self.user.full_name, "Bort") self.assertTrue(strategy.storage.user.changed.called) + + +@ddt.ddt +class UpdateIsActiveTests(TestCase): + """Tests for the update_is_active pipeline step.""" + + def setUp(self): + super().setUp() + self.user = UserFactory(is_active=False) + self.strategy = mock.MagicMock() + + def test_activates_when_lms_account_is_active(self): + response = {"access_token": _lms_access_token(self.user, email_verified=True)} + update_is_active(self.strategy, user=self.user, response=response) + self.assertTrue(self.user.is_active) + self.strategy.storage.user.changed.assert_called_once_with(self.user) + + @ddt.data(False, None) + def test_stays_inactive_when_lms_account_is_not_active(self, email_verified): + response = {"access_token": _lms_access_token(self.user, email_verified=email_verified)} + update_is_active(self.strategy, user=self.user, response=response) + self.assertFalse(self.user.is_active) + self.strategy.storage.user.changed.assert_not_called() + + def test_claim_missing(self): + token = jwt.encode({"preferred_username": self.user.username}, "lms-secret", algorithm="HS256") + update_is_active(self.strategy, user=self.user, response={"access_token": token}) + self.assertFalse(self.user.is_active) + self.strategy.storage.user.changed.assert_not_called() + + @ddt.data(None, {}, {"access_token": ""}, {"access_token": "not-a-jwt"}) + def test_no_usable_token(self, response): + update_is_active(self.strategy, user=self.user, response=response) + self.assertFalse(self.user.is_active) + self.strategy.storage.user.changed.assert_not_called() + + def test_active_user_is_left_alone(self): + self.user.is_active = True + response = {"access_token": _lms_access_token(self.user, email_verified=False)} + update_is_active(self.strategy, user=self.user, response=response) + self.assertTrue(self.user.is_active) + self.strategy.storage.user.changed.assert_not_called() + + def test_no_user(self): + # Just test that we don't blow up + update_is_active(self.strategy, user=None, response={}) + + +class LoginPipelineTests(SiteMixin, TestCase): + """ + Run the real SSO login flow for a user that is inactive in Credentials. + + Before update_is_active, social-auth sent these users back to LOGIN_URL, which restarted the login (a redirect + loop), even when their LMS account was active. + """ + + next_url = "/records/" + + def setUp(self): + super().setUp() + self.user = UserFactory(is_active=False) + + def _sso_login(self, email_verified): + begin = self.client.get(reverse("social:begin", args=["edx-oauth2"]), {"next": self.next_url}) + state = parse_qs(urlparse(begin["Location"]).query)["state"][0] + token_response = { + "access_token": _lms_access_token(self.user, email_verified=email_verified), + "token_type": "JWT", + "expires_in": 3600, + } + with mock.patch.object(EdXOAuth2, "request_access_token", return_value=token_response): + return self.client.get(reverse("social:complete", args=["edx-oauth2"]), {"code": "abc", "state": state}) + + def test_active_lms_user_is_logged_in(self): + response = self._sso_login(email_verified=True) + + self.assertEqual(response.status_code, 302) + self.assertEqual(response["Location"], self.next_url) + self.user.refresh_from_db() + self.assertTrue(self.user.is_active) + self.assertEqual(int(self.client.session["_auth_user_id"]), self.user.id) + + def test_inactive_lms_user_is_not_logged_in(self): + response = self._sso_login(email_verified=False) + + self.assertEqual(response.status_code, 302) + # Back to the login page, which starts the SSO again: the redirect loop. + self.assertEqual(response["Location"], f"/login/?next={self.next_url}") + self.user.refresh_from_db() + self.assertFalse(self.user.is_active) + self.assertNotIn("_auth_user_id", self.client.session) diff --git a/credentials/apps/core/utils.py b/credentials/apps/core/utils.py index f282c78f4..49855314b 100644 --- a/credentials/apps/core/utils.py +++ b/credentials/apps/core/utils.py @@ -1,5 +1,11 @@ """Core utils.""" +import logging + +import jwt + +logger = logging.getLogger(__name__) + # This function is used by our oauth2 authorization pipeline. See settings/base.py def update_full_name(strategy, details, user=None, *_args, **_kwargs): # pylint: disable=keyword-arg-before-vararg @@ -21,6 +27,35 @@ def update_lms_user_id(strategy, details, user=None, *_args, **_kwargs): # pyli strategy.storage.user.changed(user) +def update_is_active(strategy, user=None, *_args, **kwargs): # pylint: disable=keyword-arg-before-vararg + """ + Activate an inactive user whose LMS account is active. + + A user can be created inactive from an LMS certificate event, sent before the learner activated their LMS account. + Nothing else updates is_active, so social-auth keeps sending them back to the login page. The LMS puts its + is_active value in the access token's `email_verified` claim. Like make_is_active_match_platform, this only goes + from inactive to active. + """ + if not user or user.is_active: + return + + access_token = (kwargs.get("response") or {}).get("access_token") + if not access_token: + return + + try: + # The token came straight from the LMS token endpoint. edx-auth-backends reads its other claims the same way. + claims = jwt.decode(access_token, algorithms=["HS256"], options={"verify_signature": False}) + except jwt.InvalidTokenError: + logger.warning(f"Could not decode the access token to check is_active for user [{user.id}]") + return + + if claims.get("email_verified") is True: + user.is_active = True + strategy.storage.user.changed(user) + logger.info(f"Activated user [{user.id}] with lms_user_id [{user.lms_user_id}]: the LMS account is active") + + def _choices(*values): """ Helper for use with model field 'choices'. diff --git a/credentials/settings/base.py b/credentials/settings/base.py index 11899a3ae..d42bbcd9c 100644 --- a/credentials/settings/base.py +++ b/credentials/settings/base.py @@ -347,6 +347,7 @@ # Credentials-specific pipeline below "credentials.apps.core.utils.update_full_name", "credentials.apps.core.utils.update_lms_user_id", + "credentials.apps.core.utils.update_is_active", ) # Set these to the correct values for your OAuth2 provider (e.g., devstack) diff --git a/requirements/base.in b/requirements/base.in index 28d88d638..b61ea3030 100644 --- a/requirements/base.in +++ b/requirements/base.in @@ -44,6 +44,7 @@ openedx-atlas openedx-events pillow pygments +pyjwt python-memcached pymemcache pytz diff --git a/requirements/base.txt b/requirements/base.txt index ea79ddd0f..f41127f3c 100644 --- a/requirements/base.txt +++ b/requirements/base.txt @@ -311,6 +311,7 @@ pygments==2.19.2 # via -r requirements/base.in pyjwt[crypto]==2.10.1 # via + # -r requirements/base.in # drf-jwt # edx-auth-backends # edx-drf-extensions