-
Notifications
You must be signed in to change notification settings - Fork 163
Explicitly set the expiry time for raw token, and avoid retrying if it expires #716
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
Draft
googlyrahman
wants to merge
1
commit into
fsspec:main
Choose a base branch
from
googlyrahman:fix
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from all commits
Commits
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 hidden or 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 |
|---|---|---|
|
|
@@ -18,6 +18,7 @@ | |
| from google_auth_oauthlib.flow import InstalledAppFlow | ||
|
|
||
| from gcsfs.retry import HttpError | ||
| from gcsfs.retry import NonRetryableError | ||
|
|
||
| logger = logging.getLogger("gcsfs.credentials") | ||
|
|
||
|
|
@@ -38,6 +39,42 @@ | |
| } | ||
| } | ||
|
|
||
| TOKEN_INFO_TIMEOUT_SECONDS = 10 | ||
| LOCAL_REEFRESH_BUFFER = 300 # Greater than google.auth._helpers.REFRESH_THRESHOLD | ||
|
|
||
| def _get_creds_from_raw_token(token): | ||
| # Default to True. Only disable if user explicitly says 'false', '0', or 'off'. | ||
| env_val = os.environ.get("FETCH_RAW_TOKEN_EXPIRY", "true").lower() | ||
| should_fetch_expiry = env_val not in ("false", "0", "off", "no") | ||
|
|
||
| if should_fetch_expiry: | ||
| response = requests.get( | ||
| 'https://oauth2.googleapis.com/tokeninfo', | ||
| params={'access_token': token}, | ||
| timeout=TOKEN_INFO_TIMEOUT_SECONDS | ||
| ) | ||
|
|
||
| if response.status_code == 400: | ||
| # Token is likely expired or invalid format | ||
| raise ValueError("Provided token is either not valid, or expired.") | ||
|
|
||
| response.raise_for_status() | ||
| expiry = datetime.utcfromtimestamp(float(response.json()['exp'])) | ||
|
|
||
| time_remaining = max(0, (expiry.replace(tzinfo=timezone.utc) - datetime.now(timezone.utc)).total_seconds()) | ||
| if time_remaining <= LOCAL_REEFRESH_BUFFER: | ||
| raise ValueError( | ||
| f"The provided raw token expires in {time_remaining} seconds, " | ||
| f"which is less than the safety buffer ({LOCAL_REEFRESH_BUFFER}). " | ||
| "This may cause immediate authentication failures. " | ||
| "To bypass this check and safety buffer, you can set the environment " | ||
| "variable FETCH_RAW_TOKEN_EXPIRY=false (expiry will be unknown)." | ||
| ) | ||
| else: | ||
| expiry = None | ||
|
|
||
| return Credentials(token, expiry=expiry) | ||
|
|
||
|
|
||
| class GoogleCredentials: | ||
| def __init__(self, project, access, token, check_credentials=None, on_google=True): | ||
|
|
@@ -161,7 +198,7 @@ def _connect_token(self, token): | |
| with open(token) as data: | ||
| token = json.load(data) | ||
| else: | ||
| token = Credentials(token) | ||
| token = _get_creds_from_raw_token(token) | ||
| if isinstance(token, dict): | ||
| credentials = self._dict_to_credentials(token) | ||
| elif isinstance(token, google.auth.credentials.Credentials): | ||
|
|
@@ -190,7 +227,7 @@ def _credentials_valid(self, refresh_buffer): | |
| ) | ||
| ) | ||
|
|
||
| def maybe_refresh(self, refresh_buffer=300): | ||
| def maybe_refresh(self, refresh_buffer=LOCAL_REEFRESH_BUFFER): | ||
| """ | ||
| Check and refresh credentials if needed | ||
| """ | ||
|
|
@@ -210,6 +247,15 @@ def maybe_refresh(self, refresh_buffer=300): | |
| try: | ||
| self.credentials.refresh(req) | ||
| except gauth.exceptions.RefreshError as error: | ||
| # There may be scenarios where this error is raised from the client side due | ||
| # to missing dependencies, especially when the client doesn't know how to refresh | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Do we need to add to our dependencies? That would be better. |
||
| # or lacks the necessary information. In such cases, the request gets retried | ||
| # with backoff strategy, which can be avoided. | ||
|
|
||
| # Check for client side errors (if any) | ||
| if 'credentials do not contain the necessary fields need to refresh' in str(error): | ||
| raise NonRetryableError("Got error while refreshing credentials.") from error | ||
|
|
||
| # Re-raise as HttpError with a 401 code and the expected message | ||
| raise HttpError( | ||
| {"code": 401, "message": "Invalid Credentials"} | ||
|
|
||
This file contains hidden or 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 hidden or 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
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.
Why would we NOT attempt to refresh expired or expiring tokens?
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.
OK, maybe I understand following your description in the PR. This would need careful documentation in the RTD prose pages.