clokep: I think this probably needs another test or two (at least checking the backwards compatibility code-path).
richvdh: I'm also wondering if this is the right time to start a quick doc in https://github.com/matrix-org/synapse/blob/master/docs about what API the spam checker should implement is. WDYT?
clokep: Thanks for the comments @richvdh! I can certainly add a document about the spam checker too.
clokep: @richvdh I handle the review comments, my inclination is to do the documentation as a separate PR so that this doesn't block the actual need. Does that make sense?
clokep: See #6906 for the documentation. Note that it doesn't actually include the documentation for this PR. I'll either update that PR or this one based on which is merged first!
diff --git a/changelog.d/6888.feature b/changelog.d/6888.feature
new file mode 100644
index 000000000..1b7ac0c82
--- /dev/null
+++ b/changelog.d/6888.feature
@@ -0,0 +1,1 @@
+The result of a user directory search can now be filtered via the spam checker.
diff --git a/changelog.d/6905.doc b/changelog.d/6905.doc
index ca10b3830..be0e698af 100644
--- a/changelog.d/6905.doc
+++ b/changelog.d/6905.doc
@@ -1,1 +1,1 @@
-Mention in `ACME.md` that ACMEv1 is deprecated and explain what it means for Synapse admins.
+Update Synapse's documentation to warn about the deprecation of ACME v1.
diff --git a/docs/spam_checker.md b/docs/spam_checker.md
index 97ff17f95..5b5f5000b 100644
--- a/docs/spam_checker.md
+++ b/docs/spam_checker.md
@@ -54,6 +54,9 @@ class ExampleSpamChecker:
 
     def user_may_publish_room(self, userid, room_id):
         return True  # allow publishing of all rooms
+
+    def check_username_for_spam(self, user_profile):
+        return False  # allow all usernames
 ```
 
 ## Configuration
diff --git a/synapse/events/spamcheck.py b/synapse/events/spamcheck.py
index 5a907718d..0a13fca9a 100644
--- a/synapse/events/spamcheck.py
+++ b/synapse/events/spamcheck.py
@@ -15,6 +15,7 @@
 # limitations under the License.
 
 import inspect
+from typing import Dict
 
 from synapse.spam_checker_api import SpamCheckerApi
 
@@ -125,3 +126,29 @@ class SpamChecker(object):
             return True
 
         return self.spam_checker.user_may_publish_room(userid, room_id)
+
+    def check_username_for_spam(self, user_profile: Dict[str, str]) -> bool:
+        """Checks if a user ID or display name are considered "spammy" by this server.
+
+        If the server considers a username spammy, then it will not be included in
+        user directory results.
+
+        Args:
+            user_profile: The user information to check, it contains the keys:
+                * user_id
+                * display_name
+                * avatar_url
+
+        Returns:
+            True if the user is spammy.
+        """
+        if self.spam_checker is None:
+            return False
+
+        # For backwards compatibility, if the method does not exist on the spam checker, fallback to not interfering.
+        checker = getattr(self.spam_checker, "check_username_for_spam", None)
+        if not checker:
+            return False
+        # Make a copy of the user profile object to ensure the spam checker
+        # cannot modify it.
+        return checker(user_profile.copy())
diff --git a/synapse/handlers/user_directory.py b/synapse/handlers/user_directory.py
index 81aa58dc8..722760c59 100644
--- a/synapse/handlers/user_directory.py
+++ b/synapse/handlers/user_directory.py
@@ -52,6 +52,7 @@ class UserDirectoryHandler(StateDeltasHandler):
         self.is_mine_id = hs.is_mine_id
         self.update_user_directory = hs.config.update_user_directory
         self.search_all_users = hs.config.user_directory_search_all_users
+        self.spam_checker = hs.get_spam_checker()
         # The current position in the current_state_delta stream
         self.pos = None
 
@@ -65,7 +66,7 @@ class UserDirectoryHandler(StateDeltasHandler):
             # we start populating the user directory
             self.clock.call_later(0, self.notify_new_event)
 
-    def search_users(self, user_id, search_term, limit):
+    async def search_users(self, user_id, search_term, limit):
         """Searches for users in directory
 
         Returns:
@@ -82,7 +83,16 @@ class UserDirectoryHandler(StateDeltasHandler):
                     ]
                 }
         """
-        return self.store.search_user_dir(user_id, search_term, limit)
+        results = await self.store.search_user_dir(user_id, search_term, limit)
+
+        # Remove any spammy users from the results.
+        results["results"] = [
+            user
+            for user in results["results"]
+            if not self.spam_checker.check_username_for_spam(user)
+        ]
+
+        return results
 
     def notify_new_event(self):
         """Called when there may be more deltas to process

Homeserver configuration options to tweak user directory behaviour
I'd like an option, perhaps in homeserver.yaml, to provide a list of regex patterns for the homeserver to exclude from user directory search results.
diff --git a/tests/handlers/test_user_directory.py b/tests/handlers/test_user_directory.py
index 26071059d..0a4765fff 100644
--- a/tests/handlers/test_user_directory.py
+++ b/tests/handlers/test_user_directory.py
@@ -147,6 +147,98 @@ class UserDirectoryTestCase(unittest.HomeserverTestCase):
         s = self.get_success(self.handler.search_users(u1, "user3", 10))
         self.assertEqual(len(s["results"]), 0)
 
+    def test_spam_checker(self):
+        """
+        A user which fails to the spam checks will not appear in search results.
+        """
+        u1 = self.register_user("user1", "pass")
+        u1_token = self.login(u1, "pass")
+        u2 = self.register_user("user2", "pass")
+        u2_token = self.login(u2, "pass")
+
+        # We do not add users to the directory until they join a room.
+        s = self.get_success(self.handler.search_users(u1, "user2", 10))
+        self.assertEqual(len(s["results"]), 0)
+
+        room = self.helper.create_room_as(u1, is_public=False, tok=u1_token)
+        self.helper.invite(room, src=u1, targ=u2, tok=u1_token)
+        self.helper.join(room, user=u2, tok=u2_token)
+
+        # Check we have populated the database correctly.
+        shares_private = self.get_users_who_share_private_rooms()
+        public_users = self.get_users_in_public_rooms()
+
+        self.assertEqual(
+            self._compress_shared(shares_private), set([(u1, u2, room), (u2, u1, room)])
+        )
+        self.assertEqual(public_users, [])
+
+        # We get one search result when searching for user2 by user1.
+        s = self.get_success(self.handler.search_users(u1, "user2", 10))
+        self.assertEqual(len(s["results"]), 1)
+
+        # Configure a spam checker that does not filter any users.
+        spam_checker = self.hs.get_spam_checker()
+
+        class AllowAll(object):
+            def check_username_for_spam(self, user_profile):
+                # Allow all users.
+                return False
+
+        spam_checker.spam_checker = AllowAll()
+
+        # The results do not change:
+        # We get one search result when searching for user2 by user1.
+        s = self.get_success(self.handler.search_users(u1, "user2", 10))
+        self.assertEqual(len(s["results"]), 1)
+
+        # Configure a spam checker that filters all users.
+        class BlockAll(object):
+            def check_username_for_spam(self, user_profile):
+                # All users are spammy.
+                return True
+
+        spam_checker.spam_checker = BlockAll()
+
+        # User1 now gets no search results for any of the other users.
+        s = self.get_success(self.handler.search_users(u1, "user2", 10))
+        self.assertEqual(len(s["results"]), 0)
+
+    def test_legacy_spam_checker(self):
+        """
+        A spam checker without the expected method should be ignored.
+        """
+        u1 = self.register_user("user1", "pass")
+        u1_token = self.login(u1, "pass")
+        u2 = self.register_user("user2", "pass")
+        u2_token = self.login(u2, "pass")
+
+        # We do not add users to the directory until they join a room.
+        s = self.get_success(self.handler.search_users(u1, "user2", 10))
+        self.assertEqual(len(s["results"]), 0)
+
+        room = self.helper.create_room_as(u1, is_public=False, tok=u1_token)
+        self.helper.invite(room, src=u1, targ=u2, tok=u1_token)
+        self.helper.join(room, user=u2, tok=u2_token)
+
+        # Check we have populated the database correctly.
+        shares_private = self.get_users_who_share_private_rooms()
+        public_users = self.get_users_in_public_rooms()
+
+        self.assertEqual(
+            self._compress_shared(shares_private), set([(u1, u2, room), (u2, u1, room)])
+        )
+        self.assertEqual(public_users, [])
+
+        # Configure a spam checker.
+        spam_checker = self.hs.get_spam_checker()
+        # The spam checker doesn't need any methods, so create a bare object.
+        spam_checker.spam_checker = object()
+
+        # We get one search result when searching for user2 by user1.
+        s = self.get_success(self.handler.search_users(u1, "user2", 10))
+        self.assertEqual(len(s["results"]), 1)
+
     def _compress_shared(self, shared):
         """
         Compress a list of users who share rooms dicts to a list of tuples.

pip install -e .[dev]
parse_log_pytest
requirements.txt
pytest mock coverage
apt-get update apt-get install -y build-essential python3-dev libffi-dev
3.9
requirements/base.txt
pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning
attrs==25.3.0
Automat==24.8.1
bcrypt==4.3.0
bleach==6.2.0
canonicaljson==2.0.0
certifi==2025.1.31
cffi==1.17.1
charset-normalizer==3.4.1
constantly==23.10.4
coverage==7.8.0
cryptography==44.0.2
daemonize==2.5.0
exceptiongroup==1.2.2
frozendict==2.4.6
hyperlink==21.0.0
idna==3.10
incremental==24.7.2
iniconfig==2.1.0
Jinja2==3.1.6
jsonschema==4.23.0
jsonschema-specifications==2024.10.1
MarkupSafe==3.0.2
-e git+https://github.com/matrix-org/synapse.git@361de49c90fd1f35adc4a6bca8206e50e7f15454#egg=matrix_synapse
mock==5.2.0
msgpack==1.1.0
netaddr==1.3.0
packaging==24.2
phonenumbers==9.0.2
pillow==11.1.0
pluggy==1.5.0
prometheus_client==0.7.1
pyasn1==0.6.1
pyasn1_modules==0.4.2
pycparser==2.22
pymacaroons==0.13.0
PyNaCl==1.5.0
pyOpenSSL==25.0.0
pytest==8.3.5
PyYAML==6.0.2
referencing==0.36.2
requests==2.32.3
rpds-py==0.24.0
service-identity==24.2.0
signedjson==1.1.4
six==1.17.0
sortedcontainers==2.4.0
tomli==2.2.1
treq==24.9.1
Twisted==24.11.0
typing_extensions==4.13.0
unpaddedbase64==2.1.0
urllib3==2.3.0
webencodings==0.5.1
zope.interface==7.2

name: synapse
channels:
  - defaults
  - https://repo.anaconda.com/pkgs/main
  - https://repo.anaconda.com/pkgs/r
  - conda-forge
dependencies:
  - _libgcc_mutex=0.1=main
  - _openmp_mutex=5.1=1_gnu
  - ca-certificates=2025.2.25=h06a4308_0
  - ld_impl_linux-64=2.40=h12ee557_0
  - libffi=3.4.4=h6a678d5_1
  - libgcc-ng=11.2.0=h1234567_1
  - libgomp=11.2.0=h1234567_1
  - libstdcxx-ng=11.2.0=h1234567_1
  - ncurses=6.4=h6a678d5_0
  - openssl=3.0.16=h5eee18b_0
  - pip=25.0=py39h06a4308_0
  - python=3.9.21=he870216_1
  - readline=8.2=h5eee18b_0
  - setuptools=75.8.0=py39h06a4308_0
  - sqlite=3.45.3=h5eee18b_0
  - tk=8.6.14=h39e8969_0
  - tzdata=2025a=h04d1e81_0
  - wheel=0.45.1=py39h06a4308_0
  - xz=5.6.4=h5eee18b_1
  - zlib=1.2.13=h5eee18b_1
  - pip:
      - attrs==25.3.0
      - automat==24.8.1
      - bcrypt==4.3.0
      - bleach==6.2.0
      - canonicaljson==2.0.0
      - certifi==2025.1.31
      - cffi==1.17.1
      - charset-normalizer==3.4.1
      - constantly==23.10.4
      - coverage==7.8.0
      - cryptography==44.0.2
      - daemonize==2.5.0
      - exceptiongroup==1.2.2
      - frozendict==2.4.6
      - hyperlink==21.0.0
      - idna==3.10
      - incremental==24.7.2
      - iniconfig==2.1.0
      - jinja2==3.1.6
      - jsonschema==4.23.0
      - jsonschema-specifications==2024.10.1
      - markupsafe==3.0.2
      - matrix-synapse==1.10.0
      - mock==5.2.0
      - msgpack==1.1.0
      - netaddr==1.3.0
      - packaging==24.2
      - phonenumbers==9.0.2
      - pillow==11.1.0
      - pluggy==1.5.0
      - prometheus-client==0.7.1
      - pyasn1==0.6.1
      - pyasn1-modules==0.4.2
      - pycparser==2.22
      - pymacaroons==0.13.0
      - pynacl==1.5.0
      - pyopenssl==25.0.0
      - pytest==8.3.5
      - pyyaml==6.0.2
      - referencing==0.36.2
      - requests==2.32.3
      - rpds-py==0.24.0
      - service-identity==24.2.0
      - signedjson==1.1.4
      - six==1.17.0
      - sortedcontainers==2.4.0
      - tomli==2.2.1
      - treq==24.9.1
      - twisted==24.11.0
      - typing-extensions==4.13.0
      - unpaddedbase64==2.1.0
      - urllib3==2.3.0
      - webencodings==0.5.1
      - zope-interface==7.2
prefix: /opt/conda/envs/synapse

tests/handlers/test_user_directory.py::UserDirectoryTestCase::test_spam_checker
tests/handlers/test_user_directory.py::UserDirectoryTestCase::test_handle_user_deactivated_regular_user tests/handlers/test_user_directory.py::UserDirectoryTestCase::test_handle_user_deactivated_support_user
tests/handlers/test_user_directory.py::UserDirectoryTestCase::test_handle_local_profile_change_with_support_user tests/handlers/test_user_directory.py::UserDirectoryTestCase::test_initial tests/handlers/test_user_directory.py::UserDirectoryTestCase::test_initial_share_all_users tests/handlers/test_user_directory.py::UserDirectoryTestCase::test_legacy_spam_checker tests/handlers/test_user_directory.py::UserDirectoryTestCase::test_private_room tests/handlers/test_user_directory.py::TestUserDirSearchDisabled::test_disabling_room_list
changelog.d/6888.feature synapse/events/spamcheck.py changelog.d/6905.doc synapse/handlers/user_directory.py docs/spam_checker.md
changelog.d/6888.feature synapse/events/spamcheck.py changelog.d/6905.doc synapse/handlers/user_directory.py docs/spam_checker.md