Zulip server and web application. Open-source team chat that helps teams stay productive and focused.
auth: Allow signing in to an existing account with noreply github email.
Mateusz Mandera6a5091103272
diff --git a/zerver/tests/test_auth_backends.py b/zerver/tests/test_auth_backends.pyindex 4834826e3bd..123850b477d 100644--- a/zerver/tests/test_auth_backends.py+++ b/zerver/tests/test_auth_backends.py@@ -779,7 +779,8 @@ class SocialAuthBase(DesktopFlowTestingLib, ZulipTestCase):def social_auth_test_finish(self, result: HttpResponse,account_data_dict: Dict[str, str],expect_choose_email_screen: bool,- **headers: Any) -> HttpResponse:+ headers: Any,+ **extra_data: Any) -> HttpResponse:parsed_url = urllib.parse.urlparse(result.url)csrf_state = urllib.parse.parse_qs(parsed_url.query)['state']result = self.client_get(self.AUTH_FINISH_URL,@@ -872,7 +873,8 @@ class SocialAuthBase(DesktopFlowTestingLib, ZulipTestCase):result = self.social_auth_test_finish(result, account_data_dict,expect_choose_email_screen,- **headers)+ headers=headers,+ **extra_data)return resultdef test_social_auth_no_key(self) -> None:@@ -2098,7 +2100,8 @@ class AppleIdAuthBackendTest(AppleAuthMixin, SocialAuthBase):def social_auth_test_finish(self, result: HttpResponse,account_data_dict: Dict[str, str],expect_choose_email_screen: bool,- **headers: Any) -> HttpResponse:+ headers: Any,+ **extra_data: Any) -> HttpResponse:parsed_url = urllib.parse.urlparse(result.url)state = urllib.parse.parse_qs(parsed_url.query)['state']self.client.session.flush()@@ -2358,7 +2361,9 @@ class GitHubAuthBackendTest(SocialAuthBase):def social_auth_test_finish(self, result: HttpResponse,account_data_dict: Dict[str, str],expect_choose_email_screen: bool,- **headers: Any) -> HttpResponse:+ headers: Any,+ expect_noreply_email_allowed: bool=False,+ **extra_data: Any) -> HttpResponse:parsed_url = urllib.parse.urlparse(result.url)csrf_state = urllib.parse.parse_qs(parsed_url.query)['state']result = self.client_get(self.AUTH_FINISH_URL,@@ -2379,7 +2384,7 @@ class GitHubAuthBackendTest(SocialAuthBase):all_emails_verified = Truefor email_data_dict in self.email_data:email = email_data_dict["email"]- if email.endswith("@users.noreply.github.com"):+ if email.endswith("@users.noreply.github.com") and not expect_noreply_email_allowed:self.assert_not_in_success_response([email], result)elif email_data_dict.get('verified'):self.assert_in_success_response([email], result)@@ -2706,9 +2711,10 @@ class GitHubAuthBackendTest(SocialAuthBase):def test_github_oauth2_email_no_reply_dot_github_dot_com(self) -> None:# As emails ending with `noreply.github.com` are excluded from- # verified_emails, choosing it as an email should raise a `email- # not associated` warning.- account_data_dict = self.get_account_data_dict(email="[email protected]", name=self.name)+ # verified_emails unless an account with that email already exists,+ # choosing it as an email should raise a `email not associated` warning.+ noreply_email = "[email protected]"+ account_data_dict = self.get_account_data_dict(email=noreply_email, name=self.name)email_data = [dict(email="[email protected]",verified=True),@@ -2733,6 +2739,24 @@ class GitHubAuthBackendTest(SocialAuthBase):"warning",)])+ # Now we create the user account with the noreply email and verify that it's+ # possible to sign in to it.+ realm = get_realm("zulip")+ do_create_user(noreply_email, 'password', realm, account_data_dict["name"])+ result = self.social_auth_test(account_data_dict,+ subdomain='zulip',+ expect_choose_email_screen=True,+ expect_noreply_email_allowed=True,+ email_data=email_data)+ data = load_subdomain_token(result)+ self.assertEqual(data['email'], account_data_dict["email"])+ self.assertEqual(data['full_name'], account_data_dict["name"])+ self.assertEqual(data['subdomain'], 'zulip')+ self.assertEqual(result.status_code, 302)+ parsed_url = urllib.parse.urlparse(result.url)+ uri = f"{parsed_url.scheme}://{parsed_url.netloc}{parsed_url.path}"+ self.assertTrue(uri.startswith('http://zulip.testserver/accounts/login/subdomain/'))+def test_github_oauth2_email_not_associated(self) -> None:account_data_dict = self.get_account_data_dict(email='[email protected]', name=self.name)email_data = [diff --git a/zproject/backends.py b/zproject/backends.pyindex f37ad001d2c..d91efab6761 100644--- a/zproject/backends.py+++ b/zproject/backends.py@@ -1109,7 +1109,7 @@ def social_associate_user_helper(backend: BaseAuth, return_data: Dict[str, Any],# field of the `details` object). For those backends, we have# custom per-backend code to properly fetch only verified# email addresses from the appropriate third-party API.- verified_emails = backend.get_verified_emails(*args, **kwargs)+ verified_emails = backend.get_verified_emails(realm, *args, **kwargs)verified_emails_length = len(verified_emails)if verified_emails_length == 0:# TODO: Provide a nice error message screen to the user@@ -1136,7 +1136,7 @@ def social_associate_user_helper(backend: BaseAuth, return_data: Dict[str, Any],if (len(existing_account_emails) != 1 or backend.strategy.session_get('is_signup') == '1'):unverified_emails = []if hasattr(backend, 'get_unverified_emails'):- unverified_emails = backend.get_unverified_emails(*args, **kwargs)+ unverified_emails = backend.get_unverified_emails(realm, *args, **kwargs)return render(backend.strategy.request, 'zerver/social_auth_select_email.html', context = {'primary_email': verified_emails[0],'verified_non_primary_emails': verified_emails[1:],@@ -1427,18 +1427,18 @@ class GitHubAuthBackend(SocialAuthMixin, GithubOAuth2):emails = []return emails- def get_unverified_emails(self, *args: Any, **kwargs: Any) -> List[str]:+ def get_unverified_emails(self, realm: Realm, *args: Any, **kwargs: Any) -> List[str]:return [- email_obj['email'] for email_obj in self.get_usable_email_objects(*args, **kwargs)+ email_obj['email'] for email_obj in self.get_usable_email_objects(realm, *args, **kwargs)if not email_obj.get('verified')]- def get_verified_emails(self, *args: Any, **kwargs: Any) -> List[str]:+ def get_verified_emails(self, realm: Realm, *args: Any, **kwargs: Any) -> List[str]:# We only let users login using email addresses that are# verified by GitHub, because the whole point is for the user# to demonstrate that they control the target email address.verified_emails: List[str] = []- for email_obj in [obj for obj in self.get_usable_email_objects(*args, **kwargs)+ for email_obj in [obj for obj in self.get_usable_email_objects(realm, *args, **kwargs)if obj.get('verified')]:# social_associate_user_helper assumes that the first email in# verified_emails is primary.@@ -1449,15 +1449,19 @@ class GitHubAuthBackend(SocialAuthMixin, GithubOAuth2):return verified_emails- def get_usable_email_objects(self, *args: Any, **kwargs: Any) -> List[Dict[str, Any]]:- # We disallow the+ def get_usable_email_objects(self, realm: Realm, *args: Any, **kwargs: Any) -> List[Dict[str, Any]]:+ # We disallow creation of new accounts with# @noreply.github.com/@users.noreply.github.com email# addresses, because structurally, we only want to allow email- # addresses that can receive emails, and those cannot.+ # addresses that can receive emails, and those cannot. However,+ # if an account with this address happens to already exist in the realm+ # (which could happen e.g. as a result of data import from another chat tool),+ # we will allow signing in to it.email_objs = self.get_all_associated_email_objects(*args, **kwargs)return [email for email in email_objs- if not email["email"].endswith("@users.noreply.github.com")+ if (not email["email"].endswith("@users.noreply.github.com")+ or common_get_active_user(email["email"], realm) is not None)]def user_data(self, access_token: str, *args: Any, **kwargs: Any) -> Dict[str, str]: