You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@tooling.apache.org by sb...@apache.org on 2026/05/14 16:56:19 UTC

(tooling-trusted-releases) branch altera updated: Cache a map of hashed email addresses to ASF UIDs in a file

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

sbp pushed a commit to branch altera
in repository https://gitbox.apache.org/repos/asf/tooling-trusted-releases.git


The following commit(s) were added to refs/heads/altera by this push:
     new 83c69617 Cache a map of hashed email addresses to ASF UIDs in a file
83c69617 is described below

commit 83c69617e3f0d03a283de274f13c2ba0205f4b64
Author: Sean B. Palmer <se...@miscoranda.com>
AuthorDate: Thu May 14 17:55:21 2026 +0100

    Cache a map of hashed email addresses to ASF UIDs in a file
---
 atr/admin/__init__.py          |   5 +-
 atr/cache.py                   | 297 +++++++++++++++++++++++++++++++++++++++++
 atr/ldap.py                    |  31 +++++
 atr/server.py                  |   5 +
 atr/storage/writers/keys.py    |  35 ++---
 atr/tabulate.py                |  13 +-
 atr/util.py                    |  20 +--
 scripts/keys_import.py         |  17 ++-
 tests/unit/conftest.py         |  72 ++++++++++
 tests/unit/test_cache.py       |  51 +++++++
 tests/unit/test_keys_writer.py | 108 ++++++++-------
 tests/unit/test_tabulate.py    |  17 +--
 12 files changed, 562 insertions(+), 109 deletions(-)

diff --git a/atr/admin/__init__.py b/atr/admin/__init__.py
index 2d9e84f1..614d3243 100644
--- a/atr/admin/__init__.py
+++ b/atr/admin/__init__.py
@@ -39,6 +39,7 @@ import sqlmodel
 import werkzeug.exceptions as exceptions
 
 import atr.blueprints.admin as admin
+import atr.cache as cache
 import atr.config as config
 import atr.db as db
 import atr.db.interaction as interaction
@@ -1293,7 +1294,7 @@ async def validate_jwt_post(
 
 
 async def _check_keys(fix: bool = False) -> str:
-    email_to_uid = await util.email_to_uid_map()
+    await cache.email_uid_view_or_live()
     bad_keys = []
     async with db.session() as data:
         keys = await data.public_signing_key().all()
@@ -1303,7 +1304,7 @@ async def _check_keys(fix: bool = False) -> str:
                 uids.append(key.primary_declared_uid)
             if key.secondary_declared_uids:
                 uids.extend(key.secondary_declared_uids)
-            asf_uid = await util.asf_uid_from_uids(uids, ldap_data=email_to_uid)
+            asf_uid = await util.asf_uid_from_uids(uids, use_ldap=False)
             if asf_uid != key.apache_uid:
                 bad_keys.append(f"{key.fingerprint} detected: {asf_uid}, key: {key.apache_uid}")
             if fix:
diff --git a/atr/cache.py b/atr/cache.py
index b9398036..add6e55d 100644
--- a/atr/cache.py
+++ b/atr/cache.py
@@ -16,11 +16,17 @@
 # under the License.
 
 import asyncio
+import contextlib
 import datetime
+import hashlib
+import os
 import pathlib
+import uuid
+from collections.abc import Iterable, Mapping
 from typing import Final
 
 import aiofiles
+import aiofiles.os
 import asfquart
 import pydantic
 
@@ -41,6 +47,39 @@ class AdminsCache(schema.Strict):
     admins: frozenset[str] = schema.description("Set of admin user IDs from LDAP")
 
 
+class EmailUidCache(schema.Strict):
+    refreshed: datetime.datetime = schema.description("When the cache was last refreshed")
+    hashes: dict[str, str] = schema.description("SHA-256(email.lower()) to ASF uid")
+    reverse: dict[str, list[str]] = schema.description("ASF uid to list of SHA-256 email hashes")
+
+
+class EmailUidLookup:
+    def __init__(self, hashes: Mapping[str, str]) -> None:
+        self._hashes = hashes
+
+    @classmethod
+    def from_plain(cls, mapping: Mapping[str, str]) -> "EmailUidLookup":
+        return cls({_email_uid_hash(email): uid for email, uid in mapping.items() if email})
+
+    def get(self, email: str) -> str | None:
+        if not email:
+            return None
+        return self._hashes.get(_email_uid_hash(email))
+
+    def __contains__(self, email: object) -> bool:
+        if not isinstance(email, str):
+            return False
+        if not email:
+            return False
+        return _email_uid_hash(email) in self._hashes
+
+    def __getitem__(self, email: str) -> str:
+        return self._hashes[_email_uid_hash(email)]
+
+    def __len__(self) -> int:
+        return len(self._hashes)
+
+
 def admins_get() -> frozenset[str]:
     if asfquart.APP is not None:
         return asfquart.APP.extensions.get("admins", frozenset())
@@ -95,6 +134,153 @@ async def admins_startup_load() -> None:
         log.warning(f"Failed to fetch admin users from LDAP at startup: {e}")
 
 
+def email_uid_apply_delta(uid: str, old_emails: Iterable[str], new_emails: Iterable[str]) -> bool:
+    if asfquart.APP is None:
+        return False
+    hashes = asfquart.APP.extensions.get("email_uid_hashes")
+    reverse = asfquart.APP.extensions.get("email_uid_reverse")
+    if (not isinstance(hashes, dict)) or (not isinstance(reverse, dict)):
+        return False
+    uid_lower = uid.lower()
+    old_set = {e.lower() for e in old_emails if e}
+    new_set = {e.lower() for e in new_emails if e}
+    removed = old_set - new_set
+    added = new_set - old_set
+    if (not removed) and (not added):
+        return False
+    existing = set(reverse.get(uid_lower, []))
+    for email in removed:
+        h = _email_uid_hash(email)
+        if hashes.get(h) == uid_lower:
+            del hashes[h]
+        existing.discard(h)
+    for email in added:
+        h = _email_uid_hash(email)
+        hashes[h] = uid_lower
+        existing.add(h)
+    if existing:
+        reverse[uid_lower] = sorted(existing)
+    elif uid_lower in reverse:
+        del reverse[uid_lower]
+    asfquart.APP.extensions["email_uid_refreshed"] = datetime.datetime.now(datetime.UTC)
+    return True
+
+
+def email_uid_erase() -> None:
+    cache_path = _email_uid_path()
+    try:
+        cache_path.unlink(missing_ok=True)
+    except OSError as e:
+        log.warning(f"Failed to erase email-to-UID cache: {e}")
+
+
+def email_uid_lookup(email: str) -> str | None:
+    return _email_uid_view().get(email)
+
+
+def email_uid_purge_uid(uid: str) -> bool:
+    if asfquart.APP is None:
+        return False
+    hashes = asfquart.APP.extensions.get("email_uid_hashes")
+    reverse = asfquart.APP.extensions.get("email_uid_reverse")
+    if (not isinstance(hashes, dict)) or (not isinstance(reverse, dict)):
+        return False
+    uid_lower = uid.lower()
+    uid_hashes = reverse.pop(uid_lower, [])
+    if not uid_hashes:
+        return False
+    for h in uid_hashes:
+        if hashes.get(h) == uid_lower:
+            del hashes[h]
+    asfquart.APP.extensions["email_uid_refreshed"] = datetime.datetime.now(datetime.UTC)
+    return True
+
+
+async def email_uid_refresh() -> None:
+    import atr.util as util
+
+    email_to_uid = await util.email_to_uid_map()
+    hashes: dict[str, str] = {}
+    reverse: dict[str, list[str]] = {}
+    for email, uid in email_to_uid.items():
+        if (not email) or (not uid):
+            continue
+        h = _email_uid_hash(email)
+        hashes[h] = uid
+        reverse.setdefault(uid, []).append(h)
+    if (not hashes) or (not reverse):
+        log.warning(
+            "Email-to-UID cache refresh produced no usable LDAP email mappings; not writing cache: "
+            f"ldap_email_values={len(email_to_uid)}"
+        )
+        raise RuntimeError("Email-to-UID cache refresh produced no usable LDAP email mappings")
+    await email_uid_save_to_file(hashes, reverse)
+    _email_uid_update_app_extensions(hashes, reverse)
+    log.info(f"Email-to-UID cache refreshed: {len(hashes)} hashes for {len(reverse)} users")
+
+
+async def email_uid_save_current_to_file() -> None:
+    if asfquart.APP is None:
+        return
+    hashes = asfquart.APP.extensions.get("email_uid_hashes")
+    reverse = asfquart.APP.extensions.get("email_uid_reverse")
+    if (not isinstance(hashes, dict)) or (not isinstance(reverse, dict)):
+        return
+    hashes_copy = dict(hashes)
+    reverse_copy = {uid: list(hs) for uid, hs in reverse.items()}
+    await email_uid_save_to_file(hashes_copy, reverse_copy)
+    _email_uid_update_app_extensions(hashes_copy, reverse_copy)
+
+
+async def email_uid_save_to_file(hashes: dict[str, str], reverse: dict[str, list[str]]) -> None:
+    cache_path = _email_uid_path()
+    cache_path.parent.mkdir(parents=True, exist_ok=True)
+    cache_data = EmailUidCache(
+        refreshed=datetime.datetime.now(datetime.UTC),
+        hashes=hashes,
+        reverse=reverse,
+    )
+    content = cache_data.model_dump_json()
+    temp_path = cache_path.parent / f".{cache_path.name}.{uuid.uuid4()}.tmp"
+    try:
+        async with aiofiles.open(temp_path, "w") as f:
+            await f.write(content)
+            await f.flush()
+            await asyncio.to_thread(os.fsync, f.fileno())
+        await asyncio.to_thread(os.chmod, temp_path, 0o400)
+        await aiofiles.os.rename(temp_path, cache_path)
+    except Exception:
+        with contextlib.suppress(FileNotFoundError):
+            await aiofiles.os.remove(temp_path)
+        raise
+
+
+async def email_uid_startup_load() -> None:
+    cache_data = await _email_uid_read_from_file_async()
+    if cache_data is not None:
+        _email_uid_update_app_extensions(cache_data.hashes, cache_data.reverse)
+        log.info(f"Loaded {len(cache_data.hashes)} email hashes from cache (refreshed: {cache_data.refreshed})")
+        return
+    log.info("No email-to-UID cache found, fetching from LDAP")
+    try:
+        await email_uid_refresh()
+    except Exception as e:
+        log.warning(f"Failed to populate email-to-UID cache at startup from LDAP: {e}")
+
+
+def email_uid_view() -> EmailUidLookup:
+    return _email_uid_view()
+
+
+async def email_uid_view_or_live() -> EmailUidLookup:
+    view = _email_uid_view()
+    if len(view) > 0:
+        return view
+    log.warning("Email-to-UID cache empty, falling back to live LDAP query")
+    await email_uid_refresh()
+    return _email_uid_view()
+
+
 def project_version_get() -> dict[str, set[str]]:
     if asfquart.APP is not None:
         return asfquart.APP.extensions.get("project_versions", {})
@@ -172,6 +358,117 @@ def _admins_update_app_extensions(admins: frozenset[str]) -> None:
     app.extensions["admins_refreshed"] = datetime.datetime.now(datetime.UTC)
 
 
+def _email_uid_file_mtime_ns() -> int | None:
+    try:
+        return _email_uid_path().stat().st_mtime_ns
+    except FileNotFoundError:
+        return None
+    except OSError as e:
+        log.warning(f"Failed to stat email-to-UID cache: {e}")
+        return None
+
+
+def _email_uid_hash(email: str) -> str:
+    return hashlib.sha256(email.lower().encode("utf-8")).hexdigest()
+
+
+def _email_uid_path() -> pathlib.Path:
+    return pathlib.Path(config.get().STATE_DIR) / "secrets" / "cached" / "email_uid.json"
+
+
+def _email_uid_read_from_file() -> EmailUidCache | None:
+    cache_path = _email_uid_path()
+    if not cache_path.exists():
+        return None
+    try:
+        with open(cache_path) as f:
+            raw_data = f.read()
+    except OSError as e:
+        log.warning(f"Failed to read email-to-UID cache: {e}")
+        return None
+    try:
+        cache_data = EmailUidCache.model_validate_json(raw_data)
+    except pydantic.ValidationError as e:
+        log.warning(f"Failed to parse email-to-UID cache: {e}")
+        return None
+    return _email_uid_validate_cache_data(cache_path, cache_data)
+
+
+async def _email_uid_read_from_file_async() -> EmailUidCache | None:
+    cache_path = _email_uid_path()
+    if not cache_path.exists():
+        return None
+    try:
+        async with aiofiles.open(cache_path) as f:
+            raw_data = await f.read()
+    except OSError as e:
+        log.warning(f"Failed to read email-to-UID cache: {e}")
+        return None
+    try:
+        cache_data = EmailUidCache.model_validate_json(raw_data)
+    except pydantic.ValidationError as e:
+        log.warning(f"Failed to parse email-to-UID cache: {e}")
+        return None
+    return _email_uid_validate_cache_data(cache_path, cache_data)
+
+
+def _email_uid_reload_app_extensions_from_file_if_changed() -> None:
+    app = asfquart.APP
+    if app is None:
+        return
+    file_mtime_ns = _email_uid_file_mtime_ns()
+    if file_mtime_ns is None:
+        return
+    stored_mtime_ns = app.extensions.get("email_uid_file_mtime_ns")
+    hashes = app.extensions.get("email_uid_hashes")
+    if (stored_mtime_ns == file_mtime_ns) and isinstance(hashes, dict):
+        return
+    cache_data = _email_uid_read_from_file()
+    if cache_data is None:
+        return
+    _email_uid_update_app_extensions(cache_data.hashes, cache_data.reverse, file_mtime_ns)
+
+
+def _email_uid_update_app_extensions(
+    hashes: dict[str, str], reverse: dict[str, list[str]], file_mtime_ns: int | None = None
+) -> None:
+    app = asfquart.APP
+    if app is None:
+        return
+    app.extensions["email_uid_hashes"] = dict(hashes)
+    app.extensions["email_uid_reverse"] = {uid: list(hs) for uid, hs in reverse.items()}
+    app.extensions["email_uid_refreshed"] = datetime.datetime.now(datetime.UTC)
+    mtime_ns = file_mtime_ns
+    if mtime_ns is None:
+        mtime_ns = _email_uid_file_mtime_ns()
+    app.extensions["email_uid_file_mtime_ns"] = mtime_ns
+
+
+def _email_uid_validate_cache_data(cache_path: pathlib.Path, cache_data: EmailUidCache) -> EmailUidCache | None:
+    if cache_data.hashes and cache_data.reverse:
+        return cache_data
+    log.warning(f"Ignoring empty email-to-UID cache at {cache_path} (refreshed: {cache_data.refreshed})")
+    try:
+        cache_path.unlink()
+    except FileNotFoundError:
+        pass
+    except OSError as e:
+        log.warning(f"Failed to remove empty email-to-UID cache at {cache_path}: {e}")
+    return None
+
+
+def _email_uid_view() -> EmailUidLookup:
+    if asfquart.APP is not None:
+        _email_uid_reload_app_extensions_from_file_if_changed()
+        hashes = asfquart.APP.extensions.get("email_uid_hashes")
+        if isinstance(hashes, dict):
+            return EmailUidLookup(hashes)
+    cache_data = _email_uid_read_from_file()
+    if cache_data is None:
+        return EmailUidLookup({})
+    return EmailUidLookup(cache_data.hashes)
+
+
 async def _project_version_fetch_from_db() -> dict[str, set[str]]:
     import atr.db as db
     import atr.models.sql as sql
diff --git a/atr/ldap.py b/atr/ldap.py
index 4d0f0f9f..71790124 100644
--- a/atr/ldap.py
+++ b/atr/ldap.py
@@ -47,7 +47,10 @@ RESULT_ATTRIBUTES: Final[list[str]] = [
 class PubSubAttributes(schema.Subset):
     """LDAP attributes as they appear in pubsub old_attributes/new_attributes."""
 
+    asf_alt_email: list[str] = schema.Field(default_factory=list, alias="asf-altEmail")
     asf_banned: list[str] = schema.Field(default_factory=list, alias="asf-banned")
+    asf_committer_email: list[str] = schema.Field(default_factory=list, alias="asf-committer-email")
+    mail: list[str] = schema.Field(default_factory=list)
     uid: list[str] = schema.Field(default_factory=list)
 
 
@@ -259,6 +262,7 @@ async def github_to_apache(github_numeric_uid: int) -> str:
 
 
 async def handle_update(payload: dict) -> None:
+    import atr.cache as cache
     import atr.log as log
 
     try:
@@ -283,6 +287,19 @@ async def handle_update(payload: dict) -> None:
         log.info(f"LDAP pubsub: user {uid} has been reactivated")
         log.auth_event("account_reactivated", uid)
 
+    change_type = parsed.change_type.lower()
+    if change_type == "delete":
+        if cache.email_uid_purge_uid(uid):
+            await cache.email_uid_save_current_to_file()
+            log.info(f"LDAP pubsub: purged email cache entries for deleted user {uid}")
+        return
+
+    old_emails = _emails_from_pubsub(parsed.old_attributes)
+    new_emails = _emails_from_pubsub(parsed.new_attributes)
+    if cache.email_uid_apply_delta(uid, old_emails, new_emails):
+        await cache.email_uid_save_current_to_file()
+        log.info(f"LDAP pubsub: applied email cache delta for {uid}")
+
 
 async def is_active(asf_uid: str) -> bool:
     import atr.config as config
@@ -328,6 +345,20 @@ def search(params: SearchParameters) -> None:
                 ...
 
 
+def _emails_from_pubsub(attributes: PubSubAttributes) -> list[str]:
+    emails: list[str] = []
+    for email in attributes.mail:
+        if email:
+            emails.append(email)
+    for email in attributes.asf_alt_email:
+        if email:
+            emails.append(email)
+    for email in attributes.asf_committer_email:
+        if email:
+            emails.append(email)
+    return emails
+
+
 def _extract_uid_from_pubsub(payload: PubSubPayload) -> str | None:
     """Extract the ASF UID from a pubsub payload, preferring new_attributes.uid then the DN."""
     if payload.new_attributes.uid:
diff --git a/atr/server.py b/atr/server.py
index 60d0c43f..8bda864f 100644
--- a/atr/server.py
+++ b/atr/server.py
@@ -182,6 +182,7 @@ def _app_dirs_setup(state_dir_str: str, hot_reload: bool) -> None:
         pathlib.Path(state_dir_str) / "hypercorn" / "secrets",
         pathlib.Path(state_dir_str) / "logs",
         pathlib.Path(state_dir_str) / "runtime",
+        pathlib.Path(state_dir_str) / "secrets" / "cached",
         pathlib.Path(state_dir_str) / "secrets" / "curated",
         pathlib.Path(state_dir_str) / "secrets" / "generated",
         pathlib.Path(paths.get_archives_dir()),
@@ -319,6 +320,8 @@ def _app_setup_lifecycle(app: base.QuartApp, app_config: type[config.AppConfig])
         project_version_task = asyncio.create_task(cache.project_version_refresh_loop())
         app.extensions["project_version_task"] = project_version_task
 
+        await cache.email_uid_startup_load()
+
         worker_manager = manager.get_worker_manager()
         await worker_manager.start()
 
@@ -370,6 +373,8 @@ def _app_setup_lifecycle(app: base.QuartApp, app_config: type[config.AppConfig])
             with contextlib.suppress(asyncio.CancelledError):
                 await task
 
+        cache.email_uid_erase()
+
         await db.shutdown_database()
 
         await _app_shutdown_log_listeners(app)
diff --git a/atr/storage/writers/keys.py b/atr/storage/writers/keys.py
index c8ba8384..4aba83c4 100644
--- a/atr/storage/writers/keys.py
+++ b/atr/storage/writers/keys.py
@@ -32,6 +32,7 @@ import sqlalchemy.dialects.sqlite as sqlite
 import sqlalchemy.orm as orm
 import sqlmodel
 
+import atr.cache as cache
 import atr.config as config
 import atr.db as db
 import atr.log as log
@@ -235,7 +236,7 @@ class FoundationCommitter(GeneralPublic):
     def public_key_model(
         self,
         key: openpgp.PublicKey,
-        ldap_data: dict[str, str],
+        ldap_data: cache.EmailUidLookup,
         original_key_block: str | None = None,
     ) -> sql.PublicSigningKey:
         uids = list(key.user_ids)
@@ -440,7 +441,7 @@ class FoundationCommitter(GeneralPublic):
 
         return affected
 
-    def __block_model(self, key_block: str, ldap_data: dict[str, str]) -> types.Key:
+    def __block_model(self, key_block: str, ldap_data: cache.EmailUidLookup) -> types.Key:
         # This cache is only held for the session
         if key_block in self.__key_block_models_cache:
             cached_key_models = self.__key_block_models_cache[key_block]
@@ -497,7 +498,7 @@ class FoundationCommitter(GeneralPublic):
             return outcome.Error(ValueError("Expected one key block, got none or multiple"))
         key_block = key_blocks[0]
         try:
-            ldap_data = await util.email_to_uid_map()
+            ldap_data = await cache.email_uid_view_or_live()
             key = await asyncio.to_thread(self.__block_model, key_block, ldap_data)
         except Exception as e:
             return outcome.Error(e)
@@ -557,7 +558,7 @@ and was published by the committee.\
         full_keys_file_content = header_content + key_blocks_str
         return full_keys_file_content
 
-    def __uids_asf_uid(self, uids: list[str], ldap_data: dict[str, str]) -> str | None:
+    def __uids_asf_uid(self, uids: list[str], ldap_data: cache.EmailUidLookup) -> str | None:
         # Test data
         test_key_uids = [
             "Apache Tooling (For test use only) <ap...@example.invalid>",
@@ -674,26 +675,14 @@ class CommitteeParticipant(FoundationCommitter):
     def committee_key(self) -> str:
         return self.__committee_key
 
-    async def ensure_associated(
-        self, keys_file_text: str, ldap_data: dict[str, str] | None = None
-    ) -> outcome.List[types.Key]:
-        outcomes: outcome.List[types.Key] = await self.__ensure(
-            keys_file_text,
-            associate=True,
-            ldap_data=ldap_data,
-        )
+    async def ensure_associated(self, keys_file_text: str) -> outcome.List[types.Key]:
+        outcomes: outcome.List[types.Key] = await self.__ensure(keys_file_text, associate=True)
         if outcomes.any_result:
             await self.autogenerate_keys_file()
         return outcomes
 
-    async def ensure_stored(
-        self, keys_file_text: str, ldap_data: dict[str, str] | None = None
-    ) -> outcome.List[types.Key]:
-        outcomes: outcome.List[types.Key] = await self.__ensure(
-            keys_file_text,
-            associate=False,
-            ldap_data=ldap_data,
-        )
+    async def ensure_stored(self, keys_file_text: str) -> outcome.List[types.Key]:
+        outcomes: outcome.List[types.Key] = await self.__ensure(keys_file_text, associate=False)
         if outcomes.any_result:
             await self.autogenerate_keys_file()
         return outcomes
@@ -748,7 +737,7 @@ class CommitteeParticipant(FoundationCommitter):
         )
         return outcomes
 
-    def __block_models(self, key_block: str, ldap_data: dict[str, str]) -> list[types.Key | Exception]:
+    def __block_models(self, key_block: str, ldap_data: cache.EmailUidLookup) -> list[types.Key | Exception]:
         try:
             public_key, _ = openpgp.PublicKey.from_armor(key_block)
         except Exception as e:
@@ -864,12 +853,10 @@ class CommitteeParticipant(FoundationCommitter):
         self,
         keys_file_text: str,
         associate: bool = True,
-        ldap_data: dict[str, str] | None = None,
     ) -> outcome.List[types.Key]:
         outcomes = outcome.List[types.Key]()
         try:
-            if ldap_data is None:
-                ldap_data = await util.email_to_uid_map()
+            ldap_data = await cache.email_uid_view_or_live()
             key_blocks = util.parse_key_blocks(keys_file_text)
         except Exception as e:
             outcomes.append_error(e)
diff --git a/atr/tabulate.py b/atr/tabulate.py
index 969848f7..0411604b 100644
--- a/atr/tabulate.py
+++ b/atr/tabulate.py
@@ -19,6 +19,7 @@ import time
 from collections.abc import Generator
 from typing import Protocol
 
+import atr.cache as cache
 import atr.config as config
 import atr.db as db
 import atr.log as log
@@ -209,11 +210,11 @@ async def votes(  # noqa: C901
         _message_id_normalize(message_id) for message_id in (excluded_message_ids or set()) if message_id
     }
 
-    start = time.perf_counter_ns()
-    email_to_uid = await util.email_to_uid_map()
-    end = time.perf_counter_ns()
-    log.info(f"LDAP search took {(end - start) / 1000000} ms")
-    log.info(f"Email addresses from LDAP: {len(email_to_uid)}")
+    try:
+        email_to_uid = await cache.email_uid_view_or_live()
+    except Exception as e:
+        raise ValueError(f"email-to-UID lookup unavailable for tabulation: {e}") from e
+    log.info(f"Email hashes available: {len(email_to_uid)}")
 
     start = time.perf_counter_ns()
     tabulated_votes = {}
@@ -431,7 +432,7 @@ def _vote_continue(line: str) -> bool:
 
 
 def _vote_identity(
-    from_raw: str, email_to_uid: dict[str, str], list_email: str, cc: list[str]
+    from_raw: str, email_to_uid: cache.EmailUidLookup, list_email: str, cc: list[str]
 ) -> tuple[bool, str, str, str | None]:
     from_email_lower = util.email_from_uid(from_raw)
     if not from_email_lower:
diff --git a/atr/util.py b/atr/util.py
index c3884bf3..ccb3e0b4 100644
--- a/atr/util.py
+++ b/atr/util.py
@@ -176,9 +176,9 @@ def asf_uid_from_email(email: str) -> str | None:
     return ldap_params.results_list[0].uid[0]
 
 
-async def asf_uid_from_uids(
-    uids: list[str], use_ldap: bool = True, ldap_data: dict[str, str] | None = None
-) -> str | None:
+async def asf_uid_from_uids(uids: list[str], use_ldap: bool = True) -> str | None:
+    import atr.cache as cache
+
     # Determine ASF UID if not provided
     emails = []
     for uid_str in uids:
@@ -188,13 +188,11 @@ async def asf_uid_from_uids(
                 return email.removesuffix("@apache.org")
             emails.append(email)
     # We did not find a direct @apache.org email address
-    # Therefore, search LDAP data, either cached or directly
-    if ldap_data is not None:
-        # Use cached LDAP data
-        for email in emails:
-            if email in ldap_data:
-                return ldap_data[email]
-        return None
+    # Therefore, search cached LDAP data, then LDAP directly if configured
+    lookup = cache.email_uid_view()
+    for email in emails:
+        if asf_uid := lookup.get(email):
+            return asf_uid
     if use_ldap:
         # Search LDAP directly
         for email in emails:
@@ -436,6 +434,8 @@ async def email_to_uid_map() -> dict[str, str]:
         bind_password_from_config=bind_password,
     )
     await asyncio.to_thread(ldap.search, ldap_params)
+    if ldap_params.err_msg:
+        raise RuntimeError(f"LDAP search failed: {ldap_params.err_msg}")
 
     # Map the LDAP addresses to Apache UIDs
     email_to_uid: dict[str, str] = {}
diff --git a/scripts/keys_import.py b/scripts/keys_import.py
index a0f99337..8b019161 100755
--- a/scripts/keys_import.py
+++ b/scripts/keys_import.py
@@ -30,6 +30,7 @@ from typing import TYPE_CHECKING
 sys.path.append(".")
 
 
+import atr.cache as cache
 import atr.config as config
 import atr.db as db
 import atr.storage as storage
@@ -143,13 +144,15 @@ async def keys_import(conf: config.AppConfig, asf_uid: str) -> None:
     print(f"--- {time.strftime('%Y-%m-%d %H:%M:%S')} by pid {os.getpid()} ---")
     sys.stdout.flush()
 
-    # Get all email addresses in LDAP
-    # We'll discard them when we're finished
     start = time.perf_counter_ns()
-    email_to_uid = await util.email_to_uid_map()
-    end = time.perf_counter_ns()
-    print_and_flush(f"LDAP search took {(end - start) / 1000000} ms")
-    print_and_flush(f"Email addresses from LDAP: {len(email_to_uid)}")
+
+    ldap_start = time.perf_counter_ns()
+    try:
+        await cache.email_uid_refresh()
+    except Exception as e:
+        print_and_flush(f"Email-to-UID cache refresh failed: {e}")
+    ldap_end = time.perf_counter_ns()
+    print_and_flush(f"LDAP refresh took {(ldap_end - ldap_start) / 1000000} ms")
 
     # Get the KEYS file of each committee
     async with db.session() as data:
@@ -181,7 +184,7 @@ async def keys_import(conf: config.AppConfig, asf_uid: str) -> None:
         async with storage.write(asf_uid) as write:
             waca = write.as_committee_admin(committee_key)
             keys_file_text = content.decode("utf-8", errors="replace")
-            outcomes = await waca.keys.ensure_associated(keys_file_text, ldap_data=email_to_uid)
+            outcomes = await waca.keys.ensure_associated(keys_file_text)
             log_outcome_errors(outcomes, committee_key)
             yes = outcomes.result_count
             no = outcomes.error_count
diff --git a/tests/unit/conftest.py b/tests/unit/conftest.py
new file mode 100644
index 00000000..8365f72b
--- /dev/null
+++ b/tests/unit/conftest.py
@@ -0,0 +1,72 @@
+# 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 pathlib
+from typing import NamedTuple
+
+import pytest
+
+import atr.cache as cache
+
+
+class EmailUidCacheSnapshot(NamedTuple):
+    exists: bool
+    size: int | None
+    mode: int | None
+    mtime_ns: int | None
+
+
+def _real_email_uid_cache_path() -> pathlib.Path:
+    repo_root = pathlib.Path(__file__).resolve().parents[2]
+    return repo_root / "state" / "secrets" / "cached" / "email_uid.json"
+
+
+_REAL_EMAIL_UID_CACHE_PATH = _real_email_uid_cache_path().resolve()
+_ORIGINAL_EMAIL_UID_SAVE_TO_FILE = cache.email_uid_save_to_file
+
+
+async def _guarded_email_uid_save_to_file(hashes: dict[str, str], reverse: dict[str, list[str]]) -> None:
+    if cache._email_uid_path().resolve() == _REAL_EMAIL_UID_CACHE_PATH:
+        raise AssertionError(
+            "Unit test attempted to write the real email-to-UID cache. "
+            "Patch atr.config.get to use a temporary STATE_DIR, or mock cache.email_uid_view_or_live()."
+        )
+    await _ORIGINAL_EMAIL_UID_SAVE_TO_FILE(hashes, reverse)
+
+
+cache.email_uid_save_to_file = _guarded_email_uid_save_to_file
+
+
+def _snapshot(path: pathlib.Path) -> EmailUidCacheSnapshot:
+    try:
+        stat = path.stat()
+    except FileNotFoundError:
+        return EmailUidCacheSnapshot(False, None, None, None)
+    return EmailUidCacheSnapshot(True, stat.st_size, stat.st_mode & 0o777, stat.st_mtime_ns)
+
+
+@pytest.fixture(autouse=True)
+def prevent_real_email_uid_cache_writes():
+    before = _snapshot(_REAL_EMAIL_UID_CACHE_PATH)
+
+    yield
+
+    after = _snapshot(_REAL_EMAIL_UID_CACHE_PATH)
+    assert after == before, (
+        "Unit test changed the real email-to-UID cache file. "
+        f"path={_REAL_EMAIL_UID_CACHE_PATH}, before={before}, after={after}"
+    )
diff --git a/tests/unit/test_cache.py b/tests/unit/test_cache.py
index a1657783..12ce9a72 100644
--- a/tests/unit/test_cache.py
+++ b/tests/unit/test_cache.py
@@ -231,3 +231,54 @@ async def test_admins_startup_load_uses_cache_when_present(
 
     assert ldap_called is False
     assert mock_app.extensions["admins"] == frozenset({"cached_alice", "cached_bob"})
+
+
+@pytest.mark.asyncio
+async def test_email_uid_read_ignores_empty_disk_cache(state_dir: pathlib.Path):
+    cache_path = state_dir / "secrets" / "cached" / "email_uid.json"
+    cache_path.parent.mkdir(parents=True)
+    cache_data = cache.EmailUidCache(
+        refreshed=datetime.datetime.now(datetime.UTC),
+        hashes={},
+        reverse={},
+    )
+    cache_path.write_text(cache_data.model_dump_json())
+
+    assert cache._email_uid_read_from_file() is None
+    assert not cache_path.exists()
+    assert await cache._email_uid_read_from_file_async() is None
+
+
+@pytest.mark.asyncio
+async def test_email_uid_refresh_refuses_empty_ldap_mapping(
+    state_dir: pathlib.Path, mock_app: MockApp, monkeypatch: "MonkeyPatch"
+):
+    async def email_to_uid_map() -> dict[str, str]:
+        return {}
+
+    monkeypatch.setattr("atr.util.email_to_uid_map", email_to_uid_map)
+
+    with pytest.raises(RuntimeError, match="no usable LDAP email mappings"):
+        await cache.email_uid_refresh()
+
+    cache_path = state_dir / "secrets" / "cached" / "email_uid.json"
+    assert not cache_path.exists()
+    assert "email_uid_hashes" not in mock_app.extensions
+    assert "email_uid_reverse" not in mock_app.extensions
+
+
+@pytest.mark.asyncio
+async def test_email_uid_view_reloads_changed_disk_cache(state_dir: pathlib.Path, mock_app: MockApp):
+    old_hash = cache._email_uid_hash("old@example.org")
+    new_hash = cache._email_uid_hash("new@example.org")
+    mock_app.extensions["email_uid_hashes"] = {old_hash: "old"}
+    mock_app.extensions["email_uid_reverse"] = {"old": [old_hash]}
+    mock_app.extensions["email_uid_file_mtime_ns"] = 0
+
+    await cache.email_uid_save_to_file({new_hash: "new"}, {"new": [new_hash]})
+
+    lookup = cache.email_uid_view()
+
+    assert lookup.get("new@example.org") == "new"
+    assert lookup.get("old@example.org") is None
+    assert mock_app.extensions["email_uid_hashes"] == {new_hash: "new"}
diff --git a/tests/unit/test_keys_writer.py b/tests/unit/test_keys_writer.py
index e56af89c..0658c5b0 100644
--- a/tests/unit/test_keys_writer.py
+++ b/tests/unit/test_keys_writer.py
@@ -227,10 +227,12 @@ async def test_ensure_allows_key_without_apache_uid_for_bulk_import() -> None:
         key_model=_public_signing_key("fp1", apache_uid=None),
     )
     database_outcomes = outcome.List(outcome.Result(key))
-    ldap_data = {}
+    lookup = keys_writer.cache.EmailUidLookup({})
 
     with (
-        mock.patch.object(keys_writer.util, "email_to_uid_map", new=mock.AsyncMock()) as email_to_uid_map,
+        mock.patch.object(
+            keys_writer.cache, "email_uid_view_or_live", new=mock.AsyncMock(return_value=lookup)
+        ) as email_uid_view,
         mock.patch.object(keys_writer.util, "parse_key_blocks", return_value=["block-one"]),
         mock.patch.object(writer, "_CommitteeParticipant__block_models", return_value=[key]) as block_models,
         mock.patch.object(
@@ -239,52 +241,16 @@ async def test_ensure_allows_key_without_apache_uid_for_bulk_import() -> None:
             new=mock.AsyncMock(return_value=database_outcomes),
         ) as database_add_models,
     ):
-        result = await writer._CommitteeParticipant__ensure("keys text", ldap_data=ldap_data)
+        result = await writer._CommitteeParticipant__ensure("keys text")
 
     assert result is database_outcomes
-    email_to_uid_map.assert_not_awaited()
-    block_models.assert_called_once_with("block-one", ldap_data)
+    email_uid_view.assert_awaited_once()
+    block_models.assert_called_once_with("block-one", lookup)
     database_add_models.assert_awaited_once()
     parsed_outcomes = database_add_models.await_args.args[0]
     assert parsed_outcomes.result_count == 1
 
 
-@pytest.mark.asyncio
-async def test_ensure_reuses_supplied_ldap_data_for_bulk_import() -> None:
-    data = MockData(None, committees_after_commit={})
-    writer, _write_as = _make_foundation_admin(data, "alpha")
-    database_outcomes = outcome.List()
-    ldap_data = {"alice@example.org": "alice"}
-
-    with (
-        mock.patch.object(keys_writer.util, "email_to_uid_map", new=mock.AsyncMock()) as email_to_uid_map,
-        mock.patch.object(keys_writer.util, "parse_key_blocks", return_value=["block-one", "block-two"]),
-        mock.patch.object(
-            writer,
-            "_CommitteeParticipant__block_models",
-            side_effect=[
-                [SimpleNamespace(fingerprint="one")],
-                [SimpleNamespace(fingerprint="two")],
-            ],
-        ) as block_models,
-        mock.patch.object(
-            writer,
-            "_CommitteeParticipant__database_add_models",
-            new=mock.AsyncMock(return_value=database_outcomes),
-        ) as database_add_models,
-    ):
-        result = await writer._CommitteeParticipant__ensure("keys text", ldap_data=ldap_data)
-
-    assert result is database_outcomes
-    email_to_uid_map.assert_not_awaited()
-    assert block_models.call_count == 2
-    assert {call.args[0] for call in block_models.call_args_list} == {"block-one", "block-two"}
-    assert all(call.args[1] is ldap_data for call in block_models.call_args_list)
-    database_add_models.assert_awaited_once()
-    parsed_outcomes = database_add_models.await_args.args[0]
-    assert parsed_outcomes.result_count == 2
-
-
 @pytest.mark.asyncio
 async def test_ensure_stored_one_accepts_key_with_apache_uid() -> None:
     data = MockData(None, committees_after_commit={})
@@ -294,11 +260,12 @@ async def test_ensure_stored_one_accepts_key_with_apache_uid() -> None:
         key_model=_public_signing_key("fp1", apache_uid="alice"),
     )
     database_outcome = outcome.Result(key)
+    lookup = keys_writer.cache.EmailUidLookup({})
 
     with (
         mock.patch.object(
-            keys_writer.util, "email_to_uid_map", new=mock.AsyncMock(return_value={})
-        ) as email_to_uid_map,
+            keys_writer.cache, "email_uid_view_or_live", new=mock.AsyncMock(return_value=lookup)
+        ) as email_uid_view,
         mock.patch.object(keys_writer.util, "parse_key_blocks", return_value=["block-one"]),
         mock.patch.object(writer, "_FoundationCommitter__block_model", return_value=key) as block_model,
         mock.patch.object(
@@ -310,8 +277,8 @@ async def test_ensure_stored_one_accepts_key_with_apache_uid() -> None:
         result = await writer.ensure_stored_one("keys text")
 
     assert result is database_outcome
-    email_to_uid_map.assert_awaited_once()
-    block_model.assert_called_once_with("block-one", {})
+    email_uid_view.assert_awaited_once()
+    block_model.assert_called_once_with("block-one", lookup)
     database_add_model.assert_awaited_once_with(key)
 
 
@@ -323,11 +290,12 @@ async def test_ensure_stored_one_rejects_key_without_apache_uid() -> None:
         status=keys_writer.types.KeyStatus.PARSED,
         key_model=_public_signing_key("fp1", apache_uid=None),
     )
+    lookup = keys_writer.cache.EmailUidLookup({})
 
     with (
         mock.patch.object(
-            keys_writer.util, "email_to_uid_map", new=mock.AsyncMock(return_value={})
-        ) as email_to_uid_map,
+            keys_writer.cache, "email_uid_view_or_live", new=mock.AsyncMock(return_value=lookup)
+        ) as email_uid_view,
         mock.patch.object(keys_writer.util, "parse_key_blocks", return_value=["block-one"]),
         mock.patch.object(writer, "_FoundationCommitter__block_model", return_value=key) as block_model,
         mock.patch.object(
@@ -342,11 +310,49 @@ async def test_ensure_stored_one_rejects_key_without_apache_uid() -> None:
     error = result.error_or_none()
     assert isinstance(error, keys_writer.types.UnknownApacheUidError)
     assert str(error) == "OpenPGP key could not be associated with an ASF UID. Import it through a KEYS file instead."
-    email_to_uid_map.assert_awaited_once()
-    block_model.assert_called_once_with("block-one", {})
+    email_uid_view.assert_awaited_once()
+    block_model.assert_called_once_with("block-one", lookup)
     database_add_model.assert_not_awaited()
 
 
+@pytest.mark.asyncio
+async def test_ensure_uses_cached_email_lookup_for_bulk_import() -> None:
+    data = MockData(None, committees_after_commit={})
+    writer, _write_as = _make_foundation_admin(data, "alpha")
+    database_outcomes = outcome.List()
+    lookup = keys_writer.cache.EmailUidLookup({"deadbeef": "alice"})
+
+    with (
+        mock.patch.object(
+            keys_writer.cache, "email_uid_view_or_live", new=mock.AsyncMock(return_value=lookup)
+        ) as email_uid_view,
+        mock.patch.object(keys_writer.util, "parse_key_blocks", return_value=["block-one", "block-two"]),
+        mock.patch.object(
+            writer,
+            "_CommitteeParticipant__block_models",
+            side_effect=[
+                [SimpleNamespace(fingerprint="one")],
+                [SimpleNamespace(fingerprint="two")],
+            ],
+        ) as block_models,
+        mock.patch.object(
+            writer,
+            "_CommitteeParticipant__database_add_models",
+            new=mock.AsyncMock(return_value=database_outcomes),
+        ) as database_add_models,
+    ):
+        result = await writer._CommitteeParticipant__ensure("keys text")
+
+    assert result is database_outcomes
+    email_uid_view.assert_awaited_once()
+    assert block_models.call_count == 2
+    assert {call.args[0] for call in block_models.call_args_list} == {"block-one", "block-two"}
+    assert all(call.args[1] is lookup for call in block_models.call_args_list)
+    database_add_models.assert_awaited_once()
+    parsed_outcomes = database_add_models.await_args.args[0]
+    assert parsed_outcomes.result_count == 2
+
+
 def test_key_expires_at_uses_v4_user_binding_expiration() -> None:
     key, _ = keys_writer.openpgp.PublicKey.from_armor(_EMBEDDED_V4_EXPIRING_KEY_ASC)
     binding = next(iter(key.user_bindings()))
@@ -378,7 +384,9 @@ def test_public_key_model_stores_latest_self_signature_separately_from_expiry()
     data = MockData(None, committees_after_commit={})
     writer, _write, _write_as = _make_foundation_committer_with_audit(data)
 
-    key_model = writer.public_key_model(key, {}, original_key_block=_EMBEDDED_V4_EXPIRING_KEY_ASC)
+    key_model = writer.public_key_model(
+        key, keys_writer.cache.EmailUidLookup({}), original_key_block=_EMBEDDED_V4_EXPIRING_KEY_ASC
+    )
     latest_self_signature = keys_writer._latest_self_signature(key)
 
     assert latest_self_signature is not None
diff --git a/tests/unit/test_tabulate.py b/tests/unit/test_tabulate.py
index fa67503e..adc76f61 100644
--- a/tests/unit/test_tabulate.py
+++ b/tests/unit/test_tabulate.py
@@ -187,17 +187,14 @@ async def test_votes_excludes_receipts_by_rfc_message_id_only(monkeypatch: pytes
         )
 
     monkeypatch.setattr(tabulate.config, "is_dev_environment", lambda: False)
-    monkeypatch.setattr(
-        tabulate.util,
-        "email_to_uid_map",
-        mock.AsyncMock(
-            return_value={
-                "receipt@example.com": "receipt-voter",
-                "other@example.com": "other-voter",
-                "midonly@example.com": "mid-only-voter",
-            }
-        ),
+    lookup = tabulate.cache.EmailUidLookup(
+        {
+            tabulate.cache._email_uid_hash("receipt@example.com"): "receipt-voter",
+            tabulate.cache._email_uid_hash("other@example.com"): "other-voter",
+            tabulate.cache._email_uid_hash("midonly@example.com"): "mid-only-voter",
+        }
     )
+    monkeypatch.setattr(tabulate.cache, "email_uid_view_or_live", mock.AsyncMock(return_value=lookup))
     monkeypatch.setattr(tabulate.util, "thread_messages", _thread_messages)
 
     _start_unixtime, tabulated_votes = await tabulate.votes(


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@tooling.apache.org
For additional commands, e-mail: commits-help@tooling.apache.org