forked from opensearch-project/security
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTestSecurityConfig.java
778 lines (622 loc) · 27.3 KB
/
TestSecurityConfig.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
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
/*
* Copyright 2021 floragunn GmbH
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
/*
* SPDX-License-Identifier: Apache-2.0
*
* The OpenSearch Contributors require contributions made to
* this file be licensed under the Apache-2.0 license or a
* compatible open source license.
*
* Modifications Copyright OpenSearch Contributors. See
* GitHub history for details.
*/
package org.opensearch.test.framework;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.bouncycastle.crypto.generators.OpenBSDBCrypt;
import org.opensearch.action.admin.indices.create.CreateIndexRequest;
import org.opensearch.action.index.IndexRequest;
import org.opensearch.action.update.UpdateRequest;
import org.opensearch.client.Client;
import org.opensearch.common.xcontent.XContentFactory;
import org.opensearch.core.common.bytes.BytesReference;
import org.opensearch.core.xcontent.ToXContentObject;
import org.opensearch.core.xcontent.XContentBuilder;
import org.opensearch.security.securityconf.impl.CType;
import org.opensearch.test.framework.cluster.OpenSearchClientProvider.UserCredentialsHolder;
import static org.apache.http.HttpHeaders.AUTHORIZATION;
import static org.opensearch.action.support.WriteRequest.RefreshPolicy.IMMEDIATE;
/**
* This class allows the declarative specification of the security configuration; in particular:
*
* - config.yml
* - internal_users.yml
* - roles.yml
* - roles_mapping.yml
*
* The class does the whole round-trip, i.e., the configuration is serialized to YAML/JSON and then written to
* the configuration index of the security plugin.
*/
public class TestSecurityConfig {
private static final Logger log = LogManager.getLogger(TestSecurityConfig.class);
private Config config = new Config();
private Map<String, User> internalUsers = new LinkedHashMap<>();
private Map<String, Role> roles = new LinkedHashMap<>();
private AuditConfiguration auditConfiguration;
private Map<String, RolesMapping> rolesMapping = new LinkedHashMap<>();
private String indexName = ".opendistro_security";
public TestSecurityConfig() {
}
public TestSecurityConfig configIndexName(String configIndexName) {
this.indexName = configIndexName;
return this;
}
public TestSecurityConfig authFailureListeners(AuthFailureListeners listener) {
config.authFailureListeners(listener);
return this;
}
public TestSecurityConfig anonymousAuth(boolean anonymousAuthEnabled) {
config.anonymousAuth(anonymousAuthEnabled);
return this;
}
public TestSecurityConfig doNotFailOnForbidden(boolean doNotFailOnForbidden) {
config.doNotFailOnForbidden(doNotFailOnForbidden);
return this;
}
public TestSecurityConfig xff(XffConfig xffConfig) {
config.xffConfig(xffConfig);
return this;
}
public TestSecurityConfig onBehalfOf(OnBehalfOfConfig onBehalfOfConfig) {
config.onBehalfOfConfig(onBehalfOfConfig);
return this;
}
public TestSecurityConfig authc(AuthcDomain authcDomain) {
config.authc(authcDomain);
return this;
}
public TestSecurityConfig authz(AuthzDomain authzDomain) {
config.authz(authzDomain);
return this;
}
public TestSecurityConfig user(User user) {
this.internalUsers.put(user.name, user);
for (Role role : user.roles) {
this.roles.put(role.name, role);
}
return this;
}
public List<User> getUsers() {
return new ArrayList<>(internalUsers.values());
}
public TestSecurityConfig roles(Role... roles) {
for (Role role : roles) {
if (this.roles.containsKey(role.name)) {
throw new IllegalStateException("Role with name " + role.name + " is already defined");
}
this.roles.put(role.name, role);
}
return this;
}
public TestSecurityConfig audit(AuditConfiguration auditConfiguration) {
this.auditConfiguration = auditConfiguration;
return this;
}
public TestSecurityConfig rolesMapping(RolesMapping... mappings) {
for (RolesMapping mapping : mappings) {
String roleName = mapping.getRoleName();
if (rolesMapping.containsKey(roleName)) {
throw new IllegalArgumentException("Role mapping " + roleName + " already exists");
}
this.rolesMapping.put(roleName, mapping);
}
return this;
}
public static class Config implements ToXContentObject {
private boolean anonymousAuth;
private Boolean doNotFailOnForbidden;
private XffConfig xffConfig;
private OnBehalfOfConfig onBehalfOfConfig;
private Map<String, AuthcDomain> authcDomainMap = new LinkedHashMap<>();
private AuthFailureListeners authFailureListeners;
private Map<String, AuthzDomain> authzDomainMap = new LinkedHashMap<>();
public Config anonymousAuth(boolean anonymousAuth) {
this.anonymousAuth = anonymousAuth;
return this;
}
public Config doNotFailOnForbidden(Boolean doNotFailOnForbidden) {
this.doNotFailOnForbidden = doNotFailOnForbidden;
return this;
}
public Config xffConfig(XffConfig xffConfig) {
this.xffConfig = xffConfig;
return this;
}
public Config onBehalfOfConfig(OnBehalfOfConfig onBehalfOfConfig) {
this.onBehalfOfConfig = onBehalfOfConfig;
return this;
}
public Config authc(AuthcDomain authcDomain) {
authcDomainMap.put(authcDomain.id, authcDomain);
return this;
}
public Config authFailureListeners(AuthFailureListeners authFailureListeners) {
this.authFailureListeners = authFailureListeners;
return this;
}
public Config authz(AuthzDomain authzDomain) {
authzDomainMap.put(authzDomain.getId(), authzDomain);
return this;
}
@Override
public XContentBuilder toXContent(XContentBuilder xContentBuilder, Params params) throws IOException {
xContentBuilder.startObject();
xContentBuilder.startObject("dynamic");
if (onBehalfOfConfig != null) {
xContentBuilder.field("on_behalf_of", onBehalfOfConfig);
}
if (anonymousAuth || (xffConfig != null)) {
xContentBuilder.startObject("http");
xContentBuilder.field("anonymous_auth_enabled", anonymousAuth);
if (xffConfig != null) {
xContentBuilder.field("xff", xffConfig);
}
xContentBuilder.endObject();
}
if (doNotFailOnForbidden != null) {
xContentBuilder.field("do_not_fail_on_forbidden", doNotFailOnForbidden);
}
xContentBuilder.field("authc", authcDomainMap);
if (authzDomainMap.isEmpty() == false) {
xContentBuilder.field("authz", authzDomainMap);
}
if (authFailureListeners != null) {
xContentBuilder.field("auth_failure_listeners", authFailureListeners);
}
xContentBuilder.endObject();
xContentBuilder.endObject();
return xContentBuilder;
}
}
public static class User implements UserCredentialsHolder, ToXContentObject {
public final static TestSecurityConfig.User USER_ADMIN = new TestSecurityConfig.User("admin").roles(
new Role("allaccess").indexPermissions("*").on("*").clusterPermissions("*")
);
String name;
private String password;
List<Role> roles = new ArrayList<>();
List<String> backendRoles = new ArrayList<>();
String requestedTenant;
private Map<String, String> attributes = new HashMap<>();
public User(String name) {
this.name = name;
this.password = "secret";
}
public User password(String password) {
this.password = password;
return this;
}
public User roles(Role... roles) {
// We scope the role names by user to keep tests free of potential side effects
String roleNamePrefix = "user_" + this.getName() + "__";
this.roles.addAll(
Arrays.asList(roles).stream().map((r) -> r.clone().name(roleNamePrefix + r.getName())).collect(Collectors.toSet())
);
return this;
}
public User backendRoles(String... backendRoles) {
this.backendRoles.addAll(Arrays.asList(backendRoles));
return this;
}
public User attr(String key, String value) {
this.attributes.put(key, value);
return this;
}
public String getName() {
return name;
}
public String getPassword() {
return password;
}
public Set<String> getRoleNames() {
return roles.stream().map(Role::getName).collect(Collectors.toSet());
}
public Object getAttribute(String attributeName) {
return attributes.get(attributeName);
}
@Override
public XContentBuilder toXContent(XContentBuilder xContentBuilder, Params params) throws IOException {
xContentBuilder.startObject();
xContentBuilder.field("hash", hash(password.toCharArray()));
Set<String> roleNames = getRoleNames();
if (!roleNames.isEmpty()) {
xContentBuilder.field("opendistro_security_roles", roleNames);
}
if (!backendRoles.isEmpty()) {
xContentBuilder.field("backend_roles", backendRoles);
}
if (attributes != null && attributes.size() != 0) {
xContentBuilder.field("attributes", attributes);
}
xContentBuilder.endObject();
return xContentBuilder;
}
}
public static class Role implements ToXContentObject {
public static Role ALL_ACCESS = new Role("all_access").clusterPermissions("*").indexPermissions("*").on("*").resourcePermissions("*", "*");
private String name;
private List<String> clusterPermissions = new ArrayList<>();
private List<IndexPermission> indexPermissions = new ArrayList<>();
private List<ResourcePermission> resourcePermissions = new ArrayList<>();
public Role(String name) {
this.name = name;
}
public Role clusterPermissions(String... clusterPermissions) {
this.clusterPermissions.addAll(Arrays.asList(clusterPermissions));
return this;
}
public IndexPermission indexPermissions(String... indexPermissions) {
return new IndexPermission(this, indexPermissions);
}
public Role resourcePermissions(final String resourceType, final String... resourceIds) {
resourcePermissions.add(new ResourcePermission(resourceType).resourceIds(resourceIds));
return this;
}
public Role name(String name) {
this.name = name;
return this;
}
public String getName() {
return name;
}
public Role clone() {
Role role = new Role(this.name);
role.clusterPermissions.addAll(this.clusterPermissions);
role.indexPermissions.addAll(this.indexPermissions);
role.resourcePermissions.addAll(this.resourcePermissions);
return role;
}
@Override
public XContentBuilder toXContent(XContentBuilder xContentBuilder, Params params) throws IOException {
xContentBuilder.startObject();
if (!clusterPermissions.isEmpty()) {
xContentBuilder.field("cluster_permissions", clusterPermissions);
}
if (!indexPermissions.isEmpty()) {
xContentBuilder.field("index_permissions", indexPermissions);
}
if (!resourcePermissions.isEmpty()) {
xContentBuilder.field("resource_permissions", resourcePermissions);
}
xContentBuilder.endObject();
return xContentBuilder;
}
}
public static class IndexPermission implements ToXContentObject {
private List<String> allowedActions;
private List<String> indexPatterns;
private Role role;
private String dlsQuery;
private List<String> fls;
private List<String> maskedFields;
IndexPermission(Role role, String... allowedActions) {
this.allowedActions = Arrays.asList(allowedActions);
this.role = role;
}
public IndexPermission dls(String dlsQuery) {
this.dlsQuery = dlsQuery;
return this;
}
public IndexPermission fls(String... fls) {
this.fls = Arrays.asList(fls);
return this;
}
public IndexPermission maskedFields(String... maskedFields) {
this.maskedFields = Arrays.asList(maskedFields);
return this;
}
public Role on(String... indexPatterns) {
this.indexPatterns = Arrays.asList(indexPatterns);
this.role.indexPermissions.add(this);
return this.role;
}
public Role on(TestIndex... testindices) {
this.indexPatterns = Arrays.asList(testindices).stream().map(TestIndex::getName).collect(Collectors.toList());
this.role.indexPermissions.add(this);
return this.role;
}
@Override
public XContentBuilder toXContent(XContentBuilder xContentBuilder, Params params) throws IOException {
xContentBuilder.startObject();
xContentBuilder.field("index_patterns", indexPatterns);
xContentBuilder.field("allowed_actions", allowedActions);
if (dlsQuery != null) {
xContentBuilder.field("dls", dlsQuery);
}
if (fls != null) {
xContentBuilder.field("fls", fls);
}
if (maskedFields != null) {
xContentBuilder.field("masked_fields", maskedFields);
}
xContentBuilder.endObject();
return xContentBuilder;
}
}
public static class ResourcePermission implements ToXContentObject {
private String resourceType;
private List<String> resourceIds;
ResourcePermission(final String resourceType) {
this.resourceType = resourceType;
}
public ResourcePermission resourceIds(final String... resourceIds) {
this.resourceIds = Arrays.asList(resourceIds);
return this;
}
@Override
public XContentBuilder toXContent(final XContentBuilder xContentBuilder, final Params params) throws IOException {
xContentBuilder.startObject();
xContentBuilder.field("resource_type", resourceType);
xContentBuilder.field("resource_ids", resourceIds);
xContentBuilder.endObject();
return xContentBuilder;
}
}
public static class AuthcDomain implements ToXContentObject {
private static String PUBLIC_KEY =
"MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAoqZbjLUAWc+DZTkinQAdvy1GFjPHPnxheU89hSiWoDD3NOW76H3u3T7cCDdOah2msdxSlBmCBH6wik8qLYkcV8owWukQg3PQmbEhrdPaKo0QCgomWs4nLgtmEYqcZ+QQldd82MdTlQ1QmoQmI9Uxqs1SuaKZASp3Gy19y8su5CV+FZ6BruUw9HELK055sAwl3X7j5ouabXGbcib2goBF3P52LkvbJLuWr5HDZEOeSkwIeqSeMojASM96K5SdotD+HwEyjaTjzRPL2Aa1BEQFWOQ6CFJLyLH7ZStDuPM1mJU1VxIVfMbZrhsUBjAnIhRynmWxML7YlNqkP9j6jyOIYQIDAQAB";
public static final int BASIC_AUTH_DOMAIN_ORDER = 0;
public final static AuthcDomain AUTHC_HTTPBASIC_INTERNAL = new TestSecurityConfig.AuthcDomain("basic", BASIC_AUTH_DOMAIN_ORDER)
.httpAuthenticatorWithChallenge("basic")
.backend("internal");
public final static AuthcDomain AUTHC_HTTPBASIC_INTERNAL_WITHOUT_CHALLENGE = new TestSecurityConfig.AuthcDomain(
"basic",
BASIC_AUTH_DOMAIN_ORDER
).httpAuthenticator("basic").backend("internal");
public final static AuthcDomain DISABLED_AUTHC_HTTPBASIC_INTERNAL = new TestSecurityConfig.AuthcDomain(
"basic",
BASIC_AUTH_DOMAIN_ORDER,
false
).httpAuthenticator("basic").backend("internal");
public final static AuthcDomain JWT_AUTH_DOMAIN = new TestSecurityConfig.AuthcDomain("jwt", 1).jwtHttpAuthenticator(
new JwtConfigBuilder().jwtHeader(AUTHORIZATION).signingKey(PUBLIC_KEY)
).backend("noop");
private final String id;
private boolean enabled = true;
private int order;
private List<String> skipUsers = new ArrayList<>();
private HttpAuthenticator httpAuthenticator;
private AuthenticationBackend authenticationBackend;
public AuthcDomain(String id, int order, boolean enabled) {
this.id = id;
this.order = order;
this.enabled = enabled;
}
public AuthcDomain(String id, int order) {
this(id, order, true);
}
public AuthcDomain httpAuthenticator(String type) {
this.httpAuthenticator = new HttpAuthenticator(type);
return this;
}
public AuthcDomain jwtHttpAuthenticator(JwtConfigBuilder builder) {
this.httpAuthenticator = new HttpAuthenticator("jwt").challenge(false).config(builder.build());
return this;
}
public AuthcDomain httpAuthenticatorWithChallenge(String type) {
this.httpAuthenticator = new HttpAuthenticator(type).challenge(true);
return this;
}
public AuthcDomain httpAuthenticator(HttpAuthenticator httpAuthenticator) {
this.httpAuthenticator = httpAuthenticator;
return this;
}
public AuthcDomain backend(String type) {
this.authenticationBackend = new AuthenticationBackend(type);
return this;
}
public AuthcDomain backend(AuthenticationBackend authenticationBackend) {
this.authenticationBackend = authenticationBackend;
return this;
}
public AuthcDomain skipUsers(String... users) {
this.skipUsers.addAll(Arrays.asList(users));
return this;
}
@Override
public XContentBuilder toXContent(XContentBuilder xContentBuilder, Params params) throws IOException {
xContentBuilder.startObject();
xContentBuilder.field("http_enabled", enabled);
xContentBuilder.field("order", order);
if (httpAuthenticator != null) {
xContentBuilder.field("http_authenticator", httpAuthenticator);
}
if (authenticationBackend != null) {
xContentBuilder.field("authentication_backend", authenticationBackend);
}
if (skipUsers != null && skipUsers.size() > 0) {
xContentBuilder.field("skip_users", skipUsers);
}
xContentBuilder.endObject();
return xContentBuilder;
}
public static class HttpAuthenticator implements ToXContentObject {
private final String type;
private boolean challenge;
private Map<String, Object> config = new HashMap();
public HttpAuthenticator(String type) {
this.type = type;
}
public HttpAuthenticator challenge(boolean challenge) {
this.challenge = challenge;
return this;
}
public HttpAuthenticator config(Map<String, Object> config) {
this.config.putAll(config);
return this;
}
@Override
public XContentBuilder toXContent(XContentBuilder xContentBuilder, Params params) throws IOException {
xContentBuilder.startObject();
xContentBuilder.field("type", type);
xContentBuilder.field("challenge", challenge);
xContentBuilder.field("config", config);
xContentBuilder.endObject();
return xContentBuilder;
}
}
public static class AuthenticationBackend implements ToXContentObject {
private final String type;
private Supplier<Map<String, Object>> config = () -> new HashMap();
public AuthenticationBackend(String type) {
this.type = type;
}
public AuthenticationBackend config(Map<String, Object> config) {
Map<String, Object> configCopy = new HashMap<>(config);
this.config = () -> configCopy;
return this;
}
public AuthenticationBackend config(Supplier<Map<String, Object>> configSupplier) {
this.config = configSupplier;
return this;
}
@Override
public XContentBuilder toXContent(XContentBuilder xContentBuilder, Params params) throws IOException {
xContentBuilder.startObject();
xContentBuilder.field("type", type);
xContentBuilder.field("config", config.get());
xContentBuilder.endObject();
return xContentBuilder;
}
}
}
public void initIndex(Client client) {
Map<String, Object> settings = new HashMap<>();
if (indexName.startsWith(".")) {
settings.put("index.hidden", true);
}
client.admin().indices().create(new CreateIndexRequest(indexName).settings(settings)).actionGet();
writeSingleEntryConfigToIndex(client, CType.CONFIG, config);
if (auditConfiguration != null) {
writeSingleEntryConfigToIndex(client, CType.AUDIT, "config", auditConfiguration);
}
writeConfigToIndex(client, CType.ROLES, roles);
writeConfigToIndex(client, CType.INTERNALUSERS, internalUsers);
writeConfigToIndex(client, CType.ROLESMAPPING, rolesMapping);
writeEmptyConfigToIndex(client, CType.ACTIONGROUPS);
writeEmptyConfigToIndex(client, CType.TENANTS);
}
public void updateInternalUsersConfiguration(Client client, List<User> users) {
Map<String, ToXContentObject> userMap = new HashMap<>();
for (User user : users) {
userMap.put(user.getName(), user);
}
updateConfigInIndex(client, CType.INTERNALUSERS, userMap);
}
static String hash(final char[] clearTextPassword) {
final byte[] salt = new byte[16];
new SecureRandom().nextBytes(salt);
final String hash = OpenBSDBCrypt.generate((Objects.requireNonNull(clearTextPassword)), salt, 12);
Arrays.fill(salt, (byte) 0);
Arrays.fill(clearTextPassword, '\0');
return hash;
}
private void writeEmptyConfigToIndex(Client client, CType configType) {
writeConfigToIndex(client, configType, Collections.emptyMap());
}
private void writeConfigToIndex(Client client, CType configType, Map<String, ? extends ToXContentObject> config) {
try {
String json = configToJson(configType, config);
log.info("Writing security configuration into index " + configType + ":\n" + json);
BytesReference bytesReference = toByteReference(json);
client.index(
new IndexRequest(indexName).id(configType.toLCString())
.setRefreshPolicy(IMMEDIATE)
.source(configType.toLCString(), bytesReference)
).actionGet();
} catch (Exception e) {
throw new RuntimeException("Error while initializing config for " + indexName, e);
}
}
private static BytesReference toByteReference(String string) throws UnsupportedEncodingException {
return BytesReference.fromByteBuffer(ByteBuffer.wrap(string.getBytes("utf-8")));
}
private void updateConfigInIndex(Client client, CType configType, Map<String, ? extends ToXContentObject> config) {
try {
String json = configToJson(configType, config);
BytesReference bytesReference = toByteReference(json);
log.info("Update configuration of type '{}' in index '{}', new value '{}'.", configType, indexName, json);
UpdateRequest upsert = new UpdateRequest(indexName, configType.toLCString()).doc(configType.toLCString(), bytesReference)
.setRefreshPolicy(IMMEDIATE);
client.update(upsert).actionGet();
} catch (Exception e) {
throw new RuntimeException("Error while updating config for " + indexName, e);
}
}
private static String configToJson(CType configType, Map<String, ? extends ToXContentObject> config) throws IOException {
XContentBuilder builder = XContentFactory.jsonBuilder();
builder.startObject();
builder.startObject("_meta");
builder.field("type", configType.toLCString());
builder.field("config_version", 2);
builder.endObject();
for (Map.Entry<String, ? extends ToXContentObject> entry : config.entrySet()) {
builder.field(entry.getKey(), entry.getValue());
}
builder.endObject();
return builder.toString();
}
private void writeSingleEntryConfigToIndex(Client client, CType configType, ToXContentObject config) {
writeSingleEntryConfigToIndex(client, configType, configType.toLCString(), config);
}
private void writeSingleEntryConfigToIndex(Client client, CType configType, String configurationRoot, ToXContentObject config) {
try {
XContentBuilder builder = XContentFactory.jsonBuilder();
builder.startObject();
builder.startObject("_meta");
builder.field("type", configType.toLCString());
builder.field("config_version", 2);
builder.endObject();
builder.field(configurationRoot, config);
builder.endObject();
String json = builder.toString();
log.info("Writing security plugin configuration into index " + configType + ":\n" + json);
client.index(
new IndexRequest(indexName).id(configType.toLCString())
.setRefreshPolicy(IMMEDIATE)
.source(configType.toLCString(), toByteReference(json))
).actionGet();
} catch (Exception e) {
throw new RuntimeException("Error while initializing config for " + indexName, e);
}
}
}