shieldapi 2.2.0__tar.gz → 2.3.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.
- {shieldapi-2.2.0/shieldapi.egg-info → shieldapi-2.3.0}/PKG-INFO +1 -1
- {shieldapi-2.2.0 → shieldapi-2.3.0}/setup.cfg +2 -2
- {shieldapi-2.2.0 → shieldapi-2.3.0}/shieldapi/frameworks/fastapi.py +34 -1
- {shieldapi-2.2.0 → shieldapi-2.3.0}/shieldapi/keycloak_utils.py +12 -0
- {shieldapi-2.2.0 → shieldapi-2.3.0/shieldapi.egg-info}/PKG-INFO +1 -1
- {shieldapi-2.2.0 → shieldapi-2.3.0}/tests/test_fastapi.py +50 -2
- {shieldapi-2.2.0 → shieldapi-2.3.0}/tests/test_keycloak_utils.py +13 -1
- {shieldapi-2.2.0 → shieldapi-2.3.0}/LICENSE +0 -0
- {shieldapi-2.2.0 → shieldapi-2.3.0}/README.md +0 -0
- {shieldapi-2.2.0 → shieldapi-2.3.0}/pyproject.toml +0 -0
- {shieldapi-2.2.0 → shieldapi-2.3.0}/setup.py +0 -0
- {shieldapi-2.2.0 → shieldapi-2.3.0}/shieldapi/__init__.py +0 -0
- {shieldapi-2.2.0 → shieldapi-2.3.0}/shieldapi/frameworks/__init__.py +0 -0
- {shieldapi-2.2.0 → shieldapi-2.3.0}/shieldapi/frameworks/flask.py +0 -0
- {shieldapi-2.2.0 → shieldapi-2.3.0}/shieldapi.egg-info/SOURCES.txt +0 -0
- {shieldapi-2.2.0 → shieldapi-2.3.0}/shieldapi.egg-info/dependency_links.txt +0 -0
- {shieldapi-2.2.0 → shieldapi-2.3.0}/shieldapi.egg-info/requires.txt +0 -0
- {shieldapi-2.2.0 → shieldapi-2.3.0}/shieldapi.egg-info/top_level.txt +0 -0
- {shieldapi-2.2.0 → shieldapi-2.3.0}/tests/__init__.py +0 -0
- {shieldapi-2.2.0 → shieldapi-2.3.0}/tests/conftest.py +0 -0
- {shieldapi-2.2.0 → shieldapi-2.3.0}/tests/mock.py +0 -0
- {shieldapi-2.2.0 → shieldapi-2.3.0}/tests/test_flask.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
[metadata]
|
|
2
2
|
name = shieldapi
|
|
3
|
-
version = v2.
|
|
3
|
+
version = v2.3.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
|
|
@@ -34,7 +34,7 @@ tests =
|
|
|
34
34
|
pytest-mock>=3.10.0
|
|
35
35
|
|
|
36
36
|
[bumpver]
|
|
37
|
-
current_version = "v2.
|
|
37
|
+
current_version = "v2.3.0"
|
|
38
38
|
version_pattern = "vMAJOR.MINOR.PATCH[PYTAGNUM]"
|
|
39
39
|
commit_message = "Bump version {old_version} -> {new_version}"
|
|
40
40
|
commit = True
|
|
@@ -7,7 +7,13 @@ from fastapi.security import HTTPBasic, HTTPBasicCredentials, HTTPBearer
|
|
|
7
7
|
from pydantic import BaseModel
|
|
8
8
|
|
|
9
9
|
from shieldapi import logger
|
|
10
|
-
from shieldapi.keycloak_utils import
|
|
10
|
+
from shieldapi.keycloak_utils import (
|
|
11
|
+
check_role,
|
|
12
|
+
check_token_validity,
|
|
13
|
+
get_keycloak_openid,
|
|
14
|
+
get_token_sub,
|
|
15
|
+
login,
|
|
16
|
+
)
|
|
11
17
|
|
|
12
18
|
|
|
13
19
|
class Auth(str):
|
|
@@ -212,3 +218,30 @@ async def depends_auth_token_bearer(request: Request) -> Auth:
|
|
|
212
218
|
"depends_auth_token_bearer: Calling AuthTokenBearer instance with request"
|
|
213
219
|
)
|
|
214
220
|
return await bearer(request)
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
def require_self_or_role(role: str):
|
|
224
|
+
"""Return a FastAPI dependency that allows access to the user themselves or holders of ``role``.
|
|
225
|
+
|
|
226
|
+
The dependency checks whether the requesting user has ``role`` (unconditional
|
|
227
|
+
access) or whether the token subject matches the ``user_id`` path parameter.
|
|
228
|
+
Returns the raw token string on success and raises HTTP 403 otherwise.
|
|
229
|
+
|
|
230
|
+
Args:
|
|
231
|
+
role: Role name that grants unconditional access.
|
|
232
|
+
"""
|
|
233
|
+
|
|
234
|
+
async def dependency(request: Request) -> str:
|
|
235
|
+
token_with_bearer = await depends_auth_token_bearer(request)
|
|
236
|
+
raw_token = token_with_bearer.split(" ", 1)[1]
|
|
237
|
+
if check_role(raw_token, role):
|
|
238
|
+
return raw_token
|
|
239
|
+
user_id = request.path_params.get("user_id")
|
|
240
|
+
if user_id and get_token_sub(raw_token) == user_id:
|
|
241
|
+
return raw_token
|
|
242
|
+
raise HTTPException(
|
|
243
|
+
status_code=403,
|
|
244
|
+
detail=f"Requires '{role}' role or matching user_id",
|
|
245
|
+
)
|
|
246
|
+
|
|
247
|
+
return dependency
|
|
@@ -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
|
|
@@ -6,10 +6,14 @@ import pytest
|
|
|
6
6
|
from fastapi import Depends, FastAPI
|
|
7
7
|
from fastapi.testclient import TestClient
|
|
8
8
|
|
|
9
|
-
from shieldapi.frameworks.fastapi import
|
|
9
|
+
from shieldapi.frameworks.fastapi import (
|
|
10
|
+
AuthTokenBearer,
|
|
11
|
+
depends_auth_token_bearer,
|
|
12
|
+
require_self_or_role,
|
|
13
|
+
)
|
|
10
14
|
from shieldapi.keycloak_utils import make_auth_header
|
|
11
15
|
|
|
12
|
-
from .mock import MESSAGE, register_mock
|
|
16
|
+
from .mock import MESSAGE, register_mock, register_mock_non_admin
|
|
13
17
|
|
|
14
18
|
|
|
15
19
|
@pytest.fixture(scope="function", params=["dependency", "helper"])
|
|
@@ -85,3 +89,47 @@ def test_fastapi_login(client, requests_mock):
|
|
|
85
89
|
host_list = [resp.hostname for resp in requests_mock.request_history]
|
|
86
90
|
assert host_list.count("example_keycloak.org") == 2 # called 2x keycloak-mock
|
|
87
91
|
assert response.json() == MESSAGE
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def _make_self_or_role_app():
|
|
95
|
+
app = FastAPI()
|
|
96
|
+
|
|
97
|
+
@app.get("/users/{user_id}")
|
|
98
|
+
def get_user(user_id: str, token: str = Depends(require_self_or_role("admin"))):
|
|
99
|
+
return {"user_id": user_id}
|
|
100
|
+
|
|
101
|
+
return app
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def test_require_self_or_role_admin_access(requests_mock):
|
|
105
|
+
"""Admin role grants access regardless of user_id path param."""
|
|
106
|
+
register_mock(requests_mock)
|
|
107
|
+
with TestClient(_make_self_or_role_app()) as client:
|
|
108
|
+
# INTROSPECT_RESPONSE has admin role and sub="test-user-id"
|
|
109
|
+
response = client.get(
|
|
110
|
+
"/users/other-user", headers={"Authorization": "Bearer 123"}
|
|
111
|
+
)
|
|
112
|
+
assert response.status_code == 200
|
|
113
|
+
assert response.json() == {"user_id": "other-user"}
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def test_require_self_or_role_self_access(requests_mock):
|
|
117
|
+
"""Non-admin user can access a path whose user_id matches their own sub."""
|
|
118
|
+
register_mock_non_admin(requests_mock)
|
|
119
|
+
with TestClient(_make_self_or_role_app()) as client:
|
|
120
|
+
# INTROSPECT_NON_ADMIN has no admin role and sub="non-admin-user-id"
|
|
121
|
+
response = client.get(
|
|
122
|
+
"/users/non-admin-user-id", headers={"Authorization": "Bearer 123"}
|
|
123
|
+
)
|
|
124
|
+
assert response.status_code == 200
|
|
125
|
+
assert response.json() == {"user_id": "non-admin-user-id"}
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def test_require_self_or_role_forbidden(requests_mock):
|
|
129
|
+
"""Non-admin user is blocked when user_id path param does not match their sub."""
|
|
130
|
+
register_mock_non_admin(requests_mock)
|
|
131
|
+
with TestClient(_make_self_or_role_app()) as client:
|
|
132
|
+
response = client.get(
|
|
133
|
+
"/users/other-user", headers={"Authorization": "Bearer 123"}
|
|
134
|
+
)
|
|
135
|
+
assert response.status_code == 403
|
|
@@ -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
|
|
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"
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|