shieldapi 2.1.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.1.0/shieldapi.egg-info → shieldapi-2.3.0}/PKG-INFO +11 -9
- {shieldapi-2.1.0 → shieldapi-2.3.0}/setup.cfg +12 -10
- {shieldapi-2.1.0 → shieldapi-2.3.0}/shieldapi/frameworks/fastapi.py +36 -3
- {shieldapi-2.1.0 → shieldapi-2.3.0}/shieldapi/frameworks/flask.py +29 -61
- shieldapi-2.3.0/shieldapi/keycloak_utils.py +355 -0
- {shieldapi-2.1.0 → shieldapi-2.3.0/shieldapi.egg-info}/PKG-INFO +11 -9
- shieldapi-2.3.0/shieldapi.egg-info/requires.txt +19 -0
- shieldapi-2.3.0/tests/mock.py +112 -0
- {shieldapi-2.1.0 → shieldapi-2.3.0}/tests/test_fastapi.py +51 -3
- shieldapi-2.3.0/tests/test_flask.py +224 -0
- {shieldapi-2.1.0 → shieldapi-2.3.0}/tests/test_keycloak_utils.py +13 -1
- shieldapi-2.1.0/shieldapi/keycloak_utils.py +0 -460
- shieldapi-2.1.0/shieldapi.egg-info/requires.txt +0 -15
- shieldapi-2.1.0/tests/mock.py +0 -69
- shieldapi-2.1.0/tests/test_flask.py +0 -27
- {shieldapi-2.1.0 → shieldapi-2.3.0}/LICENSE +0 -0
- {shieldapi-2.1.0 → shieldapi-2.3.0}/README.md +0 -0
- {shieldapi-2.1.0 → shieldapi-2.3.0}/pyproject.toml +0 -0
- {shieldapi-2.1.0 → shieldapi-2.3.0}/setup.py +0 -0
- {shieldapi-2.1.0 → shieldapi-2.3.0}/shieldapi/__init__.py +0 -0
- {shieldapi-2.1.0 → shieldapi-2.3.0}/shieldapi/frameworks/__init__.py +0 -0
- {shieldapi-2.1.0 → shieldapi-2.3.0}/shieldapi.egg-info/SOURCES.txt +0 -0
- {shieldapi-2.1.0 → shieldapi-2.3.0}/shieldapi.egg-info/dependency_links.txt +0 -0
- {shieldapi-2.1.0 → shieldapi-2.3.0}/shieldapi.egg-info/top_level.txt +0 -0
- {shieldapi-2.1.0 → shieldapi-2.3.0}/tests/__init__.py +0 -0
- {shieldapi-2.1.0 → shieldapi-2.3.0}/tests/conftest.py +0 -0
|
@@ -1,26 +1,28 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: shieldapi
|
|
3
|
-
Version: 2.
|
|
3
|
+
Version: 2.3.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.
|
|
10
|
+
Requires-Python: >=3.9
|
|
11
11
|
Description-Content-Type: text/markdown
|
|
12
12
|
License-File: LICENSE
|
|
13
|
-
Requires-Dist: python-keycloak>=
|
|
14
|
-
|
|
15
|
-
Requires-Dist:
|
|
13
|
+
Requires-Dist: python-keycloak>=4.0
|
|
14
|
+
Provides-Extra: flask
|
|
15
|
+
Requires-Dist: flask>=2.3; extra == "flask"
|
|
16
|
+
Provides-Extra: fastapi
|
|
17
|
+
Requires-Dist: fastapi>=0.100.0; extra == "fastapi"
|
|
16
18
|
Provides-Extra: dev
|
|
17
|
-
Requires-Dist: bumpver
|
|
18
|
-
Requires-Dist: dunamai
|
|
19
|
+
Requires-Dist: bumpver>=2023.1119; extra == "dev"
|
|
20
|
+
Requires-Dist: dunamai>=1.7.0; extra == "dev"
|
|
19
21
|
Requires-Dist: pre-commit~=4.3.0; extra == "dev"
|
|
20
22
|
Provides-Extra: tests
|
|
21
|
-
Requires-Dist: pytest
|
|
23
|
+
Requires-Dist: pytest>=7.1.3; extra == "tests"
|
|
22
24
|
Requires-Dist: requests-mock<2.0,>=1.10.0; extra == "tests"
|
|
23
|
-
Requires-Dist: httpx
|
|
25
|
+
Requires-Dist: httpx>=0.23.3; extra == "tests"
|
|
24
26
|
Requires-Dist: semver<3.0,>=2.13.0; extra == "tests"
|
|
25
27
|
Requires-Dist: pytest-mock>=3.10.0; extra == "tests"
|
|
26
28
|
Dynamic: license-file
|
|
@@ -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
|
|
@@ -13,26 +13,28 @@ classifiers =
|
|
|
13
13
|
|
|
14
14
|
[options]
|
|
15
15
|
packages = find:
|
|
16
|
-
python_requires = >=3.
|
|
16
|
+
python_requires = >=3.9
|
|
17
17
|
install_requires =
|
|
18
|
-
python-keycloak>=
|
|
19
|
-
flask>=2.2.3,<3.0
|
|
20
|
-
fastapi>=0.85.0,<1.0
|
|
18
|
+
python-keycloak>=4.0
|
|
21
19
|
|
|
22
20
|
[options.extras_require]
|
|
21
|
+
flask =
|
|
22
|
+
flask>=2.3
|
|
23
|
+
fastapi =
|
|
24
|
+
fastapi>=0.100.0
|
|
23
25
|
dev =
|
|
24
|
-
bumpver
|
|
25
|
-
dunamai
|
|
26
|
+
bumpver>=2023.1119
|
|
27
|
+
dunamai>=1.7.0
|
|
26
28
|
pre-commit~=4.3.0
|
|
27
29
|
tests =
|
|
28
|
-
pytest>=7.1.3
|
|
30
|
+
pytest>=7.1.3
|
|
29
31
|
requests-mock>=1.10.0,<2.0
|
|
30
|
-
httpx>=0.23.3
|
|
32
|
+
httpx>=0.23.3
|
|
31
33
|
semver>=2.13.0,<3.0
|
|
32
34
|
pytest-mock>=3.10.0
|
|
33
35
|
|
|
34
36
|
[bumpver]
|
|
35
|
-
current_version = "
|
|
37
|
+
current_version = "v2.3.0"
|
|
36
38
|
version_pattern = "vMAJOR.MINOR.PATCH[PYTAGNUM]"
|
|
37
39
|
commit_message = "Bump version {old_version} -> {new_version}"
|
|
38
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):
|
|
@@ -104,7 +110,7 @@ class BasicLoginCredentials(HTTPBasicCredentials):
|
|
|
104
110
|
f"BasicLoginCredentials.token: Attempting login for username={self.username}"
|
|
105
111
|
)
|
|
106
112
|
token = login(self.username, self.password)
|
|
107
|
-
if
|
|
113
|
+
if isinstance(token, tuple):
|
|
108
114
|
logger.error(
|
|
109
115
|
f"BasicLoginCredentials.token: Invalid credentials for username={self.username}"
|
|
110
116
|
)
|
|
@@ -154,7 +160,7 @@ class BasicLogin(HTTPBasic):
|
|
|
154
160
|
f"BasicLogin.__call__: Credentials extracted for username={log.username}"
|
|
155
161
|
)
|
|
156
162
|
token = login(log.username, log.password)
|
|
157
|
-
if
|
|
163
|
+
if isinstance(token, tuple):
|
|
158
164
|
logger.error(
|
|
159
165
|
f"BasicLogin.__call__: Invalid credentials for username={log.username}"
|
|
160
166
|
)
|
|
@@ -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
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"""
|
|
1
|
+
"""Decorators for protecting Flask endpoints with Keycloak authentication."""
|
|
2
2
|
|
|
3
3
|
from functools import wraps
|
|
4
4
|
from typing import Callable, List
|
|
@@ -13,13 +13,10 @@ from shieldapi.keycloak_utils import (
|
|
|
13
13
|
)
|
|
14
14
|
|
|
15
15
|
|
|
16
|
-
def get_access_token():
|
|
17
|
-
"""
|
|
18
|
-
Returns the access token from the Authorization header of the request.
|
|
16
|
+
def get_access_token() -> str:
|
|
17
|
+
"""Extract the Bearer token from the Authorization request header.
|
|
19
18
|
|
|
20
|
-
Returns
|
|
21
|
-
str:
|
|
22
|
-
The access token.
|
|
19
|
+
Returns an empty string when the header is missing or malformed.
|
|
23
20
|
"""
|
|
24
21
|
auth_header = request.headers.get("Authorization", default="")
|
|
25
22
|
if not auth_header or "Bearer" not in auth_header:
|
|
@@ -31,17 +28,7 @@ def get_access_token():
|
|
|
31
28
|
|
|
32
29
|
|
|
33
30
|
def login_required(fn: Callable) -> Callable:
|
|
34
|
-
"""
|
|
35
|
-
Decorator that checks if the user is logged in.
|
|
36
|
-
|
|
37
|
-
Args:
|
|
38
|
-
fn (Callable):
|
|
39
|
-
The function to be decorated.
|
|
40
|
-
|
|
41
|
-
Returns:
|
|
42
|
-
Callable:
|
|
43
|
-
The decorated function.
|
|
44
|
-
"""
|
|
31
|
+
"""Decorator: reject requests without a valid Keycloak Bearer token (401)."""
|
|
45
32
|
|
|
46
33
|
@wraps(fn)
|
|
47
34
|
def decorated_view(*args, **kwargs):
|
|
@@ -50,8 +37,7 @@ def login_required(fn: Callable) -> Callable:
|
|
|
50
37
|
logger.warning("login_required: Access token is missing")
|
|
51
38
|
abort(401)
|
|
52
39
|
|
|
53
|
-
|
|
54
|
-
if not valid:
|
|
40
|
+
if not check_token_validity(access_token):
|
|
55
41
|
logger.warning("login_required: Access token is invalid or expired")
|
|
56
42
|
abort(401)
|
|
57
43
|
|
|
@@ -62,16 +48,11 @@ def login_required(fn: Callable) -> Callable:
|
|
|
62
48
|
|
|
63
49
|
|
|
64
50
|
def admin_required(fn: Callable) -> Callable:
|
|
65
|
-
"""
|
|
66
|
-
Decorator that checks if the user is an admin.
|
|
67
|
-
|
|
68
|
-
Args:
|
|
69
|
-
fn (Callable):
|
|
70
|
-
The function to be decorated.
|
|
51
|
+
"""Decorator: reject requests where the token does not carry the 'admin' role (403).
|
|
71
52
|
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
53
|
+
Checks realm_access.roles, resource_access.<client>.roles, and any flat
|
|
54
|
+
top-level 'roles' field in the Keycloak introspection response.
|
|
55
|
+
Must be stacked inside login_required so the token is already validated.
|
|
75
56
|
"""
|
|
76
57
|
|
|
77
58
|
@wraps(fn)
|
|
@@ -92,16 +73,14 @@ def admin_required(fn: Callable) -> Callable:
|
|
|
92
73
|
|
|
93
74
|
|
|
94
75
|
def role_required(role: str) -> Callable:
|
|
95
|
-
"""
|
|
96
|
-
Decorator that limits access to users with a certain role.
|
|
76
|
+
"""Decorator factory: reject requests missing the given Keycloak role (403).
|
|
97
77
|
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
78
|
+
Checks realm_access.roles, resource_access.<client>.roles, and any flat
|
|
79
|
+
top-level 'roles' field in the Keycloak introspection response.
|
|
80
|
+
Must be stacked inside login_required so the token is already validated.
|
|
101
81
|
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
The decorator function.
|
|
82
|
+
Args:
|
|
83
|
+
role: The Keycloak role name that the caller must hold.
|
|
105
84
|
"""
|
|
106
85
|
|
|
107
86
|
def decorator(f: Callable) -> Callable:
|
|
@@ -110,20 +89,18 @@ def role_required(role: str) -> Callable:
|
|
|
110
89
|
access_token = get_access_token()
|
|
111
90
|
if not access_token:
|
|
112
91
|
logger.warning(
|
|
113
|
-
f"role_required: Access token is missing for role {role}"
|
|
92
|
+
f"role_required: Access token is missing for role '{role}'"
|
|
114
93
|
)
|
|
115
94
|
abort(401)
|
|
116
95
|
|
|
117
96
|
if not check_role(access_token, role):
|
|
118
97
|
logger.warning(
|
|
119
|
-
f"role_required: User does not have required role {role}"
|
|
98
|
+
f"role_required: User does not have required role '{role}'"
|
|
120
99
|
)
|
|
121
100
|
abort(403)
|
|
122
101
|
|
|
123
|
-
logger.info(f"role_required: User has required role {role}")
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
return res
|
|
102
|
+
logger.info(f"role_required: User has required role '{role}'")
|
|
103
|
+
return f(*args, **kwargs)
|
|
127
104
|
|
|
128
105
|
return restricted_function
|
|
129
106
|
|
|
@@ -131,17 +108,10 @@ def role_required(role: str) -> Callable:
|
|
|
131
108
|
|
|
132
109
|
|
|
133
110
|
def has_scope(scope_list: List[str]) -> Callable:
|
|
134
|
-
"""
|
|
135
|
-
Decorator that limits access to the applications which have been
|
|
136
|
-
granted the required scopes.
|
|
111
|
+
"""Decorator factory: reject requests where the token lacks any listed OAuth scope (403).
|
|
137
112
|
|
|
138
113
|
Args:
|
|
139
|
-
scope_list
|
|
140
|
-
The list of required scopes.
|
|
141
|
-
|
|
142
|
-
Returns:
|
|
143
|
-
Callable:
|
|
144
|
-
The decorator function.
|
|
114
|
+
scope_list: OAuth scopes that must all be present in the token.
|
|
145
115
|
"""
|
|
146
116
|
|
|
147
117
|
def decorator(f: Callable) -> Callable:
|
|
@@ -150,25 +120,23 @@ def has_scope(scope_list: List[str]) -> Callable:
|
|
|
150
120
|
token = get_access_token()
|
|
151
121
|
if not token:
|
|
152
122
|
logger.warning("has_scope: Access token is missing")
|
|
153
|
-
|
|
123
|
+
abort(401)
|
|
154
124
|
|
|
155
125
|
token_info = get_keycloak_openid().introspect(token)
|
|
156
|
-
if not token_info.
|
|
126
|
+
if not bool(token_info.get("active")):
|
|
157
127
|
logger.warning("has_scope: Access token is inactive")
|
|
158
|
-
|
|
128
|
+
abort(401)
|
|
159
129
|
|
|
160
|
-
granted_scope = token_info.
|
|
130
|
+
granted_scope = token_info.get("scope", "").split()
|
|
161
131
|
for requested_scope in scope_list:
|
|
162
132
|
if requested_scope not in granted_scope:
|
|
163
133
|
logger.warning(
|
|
164
|
-
f"has_scope: Required scope {requested_scope} not granted"
|
|
134
|
+
f"has_scope: Required scope '{requested_scope}' not granted"
|
|
165
135
|
)
|
|
166
|
-
|
|
136
|
+
abort(403)
|
|
167
137
|
|
|
168
138
|
logger.info("has_scope: All required scopes are granted")
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
return res
|
|
139
|
+
return f(*args, **kwargs)
|
|
172
140
|
|
|
173
141
|
return restricted_function
|
|
174
142
|
|
|
@@ -0,0 +1,355 @@
|
|
|
1
|
+
"""Functions for interacting with a Keycloak-client."""
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
import warnings
|
|
5
|
+
from ast import literal_eval
|
|
6
|
+
from typing import Any, Dict, Optional, Tuple, Union
|
|
7
|
+
|
|
8
|
+
from keycloak import KeycloakAdmin, KeycloakOpenID
|
|
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
|
+
|
|
35
|
+
|
|
36
|
+
def get_keycloak_openid(
|
|
37
|
+
server_url: Optional[str] = None,
|
|
38
|
+
realm_name: Optional[str] = None,
|
|
39
|
+
client_id: Optional[str] = None,
|
|
40
|
+
client_secret: Optional[str] = None,
|
|
41
|
+
verify: Optional[bool] = None,
|
|
42
|
+
) -> KeycloakOpenID:
|
|
43
|
+
"""Create a KeycloakOpenID instance from parameters or environment variables.
|
|
44
|
+
|
|
45
|
+
Kwargs:
|
|
46
|
+
server_url: Keycloak server URL. Falls back to $KEYCLOAK_HOST.
|
|
47
|
+
realm_name: Realm name. Falls back to $KEYCLOAK_REALM_NAME.
|
|
48
|
+
client_id: OIDC client ID. Falls back to $KEYCLOAK_CLIENT_ID.
|
|
49
|
+
client_secret: Client secret. Falls back to $KEYCLOAK_CLIENT_SECRET.
|
|
50
|
+
verify: TLS verification. Falls back to $KEYCLOAK_VERIFY_HOST (default False).
|
|
51
|
+
"""
|
|
52
|
+
logger.debug("Creating KeycloakOpenID instance")
|
|
53
|
+
return KeycloakOpenID(
|
|
54
|
+
server_url=_get_value(
|
|
55
|
+
server_url, "KEYCLOAK_HOST", "http://keycloak:8080/auth/"
|
|
56
|
+
),
|
|
57
|
+
realm_name=_get_value(realm_name, "KEYCLOAK_REALM_NAME"),
|
|
58
|
+
client_id=_get_value(client_id, "KEYCLOAK_CLIENT_ID", "shieldapi"),
|
|
59
|
+
client_secret_key=_get_value(client_secret, "KEYCLOAK_CLIENT_SECRET"),
|
|
60
|
+
verify=_get_value(verify, "KEYCLOAK_VERIFY_HOST", False, True),
|
|
61
|
+
)
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def get_keycloak_admin(
|
|
65
|
+
server_url: Optional[str] = None,
|
|
66
|
+
username: Optional[str] = None,
|
|
67
|
+
password: Optional[str] = None,
|
|
68
|
+
client_id: Optional[str] = None,
|
|
69
|
+
client_secret: Optional[str] = None,
|
|
70
|
+
realm_name: Optional[str] = None,
|
|
71
|
+
verify: Optional[bool] = None,
|
|
72
|
+
use_service_account: Optional[bool] = None,
|
|
73
|
+
) -> KeycloakAdmin:
|
|
74
|
+
"""Create a KeycloakAdmin instance from parameters or environment variables.
|
|
75
|
+
|
|
76
|
+
Kwargs:
|
|
77
|
+
server_url: Keycloak server URL. Falls back to $KEYCLOAK_HOST.
|
|
78
|
+
username: Admin username. Falls back to $KEYCLOAK_REALM_ADMIN_USER.
|
|
79
|
+
password: Admin password. Falls back to $KEYCLOAK_REALM_ADMIN_PASSWORD.
|
|
80
|
+
client_id: Client ID for service account auth. Falls back to $KEYCLOAK_CLIENT_ID.
|
|
81
|
+
client_secret: Client secret for service account auth. Falls back to $KEYCLOAK_CLIENT_SECRET.
|
|
82
|
+
realm_name: Realm name. Falls back to $KEYCLOAK_REALM_NAME.
|
|
83
|
+
verify: TLS verification. Falls back to $KEYCLOAK_VERIFY_HOST (default False).
|
|
84
|
+
use_service_account: Use client credentials instead of user/password.
|
|
85
|
+
Falls back to $KEYCLOAK_USE_SERVICE_ACCOUNT (default False).
|
|
86
|
+
"""
|
|
87
|
+
logger.debug("Creating KeycloakAdmin instance")
|
|
88
|
+
use_service_account = _get_value(
|
|
89
|
+
use_service_account, "KEYCLOAK_USE_SERVICE_ACCOUNT", False, True
|
|
90
|
+
)
|
|
91
|
+
if use_service_account:
|
|
92
|
+
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),
|
|
101
|
+
)
|
|
102
|
+
else:
|
|
103
|
+
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
|
+
)
|
|
113
|
+
return admin
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def _get_value(
|
|
117
|
+
param: Any,
|
|
118
|
+
env_var: str,
|
|
119
|
+
default: Optional[Any] = None,
|
|
120
|
+
boolean: Optional[bool] = False,
|
|
121
|
+
) -> Any:
|
|
122
|
+
"""Return param, falling back to env_var, then default.
|
|
123
|
+
|
|
124
|
+
Emits a UserWarning when both param and env_var are set (param wins).
|
|
125
|
+
Raises ValueError when all three are None.
|
|
126
|
+
Raises TypeError when boolean=True and the env_var value is not 'True'/'False'.
|
|
127
|
+
"""
|
|
128
|
+
env = os.environ.get(env_var)
|
|
129
|
+
|
|
130
|
+
if (param or isinstance(param, bool)) and env:
|
|
131
|
+
message = (
|
|
132
|
+
f"Both the kwarg ({param}) and the env-variable for '{env_var}' ({env}) are assigned. "
|
|
133
|
+
f"Note that the argument takes precedence over the env-variable."
|
|
134
|
+
)
|
|
135
|
+
warnings.warn(UserWarning(message))
|
|
136
|
+
logger.warning(message)
|
|
137
|
+
elif param is None and env is None and default is None:
|
|
138
|
+
message = (
|
|
139
|
+
f"Both the kwarg and the env-variable for '{env_var}' are None. "
|
|
140
|
+
f"Please assign one of them to a value."
|
|
141
|
+
)
|
|
142
|
+
logger.error(message)
|
|
143
|
+
raise ValueError(message)
|
|
144
|
+
|
|
145
|
+
if isinstance(param, bool):
|
|
146
|
+
return param
|
|
147
|
+
else:
|
|
148
|
+
if boolean and env:
|
|
149
|
+
try:
|
|
150
|
+
env = literal_eval(env)
|
|
151
|
+
if not isinstance(env, bool):
|
|
152
|
+
raise ValueError
|
|
153
|
+
except (ValueError, SyntaxError):
|
|
154
|
+
message = (
|
|
155
|
+
f"The '{env_var}' env-var valued '{env}' must be 'True' or 'False'."
|
|
156
|
+
)
|
|
157
|
+
logger.error(message)
|
|
158
|
+
print(message, flush=True)
|
|
159
|
+
raise TypeError(message)
|
|
160
|
+
return param or env or default
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def check_role(token: str, role: str) -> bool:
|
|
164
|
+
"""Return True if the token grants the given role.
|
|
165
|
+
|
|
166
|
+
Keycloak's token introspection endpoint returns roles in two locations:
|
|
167
|
+
- realm_access.roles (realm-level roles)
|
|
168
|
+
- resource_access.<client>.roles (client-level roles)
|
|
169
|
+
|
|
170
|
+
A flat top-level ``roles`` field is also checked for compatibility with
|
|
171
|
+
Keycloak deployments that include a custom protocol mapper.
|
|
172
|
+
|
|
173
|
+
Args:
|
|
174
|
+
token: Raw access token string.
|
|
175
|
+
role: Role name to check.
|
|
176
|
+
"""
|
|
177
|
+
logger.info(f"Checking role '{role}' for token")
|
|
178
|
+
token_info = get_keycloak_openid().introspect(token)
|
|
179
|
+
if not bool(token_info.get("active")):
|
|
180
|
+
logger.debug("Token is inactive")
|
|
181
|
+
return False
|
|
182
|
+
|
|
183
|
+
# Flat roles field (custom protocol mapper or older Keycloak configs)
|
|
184
|
+
if role in token_info.get("roles", []):
|
|
185
|
+
logger.debug(f"Role '{role}' found in flat roles field")
|
|
186
|
+
return True
|
|
187
|
+
|
|
188
|
+
# Realm-level roles
|
|
189
|
+
if role in token_info.get("realm_access", {}).get("roles", []):
|
|
190
|
+
logger.debug(f"Role '{role}' found in realm_access.roles")
|
|
191
|
+
return True
|
|
192
|
+
|
|
193
|
+
# Client-level roles across all resource_access entries
|
|
194
|
+
for client, client_data in token_info.get("resource_access", {}).items():
|
|
195
|
+
if role in client_data.get("roles", []):
|
|
196
|
+
logger.debug(f"Role '{role}' found in resource_access.{client}.roles")
|
|
197
|
+
return True
|
|
198
|
+
|
|
199
|
+
logger.debug(f"Role '{role}' not found in token")
|
|
200
|
+
return False
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def check_token_validity(
|
|
204
|
+
access_token: str, validate_with_auth_server: Optional[bool] = True
|
|
205
|
+
) -> bool:
|
|
206
|
+
"""Return True if the access token is currently valid.
|
|
207
|
+
|
|
208
|
+
Args:
|
|
209
|
+
access_token: The access token to check.
|
|
210
|
+
validate_with_auth_server: When True (default), validates via Keycloak
|
|
211
|
+
introspection. When False, validates the JWT signature locally
|
|
212
|
+
(requires JWKS key configuration).
|
|
213
|
+
"""
|
|
214
|
+
logger.info("Checking token validity")
|
|
215
|
+
keycloak_openid = get_keycloak_openid()
|
|
216
|
+
|
|
217
|
+
valid = False
|
|
218
|
+
if validate_with_auth_server:
|
|
219
|
+
token_info = keycloak_openid.introspect(access_token)
|
|
220
|
+
valid = bool(token_info.get("active"))
|
|
221
|
+
else:
|
|
222
|
+
try:
|
|
223
|
+
get_keycloak_openid().decode_token(access_token, validate=True)
|
|
224
|
+
valid = True
|
|
225
|
+
except Exception as e:
|
|
226
|
+
logger.warning(f"check_token_validity: Token validation failed: {e}")
|
|
227
|
+
logger.debug(f"Token validity: {valid}")
|
|
228
|
+
return valid
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
def check_useraccount_access(
|
|
232
|
+
access_token: str,
|
|
233
|
+
server_url: Optional[str] = None,
|
|
234
|
+
realm_name: Optional[str] = None,
|
|
235
|
+
client_id: Optional[str] = None,
|
|
236
|
+
client_secret: Optional[str] = None,
|
|
237
|
+
verify: Optional[bool] = None,
|
|
238
|
+
) -> Tuple[str, int]:
|
|
239
|
+
"""Return (message, status_code) indicating whether the token has 'openid' scope.
|
|
240
|
+
|
|
241
|
+
Args:
|
|
242
|
+
access_token: The access token to check.
|
|
243
|
+
Kwargs: See get_keycloak_openid for remaining parameters.
|
|
244
|
+
"""
|
|
245
|
+
logger.info("Checking user account access")
|
|
246
|
+
token_info = get_keycloak_openid(
|
|
247
|
+
server_url, realm_name, client_id, client_secret, verify
|
|
248
|
+
).introspect(access_token)
|
|
249
|
+
granted_scope = token_info.get("scope", "").split()
|
|
250
|
+
if "openid" not in granted_scope:
|
|
251
|
+
message = "OpenID scope was not granted"
|
|
252
|
+
logger.warning(message)
|
|
253
|
+
return message, 401
|
|
254
|
+
message = "Access granted"
|
|
255
|
+
logger.info(message)
|
|
256
|
+
return message, 200
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
def login(
|
|
260
|
+
username: str,
|
|
261
|
+
password: str,
|
|
262
|
+
server_url: Optional[str] = None,
|
|
263
|
+
realm_name: Optional[str] = None,
|
|
264
|
+
client_id: Optional[str] = None,
|
|
265
|
+
client_secret: Optional[str] = None,
|
|
266
|
+
verify: Optional[bool] = None,
|
|
267
|
+
) -> Union[str, Tuple[int, str]]:
|
|
268
|
+
"""Authenticate with Keycloak and return a Bearer token string.
|
|
269
|
+
|
|
270
|
+
Returns ``"Bearer <access_token>"`` on success, or ``(status_code, message)``
|
|
271
|
+
on failure.
|
|
272
|
+
|
|
273
|
+
Args:
|
|
274
|
+
username: Keycloak username.
|
|
275
|
+
password: Keycloak password.
|
|
276
|
+
Kwargs: See get_keycloak_openid for remaining parameters.
|
|
277
|
+
"""
|
|
278
|
+
logger.info("Logging in user")
|
|
279
|
+
token = get_keycloak_openid(
|
|
280
|
+
server_url, realm_name, client_id, client_secret, verify
|
|
281
|
+
).token(username=username, password=password)
|
|
282
|
+
if not token.get("access_token") or not token.get("token_type"):
|
|
283
|
+
message = "Token could not be generated. Please contact the admin."
|
|
284
|
+
logger.error(message)
|
|
285
|
+
return 401, message
|
|
286
|
+
token_str = f"{token.get('token_type')} {token.get('access_token')}"
|
|
287
|
+
logger.info("Token generated successfully")
|
|
288
|
+
return token_str
|
|
289
|
+
|
|
290
|
+
|
|
291
|
+
def make_auth_header(
|
|
292
|
+
username: str,
|
|
293
|
+
password: str,
|
|
294
|
+
server_url: Optional[str] = None,
|
|
295
|
+
realm_name: Optional[str] = None,
|
|
296
|
+
client_id: Optional[str] = None,
|
|
297
|
+
client_secret: Optional[str] = None,
|
|
298
|
+
verify: Optional[bool] = None,
|
|
299
|
+
) -> Union[Dict[str, str], Tuple[int, str]]:
|
|
300
|
+
"""Return an ``Authorization`` header dict, or ``(status_code, message)`` on failure.
|
|
301
|
+
|
|
302
|
+
Args:
|
|
303
|
+
username: Keycloak username.
|
|
304
|
+
password: Keycloak password.
|
|
305
|
+
Kwargs: See get_keycloak_openid for remaining parameters.
|
|
306
|
+
"""
|
|
307
|
+
logger.info("Making authentication header")
|
|
308
|
+
credentials = login(
|
|
309
|
+
username,
|
|
310
|
+
password,
|
|
311
|
+
server_url,
|
|
312
|
+
realm_name,
|
|
313
|
+
client_id,
|
|
314
|
+
client_secret,
|
|
315
|
+
verify,
|
|
316
|
+
)
|
|
317
|
+
if isinstance(credentials, str):
|
|
318
|
+
logger.info("Authentication header created successfully")
|
|
319
|
+
return {"Authorization": credentials}
|
|
320
|
+
logger.error("Failed to create authentication header")
|
|
321
|
+
return credentials
|
|
322
|
+
|
|
323
|
+
|
|
324
|
+
def get_userinfo(token: str) -> dict:
|
|
325
|
+
"""Return the userinfo claims from Keycloak for the given access token.
|
|
326
|
+
|
|
327
|
+
Args:
|
|
328
|
+
token: Raw access token string.
|
|
329
|
+
"""
|
|
330
|
+
userinfo = get_keycloak_openid().userinfo(token)
|
|
331
|
+
logger.debug(f"get_userinfo: Retrieved user info {userinfo}")
|
|
332
|
+
return userinfo
|
|
333
|
+
|
|
334
|
+
|
|
335
|
+
def get_current_user() -> str:
|
|
336
|
+
"""Return the Keycloak user ID (``sub``) for the current request token."""
|
|
337
|
+
user_info = get_userinfo()
|
|
338
|
+
if not user_info:
|
|
339
|
+
logger.warning("get_current_user: No user info available")
|
|
340
|
+
return ""
|
|
341
|
+
user_id = user_info.get("sub", "")
|
|
342
|
+
logger.debug(f"get_current_user: Current user ID {user_id}")
|
|
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
|