shieldapi 2.4.0__tar.gz → 2.5.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (22) hide show
  1. {shieldapi-2.4.0/shieldapi.egg-info → shieldapi-2.5.0}/PKG-INFO +2 -2
  2. {shieldapi-2.4.0 → shieldapi-2.5.0}/setup.cfg +3 -3
  3. {shieldapi-2.4.0 → shieldapi-2.5.0}/shieldapi/keycloak_utils.py +49 -19
  4. {shieldapi-2.4.0 → shieldapi-2.5.0/shieldapi.egg-info}/PKG-INFO +2 -2
  5. {shieldapi-2.4.0 → shieldapi-2.5.0}/tests/test_keycloak_utils.py +36 -0
  6. {shieldapi-2.4.0 → shieldapi-2.5.0}/LICENSE +0 -0
  7. {shieldapi-2.4.0 → shieldapi-2.5.0}/README.md +0 -0
  8. {shieldapi-2.4.0 → shieldapi-2.5.0}/pyproject.toml +0 -0
  9. {shieldapi-2.4.0 → shieldapi-2.5.0}/setup.py +0 -0
  10. {shieldapi-2.4.0 → shieldapi-2.5.0}/shieldapi/__init__.py +0 -0
  11. {shieldapi-2.4.0 → shieldapi-2.5.0}/shieldapi/frameworks/__init__.py +0 -0
  12. {shieldapi-2.4.0 → shieldapi-2.5.0}/shieldapi/frameworks/fastapi.py +0 -0
  13. {shieldapi-2.4.0 → shieldapi-2.5.0}/shieldapi/frameworks/flask.py +0 -0
  14. {shieldapi-2.4.0 → shieldapi-2.5.0}/shieldapi.egg-info/SOURCES.txt +0 -0
  15. {shieldapi-2.4.0 → shieldapi-2.5.0}/shieldapi.egg-info/dependency_links.txt +0 -0
  16. {shieldapi-2.4.0 → shieldapi-2.5.0}/shieldapi.egg-info/requires.txt +0 -0
  17. {shieldapi-2.4.0 → shieldapi-2.5.0}/shieldapi.egg-info/top_level.txt +0 -0
  18. {shieldapi-2.4.0 → shieldapi-2.5.0}/tests/__init__.py +0 -0
  19. {shieldapi-2.4.0 → shieldapi-2.5.0}/tests/conftest.py +0 -0
  20. {shieldapi-2.4.0 → shieldapi-2.5.0}/tests/mock.py +0 -0
  21. {shieldapi-2.4.0 → shieldapi-2.5.0}/tests/test_fastapi.py +0 -0
  22. {shieldapi-2.4.0 → shieldapi-2.5.0}/tests/test_flask.py +0 -0
@@ -1,13 +1,13 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: shieldapi
3
- Version: 2.4.0
3
+ Version: 2.5.0
4
4
  Summary: A package for endpoint protection of APIs using Keycloak
5
5
  Author: SINTEF, Fraunhofer IWM
6
6
  Author-email: yoav.nahshon@iwm.fraunhofer.de
7
7
  Classifier: Programming Language :: Python :: 3
8
8
  Classifier: License :: OSI Approved :: BSD License
9
9
  Classifier: Operating System :: OS Independent
10
- Requires-Python: >=3.9
10
+ Requires-Python: >=3.10
11
11
  Description-Content-Type: text/markdown
12
12
  License-File: LICENSE
13
13
  Requires-Dist: python-keycloak>=4.0
@@ -1,6 +1,6 @@
1
1
  [metadata]
2
2
  name = shieldapi
3
- version = v2.4.0
3
+ version = v2.5.0
4
4
  author = SINTEF, Fraunhofer IWM
5
5
  author_email = yoav.nahshon@iwm.fraunhofer.de
6
6
  description = A package for endpoint protection of APIs using Keycloak
@@ -13,7 +13,7 @@ classifiers =
13
13
 
14
14
  [options]
15
15
  packages = find:
16
- python_requires = >=3.9
16
+ python_requires = >=3.10
17
17
  install_requires =
18
18
  python-keycloak>=4.0
19
19
 
@@ -34,7 +34,7 @@ tests =
34
34
  pytest-mock>=3.10.0
35
35
 
36
36
  [bumpver]
37
- current_version = "v2.4.0"
37
+ current_version = "v2.5.0"
38
38
  version_pattern = "vMAJOR.MINOR.PATCH[PYTAGNUM]"
39
39
  commit_message = "Bump version {old_version} -> {new_version}"
40
40
  commit = True
@@ -1,11 +1,12 @@
1
1
  """Functions for interacting with a Keycloak-client."""
2
2
 
3
3
  import os
4
+ import threading
4
5
  import warnings
5
6
  from ast import literal_eval
6
7
  from typing import Any, Dict, Optional, Tuple, Union
7
8
 
8
- from keycloak import KeycloakAdmin, KeycloakOpenID
9
+ from keycloak import KeycloakAdmin, KeycloakOpenID, KeycloakOpenIDConnection
9
10
 
10
11
  from shieldapi import logger
11
12
 
@@ -71,7 +72,13 @@ def get_keycloak_admin(
71
72
  verify: Optional[bool] = None,
72
73
  use_service_account: Optional[bool] = None,
73
74
  ) -> KeycloakAdmin:
74
- """Create a KeycloakAdmin instance from parameters or environment variables.
75
+ """Return the KeycloakAdmin for the given parameters or environment variables.
76
+
77
+ The instance is shared: calls with the same settings return the same
78
+ instance, which logs in once and refreshes its token when needed.
79
+ Creating one instance per request would log in on every request, and
80
+ Keycloak rejects simultaneous password logins of the same user with
81
+ "invalid_grant: Invalid user credentials".
75
82
 
76
83
  Kwargs:
77
84
  server_url: Keycloak server URL. Falls back to $KEYCLOAK_HOST.
@@ -88,31 +95,54 @@ def get_keycloak_admin(
88
95
  use_service_account = _get_value(
89
96
  use_service_account, "KEYCLOAK_USE_SERVICE_ACCOUNT", False, True
90
97
  )
98
+ settings = {
99
+ "server_url": _get_value(
100
+ server_url, "KEYCLOAK_HOST", "http://keycloak:8080/auth/"
101
+ )
102
+ }
91
103
  if use_service_account:
92
104
  logger.debug("Using Service Account for Admin authentication")
93
- admin = KeycloakAdmin(
94
- server_url=_get_value(
95
- server_url, "KEYCLOAK_HOST", "http://keycloak:8080/auth/"
96
- ),
97
- client_id=_get_value(client_id, "KEYCLOAK_CLIENT_ID"),
98
- client_secret_key=_get_value(client_secret, "KEYCLOAK_CLIENT_SECRET"),
99
- realm_name=_get_value(realm_name, "KEYCLOAK_REALM_NAME"),
100
- verify=_get_value(verify, "KEYCLOAK_VERIFY_HOST", False, True),
105
+ settings["client_id"] = _get_value(client_id, "KEYCLOAK_CLIENT_ID")
106
+ settings["client_secret_key"] = _get_value(
107
+ client_secret, "KEYCLOAK_CLIENT_SECRET"
101
108
  )
102
109
  else:
103
110
  logger.debug("Using Custom User Account for Admin authentication")
104
- admin = KeycloakAdmin(
105
- server_url=_get_value(
106
- server_url, "KEYCLOAK_HOST", "http://keycloak:8080/auth/"
107
- ),
108
- username=_get_value(username, "KEYCLOAK_REALM_ADMIN_USER"),
109
- password=_get_value(password, "KEYCLOAK_REALM_ADMIN_PASSWORD"),
110
- realm_name=_get_value(realm_name, "KEYCLOAK_REALM_NAME"),
111
- verify=_get_value(verify, "KEYCLOAK_VERIFY_HOST", False, True),
112
- )
111
+ settings["username"] = _get_value(username, "KEYCLOAK_REALM_ADMIN_USER")
112
+ settings["password"] = _get_value(password, "KEYCLOAK_REALM_ADMIN_PASSWORD")
113
+ settings["realm_name"] = _get_value(realm_name, "KEYCLOAK_REALM_NAME")
114
+ settings["verify"] = _get_value(verify, "KEYCLOAK_VERIFY_HOST", False, True)
115
+
116
+ key = tuple(sorted(settings.items()))
117
+ with _admin_clients_lock:
118
+ admin = _admin_clients.get(key)
119
+ if admin is None:
120
+ admin = KeycloakAdmin(connection=_SharedConnection(**settings))
121
+ _admin_clients[key] = admin
113
122
  return admin
114
123
 
115
124
 
125
+ class _SharedConnection(KeycloakOpenIDConnection):
126
+ """Admin connection that is safe to share between threads.
127
+
128
+ Only one thread at a time checks the token and logs in or refreshes it;
129
+ the others wait and then use the new token. The check itself is left to
130
+ python-keycloak, whose token expiry type differs between versions.
131
+ """
132
+
133
+ def __init__(self, *args, **kwargs):
134
+ self._token_lock = threading.Lock()
135
+ super().__init__(*args, **kwargs)
136
+
137
+ def _refresh_if_required(self):
138
+ with self._token_lock:
139
+ super()._refresh_if_required()
140
+
141
+
142
+ _admin_clients: Dict[tuple, KeycloakAdmin] = {}
143
+ _admin_clients_lock = threading.Lock()
144
+
145
+
116
146
  def _get_value(
117
147
  param: Any,
118
148
  env_var: str,
@@ -1,13 +1,13 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: shieldapi
3
- Version: 2.4.0
3
+ Version: 2.5.0
4
4
  Summary: A package for endpoint protection of APIs using Keycloak
5
5
  Author: SINTEF, Fraunhofer IWM
6
6
  Author-email: yoav.nahshon@iwm.fraunhofer.de
7
7
  Classifier: Programming Language :: Python :: 3
8
8
  Classifier: License :: OSI Approved :: BSD License
9
9
  Classifier: Operating System :: OS Independent
10
- Requires-Python: >=3.9
10
+ Requires-Python: >=3.10
11
11
  Description-Content-Type: text/markdown
12
12
  License-File: LICENSE
13
13
  Requires-Dist: python-keycloak>=4.0
@@ -133,3 +133,39 @@ def test_get_token_sub(requests_mock):
133
133
  register_mock(requests_mock)
134
134
  result = get_token_sub("123")
135
135
  assert result == "test-user-id"
136
+
137
+
138
+ def test_keycloak_admin_is_shared(requests_mock):
139
+ """Calls with the same settings return the same admin client."""
140
+ register_mock(requests_mock)
141
+ first = get_keycloak_admin()
142
+ assert get_keycloak_admin() is first
143
+ with pytest.warns(UserWarning, match="KEYCLOAK_REALM_NAME"):
144
+ other_realm = get_keycloak_admin(realm_name="other_realm")
145
+ assert other_realm is not first
146
+
147
+
148
+ def test_keycloak_admin_logs_in_once_for_parallel_requests(requests_mock):
149
+ """Parallel requests wait for one login instead of each logging in.
150
+
151
+ Keycloak rejects simultaneous password logins of the same user.
152
+ """
153
+ import threading
154
+ import time
155
+ from concurrent.futures import ThreadPoolExecutor
156
+
157
+ register_mock(requests_mock)
158
+ connection = get_keycloak_admin(realm_name=None).connection
159
+ connection.token = None # not logged in yet
160
+ logins = []
161
+
162
+ def fake_login():
163
+ logins.append(threading.get_ident())
164
+ time.sleep(0.05)
165
+ connection.token = {"access_token": "abc", "expires_in": 300}
166
+
167
+ connection.refresh_token = fake_login
168
+ with ThreadPoolExecutor(8) as pool:
169
+ list(pool.map(lambda _: connection._refresh_if_required(), range(8)))
170
+
171
+ assert len(logins) == 1
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes