-
Notifications
You must be signed in to change notification settings - Fork 24.3k
/
FileRolesStore.java
357 lines (323 loc) · 15.9 KB
/
FileRolesStore.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
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/
package org.elasticsearch.xpack.security.authz.store;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.message.ParameterizedMessage;
import org.apache.logging.log4j.util.Supplier;
import org.elasticsearch.ElasticsearchParseException;
import org.elasticsearch.common.Nullable;
import org.elasticsearch.common.component.AbstractComponent;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.util.set.Sets;
import org.elasticsearch.common.xcontent.LoggingDeprecationHandler;
import org.elasticsearch.common.xcontent.NamedXContentRegistry;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.common.xcontent.yaml.YamlXContent;
import org.elasticsearch.env.Environment;
import org.elasticsearch.license.XPackLicenseState;
import org.elasticsearch.watcher.FileChangesListener;
import org.elasticsearch.watcher.FileWatcher;
import org.elasticsearch.watcher.ResourceWatcherService;
import org.elasticsearch.xpack.core.XPackPlugin;
import org.elasticsearch.xpack.core.XPackSettings;
import org.elasticsearch.xpack.core.security.authz.RoleDescriptor;
import org.elasticsearch.xpack.core.security.authz.RoleDescriptor.IndicesPrivileges;
import org.elasticsearch.xpack.core.security.authz.store.ReservedRolesStore;
import org.elasticsearch.xpack.core.security.support.NoOpLogger;
import org.elasticsearch.xpack.core.security.support.Validation;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.function.Consumer;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import static java.util.Collections.emptyMap;
import static java.util.Collections.unmodifiableMap;
public class FileRolesStore extends AbstractComponent {
private static final Pattern IN_SEGMENT_LINE = Pattern.compile("^\\s+.+");
private static final Pattern SKIP_LINE = Pattern.compile("(^#.*|^\\s*)");
private final Path file;
private final XPackLicenseState licenseState;
private final List<Consumer<Set<String>>> listeners = new ArrayList<>();
private volatile Map<String, RoleDescriptor> permissions;
public FileRolesStore(Settings settings, Environment env, ResourceWatcherService watcherService, XPackLicenseState licenseState)
throws IOException {
this(settings, env, watcherService, null, licenseState);
}
FileRolesStore(Settings settings, Environment env, ResourceWatcherService watcherService, Consumer<Set<String>> listener,
XPackLicenseState licenseState) throws IOException {
super(settings);
this.file = resolveFile(env);
if (listener != null) {
listeners.add(listener);
}
this.licenseState = licenseState;
FileWatcher watcher = new FileWatcher(file.getParent());
watcher.addListener(new FileListener());
watcherService.add(watcher, ResourceWatcherService.Frequency.HIGH);
permissions = parseFile(file, logger, settings, licenseState);
}
public Set<RoleDescriptor> roleDescriptors(Set<String> roleNames) {
final Map<String, RoleDescriptor> localPermissions = permissions;
Set<RoleDescriptor> descriptors = new HashSet<>();
roleNames.forEach((name) -> {
RoleDescriptor descriptor = localPermissions.get(name);
if (descriptor != null) {
descriptors.add(descriptor);
}
});
return descriptors;
}
public Map<String, Object> usageStats() {
final Map<String, RoleDescriptor> localPermissions = permissions;
Map<String, Object> usageStats = new HashMap<>(3);
usageStats.put("size", localPermissions.size());
boolean dls = false;
boolean fls = false;
for (RoleDescriptor descriptor : localPermissions.values()) {
for (IndicesPrivileges indicesPrivileges : descriptor.getIndicesPrivileges()) {
fls = fls || indicesPrivileges.getGrantedFields() != null || indicesPrivileges.getDeniedFields() != null;
dls = dls || indicesPrivileges.getQuery() != null;
}
if (fls && dls) {
break;
}
}
usageStats.put("fls", fls);
usageStats.put("dls", dls);
return usageStats;
}
public void addListener(Consumer<Set<String>> consumer) {
Objects.requireNonNull(consumer);
synchronized (this) {
listeners.add(consumer);
}
}
public Path getFile() {
return file;
}
// package private for testing
Set<String> getAllRoleNames() {
return permissions.keySet();
}
public static Path resolveFile(Environment env) {
return XPackPlugin.resolveConfigFile(env, "roles.yml");
}
public static Set<String> parseFileForRoleNames(Path path, Logger logger) {
return parseRoleDescriptors(path, logger, false, Settings.EMPTY).keySet();
}
public static Map<String, RoleDescriptor> parseFile(Path path, Logger logger, Settings settings, XPackLicenseState licenseState) {
return parseFile(path, logger, true, settings, licenseState);
}
public static Map<String, RoleDescriptor> parseFile(Path path, Logger logger, boolean resolvePermission,
Settings settings, XPackLicenseState licenseState) {
if (logger == null) {
logger = NoOpLogger.INSTANCE;
}
Map<String, RoleDescriptor> roles = new HashMap<>();
logger.debug("attempting to read roles file located at [{}]", path.toAbsolutePath());
if (Files.exists(path)) {
try {
List<String> roleSegments = roleSegments(path);
final boolean flsDlsLicensed = licenseState.isDocumentAndFieldLevelSecurityAllowed();
for (String segment : roleSegments) {
RoleDescriptor descriptor = parseRoleDescriptor(segment, path, logger, resolvePermission, settings);
if (descriptor != null) {
if (ReservedRolesStore.isReserved(descriptor.getName())) {
logger.warn("role [{}] is reserved. the relevant role definition in the mapping file will be ignored",
descriptor.getName());
} else if (flsDlsLicensed == false && descriptor.isUsingDocumentOrFieldLevelSecurity()) {
logger.warn("role [{}] uses document and/or field level security, which is not enabled by the current license" +
". this role will be ignored", descriptor.getName());
// we still put the role in the map to avoid unnecessary negative lookups
roles.put(descriptor.getName(), descriptor);
} else {
roles.put(descriptor.getName(), descriptor);
}
}
}
} catch (IOException ioe) {
logger.error(
(Supplier<?>) () -> new ParameterizedMessage(
"failed to read roles file [{}]. skipping all roles...",
path.toAbsolutePath()),
ioe);
return emptyMap();
}
} else {
logger.debug("roles file does not exist");
return emptyMap();
}
logger.info("parsed [{}] roles from file [{}]", roles.size(), path.toAbsolutePath());
return unmodifiableMap(roles);
}
public static Map<String, RoleDescriptor> parseRoleDescriptors(Path path, Logger logger, boolean resolvePermission, Settings settings) {
if (logger == null) {
logger = NoOpLogger.INSTANCE;
}
Map<String, RoleDescriptor> roles = new HashMap<>();
logger.trace("attempting to read roles file located at [{}]", path.toAbsolutePath());
if (Files.exists(path)) {
try {
List<String> roleSegments = roleSegments(path);
for (String segment : roleSegments) {
RoleDescriptor rd = parseRoleDescriptor(segment, path, logger, resolvePermission, settings);
if (rd != null) {
roles.put(rd.getName(), rd);
}
}
} catch (IOException ioe) {
logger.error(
(Supplier<?>) () -> new ParameterizedMessage(
"failed to read roles file [{}]. skipping all roles...",
path.toAbsolutePath()),
ioe);
return emptyMap();
}
}
return unmodifiableMap(roles);
}
@Nullable
static RoleDescriptor parseRoleDescriptor(String segment, Path path, Logger logger, boolean resolvePermissions, Settings settings) {
String roleName = null;
try {
// EMPTY is safe here because we never use namedObject
XContentParser parser = YamlXContent.yamlXContent
.createParser(NamedXContentRegistry.EMPTY, LoggingDeprecationHandler.INSTANCE, segment);
XContentParser.Token token = parser.nextToken();
if (token == XContentParser.Token.START_OBJECT) {
token = parser.nextToken();
if (token == XContentParser.Token.FIELD_NAME) {
roleName = parser.currentName();
Validation.Error validationError = Validation.Roles.validateRoleName(roleName);
if (validationError != null) {
logger.error("invalid role definition [{}] in roles file [{}]. invalid role name - {}. skipping role... ",
roleName, path.toAbsolutePath(), validationError);
return null;
}
if (resolvePermissions == false) {
return new RoleDescriptor(roleName, null, null, null);
}
token = parser.nextToken();
if (token == XContentParser.Token.START_OBJECT) {
// we pass true as last parameter because we do not want to reject files if field permissions
// are given in 2.x syntax
RoleDescriptor descriptor = RoleDescriptor.parse(roleName, parser, true);
return checkDescriptor(descriptor, path, logger, settings);
} else {
logger.error("invalid role definition [{}] in roles file [{}]. skipping role...", roleName, path.toAbsolutePath());
return null;
}
}
}
logger.error("invalid role definition [{}] in roles file [{}]. skipping role...", roleName, path.toAbsolutePath());
} catch (ElasticsearchParseException e) {
assert roleName != null;
if (logger.isDebugEnabled()) {
final String finalRoleName = roleName;
logger.debug((Supplier<?>) () -> new ParameterizedMessage("parsing exception for role [{}]", finalRoleName), e);
} else {
logger.error(e.getMessage() + ". skipping role...");
}
} catch (IOException e) {
if (roleName != null) {
final String finalRoleName = roleName;
logger.error(
(Supplier<?>) () -> new ParameterizedMessage(
"invalid role definition [{}] in roles file [{}]. skipping role...",
finalRoleName,
path),
e);
} else {
logger.error(
(Supplier<?>) () -> new ParameterizedMessage(
"invalid role definition in roles file [{}]. skipping role...",
path),
e);
}
}
return null;
}
@Nullable
private static RoleDescriptor checkDescriptor(RoleDescriptor descriptor, Path path, Logger logger, Settings settings) {
String roleName = descriptor.getName();
// first check if FLS/DLS is enabled on the role...
for (RoleDescriptor.IndicesPrivileges privilege : descriptor.getIndicesPrivileges()) {
if ((privilege.getQuery() != null || privilege.getGrantedFields() != null || privilege.getDeniedFields() != null)
&& XPackSettings.DLS_FLS_ENABLED.get(settings) == false) {
logger.error("invalid role definition [{}] in roles file [{}]. document and field level security is not " +
"enabled. set [{}] to [true] in the configuration file. skipping role...", roleName, path
.toAbsolutePath(), XPackSettings.DLS_FLS_ENABLED.getKey());
return null;
}
}
return descriptor;
}
private static List<String> roleSegments(Path path) throws IOException {
List<String> segments = new ArrayList<>();
StringBuilder builder = null;
for (String line : Files.readAllLines(path, StandardCharsets.UTF_8)) {
if (!SKIP_LINE.matcher(line).matches()) {
if (IN_SEGMENT_LINE.matcher(line).matches()) {
if (builder != null) {
builder.append(line).append("\n");
}
} else {
if (builder != null) {
segments.add(builder.toString());
}
builder = new StringBuilder(line).append("\n");
}
}
}
if (builder != null) {
segments.add(builder.toString());
}
return segments;
}
private class FileListener implements FileChangesListener {
@Override
public void onFileCreated(Path file) {
onFileChanged(file);
}
@Override
public void onFileDeleted(Path file) {
onFileChanged(file);
}
@Override
public synchronized void onFileChanged(Path file) {
if (file.equals(FileRolesStore.this.file)) {
final Map<String, RoleDescriptor> previousPermissions = permissions;
try {
permissions = parseFile(file, logger, settings, licenseState);
logger.info("updated roles (roles file [{}] {})", file.toAbsolutePath(),
Files.exists(file) ? "changed" : "removed");
} catch (Exception e) {
logger.error(
(Supplier<?>) () -> new ParameterizedMessage(
"could not reload roles file [{}]. Current roles remain unmodified", file.toAbsolutePath()), e);
return;
}
final Set<String> changedOrMissingRoles = Sets.difference(previousPermissions.entrySet(), permissions.entrySet())
.stream()
.map(Map.Entry::getKey)
.collect(Collectors.toSet());
final Set<String> addedRoles = Sets.difference(permissions.keySet(), previousPermissions.keySet());
final Set<String> changedRoles = Collections.unmodifiableSet(Sets.union(changedOrMissingRoles, addedRoles));
listeners.forEach(c -> c.accept(changedRoles));
}
}
}
}