shieldapi 1.0.0__tar.gz → 1.1.1__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.0.0/shieldapi.egg-info → shieldapi-1.1.1}/PKG-INFO +2 -2
- {shieldapi-1.0.0 → shieldapi-1.1.1}/README.md +1 -1
- {shieldapi-1.0.0 → shieldapi-1.1.1}/setup.cfg +2 -1
- {shieldapi-1.0.0 → shieldapi-1.1.1}/shieldapi/frameworks/flask.py +41 -10
- {shieldapi-1.0.0 → shieldapi-1.1.1}/shieldapi/keycloak_utils.py +109 -98
- {shieldapi-1.0.0 → shieldapi-1.1.1/shieldapi.egg-info}/PKG-INFO +2 -2
- {shieldapi-1.0.0 → shieldapi-1.1.1}/shieldapi.egg-info/SOURCES.txt +1 -0
- {shieldapi-1.0.0 → shieldapi-1.1.1}/shieldapi.egg-info/requires.txt +1 -0
- shieldapi-1.1.1/tests/conftest.py +17 -0
- {shieldapi-1.0.0 → shieldapi-1.1.1}/tests/mock.py +1 -1
- {shieldapi-1.0.0 → shieldapi-1.1.1}/tests/test_flask.py +1 -1
- {shieldapi-1.0.0 → shieldapi-1.1.1}/tests/test_keycloak_utils.py +8 -13
- {shieldapi-1.0.0 → shieldapi-1.1.1}/LICENSE +0 -0
- {shieldapi-1.0.0 → shieldapi-1.1.1}/pyproject.toml +0 -0
- {shieldapi-1.0.0 → shieldapi-1.1.1}/setup.py +0 -0
- {shieldapi-1.0.0 → shieldapi-1.1.1}/shieldapi/__init__.py +0 -0
- {shieldapi-1.0.0 → shieldapi-1.1.1}/shieldapi/frameworks/__init__.py +0 -0
- {shieldapi-1.0.0 → shieldapi-1.1.1}/shieldapi/frameworks/fastapi.py +0 -0
- {shieldapi-1.0.0 → shieldapi-1.1.1}/shieldapi.egg-info/dependency_links.txt +0 -0
- {shieldapi-1.0.0 → shieldapi-1.1.1}/shieldapi.egg-info/top_level.txt +0 -0
- {shieldapi-1.0.0 → shieldapi-1.1.1}/tests/__init__.py +0 -0
- {shieldapi-1.0.0 → shieldapi-1.1.1}/tests/test_fastapi.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.1
|
|
2
2
|
Name: shieldapi
|
|
3
|
-
Version: 1.
|
|
3
|
+
Version: 1.1.1
|
|
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
|
|
@@ -63,7 +63,7 @@ In order to successfully enable the callback for the token-generation and token-
|
|
|
63
63
|
| `KEYCLOAK_HOST` | Hostname of the the Keycloak instance | "http://localhost:8080" |
|
|
64
64
|
| `KEYCLOAK_REALM_NAME` | Realm name you set under step 2 in the previous chapter | "my_realm" |
|
|
65
65
|
| `KEYCLOAK_CLIENT_ID` | Client ID you created under step 3. | "shieldapi" |
|
|
66
|
-
| `
|
|
66
|
+
| `KEYCLOAK_CLIENT_SECRET` | Client secret you created under step 3 (`access_type` should be set to "confidential"). | "1169a83e-a237-40ad-90db-8b8d4848de09" |
|
|
67
67
|
| `KEYCLOAK_VERIFY_HOST` | Controls whether SSL certificates are verified for HTTPS requests. Default is set to `False`. | "True" |
|
|
68
68
|
| `KEYCLOAK_REALM_ADMIN_USER` | User name of the realm admin, if any action shall be performed as admin in your Flask/FastAPI application. | "admin" |
|
|
69
69
|
| `KEYCLOAK_REALM_ADMIN_PASSWORD` | Password of the realm admin, if any action shall be performed as admin in your Flask/FastAPI application. | "admin_password" |
|
|
@@ -48,7 +48,7 @@ In order to successfully enable the callback for the token-generation and token-
|
|
|
48
48
|
| `KEYCLOAK_HOST` | Hostname of the the Keycloak instance | "http://localhost:8080" |
|
|
49
49
|
| `KEYCLOAK_REALM_NAME` | Realm name you set under step 2 in the previous chapter | "my_realm" |
|
|
50
50
|
| `KEYCLOAK_CLIENT_ID` | Client ID you created under step 3. | "shieldapi" |
|
|
51
|
-
| `
|
|
51
|
+
| `KEYCLOAK_CLIENT_SECRET` | Client secret you created under step 3 (`access_type` should be set to "confidential"). | "1169a83e-a237-40ad-90db-8b8d4848de09" |
|
|
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" |
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
[metadata]
|
|
2
2
|
name = shieldapi
|
|
3
|
-
version = v1.
|
|
3
|
+
version = v1.1.1
|
|
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
|
|
@@ -29,6 +29,7 @@ tests =
|
|
|
29
29
|
requests-mock>=1.10.0,<2.0
|
|
30
30
|
httpx>=0.23.3,<1.0
|
|
31
31
|
semver>=2.13.0,<3.0
|
|
32
|
+
pytest-mock>=3.10.0
|
|
32
33
|
|
|
33
34
|
[bumpver]
|
|
34
35
|
current_version = "v0.0.0"
|
|
@@ -4,7 +4,11 @@ from typing import Callable, List
|
|
|
4
4
|
|
|
5
5
|
from flask import abort, request
|
|
6
6
|
|
|
7
|
-
from shieldapi.keycloak_utils import
|
|
7
|
+
from shieldapi.keycloak_utils import (
|
|
8
|
+
check_role,
|
|
9
|
+
check_token_validity,
|
|
10
|
+
get_keycloak_openid,
|
|
11
|
+
)
|
|
8
12
|
|
|
9
13
|
|
|
10
14
|
def get_access_token():
|
|
@@ -65,9 +69,9 @@ def login_required(fn: Callable) -> Callable:
|
|
|
65
69
|
if not access_token:
|
|
66
70
|
abort(401)
|
|
67
71
|
|
|
68
|
-
|
|
72
|
+
valid = check_token_validity(access_token)
|
|
69
73
|
|
|
70
|
-
if not
|
|
74
|
+
if not valid:
|
|
71
75
|
abort(401)
|
|
72
76
|
|
|
73
77
|
return fn(*args, **kwargs)
|
|
@@ -94,12 +98,7 @@ def admin_required(fn: Callable) -> Callable:
|
|
|
94
98
|
if not access_token:
|
|
95
99
|
abort(401)
|
|
96
100
|
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
if not token_info["active"]:
|
|
100
|
-
abort(401)
|
|
101
|
-
|
|
102
|
-
if not ("roles" in token_info and "admin" in token_info["roles"]):
|
|
101
|
+
if not check_role(access_token, "admin"):
|
|
103
102
|
abort(403)
|
|
104
103
|
|
|
105
104
|
return fn(*args, **kwargs)
|
|
@@ -107,9 +106,41 @@ def admin_required(fn: Callable) -> Callable:
|
|
|
107
106
|
return decorated_view
|
|
108
107
|
|
|
109
108
|
|
|
109
|
+
def role_required(role: str) -> Callable:
|
|
110
|
+
"""
|
|
111
|
+
Decorator that limits access to users with a certain role.
|
|
112
|
+
|
|
113
|
+
Args:
|
|
114
|
+
role (str):
|
|
115
|
+
The required role.
|
|
116
|
+
|
|
117
|
+
Returns:
|
|
118
|
+
Callable:
|
|
119
|
+
The decorator function.
|
|
120
|
+
"""
|
|
121
|
+
|
|
122
|
+
def decorator(f: Callable) -> Callable:
|
|
123
|
+
@wraps(f)
|
|
124
|
+
def restricted_function(*args, **kwargs):
|
|
125
|
+
access_token = get_access_token()
|
|
126
|
+
if not access_token:
|
|
127
|
+
abort(401)
|
|
128
|
+
|
|
129
|
+
if not check_role(access_token, role):
|
|
130
|
+
abort(403)
|
|
131
|
+
|
|
132
|
+
res = f(*args, **kwargs)
|
|
133
|
+
|
|
134
|
+
return res
|
|
135
|
+
|
|
136
|
+
return restricted_function
|
|
137
|
+
|
|
138
|
+
return decorator
|
|
139
|
+
|
|
140
|
+
|
|
110
141
|
def has_scope(scope_list: List[str]) -> Callable:
|
|
111
142
|
"""
|
|
112
|
-
|
|
143
|
+
Decorator that limits access to the applications which have been
|
|
113
144
|
granted the required scopes.
|
|
114
145
|
|
|
115
146
|
Args:
|
|
@@ -12,7 +12,7 @@ def get_keycloak_openid(
|
|
|
12
12
|
server_url: Optional[str] = None,
|
|
13
13
|
realm_name: Optional[str] = None,
|
|
14
14
|
client_id: Optional[str] = None,
|
|
15
|
-
|
|
15
|
+
client_secret: Optional[str] = None,
|
|
16
16
|
verify: Optional[bool] = None,
|
|
17
17
|
) -> KeycloakOpenID:
|
|
18
18
|
"""
|
|
@@ -20,17 +20,13 @@ def get_keycloak_openid(
|
|
|
20
20
|
|
|
21
21
|
Kwargs:
|
|
22
22
|
server_url (Optional[str]):
|
|
23
|
-
The URL of the Keycloak server. If
|
|
24
|
-
KEYCLOAK_HOST will be used.
|
|
23
|
+
The URL of the Keycloak server. If missing, $KEYCLOAK_HOST or 'http://keycloak:8080/auth/' will be used.
|
|
25
24
|
realm_name (Optional[str]):
|
|
26
|
-
The name of the realm in Keycloak. If
|
|
27
|
-
KEYCLOAK_REALM_NAME will be used.
|
|
25
|
+
The name of the realm in Keycloak. If missing, $KEYCLOAK_REALM_NAME will be used.
|
|
28
26
|
client_id (Optional[str]):
|
|
29
|
-
The id of the client in Keycloak. If
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
The client secret key for the client in Keycloak. If not provided, the value from the environment
|
|
33
|
-
variable KEYCLOAK_CLIENT_SECRET_KEY will be used.
|
|
27
|
+
The id of the client in Keycloak. If missing, $KEYCLOAK_CLIENT_ID or 'shieldapi' will be used.
|
|
28
|
+
client_secret (Optional[str]):
|
|
29
|
+
The client secret key for the client in Keycloak. If missing, $KEYCLOAK_CLIENT_SECRET will be used.
|
|
34
30
|
verify (Optional[bool]):
|
|
35
31
|
Controls whether SSL certificates are verified for HTTPS requests. If set to False, SSL
|
|
36
32
|
verification is disabled. If set to a string, it should be the path to a CA_BUNDLE file or
|
|
@@ -40,15 +36,17 @@ def get_keycloak_openid(
|
|
|
40
36
|
KeycloakOpenID: An object for communicating with Keycloak via OpenID Connect.
|
|
41
37
|
|
|
42
38
|
Raises:
|
|
43
|
-
KeyError: If any required
|
|
39
|
+
KeyError: If any required values are missing.
|
|
44
40
|
"""
|
|
45
41
|
|
|
46
42
|
return KeycloakOpenID(
|
|
47
|
-
server_url=_get_value(
|
|
43
|
+
server_url=_get_value(
|
|
44
|
+
server_url, "KEYCLOAK_HOST", "http://keycloak:8080/auth/"
|
|
45
|
+
),
|
|
48
46
|
realm_name=_get_value(realm_name, "KEYCLOAK_REALM_NAME"),
|
|
49
|
-
client_id=_get_value(client_id, "KEYCLOAK_CLIENT_ID"),
|
|
50
|
-
client_secret_key=_get_value(
|
|
51
|
-
verify=
|
|
47
|
+
client_id=_get_value(client_id, "KEYCLOAK_CLIENT_ID", "shieldapi"),
|
|
48
|
+
client_secret_key=_get_value(client_secret, "KEYCLOAK_CLIENT_SECRET"),
|
|
49
|
+
verify=_get_value(verify, "KEYCLOAK_VERIFY_HOST", True, True),
|
|
52
50
|
)
|
|
53
51
|
|
|
54
52
|
|
|
@@ -63,17 +61,13 @@ def get_keycloak_admin(
|
|
|
63
61
|
|
|
64
62
|
Kwargs:
|
|
65
63
|
server_url (Optional[str]):
|
|
66
|
-
The URL of the Keycloak server. If
|
|
67
|
-
KEYCLOAK_HOST will be used.
|
|
64
|
+
The URL of the Keycloak server. If missing, $KEYCLOAK_HOST or 'http://keycloak:8080/auth/' will be used.
|
|
68
65
|
username (Optional[str]):
|
|
69
|
-
The username to log in with. If
|
|
70
|
-
KEYCLOAK_REALM_ADMIN_USER will be used.
|
|
66
|
+
The username to log in with. If missing, $KEYCLOAK_REALM_ADMIN_USER will be used.
|
|
71
67
|
password (Optional[str]):
|
|
72
|
-
The password to log in with. If
|
|
73
|
-
KEYCLOAK_REALM_ADMIN_PASSWORD will be used.
|
|
68
|
+
The password to log in with. If missing, $KEYCLOAK_REALM_ADMIN_PASSWORD will be used.
|
|
74
69
|
realm_name (Optional[str]):
|
|
75
|
-
The name of the realm in Keycloak. If
|
|
76
|
-
KEYCLOAK_REALM_NAME will be used.
|
|
70
|
+
The name of the realm in Keycloak. If missing, $KEYCLOAK_REALM_NAME will be used.
|
|
77
71
|
verify (Optional[bool]):
|
|
78
72
|
Controls whether SSL certificates are verified for HTTPS requests. If set to False, SSL
|
|
79
73
|
verification is disabled. If set to a string, it should be the path to a CA_BUNDLE file or
|
|
@@ -85,89 +79,90 @@ def get_keycloak_admin(
|
|
|
85
79
|
|
|
86
80
|
Raises:
|
|
87
81
|
KeyError:
|
|
88
|
-
If any required
|
|
82
|
+
If any required values are missing.
|
|
89
83
|
"""
|
|
90
84
|
return KeycloakAdmin(
|
|
91
|
-
server_url=_get_value(
|
|
85
|
+
server_url=_get_value(
|
|
86
|
+
server_url, "KEYCLOAK_HOST", "http://keycloak:8080/auth/"
|
|
87
|
+
),
|
|
92
88
|
username=_get_value(username, "KEYCLOAK_REALM_ADMIN_USER"),
|
|
93
89
|
password=_get_value(password, "KEYCLOAK_REALM_ADMIN_PASSWORD"),
|
|
94
90
|
realm_name=_get_value(realm_name, "KEYCLOAK_REALM_NAME"),
|
|
95
|
-
verify=
|
|
91
|
+
verify=_get_value(verify, "KEYCLOAK_VERIFY_HOST", True, True),
|
|
96
92
|
)
|
|
97
93
|
|
|
98
94
|
|
|
99
|
-
def _get_value(
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
95
|
+
def _get_value(
|
|
96
|
+
param: Any,
|
|
97
|
+
env_var: str,
|
|
98
|
+
default: Optional[Any] = None,
|
|
99
|
+
boolean: Optional[bool] = False,
|
|
100
|
+
) -> Any:
|
|
101
|
+
"""Get a value by following the assignment priority.
|
|
102
|
+
|
|
103
|
+
Parameters take priority over environment variables and defaults.
|
|
104
|
+
An error is raised if no values are defined.
|
|
106
105
|
|
|
107
106
|
Args:
|
|
108
107
|
var (Any):
|
|
109
|
-
|
|
108
|
+
parameter passed to the respective upstream function.
|
|
110
109
|
env_var (str):
|
|
111
110
|
Name of the corresponding environmental variable.
|
|
111
|
+
default (Optional[Any]):
|
|
112
|
+
Default value when no others are provided
|
|
113
|
+
boolean (Optional[bool]):
|
|
114
|
+
Whether the expected values is a boolean
|
|
112
115
|
Returns:
|
|
113
116
|
Any: The value of the Python-object (preferred) or its respective env-variable.
|
|
114
117
|
The latter can also resolve into a `None`, if not set.
|
|
115
118
|
|
|
116
119
|
Raises:
|
|
117
|
-
UserWarning: If both
|
|
118
|
-
|
|
119
|
-
ValueError: If both variables are `None` or if the Python-object is `False`
|
|
120
|
-
and env-variable not `None`.
|
|
120
|
+
UserWarning: If both the parameter and env-variable are set.
|
|
121
|
+
ValueError: If both the parameter and env-variable are None, or a boolean
|
|
121
122
|
"""
|
|
122
123
|
env = os.environ.get(env_var)
|
|
123
|
-
|
|
124
|
-
|
|
124
|
+
|
|
125
|
+
if (param or isinstance(param, bool)) and env:
|
|
126
|
+
message = f"""Both the kwarg ({param}) and the env-variable for '{env_var}' ({env}) are assigned.
|
|
125
127
|
Note that the argument takes precedence over the env-variable."""
|
|
126
128
|
warnings.warn(UserWarning(message))
|
|
127
|
-
elif
|
|
128
|
-
message = f"""Both the kwarg and the env-variable for
|
|
129
|
-
The kwarg is of type `bool` and valued `{var}` whereas the env-variable is set
|
|
130
|
-
to `{env}`. Note that the argument takes precedence over the env-variable."""
|
|
131
|
-
warnings.warn(UserWarning(message))
|
|
132
|
-
elif var is None and env is None:
|
|
133
|
-
message = f"""Both the kwarg and the env-variable for `{env_var}` are `None`.
|
|
129
|
+
elif param is None and env is None and default is None:
|
|
130
|
+
message = f"""Both the kwarg and the env-variable for '{env_var}' are None.
|
|
134
131
|
Please assign one of them to a value."""
|
|
135
132
|
raise ValueError(message)
|
|
136
|
-
if isinstance(var, bool):
|
|
137
|
-
return var
|
|
138
|
-
else:
|
|
139
|
-
return var or env
|
|
140
133
|
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
134
|
+
if isinstance(param, bool):
|
|
135
|
+
return param
|
|
136
|
+
else:
|
|
137
|
+
if boolean and env:
|
|
138
|
+
try:
|
|
139
|
+
env = literal_eval(env)
|
|
140
|
+
if not isinstance(env, bool):
|
|
141
|
+
raise ValueError
|
|
142
|
+
except (ValueError, SyntaxError):
|
|
143
|
+
message = (
|
|
144
|
+
f"The '{env_var}' env-var valued '{env}' must be 'True' or 'False'."
|
|
145
|
+
)
|
|
146
|
+
print(message, flush=True)
|
|
147
|
+
raise TypeError(message)
|
|
148
|
+
return param or env or default
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def check_role(token: str, role: str) -> bool:
|
|
152
|
+
"""Check if a token contains a certain role
|
|
145
153
|
|
|
146
154
|
Args:
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
Name of the corresponding environmental variable.
|
|
155
|
+
token (str): token from a user
|
|
156
|
+
role (str): role to be checked
|
|
157
|
+
|
|
151
158
|
Returns:
|
|
152
|
-
|
|
153
|
-
The evaluated value of the environment variable as a boolean, or None
|
|
154
|
-
if the environment variable does not exist.
|
|
155
|
-
Raises:
|
|
156
|
-
TypeError: If the value of the environmental variable cannot be evaluated or it
|
|
157
|
-
can be evaluated but is not an instance of <bool>.
|
|
159
|
+
bool: whether the token contains the role
|
|
158
160
|
"""
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
return value
|
|
165
|
-
except (ValueError, AssertionError, SyntaxError):
|
|
166
|
-
message = f"""Env-variable `{env_var}` valued `{boolean}` is not a boolean.
|
|
167
|
-
Must be valued `True` or `False`."""
|
|
168
|
-
raise TypeError(message)
|
|
169
|
-
elif isinstance(boolean, bool):
|
|
170
|
-
return boolean
|
|
161
|
+
token_info = get_keycloak_openid().introspect(token)
|
|
162
|
+
valid_token = _check_active_token(token_info)
|
|
163
|
+
if valid_token:
|
|
164
|
+
return "roles" in token_info and role in token_info["roles"]
|
|
165
|
+
return False
|
|
171
166
|
|
|
172
167
|
|
|
173
168
|
def check_token_validity(
|
|
@@ -175,9 +170,9 @@ def check_token_validity(
|
|
|
175
170
|
server_url: Optional[str] = None,
|
|
176
171
|
realm_name: Optional[str] = None,
|
|
177
172
|
client_id: Optional[str] = None,
|
|
178
|
-
|
|
173
|
+
client_secret: Optional[str] = None,
|
|
179
174
|
verify: Optional[bool] = None,
|
|
180
|
-
) ->
|
|
175
|
+
) -> bool:
|
|
181
176
|
"""Check if the given access token is valid.
|
|
182
177
|
|
|
183
178
|
Args:
|
|
@@ -193,24 +188,34 @@ def check_token_validity(
|
|
|
193
188
|
client_id (Optional[str]):
|
|
194
189
|
The id of the client in Keycloak. If not provided, the value from the environment
|
|
195
190
|
variable KEYCLOAK_CLIENT_ID will be used.
|
|
196
|
-
|
|
191
|
+
client_secret (Optional[str]):
|
|
197
192
|
The client secret key for the client in Keycloak. If not provided, the value from the environment
|
|
198
|
-
variable
|
|
193
|
+
variable KEYCLOAK_CLIENT_SECRET will be used.
|
|
199
194
|
verify (Optional[bool]):
|
|
200
195
|
Controls whether SSL certificates are verified for HTTPS requests. If set to False, SSL
|
|
201
196
|
verification is disabled. If set to a string, it should be the path to a CA_BUNDLE file or
|
|
202
197
|
a directory containing certificates of trusted CA.
|
|
203
198
|
|
|
204
199
|
Returns:
|
|
205
|
-
|
|
200
|
+
bool: Whether the token is valid.
|
|
206
201
|
"""
|
|
207
202
|
token_info = get_keycloak_openid(
|
|
208
|
-
server_url, realm_name, client_id,
|
|
203
|
+
server_url, realm_name, client_id, client_secret, verify
|
|
209
204
|
).introspect(access_token)
|
|
210
205
|
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
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
|
|
211
|
+
|
|
212
|
+
Args:
|
|
213
|
+
token_info (Any): output from the introspect request
|
|
214
|
+
|
|
215
|
+
Returns:
|
|
216
|
+
bool: Whether the token is valid
|
|
217
|
+
"""
|
|
218
|
+
return bool(token_info["active"])
|
|
214
219
|
|
|
215
220
|
|
|
216
221
|
def check_useraccount_access(
|
|
@@ -218,7 +223,7 @@ def check_useraccount_access(
|
|
|
218
223
|
server_url: Optional[str] = None,
|
|
219
224
|
realm_name: Optional[str] = None,
|
|
220
225
|
client_id: Optional[str] = None,
|
|
221
|
-
|
|
226
|
+
client_secret: Optional[str] = None,
|
|
222
227
|
verify: Optional[bool] = None,
|
|
223
228
|
) -> str:
|
|
224
229
|
"""
|
|
@@ -237,9 +242,9 @@ def check_useraccount_access(
|
|
|
237
242
|
client_id (Optional[str]):
|
|
238
243
|
The id of the client in Keycloak. If not provided, the value from the environment
|
|
239
244
|
variable KEYCLOAK_CLIENT_ID will be used.
|
|
240
|
-
|
|
245
|
+
client_secret (Optional[str]):
|
|
241
246
|
The client secret key for the client in Keycloak. If not provided, the value from the environment
|
|
242
|
-
variable
|
|
247
|
+
variable KEYCLOAK_CLIENT_SECRET will be used.
|
|
243
248
|
verify (Optional[bool]):
|
|
244
249
|
Controls whether SSL certificates are verified for HTTPS requests. If set to False, SSL
|
|
245
250
|
verification is disabled. If set to a string, it should be the path to a CA_BUNDLE file or
|
|
@@ -249,7 +254,7 @@ def check_useraccount_access(
|
|
|
249
254
|
str: A string indicating whether or not the access token has the 'openid' scope.
|
|
250
255
|
"""
|
|
251
256
|
token_info = get_keycloak_openid(
|
|
252
|
-
server_url, realm_name, client_id,
|
|
257
|
+
server_url, realm_name, client_id, client_secret, verify
|
|
253
258
|
).introspect(access_token)
|
|
254
259
|
granted_scope = token_info.json()["scope"].split()
|
|
255
260
|
if "openid" not in granted_scope:
|
|
@@ -263,7 +268,7 @@ def login(
|
|
|
263
268
|
server_url: Optional[str] = None,
|
|
264
269
|
realm_name: Optional[str] = None,
|
|
265
270
|
client_id: Optional[str] = None,
|
|
266
|
-
|
|
271
|
+
client_secret: Optional[str] = None,
|
|
267
272
|
verify: Optional[bool] = None,
|
|
268
273
|
) -> str:
|
|
269
274
|
"""
|
|
@@ -284,9 +289,9 @@ def login(
|
|
|
284
289
|
client_id (Optional[str]):
|
|
285
290
|
The id of the client in Keycloak. If not provided, the value from the environment
|
|
286
291
|
variable KEYCLOAK_CLIENT_ID will be used.
|
|
287
|
-
|
|
292
|
+
client_secret (Optional[str]):
|
|
288
293
|
The client secret key for the client in Keycloak. If not provided, the value from the environment
|
|
289
|
-
variable
|
|
294
|
+
variable KEYCLOAK_CLIENT_SECRET will be used.
|
|
290
295
|
verify (Optional[Union[bool, str]]):
|
|
291
296
|
Controls whether SSL certificates are verified for HTTPS requests. If set to False, SSL
|
|
292
297
|
verification is disabled. If set to a string, it should be the path to a CA_BUNDLE file or
|
|
@@ -298,7 +303,7 @@ def login(
|
|
|
298
303
|
a tuple containing the status code and an error message.
|
|
299
304
|
"""
|
|
300
305
|
token = get_keycloak_openid(
|
|
301
|
-
server_url, realm_name, client_id,
|
|
306
|
+
server_url, realm_name, client_id, client_secret, verify
|
|
302
307
|
).token(username=username, password=password)
|
|
303
308
|
if not token.get("access_token") and token.get("token_type"):
|
|
304
309
|
return 401, "Token could not be generated. Please contact the admin."
|
|
@@ -312,7 +317,7 @@ def make_auth_header(
|
|
|
312
317
|
server_url: Optional[str] = None,
|
|
313
318
|
realm_name: Optional[str] = None,
|
|
314
319
|
client_id: Optional[str] = None,
|
|
315
|
-
|
|
320
|
+
client_secret: Optional[str] = None,
|
|
316
321
|
verify: Optional[bool] = None,
|
|
317
322
|
) -> Union[int, Tuple[int, str]]:
|
|
318
323
|
"""
|
|
@@ -333,9 +338,9 @@ def make_auth_header(
|
|
|
333
338
|
client_id (Optional[str]):
|
|
334
339
|
The id of the client in Keycloak. If not provided, the value from the environment
|
|
335
340
|
variable KEYCLOAK_CLIENT_ID will be used.
|
|
336
|
-
|
|
341
|
+
client_secret (Optional[str]):
|
|
337
342
|
The client secret key for the client in Keycloak. If not provided, the value from the environment
|
|
338
|
-
variable
|
|
343
|
+
variable KEYCLOAK_CLIENT_SECRET will be used.
|
|
339
344
|
verify (Optional[bool]):
|
|
340
345
|
Controls whether SSL certificates are verified for HTTPS requests. If set to False, SSL
|
|
341
346
|
verification is disabled. If set to a string, it should be the path to a CA_BUNDLE file or
|
|
@@ -348,7 +353,13 @@ def make_auth_header(
|
|
|
348
353
|
|
|
349
354
|
"""
|
|
350
355
|
credentials = login(
|
|
351
|
-
username,
|
|
356
|
+
username,
|
|
357
|
+
password,
|
|
358
|
+
server_url,
|
|
359
|
+
realm_name,
|
|
360
|
+
client_id,
|
|
361
|
+
client_secret,
|
|
362
|
+
verify,
|
|
352
363
|
)
|
|
353
364
|
if type(credentials) == str:
|
|
354
365
|
return {"Authorization": credentials}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.1
|
|
2
2
|
Name: shieldapi
|
|
3
|
-
Version: 1.
|
|
3
|
+
Version: 1.1.1
|
|
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
|
|
@@ -63,7 +63,7 @@ In order to successfully enable the callback for the token-generation and token-
|
|
|
63
63
|
| `KEYCLOAK_HOST` | Hostname of the the Keycloak instance | "http://localhost:8080" |
|
|
64
64
|
| `KEYCLOAK_REALM_NAME` | Realm name you set under step 2 in the previous chapter | "my_realm" |
|
|
65
65
|
| `KEYCLOAK_CLIENT_ID` | Client ID you created under step 3. | "shieldapi" |
|
|
66
|
-
| `
|
|
66
|
+
| `KEYCLOAK_CLIENT_SECRET` | Client secret you created under step 3 (`access_type` should be set to "confidential"). | "1169a83e-a237-40ad-90db-8b8d4848de09" |
|
|
67
67
|
| `KEYCLOAK_VERIFY_HOST` | Controls whether SSL certificates are verified for HTTPS requests. Default is set to `False`. | "True" |
|
|
68
68
|
| `KEYCLOAK_REALM_ADMIN_USER` | User name of the realm admin, if any action shall be performed as admin in your Flask/FastAPI application. | "admin" |
|
|
69
69
|
| `KEYCLOAK_REALM_ADMIN_PASSWORD` | Password of the realm admin, if any action shall be performed as admin in your Flask/FastAPI application. | "admin_password" |
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import pytest
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
def _mock_active_token(token_info: dict) -> bool:
|
|
5
|
+
"""Make a mock for checking if token is active."""
|
|
6
|
+
return bool(token_info["active"])
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
@pytest.fixture(scope="function")
|
|
10
|
+
def mock_introspect(mocker):
|
|
11
|
+
"""Make a mock for checking if token is active."""
|
|
12
|
+
import shieldapi.keycloak_utils as utils
|
|
13
|
+
|
|
14
|
+
mocker_intro = mocker.MagicMock()
|
|
15
|
+
with mocker.patch.object(utils, "_check_active_token", mocker_intro):
|
|
16
|
+
mocker_intro.side_effect = _mock_active_token
|
|
17
|
+
yield mocker_intro
|
|
@@ -9,7 +9,7 @@ VARIABLES = dict(
|
|
|
9
9
|
KEYCLOAK_HOST="http://example_keycloak.org/auth/",
|
|
10
10
|
KEYCLOAK_REALM_NAME="my_realm",
|
|
11
11
|
KEYCLOAK_CLIENT_ID="testshield",
|
|
12
|
-
|
|
12
|
+
KEYCLOAK_CLIENT_SECRET="123a",
|
|
13
13
|
KEYCLOAK_REALM_ADMIN_USER="admin",
|
|
14
14
|
KEYCLOAK_REALM_ADMIN_PASSWORD="passwd",
|
|
15
15
|
KEYCLOAK_VERIFY_HOST="True",
|
|
@@ -54,11 +54,11 @@ def test__get_value_bool(var, env_var, requests_mock):
|
|
|
54
54
|
else:
|
|
55
55
|
os.environ.pop(key)
|
|
56
56
|
if var is None and env_var is None:
|
|
57
|
-
match = f"Both the kwarg and the env-variable for
|
|
57
|
+
match = f"Both the kwarg and the env-variable for '{key}' are None."
|
|
58
58
|
with pytest.raises(ValueError, match=match):
|
|
59
59
|
no_warning_raised(_get_value, args=(var, key), expected=var)
|
|
60
60
|
elif isinstance(var, bool) and env_var or (var and env_var):
|
|
61
|
-
match = f"Both the kwarg and the env-variable for
|
|
61
|
+
match = f"Both the kwarg ({var}) and the env-variable for '{key}' ({env_var}) are assigned."
|
|
62
62
|
warning_raised(_get_value, match, args=(var, key), expected=var)
|
|
63
63
|
|
|
64
64
|
|
|
@@ -66,7 +66,7 @@ def test__get_value_bool(var, env_var, requests_mock):
|
|
|
66
66
|
def test_keycloak_warning(func, requests_mock):
|
|
67
67
|
"""Pytest for `get_keycloak_openid` and `get_keycloak_admin` with
|
|
68
68
|
both not None-typed values."""
|
|
69
|
-
match = "Both the kwarg and the env-variable for
|
|
69
|
+
match = f"Both the kwarg (http://example_keycloak.org/auth/) and the env-variable for 'KEYCLOAK_HOST'"
|
|
70
70
|
register_mock(requests_mock)
|
|
71
71
|
warning_raised(
|
|
72
72
|
func, match, kwargs={"server_url": "http://example_keycloak.org/auth/"}
|
|
@@ -78,7 +78,7 @@ def test_keycloak_valueerror(func, requests_mock):
|
|
|
78
78
|
"""Pytest for `get_keycloak_openid` and `get_keycloak_admin` with
|
|
79
79
|
both None-typed values."""
|
|
80
80
|
register_mock(requests_mock)
|
|
81
|
-
match = "Both the kwarg and the env-variable for
|
|
81
|
+
match = "Both the kwarg and the env-variable for 'KEYCLOAK_REALM_NAME'"
|
|
82
82
|
os.environ.pop("KEYCLOAK_REALM_NAME")
|
|
83
83
|
with pytest.raises(ValueError, match=match):
|
|
84
84
|
no_warning_raised(func)
|
|
@@ -94,12 +94,13 @@ def test_keycloak_typeerror_bool(var, test_input, func, requests_mock):
|
|
|
94
94
|
`KEYCLOAK_VERIFY_HOST`."""
|
|
95
95
|
register_mock(requests_mock)
|
|
96
96
|
os.environ["KEYCLOAK_VERIFY_HOST"] = test_input
|
|
97
|
-
match = "
|
|
97
|
+
match = f"The 'KEYCLOAK_VERIFY_HOST' env-var valued"
|
|
98
98
|
if not isinstance(var, bool):
|
|
99
99
|
with pytest.raises(TypeError, match=match):
|
|
100
|
+
print(match, flush=True)
|
|
100
101
|
no_warning_raised(func)
|
|
101
102
|
else:
|
|
102
|
-
match = "Both the kwarg and the env-variable for
|
|
103
|
+
match = f"Both the kwarg ({var}) and the env-variable for 'KEYCLOAK_VERIFY_HOST' ({test_input}) are assigned."
|
|
103
104
|
warning_raised(func, match, kwargs={"verify": var})
|
|
104
105
|
|
|
105
106
|
|
|
@@ -116,13 +117,7 @@ def test_keycloak_warning_bool(var, env_var, func, requests_mock):
|
|
|
116
117
|
os.environ.pop("KEYCLOAK_VERIFY_HOST")
|
|
117
118
|
|
|
118
119
|
if isinstance(var, bool) and env_var:
|
|
119
|
-
match = "Both the kwarg and the env-variable for
|
|
120
|
+
match = f"Both the kwarg ({var}) and the env-variable for 'KEYCLOAK_VERIFY_HOST' ({env_var}) are assigned."
|
|
120
121
|
warning_raised(func, match, kwargs={"verify": var})
|
|
121
|
-
elif var is None and env_var is None:
|
|
122
|
-
match = (
|
|
123
|
-
"Both the kwarg and the env-variable for `KEYCLOAK_VERIFY_HOST` are `None`."
|
|
124
|
-
)
|
|
125
|
-
with pytest.raises(ValueError, match=match):
|
|
126
|
-
no_warning_raised(func, kwargs={"verify": var})
|
|
127
122
|
else:
|
|
128
123
|
no_warning_raised(func, kwargs={"verify": var})
|
|
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
|