- Notifications
You must be signed in to change notification settings - Fork126
Add external auth provider#101
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 ourterms of service andprivacy statement. We’ll occasionally send you account related emails.
Already on GitHub?Sign in to your account
Merged
Uh oh!
There was an error while loading.Please reload this page.
Merged
Changes fromall commits
Commits
Show all changes
6 commits Select commitHold shift + click to select a range
c963c1b add external auth provider
andrefurlan-db293b547 lint fixes
andrefurlan-dbc5d490f better example documentation
andrefurlan-dbc907dba Update examples/custom_cred_provider.py
1faa4c0 Revert "Update examples/custom_cred_provider.py"
13c2c6f Update example with pip install invocation syntax
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Uh oh!
There was an error while loading.Please reload this page.
Jump to
Jump to file
Failed to load files.
Loading
Uh oh!
There was an error while loading.Please reload this page.
Diff view
Diff view
There are no files selected for viewing
1 change: 1 addition & 0 deletionsexamples/README.md
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
29 changes: 29 additions & 0 deletionsexamples/custom_cred_provider.py
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 |
|---|---|---|
| @@ -0,0 +1,29 @@ | ||
| # please pip install databricks-sdk prior to running this example. | ||
| from databricks import sql | ||
| from databricks.sdk.oauth import OAuthClient | ||
andrefurlan-db marked this conversation as resolved. Show resolvedHide resolvedUh oh!There was an error while loading.Please reload this page. | ||
| import os | ||
| oauth_client = OAuthClient(host=os.getenv("DATABRICKS_SERVER_HOSTNAME"), | ||
| client_id=os.getenv("DATABRICKS_CLIENT_ID"), | ||
| client_secret=os.getenv("DATABRICKS_CLIENT_SECRET"), | ||
| redirect_url=os.getenv("APP_REDIRECT_URL"), | ||
| scopes=['all-apis', 'offline_access']) | ||
andrefurlan-db marked this conversation as resolved. Show resolvedHide resolvedUh oh!There was an error while loading.Please reload this page. | ||
| consent = oauth_client.initiate_consent() | ||
| creds = consent.launch_external_browser() | ||
| with sql.connect(server_hostname = os.getenv("DATABRICKS_SERVER_HOSTNAME"), | ||
| http_path = os.getenv("DATABRICKS_HTTP_PATH"), | ||
| credentials_provider=creds) as connection: | ||
| for x in range(1, 5): | ||
| cursor = connection.cursor() | ||
| cursor.execute('SELECT 1+1') | ||
| result = cursor.fetchall() | ||
| for row in result: | ||
| print(row) | ||
| cursor.close() | ||
| connection.close() | ||
6 changes: 6 additions & 0 deletionssrc/databricks/sql/auth/auth.py
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
29 changes: 28 additions & 1 deletionsrc/databricks/sql/auth/authenticators.py
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,6 +1,7 @@ | ||
| import abc | ||
| import base64 | ||
| import logging | ||
| from typing importCallable,Dict, List | ||
| from databricks.sql.auth.oauth import OAuthManager | ||
| @@ -14,6 +15,22 @@ def add_headers(self, request_headers: Dict[str, str]): | ||
| pass | ||
| HeaderFactory = Callable[[], Dict[str, str]] | ||
| # In order to keep compatibility with SDK | ||
| class CredentialsProvider(abc.ABC): | ||
| """CredentialsProvider is the protocol (call-side interface) | ||
| for authenticating requests to Databricks REST APIs""" | ||
| @abc.abstractmethod | ||
| def auth_type(self) -> str: | ||
| ... | ||
andrefurlan-db marked this conversation as resolved. Show resolvedHide resolvedUh oh!There was an error while loading.Please reload this page. | ||
| @abc.abstractmethod | ||
| def __call__(self, *args, **kwargs) -> HeaderFactory: | ||
| ... | ||
| # Private API: this is an evolving interface and it will change in the future. | ||
| # Please must not depend on it in your applications. | ||
| class AccessTokenAuthProvider(AuthProvider): | ||
| @@ -120,3 +137,13 @@ def _update_token_if_expired(self): | ||
| except Exception as e: | ||
| logging.error(f"unexpected error in oauth token update", e, exc_info=True) | ||
| raise e | ||
| class ExternalAuthProvider(AuthProvider): | ||
| def __init__(self, credentials_provider: CredentialsProvider) -> None: | ||
| self._header_factory = credentials_provider() | ||
| def add_headers(self, request_headers: Dict[str, str]): | ||
| headers = self._header_factory() | ||
| for k, v in headers.items(): | ||
| request_headers[k] = v | ||
37 changes: 36 additions & 1 deletiontests/unit/test_auth.py
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,7 +1,8 @@ | ||
| import unittest | ||
| from databricks.sql.auth.auth import AccessTokenAuthProvider, BasicAuthProvider, AuthProvider, ExternalAuthProvider | ||
| from databricks.sql.auth.auth import get_python_sql_connector_auth_provider | ||
| from databricks.sql.auth.authenticators import CredentialsProvider, HeaderFactory | ||
| class Auth(unittest.TestCase): | ||
| @@ -37,6 +38,22 @@ def test_noop_auth_provider(self): | ||
| self.assertEqual(len(http_request.keys()), 1) | ||
| self.assertEqual(http_request['myKey'], 'myVal') | ||
| def test_external_provider(self): | ||
| class MyProvider(CredentialsProvider): | ||
| def auth_type(self) -> str: | ||
| return "mine" | ||
| def __call__(self, *args, **kwargs) -> HeaderFactory: | ||
| return lambda: {"foo": "bar"} | ||
andrefurlan-db marked this conversation as resolved. Show resolvedHide resolvedUh oh!There was an error while loading.Please reload this page. | ||
| auth = ExternalAuthProvider(MyProvider()) | ||
| http_request = {'myKey': 'myVal'} | ||
| auth.add_headers(http_request) | ||
| self.assertEqual(http_request['foo'], 'bar') | ||
| self.assertEqual(len(http_request.keys()), 2) | ||
| self.assertEqual(http_request['myKey'], 'myVal') | ||
| def test_get_python_sql_connector_auth_provider_access_token(self): | ||
| hostname = "moderakh-test.cloud.databricks.com" | ||
| kwargs = {'access_token': 'dpi123'} | ||
| @@ -47,6 +64,24 @@ def test_get_python_sql_connector_auth_provider_access_token(self): | ||
| auth_provider.add_headers(headers) | ||
| self.assertEqual(headers['Authorization'], 'Bearer dpi123') | ||
| def test_get_python_sql_connector_auth_provider_external(self): | ||
| class MyProvider(CredentialsProvider): | ||
| def auth_type(self) -> str: | ||
| return "mine" | ||
| def __call__(self, *args, **kwargs) -> HeaderFactory: | ||
| return lambda: {"foo": "bar"} | ||
| hostname = "moderakh-test.cloud.databricks.com" | ||
| kwargs = {'credentials_provider': MyProvider()} | ||
| auth_provider = get_python_sql_connector_auth_provider(hostname, **kwargs) | ||
| self.assertTrue(type(auth_provider).__name__, "ExternalAuthProvider") | ||
| headers = {} | ||
| auth_provider.add_headers(headers) | ||
| self.assertEqual(headers['foo'], 'bar') | ||
| def test_get_python_sql_connector_auth_provider_username_password(self): | ||
| username = "moderakh" | ||
| password = "Elevate Databricks 123!!!" | ||
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.