-
Notifications
You must be signed in to change notification settings - Fork 122
/
Copy pathLocalCryptoMaterialsCache.java
306 lines (248 loc) · 8.84 KB
/
LocalCryptoMaterialsCache.java
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
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
package com.amazonaws.encryptionsdk.caching;
import com.amazonaws.encryptionsdk.internal.Utils;
import com.amazonaws.encryptionsdk.model.DecryptionMaterials;
import com.amazonaws.encryptionsdk.model.EncryptionMaterials;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.TreeSet;
import javax.annotation.concurrent.GuardedBy;
/**
* A simple implementation of the {@link CryptoMaterialsCache} using a basic LRU cache.
*
* <p>Example usage:
*
* <pre>{@code
* LocalCryptoMaterialsCache cache = new LocalCryptoMaterialsCache(500);
*
* CachingCryptoMaterialsManager materialsManager = CachingCryptoMaterialsManager.builder()
* .setMaxAge(5, TimeUnit.MINUTES)
* .setCache(cache)
* .withMasterKeyProvider(myMasterKeyProvider)
* .build();
*
* byte[] data = new AwsCrypto().encryptData(materialsManager, plaintext).getResult();
* }</pre>
*/
public class LocalCryptoMaterialsCache implements CryptoMaterialsCache {
// The maximum number of entries to implicitly prune per access due to TTL expiration. We limit
// this to avoid
// latency spikes when a large number of entries have expired since the last cache usage.
private static final int MAX_TTL_PRUNE = 10;
// Mockable time source, to allow us to test TTL pruning.
// package access for tests
// note: we're not using the java 8 time APIs in order to improve android compatibility
MsClock clock = MsClock.WALLCLOCK;
// The magic numbers here are the normal defaults for LinkedHashMap; we have to specify them
// explicitly if we are to
// specify accessOrder=true, which enables LRU behavior
private final LinkedHashMap<CacheIdentifier, BaseEntry> cacheMap =
new LinkedHashMap<>(/* capacity */ 16, /* loadFactor */ 0.75f, /* accessOrder */ true);
// This is a treeset sorted by TTL to allow us to quickly find expired entries
private final TreeSet<BaseEntry> expirationQueue =
new TreeSet<>(LocalCryptoMaterialsCache::compareEntries);
private final int capacity;
public LocalCryptoMaterialsCache(int capacity) {
this.capacity = capacity;
}
private static int compareEntries(BaseEntry a, BaseEntry b) {
int result;
if (a == b) {
return 0;
}
result = Long.compare(a.expirationTimestamp_, b.expirationTimestamp_);
if (result != 0) {
return result;
}
return Utils.compareObjectIdentity(a, b);
}
/** A common base for both encrypt and decrypt entries */
private class BaseEntry {
final CacheIdentifier identifier_;
final long expirationTimestamp_;
final long creationTime = clock.timestamp();
private BaseEntry(CacheIdentifier identifier, long expiration) {
this.identifier_ = identifier;
this.expirationTimestamp_ = expiration;
}
}
/** This wrapper just gives us a usable hashcode over our cache identifiers. */
private static final class CacheIdentifier {
private final byte[] identifier;
private final int hashCode;
private CacheIdentifier(byte[] passed_id) {
this.identifier = passed_id.clone();
this.hashCode = Arrays.hashCode(passed_id);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
return Arrays.equals(identifier, ((CacheIdentifier) o).identifier);
}
@Override
public int hashCode() {
return hashCode;
}
}
// Note: We take locks on both cache entries as well as the overall cache.
// The lock order is overall cache -> cache entry; this means that the entry cannot call back into
// the parent cache
// while holding its own lock.
private final class EncryptCacheEntryInternal extends BaseEntry {
private final EncryptionMaterials result;
@GuardedBy("this")
private UsageStats usageStats = UsageStats.ZERO;
private EncryptCacheEntryInternal(
CacheIdentifier identifier, long expiration, EncryptionMaterials result) {
super(identifier, expiration);
this.result = result;
}
synchronized UsageStats addAndGetUsageStats(UsageStats delta) {
this.usageStats = this.usageStats.add(delta);
return this.usageStats;
}
}
// When returning cache entries, we create a new object to represent the snapshot of usage stats
// at time of get.
// This helps avoid races where two gets together push an entry over usage limits, and then both
// miss when they
// see the entry over the limit.
//
// Not static as invalidate calls back into the cache.
private final class EncryptCacheEntryExposed implements EncryptCacheEntry {
private final UsageStats usageStats_;
private final EncryptCacheEntryInternal internal_;
private EncryptCacheEntryExposed(
final UsageStats usageStats, final EncryptCacheEntryInternal internal) {
usageStats_ = usageStats;
internal_ = internal;
}
@Override
public UsageStats getUsageStats() {
return usageStats_;
}
@Override
public long getEntryCreationTime() {
return internal_.creationTime;
}
@Override
public EncryptionMaterials getResult() {
return internal_.result;
}
@Override
public void invalidate() {
removeEntry(internal_);
}
}
private final class DecryptCacheEntryInternal extends BaseEntry implements DecryptCacheEntry {
final DecryptionMaterials result;
private DecryptCacheEntryInternal(
CacheIdentifier identifier, long expiration, DecryptionMaterials result) {
super(identifier, expiration);
this.result = result;
}
@Override
public DecryptionMaterials getResult() {
return result;
}
@Override
public void invalidate() {
removeEntry(this);
}
@Override
public long getEntryCreationTime() {
return creationTime;
}
}
/**
* Removes an entry from the cache.
*
* @param e the entry to remove
*/
private synchronized void removeEntry(BaseEntry e) {
expirationQueue.remove(e);
// This does not update the LRU if the value does not match
cacheMap.remove(e.identifier_, e);
}
/** Prunes all TTL-expired entries, plus LRU entries until we are under capacity limits. */
private synchronized void prune() {
// Purge maxage-expired entries first, to avoid pruning entries by LRU unnecessarily when we're
// about to free
// up space anyway.
ttlPrune();
while (cacheMap.size() > capacity) {
removeEntry(cacheMap.values().iterator().next());
}
}
/** Prunes all TTL-expired entries. Does not check capacity. */
private void ttlPrune() {
int pruneCount = 0;
long now = clock.timestamp();
while (!expirationQueue.isEmpty()
&& expirationQueue.first().expirationTimestamp_ < now
&& pruneCount < MAX_TTL_PRUNE) {
removeEntry(expirationQueue.first());
pruneCount++;
}
}
private synchronized <T extends BaseEntry> T getEntry(Class<T> klass, byte[] identifier) {
// Perform cache maintenance first
ttlPrune();
BaseEntry e = cacheMap.get(new CacheIdentifier(identifier));
if (e == null) {
return null;
} else {
if (e.expirationTimestamp_ < clock.timestamp()) {
removeEntry(e);
return null;
}
return klass.cast(e);
}
}
private synchronized void putEntry(final BaseEntry entry) {
BaseEntry oldEntry = cacheMap.put(entry.identifier_, entry);
if (oldEntry != null) {
expirationQueue.remove(oldEntry);
}
expirationQueue.add(entry);
prune();
}
@Override
public EncryptCacheEntry getEntryForEncrypt(byte[] cacheId, final UsageStats usageIncrement) {
EncryptCacheEntryInternal entry = getEntry(EncryptCacheEntryInternal.class, cacheId);
if (entry != null) {
UsageStats stats = entry.addAndGetUsageStats(usageIncrement);
return new EncryptCacheEntryExposed(stats, entry);
}
return null;
}
@Override
public EncryptCacheEntry putEntryForEncrypt(
byte[] cacheId,
EncryptionMaterials encryptionMaterials,
CacheHint hint,
UsageStats initialUsage) {
EncryptCacheEntryInternal entry =
new EncryptCacheEntryInternal(
new CacheIdentifier(cacheId),
Utils.saturatingAdd(clock.timestamp(), hint.getMaxAgeMillis()),
encryptionMaterials);
entry.addAndGetUsageStats(initialUsage);
putEntry(entry);
return new EncryptCacheEntryExposed(initialUsage, entry);
}
@Override
public DecryptCacheEntry getEntryForDecrypt(byte[] cacheId) {
return getEntry(DecryptCacheEntryInternal.class, cacheId);
}
@Override
public void putEntryForDecrypt(
byte[] cacheId, DecryptionMaterials decryptionMaterials, CacheHint hint) {
DecryptCacheEntryInternal entry =
new DecryptCacheEntryInternal(
new CacheIdentifier(cacheId),
Utils.saturatingAdd(clock.timestamp(), hint.getMaxAgeMillis()),
decryptionMaterials);
putEntry(entry);
}
}