|
| 1 | +/* |
| 2 | +* Licensed to the Apache Software Foundation (ASF) under one or more |
| 3 | +* contributor license agreements. See the NOTICE file distributed with |
| 4 | +* this work for additional information regarding copyright ownership. |
| 5 | +* The ASF licenses this file to You under the Apache License, Version 2.0 |
| 6 | +* (the "License"); you may not use this file except in compliance with |
| 7 | +* the License. You may obtain a copy of the License at |
| 8 | +* |
| 9 | +* http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | +* |
| 11 | +* Unless required by applicable law or agreed to in writing, software |
| 12 | +* distributed under the License is distributed on an "AS IS" BASIS, |
| 13 | +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 14 | +* See the License for the specific language governing permissions and |
| 15 | +* limitations under the License. |
| 16 | +*/ |
| 17 | + |
| 18 | +using System; |
| 19 | +using System.Net.Http; |
| 20 | +using System.Net.Http.Headers; |
| 21 | +using System.Threading; |
| 22 | +using System.Threading.Tasks; |
| 23 | + |
| 24 | +namespace Apache.Arrow.Adbc.Drivers.Databricks.Auth |
| 25 | +{ |
| 26 | + /// <summary> |
| 27 | + /// HTTP message handler that performs mandatory token exchange for non-Databricks tokens. |
| 28 | + /// Uses a non-blocking approach to exchange tokens in the background. |
| 29 | + /// </summary> |
| 30 | + internal class MandatoryTokenExchangeDelegatingHandler : DelegatingHandler |
| 31 | + { |
| 32 | + private readonly string? _identityFederationClientId; |
| 33 | + private readonly object _tokenLock = new object(); |
| 34 | + private readonly ITokenExchangeClient _tokenExchangeClient; |
| 35 | + private string? _currentToken; |
| 36 | + private string? _lastSeenToken; |
| 37 | + |
| 38 | + protected Task? _pendingTokenTask = null; |
| 39 | + |
| 40 | + /// <summary> |
| 41 | + /// Initializes a new instance of the <see cref="MandatoryTokenExchangeDelegatingHandler"/> class. |
| 42 | + /// </summary> |
| 43 | + /// <param name="innerHandler">The inner handler to delegate to.</param> |
| 44 | + /// <param name="tokenExchangeClient">The client for token exchange operations.</param> |
| 45 | + /// <param name="identityFederationClientId">Optional identity federation client ID.</param> |
| 46 | + public MandatoryTokenExchangeDelegatingHandler( |
| 47 | + HttpMessageHandler innerHandler, |
| 48 | + ITokenExchangeClient tokenExchangeClient, |
| 49 | + string? identityFederationClientId = null) |
| 50 | + : base(innerHandler) |
| 51 | + { |
| 52 | + _tokenExchangeClient = tokenExchangeClient ?? throw new ArgumentNullException(nameof(tokenExchangeClient)); |
| 53 | + _identityFederationClientId = identityFederationClientId; |
| 54 | + } |
| 55 | + |
| 56 | + /// <summary> |
| 57 | + /// Determines if token exchange is needed by checking if the token is a Databricks token. |
| 58 | + /// </summary> |
| 59 | + /// <returns>True if token exchange is needed, false otherwise.</returns> |
| 60 | + private bool NeedsTokenExchange(string bearerToken) |
| 61 | + { |
| 62 | + // If we already started exchange for this token, no need to check again |
| 63 | + if (_lastSeenToken == bearerToken) |
| 64 | + { |
| 65 | + return false; |
| 66 | + } |
| 67 | + |
| 68 | + // If we already have a pending token task, don't start another exchange |
| 69 | + if (_pendingTokenTask != null) |
| 70 | + { |
| 71 | + return false; |
| 72 | + } |
| 73 | + |
| 74 | + // If we can't parse the token as JWT, default to use existing token |
| 75 | + if (!JwtTokenDecoder.TryGetIssuer(bearerToken, out string issuer)) |
| 76 | + { |
| 77 | + return false; |
| 78 | + } |
| 79 | + |
| 80 | + // Check if the issuer matches the current workspace host |
| 81 | + // If the issuer is from the same host, it's already a Databricks token |
| 82 | + string normalizedHost = _tokenExchangeClient.TokenExchangeEndpoint.Replace("/v1/token", "").ToLowerInvariant(); |
| 83 | + string normalizedIssuer = issuer.TrimEnd('/').ToLowerInvariant(); |
| 84 | + |
| 85 | + return normalizedIssuer != normalizedHost; |
| 86 | + } |
| 87 | + |
| 88 | + /// <summary> |
| 89 | + /// Starts token exchange in the background if needed. |
| 90 | + /// </summary> |
| 91 | + /// <param name="bearerToken">The bearer token to potentially exchange.</param> |
| 92 | + /// <param name="cancellationToken">A cancellation token.</param> |
| 93 | + private void StartTokenExchangeIfNeeded(string bearerToken, CancellationToken cancellationToken) |
| 94 | + { |
| 95 | + if (_lastSeenToken == bearerToken) |
| 96 | + { |
| 97 | + return; |
| 98 | + } |
| 99 | + |
| 100 | + bool needsExchange; |
| 101 | + lock (_tokenLock) |
| 102 | + { |
| 103 | + needsExchange = NeedsTokenExchange(bearerToken); |
| 104 | + |
| 105 | + _lastSeenToken = bearerToken; |
| 106 | + } |
| 107 | + |
| 108 | + if (!needsExchange) |
| 109 | + { |
| 110 | + return; |
| 111 | + } |
| 112 | + |
| 113 | + // Start token exchange in the background |
| 114 | + _pendingTokenTask = Task.Run(async () => |
| 115 | + { |
| 116 | + try |
| 117 | + { |
| 118 | + TokenExchangeResponse response = await _tokenExchangeClient.ExchangeTokenAsync( |
| 119 | + bearerToken, |
| 120 | + _identityFederationClientId, |
| 121 | + cancellationToken); |
| 122 | + |
| 123 | + lock (_tokenLock) |
| 124 | + { |
| 125 | + _currentToken = response.AccessToken; |
| 126 | + } |
| 127 | + } |
| 128 | + catch (Exception ex) |
| 129 | + { |
| 130 | + System.Diagnostics.Debug.WriteLine($"Mandatory token exchange failed: {ex.Message}"); |
| 131 | + } |
| 132 | + }, cancellationToken).ContinueWith(_ => |
| 133 | + { |
| 134 | + lock (_tokenLock) |
| 135 | + { |
| 136 | + _pendingTokenTask = null; |
| 137 | + } |
| 138 | + }, TaskScheduler.Default); |
| 139 | + } |
| 140 | + |
| 141 | + /// <summary> |
| 142 | + /// Sends an HTTP request with the current token. |
| 143 | + /// </summary> |
| 144 | + /// <param name="request">The HTTP request message to send.</param> |
| 145 | + /// <param name="cancellationToken">A cancellation token.</param> |
| 146 | + /// <returns>The HTTP response message.</returns> |
| 147 | + protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) |
| 148 | + { |
| 149 | + string? bearerToken = request.Headers.Authorization?.Parameter; |
| 150 | + if (!string.IsNullOrEmpty(bearerToken)) |
| 151 | + { |
| 152 | + StartTokenExchangeIfNeeded(bearerToken!, cancellationToken); |
| 153 | + |
| 154 | + string tokenToUse; |
| 155 | + lock (_tokenLock) |
| 156 | + { |
| 157 | + tokenToUse = _currentToken ?? bearerToken!; |
| 158 | + } |
| 159 | + |
| 160 | + request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", tokenToUse); |
| 161 | + } |
| 162 | + |
| 163 | + return await base.SendAsync(request, cancellationToken); |
| 164 | + } |
| 165 | + |
| 166 | + protected override void Dispose(bool disposing) |
| 167 | + { |
| 168 | + if (disposing) |
| 169 | + { |
| 170 | + // Wait for any pending token task to complete to avoid leaking tasks |
| 171 | + if (_pendingTokenTask != null) |
| 172 | + { |
| 173 | + try |
| 174 | + { |
| 175 | + // Try to wait for the task to complete, but don't block indefinitely |
| 176 | + _pendingTokenTask.Wait(TimeSpan.FromSeconds(10)); |
| 177 | + } |
| 178 | + catch (Exception ex) |
| 179 | + { |
| 180 | + // Log any exceptions during disposal |
| 181 | + System.Diagnostics.Debug.WriteLine($"Exception during token task cleanup: {ex.Message}"); |
| 182 | + } |
| 183 | + } |
| 184 | + } |
| 185 | + |
| 186 | + base.Dispose(disposing); |
| 187 | + } |
| 188 | + } |
| 189 | +} |
0 commit comments