shieldapi 2.3.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.3.0/shieldapi.egg-info → shieldapi-2.5.0}/PKG-INFO +2 -2
  2. {shieldapi-2.3.0 → shieldapi-2.5.0}/setup.cfg +3 -3
  3. {shieldapi-2.3.0 → shieldapi-2.5.0}/shieldapi/frameworks/fastapi.py +115 -1
  4. {shieldapi-2.3.0 → shieldapi-2.5.0}/shieldapi/keycloak_utils.py +49 -19
  5. {shieldapi-2.3.0 → shieldapi-2.5.0/shieldapi.egg-info}/PKG-INFO +2 -2
  6. {shieldapi-2.3.0 → shieldapi-2.5.0}/tests/mock.py +12 -0
  7. {shieldapi-2.3.0 → shieldapi-2.5.0}/tests/test_fastapi.py +120 -1
  8. {shieldapi-2.3.0 → shieldapi-2.5.0}/tests/test_keycloak_utils.py +36 -0
  9. {shieldapi-2.3.0 → shieldapi-2.5.0}/LICENSE +0 -0
  10. {shieldapi-2.3.0 → shieldapi-2.5.0}/README.md +0 -0
  11. {shieldapi-2.3.0 → shieldapi-2.5.0}/pyproject.toml +0 -0
  12. {shieldapi-2.3.0 → shieldapi-2.5.0}/setup.py +0 -0
  13. {shieldapi-2.3.0 → shieldapi-2.5.0}/shieldapi/__init__.py +0 -0
  14. {shieldapi-2.3.0 → shieldapi-2.5.0}/shieldapi/frameworks/__init__.py +0 -0
  15. {shieldapi-2.3.0 → shieldapi-2.5.0}/shieldapi/frameworks/flask.py +0 -0
  16. {shieldapi-2.3.0 → shieldapi-2.5.0}/shieldapi.egg-info/SOURCES.txt +0 -0
  17. {shieldapi-2.3.0 → shieldapi-2.5.0}/shieldapi.egg-info/dependency_links.txt +0 -0
  18. {shieldapi-2.3.0 → shieldapi-2.5.0}/shieldapi.egg-info/requires.txt +0 -0
  19. {shieldapi-2.3.0 → shieldapi-2.5.0}/shieldapi.egg-info/top_level.txt +0 -0
  20. {shieldapi-2.3.0 → shieldapi-2.5.0}/tests/__init__.py +0 -0
  21. {shieldapi-2.3.0 → shieldapi-2.5.0}/tests/conftest.py +0 -0
  22. {shieldapi-2.3.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.3.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.3.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.3.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,8 +1,9 @@
1
1
  """Dependencies and classes for shieldapi in FastAPI."""
2
2
 
3
3
  import os
4
+ from typing import Optional
4
5
 
5
- from fastapi import HTTPException, Request
6
+ from fastapi import Depends, HTTPException, Request
6
7
  from fastapi.security import HTTPBasic, HTTPBasicCredentials, HTTPBearer
7
8
  from pydantic import BaseModel
8
9
 
@@ -15,6 +16,9 @@ from shieldapi.keycloak_utils import (
15
16
  login,
16
17
  )
17
18
 
19
+ _ADMIN_ROLE = "admin"
20
+ _ROLES_PATH = ("resource_access", "shieldapi", "roles")
21
+
18
22
 
19
23
  class Auth(str):
20
24
  """A custom type to represent the authentication token"""
@@ -70,6 +74,31 @@ class AuthTokenBearer(HTTPBearer):
70
74
  return f"Bearer {auth.credentials}"
71
75
 
72
76
 
77
+ class OptionalAuthTokenBearer(HTTPBearer):
78
+ """Like AuthTokenBearer but returns None for requests with no Authorization header.
79
+
80
+ A present but invalid/expired token still raises HTTP 401 so callers cannot
81
+ accidentally downgrade to anonymous access with a stale credential.
82
+ """
83
+
84
+ def __init__(self, **kwargs):
85
+ super().__init__(auto_error=False, **kwargs)
86
+
87
+ async def __call__(self, request: Request) -> Optional[Auth]:
88
+ auth = await super().__call__(request=request)
89
+ if auth is None:
90
+ return None
91
+ if not auth.credentials:
92
+ raise HTTPException(
93
+ status_code=401,
94
+ detail="An access token is expected but has not been provided",
95
+ )
96
+ if not check_token_validity(auth.credentials):
97
+ logger.warning("OptionalAuthTokenBearer.__call__: Token validation failed")
98
+ raise HTTPException(status_code=401, detail="Token validation failed")
99
+ return f"Bearer {auth.credentials}"
100
+
101
+
73
102
  class BasicLoginCredentials(HTTPBasicCredentials):
74
103
  """
75
104
  A subclass of HTTPBasicCredentials that extracts the basic auth credentials and
@@ -245,3 +274,88 @@ def require_self_or_role(role: str):
245
274
  )
246
275
 
247
276
  return dependency
277
+
278
+
279
+ # ---------------------------------------------------------------------------
280
+ # Generic Keycloak FastAPI dependency chain
281
+ #
282
+ # These can be imported directly into any FastAPI service that uses shieldapi:
283
+ #
284
+ # from shieldapi.frameworks.fastapi import (
285
+ # get_access_token, get_userinfo, get_user_id, get_user_roles, is_admin,
286
+ # get_optional_access_token, get_optional_userinfo,
287
+ # get_optional_user_id, get_optional_user_roles, is_optional_admin,
288
+ # )
289
+ # ---------------------------------------------------------------------------
290
+
291
+
292
+ def get_access_token(request: Request) -> str:
293
+ """Extract the raw Bearer token string from the Authorization header, or '' if absent."""
294
+ auth_header = request.headers.get("Authorization", default="")
295
+ if not auth_header or "Bearer" not in auth_header:
296
+ return ""
297
+ return auth_header.split()[1]
298
+
299
+
300
+ def get_userinfo(token: str = Depends(get_access_token)) -> dict:
301
+ """Introspect the token against Keycloak and return the userinfo dict."""
302
+ return get_keycloak_openid().introspect(token)
303
+
304
+
305
+ def get_user_roles(userinfo: dict = Depends(get_userinfo)):
306
+ """Return the list of shieldapi realm roles from the introspection result."""
307
+ d = userinfo
308
+ for key in _ROLES_PATH:
309
+ d = d.get(key, {})
310
+ return d if isinstance(d, list) else []
311
+
312
+
313
+ def get_user_id(userinfo: dict = Depends(get_userinfo)) -> str:
314
+ """Return the Keycloak subject (user UUID) from the introspection result."""
315
+ return userinfo.get("sub")
316
+
317
+
318
+ def is_admin(roles=Depends(get_user_roles)) -> bool:
319
+ """Return True when the caller holds the 'admin' shieldapi role."""
320
+ return _ADMIN_ROLE in roles
321
+
322
+
323
+ def get_optional_access_token(request: Request) -> Optional[str]:
324
+ """Like get_access_token but returns None when no Authorization header is present."""
325
+ auth_header = request.headers.get("Authorization", default="")
326
+ if not auth_header or "Bearer" not in auth_header:
327
+ return None
328
+ return auth_header.split()[1]
329
+
330
+
331
+ def get_optional_userinfo(
332
+ token: Optional[str] = Depends(get_optional_access_token),
333
+ ) -> Optional[dict]:
334
+ """Introspect the token when present; return None for anonymous requests."""
335
+ if token is None:
336
+ return None
337
+ return get_keycloak_openid().introspect(token)
338
+
339
+
340
+ def get_optional_user_roles(userinfo: Optional[dict] = Depends(get_optional_userinfo)):
341
+ """Return roles for an authenticated caller, or [] for anonymous."""
342
+ if userinfo is None:
343
+ return []
344
+ d = userinfo
345
+ for key in _ROLES_PATH:
346
+ d = d.get(key, {})
347
+ return d if isinstance(d, list) else []
348
+
349
+
350
+ def get_optional_user_id(
351
+ userinfo: Optional[dict] = Depends(get_optional_userinfo),
352
+ ) -> Optional[str]:
353
+ """Return the subject UUID for an authenticated caller, or None for anonymous."""
354
+ if userinfo is None:
355
+ return None
356
+ return userinfo.get("sub")
357
+
358
+
359
+ def is_optional_admin(roles=Depends(get_optional_user_roles)) -> bool:
360
+ """Return True when the caller holds the 'admin' role; False for anonymous."""
361
+ return _ADMIN_ROLE in roles
@@ -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.3.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
@@ -23,6 +23,7 @@ INTROSPECT_RESPONSE = dict(
23
23
  resource_access={
24
24
  "testshield": {"roles": ["admin", "user"]},
25
25
  "account": {"roles": ["manage-account", "view-profile"]},
26
+ "shieldapi": {"roles": ["admin"]},
26
27
  },
27
28
  scope="profile email client_roles",
28
29
  preferred_username="admin",
@@ -87,6 +88,17 @@ def register_mock(requests_mock: Mocker, var: dict = VARIABLES) -> None:
87
88
  requests_mock.register_uri(route["method"], path, json=route["json"])
88
89
 
89
90
 
91
+ def register_mock_inactive(requests_mock: Mocker, var: dict = VARIABLES) -> None:
92
+ """Register mock that returns an inactive (expired) introspection result."""
93
+ os.environ.update(**var)
94
+ realm_name = var["KEYCLOAK_REALM_NAME"]
95
+ path = (
96
+ var["KEYCLOAK_HOST"]
97
+ + f"realms/{realm_name}/protocol/openid-connect/token/introspect"
98
+ )
99
+ requests_mock.register_uri("post", path, json=INTROSPECT_INACTIVE)
100
+
101
+
90
102
  def register_mock_non_admin(requests_mock: Mocker, var: dict = VARIABLES) -> None:
91
103
  """Register mock responses for a non-admin user."""
92
104
  os.environ.update(**var)
@@ -8,12 +8,24 @@ from fastapi.testclient import TestClient
8
8
 
9
9
  from shieldapi.frameworks.fastapi import (
10
10
  AuthTokenBearer,
11
+ OptionalAuthTokenBearer,
11
12
  depends_auth_token_bearer,
13
+ get_optional_user_id,
14
+ get_optional_user_roles,
15
+ get_user_id,
16
+ get_user_roles,
17
+ is_admin,
18
+ is_optional_admin,
12
19
  require_self_or_role,
13
20
  )
14
21
  from shieldapi.keycloak_utils import make_auth_header
15
22
 
16
- from .mock import MESSAGE, register_mock, register_mock_non_admin
23
+ from .mock import (
24
+ MESSAGE,
25
+ register_mock,
26
+ register_mock_inactive,
27
+ register_mock_non_admin,
28
+ )
17
29
 
18
30
 
19
31
  @pytest.fixture(scope="function", params=["dependency", "helper"])
@@ -133,3 +145,110 @@ def test_require_self_or_role_forbidden(requests_mock):
133
145
  "/users/other-user", headers={"Authorization": "Bearer 123"}
134
146
  )
135
147
  assert response.status_code == 403
148
+
149
+
150
+ # ---------------------------------------------------------------------------
151
+ # OptionalAuthTokenBearer
152
+ # ---------------------------------------------------------------------------
153
+
154
+
155
+ def _make_optional_bearer_app():
156
+ optional = OptionalAuthTokenBearer()
157
+
158
+ app = FastAPI()
159
+
160
+ @app.get("/resource")
161
+ async def resource(token=Depends(optional)):
162
+ return {"anonymous": token is None}
163
+
164
+ return app
165
+
166
+
167
+ def test_optional_bearer_no_token(requests_mock):
168
+ """No Authorization header returns None from the dependency (anonymous access)."""
169
+ register_mock(requests_mock)
170
+ with TestClient(_make_optional_bearer_app()) as client:
171
+ response = client.get("/resource")
172
+ assert response.status_code == 200
173
+ assert response.json() == {"anonymous": True}
174
+
175
+
176
+ def test_optional_bearer_valid_token(requests_mock):
177
+ """Valid Bearer token passes through; the dependency returns a non-None value."""
178
+ register_mock(requests_mock)
179
+ with TestClient(_make_optional_bearer_app()) as client:
180
+ response = client.get("/resource", headers={"Authorization": "Bearer 123"})
181
+ assert response.status_code == 200
182
+ assert response.json() == {"anonymous": False}
183
+
184
+
185
+ def test_optional_bearer_invalid_token(requests_mock):
186
+ """Inactive/expired token raises HTTP 401 even for the optional bearer."""
187
+ register_mock_inactive(requests_mock)
188
+ with TestClient(
189
+ _make_optional_bearer_app(), raise_server_exceptions=False
190
+ ) as client:
191
+ response = client.get("/resource", headers={"Authorization": "Bearer expired"})
192
+ assert response.status_code == 401
193
+
194
+
195
+ # ---------------------------------------------------------------------------
196
+ # Generic dependency chain
197
+ # ---------------------------------------------------------------------------
198
+
199
+
200
+ def _make_dep_chain_app():
201
+ app = FastAPI()
202
+
203
+ @app.get("/whoami")
204
+ def whoami(
205
+ user_id=Depends(get_user_id),
206
+ roles=Depends(get_user_roles),
207
+ admin=Depends(is_admin),
208
+ ):
209
+ return {"user_id": user_id, "roles": roles, "admin": admin}
210
+
211
+ @app.get("/optional")
212
+ def optional_whoami(
213
+ user_id=Depends(get_optional_user_id),
214
+ roles=Depends(get_optional_user_roles),
215
+ admin=Depends(is_optional_admin),
216
+ ):
217
+ return {"user_id": user_id, "roles": roles, "admin": admin}
218
+
219
+ return app
220
+
221
+
222
+ def test_dep_chain_authenticated(requests_mock):
223
+ """Authenticated request resolves correct user_id, shieldapi roles, and admin flag."""
224
+ register_mock(requests_mock)
225
+ with TestClient(_make_dep_chain_app()) as client:
226
+ response = client.get("/whoami", headers={"Authorization": "Bearer 123"})
227
+ assert response.status_code == 200
228
+ data = response.json()
229
+ assert data["user_id"] == "test-user-id"
230
+ assert "admin" in data["roles"]
231
+ assert data["admin"] is True
232
+
233
+
234
+ def test_dep_chain_optional_anonymous(requests_mock):
235
+ """Anonymous request yields None user_id, empty roles, and admin=False."""
236
+ register_mock(requests_mock)
237
+ with TestClient(_make_dep_chain_app()) as client:
238
+ response = client.get("/optional")
239
+ assert response.status_code == 200
240
+ data = response.json()
241
+ assert data["user_id"] is None
242
+ assert data["roles"] == []
243
+ assert data["admin"] is False
244
+
245
+
246
+ def test_dep_chain_optional_authenticated(requests_mock):
247
+ """Optional endpoints resolve identically to required ones for authenticated users."""
248
+ register_mock(requests_mock)
249
+ with TestClient(_make_dep_chain_app()) as client:
250
+ response = client.get("/optional", headers={"Authorization": "Bearer 123"})
251
+ assert response.status_code == 200
252
+ data = response.json()
253
+ assert data["user_id"] == "test-user-id"
254
+ assert data["admin"] is True
@@ -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