-
Notifications
You must be signed in to change notification settings - Fork 378
[MSI v2] MAA token is now cached #5534
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Draft
gladjohn
wants to merge
1
commit into
rginsburg/msiv2_feature_branch
Choose a base branch
from
gladjohn/maa_in_memory
base: rginsburg/msiv2_feature_branch
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
270 changes: 270 additions & 0 deletions
270
src/client/Microsoft.Identity.Client/ManagedIdentity/V2/AttestationTokenMemoryCache.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,270 @@ | ||
// Copyright (c) Microsoft Corporation. All rights reserved. | ||
// Licensed under the MIT License. | ||
|
||
using System; | ||
using System.Collections.Concurrent; | ||
using System.Text; | ||
using System.Threading; | ||
using System.Threading.Tasks; | ||
|
||
namespace Microsoft.Identity.Client.ManagedIdentity | ||
{ | ||
/// <summary> | ||
/// Phase 1: process-local in-memory cache for attestation tokens. | ||
/// - Key: KeyHandle pointer value | ||
/// - TTL (Time to live): 8 hours (until provider exposes an explicit expiry) | ||
/// - Background refresh: kicks off at half-time (4h) without blocking callers | ||
/// - Thread-safe across callers; no cross-process guarantees (by design for Phase 1) | ||
/// | ||
/// Phase 2 (hand-off notes for persistent cache): | ||
/// - Add an IAttestationTokenCache interface to the provider input | ||
/// - Add a persistent cache implementation | ||
/// - Use a named OS mutex | ||
/// - Persist using the same key (KeyHandle pointer value) for simplicity | ||
/// - needs logging | ||
/// - details around background refresh and process exit needs some discussion | ||
/// </summary> | ||
internal static class AttestationTokenMemoryCache | ||
{ | ||
// Today MAA does not give expiry info; assume 8h TTL for now. | ||
// We have manually validated this with MAA tokens. | ||
private static readonly TimeSpan s_defaultTtl = TimeSpan.FromHours(8); // provider has no expiry yet | ||
private static readonly TimeSpan s_halfTime = TimeSpan.FromHours(4); // background refresh point | ||
private static readonly TimeSpan s_expirySkew = TimeSpan.FromMinutes(2); | ||
private static readonly TimeSpan s_bgRetryBackoff = TimeSpan.FromMinutes(15); | ||
|
||
// One Entry per key handle value | ||
private static readonly ConcurrentDictionary<long, Entry> s_entries = | ||
new ConcurrentDictionary<long, Entry>(); | ||
|
||
/// <summary> | ||
/// Returns a valid token. If missing/expired, mints via <paramref name="provider"/> and caches it. | ||
/// If past half-time, returns the current token and schedules a background refresh. | ||
/// </summary> | ||
internal static async Task<AttestationTokenResponse> GetOrCreateAsync( | ||
AttestationTokenInput input, | ||
Func<AttestationTokenInput, CancellationToken, Task<AttestationTokenResponse>> provider, | ||
CancellationToken ct) | ||
{ | ||
if (input == null) | ||
throw new ArgumentNullException(nameof(input)); | ||
if (provider == null) | ||
throw new ArgumentNullException(nameof(provider)); | ||
|
||
long key = GetHandleValue(input); | ||
var entry = s_entries.GetOrAdd(key, k => new Entry(k)); | ||
|
||
// Gate all mutations per key | ||
await entry.Gate.WaitAsync(ct).ConfigureAwait(false); | ||
try | ||
{ | ||
var now = DateTimeOffset.UtcNow; | ||
|
||
// Happy path: valid token in memory | ||
if (!string.IsNullOrEmpty(entry.Token) && now + s_expirySkew < entry.ExpiresOnUtc) | ||
{ | ||
// Past refresh time? Kick a non-blocking background refresh. | ||
if (now >= entry.RefreshOnUtc) | ||
{ | ||
KickBackgroundRefresh(entry, input, provider); | ||
} | ||
|
||
return new AttestationTokenResponse { AttestationToken = entry.Token }; | ||
} | ||
|
||
// Miss / expired -> mint synchronously and update cache | ||
var minted = await provider(input, ct).ConfigureAwait(false); | ||
if (minted == null || string.IsNullOrEmpty(minted.AttestationToken)) | ||
{ | ||
throw new MsalClientException("attestation_failed", "Attestation provider returned no token."); | ||
} | ||
|
||
var now2 = DateTimeOffset.UtcNow; | ||
entry.Token = minted.AttestationToken; | ||
entry.ExpiresOnUtc = now2 + s_defaultTtl; | ||
entry.RefreshOnUtc = now2 + s_halfTime; | ||
|
||
// Store the refresh factory so background timer can re-mint without caller context. | ||
entry.Mint = ctk => provider(input, ctk); | ||
|
||
// (Re)schedule the per-key timer to fire at RefreshOnUtc | ||
ScheduleTimer(entry); | ||
|
||
return minted; | ||
} | ||
finally | ||
{ | ||
entry.Gate.Release(); | ||
} | ||
} | ||
|
||
// ---------------- internals ---------------- | ||
|
||
private static long GetHandleValue(AttestationTokenInput input) | ||
{ | ||
try | ||
{ | ||
if (input.KeyHandle != null && !input.KeyHandle.IsInvalid) | ||
{ | ||
return input.KeyHandle.DangerousGetHandle().ToInt64(); | ||
} | ||
} | ||
catch { /* ignore */ } | ||
return 0L; | ||
} | ||
|
||
private static void KickBackgroundRefresh( | ||
Entry entry, | ||
AttestationTokenInput lastInput, | ||
Func<AttestationTokenInput, CancellationToken, Task<AttestationTokenResponse>> provider) | ||
{ | ||
// Background: do not block the caller thread; dedupe via Gate.TryEnter | ||
Task.Run(async () => | ||
{ | ||
if (!entry.Gate.Wait(0)) | ||
return; // another refresh in progress | ||
try | ||
{ | ||
// Freshen only if still past refresh (re-check) | ||
var now = DateTimeOffset.UtcNow; | ||
if (string.IsNullOrEmpty(entry.Token) || now < entry.RefreshOnUtc) | ||
{ | ||
return; | ||
} | ||
|
||
// Prefer stored Mint; if null (first call), mint with the last input/provider | ||
var mint = entry.Mint ?? (ct => provider(lastInput, ct)); | ||
|
||
var minted = await mint(CancellationToken.None).ConfigureAwait(false); | ||
if (minted != null && !string.IsNullOrEmpty(minted.AttestationToken)) | ||
{ | ||
var now2 = DateTimeOffset.UtcNow; | ||
entry.Token = minted.AttestationToken; | ||
entry.ExpiresOnUtc = now2 + s_defaultTtl; | ||
entry.RefreshOnUtc = now2 + s_halfTime; | ||
ScheduleTimer(entry); // push next half-time | ||
} | ||
else | ||
{ | ||
// Best-effort retry before expiry | ||
ScheduleRetry(entry, s_bgRetryBackoff); | ||
} | ||
} | ||
catch | ||
{ | ||
// Swallow background errors; keep current token; try again later | ||
ScheduleRetry(entry, s_bgRetryBackoff); | ||
} | ||
finally | ||
{ | ||
entry.Gate.Release(); | ||
} | ||
}); | ||
} | ||
|
||
private static void ScheduleTimer(Entry entry) | ||
{ | ||
var due = entry.RefreshOnUtc - DateTimeOffset.UtcNow; | ||
if (due < TimeSpan.Zero) | ||
due = TimeSpan.Zero; | ||
|
||
int dueMs = SafeMs(due); | ||
if (entry.RefreshTimer == null) | ||
{ | ||
entry.RefreshTimer = new Timer(TimerCallback, entry, dueMs, Timeout.Infinite); | ||
} | ||
else | ||
{ | ||
entry.RefreshTimer.Change(dueMs, Timeout.Infinite); | ||
} | ||
} | ||
|
||
private static void ScheduleRetry(Entry entry, TimeSpan delay) | ||
{ | ||
int dueMs = SafeMs(delay); | ||
if (entry.RefreshTimer == null) | ||
{ | ||
entry.RefreshTimer = new Timer(TimerCallback, entry, dueMs, Timeout.Infinite); | ||
} | ||
else | ||
{ | ||
entry.RefreshTimer.Change(dueMs, Timeout.Infinite); | ||
} | ||
} | ||
|
||
private static int SafeMs(TimeSpan ts) | ||
{ | ||
if (ts <= TimeSpan.Zero) | ||
return 0; | ||
double ms = ts.TotalMilliseconds; | ||
if (ms > int.MaxValue) | ||
return int.MaxValue; | ||
return (int)ms; | ||
} | ||
|
||
private static void TimerCallback(object state) | ||
{ | ||
var entry = (Entry)state; | ||
// We only schedule; actual minting happens in KickBackgroundRefresh semantics: | ||
// Acquire lock, check refresh condition again, then mint. | ||
// Using stored Mint delegate to avoid needing caller context. | ||
if (entry.Mint == null) | ||
return; // no way to mint yet | ||
Task.Run(async () => | ||
{ | ||
if (!entry.Gate.Wait(0)) | ||
return; | ||
try | ||
{ | ||
var now = DateTimeOffset.UtcNow; | ||
if (now < entry.RefreshOnUtc) | ||
return; // not due anymore (rescheduled) | ||
var minted = await entry.Mint(CancellationToken.None).ConfigureAwait(false); | ||
if (minted != null && !string.IsNullOrEmpty(minted.AttestationToken)) | ||
{ | ||
var now2 = DateTimeOffset.UtcNow; | ||
entry.Token = minted.AttestationToken; | ||
entry.ExpiresOnUtc = now2 + s_defaultTtl; | ||
entry.RefreshOnUtc = now2 + s_halfTime; | ||
ScheduleTimer(entry); | ||
} | ||
else | ||
{ | ||
ScheduleRetry(entry, s_bgRetryBackoff); | ||
} | ||
} | ||
catch | ||
{ | ||
ScheduleRetry(entry, s_bgRetryBackoff); | ||
} | ||
finally | ||
{ | ||
entry.Gate.Release(); | ||
} | ||
}); | ||
} | ||
|
||
// Per-key state | ||
private sealed class Entry : IDisposable | ||
{ | ||
internal Entry(long key) { Key = key; Gate = new SemaphoreSlim(1, 1); } | ||
internal long Key; | ||
internal string Token; // opaque JWT (never parsed) | ||
internal DateTimeOffset ExpiresOnUtc; | ||
internal DateTimeOffset RefreshOnUtc; | ||
internal SemaphoreSlim Gate; | ||
internal Timer RefreshTimer; | ||
internal Func<CancellationToken, Task<AttestationTokenResponse>> Mint; // stored mint delegate | ||
|
||
public void Dispose() | ||
{ | ||
try | ||
{ RefreshTimer?.Dispose(); } | ||
catch { } | ||
try | ||
{ Gate?.Dispose(); } | ||
catch { } | ||
} | ||
} | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I thought we discussed to not do any background refresh.