-
Notifications
You must be signed in to change notification settings - Fork 527
Expand file tree
/
Copy pathTokenCredentialCache.cs
More file actions
379 lines (324 loc) · 17.5 KB
/
TokenCredentialCache.cs
File metadata and controls
379 lines (324 loc) · 17.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
#nullable enable
namespace Microsoft.Azure.Cosmos
{
using System;
using System.Globalization;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using global::Azure;
using global::Azure.Core;
using Microsoft.Azure.Cosmos.Authorization;
using Microsoft.Azure.Cosmos.Core.Trace;
using Microsoft.Azure.Cosmos.Resource.CosmosExceptions;
using Microsoft.Azure.Cosmos.Tracing;
using Microsoft.Azure.Documents;
/// <summary>
/// This is a token credential cache.
/// It starts a background task that refreshes the token at a set interval.
/// This way refreshing the token does not cause additional latency and also
/// allows for transient issue to resolve before the token expires.
/// </summary>
internal sealed class TokenCredentialCache : IDisposable
{
// Default token expiration time is 1hr.
// Making the default 50% of the token life span. This gives 50% of the tokens life for transient error
// to get resolved before the token expires.
public static readonly double DefaultBackgroundTokenCredentialRefreshIntervalPercentage = .50;
// The maximum time a task delayed is allowed is Int32.MaxValue in Milliseconds which is roughly 24 days
public static readonly TimeSpan MaxBackgroundRefreshInterval = TimeSpan.FromMilliseconds(int.MaxValue);
// The token refresh retries half the time. Given default of 1hr it will retry at 30m, 15, 7.5, 3.75, 1.875
// If the background refresh fails with less than a minute then just allow the request to hit the exception.
public static readonly TimeSpan MinimumTimeBetweenBackgroundRefreshInterval = TimeSpan.FromMinutes(1);
private readonly IScopeProvider scopeProvider;
private readonly TokenCredential tokenCredential;
private readonly CancellationTokenSource cancellationTokenSource;
private readonly CancellationToken cancellationToken;
private readonly TimeSpan? userDefinedBackgroundTokenCredentialRefreshInterval;
private readonly SemaphoreSlim isTokenRefreshingLock = new SemaphoreSlim(1);
private readonly object backgroundRefreshLock = new object();
private TimeSpan? systemBackgroundTokenCredentialRefreshInterval;
private Task<AccessToken>? currentRefreshOperation = null;
private AccessToken? cachedAccessToken = null;
private bool isBackgroundTaskRunning = false;
private bool isDisposed = false;
internal TokenCredentialCache(
TokenCredential tokenCredential,
Uri accountEndpoint,
TimeSpan? backgroundTokenCredentialRefreshInterval)
{
this.tokenCredential = tokenCredential ?? throw new ArgumentNullException(nameof(tokenCredential));
if (accountEndpoint == null)
{
throw new ArgumentNullException(nameof(accountEndpoint));
}
this.scopeProvider = new Microsoft.Azure.Cosmos.Authorization.CosmosScopeProvider(accountEndpoint);
if (backgroundTokenCredentialRefreshInterval.HasValue)
{
if (backgroundTokenCredentialRefreshInterval.Value <= TimeSpan.Zero)
{
throw new ArgumentException($"{nameof(backgroundTokenCredentialRefreshInterval)} must be a positive value greater than 0. Value '{backgroundTokenCredentialRefreshInterval.Value.TotalMilliseconds}'.");
}
// TimeSpan.MaxValue disables the background refresh
if (backgroundTokenCredentialRefreshInterval.Value > TokenCredentialCache.MaxBackgroundRefreshInterval &&
backgroundTokenCredentialRefreshInterval.Value != TimeSpan.MaxValue)
{
throw new ArgumentException($"{nameof(backgroundTokenCredentialRefreshInterval)} must be less than or equal to {TokenCredentialCache.MaxBackgroundRefreshInterval}. Value '{backgroundTokenCredentialRefreshInterval.Value}'.");
}
}
this.userDefinedBackgroundTokenCredentialRefreshInterval = backgroundTokenCredentialRefreshInterval;
this.cancellationTokenSource = new CancellationTokenSource();
this.cancellationToken = this.cancellationTokenSource.Token;
}
public TimeSpan? BackgroundTokenCredentialRefreshInterval =>
this.userDefinedBackgroundTokenCredentialRefreshInterval ?? this.systemBackgroundTokenCredentialRefreshInterval;
internal async ValueTask<string> GetTokenAsync(ITrace trace)
{
if (this.isDisposed)
{
throw new ObjectDisposedException("TokenCredentialCache");
}
// Use the cached token if it is still valid
if (this.cachedAccessToken.HasValue &&
DateTime.UtcNow < this.cachedAccessToken.Value.ExpiresOn)
{
return this.cachedAccessToken.Value.Token;
}
AccessToken accessToken = await this.GetNewTokenAsync(trace);
if (!this.isBackgroundTaskRunning)
{
// This is a background thread so no need to await
Task backgroundThread = Task.Run(this.StartBackgroundTokenRefreshLoop);
}
return accessToken.Token;
}
public void Dispose()
{
if (this.isDisposed)
{
return;
}
this.cancellationTokenSource.Cancel();
this.cancellationTokenSource.Dispose();
this.isDisposed = true;
}
private async Task<AccessToken> GetNewTokenAsync(
ITrace trace)
{
// Use a local variable to avoid the possibility the task gets changed
// between the null check and the await operation.
Task<AccessToken>? currentTask = this.currentRefreshOperation;
if (currentTask != null)
{
// The refresh is already occurring wait on the existing task
return await currentTask;
}
try
{
await this.isTokenRefreshingLock.WaitAsync();
// avoid doing the await in the semaphore to unblock the parallel requests
if (this.currentRefreshOperation == null)
{
// ValueTask can not be awaited multiple times
currentTask = this.RefreshCachedTokenWithRetryHelperAsync(trace).AsTask();
this.currentRefreshOperation = currentTask;
}
else
{
currentTask = this.currentRefreshOperation;
}
}
finally
{
this.isTokenRefreshingLock.Release();
}
return await currentTask;
}
private async ValueTask<AccessToken> RefreshCachedTokenWithRetryHelperAsync(
ITrace trace)
{
try
{
Exception? lastException = null;
const int totalRetryCount = 2;
TokenRequestContext tokenRequestContext = default;
for (int retry = 0; retry < totalRetryCount; retry++)
{
if (this.cancellationToken.IsCancellationRequested)
{
DefaultTrace.TraceInformation(
"Stop RefreshTokenWithIndefiniteRetries because cancellation is requested");
break;
}
using (ITrace getTokenTrace = trace.StartChild(
name: nameof(this.RefreshCachedTokenWithRetryHelperAsync),
component: TraceComponent.Authorization,
level: Tracing.TraceLevel.Info))
{
try
{
tokenRequestContext = this.scopeProvider.GetTokenRequestContext();
this.cachedAccessToken = await this.tokenCredential.GetTokenAsync(
requestContext: tokenRequestContext,
cancellationToken: this.cancellationToken);
if (!this.cachedAccessToken.HasValue)
{
throw new ArgumentNullException("TokenCredential.GetTokenAsync returned a null token.");
}
if (this.cachedAccessToken.Value.ExpiresOn < DateTimeOffset.UtcNow)
{
throw new ArgumentOutOfRangeException($"TokenCredential.GetTokenAsync returned a token that is already expired. Current Time:{DateTime.UtcNow:O}; Token expire time:{this.cachedAccessToken.Value.ExpiresOn:O}");
}
if (!this.userDefinedBackgroundTokenCredentialRefreshInterval.HasValue)
{
double refreshIntervalInSeconds = (this.cachedAccessToken.Value.ExpiresOn - DateTimeOffset.UtcNow).TotalSeconds * DefaultBackgroundTokenCredentialRefreshIntervalPercentage;
// Ensure the background refresh interval is a valid range.
refreshIntervalInSeconds = Math.Max(refreshIntervalInSeconds, TokenCredentialCache.MinimumTimeBetweenBackgroundRefreshInterval.TotalSeconds);
refreshIntervalInSeconds = Math.Min(refreshIntervalInSeconds, TokenCredentialCache.MaxBackgroundRefreshInterval.TotalSeconds);
this.systemBackgroundTokenCredentialRefreshInterval = TimeSpan.FromSeconds(refreshIntervalInSeconds);
}
return this.cachedAccessToken.Value;
}
catch (RequestFailedException requestFailedException)
{
lastException = requestFailedException;
getTokenTrace.AddDatum(
$"RequestFailedException at {DateTime.UtcNow.ToString(CultureInfo.InvariantCulture)}",
requestFailedException.Message);
DefaultTrace.TraceError($"TokenCredential.GetToken() failed with RequestFailedException. scope = {string.Join(";", tokenRequestContext.Scopes ?? Array.Empty<string>())}, retry = {retry}, Exception = {lastException.Message}");
// Don't retry on auth failures
if (requestFailedException.Status == (int)HttpStatusCode.Unauthorized ||
requestFailedException.Status == (int)HttpStatusCode.Forbidden)
{
this.cachedAccessToken = default;
throw;
}
// Fallback logic
if (this.scopeProvider.TryFallback(requestFailedException))
{
continue;
}
}
catch (OperationCanceledException operationCancelled)
{
lastException = operationCancelled;
getTokenTrace.AddDatum(
$"OperationCanceledException at {DateTime.UtcNow.ToString(CultureInfo.InvariantCulture)}",
operationCancelled.Message);
DefaultTrace.TraceError(
$"TokenCredential.GetTokenAsync() failed. scope = {string.Join(";", tokenRequestContext.Scopes ?? Array.Empty<string>())}, retry = {retry}, Exception = {lastException.Message}");
throw CosmosExceptionFactory.CreateRequestTimeoutException(
message: ClientResources.FailedToGetAadToken,
headers: new Headers()
{
SubStatusCode = SubStatusCodes.FailedToGetAadToken,
},
innerException: lastException,
trace: getTokenTrace);
}
catch (Exception exception)
{
lastException = exception;
getTokenTrace.AddDatum(
$"Exception at {DateTime.UtcNow.ToString(CultureInfo.InvariantCulture)}",
exception.Message);
DefaultTrace.TraceError(
$"TokenCredential.GetTokenAsync() failed. scope = {string.Join(";", tokenRequestContext.Scopes ?? Array.Empty<string>())}, retry = {retry}, Exception = {lastException.Message}");
// Fallback logic
if (this.scopeProvider.TryFallback(exception))
{
continue;
}
}
}
}
if (lastException == null)
{
throw new ArgumentException("Last exception is null.");
}
// The retries have been exhausted. Throw the last exception.
throw lastException;
}
finally
{
try
{
await this.isTokenRefreshingLock.WaitAsync();
this.currentRefreshOperation = null;
}
finally
{
this.isTokenRefreshingLock.Release();
}
}
}
#pragma warning disable VSTHRD100 // Avoid async void methods
private async void StartBackgroundTokenRefreshLoop()
#pragma warning restore VSTHRD100 // Avoid async void methods
{
if (this.isBackgroundTaskRunning)
{
return;
}
lock (this.backgroundRefreshLock)
{
if (this.isBackgroundTaskRunning)
{
return;
}
this.isBackgroundTaskRunning = true;
}
while (!this.cancellationTokenSource.IsCancellationRequested)
{
try
{
if (!this.BackgroundTokenCredentialRefreshInterval.HasValue)
{
throw new ArgumentException(nameof(this.BackgroundTokenCredentialRefreshInterval));
}
// Stop the background refresh if the interval is greater than Task.Delay allows.
if (this.BackgroundTokenCredentialRefreshInterval.Value > TokenCredentialCache.MaxBackgroundRefreshInterval)
{
DefaultTrace.TraceWarning(
"BackgroundTokenRefreshLoop() Stopped - The BackgroundTokenCredentialRefreshInterval is {0} which is greater than the maximum allow.",
this.BackgroundTokenCredentialRefreshInterval.Value);
return;
}
await Task.Delay(this.BackgroundTokenCredentialRefreshInterval.Value, this.cancellationToken);
DefaultTrace.TraceInformation("BackgroundTokenRefreshLoop() - Invoking refresh");
await this.GetNewTokenAsync(Tracing.Trace.GetRootTrace("TokenCredentialCacheBackground refresh"));
}
catch (Exception ex)
{
if (this.cancellationTokenSource.IsCancellationRequested &&
(ex is OperationCanceledException || ex is ObjectDisposedException))
{
return;
}
DefaultTrace.TraceWarning(
"BackgroundTokenRefreshLoop() - Unable to refresh token credential cache. Exception: {0}",
ex.Message);
// Since it failed retry again in with half the token life span again.
if (!this.userDefinedBackgroundTokenCredentialRefreshInterval.HasValue && this.cachedAccessToken.HasValue)
{
double totalSecondUntilExpire = (this.cachedAccessToken.Value.ExpiresOn - DateTimeOffset.UtcNow).TotalSeconds * DefaultBackgroundTokenCredentialRefreshIntervalPercentage;
this.systemBackgroundTokenCredentialRefreshInterval = TimeSpan.FromSeconds(totalSecondUntilExpire);
// Refresh interval is less than the minimum. Stop the background refresh.
// The background refresh will start again on the next successful token refresh.
if (this.systemBackgroundTokenCredentialRefreshInterval < TokenCredentialCache.MinimumTimeBetweenBackgroundRefreshInterval)
{
lock (this.backgroundRefreshLock)
{
this.isBackgroundTaskRunning = false;
}
return;
}
}
}
}
}
}
}