You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@allura.apache.org by cc...@apache.org on 2026/10/13 14:22:39 UTC

(allura) branch cc/8625-part2 updated (2ce91991e -> 5b8108ff8)

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

asf-gitbox-commits pushed a change to branch cc/8625-part2
in repository https://gitbox.apache.org/repos/asf/allura.git


 discard 2ce91991e [#8625] Implemented full field level encryption for audit log messages
    omit 26ec3d20f [#8625] Add event types for audit log records and backfill script
     new 6aebb840a [#8625] Add event types for audit log records
     new da51e53d4 [#8625] Implemented full field level encryption for audit log messages
     new 9a8ff1d6d fixup! [#8625] Implemented full field level encryption for audit log messages
     new 5b8108ff8 fixup! [#8625] Implemented full field level encryption for audit log messages

This update added new revisions after undoing existing revisions.
That is to say, some revisions that were in the old version of the
branch are not in the new version.  This situation occurs
when a user --force pushes a change and generates a repository
containing something like this:

 * -- * -- B -- O -- O -- O   (2ce91991e)
            \
             N -- N -- N   refs/heads/cc/8625-part2 (5b8108ff8)

You should already have received notification emails for all of the O
revisions, and so the following emails describe only the N revisions
from the common base, B.

Any revisions marked "omit" are not gone; other references still
refer to them.  Any revisions marked "discard" are gone forever.

The 4 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails.  The revisions
listed as "add" were already present in the repository and have only
been added to this reference.


Summary of changes:
 Allura/allura/lib/plugin.py                        | 55 ----------------
 Allura/allura/model/auth.py                        | 77 ++--------------------
 .../scripts/backfill_previous_login_details.py     | 57 ----------------
 Allura/allura/tests/decorators.py                  | 18 ++---
 Allura/allura/tests/model/test_auth.py             | 51 +++-----------
 Allura/allura/tests/scripts/test_disable_users.py  | 21 ++----
 Allura/allura/tests/test_plugin.py                 | 29 --------
 .../tests/functional/test_forum_admin.py           |  4 +-
 8 files changed, 29 insertions(+), 283 deletions(-)
 delete mode 100644 Allura/allura/scripts/backfill_previous_login_details.py


(allura) 04/04: fixup! [#8625] Implemented full field level encryption for audit log messages

Posted by cc...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

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

commit 5b8108ff8c31bb81210ec87ba9a44143abb137cc
Author: Carlos Cruz <ca...@slashdotmedia.com>
AuthorDate: Tue Oct 13 13:33:57 2026 +0000

    fixup! [#8625] Implemented full field level encryption for audit log messages
    
    Share one helper for matching decrypted audit messages in tests
    
    audits(), out_audits() and test_forum_admin each looped over AuditLog
    entries to regex-match the decrypted message. They now share
    matching_audits() in allura.tests.decorators, which also removes the
    unused `re` import from test_forum_admin.
    
    test_encrypted_message_read_and_update no longer repeats the
    no-plaintext check from test_message_encrypted_storage.
---
 Allura/allura/tests/decorators.py                      | 18 +++++++++---------
 Allura/allura/tests/model/test_auth.py                 |  1 -
 .../tests/functional/test_forum_admin.py               |  4 +---
 3 files changed, 10 insertions(+), 13 deletions(-)

diff --git a/Allura/allura/tests/decorators.py b/Allura/allura/tests/decorators.py
index 63d5ae624..aa9cfb334 100644
--- a/Allura/allura/tests/decorators.py
+++ b/Allura/allura/tests/decorators.py
@@ -150,6 +150,12 @@ def __exit__(self, exc_type, exc_val, exc_t):
         allura.config.middleware.make_app = self._make_app
 
 
+def matching_audits(pattern, **query):
+    """AuditLog entries matching ``query`` whose decrypted message matches the ``pattern`` regex"""
+    pattern = re.compile(pattern)
+    return [entry for entry in M.AuditLog.query.find(query) if pattern.search(entry.message or '')]
+
+
 @contextlib.contextmanager
 def audits(*messages, user=False, actor=r'.*', ip_addr=r'.*', user_agent=r'.*', event_type=None):
     """
@@ -168,12 +174,8 @@ def audits(*messages, user=False, actor=r'.*', ip_addr=r'.*', user_agent=r'.*',
         preamble = ''
 
     for message in messages:
-        query = {}
-        pattern = re.compile(preamble + message)
-        if event_type is not None:
-            query['event_type'] = event_type
-        found = any(pattern.search(entry.message or '') for entry in M.AuditLog.query.find(query))
-        if not found:
+        query = {'event_type': event_type} if event_type is not None else {}
+        if not matching_audits(preamble + message, **query):
             hints = ''
             all = M.AuditLog.query.find().all()
             if len(all) < 10:
@@ -199,9 +201,7 @@ def out_audits(*messages, user=False, actor=r'.*', ip_addr=r'.*'):
     else:
         preamble = ''
     for message in messages:
-        pattern = re.compile(preamble + message)
-        assert not any(pattern.search(entry.message or '') for entry in M.AuditLog.query.find()), (
-            'Found unexpected: "%s"' % message)
+        assert not matching_audits(preamble + message), 'Found unexpected: "%s"' % message
 
 
 # not a decorator but use it with LogCapture() context manager
diff --git a/Allura/allura/tests/model/test_auth.py b/Allura/allura/tests/model/test_auth.py
index 892b3d06b..6071a6cc0 100644
--- a/Allura/allura/tests/model/test_auth.py
+++ b/Allura/allura/tests/model/test_auth.py
@@ -745,7 +745,6 @@ def test_encrypted_message_read_and_update(self):
         entry.url = '/updated'
         session(entry).flush(entry)
         raw = M.main_doc_session.db.audit_log.find_one({'_id': entry_id})
-        assert 'message' not in raw
         assert M.AuditLog.decr(raw['message_encrypted']) == 'add user alice to Developer'
         assert raw['event_type'] == 'project.user_mention.unclassified'
 
diff --git a/ForgeDiscussion/forgediscussion/tests/functional/test_forum_admin.py b/ForgeDiscussion/forgediscussion/tests/functional/test_forum_admin.py
index 8ebb15fae..e00f78f10 100644
--- a/ForgeDiscussion/forgediscussion/tests/functional/test_forum_admin.py
+++ b/ForgeDiscussion/forgediscussion/tests/functional/test_forum_admin.py
@@ -17,7 +17,6 @@
 
 import logging
 
-import re
 from ming.odm import ThreadLocalODMSession
 from tg import tmpl_context as c
 from alluratest.controller import TestController
@@ -55,8 +54,7 @@ def test_forum_CRUD(self):
                                   'forum-0.shortname': 'NewTestForum',
                                   'forum-0.description': 'My desc',
                                   'forum-0.monitoring_email': ''})
-        audit_logs = [entry for entry in M.AuditLog.query.find({'project_id': project._id})
-                      if ' set option ' in (entry.message or '')]
+        audit_logs = td.matching_audits(' set option ', project_id=project._id)
         assert len(audit_logs) == 4
         r = self.app.get('/admin/discussion/forums')
         assert 'New Test Forum' in r


(allura) 02/04: [#8625] Implemented full field level encryption for audit log messages

Posted by cc...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

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

commit da51e53d4a07b81eb700c882302f426815e2553a
Author: Carlos Cruz <ca...@slashdotmedia.com>
AuthorDate: Mon Sep 21 19:37:50 2026 +0000

    [#8625] Implemented full field level encryption for audit log messages
---
 Allura/allura/lib/plugin.py                           | 19 +++++++++++++++++++
 Allura/allura/model/auth.py                           | 10 +++++-----
 Allura/allura/tests/decorators.py                     | 10 ++++++----
 Allura/allura/tests/functional/test_neighborhood.py   |  2 +-
 Allura/allura/tests/model/test_auth.py                | 16 +++++++++-------
 .../tests/functional/test_forum_admin.py              |  3 ++-
 .../forgegit/tests/functional/test_controllers.py     |  6 +++---
 7 files changed, 45 insertions(+), 21 deletions(-)

diff --git a/Allura/allura/lib/plugin.py b/Allura/allura/lib/plugin.py
index 4b100bdb8..60b8f01fd 100644
--- a/Allura/allura/lib/plugin.py
+++ b/Allura/allura/lib/plugin.py
@@ -525,6 +525,25 @@ def details_links(self, user):
     def hibp_password_check_enabled(self):
         return asbool(tg.config.get('auth.hibp_password_check', False))
 
+    @property
+    def trusted_auditlog_event_types(self):
+        return [
+            'auth.login.succeeded',
+            'account.email.primary_changed',
+            'account.email.added',
+            'account.display_name.changed',
+            'account.email.verified',
+            'account.password.changed',
+            'account.email.removed',
+            'account.activated',
+            'account.phone.verified',
+            'account.mfa.setup_viewed',
+            'account.mfa.enabled',
+            'account.mfa.config_viewed',
+            'account.mfa.recovery_codes_viewed',
+            'account.mfa.recovery_codes_regenerated',
+        ]
+
     @property
     def trusted_auditlog_line_prefixes(self):
         return [
diff --git a/Allura/allura/model/auth.py b/Allura/allura/model/auth.py
index 1c866c113..1ef4d7fa8 100644
--- a/Allura/allura/model/auth.py
+++ b/Allura/allura/model/auth.py
@@ -464,8 +464,9 @@ def backfill_login_details(self, auth_provider):
                                                            for line_prefix
                                                            in auth_provider.trusted_auditlog_line_prefixes])),
                                re.MULTILINE | re.DOTALL)
-        for auditlog in AuditLog.for_user(self, message=msg_regex):
-            if not msg_regex.search(auditlog.message):
+        candidate_types = auth_provider.trusted_auditlog_event_types + ['account.event.unclassified']
+        for auditlog in AuditLog.for_user(self, event_type={'$in': candidate_types}):
+            if not msg_regex.search(auditlog.message or ''):
                 continue
             login_detail = auth_provider.login_details_from_auditlog(auditlog)
             if login_detail:
@@ -1126,12 +1127,11 @@ def users_with_role(self, project=None):
 
 
 class AuditLogMapperExtension(MapperExtension):
-    """Dual-write encrypted messages while plaintext remains the source of truth."""
+    """Classify untyped audit messages on inserts and updates."""
 
     def before_insert(self, instance, state, sess):
         if instance.event_type is None and instance.project_id is not None:
             instance.event_type = instance.unclassified_event_type(instance.message, instance.project_id)
-        instance.message_encrypted = instance.encr(instance.message)
 
     def before_update(self, instance, state, sess):
         self.before_insert(instance, state, sess)
@@ -1157,7 +1157,7 @@ class __mongometa__:
     user = RelationProperty('User')
     timestamp = FieldProperty(datetime, if_missing=datetime.utcnow)
     url = FieldProperty(str)
-    message = FieldProperty(str)
+    message = DecryptedProperty(str, 'message_encrypted')
     message_encrypted = FieldProperty(S.Binary, if_missing=None)
     event_type = FieldProperty(str, if_missing=None)
 
diff --git a/Allura/allura/tests/decorators.py b/Allura/allura/tests/decorators.py
index 2f6e90ad3..63d5ae624 100644
--- a/Allura/allura/tests/decorators.py
+++ b/Allura/allura/tests/decorators.py
@@ -168,10 +168,11 @@ def audits(*messages, user=False, actor=r'.*', ip_addr=r'.*', user_agent=r'.*',
         preamble = ''
 
     for message in messages:
-        query = dict(message=re.compile(preamble + message))
+        query = {}
+        pattern = re.compile(preamble + message)
         if event_type is not None:
             query['event_type'] = event_type
-        found = M.AuditLog.query.find(query).count()
+        found = any(pattern.search(entry.message or '') for entry in M.AuditLog.query.find(query))
         if not found:
             hints = ''
             all = M.AuditLog.query.find().all()
@@ -198,8 +199,9 @@ def out_audits(*messages, user=False, actor=r'.*', ip_addr=r'.*'):
     else:
         preamble = ''
     for message in messages:
-        assert not M.AuditLog.query.find(dict(
-            message=re.compile(preamble + message))).count(), 'Found unexpected: "%s"' % message
+        pattern = re.compile(preamble + message)
+        assert not any(pattern.search(entry.message or '') for entry in M.AuditLog.query.find()), (
+            'Found unexpected: "%s"' % message)
 
 
 # not a decorator but use it with LogCapture() context manager
diff --git a/Allura/allura/tests/functional/test_neighborhood.py b/Allura/allura/tests/functional/test_neighborhood.py
index cacaf4386..a08bd7e4a 100644
--- a/Allura/allura/tests/functional/test_neighborhood.py
+++ b/Allura/allura/tests/functional/test_neighborhood.py
@@ -97,7 +97,7 @@ def test_admin(self):
     def test_admin_overview_audit_log(self):
 
         def check_log(message):
-            return M.AuditLog.query.find({'message': message}).count() == 1
+            return M.AuditLog.query.find({'message_encrypted': M.AuditLog.encr(message)}).count() == 1
 
         nbhd = M.Neighborhood.query.get(name='Projects')
         nbhd.features['css'] = 'custom'
diff --git a/Allura/allura/tests/model/test_auth.py b/Allura/allura/tests/model/test_auth.py
index f6fc7961b..6d00eda97 100644
--- a/Allura/allura/tests/model/test_auth.py
+++ b/Allura/allura/tests/model/test_auth.py
@@ -708,10 +708,11 @@ def test_user_backfill_login_details(self):
             # these shouldn't match
             h.auditlog_user('something happened')
             h.auditlog_user('blah blah Password changed')
+            h.auditlog_user('Comment: Account disabled', event_type='account.event.unclassified')
         with h.push_config(r, user_agent='TestBrowser/56'):
             # these should all match, but only one entry created for this ip/ua
             h.auditlog_user('Account activated')
-            h.auditlog_user('Successful login')
+            h.auditlog_user('Successful login', event_type='auth.login.succeeded')
             h.auditlog_user('Password changed')
         with h.push_config(r, user_agent='TestBrowser/57'):
             # this should match too
@@ -736,13 +737,14 @@ def setup_class(cls):
         setup_basic_test()
         setup_global_objects()
 
-    def test_message_dual_write(self):
+    def test_message_encrypted_storage(self):
         entry = M.AuditLog(message='Account disabled', event_type='account.disabled')
         for message in ['Account disabled', 'Account disabled by admin']:
             entry.message = message
             session(entry).flush(entry)
             raw = M.main_doc_session.db.audit_log.find_one({'_id': entry._id})
-            assert raw['message'] == message
+            assert 'message' not in raw
+            assert entry.message == message
             assert isinstance(raw['message_encrypted'], Binary)
             assert M.AuditLog.decr(raw['message_encrypted']) == message
             assert raw['event_type'] == 'account.disabled'
@@ -760,17 +762,17 @@ def test_log_event_type(self, message, arg, project_scoped, event_type, expected
         session(entry).flush(entry)
         assert M.main_doc_session.db.audit_log.find_one({'_id': entry._id})['event_type'] == expected
 
-    def test_legacy_message_read_and_update(self):
+    def test_encrypted_message_read_and_update(self):
         entry_id = ObjectId()
         M.main_doc_session.db.audit_log.insert_one({'_id': entry_id, 'project_id': ObjectId(),
-                                                    'message': 'add user alice to Developer'})
+                                                    'message_encrypted': M.AuditLog.encr('add user alice to Developer')})
         entry = M.AuditLog.query.get(_id=entry_id)
         assert entry.message == 'add user alice to Developer'
         entry.url = '/updated'
         session(entry).flush(entry)
         raw = M.main_doc_session.db.audit_log.find_one({'_id': entry_id})
-        assert raw['message'] == 'add user alice to Developer'
-        assert M.AuditLog.decr(raw['message_encrypted']) == raw['message']
+        assert 'message' not in raw
+        assert M.AuditLog.decr(raw['message_encrypted']) == 'add user alice to Developer'
         assert raw['event_type'] == 'project.user_mention.unclassified'
 
     def test_message_html(self):
diff --git a/ForgeDiscussion/forgediscussion/tests/functional/test_forum_admin.py b/ForgeDiscussion/forgediscussion/tests/functional/test_forum_admin.py
index 459f2c91a..8ebb15fae 100644
--- a/ForgeDiscussion/forgediscussion/tests/functional/test_forum_admin.py
+++ b/ForgeDiscussion/forgediscussion/tests/functional/test_forum_admin.py
@@ -55,7 +55,8 @@ def test_forum_CRUD(self):
                                   'forum-0.shortname': 'NewTestForum',
                                   'forum-0.description': 'My desc',
                                   'forum-0.monitoring_email': ''})
-        audit_logs = M.AuditLog.query.find({'project_id': project._id, 'message': re.compile(' set option ')}).all()
+        audit_logs = [entry for entry in M.AuditLog.query.find({'project_id': project._id})
+                      if ' set option ' in (entry.message or '')]
         assert len(audit_logs) == 4
         r = self.app.get('/admin/discussion/forums')
         assert 'New Test Forum' in r
diff --git a/ForgeGit/forgegit/tests/functional/test_controllers.py b/ForgeGit/forgegit/tests/functional/test_controllers.py
index 8210429f4..fe2122bc0 100644
--- a/ForgeGit/forgegit/tests/functional/test_controllers.py
+++ b/ForgeGit/forgegit/tests/functional/test_controllers.py
@@ -555,12 +555,12 @@ def test_force_push_toggle(self):
             self.app.post('/p/test/admin/src-git/force_push', params={'allowed': 'on'})
             assert GM.Repository.query.get(_id=c.app.repo._id).force_push_allowed is True
             assert M.AuditLog.query.find(
-                {'message': 'src-git: set "force_push_allowed" False => True'}).count() == 1
+                {'message_encrypted': M.AuditLog.encr('src-git: set "force_push_allowed" False => True')}).count() == 1
 
             self.app.post('/p/test/admin/src-git/force_push', params={})
             assert GM.Repository.query.get(_id=c.app.repo._id).force_push_allowed is False
             assert M.AuditLog.query.find(
-                {'message': 'src-git: set "force_push_allowed" True => False'}).count() == 1
+                {'message_encrypted': M.AuditLog.encr('src-git: set "force_push_allowed" True => False')}).count() == 1
 
     def test_force_push_menu_entry(self):
         with h.push_config(tg.config, **{'scm.force_push.git.enabled': 'true'}):
@@ -583,7 +583,7 @@ def test_force_push_save_writes_even_when_unchanged(self):
             assert GM.Repository.query.get(_id=c.app.repo._id).force_push_allowed is False
             post.assert_called_once_with(c.app.repo.full_fs_path, False)
             assert M.AuditLog.query.find(
-                {'message': 'src-git: set "force_push_allowed" False => False'}).count() == 0
+                {'message_encrypted': M.AuditLog.encr('src-git: set "force_push_allowed" False => False')}).count() == 0
 
     def test_force_push_hidden_until_repo_ready(self):
         with h.push_config(tg.config, **{'scm.force_push.git.enabled': 'true'}):


(allura) 01/04: [#8625] Add event types for audit log records

Posted by cc...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

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

commit 6aebb840ae122604a78778c4bacb8f4e0e7b505e
Author: Carlos Cruz <ca...@slashdotmedia.com>
AuthorDate: Thu Sep 17 19:10:19 2026 +0000

    [#8625] Add event types for audit log records
---
 Allura/allura/controllers/auth.py                  | 27 +++++----
 Allura/allura/ext/admin/admin_main.py              |  4 +-
 Allura/allura/lib/plugin.py                        | 16 ++---
 Allura/allura/model/auth.py                        | 16 ++++-
 Allura/allura/scripts/delete_projects.py           |  2 +-
 Allura/allura/scripts/disable_users.py             |  2 +-
 Allura/allura/tests/decorators.py                  |  8 ++-
 Allura/allura/tests/functional/test_admin.py       |  4 +-
 Allura/allura/tests/functional/test_auth.py        | 31 +++++-----
 Allura/allura/tests/functional/test_site_admin.py  |  5 +-
 Allura/allura/tests/model/test_auth.py             | 69 +++++++++-------------
 .../allura/tests/scripts/test_delete_projects.py   |  7 ++-
 Allura/allura/tests/scripts/test_disable_users.py  | 35 +++++++++++
 Allura/allura/tests/test_plugin.py                 |  6 +-
 14 files changed, 141 insertions(+), 91 deletions(-)

diff --git a/Allura/allura/controllers/auth.py b/Allura/allura/controllers/auth.py
index a7c8bb284..4e73b8126 100644
--- a/Allura/allura/controllers/auth.py
+++ b/Allura/allura/controllers/auth.py
@@ -232,7 +232,7 @@ def set_new_password(self, hash=None, pw=None, pw2=None):
         user.set_password(pw)
         user.set_tool_data('AuthPasswordReset', hash='', hash_expiry='')  # Clear password reset token
         user.set_tool_data('allura', pwd_reset_preserve_session=session.id)
-        h.auditlog_user('Password changed (through recovery process)', user=user)
+        h.auditlog_user('Password changed (through recovery process)', user=user, event_type='account.password.changed')
         email_body = g.jinja2_env.get_template('allura:templates/mail/password_changed.md.jinja2').render(dict(
             user=user,
             config=config
@@ -365,7 +365,7 @@ def _verify_addr(self, addr, do_auth_check=True):
             addr.confirmed = True
             addr.confirmed_date = datetime.utcnow()
             flash('Email address confirmed')
-            h.auditlog_user('Email address verified: %s',  addr.email, user=user)
+            h.auditlog_user('Email address verified: %s', addr.email, user=user, event_type='account.email.verified')
             if user.get_pref('email_address') is None:
                 user.set_pref('email_address', addr.email)
             if user.pending:
@@ -740,7 +740,8 @@ def _update_emails(self, user, admin=False, form_params={}):
                         user.set_pref('email_address', None)
                         primary_addr = None
                         user.set_tool_data('AuthPasswordReset', hash='', hash_expiry='')
-                h.auditlog_user('Email address deleted: %s', user.email_addresses[i], user=user)
+                h.auditlog_user('Email address deleted: %s', user.email_addresses[i], user=user,
+                                event_type='account.email.removed')
                 if not admin:
                     email_body = g.jinja2_env.get_template('allura:templates/mail/email_removed.md.jinja2').render(dict(
                         user=user,
@@ -785,7 +786,8 @@ def _update_emails(self, user, admin=False, form_params={}):
                         user.set_tool_data('AuthPasswordReset', hash='', hash_expiry='')
                         flash('A verification email has been sent.  Please check your email and click to confirm.')
 
-                    h.auditlog_user('New email address: %s', new_addr['addr'], user=user)
+                    h.auditlog_user('New email address: %s', new_addr['addr'], user=user,
+                                    event_type='account.email.added')
                 else:
                     flash('Email address %s is invalid' % new_addr['addr'], 'error')
             else:
@@ -801,7 +803,7 @@ def _update_emails(self, user, admin=False, form_params={}):
                     'Primary email changed: %s => %s',
                     user.get_pref('email_address'),
                     primary_addr,
-                    user=user)
+                    user=user, event_type='account.email.primary_changed')
                 if not admin:
                     email_body = g.jinja2_env.get_template('allura:templates/mail/primary_email_changed.md.jinja2').render(
                         dict(user=user, config=config, addr=primary_addr))
@@ -834,7 +836,8 @@ def update(self, preferences=None, **kw):
             old = c.user.get_pref('display_name')
             c.user.set_pref('display_name', preferences['display_name'])
             if old != preferences['display_name']:
-                h.auditlog_user('Display Name changed %s => %s', old, preferences['display_name'])
+                h.auditlog_user('Display Name changed %s => %s', old, preferences['display_name'],
+                                event_type='account.display_name.changed')
 
             for k, v in preferences.items():
                 if k == 'results_per_page':
@@ -860,7 +863,7 @@ def change_password(self, **kw):
             flash('Incorrect password', 'error')
             redirect('.')
         flash('Password changed')
-        h.auditlog_user('Password changed')
+        h.auditlog_user('Password changed', event_type='account.password.changed')
         email_body = g.jinja2_env.get_template('allura:templates/mail/password_changed.md.jinja2').render(dict(
             user=c.user,
             config=config,
@@ -907,7 +910,7 @@ def totp_new(self, **kw):
 
         qr = totp_service.get_qr_code(totp, c.user)
         key_b32 = b32encode(totp.key).decode('ascii')
-        h.auditlog_user('Visited multifactor new TOTP page')
+        h.auditlog_user('Visited multifactor new TOTP page', event_type='account.mfa.setup_viewed')
         provider = plugin.AuthenticationProvider.get(request)
 
         return dict(
@@ -928,7 +931,7 @@ def totp_view(self, **kw):
         totp = totp_service.get_totp(c.user)
         qr = totp_service.get_qr_code(totp, c.user)
         key_b32 = b32encode(totp.key).decode('ascii')
-        h.auditlog_user('Viewed multifactor TOTP config page')
+        h.auditlog_user('Viewed multifactor TOTP config page', event_type='account.mfa.config_viewed')
         provider = plugin.AuthenticationProvider.get(request)
 
         return dict(
@@ -956,7 +959,7 @@ def totp_set(self, code, **kw):
             request.validation.errors['code'] = 'Invalid code, please try again.'
             return self.totp_new(**kw)
         else:
-            h.auditlog_user('Set up multifactor TOTP')
+            h.auditlog_user('Set up multifactor TOTP', event_type='account.mfa.enabled')
             totp_service.set_secret_key(c.user, key)
             c.user.set_pref('multifactor', True)
             c.user.set_tool_data('allura', multifactor_date=datetime.utcnow())
@@ -1016,7 +1019,7 @@ def multifactor_recovery(self, **kw):
         codes = recovery.get_codes(c.user)
         if not codes:
             codes = recovery.regenerate_codes(c.user)
-        h.auditlog_user('Viewed multifactor recovery codes')
+        h.auditlog_user('Viewed multifactor recovery codes', event_type='account.mfa.recovery_codes_viewed')
         provider = plugin.AuthenticationProvider.get(request)
 
         windows_line_endings = "WINDOWS" in request.headers.get('USER_AGENT', '').upper()
@@ -1040,7 +1043,7 @@ def multifactor_recovery_regen(self, **kw):
             user=c.user,
             config=config,
         ))
-        h.auditlog_user('Regenerated multifactor recovery codes')
+        h.auditlog_user('Regenerated multifactor recovery codes', event_type='account.mfa.recovery_codes_regenerated')
         send_system_mail_to_user(c.user, 'Two-Factor Recovery Codes Regenerated', email_body)
         tg.flash('Your recovery codes have been regenerated.  Save the new codes!')
         redirect('/auth/preferences/multifactor_recovery')
diff --git a/Allura/allura/ext/admin/admin_main.py b/Allura/allura/ext/admin/admin_main.py
index f436e5f22..25f2a6312 100644
--- a/Allura/allura/ext/admin/admin_main.py
+++ b/Allura/allura/ext/admin/admin_main.py
@@ -1212,7 +1212,7 @@ def add_user(self, role_id, username, **kw):
         user_role = M.ProjectRole.by_user(user, upsert=True)
         if group._id in user_role.roles:
             return dict(error=f'{user.display_name} ({username}) is already in the group {group.name}.')
-        M.AuditLog.log('add user %s to %s', username, group.name)
+        M.AuditLog.log('add user %s to %s', username, group.name, event_type='project.member.added')
         user_role.roles.append(group._id)
         if group.name == 'Admin':
             for ac in c.project.app_configs:
@@ -1236,7 +1236,7 @@ def remove_user(self, role_id, username, **kw):
         user_role = M.ProjectRole.by_user(user)
         if not user_role or group._id not in user_role.roles:
             return dict(error=f'{user.display_name} ({username}) is not in the group {group.name}.')
-        M.AuditLog.log('remove user %s from %s', username, group.name)
+        M.AuditLog.log('remove user %s from %s', username, group.name, event_type='project.member.removed')
         user_role.roles.remove(group._id)
         if len(user_role.roles) == 0:
             # user has no roles in this project any more, so don't leave a useless doc around
diff --git a/Allura/allura/lib/plugin.py b/Allura/allura/lib/plugin.py
index 4c7cc389c..4b100bdb8 100644
--- a/Allura/allura/lib/plugin.py
+++ b/Allura/allura/lib/plugin.py
@@ -249,7 +249,7 @@ def login(self, user: M.User = None, multifactor_success: bool = False, email_ve
 
         expire_reason = None
         if self.is_password_expired(user):
-            h.auditlog_user(f'{auditlog_msg}; Password expired', user=user)
+            h.auditlog_user(f'{auditlog_msg}; Password expired', user=user, event_type='auth.login.succeeded')
             expire_reason = 'via expiration process'
         if not expire_reason:
             expire_reason = self.login_check_password_change_needed(user, self.request.params.get('password'),
@@ -260,7 +260,7 @@ def login(self, user: M.User = None, multifactor_success: bool = False, email_ve
             self.session['expired-reason'] = expire_reason
         else:
             self.session['username'] = user.username
-            h.auditlog_user(auditlog_msg, user=user)
+            h.auditlog_user(auditlog_msg, user=user, event_type='auth.login.succeeded')
 
         if not skip_after_login:
             self.after_login(user, self.request)
@@ -315,7 +315,7 @@ def login_check_password_change_needed(self, user: M.User, password: str | None,
             if trusted:
                 # current user must change password
                 h.auditlog_user(f'Successful login but {reason}, '
-                                f'from trusted source (reason: {trusted})', user=user)
+                                f'from trusted source (reason: {trusted})', user=user, event_type='auth.login.succeeded')
                 return reason_code
             else:
                 # current user may not continue, must reset password via email
@@ -668,19 +668,19 @@ def disable_user(self, user, **kw):
         user.disabled = True
         session(user).flush(user)
         if kw.get('audit', True):
-            h.auditlog_user('Account disabled', user=user)
+            h.auditlog_user('Account disabled', user=user, event_type='account.disabled')
 
     def enable_user(self, user, **kw):
         user.disabled = False
         session(user).flush(user)
         if kw.get('audit', True):
-            h.auditlog_user('Account enabled', user=user)
+            h.auditlog_user('Account enabled', user=user, event_type='account.enabled')
 
     def activate_user(self, user, **kw):
         user.pending = False
         session(user).flush(user)
         if kw.get('audit', True):
-            h.auditlog_user('Account activated', user=user)
+            h.auditlog_user('Account activated', user=user, event_type='account.activated')
 
     def deactivate_user(self, user, **kw):
         user.pending = True
@@ -1095,7 +1095,7 @@ def check_phone_verification(self, user, request_id, pin, number_hash):
         if res.get('status') == 'ok':
             user.set_tool_data('phone_verification', number_hash=number_hash)
             msg = f'Phone verification succeeded. Hash: {number_hash}'
-            h.auditlog_user(msg, user=user)
+            h.auditlog_user(msg, user=user, event_type='account.phone.verified')
         else:
             msg = f'Phone verification failed. Hash: {number_hash}'
             h.auditlog_user(msg, user=user)
@@ -1374,7 +1374,7 @@ def disable_project_users(self, project, reason=None):
                 project.neighborhood.url_prefix,
                 project.shortname,
                 reason)
-            auditlog = h.auditlog_user(msg, user=user)
+            auditlog = h.auditlog_user(msg, user=user, event_type='account.disabled')
             if auditlog:
                 session(auditlog).flush(auditlog)
             else:
diff --git a/Allura/allura/model/auth.py b/Allura/allura/model/auth.py
index b4cfb58b1..1c866c113 100644
--- a/Allura/allura/model/auth.py
+++ b/Allura/allura/model/auth.py
@@ -1129,10 +1129,12 @@ class AuditLogMapperExtension(MapperExtension):
     """Dual-write encrypted messages while plaintext remains the source of truth."""
 
     def before_insert(self, instance, state, sess):
+        if instance.event_type is None and instance.project_id is not None:
+            instance.event_type = instance.unclassified_event_type(instance.message, instance.project_id)
         instance.message_encrypted = instance.encr(instance.message)
 
     def before_update(self, instance, state, sess):
-        instance.message_encrypted = instance.encr(instance.message)
+        self.before_insert(instance, state, sess)
 
 
 class AuditLog(MappedClass):
@@ -1143,6 +1145,7 @@ class __mongometa__:
         indexes = [
             'project_id',
             'user_id',
+            'event_type',
         ]
 
     query: Query[AuditLog]
@@ -1156,6 +1159,14 @@ class __mongometa__:
     url = FieldProperty(str)
     message = FieldProperty(str)
     message_encrypted = FieldProperty(S.Binary, if_missing=None)
+    event_type = FieldProperty(str, if_missing=None)
+
+    @staticmethod
+    def unclassified_event_type(message: str | None, project_id: ObjectId | None) -> str | None:
+        """Mark possible username mentions for later target-specific redaction."""
+        if project_id is not None and message and re.search(r' user \S+ ', message):
+            return 'project.user_mention.unclassified'
+        return None
 
     @property
     def timestamp_str(self):
@@ -1193,6 +1204,7 @@ def log(cls, message, *args, **kwargs):
         project = kwargs.pop('project') if 'project' in kwargs else c.project
         user = kwargs.pop('user', c.user)
         url = kwargs.pop('url', '')
+        event_type = kwargs.pop('event_type', None)
         if not url:
             try:
                 url = request.url
@@ -1205,7 +1217,7 @@ def log(cls, message, *args, **kwargs):
         pid = project._id if project is not None else None
         if pid is None and user is None or user.is_anonymous():
             return
-        return cls(project_id=pid, user_id=user._id, url=url, message=message)
+        return cls(project_id=pid, user_id=user._id, url=url, message=message, event_type=event_type)
 
     @classmethod
     def for_user(cls, user, **kwargs):
diff --git a/Allura/allura/scripts/delete_projects.py b/Allura/allura/scripts/delete_projects.py
index 374a7237b..e18162b62 100644
--- a/Allura/allura/scripts/delete_projects.py
+++ b/Allura/allura/scripts/delete_projects.py
@@ -46,7 +46,7 @@ def execute(cls, options):
                         auth_provider.disable_user(user, audit=False)
                         msg = 'Account disabled because user-project was specified for deletion. Reason: {}'.format(
                             options.reason)
-                        log_entry = h.auditlog_user(msg, user=user)
+                        log_entry = h.auditlog_user(msg, user=user, event_type='account.disabled')
                         session(log_entry).flush(log_entry)
                     else:
                         log.info('Could not find associated user for user-project %s', proj.shortname)
diff --git a/Allura/allura/scripts/disable_users.py b/Allura/allura/scripts/disable_users.py
index a5a2f0f99..ed681d239 100644
--- a/Allura/allura/scripts/disable_users.py
+++ b/Allura/allura/scripts/disable_users.py
@@ -58,7 +58,7 @@ def disable_users(cls, usernames, message):
                 auth_provider.disable_user(user)
                 session(user).flush(user)
                 if message:
-                    log_entry = h.auditlog_user(message, user=user)
+                    log_entry = h.auditlog_user(message, user=user, event_type='account.disabled')
                     session(log_entry).flush(log_entry)
 
     @classmethod
diff --git a/Allura/allura/tests/decorators.py b/Allura/allura/tests/decorators.py
index f72c15648..2f6e90ad3 100644
--- a/Allura/allura/tests/decorators.py
+++ b/Allura/allura/tests/decorators.py
@@ -151,12 +151,13 @@ def __exit__(self, exc_type, exc_val, exc_t):
 
 
 @contextlib.contextmanager
-def audits(*messages, user=False, actor=r'.*', ip_addr=r'.*', user_agent=r'.*'):
+def audits(*messages, user=False, actor=r'.*', ip_addr=r'.*', user_agent=r'.*', event_type=None):
     """
     Asserts all the messages exist in audit log
 
     :param messages: regex strings
     :param bool user: if this is a user log
+    :param event_type: optionally require this event type for each matching message
 
     """
     M.AuditLog.query.remove()
@@ -167,7 +168,10 @@ def audits(*messages, user=False, actor=r'.*', ip_addr=r'.*', user_agent=r'.*'):
         preamble = ''
 
     for message in messages:
-        found = M.AuditLog.query.find(dict(message=re.compile(preamble + message))).count()
+        query = dict(message=re.compile(preamble + message))
+        if event_type is not None:
+            query['event_type'] = event_type
+        found = M.AuditLog.query.find(query).count()
         if not found:
             hints = ''
             all = M.AuditLog.query.find().all()
diff --git a/Allura/allura/tests/functional/test_admin.py b/Allura/allura/tests/functional/test_admin.py
index a87eb6d42..e8a1e922a 100644
--- a/Allura/allura/tests/functional/test_admin.py
+++ b/Allura/allura/tests/functional/test_admin.py
@@ -721,14 +721,14 @@ def check_roles(r):
             'table', {'id': 'usergroup_admin'}).find_all('tr')[1]
         admin_id = admin_holder['data-group']
         # test that subroles are intact after user added
-        with audits('add user test-user to Admin'):
+        with audits('add user test-user to Admin', event_type='project.member.added'):
             r = self.app.post('/admin/groups/add_user', params={
                 'role_id': admin_id,
                 'username': 'test-user'})
         r = self.app.get('/admin/groups/')
         check_roles(r)
         # test that subroles are intact after user deleted
-        with audits('remove user test-user from Admin'):
+        with audits('remove user test-user from Admin', event_type='project.member.removed'):
             r = self.app.post('/admin/groups/remove_user', params={
                 'role_id': admin_id,
                 'username': 'test-user'})
diff --git a/Allura/allura/tests/functional/test_auth.py b/Allura/allura/tests/functional/test_auth.py
index 204dbca37..0d6d974e0 100644
--- a/Allura/allura/tests/functional/test_auth.py
+++ b/Allura/allura/tests/functional/test_auth.py
@@ -82,10 +82,11 @@ def test_login(self):
         r = self.app.get('/auth/verify_addr', params=dict(a='foo'))
         assert json.loads(self.webflash(r))['status'] == 'error', self.webflash(r)
         ea = M.EmailAddress.find({'email': email}).first()
-        r = self.app.get('/auth/verify_addr', params=dict(a=ea.nonce))
-        assert json.loads(self.webflash(r))['status'] == 'ok', self.webflash(r)
+        with audits('Email address verified:', user=True, event_type='account.email.verified'):
+            r = self.app.get('/auth/verify_addr', params=dict(a=ea.nonce))
+            assert json.loads(self.webflash(r))['status'] == 'ok', self.webflash(r)
 
-        with audits('Successful login', user=True):
+        with audits('Successful login', user=True, event_type='auth.login.succeeded'):
             r = self.app.post('/auth/do_login', params=dict(
                 username='test-user', password='foo',
                 _csrf_token=self.app.cookies['_csrf_token']),
@@ -197,7 +198,7 @@ def test_login_hibp_compromised_password_trusted_client(self, sendsimplemail):
             f[encoded['password']] = 'foo'
 
             with audits(r'Successful login but password in HIBP breach database, from trusted source '
-                        r'\(reason: exact ip\)', user=True):
+                        r'\(reason: exact ip\)', user=True, event_type='auth.login.succeeded'):
                 r = f.submit(status=302)
 
             assert r.session.get('pwd-expired')
@@ -732,7 +733,7 @@ def test_change_password(self):
         old_pass = user.get_pref('password')
 
         # Change password
-        with audits('Password changed', user=True):
+        with audits('Password changed', user=True, event_type='account.password.changed'):
             self.app.post('/auth/preferences/change_password',
                           extra_environ=dict(username='test-admin'),
                           params={
@@ -802,7 +803,7 @@ def test_prefs(self, gen_message_id, sendsimplemail):
                 'test-admin@users.localhost')
 
         # add test@example
-        with td.audits('New email address: test@example.com', user=True):
+        with td.audits('New email address: test@example.com', user=True, event_type='account.email.added'):
             r = self.app.post('/auth/preferences/update_emails',
                               extra_environ=dict(username='test-admin'),
                               params={
@@ -819,7 +820,8 @@ def test_prefs(self, gen_message_id, sendsimplemail):
         assert user.get_pref('email_address') == 'test-admin@users.localhost'
 
         # remove test-admin@users.localhost
-        with td.audits('Email address deleted: test-admin@users.localhost', user=True):
+        with td.audits('Email address deleted: test-admin@users.localhost', user=True,
+                       event_type='account.email.removed'):
             r = self.app.post('/auth/preferences/update_emails',
                               extra_environ=dict(username='test-admin'),
                               params={
@@ -844,7 +846,7 @@ def test_prefs(self, gen_message_id, sendsimplemail):
         user = M.User.query.get(username='test-admin')
         assert user.get_pref('email_address') is None
 
-        with td.audits('Display Name changed Test Admin => Admin', user=True):
+        with td.audits('Display Name changed Test Admin => Admin', user=True, event_type='account.display_name.changed'):
             r = self.app.post('/auth/preferences/update',
                               params={'preferences.display_name': 'Admin',
                                       '_csrf_token': self.app.cookies['_csrf_token'],
@@ -1943,7 +1945,7 @@ def test_password_reset(self, gen_message_id, sendsimplemail):
         # fill it out correctly
         form = r.forms[0]
         form['pw'] = form['pw2'] = new_password = '154321'
-        with td.audits(r'Password changed \(through recovery process\)', user=True):
+        with td.audits(r'Password changed \(through recovery process\)', user=True, event_type='account.password.changed'):
             # escape parentheses, so they would not be treated as regex group
             r = form.submit()
 
@@ -3179,7 +3181,7 @@ def test_enable_totp(self):
             r = self.app.get('/auth/preferences/totp_new')
             assert 'Password Confirmation' in r
 
-        with audits('Visited multifactor new TOTP page', user=True):
+        with audits('Visited multifactor new TOTP page', user=True, event_type='account.mfa.setup_viewed'):
             r.form['password'] = 'foo'
             r = r.form.submit()
             assert 'Scan this' in r
@@ -3199,7 +3201,7 @@ def test_enable_totp(self):
         code = new_totp.generate(time_time())
         form = r.forms['totp_set']
         form['code'] = code
-        with audits('Set up multifactor TOTP', user=True):
+        with audits('Set up multifactor TOTP', user=True, event_type='account.mfa.enabled'):
             r = form.submit()
             msg = 'Two factor authentication has now been set up.'
             assert msg == json.loads(self.webflash(r))['message'], self.webflash(r)
@@ -3582,7 +3584,7 @@ def test_view_key(self):
             r = self.app.get('/auth/preferences/totp_view')
             assert 'Password Confirmation' in r
 
-        with audits('Viewed multifactor TOTP config page', user=True):
+        with audits('Viewed multifactor TOTP config page', user=True, event_type='account.mfa.config_viewed'):
             r.form['password'] = 'foo'
             r = r.form.submit()
             assert 'Scan this' in r
@@ -3597,14 +3599,15 @@ def test_view_recovery_codes_and_regen(self):
             assert 'Password Confirmation' in r
 
         # actual visit
-        with audits('Viewed multifactor recovery codes', user=True):
+        with audits('Viewed multifactor recovery codes', user=True, event_type='account.mfa.recovery_codes_viewed'):
             r.form['password'] = 'foo'
             r = r.form.submit()
             assert 'Download' in r
             assert 'Print' in r
 
         # regenerate codes
-        with audits('Regenerated multifactor recovery codes', user=True):
+        with audits('Regenerated multifactor recovery codes', user=True,
+                    event_type='account.mfa.recovery_codes_regenerated'):
             r = r.forms['multifactor_recovery_regen'].submit()
 
         # email confirmation
diff --git a/Allura/allura/tests/functional/test_site_admin.py b/Allura/allura/tests/functional/test_site_admin.py
index ae3b358f4..6daf212db 100644
--- a/Allura/allura/tests/functional/test_site_admin.py
+++ b/Allura/allura/tests/functional/test_site_admin.py
@@ -584,7 +584,7 @@ def test_enable_user(self):
         assert form['username'].value == 'test-user-3'
         assert form['status'].value == 'pending'
         form['status'].value = 'enable'
-        with td.audits('Account activated', user=True):
+        with td.audits('Account activated', user=True, event_type='account.activated'):
             r = form.submit()
             assert M.AuditLog.query.find().count() == 1
         assert 'User enabled' in self.webflash(r)
@@ -680,7 +680,8 @@ def test_emails(self):
         assert user.get_pref('email_address') == 'test@example.com'
 
         # change primary: test -> test2
-        with td.audits('Primary email changed: test@example.com => test2@example.com', user=True):
+        with td.audits('Primary email changed: test@example.com => test2@example.com', user=True,
+                       event_type='account.email.primary_changed'):
             r = self.app.post('/nf/admin/user/update_emails', params={
                 'username': 'test-user',
                 'new_addr.addr': '',
diff --git a/Allura/allura/tests/model/test_auth.py b/Allura/allura/tests/model/test_auth.py
index 36081140e..f6fc7961b 100644
--- a/Allura/allura/tests/model/test_auth.py
+++ b/Allura/allura/tests/model/test_auth.py
@@ -19,7 +19,6 @@
 Model tests for auth
 """
 
-import re
 import textwrap
 from datetime import datetime, timedelta
 
@@ -737,57 +736,45 @@ def setup_class(cls):
         setup_basic_test()
         setup_global_objects()
 
-    @pytest.mark.parametrize('message', ['IP Address: 192.0.2.1\nName: Carlos', '', None])
-    def test_dual_write_on_insert(self, message):
-        entry = M.AuditLog(message=message)
-        session(entry).flush(entry)
-
-        raw = M.main_doc_session.db.audit_log.find_one({'_id': entry._id})
-        assert raw['message'] == message
-        assert raw['message_encrypted'] == M.AuditLog.encr(message)
-        assert M.AuditLog.decr(raw['message_encrypted']) == message
-        if message is not None:
+    def test_message_dual_write(self):
+        entry = M.AuditLog(message='Account disabled', event_type='account.disabled')
+        for message in ['Account disabled', 'Account disabled by admin']:
+            entry.message = message
+            session(entry).flush(entry)
+            raw = M.main_doc_session.db.audit_log.find_one({'_id': entry._id})
+            assert raw['message'] == message
             assert isinstance(raw['message_encrypted'], Binary)
-        assert M.AuditLog.query.get(_id=entry._id, message=message) is entry
-
-    def test_dual_write_on_update(self):
-        entry = M.AuditLog(message='add user alice to Admin')
-        session(entry).flush(entry)
-        original_ciphertext = entry.message_encrypted
-
-        entry.message = 'add user <REDACTED> to Admin'
+            assert M.AuditLog.decr(raw['message_encrypted']) == message
+            assert raw['event_type'] == 'account.disabled'
+
+    @pytest.mark.parametrize('message, arg, project_scoped, event_type, expected', [
+        ('About user %s here', 'alice', True, None, 'project.user_mention.unclassified'),
+        ('Comment: %s', 'Account disabled', False, None, None),
+        ('Updated %s', 'description', True, None, None),
+        ('Successful login %s', 'via password', False, 'auth.login.succeeded', 'auth.login.succeeded'),
+    ])
+    def test_log_event_type(self, message, arg, project_scoped, event_type, expected):
+        entry = M.AuditLog.log(message, arg, user=c.user,
+                              project=c.project if project_scoped else None,
+                              event_type=event_type, url='/test')
         session(entry).flush(entry)
-        entry_id = entry._id
-        session(entry).expunge(entry)
-
-        entry = M.AuditLog.query.get(_id=entry_id)
-        assert entry.message == 'add user <REDACTED> to Admin'
-        assert entry.message_encrypted != original_ciphertext
-        assert M.AuditLog.decr(entry.message_encrypted) == entry.message
-        assert M.AuditLog.query.find({
-            '_id': entry_id, 'message': re.compile(r'user <REDACTED>'),
-        }).count() == 1
+        assert M.main_doc_session.db.audit_log.find_one({'_id': entry._id})['event_type'] == expected
 
     def test_legacy_message_read_and_update(self):
         entry_id = ObjectId()
-        collection = M.main_doc_session.db.audit_log
-        collection.insert_one({'_id': entry_id, 'message': 'Legacy message'})
-
+        M.main_doc_session.db.audit_log.insert_one({'_id': entry_id, 'project_id': ObjectId(),
+                                                    'message': 'add user alice to Developer'})
         entry = M.AuditLog.query.get(_id=entry_id)
-        assert entry.message == 'Legacy message'
-        assert entry.message_encrypted is None
-        assert 'message_encrypted' not in collection.find_one({'_id': entry_id})
-
+        assert entry.message == 'add user alice to Developer'
         entry.url = '/updated'
         session(entry).flush(entry)
-        raw = collection.find_one({'_id': entry_id})
-        assert raw['message'] == 'Legacy message'
-        assert M.AuditLog.decr(raw['message_encrypted']) == 'Legacy message'
+        raw = M.main_doc_session.db.audit_log.find_one({'_id': entry_id})
+        assert raw['message'] == 'add user alice to Developer'
+        assert M.AuditLog.decr(raw['message_encrypted']) == raw['message']
+        assert raw['event_type'] == 'project.user_mention.unclassified'
 
     def test_message_html(self):
         al = h.auditlog_user('our message <script>alert(1)</script>')
-        session(al).flush(al)
-        assert M.AuditLog.decr(al.message_encrypted) == al.message
         assert al.message == textwrap.dedent('''\
             IP Address: 127.0.0.1
             User-Agent: None
diff --git a/Allura/allura/tests/scripts/test_delete_projects.py b/Allura/allura/tests/scripts/test_delete_projects.py
index 0716cc700..7cfb330a2 100644
--- a/Allura/allura/tests/scripts/test_delete_projects.py
+++ b/Allura/allura/tests/scripts/test_delete_projects.py
@@ -106,7 +106,9 @@ def test_userproject_does_disable(self, req, req2):
         req.user_agent = 'MozFoo'
         req2.url = None
         self.run_script(['u/test-user'])
-        assert M.User.by_username('test-user').disabled
+        user = M.User.by_username('test-user')
+        assert user.disabled
+        assert M.AuditLog.for_user(user, event_type='account.disabled').count() == 1
 
     @patch.object(plugin.g, 'post_event', autospec=True)
     def test_event_is_fired(self, post_event):
@@ -144,6 +146,9 @@ def _disable_users(self, disable):
         dev = M.User.by_username('test-user')
         assert admin.disabled is disable
         assert dev.disabled is disable
+        if disable:
+            for user in (admin, dev):
+                assert M.AuditLog.for_user(user, event_type='account.disabled').count() == 1
 
     @patch('allura.model.auth.request')
     @patch('allura.lib.helpers.request')
diff --git a/Allura/allura/tests/scripts/test_disable_users.py b/Allura/allura/tests/scripts/test_disable_users.py
new file mode 100644
index 000000000..fb9edf621
--- /dev/null
+++ b/Allura/allura/tests/scripts/test_disable_users.py
@@ -0,0 +1,35 @@
+#       Licensed to the Apache Software Foundation (ASF) under one
+#       or more contributor license agreements.  See the NOTICE file
+#       distributed with this work for additional information
+#       regarding copyright ownership.  The ASF licenses this file
+#       to you under the Apache License, Version 2.0 (the
+#       "License"); you may not use this file except in compliance
+#       with the License.  You may obtain a copy of the License at
+#
+#         http://www.apache.org/licenses/LICENSE-2.0
+#
+#       Unless required by applicable law or agreed to in writing,
+#       software distributed under the License is distributed on an
+#       "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+#       KIND, either express or implied.  See the License for the
+#       specific language governing permissions and limitations
+#       under the License.
+
+from ming.odm import ThreadLocalODMSession
+
+from allura import model as M
+from allura.scripts.disable_users import DisableUsers
+from allura.tests.decorators import audits
+from alluratest.controller import setup_basic_test, setup_global_objects
+
+
+class TestDisableUsers:
+    def setup_method(self):
+        setup_basic_test()
+        setup_global_objects()
+
+    def test_event_type(self):
+        with audits('Account disabled', 'Spam account', user=True, event_type='account.disabled'):
+            DisableUsers.disable_users(['test-user'], 'Spam account')
+            ThreadLocalODMSession.flush_all()
+        assert M.User.by_username('test-user').disabled
diff --git a/Allura/allura/tests/test_plugin.py b/Allura/allura/tests/test_plugin.py
index cde5ba0ec..b1ed24b59 100644
--- a/Allura/allura/tests/test_plugin.py
+++ b/Allura/allura/tests/test_plugin.py
@@ -253,7 +253,7 @@ def test_check_phone_verification_success(self, g, audit):
                 self.user.get_tool_data('phone_verification', 'number_hash') ==
                 'hash')
             audit.assert_called_once_with(
-                'Phone verification succeeded. Hash: hash', user=self.user)
+                'Phone verification succeeded. Hash: hash', user=self.user, event_type='account.phone.verified')
 
     @patch.object(plugin, 'g')
     def test_verify_phone_max_limit_not_reached(self, g):
@@ -771,7 +771,7 @@ def test_get_last_password_updated(self):
     def test_enable_user(self):
         user = Mock(disabled=True, __ming__=Mock(), is_anonymous=lambda: False, _id=ObjectId())
         c.user = Mock(username='test-admin')
-        with audits('Account enabled', user=True, actor='test-admin'):
+        with audits('Account enabled', user=True, actor='test-admin', event_type='account.enabled'):
             self.provider.enable_user(user)
             ThreadLocalODMSession.flush_all()
         assert user.disabled is False
@@ -779,7 +779,7 @@ def test_enable_user(self):
     def test_disable_user(self):
         user = Mock(disabled=False, __ming__=Mock(), is_anonymous=lambda: False, _id=ObjectId())
         c.user = Mock(username='test-admin')
-        with audits('Account disabled', user=True, actor='test-admin'):
+        with audits('Account disabled', user=True, actor='test-admin', event_type='account.disabled'):
             self.provider.disable_user(user)
             ThreadLocalODMSession.flush_all()
         assert user.disabled is True


(allura) 03/04: fixup! [#8625] Implemented full field level encryption for audit log messages

Posted by cc...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

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

commit 9a8ff1d6db761316a996e31fba55a387842fc358
Author: Carlos Cruz <ca...@slashdotmedia.com>
AuthorDate: Tue Oct 13 12:55:58 2026 +0000

    fixup! [#8625] Implemented full field level encryption for audit log messages
    
    Remove the obsolete login details backfill
    
    Review: backfill_previous_login_details.py was a one-time upgrade step from
    Allura 1.11 (2019). Login details have been recorded on every login since
    then, so remove the script, User.backfill_login_details() and the
    AuthenticationProvider members only it used: trusted_auditlog_event_types,
    trusted_auditlog_line_prefixes and login_details_from_auditlog(), along with
    their tests. Allura no longer queries audit logs by event type.
---
 Allura/allura/lib/plugin.py                        | 55 ---------------------
 Allura/allura/model/auth.py                        | 15 ------
 .../scripts/backfill_previous_login_details.py     | 57 ----------------------
 Allura/allura/tests/model/test_auth.py             | 28 +----------
 Allura/allura/tests/test_plugin.py                 | 29 -----------
 5 files changed, 1 insertion(+), 183 deletions(-)

diff --git a/Allura/allura/lib/plugin.py b/Allura/allura/lib/plugin.py
index 60b8f01fd..fd1d64268 100644
--- a/Allura/allura/lib/plugin.py
+++ b/Allura/allura/lib/plugin.py
@@ -525,61 +525,6 @@ def details_links(self, user):
     def hibp_password_check_enabled(self):
         return asbool(tg.config.get('auth.hibp_password_check', False))
 
-    @property
-    def trusted_auditlog_event_types(self):
-        return [
-            'auth.login.succeeded',
-            'account.email.primary_changed',
-            'account.email.added',
-            'account.display_name.changed',
-            'account.email.verified',
-            'account.password.changed',
-            'account.email.removed',
-            'account.activated',
-            'account.phone.verified',
-            'account.mfa.setup_viewed',
-            'account.mfa.enabled',
-            'account.mfa.config_viewed',
-            'account.mfa.recovery_codes_viewed',
-            'account.mfa.recovery_codes_regenerated',
-        ]
-
-    @property
-    def trusted_auditlog_line_prefixes(self):
-        return [
-            "Successful login",  # this is the main one
-            # all others are to include login activity before mid-2017 when "Successful login" logs were introduced:
-            "Primary email changed",
-            "New email address:",
-            "Display Name changed",
-            "Email address verified:",
-            "Password changed",
-            "Email address deleted:",
-            "Account activated",
-            "Phone verification succeeded.",
-            "Visited multifactor new TOTP page",
-            "Set up multifactor TOTP",
-            "Viewed multifactor TOTP config page",
-            "Viewed multifactor recovery codes",
-            "Regenerated multifactor recovery codes",
-        ]
-
-    def login_details_from_auditlog(self, auditlog):
-        from allura import model as M
-        ip = ua = None
-        matches = re.search(r'^IP Address: (.+)\n', auditlog.message, re.MULTILINE)
-        if matches:
-            ip = matches.group(1)
-        matches = re.search(r'^User-Agent: (.+)\n', auditlog.message, re.MULTILINE)
-        if matches:
-            ua = matches.group(1)
-        if ua or ip:
-            return M.UserLoginDetails(
-                user_id=auditlog.user_id,
-                ip=ip,
-                ua=ua,
-            )
-
     def get_login_detail(self, request, user):
         from allura import model as M
         return M.UserLoginDetails(
diff --git a/Allura/allura/model/auth.py b/Allura/allura/model/auth.py
index 1ef4d7fa8..5b1bedd76 100644
--- a/Allura/allura/model/auth.py
+++ b/Allura/allura/model/auth.py
@@ -457,21 +457,6 @@ def add_login_detail(self, detail):
         except DuplicateKeyError:
             session(detail).expunge(detail)
 
-    def backfill_login_details(self, auth_provider):
-        # ".*" at start of regex and the DOTALL flag is needed only for the test, which uses mim
-        # Fixed in ming f9f69d3c, so once we upgrade to 0.6.1+ we can remove it
-        msg_regex = re.compile(r'.*^({})'.format('|'.join([re.escape(line_prefix)
-                                                           for line_prefix
-                                                           in auth_provider.trusted_auditlog_line_prefixes])),
-                               re.MULTILINE | re.DOTALL)
-        candidate_types = auth_provider.trusted_auditlog_event_types + ['account.event.unclassified']
-        for auditlog in AuditLog.for_user(self, event_type={'$in': candidate_types}):
-            if not msg_regex.search(auditlog.message or ''):
-                continue
-            login_detail = auth_provider.login_details_from_auditlog(auditlog)
-            if login_detail:
-                self.add_login_detail(login_detail)
-
     def send_password_reset_email(self, email_address=None, subject_tmpl='{site_name} Password recovery'):
         if email_address is None:
             email_address = self.get_pref('email_address')
diff --git a/Allura/allura/scripts/backfill_previous_login_details.py b/Allura/allura/scripts/backfill_previous_login_details.py
deleted file mode 100644
index f1e702c7f..000000000
--- a/Allura/allura/scripts/backfill_previous_login_details.py
+++ /dev/null
@@ -1,57 +0,0 @@
-#       Licensed to the Apache Software Foundation (ASF) under one
-#       or more contributor license agreements.  See the NOTICE file
-#       distributed with this work for additional information
-#       regarding copyright ownership.  The ASF licenses this file
-#       to you under the Apache License, Version 2.0 (the
-#       "License"); you may not use this file except in compliance
-#       with the License.  You may obtain a copy of the License at
-#
-#         http://www.apache.org/licenses/LICENSE-2.0
-#
-#       Unless required by applicable law or agreed to in writing,
-#       software distributed under the License is distributed on an
-#       "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-#       KIND, either express or implied.  See the License for the
-#       specific language governing permissions and limitations
-#       under the License.
-
-import logging
-
-import argparse
-
-from allura.model import main_orm_session, main_explicitflush_orm_session
-
-from allura.scripts import ScriptTask
-from allura import model as M
-from allura.lib.plugin import AuthenticationProvider
-from allura.lib.utils import chunked_find
-
-log = logging.getLogger('allura.scripts.backfill_previous_login_details')
-
-
-class BackfillPreviousLoginDetails(ScriptTask):
-
-    @classmethod
-    def parser(cls):
-        return argparse.ArgumentParser(description="Backfill previous login details from audit logs.  "
-                                                   "Needed if auth.hibp_failure_force_pwd_change is enabled")
-
-    @classmethod
-    def execute(cls, options):
-        auth_provider = AuthenticationProvider.get(None)
-        for i, chunk in enumerate(chunked_find(M.User, {}, pagesize=2)):
-            log.info('Backfilling login details for chunk #%s', i)
-            for u in chunk:
-                try:
-                    u.backfill_login_details(auth_provider)
-                except Exception:
-                    log.exception('Error backfilling on user %s', u)
-
-            main_orm_session.clear()  # AuditLog and User objs
-            main_explicitflush_orm_session.clear()  # UserLoginDetails objs, already flushed individually
-
-        log.info('Finished backfilling previous login details')
-
-
-if __name__ == '__main__':
-    BackfillPreviousLoginDetails.main()
diff --git a/Allura/allura/tests/model/test_auth.py b/Allura/allura/tests/model/test_auth.py
index 6d00eda97..892b3d06b 100644
--- a/Allura/allura/tests/model/test_auth.py
+++ b/Allura/allura/tests/model/test_auth.py
@@ -24,7 +24,7 @@
 
 import pytest
 from bson import Binary, ObjectId
-from tg import tmpl_context as c, app_globals as g, request as r
+from tg import tmpl_context as c, app_globals as g
 from webob import Request
 from mock import patch, Mock
 
@@ -703,32 +703,6 @@ def test_user_index_none_values(self):
         assert idx['telnumbers_t'] == ''
         assert idx['webpages_t'] == ''
 
-    def test_user_backfill_login_details(self):
-        with h.push_config(r, user_agent='TestBrowser/55'):
-            # these shouldn't match
-            h.auditlog_user('something happened')
-            h.auditlog_user('blah blah Password changed')
-            h.auditlog_user('Comment: Account disabled', event_type='account.event.unclassified')
-        with h.push_config(r, user_agent='TestBrowser/56'):
-            # these should all match, but only one entry created for this ip/ua
-            h.auditlog_user('Account activated')
-            h.auditlog_user('Successful login', event_type='auth.login.succeeded')
-            h.auditlog_user('Password changed')
-        with h.push_config(r, user_agent='TestBrowser/57'):
-            # this should match too
-            h.auditlog_user('Set up multifactor TOTP')
-        ThreadLocalODMSession.flush_all()
-
-        auth_provider = plugin.AuthenticationProvider.get(None)
-        c.user.backfill_login_details(auth_provider)
-
-        details = M.UserLoginDetails.query.find({'user_id': c.user._id}).sort('ua').all()
-        assert len(details) == 2, details
-        assert details[0].ip == '127.0.0.1'
-        assert details[0].ua == 'TestBrowser/56'
-        assert details[1].ip == '127.0.0.1'
-        assert details[1].ua == 'TestBrowser/57'
-
 
 class TestAuditLog:
 
diff --git a/Allura/allura/tests/test_plugin.py b/Allura/allura/tests/test_plugin.py
index b1ed24b59..8f14fd3c5 100644
--- a/Allura/allura/tests/test_plugin.py
+++ b/Allura/allura/tests/test_plugin.py
@@ -784,35 +784,6 @@ def test_disable_user(self):
             ThreadLocalODMSession.flush_all()
         assert user.disabled is True
 
-    def test_login_details_from_auditlog(self):
-        user = M.User(username='asfdasdf')
-
-        assert (self.provider.login_details_from_auditlog(M.AuditLog(message='')) is
-                None)
-
-        detail = self.provider.login_details_from_auditlog(M.AuditLog(message='IP Address: 1.2.3.4\nFoo', user=user))
-        assert detail.user_id == user._id
-        assert detail.ip == '1.2.3.4'
-        assert detail.ua is None
-
-        detail = self.provider.login_details_from_auditlog(M.AuditLog(message='Foo\nIP Address: 1.2.3.4\nFoo', user=user))
-        assert detail.ip == '1.2.3.4'
-        assert detail.ua is None
-
-        assert (self.provider.login_details_from_auditlog(M.AuditLog(
-            message='blah blah IP Address: 1.2.3.4\nFoo', user=user)) is
-            None)
-
-        detail = self.provider.login_details_from_auditlog(M.AuditLog(
-            message='User-Agent: Mozilla/Firefox\nFoo', user=user))
-        assert detail.ip is None
-        assert detail.ua == 'Mozilla/Firefox'
-
-        detail = self.provider.login_details_from_auditlog(M.AuditLog(
-            message='IP Address: 1.2.3.4\nUser-Agent: Mozilla/Firefox\nFoo', user=user))
-        assert detail.ip == '1.2.3.4'
-        assert detail.ua == 'Mozilla/Firefox'
-
     def test_get_login_detail(self):
         user = M.User(username='foobarbaz')
         detail = self.provider.get_login_detail(Request.blank('/'), user)