shieldapi 2.0.0rc5__tar.gz → 2.2.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.
Files changed (27) hide show
  1. {shieldapi-2.0.0rc5 → shieldapi-2.2.0}/PKG-INFO +20 -12
  2. shieldapi-2.0.0rc5/shieldapi.egg-info/PKG-INFO → shieldapi-2.2.0/README.md +6 -27
  3. {shieldapi-2.0.0rc5 → shieldapi-2.2.0}/setup.cfg +13 -11
  4. shieldapi-2.2.0/shieldapi/__init__.py +49 -0
  5. {shieldapi-2.0.0rc5 → shieldapi-2.2.0}/shieldapi/frameworks/fastapi.py +2 -2
  6. {shieldapi-2.0.0rc5 → shieldapi-2.2.0}/shieldapi/frameworks/flask.py +29 -61
  7. shieldapi-2.2.0/shieldapi/keycloak_utils.py +343 -0
  8. shieldapi-2.0.0rc5/README.md → shieldapi-2.2.0/shieldapi.egg-info/PKG-INFO +35 -1
  9. shieldapi-2.2.0/shieldapi.egg-info/requires.txt +19 -0
  10. shieldapi-2.2.0/tests/mock.py +112 -0
  11. {shieldapi-2.0.0rc5 → shieldapi-2.2.0}/tests/test_fastapi.py +1 -1
  12. shieldapi-2.2.0/tests/test_flask.py +224 -0
  13. {shieldapi-2.0.0rc5 → shieldapi-2.2.0}/tests/test_keycloak_utils.py +0 -1
  14. shieldapi-2.0.0rc5/shieldapi/__init__.py +0 -29
  15. shieldapi-2.0.0rc5/shieldapi/keycloak_utils.py +0 -423
  16. shieldapi-2.0.0rc5/shieldapi.egg-info/requires.txt +0 -15
  17. shieldapi-2.0.0rc5/tests/mock.py +0 -69
  18. shieldapi-2.0.0rc5/tests/test_flask.py +0 -27
  19. {shieldapi-2.0.0rc5 → shieldapi-2.2.0}/LICENSE +0 -0
  20. {shieldapi-2.0.0rc5 → shieldapi-2.2.0}/pyproject.toml +0 -0
  21. {shieldapi-2.0.0rc5 → shieldapi-2.2.0}/setup.py +0 -0
  22. {shieldapi-2.0.0rc5 → shieldapi-2.2.0}/shieldapi/frameworks/__init__.py +0 -0
  23. {shieldapi-2.0.0rc5 → shieldapi-2.2.0}/shieldapi.egg-info/SOURCES.txt +0 -0
  24. {shieldapi-2.0.0rc5 → shieldapi-2.2.0}/shieldapi.egg-info/dependency_links.txt +0 -0
  25. {shieldapi-2.0.0rc5 → shieldapi-2.2.0}/shieldapi.egg-info/top_level.txt +0 -0
  26. {shieldapi-2.0.0rc5 → shieldapi-2.2.0}/tests/__init__.py +0 -0
  27. {shieldapi-2.0.0rc5 → shieldapi-2.2.0}/tests/conftest.py +0 -0
@@ -1,28 +1,31 @@
1
- Metadata-Version: 2.1
1
+ Metadata-Version: 2.4
2
2
  Name: shieldapi
3
- Version: 2.0.0rc5
3
+ Version: 2.2.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.6
10
+ Requires-Python: >=3.9
11
11
  Description-Content-Type: text/markdown
12
12
  License-File: LICENSE
13
- Requires-Dist: python-keycloak>=1
14
- Requires-Dist: flask<3.0,>=2.2.3
15
- Requires-Dist: fastapi<1.0,>=0.85.0
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==2021.1114; extra == "dev"
18
- Requires-Dist: dunamai==1.7.0; extra == "dev"
19
- Requires-Dist: pre-commit~=2.20.0; extra == "dev"
19
+ Requires-Dist: bumpver>=2023.1119; extra == "dev"
20
+ Requires-Dist: dunamai>=1.7.0; extra == "dev"
21
+ Requires-Dist: pre-commit~=4.3.0; extra == "dev"
20
22
  Provides-Extra: tests
21
- Requires-Dist: pytest<8.0,>=7.1.3; extra == "tests"
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<1.0,>=0.23.3; extra == "tests"
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"
28
+ Dynamic: license-file
26
29
 
27
30
  # ShieldAPI
28
31
 
@@ -78,6 +81,11 @@ In order to successfully enable the callback for the token-generation and token-
78
81
  | `KEYCLOAK_VERIFY_HOST` | Controls whether SSL certificates are verified for HTTPS requests. Default is set to `False`. | "True" |
79
82
  | `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
83
  | `KEYCLOAK_REALM_ADMIN_PASSWORD` | Password of the realm admin, if any action shall be performed as admin in your Flask/FastAPI application. | "admin_password" |
84
+ | `KEYCLOAK_USE_SERVICE_ACCOUNT` | Whether a service account shall be used for admin operations instead of a custom user account with `KEYCLOAK_REALM_ADMIN_USER` and `KEYCLOAK_REALM_ADMIN_PASSWORD`. A service account in Keycloak is a special client configuration that allows applications to authenticate directly using client credentials (client ID and secret) without requiring a user login, enabling secure machine-to-machine (like a microservice, script, or backend job) API access. For more details, see the [official Keycloak documentation on service account authentication](https://www.keycloak.org/docs/latest/server_development/index.html#authenticating-with-a-service-account). | "True" |
85
+ | `SKIP_ENV_CHECK` | Optional. If set, skips the check for mandatory environment variables during startup. | "True" |
86
+
87
+ #### Note
88
+ - 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
89
 
82
90
  ## Usage with Flask
83
91
 
@@ -407,4 +415,4 @@ This work is supported by the MarketPlace project funded by [Horizon 2020](https
407
415
  ## License
408
416
 
409
417
  The code is licensed under BSD-3-Clause.
410
- Copyright © 2023 Materials MarketPlace
418
+ Copyright © 2025 Materials MarketPlace
@@ -1,29 +1,3 @@
1
- Metadata-Version: 2.1
2
- Name: shieldapi
3
- Version: 2.0.0rc5
4
- Summary: A package for endpoint protection of APIs using Keycloak
5
- Author: SINTEF, Fraunhofer IWM
6
- Author-email: yoav.nahshon@iwm.fraunhofer.de
7
- Classifier: Programming Language :: Python :: 3
8
- Classifier: License :: OSI Approved :: BSD License
9
- Classifier: Operating System :: OS Independent
10
- Requires-Python: >=3.6
11
- Description-Content-Type: text/markdown
12
- License-File: LICENSE
13
- Requires-Dist: python-keycloak>=1
14
- Requires-Dist: flask<3.0,>=2.2.3
15
- Requires-Dist: fastapi<1.0,>=0.85.0
16
- Provides-Extra: dev
17
- Requires-Dist: bumpver==2021.1114; extra == "dev"
18
- Requires-Dist: dunamai==1.7.0; extra == "dev"
19
- Requires-Dist: pre-commit~=2.20.0; extra == "dev"
20
- Provides-Extra: tests
21
- Requires-Dist: pytest<8.0,>=7.1.3; extra == "tests"
22
- Requires-Dist: requests-mock<2.0,>=1.10.0; extra == "tests"
23
- Requires-Dist: httpx<1.0,>=0.23.3; extra == "tests"
24
- Requires-Dist: semver<3.0,>=2.13.0; extra == "tests"
25
- Requires-Dist: pytest-mock>=3.10.0; extra == "tests"
26
-
27
1
  # ShieldAPI
28
2
 
29
3
  The `shieldapi` package provides utilities for implementing authentication/authorization mechanism through a Keycloak-backend in Python web applications, such as FastAPI and Flask. It includes functionality for managing user accounts, token authentication, and role-based access control.
@@ -78,6 +52,11 @@ In order to successfully enable the callback for the token-generation and token-
78
52
  | `KEYCLOAK_VERIFY_HOST` | Controls whether SSL certificates are verified for HTTPS requests. Default is set to `False`. | "True" |
79
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" |
80
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
+ | `KEYCLOAK_USE_SERVICE_ACCOUNT` | Whether a service account shall be used for admin operations instead of a custom user account with `KEYCLOAK_REALM_ADMIN_USER` and `KEYCLOAK_REALM_ADMIN_PASSWORD`. A service account in Keycloak is a special client configuration that allows applications to authenticate directly using client credentials (client ID and secret) without requiring a user login, enabling secure machine-to-machine (like a microservice, script, or backend job) API access. For more details, see the [official Keycloak documentation on service account authentication](https://www.keycloak.org/docs/latest/server_development/index.html#authenticating-with-a-service-account). | "True" |
56
+ | `SKIP_ENV_CHECK` | Optional. If set, skips the check for mandatory environment variables during startup. | "True" |
57
+
58
+ #### Note
59
+ - 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
60
 
82
61
  ## Usage with Flask
83
62
 
@@ -407,4 +386,4 @@ This work is supported by the MarketPlace project funded by [Horizon 2020](https
407
386
  ## License
408
387
 
409
388
  The code is licensed under BSD-3-Clause.
410
- Copyright © 2023 Materials MarketPlace
389
+ Copyright © 2025 Materials MarketPlace
@@ -1,6 +1,6 @@
1
1
  [metadata]
2
2
  name = shieldapi
3
- version = v2.0.0rc5
3
+ version = v2.2.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.6
16
+ python_requires = >=3.9
17
17
  install_requires =
18
- python-keycloak>=1
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==2021.1114
25
- dunamai==1.7.0
26
- pre-commit~=2.20.0
26
+ bumpver>=2023.1119
27
+ dunamai>=1.7.0
28
+ pre-commit~=4.3.0
27
29
  tests =
28
- pytest>=7.1.3,<8.0
30
+ pytest>=7.1.3
29
31
  requests-mock>=1.10.0,<2.0
30
- httpx>=0.23.3,<1.0
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 = "v0.0.0"
37
+ current_version = "v2.2.0"
36
38
  version_pattern = "vMAJOR.MINOR.PATCH[PYTAGNUM]"
37
39
  commit_message = "Bump version {old_version} -> {new_version}"
38
40
  commit = True
@@ -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()
@@ -104,7 +104,7 @@ class BasicLoginCredentials(HTTPBasicCredentials):
104
104
  f"BasicLoginCredentials.token: Attempting login for username={self.username}"
105
105
  )
106
106
  token = login(self.username, self.password)
107
- if len(token) == 2:
107
+ if isinstance(token, tuple):
108
108
  logger.error(
109
109
  f"BasicLoginCredentials.token: Invalid credentials for username={self.username}"
110
110
  )
@@ -154,7 +154,7 @@ class BasicLogin(HTTPBasic):
154
154
  f"BasicLogin.__call__: Credentials extracted for username={log.username}"
155
155
  )
156
156
  token = login(log.username, log.password)
157
- if len(token) == 2:
157
+ if isinstance(token, tuple):
158
158
  logger.error(
159
159
  f"BasicLogin.__call__: Invalid credentials for username={log.username}"
160
160
  )
@@ -1,4 +1,4 @@
1
- """Functions and decorators for shieldapi in Flask."""
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
- valid = check_token_validity(access_token)
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
- Returns:
73
- Callable:
74
- The decorated function.
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
- Args:
99
- role (str):
100
- The required role.
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
- Returns:
103
- Callable:
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
- res = f(*args, **kwargs)
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 (List[str]):
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
- return None
123
+ abort(401)
154
124
 
155
125
  token_info = get_keycloak_openid().introspect(token)
156
- if not token_info.json()["active"]:
126
+ if not bool(token_info.get("active")):
157
127
  logger.warning("has_scope: Access token is inactive")
158
- return None
128
+ abort(401)
159
129
 
160
- granted_scope = token_info.json()["scope"].split()
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
- return None
136
+ abort(403)
167
137
 
168
138
  logger.info("has_scope: All required scopes are granted")
169
- res = f(*args, **kwargs)
170
-
171
- return res
139
+ return f(*args, **kwargs)
172
140
 
173
141
  return restricted_function
174
142