-
Notifications
You must be signed in to change notification settings - Fork 4.9k
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
Refresh cached credentials after PreAuthenticate fails #101053
Merged
Merged
Changes from 6 commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
d1f33dd
Support refreshing credentials in pre-auth cache
rzikm b379938
Fix minor bug in CredentialCache
rzikm 842a25c
Add unit test
rzikm cc8e027
Fix tests
rzikm 53bd41a
Fix tests attempt 2
rzikm 8251325
Merge branch 'main' into 93340-preauthenticate-refresh
rzikm 1ab234c
Merge two lock statements.
rzikm 54e73cd
Fix build
rzikm 88888d5
Merge branch 'main' into 93340-preauthenticate-refresh
rzikm 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
133 changes: 133 additions & 0 deletions
133
src/libraries/Common/src/System/Net/CredentialCacheKey.cs
This file contains 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,133 @@ | ||
// Licensed to the .NET Foundation under one or more agreements. | ||
// The .NET Foundation licenses this file to you under the MIT license. | ||
|
||
using System.Collections; | ||
using System.Collections.Generic; | ||
using System.Diagnostics; | ||
using System.Diagnostics.CodeAnalysis; | ||
using System.Globalization; | ||
|
||
namespace System.Net | ||
{ | ||
internal sealed class CredentialCacheKey : IEquatable<CredentialCacheKey?> | ||
{ | ||
public readonly Uri UriPrefix; | ||
public readonly int UriPrefixLength = -1; | ||
public readonly string AuthenticationType; | ||
|
||
internal CredentialCacheKey(Uri uriPrefix, string authenticationType) | ||
{ | ||
Debug.Assert(uriPrefix != null); | ||
Debug.Assert(authenticationType != null); | ||
|
||
UriPrefix = uriPrefix; | ||
UriPrefixLength = UriPrefix.AbsolutePath.LastIndexOf('/'); | ||
AuthenticationType = authenticationType; | ||
} | ||
|
||
internal bool Match(Uri uri, string authenticationType) | ||
{ | ||
if (uri == null || authenticationType == null) | ||
{ | ||
return false; | ||
} | ||
|
||
// If the protocols don't match, this credential is not applicable for the given Uri. | ||
if (!string.Equals(authenticationType, AuthenticationType, StringComparison.OrdinalIgnoreCase)) | ||
{ | ||
return false; | ||
} | ||
|
||
if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"Match({UriPrefix} & {uri})"); | ||
|
||
return IsPrefix(uri, UriPrefix); | ||
} | ||
|
||
// IsPrefix (Uri) | ||
// | ||
// Determines whether <prefixUri> is a prefix of this URI. A prefix | ||
// match is defined as: | ||
// | ||
// scheme match | ||
// + host match | ||
// + port match, if any | ||
// + <prefix> path is a prefix of <URI> path, if any | ||
// | ||
// Returns: | ||
// True if <prefixUri> is a prefix of this URI | ||
private static bool IsPrefix(Uri uri, Uri prefixUri) | ||
{ | ||
Debug.Assert(uri != null); | ||
Debug.Assert(prefixUri != null); | ||
|
||
if (prefixUri.Scheme != uri.Scheme || prefixUri.Host != uri.Host || prefixUri.Port != uri.Port) | ||
{ | ||
return false; | ||
} | ||
|
||
int prefixLen = prefixUri.AbsolutePath.LastIndexOf('/'); | ||
if (prefixLen > uri.AbsolutePath.LastIndexOf('/')) | ||
{ | ||
return false; | ||
} | ||
|
||
return string.Compare(uri.AbsolutePath, 0, prefixUri.AbsolutePath, 0, prefixLen, StringComparison.OrdinalIgnoreCase) == 0; | ||
} | ||
|
||
public override int GetHashCode() => | ||
StringComparer.OrdinalIgnoreCase.GetHashCode(AuthenticationType) ^ | ||
UriPrefix.GetHashCode(); | ||
|
||
public bool Equals([NotNullWhen(true)] CredentialCacheKey? other) | ||
{ | ||
if (other == null) | ||
{ | ||
return false; | ||
} | ||
|
||
bool equals = | ||
string.Equals(AuthenticationType, other.AuthenticationType, StringComparison.OrdinalIgnoreCase) && | ||
UriPrefix.Equals(other.UriPrefix); | ||
|
||
if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"Equals({this},{other}) returns {equals}"); | ||
|
||
return equals; | ||
} | ||
|
||
public override bool Equals([NotNullWhen(true)] object? obj) => Equals(obj as CredentialCacheKey); | ||
|
||
public override string ToString() => | ||
string.Create(CultureInfo.InvariantCulture, $"[{UriPrefixLength}]:{UriPrefix}:{AuthenticationType}"); | ||
} | ||
|
||
internal static class CredentialCacheHelper | ||
{ | ||
public static bool TryGetCredential(Dictionary<CredentialCacheKey, NetworkCredential> cache, Uri uriPrefix, string authType, [NotNullWhen(true)] out Uri? mostSpecificMatchUri, [NotNullWhen(true)] out NetworkCredential? mostSpecificMatch) | ||
{ | ||
int longestMatchPrefix = -1; | ||
mostSpecificMatch = null; | ||
mostSpecificMatchUri = null; | ||
|
||
// Enumerate through every credential in the cache | ||
foreach ((CredentialCacheKey key, NetworkCredential value) in cache) | ||
{ | ||
// Determine if this credential is applicable to the current Uri/AuthType | ||
if (key.Match(uriPrefix, authType)) | ||
{ | ||
int prefixLen = key.UriPrefixLength; | ||
|
||
// Check if the match is better than the current-most-specific match | ||
if (prefixLen > longestMatchPrefix) | ||
{ | ||
// Yes: update the information about currently preferred match | ||
longestMatchPrefix = prefixLen; | ||
mostSpecificMatch = value; | ||
mostSpecificMatchUri = key.UriPrefix; | ||
} | ||
} | ||
} | ||
|
||
return mostSpecificMatch != null; | ||
} | ||
} | ||
} |
This file contains 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
This file contains 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
This file contains 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
61 changes: 61 additions & 0 deletions
61
...ibraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/PreAuthCredentialCache.cs
This file contains 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,61 @@ | ||
// Licensed to the .NET Foundation under one or more agreements. | ||
// The .NET Foundation licenses this file to you under the MIT license. | ||
|
||
using System.Collections; | ||
using System.Collections.Generic; | ||
using System.Diagnostics; | ||
using System.Diagnostics.CodeAnalysis; | ||
using System.Globalization; | ||
|
||
namespace System.Net.Http | ||
{ | ||
internal sealed class PreAuthCredentialCache | ||
{ | ||
private Dictionary<CredentialCacheKey, NetworkCredential>? _cache; | ||
|
||
public void Add(Uri uriPrefix, string authType, NetworkCredential cred) | ||
{ | ||
Debug.Assert(uriPrefix != null); | ||
Debug.Assert(authType != null); | ||
|
||
var key = new CredentialCacheKey(uriPrefix, authType); | ||
|
||
if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"Adding key:[{key}], cred:[{cred.Domain}],[{cred.UserName}]"); | ||
|
||
_cache ??= new Dictionary<CredentialCacheKey, NetworkCredential>(); | ||
_cache.Add(key, cred); | ||
} | ||
|
||
public void Remove(Uri uriPrefix, string authType) | ||
{ | ||
Debug.Assert(uriPrefix != null); | ||
Debug.Assert(authType != null); | ||
|
||
if (_cache == null) | ||
{ | ||
return; | ||
} | ||
|
||
var key = new CredentialCacheKey(uriPrefix, authType); | ||
if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"Removing key:[{key}]"); | ||
_cache.Remove(key); | ||
} | ||
|
||
public (Uri uriPrefix, NetworkCredential credential)? GetCredential(Uri uriPrefix, string authType) | ||
{ | ||
Debug.Assert(uriPrefix != null); | ||
Debug.Assert(authType != null); | ||
|
||
if (_cache == null) | ||
{ | ||
return null; | ||
} | ||
|
||
CredentialCacheHelper.TryGetCredential(_cache, uriPrefix, authType, out Uri? mostSpecificMatchUri, out NetworkCredential? mostSpecificMatch); | ||
|
||
if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"Returning {(mostSpecificMatch == null ? "null" : "(" + mostSpecificMatch.UserName + ":" + mostSpecificMatch.Domain + ")")}"); | ||
|
||
return mostSpecificMatch == null ? null : (mostSpecificMatchUri!, mostSpecificMatch!); | ||
} | ||
} | ||
} |
Oops, something went wrong.
Oops, something went wrong.
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.
While we lock the PreAuthCredentials the logic leading to this can run in parallel, right? Do we have concurrency problem when
Remove
can throw? Perhaps useTryRemove
?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.
The method calls
Dictionary<TKey, TValue>.Remove()
internally, which does not throw if the key does not exist in the first place.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.
But considering parallel requests, since we drop the lock between removing the creds and adding new ones, there may be some weird behavior if a parallel request starts when in-between. So I will move the removal to the same lock scope.