-
Notifications
You must be signed in to change notification settings - Fork 3
feat: Add support to refresh federated auth access token #46
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
tkislan
wants to merge
6
commits into
main
Choose a base branch
from
tomaskislan/support-federated-auth-token-refresh
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
Show all changes
6 commits
Select commit
Hold shift + click to select a range
c50220d
feat: Add support to refresh federated auth access token
tkislan 895e221
refactor(sql_execution): Update federated auth handling and improve t…
tkislan 66b9979
Fix typo
tkislan 8d31236
Fix federated auth key name, raise on http error
tkislan 42c90f9
Add tests for federated auth token fetch from webapp
tkislan 7fad890
Reformat code
tkislan 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
Some comments aren't visible on the classic Files Changed page.
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 |
|---|---|---|
| @@ -1,9 +1,11 @@ | ||
| import base64 | ||
| import contextlib | ||
| import json | ||
| import logging | ||
| import re | ||
| import uuid | ||
| import warnings | ||
| from typing import Any | ||
| from urllib.parse import quote | ||
|
|
||
| import google.oauth2.credentials | ||
|
|
@@ -14,6 +16,7 @@ | |
| from google.api_core.client_info import ClientInfo | ||
| from google.cloud import bigquery | ||
| from packaging.version import parse as parse_version | ||
| from pydantic import BaseModel, ValidationError | ||
| from sqlalchemy.engine import URL, create_engine, make_url | ||
| from sqlalchemy.exc import ResourceClosedError | ||
|
|
||
|
|
@@ -33,6 +36,18 @@ | |
| from deepnote_toolkit.sql.sql_utils import is_single_select_query | ||
| from deepnote_toolkit.sql.url_utils import replace_user_pass_in_pg_url | ||
|
|
||
| logger = logging.getLogger(__name__) | ||
|
|
||
|
|
||
| class IntegrationFederatedAuthParams(BaseModel): | ||
| integrationId: str | ||
| authContextToken: str | ||
|
|
||
|
|
||
| class FederatedAuthResponseData(BaseModel): | ||
| integrationType: str | ||
| accessToken: str | ||
|
|
||
|
|
||
| def compile_sql_query( | ||
| skip_jinja_template_render, | ||
|
|
@@ -242,11 +257,89 @@ def _generate_temporary_credentials(integration_id): | |
|
|
||
| response = requests.post(url, timeout=10, headers=headers) | ||
|
|
||
| response.raise_for_status() | ||
|
|
||
| data = response.json() | ||
|
|
||
| return quote(data["username"]), quote(data["password"]) | ||
|
|
||
|
|
||
| def _get_federated_auth_credentials( | ||
| integration_id: str, user_pod_auth_context_token: str | ||
| ) -> FederatedAuthResponseData: | ||
| """Get federated auth credentials for the given integration ID and user pod auth context token.""" | ||
|
|
||
| url = get_absolute_userpod_api_url( | ||
| f"integrations/federated-auth-token/{integration_id}" | ||
| ) | ||
|
|
||
| # Add project credentials in detached mode | ||
| headers = get_project_auth_headers() | ||
| headers["UserPodAuthContextToken"] = user_pod_auth_context_token | ||
|
|
||
| response = requests.post(url, timeout=10, headers=headers) | ||
|
|
||
| response.raise_for_status() | ||
|
|
||
| data = FederatedAuthResponseData.model_validate(response.json()) | ||
|
|
||
| return data | ||
|
|
||
tkislan marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| def _handle_iam_params(sql_alchemy_dict: dict[str, Any]) -> None: | ||
| """Apply IAM credentials to the connection URL in-place.""" | ||
|
|
||
| if "iamParams" not in sql_alchemy_dict: | ||
| return | ||
|
|
||
| integration_id = sql_alchemy_dict["iamParams"]["integrationId"] | ||
|
|
||
| temporary_username, temporary_password = _generate_temporary_credentials( | ||
| integration_id | ||
| ) | ||
|
|
||
| sql_alchemy_dict["url"] = replace_user_pass_in_pg_url( | ||
| sql_alchemy_dict["url"], temporary_username, temporary_password | ||
| ) | ||
|
|
||
|
|
||
| def _handle_federated_auth_params(sql_alchemy_dict: dict[str, Any]) -> None: | ||
| """Fetch and apply federated auth credentials to connection params in-place.""" | ||
|
|
||
| if "federatedAuthParams" not in sql_alchemy_dict: | ||
| return | ||
|
|
||
| try: | ||
| federated_auth_params = IntegrationFederatedAuthParams.model_validate( | ||
| sql_alchemy_dict["federatedAuthParams"] | ||
| ) | ||
| except ValidationError as e: | ||
| logger.error( | ||
| "Invalid federated auth params, try updating toolkit version:", exc_info=e | ||
| ) | ||
| return | ||
|
|
||
| federated_auth = _get_federated_auth_credentials( | ||
| federated_auth_params.integrationId, federated_auth_params.authContextToken | ||
| ) | ||
|
|
||
| if federated_auth.integrationType == "trino": | ||
| sql_alchemy_dict["params"]["connect_args"]["http_headers"][ | ||
| "Authorization" | ||
| ] = f"Bearer {federated_auth.accessToken}" | ||
| elif federated_auth.integrationType == "big-query": | ||
| sql_alchemy_dict["params"]["access_token"] = federated_auth.accessToken | ||
|
Comment on lines
+326
to
+331
Contributor
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. Missing KeyError handling for nested dict access. Lines 319-321 assume 🔎 Proposed fix if federated_auth.integrationType == "trino":
- sql_alchemy_dict["params"]["connect_args"]["http_headers"][
- "Authorization"
- ] = f"Bearer {federated_auth.accessToken}"
+ try:
+ sql_alchemy_dict["params"]["connect_args"]["http_headers"][
+ "Authorization"
+ ] = f"Bearer {federated_auth.accessToken}"
+ except KeyError:
+ logger.error(
+ "Missing required connection structure for Trino federated auth"
+ )
+ return
elif federated_auth.integrationType == "big-query":
sql_alchemy_dict["params"]["access_token"] = federated_auth.accessToken🤖 Prompt for AI Agents |
||
| elif federated_auth.integrationType == "snowflake": | ||
| logger.warning( | ||
| "Snowflake federated auth is not supported yet, using the original connection URL" | ||
| ) | ||
| else: | ||
| logger.error( | ||
| "Unsupported integration type: %s, try updating toolkit version", | ||
| federated_auth.integrationType, | ||
| ) | ||
|
|
||
|
|
||
| @contextlib.contextmanager | ||
| def _create_sql_ssh_uri(ssh_enabled, sql_alchemy_dict): | ||
| server = None | ||
|
|
@@ -346,16 +439,9 @@ def _query_data_source( | |
| ): | ||
| sshEnabled = sql_alchemy_dict.get("ssh_options", {}).get("enabled", False) | ||
|
|
||
| if "iamParams" in sql_alchemy_dict: | ||
| integration_id = sql_alchemy_dict["iamParams"]["integrationId"] | ||
| _handle_iam_params(sql_alchemy_dict) | ||
|
|
||
| temporaryUsername, temporaryPassword = _generate_temporary_credentials( | ||
| integration_id | ||
| ) | ||
|
|
||
| sql_alchemy_dict["url"] = replace_user_pass_in_pg_url( | ||
| sql_alchemy_dict["url"], temporaryUsername, temporaryPassword | ||
| ) | ||
| _handle_federated_auth_params(sql_alchemy_dict) | ||
|
|
||
| with _create_sql_ssh_uri(sshEnabled, sql_alchemy_dict) as url: | ||
| if url is None: | ||
|
|
||
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
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.
Uh oh!
There was an error while loading. Please reload this page.