shieldapi 2.2.0__py3-none-any.whl → 2.4.0__py3-none-any.whl

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.
@@ -1,13 +1,23 @@
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
 
9
10
  from shieldapi import logger
10
- from shieldapi.keycloak_utils import check_token_validity, get_keycloak_openid, login
11
+ from shieldapi.keycloak_utils import (
12
+ check_role,
13
+ check_token_validity,
14
+ get_keycloak_openid,
15
+ get_token_sub,
16
+ login,
17
+ )
18
+
19
+ _ADMIN_ROLE = "admin"
20
+ _ROLES_PATH = ("resource_access", "shieldapi", "roles")
11
21
 
12
22
 
13
23
  class Auth(str):
@@ -64,6 +74,31 @@ class AuthTokenBearer(HTTPBearer):
64
74
  return f"Bearer {auth.credentials}"
65
75
 
66
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
+
67
102
  class BasicLoginCredentials(HTTPBasicCredentials):
68
103
  """
69
104
  A subclass of HTTPBasicCredentials that extracts the basic auth credentials and
@@ -212,3 +247,115 @@ async def depends_auth_token_bearer(request: Request) -> Auth:
212
247
  "depends_auth_token_bearer: Calling AuthTokenBearer instance with request"
213
248
  )
214
249
  return await bearer(request)
250
+
251
+
252
+ def require_self_or_role(role: str):
253
+ """Return a FastAPI dependency that allows access to the user themselves or holders of ``role``.
254
+
255
+ The dependency checks whether the requesting user has ``role`` (unconditional
256
+ access) or whether the token subject matches the ``user_id`` path parameter.
257
+ Returns the raw token string on success and raises HTTP 403 otherwise.
258
+
259
+ Args:
260
+ role: Role name that grants unconditional access.
261
+ """
262
+
263
+ async def dependency(request: Request) -> str:
264
+ token_with_bearer = await depends_auth_token_bearer(request)
265
+ raw_token = token_with_bearer.split(" ", 1)[1]
266
+ if check_role(raw_token, role):
267
+ return raw_token
268
+ user_id = request.path_params.get("user_id")
269
+ if user_id and get_token_sub(raw_token) == user_id:
270
+ return raw_token
271
+ raise HTTPException(
272
+ status_code=403,
273
+ detail=f"Requires '{role}' role or matching user_id",
274
+ )
275
+
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
@@ -341,3 +341,15 @@ def get_current_user() -> str:
341
341
  user_id = user_info.get("sub", "")
342
342
  logger.debug(f"get_current_user: Current user ID {user_id}")
343
343
  return user_id
344
+
345
+
346
+ def get_token_sub(token: str) -> str:
347
+ """Return the subject (user ID) from an introspected token.
348
+
349
+ Args:
350
+ token: Raw access token string.
351
+ """
352
+ token_info = get_keycloak_openid().introspect(token)
353
+ sub = token_info.get("sub", "")
354
+ logger.debug(f"get_token_sub: sub={sub}")
355
+ return sub
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: shieldapi
3
- Version: 2.2.0
3
+ Version: 2.4.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
@@ -0,0 +1,16 @@
1
+ shieldapi/__init__.py,sha256=IL5_3eBPncM2UjlJyeh5JikmC17Gv26vSJAW84NXUjk,1469
2
+ shieldapi/keycloak_utils.py,sha256=lCnEjouHHf18RXH2FJqOG-Gx0aoNjboEQtZLxjgqnGs,13030
3
+ shieldapi/frameworks/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
4
+ shieldapi/frameworks/fastapi.py,sha256=EQv8ruHlsuYW02MkyUNmMKNjOSNMwDL27leprqdW4Yo,12281
5
+ shieldapi/frameworks/flask.py,sha256=tI8WcfA8kEy7kMmCk06be7dIkQYLmKWTIS-6TUJc8bo,4713
6
+ shieldapi-2.4.0.dist-info/licenses/LICENSE,sha256=Mb4AMpANQymZqBk8jkFQLzXAfjDbYPTxBdvdUkUjJ2I,1491
7
+ tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
8
+ tests/conftest.py,sha256=P1eceCyc83qAnfCwyrGpHnko4hzoGHqhA-mNeW7wKJk,390
9
+ tests/mock.py,sha256=hZDAyKGps58MXGsY6qqRFo30lJZ19JBKCEDJ2LQLWTM,4066
10
+ tests/test_fastapi.py,sha256=_yXpL5jY_sYbuVul5F8pSTXYrc5XgUHeJLFzPK5dFQ8,8828
11
+ tests/test_flask.py,sha256=CzF64A8Pch7s19nfdn7qP-f2YLngu75Xn-B9V76CeiE,6829
12
+ tests/test_keycloak_utils.py,sha256=pmRHEmT4x7yKU_hd82OyXWhtbpNY5fQoAVI7Anm0c2A,4936
13
+ shieldapi-2.4.0.dist-info/METADATA,sha256=dRFC-2XQ0F-JRztDMCtKbylln7Bg38oIibI45I0E_UQ,20553
14
+ shieldapi-2.4.0.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
15
+ shieldapi-2.4.0.dist-info/top_level.txt,sha256=3Ohn103e0r89q0KbiIN8rVmvDGJnrWr-2Cyg8Cv626I,16
16
+ shieldapi-2.4.0.dist-info/RECORD,,
tests/mock.py CHANGED
@@ -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)
tests/test_fastapi.py CHANGED
@@ -6,10 +6,26 @@ import pytest
6
6
  from fastapi import Depends, FastAPI
7
7
  from fastapi.testclient import TestClient
8
8
 
9
- from shieldapi.frameworks.fastapi import AuthTokenBearer, depends_auth_token_bearer
9
+ from shieldapi.frameworks.fastapi import (
10
+ AuthTokenBearer,
11
+ OptionalAuthTokenBearer,
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,
19
+ require_self_or_role,
20
+ )
10
21
  from shieldapi.keycloak_utils import make_auth_header
11
22
 
12
- from .mock import MESSAGE, register_mock
23
+ from .mock import (
24
+ MESSAGE,
25
+ register_mock,
26
+ register_mock_inactive,
27
+ register_mock_non_admin,
28
+ )
13
29
 
14
30
 
15
31
  @pytest.fixture(scope="function", params=["dependency", "helper"])
@@ -85,3 +101,154 @@ def test_fastapi_login(client, requests_mock):
85
101
  host_list = [resp.hostname for resp in requests_mock.request_history]
86
102
  assert host_list.count("example_keycloak.org") == 2 # called 2x keycloak-mock
87
103
  assert response.json() == MESSAGE
104
+
105
+
106
+ def _make_self_or_role_app():
107
+ app = FastAPI()
108
+
109
+ @app.get("/users/{user_id}")
110
+ def get_user(user_id: str, token: str = Depends(require_self_or_role("admin"))):
111
+ return {"user_id": user_id}
112
+
113
+ return app
114
+
115
+
116
+ def test_require_self_or_role_admin_access(requests_mock):
117
+ """Admin role grants access regardless of user_id path param."""
118
+ register_mock(requests_mock)
119
+ with TestClient(_make_self_or_role_app()) as client:
120
+ # INTROSPECT_RESPONSE has admin role and sub="test-user-id"
121
+ response = client.get(
122
+ "/users/other-user", headers={"Authorization": "Bearer 123"}
123
+ )
124
+ assert response.status_code == 200
125
+ assert response.json() == {"user_id": "other-user"}
126
+
127
+
128
+ def test_require_self_or_role_self_access(requests_mock):
129
+ """Non-admin user can access a path whose user_id matches their own sub."""
130
+ register_mock_non_admin(requests_mock)
131
+ with TestClient(_make_self_or_role_app()) as client:
132
+ # INTROSPECT_NON_ADMIN has no admin role and sub="non-admin-user-id"
133
+ response = client.get(
134
+ "/users/non-admin-user-id", headers={"Authorization": "Bearer 123"}
135
+ )
136
+ assert response.status_code == 200
137
+ assert response.json() == {"user_id": "non-admin-user-id"}
138
+
139
+
140
+ def test_require_self_or_role_forbidden(requests_mock):
141
+ """Non-admin user is blocked when user_id path param does not match their sub."""
142
+ register_mock_non_admin(requests_mock)
143
+ with TestClient(_make_self_or_role_app()) as client:
144
+ response = client.get(
145
+ "/users/other-user", headers={"Authorization": "Bearer 123"}
146
+ )
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
@@ -6,7 +6,12 @@ from typing import Any, Dict, List, Optional
6
6
 
7
7
  import pytest
8
8
 
9
- from shieldapi.keycloak_utils import _get_value, get_keycloak_admin, get_keycloak_openid
9
+ from shieldapi.keycloak_utils import (
10
+ _get_value,
11
+ get_keycloak_admin,
12
+ get_keycloak_openid,
13
+ get_token_sub,
14
+ )
10
15
 
11
16
  from .mock import register_mock
12
17
 
@@ -121,3 +126,10 @@ def test_keycloak_warning_bool(var, env_var, func, requests_mock):
121
126
  warning_raised(func, match, kwargs={"verify": var})
122
127
  else:
123
128
  no_warning_raised(func, kwargs={"verify": var})
129
+
130
+
131
+ def test_get_token_sub(requests_mock):
132
+ """get_token_sub returns the 'sub' claim from the introspect response."""
133
+ register_mock(requests_mock)
134
+ result = get_token_sub("123")
135
+ assert result == "test-user-id"
@@ -1,16 +0,0 @@
1
- shieldapi/__init__.py,sha256=IL5_3eBPncM2UjlJyeh5JikmC17Gv26vSJAW84NXUjk,1469
2
- shieldapi/keycloak_utils.py,sha256=qkSYbuM0KFqDanhAq-BIdqaB43qVH51C_qpwmX_OiPg,12713
3
- shieldapi/frameworks/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
4
- shieldapi/frameworks/fastapi.py,sha256=z_wprmy-CO1b9_DsLjTFN4AAptQMz1mpYrRCdd8rDz0,7033
5
- shieldapi/frameworks/flask.py,sha256=tI8WcfA8kEy7kMmCk06be7dIkQYLmKWTIS-6TUJc8bo,4713
6
- shieldapi-2.2.0.dist-info/licenses/LICENSE,sha256=Mb4AMpANQymZqBk8jkFQLzXAfjDbYPTxBdvdUkUjJ2I,1491
7
- tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
8
- tests/conftest.py,sha256=P1eceCyc83qAnfCwyrGpHnko4hzoGHqhA-mNeW7wKJk,390
9
- tests/mock.py,sha256=epXgNzvgiWf8T-Vrd6PqrQAjpVRMs1rL2ktpDyVaqS0,3592
10
- tests/test_fastapi.py,sha256=tgLFNAnJtwa4PFqPgQxj44E9ahniFt1iSN6OSbkp3NA,3177
11
- tests/test_flask.py,sha256=CzF64A8Pch7s19nfdn7qP-f2YLngu75Xn-B9V76CeiE,6829
12
- tests/test_keycloak_utils.py,sha256=UpGnLHiMo1inn-6W0qkDRvDBCvwJr15Dd40MOdDXQKM,4678
13
- shieldapi-2.2.0.dist-info/METADATA,sha256=ckw_tc-Uf-XLMz-r7n_3k4y0bYvfW85lZSdlC1oxsnw,20553
14
- shieldapi-2.2.0.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
15
- shieldapi-2.2.0.dist-info/top_level.txt,sha256=3Ohn103e0r89q0KbiIN8rVmvDGJnrWr-2Cyg8Cv626I,16
16
- shieldapi-2.2.0.dist-info/RECORD,,