-
Notifications
You must be signed in to change notification settings - Fork 380
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
[#3755] improvement(client-python): Support OAuth2TokenProvider for Python client #4011
Merged
Merged
Changes from all commits
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
8d534b0
oauth WIP
8d9d02c
fix format
b22b5b0
second to millis
8b60110
mock methods
f999048
fix form to json type
78d0de0
add comments
6ffdace
add comments
56ad4de
http_client header
d0fe7fb
change license
791f306
fix test
e5176ca
fix test
8410c81
fix filename
328884b
fix test
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
133 changes: 133 additions & 0 deletions
133
clients/client-python/gravitino/auth/default_oauth2_token_provider.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,133 @@ | ||
""" | ||
Licensed to the Apache Software Foundation (ASF) under one | ||
or more contributor license agreements. See the NOTICE file | ||
distributed with this work for additional information | ||
regarding copyright ownership. The ASF licenses this file | ||
to you under the Apache License, Version 2.0 (the | ||
"License"); you may not use this file except in compliance | ||
with the License. You may obtain a copy of the License at | ||
|
||
http://www.apache.org/licenses/LICENSE-2.0 | ||
|
||
Unless required by applicable law or agreed to in writing, | ||
software distributed under the License is distributed on an | ||
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY | ||
KIND, either express or implied. See the License for the | ||
specific language governing permissions and limitations | ||
under the License. | ||
""" | ||
|
||
import time | ||
import json | ||
import base64 | ||
from typing import Optional | ||
from gravitino.auth.oauth2_token_provider import OAuth2TokenProvider | ||
from gravitino.dto.responses.oauth2_token_response import OAuth2TokenResponse | ||
from gravitino.dto.requests.oauth2_client_credential_request import ( | ||
OAuth2ClientCredentialRequest, | ||
) | ||
from gravitino.exceptions.base import GravitinoRuntimeException | ||
|
||
CLIENT_CREDENTIALS = "client_credentials" | ||
CREDENTIAL_SPLITTER = ":" | ||
TOKEN_SPLITTER = "." | ||
JWT_EXPIRE = "exp" | ||
|
||
|
||
class DefaultOAuth2TokenProvider(OAuth2TokenProvider): | ||
"""This class is the default implement of OAuth2TokenProvider.""" | ||
|
||
_credential: Optional[str] | ||
_scope: Optional[str] | ||
_path: Optional[str] | ||
_token: Optional[str] | ||
|
||
def __init__( | ||
self, | ||
uri: str = None, | ||
credential: str = None, | ||
scope: str = None, | ||
path: str = None, | ||
): | ||
super().__init__(uri) | ||
|
||
self._credential = credential | ||
self._scope = scope | ||
self._path = path | ||
|
||
self.validate() | ||
|
||
self._token = self._fetch_token() | ||
|
||
def validate(self): | ||
assert ( | ||
self._credential and self._credential.strip() | ||
), "OAuth2TokenProvider must set credential" | ||
assert self._scope and self._scope.strip(), "OAuth2TokenProvider must set scope" | ||
assert self._path and self._path.strip(), "OAuth2TokenProvider must set path" | ||
|
||
def _get_access_token(self) -> Optional[str]: | ||
|
||
expires = self._expires_at_millis() | ||
|
||
if expires is None: | ||
return None | ||
|
||
if expires > time.time() * 1000: | ||
return self._token | ||
|
||
self._token = self._fetch_token() | ||
return self._token | ||
|
||
def _parse_credential(self): | ||
assert self._credential is not None, "Invalid credential: None" | ||
|
||
credential_info = self._credential.split(CREDENTIAL_SPLITTER, maxsplit=1) | ||
client_id = None | ||
client_secret = None | ||
|
||
if len(credential_info) == 2: | ||
client_id, client_secret = credential_info | ||
elif len(credential_info) == 1: | ||
client_secret = credential_info[0] | ||
else: | ||
raise GravitinoRuntimeException(f"Invalid credential: {self._credential}") | ||
|
||
return client_id, client_secret | ||
|
||
def _fetch_token(self) -> str: | ||
|
||
client_id, client_secret = self._parse_credential() | ||
|
||
client_credential_request = OAuth2ClientCredentialRequest( | ||
grant_type=CLIENT_CREDENTIALS, | ||
client_id=client_id, | ||
client_secret=client_secret, | ||
scope=self._scope, | ||
) | ||
|
||
resp = self._client.post_form( | ||
self._path, data=client_credential_request.to_dict() | ||
) | ||
oauth2_resp = OAuth2TokenResponse.from_json(resp.body, infer_missing=True) | ||
oauth2_resp.validate() | ||
|
||
return oauth2_resp.access_token() | ||
|
||
def _expires_at_millis(self) -> int: | ||
if self._token is None: | ||
return None | ||
|
||
parts = self._token.split(TOKEN_SPLITTER) | ||
|
||
if len(parts) != 3: | ||
return None | ||
|
||
jwt = json.loads( | ||
base64.b64decode(parts[1] + "=" * (-len(parts[1]) % 4)).decode("utf-8") | ||
) | ||
|
||
if JWT_EXPIRE not in jwt or not isinstance(jwt[JWT_EXPIRE], int): | ||
return None | ||
|
||
return jwt[JWT_EXPIRE] * 1000 |
75 changes: 75 additions & 0 deletions
75
clients/client-python/gravitino/auth/oauth2_token_provider.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,75 @@ | ||
""" | ||
Licensed to the Apache Software Foundation (ASF) under one | ||
or more contributor license agreements. See the NOTICE file | ||
distributed with this work for additional information | ||
regarding copyright ownership. The ASF licenses this file | ||
to you under the Apache License, Version 2.0 (the | ||
"License"); you may not use this file except in compliance | ||
with the License. You may obtain a copy of the License at | ||
|
||
http://www.apache.org/licenses/LICENSE-2.0 | ||
|
||
Unless required by applicable law or agreed to in writing, | ||
software distributed under the License is distributed on an | ||
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY | ||
KIND, either express or implied. See the License for the | ||
specific language governing permissions and limitations | ||
under the License. | ||
""" | ||
|
||
from abc import abstractmethod | ||
from typing import Optional | ||
|
||
from gravitino.utils.http_client import HTTPClient | ||
from gravitino.auth.auth_data_provider import AuthDataProvider | ||
from gravitino.auth.auth_constants import AuthConstants | ||
|
||
|
||
class OAuth2TokenProvider(AuthDataProvider): | ||
"""OAuth2TokenProvider will request the access token from the authorization server and then provide | ||
the access token for every request. | ||
""" | ||
|
||
# The HTTP client used to request the access token from the authorization server. | ||
_client: HTTPClient | ||
|
||
def __init__(self, uri: str): | ||
self._client = HTTPClient(uri) | ||
|
||
def has_token_data(self) -> bool: | ||
"""Judge whether AuthDataProvider can provide token data. | ||
|
||
Returns: | ||
true if the AuthDataProvider can provide token data otherwise false. | ||
""" | ||
return True | ||
|
||
def get_token_data(self) -> Optional[bytes]: | ||
"""Acquire the data of token for authentication. The client will set the token data as HTTP header | ||
Authorization directly. So the return value should ensure token data contain the token header | ||
(eg: Bearer, Basic) if necessary. | ||
|
||
Returns: | ||
the token data is used for authentication. | ||
""" | ||
access_token = self._get_access_token() | ||
|
||
if access_token is None: | ||
return None | ||
|
||
return (AuthConstants.AUTHORIZATION_BEARER_HEADER + access_token).encode( | ||
"utf-8" | ||
) | ||
|
||
def close(self): | ||
"""Closes the OAuth2TokenProvider and releases any underlying resources.""" | ||
if self._client is not None: | ||
self._client.close() | ||
|
||
@abstractmethod | ||
def _get_access_token(self) -> Optional[str]: | ||
"""Get the access token from the authorization server.""" | ||
|
||
@abstractmethod | ||
def validate(self): | ||
"""Validate the OAuth2TokenProvider""" |
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
33 changes: 33 additions & 0 deletions
33
clients/client-python/gravitino/dto/requests/oauth2_client_credential_request.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,33 @@ | ||
""" | ||
Licensed to the Apache Software Foundation (ASF) under one | ||
or more contributor license agreements. See the NOTICE file | ||
distributed with this work for additional information | ||
regarding copyright ownership. The ASF licenses this file | ||
to you under the Apache License, Version 2.0 (the | ||
"License"); you may not use this file except in compliance | ||
with the License. You may obtain a copy of the License at | ||
|
||
http://www.apache.org/licenses/LICENSE-2.0 | ||
|
||
Unless required by applicable law or agreed to in writing, | ||
software distributed under the License is distributed on an | ||
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY | ||
KIND, either express or implied. See the License for the | ||
specific language governing permissions and limitations | ||
under the License. | ||
""" | ||
|
||
from typing import Optional | ||
from dataclasses import dataclass | ||
|
||
|
||
@dataclass | ||
class OAuth2ClientCredentialRequest: | ||
|
||
grant_type: str | ||
client_id: Optional[str] | ||
client_secret: str | ||
scope: str | ||
|
||
def to_dict(self, **kwarg): | ||
return {k: v for k, v in self.__dict__.items() if v is not None} |
55 changes: 55 additions & 0 deletions
55
clients/client-python/gravitino/dto/responses/oauth2_token_response.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,55 @@ | ||
""" | ||
Licensed to the Apache Software Foundation (ASF) under one | ||
or more contributor license agreements. See the NOTICE file | ||
distributed with this work for additional information | ||
regarding copyright ownership. The ASF licenses this file | ||
to you under the Apache License, Version 2.0 (the | ||
"License"); you may not use this file except in compliance | ||
with the License. You may obtain a copy of the License at | ||
|
||
http://www.apache.org/licenses/LICENSE-2.0 | ||
|
||
Unless required by applicable law or agreed to in writing, | ||
software distributed under the License is distributed on an | ||
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY | ||
KIND, either express or implied. See the License for the | ||
specific language governing permissions and limitations | ||
under the License. | ||
""" | ||
|
||
from typing import Optional | ||
from dataclasses import dataclass, field | ||
from dataclasses_json import config | ||
|
||
from gravitino.dto.responses.base_response import BaseResponse | ||
from gravitino.auth.auth_constants import AuthConstants | ||
|
||
|
||
@dataclass | ||
class OAuth2TokenResponse(BaseResponse): | ||
|
||
_access_token: str = field(metadata=config(field_name="access_token")) | ||
_issue_token_type: Optional[str] = field( | ||
metadata=config(field_name="issued_token_type") | ||
) | ||
_token_type: str = field(metadata=config(field_name="token_type")) | ||
_expires_in: int = field(metadata=config(field_name="expires_in")) | ||
_scope: str = field(metadata=config(field_name="scope")) | ||
_refresh_token: Optional[str] = field(metadata=config(field_name="refresh_token")) | ||
|
||
def validate(self): | ||
"""Validates the response. | ||
|
||
Raise: | ||
IllegalArgumentException If the response is invalid, this exception is thrown. | ||
""" | ||
super().validate() | ||
|
||
assert self._access_token is not None, "Invalid access token: None" | ||
assert ( | ||
AuthConstants.AUTHORIZATION_BEARER_HEADER.strip().lower() | ||
== self._token_type.lower() | ||
), f'Unsupported token type: {self._token_type} (must be "bearer")' | ||
|
||
def access_token(self) -> str: | ||
return self._access_token |
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
Oops, something went wrong.
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.
It seems that do not have docs, please add some docs for the new classes which have docs in Java.
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.
Done!