You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@allura.apache.org by di...@apache.org on 2026/05/01 18:21:01 UTC

(allura) 06/07: [#8601] Do email verification for untrusted logins even if they did multifactor (protects against MITM attacks)

This is an automated email from the ASF dual-hosted git repository.

asf-gitbox-commits pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/allura.git

commit b715604ae4bdbfe5f2db5050af0b56b9d5c00dc3
Author: Dave Brondsema <da...@brondsema.net>
AuthorDate: Wed Apr 22 15:53:27 2026 -0400

    [#8601] Do email verification for untrusted logins even if they did multifactor (protects against MITM attacks)
---
 Allura/allura/controllers/auth.py           |  5 +-
 Allura/allura/lib/plugin.py                 | 37 +++++++--------
 Allura/allura/tests/functional/test_auth.py | 74 +++++++++++++++++++++--------
 3 files changed, 75 insertions(+), 41 deletions(-)

diff --git a/Allura/allura/controllers/auth.py b/Allura/allura/controllers/auth.py
index 3f3feaf8b..30e719ebc 100644
--- a/Allura/allura/controllers/auth.py
+++ b/Allura/allura/controllers/auth.py
@@ -473,6 +473,8 @@ def do_multifactor(self, code, mode, **kwargs):
             return self.multifactor(mode=mode, **kwargs)
         else:
             plugin.AuthenticationProvider.get(request).login(user=user, multifactor_success=True)
+            if session.get('mode') == 'email_code':
+                redirect(tg.url('/auth/login_email_sent', dict(return_to=kwargs.get('return_to', '/'))))
             return_to = self._verify_return_to(kwargs.get('return_to'))
             redirect(return_to)
 
@@ -510,8 +512,7 @@ def login_email_verify(self, token, return_to='/', **kwargs):
             session.save()
             redirect('/auth/')
 
-        h.auditlog_user('Logged in using email authentication link', user=user)
-        plugin.AuthenticationProvider.get(request).login(user=user, multifactor_success=True)
+        plugin.AuthenticationProvider.get(request).login(user=user, multifactor_success=True, email_verified=True)
         redirect(self._verify_return_to(return_to))
 
     @expose(content_type='text/plain')
diff --git a/Allura/allura/lib/plugin.py b/Allura/allura/lib/plugin.py
index 476c1bf69..6cd02d63c 100644
--- a/Allura/allura/lib/plugin.py
+++ b/Allura/allura/lib/plugin.py
@@ -205,7 +205,7 @@ def after_login(self, user: M.User, request):
         '''
         pass
 
-    def login(self, user: M.User = None, multifactor_success: bool = False) -> M.User | None:
+    def login(self, user: M.User = None, multifactor_success: bool = False, email_verified: bool = False) -> M.User | None:
         from allura import model as M
         if user is None:
             try:
@@ -217,37 +217,36 @@ def login(self, user: M.User = None, multifactor_success: bool = False) -> M.Use
         if user.is_anonymous():
             raise ValueError('Cannot log in an anonymous user')
 
+        login_details = self.get_login_detail(self.request, user)
+
+        # Stage: TOTP — MFA users who haven't completed TOTP yet
         if user.get_pref('multifactor') and not multifactor_success:
             self.session['multifactor-username'] = user.username
             h.auditlog_user('Multifactor login - password ok, code not entered yet', user=user)
             self.session.save()
             return None
-        else:
-            self.session.pop('multifactor-username', None)
-
-        login_details = self.get_login_detail(self.request, user)
 
-        # check if the user doesn't have mfa enabled but is logging in from an unknown location
-        # they'll get an authentication code via email
-        skip_after_login = False
-        if asbool(config.get('auth.email_auth_code.enabled', False)) and not user.get_pref('multifactor') and not self.trusted_login_source(user, login_details) and not multifactor_success:
-            h.auditlog_user('User without MFA attempted to login from untrusted location, '
-                            'sending code via email for them to enter',
-                            user=user)
+        # Stage: email link — any user logging in from an untrusted location (after TOTP if applicable)
+        if asbool(config.get('auth.email_auth_code.enabled', False)) and not self.trusted_login_source(user, login_details) and not email_verified:
+            h.auditlog_user('Attempted login from untrusted location, sending email verification link', user=user)
             self.session['multifactor-username'] = user.username
             self.session['mode'] = 'email_code'
             self.session.save()
             user.send_email_auth_code(return_to=self.request.params.get('return_to', '/'))
             return None
-        else:
-            # Validate if we used an auth code to skip the `after_login` which sends a foreign login email
-            skip_after_login = self.session.get('mode') == 'email_code'
-            self.session.pop('multifactor-username', None)
-            self.session.pop('mode', None)
+
+        # All stages complete — clean up and proceed to login
+        skip_after_login = self.session.get('mode') == 'email_code'  #  if we used an email link we'll skip `after_login` which sends a foreign login email
+        self.session.pop('multifactor-username', None)
+        self.session.pop('mode', None)
+
+        auditlog_msg = 'Successful login'
+        if email_verified:
+            auditlog_msg += ' using email verification'
 
         expire_reason = None
         if self.is_password_expired(user):
-            h.auditlog_user('Successful login; Password expired', user=user)
+            h.auditlog_user(f'{auditlog_msg}; Password expired', user=user)
             expire_reason = 'via expiration process'
         if not expire_reason:
             expire_reason = self.login_check_password_change_needed(user, self.request.params.get('password'),
@@ -258,7 +257,7 @@ def login(self, user: M.User = None, multifactor_success: bool = False) -> M.Use
             self.session['expired-reason'] = expire_reason
         else:
             self.session['username'] = user.username
-            h.auditlog_user('Successful login', user=user)
+            h.auditlog_user(auditlog_msg, user=user)
 
         if not skip_after_login:
             self.after_login(user, self.request)
diff --git a/Allura/allura/tests/functional/test_auth.py b/Allura/allura/tests/functional/test_auth.py
index 8d8f1edd1..4a5692eda 100644
--- a/Allura/allura/tests/functional/test_auth.py
+++ b/Allura/allura/tests/functional/test_auth.py
@@ -3125,7 +3125,10 @@ def test_disable(self):
         assert tasks[0].kwargs['subject'] == 'Two-Factor Authentication Disabled'
         assert 'disabled two-factor authentication' in tasks[0].kwargs['text']
 
-    def test_login_totp(self):
+    @mock.patch.dict(config, {'auth.email_auth_code.enabled': True})
+    @patch('allura.tasks.mail_tasks.send_system_mail_to_user')
+    @patch('allura.lib.plugin.AuthenticationProvider.trusted_login_source', return_value='exact ip')
+    def test_login_totp(self, trusted_login_source, send_system_mail_to_user):
         self._init_totp()
 
         # so test-admin isn't automatically logged in for all requests
@@ -3143,6 +3146,8 @@ def test_login_totp(self):
         assert r.location.endswith('/auth/multifactor?return_to=%2Fp%2Ffoo'), r
         r = r.follow()
         assert not r.session.get('username')
+        assert r.session.get('multifactor-username') == 'test-admin'
+        assert send_system_mail_to_user.call_count == 0
 
         # try an invalid code
         r.form['code'] = 'invalid-code'
@@ -3158,14 +3163,61 @@ def test_login_totp(self):
         with audits('Successful login', user=True):
             r = r.form.submit()
 
-        # confirm login and final page
+        # confirm login and final page — trusted source, so no email link stage
         assert r.session['username'] == 'test-admin'
         assert r.location.endswith('/p/foo'), r
+        assert send_system_mail_to_user.call_count == 0
 
         # if you end up on multifactor page again somehow, redir
         r = self.app.get('/auth/multifactor?return_to=/p/foo', status=302)
         assert r.location == 'http://localhost/p/foo'
 
+    @mock.patch.dict(config, {'auth.email_auth_code.enabled': True})
+    @patch('allura.tasks.mail_tasks.send_system_mail_to_user')
+    @patch('allura.lib.plugin.AuthenticationProvider.trusted_login_source', return_value=False)
+    def test_login_totp_untrusted_source(self, trusted_login_source, send_system_mail_to_user):
+        """MFA users from untrusted locations go through a 3-stage flow: password → TOTP → email link."""
+        self._init_totp()
+
+        # so test-admin isn't automatically logged in for all requests
+        self.app.extra_environ = {'disable_auth_magic': 'True'}
+
+        # regular login
+        r = self.app.get('/auth/?return_to=/p/foo')
+        f = r.forms[0]
+        encoded = self.app.antispam_field_names(f)
+        f[encoded['username']] = 'test-admin'
+        f[encoded['password']] = 'foo'
+        with audits('Multifactor login - password ok, code not entered yet', user=True):
+            r = r.form.submit()
+
+        # check results
+        assert r.location.endswith('/auth/multifactor?return_to=%2Fp%2Ffoo'), r
+        r = r.follow()
+        assert not r.session.get('username')
+        assert r.session.get('multifactor-username') == 'test-admin'
+        assert send_system_mail_to_user.call_count == 0
+
+        # use a valid code
+        totp = TotpService().Totp(self.sample_key)
+        code = totp.generate(time_time())
+        r.form['code'] = code
+        with audits('Attempted login from untrusted location, sending email verification link', user=True):
+            r = r.form.submit()
+        r = r.follow()
+
+        # have to verify by email now
+        assert r.request.path == '/auth/login_email_sent', self.webflash(r)
+        assert send_system_mail_to_user.call_count == 1
+        assert not r.session.get('username')
+        email_text = send_system_mail_to_user.call_args[0][2]
+        link = [line for line in email_text.splitlines() if '/auth/login_email_verify' in line][0]
+
+        # confirm login and final page
+        r = self.app.get(link, status=302)
+        assert r.location == 'http://localhost/p/foo'
+        assert r.session.get('username') == 'test-admin'
+
     def test_login_rate_limit(self):
         self._init_totp()
 
@@ -3356,24 +3408,6 @@ def test_send_links(self):
 
 class TestEmailAuthCode(TestController):
 
-    @mock.patch.dict(config, {'auth.email_auth_code.enabled': True})
-    @patch('allura.tasks.mail_tasks.send_system_mail_to_user')
-    def test_mfa_no_email_auth(self, send_system_mail_to_user):
-        self.app.extra_environ = {'disable_auth_magic': 'True'}
-        user = M.User.by_username('test-user')
-        user.set_pref('multifactor', True)
-
-        with patch('allura.lib.plugin.AuthenticationProvider.trusted_login_source', return_value=True):
-            r = self.app.get('/auth/')
-
-            f = r.forms[0]
-            encoded = self.app.antispam_field_names(f)
-            f[encoded['username']] = 'test-user'
-            f[encoded['password']] = 'foo'
-            r = f.submit(status=302)
-            assert send_system_mail_to_user.call_count == 0
-            assert r.session.get('mode') is None
-
     @mock.patch.dict(config, {'auth.email_auth_code.enabled': True})
     @patch('allura.tasks.mail_tasks.send_system_mail_to_user')
     def test_email_auth_code(self, send_system_mail_to_user):