-
Notifications
You must be signed in to change notification settings - Fork 6
[FC-0099] refactor: manage enforcer state and casbin models only when app is ready #93
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 18 commits
Commits
Show all changes
21 commits
Select commit
Hold shift + click to select a range
ed9ef8f
refactor: manage enforcer state within class when app is ready
mariajgrimaldi 19bf8df
refactor: get class attribute in runtime so it's available
mariajgrimaldi 3c728c4
refactor: use common settings module as default
mariajgrimaldi 986d014
refactor: move adding installed app when apps are ready
mariajgrimaldi 421cd21
refactor: move authzenforcer to ready hook
mariajgrimaldi 015b341
refactor: add casbin adapter to common to avoid build failing
mariajgrimaldi 84f4cee
refactor: include casbin in installed apps before loading models
mariajgrimaldi 71503ea
Revert "refactor: add casbin adapter to common to avoid build failing"
mariajgrimaldi 0af187b
refactor: move installed apps configuration to common settings
mariajgrimaldi cb06ea2
refactor: skip improperly configured issue when apps are not fully co…
mariajgrimaldi 820c8d4
refactor: override casbin adapter config for a safe load
mariajgrimaldi 4a77050
refactor: go back to using test settings but fix import order
mariajgrimaldi 9ceaa07
refactor: initialize enforcer when firstly use to avoid raising error…
mariajgrimaldi 336d7d7
docs: add inline doc explaining why initialize enforcer
mariajgrimaldi b2bb892
refactor: address rebase failure
mariajgrimaldi 5996ef9
refactor: address quality issues
mariajgrimaldi 64ee68d
refactor: address quality issues
mariajgrimaldi bd9d677
refactor: address quality issues
mariajgrimaldi 370d380
refactor: use load policy before enforcing
mariajgrimaldi 55a58ec
refactor: declare enforcer variable
mariajgrimaldi 6e15616
docs: update changelog and fix release order
mariajgrimaldi File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,23 @@ | ||
| """Initialization for the casbin_adapter Django application. | ||
|
|
||
| This overrides the default AppConfig to avoid making queries to the database | ||
| when the app is not fully loaded (e.g., while pulling translations). Moved | ||
| the initialization of the enforcer to a lazy load when it's first used. | ||
|
|
||
| See openedx_authz/engine/enforcer.py for the enforcer implementation. | ||
| """ | ||
|
|
||
| from django.apps import AppConfig | ||
|
|
||
|
|
||
| class CasbinAdapterConfig(AppConfig): | ||
| name = "casbin_adapter" | ||
|
|
||
| def ready(self): | ||
| """Initialize the casbin_adapter app. | ||
|
|
||
| The upstream casbin_adapter app tries to initialize the enforcer | ||
| when the app is loaded, which can lead to issues if the database is not | ||
| ready (e.g., while pulling translations). To avoid this, we override | ||
| the ready method and do not initialize the enforcer here. | ||
| """ |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -10,7 +10,7 @@ | |
| - Watcher: Redis-based watcher for real-time policy updates | ||
|
|
||
| Usage: | ||
| from openedx_authz.engine.enforcer import enforcer | ||
| from openedx_authz.engine.enforcer import AuthzEnforcer | ||
| allowed = enforcer.enforce(user, resource, action) | ||
|
|
||
| Requires `CASBIN_MODEL` setting and Redis configuration for watcher functionality. | ||
|
|
@@ -19,20 +19,93 @@ | |
| import logging | ||
|
|
||
| from casbin import FastEnforcer | ||
| from casbin_adapter.enforcer import initialize_enforcer | ||
| from django.conf import settings | ||
|
|
||
| from openedx_authz.engine.adapter import ExtendedAdapter | ||
| from openedx_authz.engine.watcher import Watcher | ||
|
|
||
| logger = logging.getLogger(__name__) | ||
|
|
||
| adapter = ExtendedAdapter() | ||
| enforcer = FastEnforcer(settings.CASBIN_MODEL, adapter, enable_log=True) | ||
| enforcer.enable_auto_save(True) | ||
|
|
||
| if Watcher: | ||
| try: | ||
| enforcer.set_watcher(Watcher) | ||
| logger.info("Watcher successfully set on Casbin enforcer") | ||
| except Exception as e: # pylint: disable=broad-exception-caught | ||
| logger.error(f"Failed to set watcher on Casbin enforcer: {e}") | ||
| class AuthzEnforcer: | ||
| """Singleton class to manage the Casbin FastEnforcer instance. | ||
|
|
||
| Ensures a single enforcer instance is created safely and configured with the | ||
| ExtendedAdapter and Redis watcher for policy management and synchronization. | ||
|
|
||
| There are two main use cases for this class: | ||
|
|
||
| 1. Directly get the enforcer instance and initialize it if needed:: | ||
|
|
||
| from openedx_authz.engine.enforcer import AuthzEnforcer | ||
| enforcer = AuthzEnforcer.get_enforcer() | ||
| allowed = enforcer.enforce(user, resource, action) | ||
|
|
||
| 2. Instantiate the class to get the singleton enforcer instance:: | ||
|
|
||
| from openedx_authz.engine.enforcer import AuthzEnforcer | ||
| enforcer = AuthzEnforcer() | ||
| allowed = enforcer.get_enforcer().enforce(user, resource, action) | ||
|
|
||
| Any of the two approaches will yield the same singleton enforcer instance. | ||
| """ | ||
|
|
||
| _enforcer = None | ||
|
|
||
| def __new__(cls): | ||
| """Singleton pattern to ensure a single enforcer instance.""" | ||
| if cls._enforcer is None: | ||
| cls._enforcer = cls._initialize_enforcer() | ||
| return cls._enforcer | ||
|
|
||
| @classmethod | ||
| def get_enforcer(cls) -> FastEnforcer: | ||
| """Get the enforcer instance, creating it if needed. | ||
|
|
||
| Returns: | ||
| FastEnforcer: The singleton enforcer instance. | ||
| """ | ||
| if cls._enforcer is None: | ||
| cls._enforcer = cls._initialize_enforcer() | ||
|
Comment on lines
+69
to
+70
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I don't think this would be needed. |
||
| return cls._enforcer | ||
|
|
||
| @staticmethod | ||
| def _initialize_enforcer() -> FastEnforcer: | ||
| """ | ||
| Create and configure the Casbin FastEnforcer instance. | ||
|
|
||
| This method initializes the FastEnforcer with the ExtendedAdapter | ||
| for database policy storage and sets up the Redis watcher for real-time | ||
| policy synchronization if the Watcher is available. It also initializes | ||
| the enforcer with the specified database alias from settings. | ||
|
|
||
| Returns: | ||
| FastEnforcer: Configured Casbin enforcer with adapter and watcher | ||
| """ | ||
| db_alias = getattr(settings, "CASBIN_DB_ALIAS", "default") | ||
|
|
||
| try: | ||
| # Initialize the enforcer with the specified database alias to set up the adapter. | ||
| # Best to lazy load it when it's first used to ensure the database is ready and avoid | ||
| # issues when the app is not fully loaded (e.g., while pulling translations, etc.). | ||
| initialize_enforcer(db_alias) | ||
| except Exception as e: | ||
| logger.error(f"Failed to initialize Casbin enforcer with DB alias '{db_alias}': {e}") | ||
| raise | ||
|
|
||
| adapter = ExtendedAdapter() | ||
| enforcer = FastEnforcer(settings.CASBIN_MODEL, adapter, enable_log=True) | ||
| enforcer.enable_auto_save(True) | ||
|
|
||
| if not Watcher: | ||
| logger.warning("Redis configuration not completed successfully. Watcher is disabled.") | ||
| return enforcer | ||
|
|
||
| try: | ||
| enforcer.set_watcher(Watcher) | ||
| logger.info("Watcher successfully set on Casbin enforcer") | ||
| except Exception as e: # pylint: disable=broad-exception-caught | ||
| logger.error(f"Failed to set watcher on Casbin enforcer: {e}") | ||
|
|
||
| return enforcer | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.