-
Notifications
You must be signed in to change notification settings - Fork 349
Expand file tree
/
Copy pathOboSqlTokenProvider.cs
More file actions
275 lines (240 loc) · 10.8 KB
/
Copy pathOboSqlTokenProvider.cs
File metadata and controls
275 lines (240 loc) · 10.8 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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System.Diagnostics;
using System.Net;
using System.Security.Claims;
using System.Security.Cryptography;
using System.Text;
using Azure.DataApiBuilder.Service.Exceptions;
using Microsoft.Extensions.Logging;
using Microsoft.Identity.Client;
using ZiggyCreatures.Caching.Fusion;
using AuthenticationOptions = Azure.DataApiBuilder.Config.ObjectModel.AuthenticationOptions;
namespace Azure.DataApiBuilder.Core.Resolvers;
/// <summary>
/// Provides SQL access tokens acquired using On-Behalf-Of (OBO) flow
/// for user-delegated authentication against Microsoft Entra ID.
/// Uses FusionCache (L1 in-memory only) for token caching with automatic
/// expiration and eager refresh.
/// </summary>
public sealed class OboSqlTokenProvider : IOboTokenProvider
{
private readonly IMsalClientWrapper _msalClient;
private readonly ILogger<OboSqlTokenProvider> _logger;
private readonly IFusionCache _cache;
/// <summary>
/// Cache key prefix for OBO tokens to isolate from other cached data.
/// </summary>
private const string CACHE_KEY_PREFIX = "obo:";
/// <summary>
/// Eager refresh threshold as a fraction of TTL.
/// At 0.85, a token cached for 60 minutes will be eagerly refreshed after 51 minutes.
/// </summary>
private const float EAGER_REFRESH_THRESHOLD = 0.85f;
/// <summary>
/// Minimum buffer before token expiry to trigger a refresh (in minutes).
/// </summary>
private const int MIN_EARLY_REFRESH_MINUTES = 5;
/// <summary>
/// Initializes a new instance of OboSqlTokenProvider.
/// </summary>
/// <param name="msalClient">MSAL client wrapper for token acquisition.</param>
/// <param name="logger">Logger instance.</param>
/// <param name="cache">FusionCache instance for token caching (L1 in-memory only).</param>
public OboSqlTokenProvider(
IMsalClientWrapper msalClient,
ILogger<OboSqlTokenProvider> logger,
IFusionCache cache)
{
_msalClient = msalClient ?? throw new ArgumentNullException(nameof(msalClient));
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
_cache = cache ?? throw new ArgumentNullException(nameof(cache));
}
/// <inheritdoc />
public async Task<string?> GetAccessTokenOnBehalfOfAsync(
ClaimsPrincipal principal,
string incomingJwtAssertion,
string databaseAudience,
CancellationToken cancellationToken = default)
{
if (principal is null)
{
_logger.LogWarning(
"{EventType}: Cannot acquire OBO token - ClaimsPrincipal is null (traceId: {TraceId}).",
"OboValidationFailed",
Activity.Current?.TraceId.ToString() ?? "none");
return null;
}
if (string.IsNullOrWhiteSpace(incomingJwtAssertion))
{
_logger.LogWarning(
"{EventType}: Cannot acquire OBO token - Incoming JWT assertion is null or empty (traceId: {TraceId}).",
"OboValidationFailed",
Activity.Current?.TraceId.ToString() ?? "none");
return null;
}
// Extract identity claims
string? subjectId = ExtractSubjectId(principal);
if (string.IsNullOrWhiteSpace(subjectId))
{
_logger.LogWarning(
"{EventType}: Cannot acquire OBO token - Neither 'oid' nor 'sub' claim found in token (traceId: {TraceId}).",
"OboValidationFailed",
Activity.Current?.TraceId.ToString() ?? "none");
throw new DataApiBuilderException(
message: DataApiBuilderException.OBO_IDENTITY_CLAIMS_MISSING,
statusCode: HttpStatusCode.Unauthorized,
subStatusCode: DataApiBuilderException.SubStatusCodes.OboAuthenticationFailure);
}
string? tenantId = principal.FindFirst("tid")?.Value;
if (string.IsNullOrWhiteSpace(tenantId))
{
_logger.LogWarning(
"{EventType}: Cannot acquire OBO token - 'tid' (tenant id) claim not found or empty in token (traceId: {TraceId}).",
"OboValidationFailed",
Activity.Current?.TraceId.ToString() ?? "none");
throw new DataApiBuilderException(
message: DataApiBuilderException.OBO_TENANT_CLAIM_MISSING,
statusCode: HttpStatusCode.Unauthorized,
subStatusCode: DataApiBuilderException.SubStatusCodes.OboAuthenticationFailure);
}
string authContextHash = ComputeAuthorizationContextHash(principal);
string cacheKey = BuildCacheKey(subjectId, tenantId, authContextHash);
try
{
string[] scopes = [$"{databaseAudience.TrimEnd('/')}/.default"];
// Track whether we had a cache hit for logging
bool wasCacheMiss = false;
// Use FusionCache GetOrSetAsync with factory pattern
// The factory is only called on cache miss
string? accessToken = await _cache.GetOrSetAsync<string>(
key: cacheKey,
factory: async (ctx, ct) =>
{
wasCacheMiss = true;
_logger.LogInformation(
"{EventType}: OBO token cache MISS for subject {SubjectId} (tenant: {TenantId}, traceId: {TraceId}). Acquiring new token from Azure AD.",
"OboTokenCacheMiss",
subjectId,
tenantId,
Activity.Current?.TraceId.ToString() ?? "none");
AuthenticationResult result = await _msalClient.AcquireTokenOnBehalfOfAsync(
scopes,
incomingJwtAssertion,
ct);
// Calculate TTL based on token expiry with early refresh buffer
TimeSpan tokenLifetime = result.ExpiresOn - DateTimeOffset.UtcNow;
TimeSpan cacheDuration = tokenLifetime - TimeSpan.FromMinutes(MIN_EARLY_REFRESH_MINUTES);
// Ensure minimum cache duration of 1 minute
if (cacheDuration < TimeSpan.FromMinutes(1))
{
cacheDuration = TimeSpan.FromMinutes(1);
}
// Set the cache duration based on actual token expiry
ctx.Options.SetDuration(cacheDuration);
// Enable eager refresh - token will be refreshed in background at threshold
ctx.Options.SetEagerRefresh(EAGER_REFRESH_THRESHOLD);
// Ensure tokens stay in L1 only (no distributed cache for security)
ctx.Options.SetSkipDistributedCache(true, true);
_logger.LogInformation(
"{EventType}: OBO token ACQUIRED for subject {SubjectId} (traceId: {TraceId}). Expires: {ExpiresOn}, Cache TTL: {CacheDuration}.",
"OboTokenAcquired",
subjectId,
Activity.Current?.TraceId.ToString() ?? "none",
result.ExpiresOn,
cacheDuration);
return result.AccessToken;
},
token: cancellationToken);
if (!string.IsNullOrEmpty(accessToken) && !wasCacheMiss)
{
_logger.LogInformation(
"{EventType}: OBO token cache HIT for subject {SubjectId} (traceId: {TraceId}).",
"OboTokenCacheHit",
subjectId,
Activity.Current?.TraceId.ToString() ?? "none");
}
return accessToken;
}
catch (MsalException ex)
{
_logger.LogError(
ex,
"{EventType}: Failed to acquire OBO token for subject {SubjectId} (traceId: {TraceId}). Error: {ErrorCode} - {Message}",
"OboTokenAcquisitionFailed",
subjectId,
Activity.Current?.TraceId.ToString() ?? "none",
ex.ErrorCode,
ex.Message);
throw new DataApiBuilderException(
message: DataApiBuilderException.OBO_TOKEN_ACQUISITION_FAILED,
statusCode: HttpStatusCode.Unauthorized,
subStatusCode: DataApiBuilderException.SubStatusCodes.OboAuthenticationFailure,
innerException: ex);
}
}
/// <summary>
/// Extracts the subject identifier from the principal.
/// Prefers 'oid' claim (object ID) over 'sub' claim.
/// </summary>
private static string? ExtractSubjectId(ClaimsPrincipal principal)
{
string? oid = principal.FindFirst("oid")?.Value;
if (!string.IsNullOrWhiteSpace(oid))
{
return oid;
}
return principal.FindFirst("sub")?.Value;
}
/// <summary>
/// Builds a canonical representation of permission-affecting claims (roles and scopes)
/// and computes a SHA-512 hash for use in the cache key.
/// </summary>
private static string ComputeAuthorizationContextHash(ClaimsPrincipal principal)
{
List<string> values = [];
HashSet<string> roleClaimTypes = principal.Identities
.Select(identity => string.IsNullOrWhiteSpace(identity.RoleClaimType)
? AuthenticationOptions.ROLE_CLAIM_TYPE
: identity.RoleClaimType)
.ToHashSet(StringComparer.OrdinalIgnoreCase);
foreach (Claim claim in principal.Claims)
{
if (roleClaimTypes.Contains(claim.Type) ||
claim.Type.Equals("scp", StringComparison.OrdinalIgnoreCase))
{
string[] parts = claim.Value.Split(
[' ', ','],
StringSplitOptions.RemoveEmptyEntries);
foreach (string part in parts)
{
values.Add(part);
}
}
}
if (values.Count == 0)
{
return ComputeSha512Hex(string.Empty);
}
values.Sort(StringComparer.OrdinalIgnoreCase);
string canonical = string.Join("|", values);
return ComputeSha512Hex(canonical);
}
/// <summary>
/// Computes SHA-512 hash and returns as hex string.
/// </summary>
private static string ComputeSha512Hex(string input)
{
byte[] data = Encoding.UTF8.GetBytes(input ?? string.Empty);
byte[] hash = SHA512.HashData(data);
return Convert.ToHexString(hash);
}
/// <summary>
/// Builds the cache key from subject, tenant, and authorization context hash.
/// Format: obo:subjectId+tenantId+authContextHash
/// </summary>
private static string BuildCacheKey(string subjectId, string tenantId, string authContextHash)
{
return $"{CACHE_KEY_PREFIX}{subjectId}{tenantId}{authContextHash}";
}
}