oidcauthlib 0.0.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.
Files changed (41) hide show
  1. oidcauthlib-0.0.1/LICENSE +201 -0
  2. oidcauthlib-0.0.1/MANIFEST.in +6 -0
  3. oidcauthlib-0.0.1/Makefile +75 -0
  4. oidcauthlib-0.0.1/PKG-INFO +30 -0
  5. oidcauthlib-0.0.1/README.md +1 -0
  6. oidcauthlib-0.0.1/VERSION +1 -0
  7. oidcauthlib-0.0.1/oidcauthlib/__init__.py +0 -0
  8. oidcauthlib-0.0.1/oidcauthlib/auth/__init__.py +0 -0
  9. oidcauthlib-0.0.1/oidcauthlib/auth/auth_helper.py +51 -0
  10. oidcauthlib-0.0.1/oidcauthlib/auth/auth_manager.py +303 -0
  11. oidcauthlib-0.0.1/oidcauthlib/auth/cache/__init__.py +0 -0
  12. oidcauthlib-0.0.1/oidcauthlib/auth/cache/oauth_cache.py +47 -0
  13. oidcauthlib-0.0.1/oidcauthlib/auth/cache/oauth_memory_cache.py +52 -0
  14. oidcauthlib-0.0.1/oidcauthlib/auth/cache/oauth_mongo_cache.py +183 -0
  15. oidcauthlib-0.0.1/oidcauthlib/auth/config/__init__.py +0 -0
  16. oidcauthlib-0.0.1/oidcauthlib/auth/config/auth_config.py +24 -0
  17. oidcauthlib-0.0.1/oidcauthlib/auth/config/auth_config_reader.py +175 -0
  18. oidcauthlib-0.0.1/oidcauthlib/auth/exceptions/__init__.py +0 -0
  19. oidcauthlib-0.0.1/oidcauthlib/auth/exceptions/authorization_bearer_token_expired_exception.py +37 -0
  20. oidcauthlib-0.0.1/oidcauthlib/auth/exceptions/authorization_bearer_token_invalid_exception.py +21 -0
  21. oidcauthlib-0.0.1/oidcauthlib/auth/exceptions/authorization_bearer_token_missing_exception.py +20 -0
  22. oidcauthlib-0.0.1/oidcauthlib/auth/exceptions/authorization_needed_exception.py +17 -0
  23. oidcauthlib-0.0.1/oidcauthlib/auth/models/__init__.py +0 -0
  24. oidcauthlib-0.0.1/oidcauthlib/auth/models/token.py +190 -0
  25. oidcauthlib-0.0.1/oidcauthlib/auth/token_reader.py +471 -0
  26. oidcauthlib-0.0.1/oidcauthlib/py.typed +0 -0
  27. oidcauthlib-0.0.1/oidcauthlib/utilities/__init__.py +0 -0
  28. oidcauthlib-0.0.1/oidcauthlib/utilities/environment_variables.py +85 -0
  29. oidcauthlib-0.0.1/oidcauthlib/utilities/logger/__init__.py +0 -0
  30. oidcauthlib-0.0.1/oidcauthlib/utilities/logger/log_levels.py +43 -0
  31. oidcauthlib-0.0.1/oidcauthlib/utilities/logger/logging_response.py +37 -0
  32. oidcauthlib-0.0.1/oidcauthlib/utilities/logger/logging_transport.py +56 -0
  33. oidcauthlib-0.0.1/oidcauthlib.egg-info/PKG-INFO +30 -0
  34. oidcauthlib-0.0.1/oidcauthlib.egg-info/SOURCES.txt +40 -0
  35. oidcauthlib-0.0.1/oidcauthlib.egg-info/dependency_links.txt +1 -0
  36. oidcauthlib-0.0.1/oidcauthlib.egg-info/not-zip-safe +1 -0
  37. oidcauthlib-0.0.1/oidcauthlib.egg-info/requires.txt +4 -0
  38. oidcauthlib-0.0.1/oidcauthlib.egg-info/top_level.txt +2 -0
  39. oidcauthlib-0.0.1/setup.cfg +23 -0
  40. oidcauthlib-0.0.1/setup.py +75 -0
  41. oidcauthlib-0.0.1/tests/__init__.py +0 -0
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,6 @@
1
+ include README.md
2
+ include requirements.txt
3
+ include requirements-test.txt
4
+ include VERSION
5
+ include Makefile
6
+ include oidcauthlib/py.typed
@@ -0,0 +1,75 @@
1
+ LANG=en_US.utf-8
2
+
3
+ export LANG
4
+
5
+ .PHONY: Pipfile.lock
6
+ Pipfile.lock:
7
+ docker compose --progress=plain build --no-cache --build-arg RUN_PIPENV_LOCK=true dev && \
8
+ docker compose --progress=plain run --rm dev sh -c "cp -f /tmp/Pipfile.lock /usr/src/oidcauthlib/Pipfile.lock"
9
+
10
+ .PHONY:devdocker
11
+ devdocker: ## Builds the docker for dev
12
+ docker compose build
13
+
14
+ .PHONY:init
15
+ init: Pipfile.lock devdocker up setup-pre-commit ## Initializes the local developer environment
16
+
17
+ .PHONY: up
18
+ up:
19
+ docker compose up --build -d --remove-orphans
20
+
21
+ .PHONY: down
22
+ down:
23
+ docker compose down
24
+
25
+ .PHONY:clean-pre-commit
26
+ clean-pre-commit: ## removes pre-commit hook
27
+ rm -f .git/hooks/pre-commit
28
+
29
+ .PHONY:setup-pre-commit
30
+ setup-pre-commit:
31
+ cp ./pre-commit-hook ./.git/hooks/pre-commit && \
32
+ chmod +x ./.git/hooks/pre-commit
33
+
34
+ .PHONY:run-pre-commit
35
+ run-pre-commit: setup-pre-commit
36
+ ./.git/hooks/pre-commit
37
+
38
+ .PHONY:update
39
+ update: down Pipfile.lock setup-pre-commit ## Updates all the packages using Pipfile
40
+ make devdocker && \
41
+ make pipenv-setup
42
+
43
+ .PHONY:tests
44
+ tests: up
45
+ docker compose run --rm --name oidcauthlib dev pytest tests oidcauthlib
46
+
47
+ .PHONY:shell
48
+ shell:devdocker ## Brings up the bash shell in dev docker
49
+ docker compose run --rm --name oidcauthlib dev sh
50
+
51
+ .PHONY:build
52
+ build:
53
+ docker compose run --rm --name oidcauthlib dev rm -rf dist/
54
+ docker compose run --rm --name oidcauthlib dev python3 setup.py sdist bdist_wheel
55
+
56
+ .PHONY:testpackage
57
+ testpackage:build
58
+ docker compose run --rm --name oidcauthlib dev python3 -m twine upload -u __token__ --repository testpypi dist/*
59
+ # password can be set in TWINE_PASSWORD. https://twine.readthedocs.io/en/latest/
60
+
61
+ .PHONY:package
62
+ package:build
63
+ docker compose run --rm --name oidcauthlib dev python3 -m twine upload -u __token__ --repository pypi dist/*
64
+ # password can be set in TWINE_PASSWORD. https://twine.readthedocs.io/en/latest/ (note this is the token not your password)
65
+
66
+ .DEFAULT_GOAL := help
67
+ .PHONY: help
68
+ help: ## Show this help.
69
+ # from https://marmelab.com/blog/2016/02/29/auto-documented-makefile.html
70
+ @grep -E '^[a-zA-Z_-]+:.*?## .*$$' $(MAKEFILE_LIST) | sort | awk 'BEGIN {FS = ":.*?## "}; {printf "\033[36m%-30s\033[0m %s\n", $$1, $$2}'
71
+
72
+ .PHONY:pipenv-setup
73
+ pipenv-setup:devdocker ## Run pipenv-setup to update setup.py with latest dependencies
74
+ docker compose run --rm dev sh -c "pipenv run pipenv install --skip-lock --categories \"pipenvsetup\" && pipenv run pipenv-setup sync --pipfile" && \
75
+ make run-pre-commit
@@ -0,0 +1,30 @@
1
+ Metadata-Version: 2.4
2
+ Name: oidcauthlib
3
+ Version: 0.0.1
4
+ Summary: oidcauthlib
5
+ Home-page: https://github.com/icanbwell/oidc-auth-lib
6
+ Author: Imran Qureshi
7
+ Author-email: imran.qureshi@bwell.com
8
+ Classifier: Development Status :: 4 - Beta
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: License :: OSI Approved :: Apache Software License
11
+ Classifier: Operating System :: OS Independent
12
+ Requires-Python: >=3.10
13
+ Description-Content-Type: text/markdown
14
+ License-File: LICENSE
15
+ Requires-Dist: httpx>=0.27.2
16
+ Requires-Dist: authlib>=1.6.4
17
+ Requires-Dist: joserfc>=1.2.2
18
+ Requires-Dist: pydantic<3.0.0,>=2.0
19
+ Dynamic: author
20
+ Dynamic: author-email
21
+ Dynamic: classifier
22
+ Dynamic: description
23
+ Dynamic: description-content-type
24
+ Dynamic: home-page
25
+ Dynamic: license-file
26
+ Dynamic: requires-dist
27
+ Dynamic: requires-python
28
+ Dynamic: summary
29
+
30
+ # oidcauthlib
@@ -0,0 +1 @@
1
+ # oidcauthlib
@@ -0,0 +1 @@
1
+ 0.0.1
File without changes
File without changes
@@ -0,0 +1,51 @@
1
+ import base64
2
+ import json
3
+ import logging
4
+
5
+ from oidcauthlib.utilities.logger.log_levels import SRC_LOG_LEVELS
6
+
7
+ logger = logging.getLogger(__name__)
8
+ logger.setLevel(SRC_LOG_LEVELS["AUTH"])
9
+
10
+
11
+ class AuthHelper:
12
+ @staticmethod
13
+ def encode_state(content: dict[str, str | None]) -> str:
14
+ """
15
+ Encode the state content into a base64url encoded string.
16
+
17
+ Args:
18
+ content: The content to encode, typically a dictionary.
19
+
20
+ Returns:
21
+ A base64url encoded string of the content.
22
+ """
23
+ json_content = json.dumps(content)
24
+ encoded_content = base64.urlsafe_b64encode(json_content.encode("utf-8")).decode(
25
+ "utf-8"
26
+ )
27
+ return encoded_content.rstrip("=")
28
+
29
+ @staticmethod
30
+ def decode_state(encoded_content: str) -> dict[str, str | None]:
31
+ """
32
+ Decode a base64url encoded string back into its original dictionary form.
33
+
34
+ Args:
35
+ encoded_content: The base64url encoded string to decode.
36
+
37
+ Returns:
38
+ The decoded content as a dictionary.
39
+ """
40
+ # Add padding if necessary
41
+ padding_needed = (-len(encoded_content)) % 4
42
+ padded_content = encoded_content + ("=" * padding_needed)
43
+ try:
44
+ json_content = base64.urlsafe_b64decode(padded_content).decode("utf-8")
45
+ result = json.loads(json_content)
46
+ if not isinstance(result, dict):
47
+ raise ValueError("Decoded state is not a dictionary")
48
+ return result
49
+ except Exception as e:
50
+ logger.error(f"Failed to decode state: {e}")
51
+ raise ValueError("Invalid encoded state") from e
@@ -0,0 +1,303 @@
1
+ import logging
2
+ import os
3
+ import time
4
+ import uuid
5
+ from typing import Any, Dict, cast, List
6
+
7
+ import httpx
8
+ from authlib.integrations.httpx_client import AsyncOAuth2Client
9
+ from authlib.integrations.starlette_client import OAuth, StarletteOAuth2App
10
+
11
+ from oidcauthlib.auth.auth_helper import AuthHelper
12
+ from oidcauthlib.auth.cache.oauth_cache import OAuthCache
13
+ from oidcauthlib.auth.cache.oauth_memory_cache import (
14
+ OAuthMemoryCache,
15
+ )
16
+ from oidcauthlib.auth.cache.oauth_mongo_cache import OAuthMongoCache
17
+ from oidcauthlib.auth.config.auth_config import AuthConfig
18
+ from oidcauthlib.auth.config.auth_config_reader import (
19
+ AuthConfigReader,
20
+ )
21
+ from oidcauthlib.auth.exceptions.authorization_needed_exception import (
22
+ AuthorizationNeededException,
23
+ )
24
+ from oidcauthlib.auth.token_reader import TokenReader
25
+ from oidcauthlib.utilities.environment_variables import (
26
+ EnvironmentVariables,
27
+ )
28
+ from oidcauthlib.utilities.logger.log_levels import SRC_LOG_LEVELS
29
+ from oidcauthlib.utilities.logger.logging_transport import (
30
+ LoggingTransport,
31
+ )
32
+
33
+ logger = logging.getLogger(__name__)
34
+ logger.setLevel(SRC_LOG_LEVELS["AUTH"])
35
+
36
+
37
+ class AuthManager:
38
+ """
39
+ AuthManager is responsible for managing authentication using OIDC PKCE.
40
+
41
+ It initializes the OAuth client with the necessary configuration and provides methods
42
+ to create authorization URLs and handle callback responses.
43
+ """
44
+
45
+ def __init__(
46
+ self,
47
+ *,
48
+ environment_variables: EnvironmentVariables,
49
+ auth_config_reader: AuthConfigReader,
50
+ token_reader: TokenReader,
51
+ ) -> None:
52
+ """
53
+ Initialize the AuthManager with the necessary configuration for OIDC PKCE.
54
+ It sets up the OAuth cache, reads environment variables for the OIDC provider,
55
+ and configures the OAuth client.
56
+ The environment variables required are:
57
+ - MONGO_URL: The connection string for the MongoDB database.
58
+ - MONGO_DB_NAME: The name of the MongoDB database.
59
+ - MONGO_DB_TOKEN_COLLECTION_NAME: The name of the MongoDB collection for tokens.
60
+ It also initializes the OAuth cache based on the OAUTH_CACHE environment variable,
61
+ which can be set to "memory" for in-memory caching or "mongo" for MongoDB caching.
62
+ If the OAUTH_CACHE environment variable is not set, it defaults to "memory".
63
+
64
+ Args:
65
+ environment_variables (EnvironmentVariables): The environment variables for the application.
66
+ auth_config_reader (AuthConfigReader): The reader for authentication configurations.
67
+ token_reader (TokenReader): The reader for tokens.
68
+ """
69
+ self.environment_variables: EnvironmentVariables = environment_variables
70
+ if self.environment_variables is None:
71
+ raise ValueError("environment_variables must not be None")
72
+ if not isinstance(self.environment_variables, EnvironmentVariables):
73
+ raise TypeError(
74
+ "environment_variables must be an instance of EnvironmentVariables"
75
+ )
76
+
77
+ self.auth_config_reader: AuthConfigReader = auth_config_reader
78
+ if self.auth_config_reader is None:
79
+ raise ValueError("auth_config_reader must not be None")
80
+ if not isinstance(self.auth_config_reader, AuthConfigReader):
81
+ raise TypeError(
82
+ "auth_config_reader must be an instance of AuthConfigReader"
83
+ )
84
+
85
+ self.token_reader: TokenReader = token_reader
86
+ if self.token_reader is None:
87
+ raise ValueError("token_reader must not be None")
88
+ if not isinstance(self.token_reader, TokenReader):
89
+ raise TypeError("token_reader must be an instance of TokenReader")
90
+
91
+ oauth_cache_type = environment_variables.oauth_cache
92
+ self.cache: OAuthCache = (
93
+ OAuthMemoryCache()
94
+ if oauth_cache_type == "memory"
95
+ else OAuthMongoCache(environment_variables=environment_variables)
96
+ )
97
+
98
+ logger.debug(
99
+ f"Initializing AuthManager with cache type {type(self.cache)} cache id: {self.cache.id}"
100
+ )
101
+ # OIDC PKCE setup
102
+ self.redirect_uri = os.getenv("AUTH_REDIRECT_URI")
103
+ if self.redirect_uri is None:
104
+ raise ValueError("AUTH_REDIRECT_URI environment variable must be set")
105
+ # https://docs.authlib.org/en/latest/client/frameworks.html#frameworks-clients
106
+ self.oauth: OAuth = OAuth(cache=self.cache) # type: ignore[no-untyped-call]
107
+ # read AUTH_PROVIDERS comma separated list from the environment variable and register the OIDC provider for each provider
108
+ auth_configs: List[AuthConfig] = (
109
+ self.auth_config_reader.get_auth_configs_for_all_auth_providers()
110
+ )
111
+
112
+ auth_config: AuthConfig
113
+ for auth_config in auth_configs:
114
+ self.oauth.register(
115
+ name=auth_config.audience,
116
+ client_id=auth_config.client_id,
117
+ client_secret=auth_config.client_secret,
118
+ server_metadata_url=auth_config.well_known_uri,
119
+ client_kwargs={
120
+ "scope": "openid email",
121
+ "code_challenge_method": "S256",
122
+ "transport": LoggingTransport(httpx.AsyncHTTPTransport()),
123
+ },
124
+ )
125
+
126
+ async def create_authorization_url(
127
+ self,
128
+ *,
129
+ redirect_uri: str,
130
+ audience: str,
131
+ issuer: str,
132
+ url: str | None,
133
+ referring_email: str | None,
134
+ referring_subject: str | None,
135
+ ) -> str:
136
+ """
137
+ Create the authorization URL for the OIDC provider.
138
+
139
+ This method generates the authorization URL with the necessary parameters,
140
+ including the redirect URI and state. The state is encoded to include the tool name,
141
+ which is used to identify the tool that initiated the authentication process.
142
+ Args:
143
+ redirect_uri (str): The redirect URI to which the OIDC provider will send the user
144
+ after authentication.
145
+ audience (str): The audience we need to get a token for.
146
+ issuer (str): The issuer of the OIDC provider, used to validate the token.
147
+ url (str): The URL of the tool that has requested this.
148
+ referring_email (str): The email of the user who initiated the request.
149
+ referring_subject (str): The subject of the user who initiated the request.
150
+ Returns:
151
+ str: The authorization URL to redirect the user to for authentication.
152
+ """
153
+ # default to first audience
154
+ client: StarletteOAuth2App = self.oauth.create_client(audience) # type: ignore[no-untyped-call]
155
+ if client is None:
156
+ raise ValueError(f"Client for audience {audience} not found")
157
+ state_content: Dict[str, str | None] = {
158
+ "audience": audience,
159
+ "auth_provider": self.auth_config_reader.get_provider_for_audience(
160
+ audience=audience
161
+ ),
162
+ "issuer": issuer,
163
+ "referring_email": referring_email,
164
+ "referring_subject": referring_subject,
165
+ "url": url, # the URL of the tool that has requested this
166
+ # include a unique request ID so we don't get cache for another request
167
+ # This will create a unique state for each request
168
+ # the callback will use this state to find the correct token
169
+ "request_id": uuid.uuid4().hex,
170
+ }
171
+ # convert state_content to a string
172
+ state: str = AuthHelper.encode_state(state_content)
173
+
174
+ logger.debug(
175
+ f"Creating authorization URL for audience {audience} with state {state_content} and encoded state {state}"
176
+ )
177
+
178
+ rv: Dict[str, Any] = await client.create_authorization_url(
179
+ redirect_uri=redirect_uri, state=state
180
+ )
181
+ logger.debug(f"Authorization URL created: {rv}")
182
+ # request is only needed if we are using the session to store the state
183
+ await client.save_authorize_data(request=None, redirect_uri=redirect_uri, **rv)
184
+ return cast(str, rv["url"])
185
+
186
+ @staticmethod
187
+ async def login_and_get_token_with_username_password_async(
188
+ *,
189
+ auth_config: AuthConfig,
190
+ username: str,
191
+ password: str,
192
+ audience: str | None = None,
193
+ token_name: str = "access_token",
194
+ ) -> str:
195
+ """
196
+ Logs in a user with the provided username and password, and retrieves an access token.
197
+
198
+ Args:
199
+ auth_config (AuthConfig): The authentication configuration.
200
+ username (str): The username of the user.
201
+ password (str): The password of the user.
202
+ audience (str | None): The intended audience for the token. Optional.
203
+ token_name (str): The name of the token to retrieve. Defaults to "access_token".
204
+
205
+ Returns:
206
+ str: The access token if login is successful.
207
+
208
+ Raises:
209
+ Exception: If login fails or token retrieval is unsuccessful.
210
+ """
211
+
212
+ # Discover token endpoint
213
+ token_url = None
214
+ if auth_config.well_known_uri:
215
+ try:
216
+ async with httpx.AsyncClient(timeout=5) as async_client:
217
+ resp = await async_client.get(auth_config.well_known_uri)
218
+ resp.raise_for_status()
219
+ token_url = resp.json().get("token_endpoint")
220
+ except Exception as e:
221
+ raise AuthorizationNeededException(
222
+ message=f"Failed to discover token endpoint: {e}"
223
+ )
224
+ if not token_url and auth_config.issuer:
225
+ token_url = (
226
+ auth_config.issuer.rstrip("/") + "/protocol/openid-connect/token"
227
+ )
228
+ if not token_url:
229
+ raise AuthorizationNeededException(
230
+ message="No token endpoint found in AuthConfig."
231
+ )
232
+
233
+ # Prepare OAuth2 client
234
+ client_id = auth_config.client_id
235
+ client_secret = auth_config.client_secret
236
+ audience = audience or auth_config.audience
237
+ client = AsyncOAuth2Client(client_id, client_secret, timeout=10)
238
+
239
+ # Request token
240
+ try:
241
+ # This DOES return a coroutine
242
+ # noinspection PyUnresolvedReferences
243
+ token: Dict[str, Any] = await client.fetch_token(
244
+ url=token_url,
245
+ grant_type="password",
246
+ username=username,
247
+ password=password,
248
+ scope="openid",
249
+ audience=audience,
250
+ )
251
+ if not isinstance(token, dict):
252
+ raise TypeError(f"Expected token to be a dict, got {type(token)}")
253
+
254
+ except Exception as e:
255
+ raise AuthorizationNeededException(message=f"Token request failed: {e}")
256
+
257
+ access_token: str | None = token.get(token_name)
258
+ if not access_token:
259
+ raise AuthorizationNeededException(message="No access token returned.")
260
+
261
+ return access_token
262
+
263
+ @staticmethod
264
+ def wait_till_well_known_configuration_available(
265
+ *, auth_config: AuthConfig, timeout_seconds: int = 30
266
+ ) -> None:
267
+ """
268
+ Wait until the well-known configuration is available for the given AuthConfig.
269
+
270
+ This method repeatedly attempts to fetch the well-known configuration from the
271
+ specified URL until it succeeds or the timeout is reached.
272
+
273
+ Args:
274
+ auth_config (AuthConfig): The authentication configuration containing the
275
+ well-known URL.
276
+ timeout_seconds (int): The maximum time to wait in seconds. Defaults to 30 seconds.
277
+ Raises:
278
+ TimeoutError: If the well-known configuration is not available within the timeout period.
279
+ """
280
+ if not auth_config.well_known_uri:
281
+ raise ValueError("AuthConfig must have a well-known URI to wait for.")
282
+
283
+ start_time = time.time()
284
+ while True:
285
+ try:
286
+ with httpx.Client(timeout=5) as client:
287
+ resp = client.get(auth_config.well_known_uri)
288
+ resp.raise_for_status()
289
+ # Successfully fetched the configuration
290
+ logger.info(
291
+ f"Well-known configuration is now available at {auth_config.well_known_uri}"
292
+ )
293
+ return
294
+ except Exception as e:
295
+ elapsed_time = time.time() - start_time
296
+ if elapsed_time >= timeout_seconds:
297
+ raise TimeoutError(
298
+ f"Timed out waiting for well-known configuration at {auth_config.well_known_uri}"
299
+ ) from e
300
+ logger.debug(
301
+ f"Well-known configuration not yet available, retrying... ({elapsed_time:.1f}s elapsed)"
302
+ )
303
+ time.sleep(2) # Wait before retrying
File without changes