Skip to content

Commit a647060

Browse files
martincostellocaptainsafia
authored andcommitted
Compute dates in DefaultKeyResolver once (#60051)
Compute the maximum activation and creation `DateTImeOffset` for `DefaultKeyResolver` once before executing a LINQ query, rather than for each evaluation of `where`.
1 parent 60479cc commit a647060

File tree

1 file changed

+5
-3
lines changed

1 file changed

+5
-3
lines changed

src/DataProtection/DataProtection/src/KeyManagement/DefaultKeyResolver.cs

+5-3
Original file line numberDiff line numberDiff line change
@@ -157,8 +157,9 @@ private bool CanCreateAuthenticatedEncryptor(IKey key, ref int retriesRemaining)
157157
// fallback code below and the hypothetical advantage of making it easier for instances
158158
// to choose the same key in the event of a race (though we never managed to show that
159159
// empirically. See also https://github.com/dotnet/aspnetcore/issues/57137.
160+
var maxActivationDate = now + _maxServerToServerClockSkew;
160161
var preferredDefaultKey = (from key in allKeys
161-
where key.ActivationDate <= now + _maxServerToServerClockSkew
162+
where key.ActivationDate <= maxActivationDate
162163
orderby key.ActivationDate descending, key.KeyId ascending
163164
select key).FirstOrDefault();
164165

@@ -192,13 +193,14 @@ private bool CanCreateAuthenticatedEncryptor(IKey key, ref int retriesRemaining)
192193
// Unlike for the preferred key, we don't choose a fallback key and then reject it if
193194
// CanCreateAuthenticatedEncryptor is false. We want to end up with *some* key, so we
194195
// keep trying until we find one that works.
196+
var maxCreationDate = now - _keyPropagationWindow;
195197
var unrevokedKeys = allKeys.Where(key => !key.IsRevoked);
196198
fallbackKey = (from key in (from key in unrevokedKeys
197199
where !ReferenceEquals(key, preferredDefaultKey) // Don't reconsider it as a fallback
198-
where key.CreationDate <= now - _keyPropagationWindow
200+
where key.CreationDate <= maxCreationDate
199201
orderby key.CreationDate descending
200202
select key).Concat(from key in unrevokedKeys
201-
where key.CreationDate > now - _keyPropagationWindow
203+
where key.CreationDate > maxCreationDate
202204
orderby key.CreationDate ascending
203205
select key)
204206
where CanCreateAuthenticatedEncryptor(key, ref decryptRetriesRemaining)

0 commit comments

Comments
 (0)