shieldapi 1.3.0rc0__tar.gz → 2.0.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-1.3.0rc0/shieldapi.egg-info → shieldapi-2.0.0}/PKG-INFO +8 -4
- {shieldapi-1.3.0rc0 → shieldapi-2.0.0}/README.md +5 -1
- {shieldapi-1.3.0rc0 → shieldapi-2.0.0}/setup.cfg +2 -2
- shieldapi-2.0.0/shieldapi/__init__.py +49 -0
- {shieldapi-1.3.0rc0 → shieldapi-2.0.0}/shieldapi/frameworks/fastapi.py +35 -5
- {shieldapi-1.3.0rc0 → shieldapi-2.0.0}/shieldapi/frameworks/flask.py +25 -29
- {shieldapi-1.3.0rc0 → shieldapi-2.0.0}/shieldapi/keycloak_utils.py +103 -47
- {shieldapi-1.3.0rc0 → shieldapi-2.0.0/shieldapi.egg-info}/PKG-INFO +8 -4
- {shieldapi-1.3.0rc0 → shieldapi-2.0.0}/tests/conftest.py +2 -5
- shieldapi-1.3.0rc0/tests/__init__.py +0 -0
- {shieldapi-1.3.0rc0 → shieldapi-2.0.0}/LICENSE +0 -0
- {shieldapi-1.3.0rc0 → shieldapi-2.0.0}/pyproject.toml +0 -0
- {shieldapi-1.3.0rc0 → shieldapi-2.0.0}/setup.py +0 -0
- {shieldapi-1.3.0rc0/shieldapi → shieldapi-2.0.0/shieldapi/frameworks}/__init__.py +0 -0
- {shieldapi-1.3.0rc0 → shieldapi-2.0.0}/shieldapi.egg-info/SOURCES.txt +0 -0
- {shieldapi-1.3.0rc0 → shieldapi-2.0.0}/shieldapi.egg-info/dependency_links.txt +0 -0
- {shieldapi-1.3.0rc0 → shieldapi-2.0.0}/shieldapi.egg-info/requires.txt +0 -0
- {shieldapi-1.3.0rc0 → shieldapi-2.0.0}/shieldapi.egg-info/top_level.txt +0 -0
- {shieldapi-1.3.0rc0/shieldapi/frameworks → shieldapi-2.0.0/tests}/__init__.py +0 -0
- {shieldapi-1.3.0rc0 → shieldapi-2.0.0}/tests/mock.py +0 -0
- {shieldapi-1.3.0rc0 → shieldapi-2.0.0}/tests/test_fastapi.py +0 -0
- {shieldapi-1.3.0rc0 → shieldapi-2.0.0}/tests/test_flask.py +0 -0
- {shieldapi-1.3.0rc0 → shieldapi-2.0.0}/tests/test_keycloak_utils.py +0 -0
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
Metadata-Version: 2.
|
|
1
|
+
Metadata-Version: 2.2
|
|
2
2
|
Name: shieldapi
|
|
3
|
-
Version:
|
|
3
|
+
Version: 2.0.0
|
|
4
4
|
Summary: A package for endpoint protection of APIs using Keycloak
|
|
5
|
-
Author:
|
|
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
|
|
@@ -78,6 +78,10 @@ In order to successfully enable the callback for the token-generation and token-
|
|
|
78
78
|
| `KEYCLOAK_VERIFY_HOST` | Controls whether SSL certificates are verified for HTTPS requests. Default is set to `False`. | "True" |
|
|
79
79
|
| `KEYCLOAK_REALM_ADMIN_USER` | User name of the realm admin, if any action shall be performed as admin in your Flask/FastAPI application. | "admin" |
|
|
80
80
|
| `KEYCLOAK_REALM_ADMIN_PASSWORD` | Password of the realm admin, if any action shall be performed as admin in your Flask/FastAPI application. | "admin_password" |
|
|
81
|
+
| `SKIP_ENV_CHECK` | Optional. If set, skips the check for mandatory environment variables during startup. | "True" |
|
|
82
|
+
|
|
83
|
+
#### Note
|
|
84
|
+
- If `SKIP_ENV_CHECK` is set, the application will bypass the mandatory environment variable checks during startup. This is useful for development or testing scenarios where not all variables are needed.
|
|
81
85
|
|
|
82
86
|
## Usage with Flask
|
|
83
87
|
|
|
@@ -407,4 +411,4 @@ This work is supported by the MarketPlace project funded by [Horizon 2020](https
|
|
|
407
411
|
## License
|
|
408
412
|
|
|
409
413
|
The code is licensed under BSD-3-Clause.
|
|
410
|
-
Copyright ©
|
|
414
|
+
Copyright © 2025 Materials MarketPlace
|
|
@@ -52,6 +52,10 @@ In order to successfully enable the callback for the token-generation and token-
|
|
|
52
52
|
| `KEYCLOAK_VERIFY_HOST` | Controls whether SSL certificates are verified for HTTPS requests. Default is set to `False`. | "True" |
|
|
53
53
|
| `KEYCLOAK_REALM_ADMIN_USER` | User name of the realm admin, if any action shall be performed as admin in your Flask/FastAPI application. | "admin" |
|
|
54
54
|
| `KEYCLOAK_REALM_ADMIN_PASSWORD` | Password of the realm admin, if any action shall be performed as admin in your Flask/FastAPI application. | "admin_password" |
|
|
55
|
+
| `SKIP_ENV_CHECK` | Optional. If set, skips the check for mandatory environment variables during startup. | "True" |
|
|
56
|
+
|
|
57
|
+
#### Note
|
|
58
|
+
- If `SKIP_ENV_CHECK` is set, the application will bypass the mandatory environment variable checks during startup. This is useful for development or testing scenarios where not all variables are needed.
|
|
55
59
|
|
|
56
60
|
## Usage with Flask
|
|
57
61
|
|
|
@@ -381,4 +385,4 @@ This work is supported by the MarketPlace project funded by [Horizon 2020](https
|
|
|
381
385
|
## License
|
|
382
386
|
|
|
383
387
|
The code is licensed under BSD-3-Clause.
|
|
384
|
-
Copyright ©
|
|
388
|
+
Copyright © 2025 Materials MarketPlace
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
[metadata]
|
|
2
2
|
name = shieldapi
|
|
3
|
-
version =
|
|
4
|
-
author =
|
|
3
|
+
version = v2.0.0
|
|
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
|
|
7
7
|
long_description = file: README.md
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
import os
|
|
3
|
+
from ast import literal_eval
|
|
4
|
+
|
|
5
|
+
# Configure logging
|
|
6
|
+
logging.basicConfig(level=logging.INFO)
|
|
7
|
+
logger = logging.getLogger("shieldapi")
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def check_env_vars():
|
|
11
|
+
"""
|
|
12
|
+
Checks if all environment variables are set.
|
|
13
|
+
Skips the check if SKIP_ENV_CHECK is set.
|
|
14
|
+
"""
|
|
15
|
+
# Allow skipping the check if SKIP_ENV_CHECK is set
|
|
16
|
+
skip_check = False
|
|
17
|
+
try:
|
|
18
|
+
skip_check = literal_eval(os.environ.get("SKIP_ENV_CHECK", "False"))
|
|
19
|
+
if not isinstance(skip_check, bool):
|
|
20
|
+
logger.warning(
|
|
21
|
+
f"Invalid value for SKIP_ENV_CHECK: {os.environ.get('SKIP_ENV_CHECK', '')}. Proceeding with environment variable checks."
|
|
22
|
+
)
|
|
23
|
+
except (ValueError, SyntaxError):
|
|
24
|
+
logger.warning(
|
|
25
|
+
f"Invalid value for SKIP_ENV_CHECK: {os.environ.get('SKIP_ENV_CHECK', '')}. Proceeding with environment variable checks."
|
|
26
|
+
)
|
|
27
|
+
|
|
28
|
+
if skip_check:
|
|
29
|
+
logger.info(
|
|
30
|
+
"Skipping environment variable environment variable check due to SKIP_ENV_CHECK."
|
|
31
|
+
)
|
|
32
|
+
return
|
|
33
|
+
|
|
34
|
+
mandatory_vars = [
|
|
35
|
+
"KEYCLOAK_HOST",
|
|
36
|
+
"KEYCLOAK_REALM_NAME",
|
|
37
|
+
"KEYCLOAK_CLIENT_ID",
|
|
38
|
+
"KEYCLOAK_CLIENT_SECRET",
|
|
39
|
+
]
|
|
40
|
+
|
|
41
|
+
missing_vars = [var for var in mandatory_vars if not os.environ.get(var)]
|
|
42
|
+
|
|
43
|
+
if missing_vars:
|
|
44
|
+
logger.warning("Missing environment variables: %s", ", ".join(missing_vars))
|
|
45
|
+
else:
|
|
46
|
+
logger.info("All environment variables are set.")
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
check_env_vars()
|
|
@@ -6,7 +6,8 @@ from fastapi import HTTPException, Request
|
|
|
6
6
|
from fastapi.security import HTTPBasic, HTTPBasicCredentials, HTTPBearer
|
|
7
7
|
from pydantic import BaseModel
|
|
8
8
|
|
|
9
|
-
from shieldapi
|
|
9
|
+
from shieldapi import logger
|
|
10
|
+
from shieldapi.keycloak_utils import check_token_validity, get_keycloak_openid, login
|
|
10
11
|
|
|
11
12
|
|
|
12
13
|
class Auth(str):
|
|
@@ -47,18 +48,19 @@ class AuthTokenBearer(HTTPBearer):
|
|
|
47
48
|
HTTPException:
|
|
48
49
|
If the authentication token is missing or expired.
|
|
49
50
|
"""
|
|
51
|
+
logger.debug("AuthTokenBearer.__call__: Starting token extraction")
|
|
50
52
|
auth = await super().__call__(request=request)
|
|
51
53
|
|
|
52
54
|
if not auth.credentials:
|
|
55
|
+
logger.warning("AuthTokenBearer.__call__: Missing access token")
|
|
53
56
|
raise HTTPException(
|
|
54
57
|
status_code=401,
|
|
55
58
|
detail="An access token is expected but has not been provided",
|
|
56
59
|
)
|
|
57
60
|
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
raise HTTPException(status_code=401, detail="
|
|
61
|
-
|
|
61
|
+
if not check_token_validity(auth.credentials):
|
|
62
|
+
logger.warning(f"AuthTokenBearer.__call__: Token validation failed")
|
|
63
|
+
raise HTTPException(status_code=401, detail="Token validation failed")
|
|
62
64
|
return f"Bearer {auth.credentials}"
|
|
63
65
|
|
|
64
66
|
|
|
@@ -80,6 +82,9 @@ class BasicLoginCredentials(HTTPBasicCredentials):
|
|
|
80
82
|
|
|
81
83
|
def __init__(self, **kwargs):
|
|
82
84
|
super().__init__(**kwargs)
|
|
85
|
+
logger.debug(
|
|
86
|
+
f"BasicLoginCredentials.__init__: Initialized with username={self.username}"
|
|
87
|
+
)
|
|
83
88
|
|
|
84
89
|
@property
|
|
85
90
|
def token(self, **kwargs) -> Auth:
|
|
@@ -95,10 +100,19 @@ class BasicLoginCredentials(HTTPBasicCredentials):
|
|
|
95
100
|
HTTPException:
|
|
96
101
|
If the authentication credentials are invalid.
|
|
97
102
|
"""
|
|
103
|
+
logger.debug(
|
|
104
|
+
f"BasicLoginCredentials.token: Attempting login for username={self.username}"
|
|
105
|
+
)
|
|
98
106
|
token = login(self.username, self.password)
|
|
99
107
|
if len(token) == 2:
|
|
108
|
+
logger.error(
|
|
109
|
+
f"BasicLoginCredentials.token: Invalid credentials for username={self.username}"
|
|
110
|
+
)
|
|
100
111
|
raise HTTPException(status_code=token[0], detail=token[1])
|
|
101
112
|
else:
|
|
113
|
+
logger.info(
|
|
114
|
+
f"BasicLoginCredentials.token: Login successful for username={self.username}"
|
|
115
|
+
)
|
|
102
116
|
return token
|
|
103
117
|
|
|
104
118
|
|
|
@@ -134,11 +148,21 @@ class BasicLogin(HTTPBasic):
|
|
|
134
148
|
HTTPException:
|
|
135
149
|
If the authentication credentials are invalid.
|
|
136
150
|
"""
|
|
151
|
+
logger.debug("BasicLogin.__call__: Extracting credentials from request")
|
|
137
152
|
log = await super().__call__(request=request)
|
|
153
|
+
logger.debug(
|
|
154
|
+
f"BasicLogin.__call__: Credentials extracted for username={log.username}"
|
|
155
|
+
)
|
|
138
156
|
token = login(log.username, log.password)
|
|
139
157
|
if len(token) == 2:
|
|
158
|
+
logger.error(
|
|
159
|
+
f"BasicLogin.__call__: Invalid credentials for username={log.username}"
|
|
160
|
+
)
|
|
140
161
|
raise HTTPException(status_code=token[0], detail=token[1])
|
|
141
162
|
else:
|
|
163
|
+
logger.info(
|
|
164
|
+
f"BasicLogin.__call__: Login successful for username={log.username}"
|
|
165
|
+
)
|
|
142
166
|
return token
|
|
143
167
|
|
|
144
168
|
|
|
@@ -156,9 +180,11 @@ async def depends_basic_login(request: Request) -> Auth:
|
|
|
156
180
|
Auth:
|
|
157
181
|
A custom str-type representing the access token.
|
|
158
182
|
"""
|
|
183
|
+
logger.debug("depends_basic_login: Creating BasicLogin instance")
|
|
159
184
|
basic = BasicLogin(
|
|
160
185
|
scheme_name=os.environ.get("AUTH_BEARER_SCHEME_NAME"),
|
|
161
186
|
)
|
|
187
|
+
logger.debug("depends_basic_login: Calling BasicLogin instance with request")
|
|
162
188
|
return await basic(request)
|
|
163
189
|
|
|
164
190
|
|
|
@@ -176,9 +202,13 @@ async def depends_auth_token_bearer(request: Request) -> Auth:
|
|
|
176
202
|
Auth:
|
|
177
203
|
A custom str-type representing the access token.
|
|
178
204
|
"""
|
|
205
|
+
logger.debug("depends_auth_token_bearer: Creating AuthTokenBearer instance")
|
|
179
206
|
bearer = AuthTokenBearer(
|
|
180
207
|
bearerFormat=os.environ.get("AUTH_TOKEN_BEARER_FORMAT"),
|
|
181
208
|
scheme_name=os.environ.get("AUTH_BEARER_SCHEME_NAME"),
|
|
182
209
|
description=os.environ.get("AUTH_BEARER_DESCRIPTION"),
|
|
183
210
|
)
|
|
211
|
+
logger.debug(
|
|
212
|
+
"depends_auth_token_bearer: Calling AuthTokenBearer instance with request"
|
|
213
|
+
)
|
|
184
214
|
return await bearer(request)
|
|
@@ -1,10 +1,11 @@
|
|
|
1
|
-
"""
|
|
1
|
+
"""Functions and decorators for shieldapi in Flask."""
|
|
2
2
|
|
|
3
3
|
from functools import wraps
|
|
4
4
|
from typing import Callable, List
|
|
5
5
|
|
|
6
6
|
from flask import abort, request
|
|
7
7
|
|
|
8
|
+
from shieldapi import logger
|
|
8
9
|
from shieldapi.keycloak_utils import (
|
|
9
10
|
check_role,
|
|
10
11
|
check_token_validity,
|
|
@@ -22,33 +23,11 @@ def get_access_token():
|
|
|
22
23
|
"""
|
|
23
24
|
auth_header = request.headers.get("Authorization", default="")
|
|
24
25
|
if not auth_header or "Bearer" not in auth_header:
|
|
26
|
+
logger.warning("get_access_token: Missing or invalid Authorization header")
|
|
25
27
|
return ""
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
def get_userinfo() -> dict:
|
|
30
|
-
"""
|
|
31
|
-
Returns the user information from the access token.
|
|
32
|
-
|
|
33
|
-
Returns:
|
|
34
|
-
dict:
|
|
35
|
-
The user information.
|
|
36
|
-
"""
|
|
37
|
-
token = get_access_token()
|
|
38
|
-
userinfo = get_keycloak_openid().userinfo(token)
|
|
39
|
-
return userinfo
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
def get_current_user() -> str:
|
|
43
|
-
"""
|
|
44
|
-
Get the current logged in user.
|
|
45
|
-
|
|
46
|
-
Returns:
|
|
47
|
-
str:
|
|
48
|
-
The user ID.
|
|
49
|
-
"""
|
|
50
|
-
user_info = get_userinfo()
|
|
51
|
-
return user_info["sub"]
|
|
28
|
+
token = auth_header.split()[1]
|
|
29
|
+
logger.debug(f"get_access_token: Extracted token {token}")
|
|
30
|
+
return token
|
|
52
31
|
|
|
53
32
|
|
|
54
33
|
def login_required(fn: Callable) -> Callable:
|
|
@@ -68,13 +47,15 @@ def login_required(fn: Callable) -> Callable:
|
|
|
68
47
|
def decorated_view(*args, **kwargs):
|
|
69
48
|
access_token = get_access_token()
|
|
70
49
|
if not access_token:
|
|
50
|
+
logger.warning("login_required: Access token is missing")
|
|
71
51
|
abort(401)
|
|
72
52
|
|
|
73
53
|
valid = check_token_validity(access_token)
|
|
74
|
-
|
|
75
54
|
if not valid:
|
|
55
|
+
logger.warning("login_required: Access token is invalid or expired")
|
|
76
56
|
abort(401)
|
|
77
57
|
|
|
58
|
+
logger.info("login_required: User is logged in")
|
|
78
59
|
return fn(*args, **kwargs)
|
|
79
60
|
|
|
80
61
|
return decorated_view
|
|
@@ -97,11 +78,14 @@ def admin_required(fn: Callable) -> Callable:
|
|
|
97
78
|
def decorated_view(*args, **kwargs):
|
|
98
79
|
access_token = get_access_token()
|
|
99
80
|
if not access_token:
|
|
81
|
+
logger.warning("admin_required: Access token is missing")
|
|
100
82
|
abort(401)
|
|
101
83
|
|
|
102
84
|
if not check_role(access_token, "admin"):
|
|
85
|
+
logger.warning("admin_required: User does not have admin role")
|
|
103
86
|
abort(403)
|
|
104
87
|
|
|
88
|
+
logger.info("admin_required: User is an admin")
|
|
105
89
|
return fn(*args, **kwargs)
|
|
106
90
|
|
|
107
91
|
return decorated_view
|
|
@@ -125,11 +109,18 @@ def role_required(role: str) -> Callable:
|
|
|
125
109
|
def restricted_function(*args, **kwargs):
|
|
126
110
|
access_token = get_access_token()
|
|
127
111
|
if not access_token:
|
|
112
|
+
logger.warning(
|
|
113
|
+
f"role_required: Access token is missing for role {role}"
|
|
114
|
+
)
|
|
128
115
|
abort(401)
|
|
129
116
|
|
|
130
117
|
if not check_role(access_token, role):
|
|
118
|
+
logger.warning(
|
|
119
|
+
f"role_required: User does not have required role {role}"
|
|
120
|
+
)
|
|
131
121
|
abort(403)
|
|
132
122
|
|
|
123
|
+
logger.info(f"role_required: User has required role {role}")
|
|
133
124
|
res = f(*args, **kwargs)
|
|
134
125
|
|
|
135
126
|
return res
|
|
@@ -158,18 +149,23 @@ def has_scope(scope_list: List[str]) -> Callable:
|
|
|
158
149
|
def restricted_function(*args, **kwargs):
|
|
159
150
|
token = get_access_token()
|
|
160
151
|
if not token:
|
|
152
|
+
logger.warning("has_scope: Access token is missing")
|
|
161
153
|
return None
|
|
162
154
|
|
|
163
155
|
token_info = get_keycloak_openid().introspect(token)
|
|
164
|
-
|
|
165
156
|
if not token_info.json()["active"]:
|
|
157
|
+
logger.warning("has_scope: Access token is inactive")
|
|
166
158
|
return None
|
|
167
159
|
|
|
168
160
|
granted_scope = token_info.json()["scope"].split()
|
|
169
161
|
for requested_scope in scope_list:
|
|
170
162
|
if requested_scope not in granted_scope:
|
|
163
|
+
logger.warning(
|
|
164
|
+
f"has_scope: Required scope {requested_scope} not granted"
|
|
165
|
+
)
|
|
171
166
|
return None
|
|
172
167
|
|
|
168
|
+
logger.info("has_scope: All required scopes are granted")
|
|
173
169
|
res = f(*args, **kwargs)
|
|
174
170
|
|
|
175
171
|
return res
|
|
@@ -7,6 +7,31 @@ from typing import Any, Optional, Tuple, Union
|
|
|
7
7
|
|
|
8
8
|
from keycloak import KeycloakAdmin, KeycloakOpenID
|
|
9
9
|
|
|
10
|
+
from shieldapi import logger
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def print_env_vars():
|
|
14
|
+
env_vars = {
|
|
15
|
+
"KEYCLOAK_HOST": os.environ.get("KEYCLOAK_HOST"),
|
|
16
|
+
"KEYCLOAK_REALM_NAME": os.environ.get("KEYCLOAK_REALM_NAME"),
|
|
17
|
+
"KEYCLOAK_CLIENT_ID": os.environ.get("KEYCLOAK_CLIENT_ID"),
|
|
18
|
+
"KEYCLOAK_CLIENT_SECRET": os.environ.get("KEYCLOAK_CLIENT_SECRET"),
|
|
19
|
+
"KEYCLOAK_VERIFY_HOST": os.environ.get("KEYCLOAK_VERIFY_HOST"),
|
|
20
|
+
"KEYCLOAK_REALM_ADMIN_USER": os.environ.get("KEYCLOAK_REALM_ADMIN_USER"),
|
|
21
|
+
"KEYCLOAK_REALM_ADMIN_PASSWORD": os.environ.get(
|
|
22
|
+
"KEYCLOAK_REALM_ADMIN_PASSWORD"
|
|
23
|
+
),
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
logger.info("Environment variables received:")
|
|
27
|
+
|
|
28
|
+
for key, value in env_vars.items():
|
|
29
|
+
if value and key in {"KEYCLOAK_CLIENT_SECRET", "KEYCLOAK_REALM_ADMIN_PASSWORD"}:
|
|
30
|
+
masked_value = value[:4] + "*" * (len(value) - 4)
|
|
31
|
+
logger.info(f"{key}: {masked_value}")
|
|
32
|
+
else:
|
|
33
|
+
logger.info(f"{key}: {value}")
|
|
34
|
+
|
|
10
35
|
|
|
11
36
|
def get_keycloak_openid(
|
|
12
37
|
server_url: Optional[str] = None,
|
|
@@ -38,7 +63,7 @@ def get_keycloak_openid(
|
|
|
38
63
|
Raises:
|
|
39
64
|
KeyError: If any required values are missing.
|
|
40
65
|
"""
|
|
41
|
-
|
|
66
|
+
logger.debug("Creating KeycloakOpenID instance")
|
|
42
67
|
return KeycloakOpenID(
|
|
43
68
|
server_url=_get_value(
|
|
44
69
|
server_url, "KEYCLOAK_HOST", "http://keycloak:8080/auth/"
|
|
@@ -81,6 +106,7 @@ def get_keycloak_admin(
|
|
|
81
106
|
KeyError:
|
|
82
107
|
If any required values are missing.
|
|
83
108
|
"""
|
|
109
|
+
logger.debug("Creating KeycloakAdmin instance")
|
|
84
110
|
return KeycloakAdmin(
|
|
85
111
|
server_url=_get_value(
|
|
86
112
|
server_url, "KEYCLOAK_HOST", "http://keycloak:8080/auth/"
|
|
@@ -126,9 +152,11 @@ def _get_value(
|
|
|
126
152
|
message = f"""Both the kwarg ({param}) and the env-variable for '{env_var}' ({env}) are assigned.
|
|
127
153
|
Note that the argument takes precedence over the env-variable."""
|
|
128
154
|
warnings.warn(UserWarning(message))
|
|
155
|
+
logger.warning(message)
|
|
129
156
|
elif param is None and env is None and default is None:
|
|
130
157
|
message = f"""Both the kwarg and the env-variable for '{env_var}' are None.
|
|
131
158
|
Please assign one of them to a value."""
|
|
159
|
+
logger.error(message)
|
|
132
160
|
raise ValueError(message)
|
|
133
161
|
|
|
134
162
|
if isinstance(param, bool):
|
|
@@ -143,6 +171,7 @@ def _get_value(
|
|
|
143
171
|
message = (
|
|
144
172
|
f"The '{env_var}' env-var valued '{env}' must be 'True' or 'False'."
|
|
145
173
|
)
|
|
174
|
+
logger.error(message)
|
|
146
175
|
print(message, flush=True)
|
|
147
176
|
raise TypeError(message)
|
|
148
177
|
return param or env or default
|
|
@@ -158,64 +187,44 @@ def check_role(token: str, role: str) -> bool:
|
|
|
158
187
|
Returns:
|
|
159
188
|
bool: whether the token contains the role
|
|
160
189
|
"""
|
|
190
|
+
logger.info(f"Checking role '{role}' for token")
|
|
161
191
|
token_info = get_keycloak_openid().introspect(token)
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
192
|
+
if bool(token_info["active"]):
|
|
193
|
+
has_role = "roles" in token_info and role in token_info["roles"]
|
|
194
|
+
logger.debug(f"Token has role '{role}': {has_role}")
|
|
195
|
+
return has_role
|
|
165
196
|
return False
|
|
166
197
|
|
|
167
198
|
|
|
168
199
|
def check_token_validity(
|
|
169
|
-
access_token: str,
|
|
170
|
-
server_url: Optional[str] = None,
|
|
171
|
-
realm_name: Optional[str] = None,
|
|
172
|
-
client_id: Optional[str] = None,
|
|
173
|
-
client_secret: Optional[str] = None,
|
|
174
|
-
verify: Optional[bool] = None,
|
|
200
|
+
access_token: str, validate_with_auth_server: Optional[bool] = True
|
|
175
201
|
) -> bool:
|
|
176
202
|
"""Check if the given access token is valid.
|
|
177
203
|
|
|
178
204
|
Args:
|
|
179
205
|
access_token: str
|
|
180
206
|
The access token to check.
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
The URL of the Keycloak server. If not provided, the value from the environment variable
|
|
184
|
-
KEYCLOAK_HOST will be used.
|
|
185
|
-
realm_name (Optional[str]):
|
|
186
|
-
The name of the realm in Keycloak. If not provided, the value from the environment variable
|
|
187
|
-
KEYCLOAK_REALM_NAME will be used.
|
|
188
|
-
client_id (Optional[str]):
|
|
189
|
-
The id of the client in Keycloak. If not provided, the value from the environment
|
|
190
|
-
variable KEYCLOAK_CLIENT_ID will be used.
|
|
191
|
-
client_secret (Optional[str]):
|
|
192
|
-
The client secret key for the client in Keycloak. If not provided, the value from the environment
|
|
193
|
-
variable KEYCLOAK_CLIENT_SECRET will be used.
|
|
194
|
-
verify (Optional[bool]):
|
|
195
|
-
Controls whether SSL certificates are verified for HTTPS requests. If set to False, SSL
|
|
196
|
-
verification is disabled. If set to a string, it should be the path to a CA_BUNDLE file or
|
|
197
|
-
a directory containing certificates of trusted CA.
|
|
207
|
+
validate_with_auth_server: boolean
|
|
208
|
+
Indicates whether the validation is done through the server.
|
|
198
209
|
|
|
199
210
|
Returns:
|
|
200
211
|
bool: Whether the token is valid.
|
|
201
212
|
"""
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
).introspect(access_token)
|
|
205
|
-
|
|
206
|
-
return _check_active_token(token_info)
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
def _check_active_token(token_info) -> bool:
|
|
210
|
-
"""Checks if a given token introspect information is marked as valid
|
|
213
|
+
logger.info("Checking token validity")
|
|
214
|
+
keycloak_openid = get_keycloak_openid()
|
|
211
215
|
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
216
|
+
valid = False
|
|
217
|
+
if validate_with_auth_server:
|
|
218
|
+
token_info = keycloak_openid.introspect(access_token)
|
|
219
|
+
valid = bool(token_info["active"])
|
|
220
|
+
else:
|
|
221
|
+
try:
|
|
222
|
+
get_keycloak_openid().decode_token(access_token, validate=True)
|
|
223
|
+
valid = True
|
|
224
|
+
except Exception as e:
|
|
225
|
+
logger.warning(f"AuthTokenBearer.__call__: Token validation failed: {e}")
|
|
226
|
+
logger.debug(f"Token validity: {valid}")
|
|
227
|
+
return valid
|
|
219
228
|
|
|
220
229
|
|
|
221
230
|
def check_useraccount_access(
|
|
@@ -253,13 +262,18 @@ def check_useraccount_access(
|
|
|
253
262
|
Returns:
|
|
254
263
|
str: A string indicating whether or not the access token has the 'openid' scope.
|
|
255
264
|
"""
|
|
265
|
+
logger.info("Checking user account access")
|
|
256
266
|
token_info = get_keycloak_openid(
|
|
257
267
|
server_url, realm_name, client_id, client_secret, verify
|
|
258
268
|
).introspect(access_token)
|
|
259
269
|
granted_scope = token_info.json()["scope"].split()
|
|
260
270
|
if "openid" not in granted_scope:
|
|
261
|
-
|
|
262
|
-
|
|
271
|
+
message = "OpenID scope was not granted"
|
|
272
|
+
logger.warning(message)
|
|
273
|
+
return message, 401
|
|
274
|
+
message = "Access granted"
|
|
275
|
+
logger.info(message)
|
|
276
|
+
return message, 200
|
|
263
277
|
|
|
264
278
|
|
|
265
279
|
def login(
|
|
@@ -302,13 +316,18 @@ def login(
|
|
|
302
316
|
If successful, returns a string representing the access token. Otherwise, returns
|
|
303
317
|
a tuple containing the status code and an error message.
|
|
304
318
|
"""
|
|
319
|
+
logger.info("Logging in user")
|
|
305
320
|
token = get_keycloak_openid(
|
|
306
321
|
server_url, realm_name, client_id, client_secret, verify
|
|
307
322
|
).token(username=username, password=password)
|
|
308
323
|
if not token.get("access_token") and token.get("token_type"):
|
|
309
|
-
|
|
324
|
+
message = "Token could not be generated. Please contact the admin."
|
|
325
|
+
logger.error(message)
|
|
326
|
+
return 401, message
|
|
310
327
|
else:
|
|
311
|
-
|
|
328
|
+
token_str = f"{token.get('token_type')} {token.get('access_token')}"
|
|
329
|
+
logger.info("Token generated successfully")
|
|
330
|
+
return token_str
|
|
312
331
|
|
|
313
332
|
|
|
314
333
|
def make_auth_header(
|
|
@@ -352,6 +371,7 @@ def make_auth_header(
|
|
|
352
371
|
Otherwise, a tuple containing a status code and an error message.
|
|
353
372
|
|
|
354
373
|
"""
|
|
374
|
+
logger.info("Making authentication header")
|
|
355
375
|
credentials = login(
|
|
356
376
|
username,
|
|
357
377
|
password,
|
|
@@ -362,6 +382,42 @@ def make_auth_header(
|
|
|
362
382
|
verify,
|
|
363
383
|
)
|
|
364
384
|
if type(credentials) == str:
|
|
385
|
+
logger.info("Authentication header created successfully")
|
|
365
386
|
return {"Authorization": credentials}
|
|
366
387
|
else:
|
|
388
|
+
logger.error("Failed to create authentication header")
|
|
367
389
|
return credentials
|
|
390
|
+
|
|
391
|
+
|
|
392
|
+
def get_userinfo(token) -> dict:
|
|
393
|
+
"""
|
|
394
|
+
Returns the user information from the access token.
|
|
395
|
+
|
|
396
|
+
Args:
|
|
397
|
+
token: str
|
|
398
|
+
The access token of the user.
|
|
399
|
+
|
|
400
|
+
Returns:
|
|
401
|
+
dict:
|
|
402
|
+
The user information.
|
|
403
|
+
"""
|
|
404
|
+
userinfo = get_keycloak_openid().userinfo(token)
|
|
405
|
+
logger.debug(f"get_userinfo: Retrieved user info {userinfo}")
|
|
406
|
+
return userinfo
|
|
407
|
+
|
|
408
|
+
|
|
409
|
+
def get_current_user() -> str:
|
|
410
|
+
"""
|
|
411
|
+
Get the current logged in user.
|
|
412
|
+
|
|
413
|
+
Returns:
|
|
414
|
+
str:
|
|
415
|
+
The user ID.
|
|
416
|
+
"""
|
|
417
|
+
user_info = get_userinfo()
|
|
418
|
+
if not user_info:
|
|
419
|
+
logger.warning("get_current_user: No user info available")
|
|
420
|
+
return ""
|
|
421
|
+
user_id = user_info.get("sub", "")
|
|
422
|
+
logger.debug(f"get_current_user: Current user ID {user_id}")
|
|
423
|
+
return user_id
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
Metadata-Version: 2.
|
|
1
|
+
Metadata-Version: 2.2
|
|
2
2
|
Name: shieldapi
|
|
3
|
-
Version:
|
|
3
|
+
Version: 2.0.0
|
|
4
4
|
Summary: A package for endpoint protection of APIs using Keycloak
|
|
5
|
-
Author:
|
|
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
|
|
@@ -78,6 +78,10 @@ In order to successfully enable the callback for the token-generation and token-
|
|
|
78
78
|
| `KEYCLOAK_VERIFY_HOST` | Controls whether SSL certificates are verified for HTTPS requests. Default is set to `False`. | "True" |
|
|
79
79
|
| `KEYCLOAK_REALM_ADMIN_USER` | User name of the realm admin, if any action shall be performed as admin in your Flask/FastAPI application. | "admin" |
|
|
80
80
|
| `KEYCLOAK_REALM_ADMIN_PASSWORD` | Password of the realm admin, if any action shall be performed as admin in your Flask/FastAPI application. | "admin_password" |
|
|
81
|
+
| `SKIP_ENV_CHECK` | Optional. If set, skips the check for mandatory environment variables during startup. | "True" |
|
|
82
|
+
|
|
83
|
+
#### Note
|
|
84
|
+
- If `SKIP_ENV_CHECK` is set, the application will bypass the mandatory environment variable checks during startup. This is useful for development or testing scenarios where not all variables are needed.
|
|
81
85
|
|
|
82
86
|
## Usage with Flask
|
|
83
87
|
|
|
@@ -407,4 +411,4 @@ This work is supported by the MarketPlace project funded by [Horizon 2020](https
|
|
|
407
411
|
## License
|
|
408
412
|
|
|
409
413
|
The code is licensed under BSD-3-Clause.
|
|
410
|
-
Copyright ©
|
|
414
|
+
Copyright © 2025 Materials MarketPlace
|
|
@@ -9,9 +9,6 @@ def _mock_active_token(token_info: dict) -> bool:
|
|
|
9
9
|
@pytest.fixture(scope="function")
|
|
10
10
|
def mock_introspect(mocker):
|
|
11
11
|
"""Make a mock for checking if token is active."""
|
|
12
|
-
import shieldapi.keycloak_utils as utils
|
|
13
|
-
|
|
14
12
|
mocker_intro = mocker.MagicMock()
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
yield mocker_intro
|
|
13
|
+
mocker_intro.side_effect = _mock_active_token
|
|
14
|
+
yield mocker_intro
|
|
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
|