-
Notifications
You must be signed in to change notification settings - Fork 24.3k
/
CachingServiceAccountTokenStore.java
196 lines (173 loc) · 8.18 KB
/
CachingServiceAccountTokenStore.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
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/
package org.elasticsearch.xpack.security.authc.service;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.cache.Cache;
import org.elasticsearch.common.cache.CacheBuilder;
import org.elasticsearch.common.settings.Setting;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.core.TimeValue;
import org.elasticsearch.common.util.concurrent.ListenableFuture;
import org.elasticsearch.threadpool.ThreadPool;
import org.elasticsearch.xpack.core.security.action.service.TokenInfo.TokenSource;
import org.elasticsearch.xpack.core.security.authc.support.Hasher;
import org.elasticsearch.xpack.security.support.CacheInvalidatorRegistry;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Predicate;
public abstract class CachingServiceAccountTokenStore implements ServiceAccountTokenStore, CacheInvalidatorRegistry.CacheInvalidator {
private static final Logger logger = LogManager.getLogger(CachingServiceAccountTokenStore.class);
public static final Setting<String> CACHE_HASH_ALGO_SETTING = Setting.simpleString("xpack.security.authc.service_token.cache.hash_algo",
"ssha256", Setting.Property.NodeScope);
public static final Setting<TimeValue> CACHE_TTL_SETTING = Setting.timeSetting("xpack.security.authc.service_token.cache.ttl",
TimeValue.timeValueMinutes(20), Setting.Property.NodeScope);
public static final Setting<Integer> CACHE_MAX_TOKENS_SETTING = Setting.intSetting(
"xpack.security.authc.service_token.cache.max_tokens", 100_000, Setting.Property.NodeScope);
private final Settings settings;
private final ThreadPool threadPool;
private final Cache<String, ListenableFuture<CachedResult>> cache;
private final Hasher hasher;
CachingServiceAccountTokenStore(Settings settings, ThreadPool threadPool) {
this.settings = settings;
this.threadPool = threadPool;
final TimeValue ttl = CACHE_TTL_SETTING.get(settings);
if (ttl.getNanos() > 0) {
cache = CacheBuilder.<String, ListenableFuture<CachedResult>>builder()
.setExpireAfterWrite(ttl)
.setMaximumWeight(CACHE_MAX_TOKENS_SETTING.get(settings))
.build();
} else {
cache = null;
}
hasher = Hasher.resolve(CACHE_HASH_ALGO_SETTING.get(settings));
}
@Override
public void authenticate(ServiceAccountToken token, ActionListener<StoreAuthenticationResult> listener) {
try {
if (cache == null) {
doAuthenticate(token, listener);
} else {
authenticateWithCache(token, listener);
}
} catch (Exception e) {
listener.onFailure(e);
}
}
private void authenticateWithCache(ServiceAccountToken token, ActionListener<StoreAuthenticationResult> listener) {
assert cache != null;
try {
final AtomicBoolean valueAlreadyInCache = new AtomicBoolean(true);
final ListenableFuture<CachedResult> listenableCacheEntry = cache.computeIfAbsent(token.getQualifiedName(), k -> {
valueAlreadyInCache.set(false);
return new ListenableFuture<>();
});
if (valueAlreadyInCache.get()) {
listenableCacheEntry.addListener(ActionListener.wrap(result -> {
if (result.success) {
listener.onResponse(new StoreAuthenticationResult(result.verify(token), getTokenSource()));
} else if (result.verify(token)) {
// same wrong token
listener.onResponse(new StoreAuthenticationResult(false, getTokenSource()));
} else {
cache.invalidate(token.getQualifiedName(), listenableCacheEntry);
authenticateWithCache(token, listener);
}
}, listener::onFailure), threadPool.generic(), threadPool.getThreadContext());
} else {
doAuthenticate(token, ActionListener.wrap(storeAuthenticationResult -> {
if (false == storeAuthenticationResult.isSuccess()) {
// Do not cache failed attempt
cache.invalidate(token.getQualifiedName(), listenableCacheEntry);
} else {
logger.trace("cache service token [{}] authentication result", token.getQualifiedName());
}
listenableCacheEntry.onResponse(new CachedResult(hasher, storeAuthenticationResult.isSuccess(), token));
listener.onResponse(storeAuthenticationResult);
}, e -> {
// In case of failure, evict the cache entry and notify all listeners
cache.invalidate(token.getQualifiedName(), listenableCacheEntry);
listenableCacheEntry.onFailure(e);
listener.onFailure(e);
}));
}
} catch (final ExecutionException e) {
listener.onFailure(e);
}
}
/**
* Invalidate cache entries with keys matching to the specified qualified token names.
* @param qualifiedTokenNames The list of qualified toke names. If a name has trailing
* slash, it is treated as a prefix wildcard, i.e. all keys
* with this prefix are considered matching.
*/
@Override
public final void invalidate(Collection<String> qualifiedTokenNames) {
if (cache != null) {
logger.trace("invalidating cache for service token [{}]", Strings.collectionToCommaDelimitedString(qualifiedTokenNames));
final Set<String> exacts = new HashSet<>(qualifiedTokenNames);
final Set<String> prefixes = new HashSet<>();
final Iterator<String> it = exacts.iterator();
while (it.hasNext()) {
final String name = it.next();
if (name.endsWith("/")) {
prefixes.add(name);
it.remove();
}
}
exacts.forEach(cache::invalidate);
if (false == prefixes.isEmpty()) {
final Predicate<String> predicate = k -> prefixes.stream().anyMatch(k::startsWith);
final List<String> keys = new ArrayList<>();
cache.forEach((k, v) -> {
if (predicate.test(k)) {
keys.add(k);
}
});
keys.forEach(cache::invalidate);
}
}
}
@Override
public final void invalidateAll() {
if (cache != null) {
logger.trace("invalidating cache for all service tokens");
cache.invalidateAll();
}
}
protected Settings getSettings() {
return settings;
}
protected ThreadPool getThreadPool() {
return threadPool;
}
abstract void doAuthenticate(ServiceAccountToken token, ActionListener<StoreAuthenticationResult> listener);
abstract TokenSource getTokenSource();
// package private for testing
Cache<String, ListenableFuture<CachedResult>> getCache() {
return cache;
}
static class CachedResult {
private final boolean success;
private final char[] hash;
private CachedResult(Hasher hasher, boolean success, ServiceAccountToken token) {
this.success = success;
this.hash = hasher.hash(token.getSecret());
}
private boolean verify(ServiceAccountToken token) {
return hash != null && Hasher.verifyHash(token.getSecret(), hash);
}
}
}