-
Notifications
You must be signed in to change notification settings - Fork 4.4k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
🎉 CDK: Add requests native authenticator support #5731
Merged
Merged
Changes from all commits
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
4db4935
Add requests native auth class
htrueman e592bee
Merge remote-tracking branch 'origin/master' into htrueman/update-cdk…
htrueman 3378eb1
Update init file.
htrueman e841e77
Update TokenAuthenticator implementation.
htrueman 2591916
Update Oauth2Authenticator default value setting.
htrueman 44505df
Merge remote-tracking branch 'origin/master' into htrueman/update-cdk…
htrueman fd43229
Add requests native authenticator tests
htrueman 25f0b62
Add CDK requests native __call__ method tests.
htrueman 6df105b
Add outdated auth deprication messages
htrueman 1cffc36
Update requests native auth __call__ method tests
htrueman 708f4f9
Merge remote-tracking branch 'origin/master' into htrueman/update-cdk…
htrueman a2f87e5
Bump CDK version to 0.1.20
htrueman File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
32 changes: 32 additions & 0 deletions
32
airbyte-cdk/python/airbyte_cdk/sources/streams/http/requests_native_auth/__init__.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,32 @@ | ||
# | ||
# MIT License | ||
# | ||
# Copyright (c) 2020 Airbyte | ||
# | ||
# Permission is hereby granted, free of charge, to any person obtaining a copy | ||
# of this software and associated documentation files (the "Software"), to deal | ||
# in the Software without restriction, including without limitation the rights | ||
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
# copies of the Software, and to permit persons to whom the Software is | ||
# furnished to do so, subject to the following conditions: | ||
# | ||
# The above copyright notice and this permission notice shall be included in all | ||
# copies or substantial portions of the Software. | ||
# | ||
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | ||
# SOFTWARE. | ||
# | ||
|
||
from .oauth import Oauth2Authenticator | ||
from .token import MultipleTokenAuthenticator, TokenAuthenticator | ||
|
||
__all__ = [ | ||
"Oauth2Authenticator", | ||
"TokenAuthenticator", | ||
"MultipleTokenAuthenticator", | ||
] |
104 changes: 104 additions & 0 deletions
104
airbyte-cdk/python/airbyte_cdk/sources/streams/http/requests_native_auth/oauth.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,104 @@ | ||
# | ||
# MIT License | ||
# | ||
# Copyright (c) 2020 Airbyte | ||
# | ||
# Permission is hereby granted, free of charge, to any person obtaining a copy | ||
# of this software and associated documentation files (the "Software"), to deal | ||
# in the Software without restriction, including without limitation the rights | ||
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
# copies of the Software, and to permit persons to whom the Software is | ||
# furnished to do so, subject to the following conditions: | ||
# | ||
# The above copyright notice and this permission notice shall be included in all | ||
# copies or substantial portions of the Software. | ||
# | ||
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | ||
# SOFTWARE. | ||
# | ||
|
||
|
||
from typing import Any, List, Mapping, MutableMapping, Tuple | ||
|
||
import pendulum | ||
import requests | ||
from requests.auth import AuthBase | ||
|
||
|
||
class Oauth2Authenticator(AuthBase): | ||
""" | ||
Generates OAuth2.0 access tokens from an OAuth2.0 refresh token and client credentials. | ||
The generated access token is attached to each request via the Authorization header. | ||
""" | ||
|
||
def __init__( | ||
self, | ||
token_refresh_endpoint: str, | ||
client_id: str, | ||
client_secret: str, | ||
refresh_token: str, | ||
scopes: List[str] = None, | ||
token_expiry_date: pendulum.datetime = None, | ||
access_token_name: str = "access_token", | ||
expires_in_name: str = "expires_in", | ||
): | ||
self.token_refresh_endpoint = token_refresh_endpoint | ||
self.client_secret = client_secret | ||
self.client_id = client_id | ||
self.refresh_token = refresh_token | ||
self.scopes = scopes | ||
self.access_token_name = access_token_name | ||
self.expires_in_name = expires_in_name | ||
|
||
self._token_expiry_date = token_expiry_date or pendulum.now().subtract(days=1) | ||
self._access_token = None | ||
|
||
def __call__(self, request): | ||
request.headers.update(self.get_auth_header()) | ||
return request | ||
|
||
def get_auth_header(self) -> Mapping[str, Any]: | ||
return {"Authorization": f"Bearer {self.get_access_token()}"} | ||
|
||
def get_access_token(self): | ||
if self.token_has_expired(): | ||
t0 = pendulum.now() | ||
token, expires_in = self.refresh_access_token() | ||
self._access_token = token | ||
self._token_expiry_date = t0.add(seconds=expires_in) | ||
|
||
return self._access_token | ||
|
||
def token_has_expired(self) -> bool: | ||
return pendulum.now() > self._token_expiry_date | ||
|
||
def get_refresh_request_body(self) -> Mapping[str, Any]: | ||
"""Override to define additional parameters""" | ||
payload: MutableMapping[str, Any] = { | ||
"grant_type": "refresh_token", | ||
"client_id": self.client_id, | ||
"client_secret": self.client_secret, | ||
"refresh_token": self.refresh_token, | ||
} | ||
|
||
if self.scopes: | ||
payload["scopes"] = self.scopes | ||
|
||
return payload | ||
|
||
def refresh_access_token(self) -> Tuple[str, int]: | ||
""" | ||
returns a tuple of (access_token, token_lifespan_in_seconds) | ||
""" | ||
try: | ||
response = requests.request(method="POST", url=self.token_refresh_endpoint, data=self.get_refresh_request_body()) | ||
response.raise_for_status() | ||
response_json = response.json() | ||
return response_json[self.access_token_name], response_json[self.expires_in_name] | ||
except Exception as e: | ||
raise Exception(f"Error while refreshing access token: {e}") from e |
59 changes: 59 additions & 0 deletions
59
airbyte-cdk/python/airbyte_cdk/sources/streams/http/requests_native_auth/token.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,59 @@ | ||
# | ||
# MIT License | ||
# | ||
# Copyright (c) 2020 Airbyte | ||
# | ||
# Permission is hereby granted, free of charge, to any person obtaining a copy | ||
# of this software and associated documentation files (the "Software"), to deal | ||
# in the Software without restriction, including without limitation the rights | ||
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
# copies of the Software, and to permit persons to whom the Software is | ||
# furnished to do so, subject to the following conditions: | ||
# | ||
# The above copyright notice and this permission notice shall be included in all | ||
# copies or substantial portions of the Software. | ||
# | ||
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | ||
# SOFTWARE. | ||
# | ||
|
||
from itertools import cycle | ||
from typing import Any, List, Mapping | ||
|
||
from requests.auth import AuthBase | ||
|
||
|
||
class MultipleTokenAuthenticator(AuthBase): | ||
""" | ||
Builds auth header, based on the list of tokens provided. | ||
Auth header is changed per each `get_auth_header` call, using each token in cycle. | ||
The token is attached to each request via the `auth_header` header. | ||
""" | ||
|
||
def __init__(self, tokens: List[str], auth_method: str = "Bearer", auth_header: str = "Authorization"): | ||
htrueman marked this conversation as resolved.
Show resolved
Hide resolved
|
||
self.auth_method = auth_method | ||
self.auth_header = auth_header | ||
self._tokens = tokens | ||
self._tokens_iter = cycle(self._tokens) | ||
|
||
def __call__(self, request): | ||
request.headers.update(self.get_auth_header()) | ||
return request | ||
|
||
def get_auth_header(self) -> Mapping[str, Any]: | ||
return {self.auth_header: f"{self.auth_method} {next(self._tokens_iter)}"} | ||
|
||
|
||
class TokenAuthenticator(MultipleTokenAuthenticator): | ||
""" | ||
Builds auth header, based on the token provided. | ||
The token is attached to each request via the `auth_header` header. | ||
""" | ||
|
||
def __init__(self, token: str, auth_method: str = "Bearer", auth_header: str = "Authorization"): | ||
htrueman marked this conversation as resolved.
Show resolved
Hide resolved
|
||
super().__init__([token], auth_method, auth_header) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Maybe create a ticket for it? And when it should be removed?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
#5755