|
| 1 | +import logging |
| 2 | +import json |
| 3 | +from datetime import datetime, timedelta |
| 4 | +from typing import Optional, Dict, Tuple |
| 5 | +from urllib.parse import urlencode |
| 6 | + |
| 7 | +from databricks.sql.auth.authenticators import AuthProvider |
| 8 | +from databricks.sql.auth.auth_utils import ( |
| 9 | + parse_hostname, |
| 10 | + decode_token, |
| 11 | + is_same_host, |
| 12 | +) |
| 13 | +from databricks.sql.common.http import HttpMethod |
| 14 | + |
| 15 | +logger = logging.getLogger(__name__) |
| 16 | + |
| 17 | + |
| 18 | +class Token: |
| 19 | + """ |
| 20 | + Represents an OAuth token with expiration management. |
| 21 | + """ |
| 22 | + |
| 23 | + def __init__(self, access_token: str, token_type: str = "Bearer"): |
| 24 | + """ |
| 25 | + Initialize a token. |
| 26 | +
|
| 27 | + Args: |
| 28 | + access_token: The access token string |
| 29 | + token_type: The token type (default: Bearer) |
| 30 | + """ |
| 31 | + self.access_token = access_token |
| 32 | + self.token_type = token_type |
| 33 | + self.expiry_time = self._calculate_expiry() |
| 34 | + |
| 35 | + def _calculate_expiry(self) -> datetime: |
| 36 | + """ |
| 37 | + Calculate the token expiry time from JWT claims. |
| 38 | +
|
| 39 | + Returns: |
| 40 | + The token expiry datetime |
| 41 | + """ |
| 42 | + decoded = decode_token(self.access_token) |
| 43 | + if decoded and "exp" in decoded: |
| 44 | + # Use JWT exp claim with 1 minute buffer |
| 45 | + return datetime.fromtimestamp(decoded["exp"]) - timedelta(minutes=1) |
| 46 | + # Default to 1 hour if no expiry info |
| 47 | + return datetime.now() + timedelta(hours=1) |
| 48 | + |
| 49 | + def is_expired(self) -> bool: |
| 50 | + """ |
| 51 | + Check if the token is expired. |
| 52 | +
|
| 53 | + Returns: |
| 54 | + True if token is expired, False otherwise |
| 55 | + """ |
| 56 | + return datetime.now() >= self.expiry_time |
| 57 | + |
| 58 | + def to_dict(self) -> Dict[str, str]: |
| 59 | + """ |
| 60 | + Convert token to dictionary format. |
| 61 | +
|
| 62 | + Returns: |
| 63 | + Dictionary with access_token and token_type |
| 64 | + """ |
| 65 | + return { |
| 66 | + "access_token": self.access_token, |
| 67 | + "token_type": self.token_type, |
| 68 | + } |
| 69 | + |
| 70 | + |
| 71 | +class TokenFederationProvider(AuthProvider): |
| 72 | + """ |
| 73 | + Implementation of Token Federation for Databricks SQL Python driver. |
| 74 | +
|
| 75 | + This provider exchanges third-party access tokens for Databricks in-house tokens |
| 76 | + when the token issuer is different from the Databricks host. |
| 77 | + """ |
| 78 | + |
| 79 | + TOKEN_EXCHANGE_ENDPOINT = "/oidc/v1/token" |
| 80 | + TOKEN_EXCHANGE_GRANT_TYPE = "urn:ietf:params:oauth:grant-type:token-exchange" |
| 81 | + TOKEN_EXCHANGE_SUBJECT_TYPE = "urn:ietf:params:oauth:token-type:jwt" |
| 82 | + |
| 83 | + def __init__( |
| 84 | + self, |
| 85 | + hostname: str, |
| 86 | + external_provider: AuthProvider, |
| 87 | + http_client, |
| 88 | + identity_federation_client_id: Optional[str] = None, |
| 89 | + ): |
| 90 | + """ |
| 91 | + Initialize the Token Federation Provider. |
| 92 | +
|
| 93 | + Args: |
| 94 | + hostname: The Databricks workspace hostname |
| 95 | + external_provider: The external authentication provider |
| 96 | + http_client: HTTP client for making requests (required) |
| 97 | + identity_federation_client_id: Optional client ID for token federation |
| 98 | + """ |
| 99 | + if not http_client: |
| 100 | + raise ValueError("http_client is required for TokenFederationProvider") |
| 101 | + |
| 102 | + self.hostname = parse_hostname(hostname) |
| 103 | + self.external_provider = external_provider |
| 104 | + self.http_client = http_client |
| 105 | + self.identity_federation_client_id = identity_federation_client_id |
| 106 | + |
| 107 | + self._cached_token: Optional[Token] = None |
| 108 | + self._external_headers: Dict[str, str] = {} |
| 109 | + |
| 110 | + def add_headers(self, request_headers: Dict[str, str]): |
| 111 | + """Add authentication headers to the request.""" |
| 112 | + |
| 113 | + if self._cached_token and not self._cached_token.is_expired(): |
| 114 | + request_headers[ |
| 115 | + "Authorization" |
| 116 | + ] = f"{self._cached_token.token_type} {self._cached_token.access_token}" |
| 117 | + return |
| 118 | + |
| 119 | + # Get the external headers first to check if we need token federation |
| 120 | + self._external_headers = {} |
| 121 | + self.external_provider.add_headers(self._external_headers) |
| 122 | + |
| 123 | + # If no Authorization header from external provider, pass through all headers |
| 124 | + if "Authorization" not in self._external_headers: |
| 125 | + request_headers.update(self._external_headers) |
| 126 | + return |
| 127 | + |
| 128 | + token = self._get_token() |
| 129 | + request_headers["Authorization"] = f"{token.token_type} {token.access_token}" |
| 130 | + |
| 131 | + def _get_token(self) -> Token: |
| 132 | + """Get or refresh the authentication token.""" |
| 133 | + # Check if cached token is still valid |
| 134 | + if self._cached_token and not self._cached_token.is_expired(): |
| 135 | + return self._cached_token |
| 136 | + |
| 137 | + # Extract token from already-fetched headers |
| 138 | + auth_header = self._external_headers.get("Authorization", "") |
| 139 | + token_type, access_token = self._extract_token_from_header(auth_header) |
| 140 | + |
| 141 | + # Check if token exchange is needed |
| 142 | + if self._should_exchange_token(access_token): |
| 143 | + try: |
| 144 | + token = self._exchange_token(access_token) |
| 145 | + self._cached_token = token |
| 146 | + return token |
| 147 | + except Exception as e: |
| 148 | + logger.warning("Token exchange failed, using external token: %s", e) |
| 149 | + |
| 150 | + # Use external token directly |
| 151 | + token = Token(access_token, token_type) |
| 152 | + self._cached_token = token |
| 153 | + return token |
| 154 | + |
| 155 | + def _should_exchange_token(self, access_token: str) -> bool: |
| 156 | + """Check if the token should be exchanged based on issuer.""" |
| 157 | + decoded = decode_token(access_token) |
| 158 | + if not decoded: |
| 159 | + return False |
| 160 | + |
| 161 | + issuer = decoded.get("iss", "") |
| 162 | + # Check if issuer host is different from Databricks host |
| 163 | + return not is_same_host(issuer, self.hostname) |
| 164 | + |
| 165 | + def _exchange_token(self, access_token: str) -> Token: |
| 166 | + """Exchange the external token for a Databricks token.""" |
| 167 | + token_url = f"{self.hostname.rstrip('/')}{self.TOKEN_EXCHANGE_ENDPOINT}" |
| 168 | + |
| 169 | + data = { |
| 170 | + "grant_type": self.TOKEN_EXCHANGE_GRANT_TYPE, |
| 171 | + "subject_token": access_token, |
| 172 | + "subject_token_type": self.TOKEN_EXCHANGE_SUBJECT_TYPE, |
| 173 | + "scope": "sql", |
| 174 | + "return_original_token_if_authenticated": "true", |
| 175 | + } |
| 176 | + |
| 177 | + if self.identity_federation_client_id: |
| 178 | + data["client_id"] = self.identity_federation_client_id |
| 179 | + |
| 180 | + headers = { |
| 181 | + "Content-Type": "application/x-www-form-urlencoded", |
| 182 | + "Accept": "*/*", |
| 183 | + } |
| 184 | + |
| 185 | + body = urlencode(data) |
| 186 | + |
| 187 | + response = self.http_client.request( |
| 188 | + HttpMethod.POST, url=token_url, body=body, headers=headers |
| 189 | + ) |
| 190 | + |
| 191 | + token_response = json.loads(response.data.decode()) |
| 192 | + |
| 193 | + return Token( |
| 194 | + token_response["access_token"], token_response.get("token_type", "Bearer") |
| 195 | + ) |
| 196 | + |
| 197 | + def _extract_token_from_header(self, auth_header: str) -> Tuple[str, str]: |
| 198 | + """Extract token type and access token from Authorization header.""" |
| 199 | + if not auth_header: |
| 200 | + raise ValueError("Authorization header is missing") |
| 201 | + |
| 202 | + parts = auth_header.split(" ", 1) |
| 203 | + if len(parts) != 2: |
| 204 | + raise ValueError("Invalid Authorization header format") |
| 205 | + |
| 206 | + return parts[0], parts[1] |
0 commit comments