From 060c96a6595eaf10d85b663756e1aac46dfad60e Mon Sep 17 00:00:00 2001 From: Taylor Payne Date: Thu, 3 Dec 2026 16:27:41 -0700 Subject: [PATCH] fix: load AuthzEnforcer policy before publishing the singleton The singleton was built lazily without a lock. Two concurrent first requests in one process could each build an enforcer; the second overwrote the loaded one, saw the policy version as current, and skipped the load, leaving the process with an empty policy until the next authz write. Build and load the enforcer under a class-level lock and assign it only after the first load. AuthzEnforcer() now goes through the same path, so it also returns a loaded enforcer. Closes #671 --- CHANGELOG.rst | 5 ++ src/openedx_authz/engine/enforcer.py | 60 ++++++++++++--- src/openedx_authz/tests/test_enforcer.py | 93 ++++++++++++++++++++++++ 3 files changed, 147 insertions(+), 11 deletions(-) diff --git a/CHANGELOG.rst b/CHANGELOG.rst index 92351ab58..d659271a1 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -202,6 +202,11 @@ Fixed conflict regardless of priority, matching schema validation; only ``role_extensions`` are resolved by priority. This aligns the compiler with ADR 0031 and removes a path where a higher-priority file could silently replace a role's base definition. +* ``AuthzEnforcer`` now builds and loads its enforcer under a lock and publishes it only after the + first policy load. Before, two requests arriving together as a process's first could leave that + process with an enforcer that never loaded its policy, so it refused role assignments and + permission checks until the next authz write + (`#671 `_). * Migration ``0007_coursescope`` no longer fails with MySQL error 3780 when the platform's course table has a collation other than ``utf8mb4_unicode_ci``, because on MySQL it gives ``course_overview_id`` the collation of the course column it references before creating the foreign key (`#593 `_). Databases where an earlier run of ``0007`` failed need the steps in :doc:`Recover From Failed Course Scope Migrations ` first. Changed diff --git a/src/openedx_authz/engine/enforcer.py b/src/openedx_authz/engine/enforcer.py index c45cba03a..2710b9930 100644 --- a/src/openedx_authz/engine/enforcer.py +++ b/src/openedx_authz/engine/enforcer.py @@ -16,6 +16,7 @@ """ import logging +import threading from copy import deepcopy from uuid import uuid4 @@ -56,18 +57,47 @@ class AuthzEnforcer: Attributes: _enforcer (SyncedEnforcer): The singleton enforcer instance. _adapter (ExtendedAdapter): The singleton adapter instance. + _init_lock (threading.Lock): Serializes the one-time build and first load + of the singleton so concurrent first callers share one loaded enforcer. """ _enforcer = None _adapter = None _last_policy_loaded_version = None + _init_lock = threading.Lock() def __new__(cls): """Singleton pattern to ensure a single enforcer instance.""" - if cls._enforcer is None: - cls._enforcer = cls._initialize_enforcer() + cls._ensure_enforcer() return cls._enforcer + @classmethod + def _ensure_enforcer(cls) -> None: + """Build and load the singleton enforcer once per process. + + The enforcer is assigned to ``cls._enforcer`` only after its first policy + load. Without the lock, two concurrent first callers could each build an + enforcer; the second would overwrite the loaded one, see the policy + version as already current, and skip loading, leaving the process with + an empty policy (openedx-authz#671). + + Returns: + None + """ + if cls._enforcer is not None: + return + with cls._init_lock: + if cls._enforcer is not None: + return + enforcer = cls._initialize_enforcer() + # Read the version before loading: a write that lands during the load + # bumps the version, so the next check reloads instead of missing it. + version = cls._get_or_init_policy_version() + enforcer.load_policy() + cls._last_policy_loaded_version = version + cls._enforcer = enforcer + logger.info(f"Loaded policy to version {version}") + @classmethod def configure_enforcer_auto_loading(cls, auto_load_policy_interval: int = None): """Enable auto-load policy and auto-save on the enforcer. @@ -168,13 +198,7 @@ def load_policy_if_needed(cls): Returns: None """ - last_version = PolicyCacheControl.get_version() - - if last_version is None: - # No version in cache control; initialize it - last_version = uuid4() - PolicyCacheControl.set_version(last_version) - logger.info("Initialized policy last modified version in cache control.") + last_version = cls._get_or_init_policy_version() if cls._last_policy_loaded_version is None or last_version != cls._last_policy_loaded_version: # Policy has been modified since last load; reload it @@ -182,6 +206,21 @@ def load_policy_if_needed(cls): cls._last_policy_loaded_version = last_version logger.info(f"Reloaded policy to version {last_version}") + @classmethod + def _get_or_init_policy_version(cls): + """Return the current policy version, initializing it if none is stored. + + Returns: + UUID: The policy version stored in the cache control model. + """ + version = PolicyCacheControl.get_version() + if version is None: + # No version in cache control; initialize it + version = uuid4() + PolicyCacheControl.set_version(version) + logger.info("Initialized policy last modified version in cache control.") + return version + @classmethod def invalidate_policy_cache(cls): """Invalidate the current policy cache to force a reload on next check. @@ -203,8 +242,7 @@ def get_enforcer(cls) -> SyncedEnforcer: Returns: SyncedEnforcer: The singleton enforcer instance. """ - if cls._enforcer is None: - cls._enforcer = cls._initialize_enforcer() + cls._ensure_enforcer() # (re)load policy if needed cls.load_policy_if_needed() diff --git a/src/openedx_authz/tests/test_enforcer.py b/src/openedx_authz/tests/test_enforcer.py index be3b96bd2..bc192b063 100644 --- a/src/openedx_authz/tests/test_enforcer.py +++ b/src/openedx_authz/tests/test_enforcer.py @@ -5,12 +5,15 @@ that would be used in production environments. """ +import threading import time +from unittest import mock from uuid import uuid4 from ddt import data as ddt_data from ddt import ddt from django.conf import settings +from django.db import connections from django.test import TestCase, TransactionTestCase, override_settings from openedx_authz.engine.enforcer import AuthzEnforcer @@ -627,3 +630,93 @@ def test_invalidate_policy_cache(self): new_cache_value = PolicyCacheControl.get_version() self.assertIsNotNone(new_cache_value) self.assertNotEqual(new_cache_value, old_cache_value) + + +class TestEnforcerConcurrentInitialization(AuthzEnforcerTestMixin, TransactionTestCase): + """Regression tests for concurrent first access to the singleton (openedx-authz#671). + + Uses TransactionTestCase so worker threads read committed policy rows + through their own database connections. + """ + + THREAD_COUNT = 4 + + def _seed_and_reset(self) -> None: + """Store the static policies in the database, then drop the singleton.""" + enforcer = AuthzEnforcer.get_enforcer() + seed_static_authorization_policies(enforcer) + self._reset_authz_enforcer() + + @override_settings(CASBIN_AUTO_LOAD_POLICY_INTERVAL=0) + def test_concurrent_first_access_shares_one_loaded_enforcer(self): + """Concurrent first callers build the enforcer once and all see a loaded policy. + + Building is slowed down so every thread reaches the singleton check while + the first build is still in progress, the window in which an unguarded + singleton is replaced by a second, never-loaded enforcer. + + Expected result: + - The enforcer is built exactly once + - Every thread receives the same enforcer instance + - That enforcer holds the stored policy (not an empty one) + """ + self._seed_and_reset() + + real_initialize = AuthzEnforcer._initialize_enforcer # pylint: disable=protected-access + + def slow_initialize(): + enforcer = real_initialize() + time.sleep(0.2) + return enforcer + + barrier = threading.Barrier(self.THREAD_COUNT) + results: list = [] + errors: list[BaseException] = [] + results_lock = threading.Lock() + + def worker(): + try: + barrier.wait(timeout=10) + enforcer = AuthzEnforcer.get_enforcer() + with results_lock: + results.append(enforcer) + except BaseException as exc: + with results_lock: + errors.append(exc) + finally: + connections.close_all() + + with mock.patch.object(AuthzEnforcer, "_initialize_enforcer", side_effect=slow_initialize) as spy: + threads = [threading.Thread(target=worker) for _ in range(self.THREAD_COUNT)] + for thread in threads: + thread.start() + for thread in threads: + thread.join(timeout=20) + + self.assertFalse(any(thread.is_alive() for thread in threads), "A worker thread did not finish") + self.assertEqual(errors, []) + self.assertEqual(spy.call_count, 1) + self.assertEqual(len(results), self.THREAD_COUNT) + self.assertTrue(all(enforcer is results[0] for enforcer in results)) + self.assertIs(AuthzEnforcer._enforcer, results[0]) # pylint: disable=protected-access + self.assertGreater(len(AuthzEnforcer._enforcer.get_policy()), 0) # pylint: disable=protected-access + + @override_settings(CASBIN_AUTO_LOAD_POLICY_INTERVAL=0) + def test_instantiation_returns_loaded_enforcer(self): + """``AuthzEnforcer()`` returns the singleton with its policy already loaded. + + Expected result: + - The returned enforcer is the singleton + - Its policy is loaded and the loaded version matches the stored one + """ + self._seed_and_reset() + + enforcer = AuthzEnforcer() + + self.assertIs(enforcer, AuthzEnforcer._enforcer) # pylint: disable=protected-access + # __new__ returns the SyncedEnforcer, which pylint can't infer. + self.assertGreater(len(enforcer.get_policy()), 0) # pylint: disable=no-member + self.assertEqual( + AuthzEnforcer._last_policy_loaded_version, # pylint: disable=protected-access + PolicyCacheControl.get_version(), + )