/
MemoryTicketCache.cs
217 lines (172 loc) · 6.5 KB
/
MemoryTicketCache.cs
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
// -----------------------------------------------------------------------
// Licensed to The .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// -----------------------------------------------------------------------
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Kerberos.NET.Configuration;
using Microsoft.Extensions.Logging;
namespace Kerberos.NET
{
internal sealed class MemoryTicketCache : TicketCacheBase
{
private readonly ConcurrentDictionary<string, CacheEntry> cache
= new ConcurrentDictionary<string, CacheEntry>();
public MemoryTicketCache(Krb5Config config, ILoggerFactory logger)
: base(config, logger)
{
}
public bool BlockUpdates { get; set; }
protected override async Task BackgroundCacheOperation()
{
var originalKeys = this.cache.Keys.ToArray();
foreach (var kv in originalKeys)
{
if (!this.cache.TryGetValue(kv, out CacheEntry entry))
{
continue;
}
if (entry.IsExpired(this.Configuration.Defaults.ClockSkew))
{
this.cache.TryRemove(kv, out _);
}
else if (this.RefreshTickets)
{
await (this.Refresh?.Invoke(entry)).ConfigureAwait(false);
}
}
var finalKeys = this.cache.Keys.ToArray();
var newKeys = finalKeys.Except(originalKeys);
var purgedKeys = originalKeys.Except(finalKeys);
if (newKeys.Any() || purgedKeys.Any())
{
this.Logger.LogDebug("Cache Operation. New: {NewKeys}; Purged: {PurgedKeys}", string.Join("; ", newKeys), string.Join("; ", purgedKeys));
}
}
public override ValueTask<bool> AddAsync(TicketCacheEntry entry)
{
if (this.Add(entry))
{
return new ValueTask<bool>(true);
}
return new ValueTask<bool>(false);
}
public override bool Add(TicketCacheEntry entry)
{
var cacheEntry = new CacheEntry(entry.Computed, entry.Value, this.Logger);
if (entry.Expires > DateTimeOffset.UtcNow)
{
cacheEntry.MarkLifetime(entry.Expires, entry.RenewUntil);
}
bool added = false;
if (this.BlockUpdates)
{
var got = this.GetInternal(cacheEntry.Key);
if (got == null)
{
added = this.cache.TryAdd(cacheEntry.Key, cacheEntry);
}
}
else
{
this.cache.AddOrUpdate(cacheEntry.Key, cacheEntry, (_, __) => cacheEntry);
added = true;
}
return added;
}
public override ValueTask<bool> ContainsAsync(TicketCacheEntry entry)
{
var exists = this.cache.ContainsKey(entry.Computed);
return new ValueTask<bool>(exists);
}
public override bool Contains(TicketCacheEntry entry)
{
return this.cache.ContainsKey(entry.Computed);
}
public override IEnumerable<object> GetAll()
{
return this.cache.Values.Select(v => v.Value).AsEnumerable();
}
public override ValueTask<object> GetCacheItemAsync(string key, string container = null)
{
return new ValueTask<object>(this.GetCacheItem(key, container));
}
public override object GetCacheItem(string key, string container = null)
{
var entryKey = TicketCacheEntry.GenerateKey(key: key, container: container);
return this.GetInternal(entryKey);
}
public override T GetCacheItem<T>(string key, string container = null)
{
var result = this.GetCacheItem(key, container);
if (result is T value)
{
return value;
}
return default;
}
private object GetInternal(string entryKey)
{
if (this.cache.TryGetValue(entryKey, out CacheEntry entry))
{
if (entry.IsExpired(this.Configuration.Defaults.ClockSkew))
{
this.Evict(entryKey);
}
else
{
return entry.Value;
}
}
return null;
}
private void Evict(string entryKey)
{
var removed = this.cache.TryRemove(entryKey, out _);
this.Logger.LogDebug($"Removal triggered for {entryKey}. Succeeded: {removed}");
}
public override async ValueTask<T> GetCacheItemAsync<T>(string key, string container = null)
{
var result = await this.GetCacheItemAsync(key, container).ConfigureAwait(false);
return result != null ? (T)result : default;
}
public override void PurgeTickets()
{
this.cache.Clear();
}
[DebuggerDisplay("{Key}; E: {Expiration}; R: {RenewUntil};")]
internal class CacheEntry
{
private readonly ILogger logger;
public CacheEntry(
string key,
object value,
ILogger logger
)
{
this.Key = key;
this.Value = value;
this.logger = logger;
}
public string Key { get; }
public object Value { get; }
public DateTimeOffset? Expiration { get; private set; }
public DateTimeOffset? RenewUntil { get; private set; }
public TimeSpan TimeToLive => (this.Expiration ?? DateTimeOffset.MaxValue) - DateTimeOffset.UtcNow;
public void MarkLifetime(DateTimeOffset expiration, DateTimeOffset? renewUntil)
{
this.logger.LogTrace("Caching ticket until {Expiration} for {Key} with renewal option until {RenewUntil}", expiration, this.Key, renewUntil);
this.Expiration = expiration;
this.RenewUntil = renewUntil;
}
public bool IsExpired(TimeSpan skew)
{
return (this.TimeToLive + skew) <= TimeSpan.Zero;
}
}
}
}