diff --git a/src/middlewared/middlewared/pytest/unit/utils/test_audit.py b/src/middlewared/middlewared/pytest/unit/utils/test_audit.py new file mode 100644 index 0000000000000..6ccb40354496a --- /dev/null +++ b/src/middlewared/middlewared/pytest/unit/utils/test_audit.py @@ -0,0 +1,31 @@ +import pytest + +from middlewared.auth import ( + ApiKeySessionManagerCredentials, + UserSessionManagerCredentials, + TrueNasNodeSessionManagerCredentials +) + +from middlewared.utils.audit import audit_username_from_session +from types import SimpleNamespace + + +API_KEY = SimpleNamespace(api_key={'id': 1, 'name': 'MY_KEY'}) + +USER_SESSION = UserSessionManagerCredentials({'username': 'bob', 'privilege': {'allowlist': []}}) +API_KEY_SESSION = ApiKeySessionManagerCredentials(API_KEY) +TOKEN_USER_SESSION = SimpleNamespace(root_credentials=USER_SESSION, is_user_session=True, user=USER_SESSION.user) +TOKEN_API_KEY_SESSION = SimpleNamespace(root_credentials=API_KEY_SESSION, is_user_session=False) +NODE_SESSION = TrueNasNodeSessionManagerCredentials() + + +@pytest.mark.parametrize('cred,expected', [ + (None, '.TRUENAS_INTERNAL'), + (USER_SESSION, 'bob'), + (API_KEY_SESSION, '.TRUENAS_API_KEY:MY_KEY'), + (TOKEN_USER_SESSION, 'bob'), + (TOKEN_API_KEY_SESSION, '.TRUENAS_API_KEY:MY_KEY'), + (NODE_SESSION, '.TRUENAS_NODE') +]) +def test_privilege_has_webui_access(cred, expected): + assert audit_username_from_session(cred) == expected diff --git a/src/middlewared/middlewared/utils/audit.py b/src/middlewared/middlewared/utils/audit.py index ebc9c002d4b45..faa3815c4e435 100644 --- a/src/middlewared/middlewared/utils/audit.py +++ b/src/middlewared/middlewared/utils/audit.py @@ -24,7 +24,7 @@ def audit_username_from_session(cred) -> str: cred = cred.root_credentials if isinstance(cred, ApiKeySessionManagerCredentials): - return f'{API_KEY_PREFIX}{app.authenticated_credentials.api_key["name"]}' + return f'{API_KEY_PREFIX}{cred.api_key.api_key["name"]}' elif isinstance(cred, TrueNasNodeSessionManagerCredentials): return NODE_SESSION