Skip to content

Commit 8de985d

Browse files
[Internal] Add DataPlane token source (#897)
## What changes are proposed in this pull request? Add DataPlane token source using the new async refresh mechanism. This first version has async disabled. ## How is this tested? Added unit tests NO_CHANGELOG=true This is not yet used.
1 parent 8740bf8 commit 8de985d

File tree

3 files changed

+163
-1
lines changed

3 files changed

+163
-1
lines changed

databricks/sdk/data_plane.py

Lines changed: 77 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,82 @@
1+
from __future__ import annotations
2+
13
import threading
24
from dataclasses import dataclass
3-
from typing import Callable, List
5+
from typing import Callable, List, Optional
6+
from urllib import parse
47

8+
from databricks.sdk import oauth
59
from databricks.sdk.oauth import Token
610

11+
URL_ENCODED_CONTENT_TYPE = "application/x-www-form-urlencoded"
12+
JWT_BEARER_GRANT_TYPE = "urn:ietf:params:oauth:grant-type:jwt-bearer"
13+
OIDC_TOKEN_PATH = "/oidc/v1/token"
14+
15+
16+
class DataPlaneTokenSource:
17+
"""
18+
EXPERIMENTAL Manages token sources for multiple DataPlane endpoints.
19+
"""
20+
21+
# TODO: Enable async once its stable. @oauth_credentials_provider must also have async enabled.
22+
def __init__(self, token_exchange_host: str, cpts: Callable[[], Token], disable_async: Optional[bool] = True):
23+
self._cpts = cpts
24+
self._token_exchange_host = token_exchange_host
25+
self._token_sources = {}
26+
self._disable_async = disable_async
27+
self._lock = threading.Lock()
28+
29+
def token(self, endpoint, auth_details):
30+
key = f"{endpoint}:{auth_details}"
31+
32+
# First, try to read without acquiring the lock to avoid contention.
33+
# Reads are atomic, so this is safe.
34+
token_source = self._token_sources.get(key)
35+
if token_source:
36+
return token_source.token()
37+
38+
# If token_source is not found, acquire the lock and check again.
39+
with self._lock:
40+
# Another thread might have created it while we were waiting for the lock.
41+
token_source = self._token_sources.get(key)
42+
if not token_source:
43+
token_source = DataPlaneEndpointTokenSource(
44+
self._token_exchange_host, self._cpts, auth_details, self._disable_async
45+
)
46+
self._token_sources[key] = token_source
47+
48+
return token_source.token()
49+
50+
51+
class DataPlaneEndpointTokenSource(oauth.Refreshable):
52+
"""
53+
EXPERIMENTAL A token source for a specific DataPlane endpoint.
54+
"""
55+
56+
def __init__(self, token_exchange_host: str, cpts: Callable[[], Token], auth_details: str, disable_async: bool):
57+
super().__init__(disable_async=disable_async)
58+
self._auth_details = auth_details
59+
self._cpts = cpts
60+
self._token_exchange_host = token_exchange_host
61+
62+
def refresh(self) -> Token:
63+
control_plane_token = self._cpts()
64+
headers = {"Content-Type": URL_ENCODED_CONTENT_TYPE}
65+
params = parse.urlencode(
66+
{
67+
"grant_type": JWT_BEARER_GRANT_TYPE,
68+
"authorization_details": self._auth_details,
69+
"assertion": control_plane_token.access_token,
70+
}
71+
)
72+
return oauth.retrieve_token(
73+
client_id="",
74+
client_secret="",
75+
token_url=self._token_exchange_host + OIDC_TOKEN_PATH,
76+
params=params,
77+
headers=headers,
78+
)
79+
780

881
@dataclass
982
class DataPlaneDetails:
@@ -17,6 +90,9 @@ class DataPlaneDetails:
1790
"""Token to query the DataPlane endpoint."""
1891

1992

93+
## Old implementation. #TODO: Remove after the new implementation is used
94+
95+
2096
class DataPlaneService:
2197
"""Helper class to fetch and manage DataPlane details."""
2298

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
from databricks.sdk.data_plane import DataPlaneTokenSource
2+
3+
4+
def test_data_plane_token_source(ucws, env_or_skip):
5+
endpoint = env_or_skip("SERVING_ENDPOINT_NAME")
6+
serving_endpoint = ucws.serving_endpoints.get(endpoint)
7+
assert serving_endpoint.data_plane_info is not None
8+
assert serving_endpoint.data_plane_info.query_info is not None
9+
10+
info = serving_endpoint.data_plane_info.query_info
11+
12+
ts = DataPlaneTokenSource(ucws.config.host, ucws._config.oauth_token)
13+
dp_token = ts.token(info.endpoint_url, info.authorization_details)
14+
15+
assert dp_token.valid

tests/test_data_plane.py

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,80 @@
11
from datetime import datetime, timedelta
2+
from unittest.mock import patch
3+
from urllib import parse
24

5+
from databricks.sdk import data_plane, oauth
36
from databricks.sdk.data_plane import DataPlaneService
47
from databricks.sdk.oauth import Token
58
from databricks.sdk.service.serving import DataPlaneInfo
69

10+
cp_token = Token(access_token="control plane token", token_type="type", expiry=datetime.now() + timedelta(hours=1))
11+
dp_token = Token(access_token="data plane token", token_type="type", expiry=datetime.now() + timedelta(hours=1))
12+
13+
14+
def success_callable(token: oauth.Token):
15+
16+
def success() -> oauth.Token:
17+
return token
18+
19+
return success
20+
21+
22+
def test_endpoint_token_source_get_token(config):
23+
token_source = data_plane.DataPlaneEndpointTokenSource(
24+
config.host, success_callable(cp_token), "authDetails", disable_async=True
25+
)
26+
27+
with patch("databricks.sdk.oauth.retrieve_token", return_value=dp_token) as retrieve_token:
28+
token_source.token()
29+
30+
retrieve_token.assert_called_once()
31+
args, kwargs = retrieve_token.call_args
32+
33+
assert kwargs["token_url"] == config.host + "/oidc/v1/token"
34+
assert kwargs["params"] == parse.urlencode(
35+
{
36+
"grant_type": "urn:ietf:params:oauth:grant-type:jwt-bearer",
37+
"authorization_details": "authDetails",
38+
"assertion": cp_token.access_token,
39+
}
40+
)
41+
assert kwargs["headers"] == {"Content-Type": "application/x-www-form-urlencoded"}
42+
43+
44+
def test_token_source_get_token_not_existing(config):
45+
token_source = data_plane.DataPlaneTokenSource(config.host, success_callable(cp_token), disable_async=True)
46+
47+
with patch("databricks.sdk.oauth.retrieve_token", return_value=dp_token) as retrieve_token:
48+
result_token = token_source.token(endpoint="endpoint", auth_details="authDetails")
49+
50+
retrieve_token.assert_called_once()
51+
assert result_token.access_token == dp_token.access_token
52+
assert "endpoint:authDetails" in token_source._token_sources
53+
54+
55+
class MockEndpointTokenSource:
56+
57+
def __init__(self, token: oauth.Token):
58+
self._token = token
59+
60+
def token(self):
61+
return self._token
62+
63+
64+
def test_token_source_get_token_existing(config):
65+
another_token = Token(access_token="another token", token_type="type", expiry=datetime.now() + timedelta(hours=1))
66+
token_source = data_plane.DataPlaneTokenSource(config.host, success_callable(token), disable_async=True)
67+
token_source._token_sources["endpoint:authDetails"] = MockEndpointTokenSource(another_token)
68+
69+
with patch("databricks.sdk.oauth.retrieve_token", return_value=dp_token) as retrieve_token:
70+
result_token = token_source.token(endpoint="endpoint", auth_details="authDetails")
71+
72+
retrieve_token.assert_not_called()
73+
assert result_token.access_token == another_token.access_token
74+
75+
76+
## These tests are for the old implementation. #TODO: Remove after the new implementation is used
77+
778
info = DataPlaneInfo(authorization_details="authDetails", endpoint_url="url")
879

980
token = Token(

0 commit comments

Comments
 (0)