forked from opensearch-project/security-analytics
-
Notifications
You must be signed in to change notification settings - Fork 0
/
MapperRestApiIT.java
1850 lines (1541 loc) · 84.9 KB
/
MapperRestApiIT.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
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Copyright OpenSearch Contributors
SPDX-License-Identifier: Apache-2.0
*/
package org.opensearch.securityanalytics.mapper;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import org.apache.hc.core5.http.HttpStatus;
import org.apache.hc.core5.http.io.entity.StringEntity;
import org.apache.hc.core5.http.message.BasicHeader;
import org.junit.Assert;
import org.opensearch.action.admin.indices.mapping.get.GetMappingsResponse;
import org.opensearch.action.search.SearchResponse;
import org.opensearch.client.Request;
import org.opensearch.client.Response;
import org.opensearch.client.ResponseException;
import org.opensearch.common.settings.Settings;
import org.opensearch.core.xcontent.DeprecationHandler;
import org.opensearch.core.xcontent.MediaTypeRegistry;
import org.opensearch.core.xcontent.NamedXContentRegistry;
import org.opensearch.core.xcontent.XContentParser;
import org.opensearch.common.xcontent.json.JsonXContent;
import org.opensearch.search.SearchHit;
import org.opensearch.securityanalytics.SecurityAnalyticsClientUtils;
import org.opensearch.securityanalytics.SecurityAnalyticsPlugin;
import org.opensearch.securityanalytics.SecurityAnalyticsRestTestCase;
import org.opensearch.securityanalytics.TestHelpers;
import org.opensearch.securityanalytics.action.GetMappingsViewResponse;
import org.opensearch.securityanalytics.model.Detector;
import org.opensearch.securityanalytics.model.DetectorInput;
import org.opensearch.securityanalytics.model.DetectorRule;
import org.opensearch.test.OpenSearchTestCase;
import static org.opensearch.securityanalytics.SecurityAnalyticsPlugin.MAPPER_BASE_URI;
import static org.opensearch.securityanalytics.TestHelpers.randomDetectorWithInputs;
public class MapperRestApiIT extends SecurityAnalyticsRestTestCase {
private String matchAllSearchBody = "{\"size\": 1000, \"query\" : {\"match_all\":{}}}";
public void testGetMappingSuccess() throws IOException {
String testIndexName1 = "my_index_1";
String testIndexName2 = "my_index_2";
String testIndexPattern = "my_index*";
createSampleIndex(testIndexName1);
createSampleIndex(testIndexName2);
createMappingsAPI(testIndexName2, "netflow");
Request request = new Request("GET", MAPPER_BASE_URI + "?index_name=" + testIndexPattern);
Response response = client().performRequest(request);
assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode());
Map<String, Object> respMap = (Map<String, Object>) responseAsMap(response);
// Assert that indexName returned is one passed by user
assertTrue(respMap.containsKey(testIndexPattern));
}
// Tests the case when the mappings map is empty
public void testGetMappings_emptyIndex_Success() throws IOException {
String testIndexName1 = "my_index_1";
String testIndexName2 = "my_index_2";
String testIndexPattern = "my_index*";
createSampleIndex(testIndexName1);
createSampleIndex(testIndexName2);
Request request = new Request("GET", MAPPER_BASE_URI + "?index_name=" + testIndexPattern);
Response response = client().performRequest(request);
assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode());
Map<String, Object> respMap = (Map<String, Object>) responseAsMap(response);
Map<String, Object> props = (Map<String, Object>)((Map<String, Object>) respMap.get(testIndexPattern)).get("mappings");
// Assert that indexName returned is one passed by user
assertTrue(respMap.containsKey(testIndexPattern));
//Assert that mappings map is also present in the output
assertTrue(props.containsKey("properties"));
}
public void testGetMappingSuccess_1() throws IOException {
String testIndexName1 = "my_index_1";
String testIndexPattern = "my_index*";
createIndex(testIndexName1, Settings.EMPTY);
String sampleDoc = "{\n" +
" \"lvl1field\": 12345,\n" +
" \"source1.ip\": \"12345\",\n" +
" \"source1.port\": 55,\n" +
" \"some.very.long.field.name\": \"test\"\n" +
"}";
indexDoc(testIndexName1, "1", sampleDoc);
// puts mappings with timestamp alias
String createMappingsRequest = "{\"index_name\":\"my_index*\",\"rule_topic\":\"windows\",\"partial\":true,\"alias_mappings\":{\"properties\":{\"timestamp\":{\"type\":\"alias\",\"path\":\"lvl1field\"},\"winlog.computer_name\":{\"type\":\"alias\",\"path\":\"source1.port\"},\"winlog.event_data.AuthenticationPackageName\":{\"type\":\"alias\",\"path\":\"source1.ip\"},\"winlog.event_data.Company\":{\"type\":\"alias\",\"path\":\"some.very.long.field.name\"}}}}";
Request request = new Request("POST", MAPPER_BASE_URI);
// both req params and req body are supported
request.setJsonEntity(createMappingsRequest);
Response response = client().performRequest(request);
assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode());
request = new Request("GET", MAPPER_BASE_URI + "?index_name=" + testIndexPattern);
response = client().performRequest(request);
assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode());
Map<String, Object> respMap = (Map<String, Object>) responseAsMap(response);
Map<String, Object> props = (Map<String, Object>)((Map<String, Object>) respMap.get(testIndexPattern)).get("mappings");
assertEquals(4, recurProps(props));
}
public void testCreateMappingSuccess() throws IOException {
String testIndexName = "my_index";
createSampleIndex(testIndexName);
// Execute CreateMappingsAction to add alias mapping for index
Request request = new Request("POST", SecurityAnalyticsPlugin.MAPPER_BASE_URI);
// both req params and req body are supported
request.setJsonEntity(
"{ \"index_name\":\"" + testIndexName + "\"," +
" \"rule_topic\":\"netflow\", " +
" \"partial\":true" +
"}"
);
Response response = client().performRequest(request);
assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode());
// Verify mappings
GetMappingsResponse getMappingsResponse = SecurityAnalyticsClientUtils.executeGetMappingsRequest(testIndexName);
MappingsTraverser mappingsTraverser = new MappingsTraverser(getMappingsResponse.getMappings().entrySet().iterator().next().getValue());
// After applying netflow aliases, our index will have 4 alias mappings
List<String> flatProperties = mappingsTraverser.extractFlatNonAliasFields();
assertFalse(flatProperties.contains("source.ip"));
assertFalse(flatProperties.contains("destination.ip"));
assertFalse(flatProperties.contains("source.port"));
assertFalse(flatProperties.contains("destination.port"));
// Try searching by alias field
String query = "{" +
" \"query\": {" +
" \"query_string\": {" +
" \"query\": \"source.port:4444\"" +
" }" +
" }" +
"}";
SearchResponse searchResponse = SecurityAnalyticsClientUtils.executeSearchRequest(testIndexName, query);
assertEquals(1L, searchResponse.getHits().getTotalHits().value);
}
public void testCreateMappingWithAliasesSuccess() throws IOException {
String testIndexName = "my_index";
createSampleIndex(testIndexName);
// Execute CreateMappingsAction to add alias mapping for index
Request request = new Request("POST", SecurityAnalyticsPlugin.MAPPER_BASE_URI);
// both req params and req body are supported
request.setJsonEntity(
"{\n" +
" \"index_name\": \"my_index\",\n" +
" \"rule_topic\":\"netflow\", " +
" \"partial\":true," +
" \"alias_mappings\": {\n" +
" \"properties\": {\n" +
" \"source.ip\": {\n" +
" \"type\": \"alias\",\n" +
" \"path\": \"netflow.source_ipv4_address\"\n" +
" },\n" +
" \"source.port\": {\n" +
" \"type\": \"alias\",\n" +
" \"path\": \"netflow.source_transport_port\"\n" +
" }\n" +
" }\n" +
" }\n" +
"}"
);
// request.addParameter("indexName", testIndexName);
// request.addParameter("ruleTopic", "netflow");
Response response = client().performRequest(request);
assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode());
// Verify mappings
GetMappingsResponse getMappingsResponse = SecurityAnalyticsClientUtils.executeGetMappingsRequest(testIndexName);
MappingsTraverser mappingsTraverser = new MappingsTraverser(getMappingsResponse.getMappings().entrySet().iterator().next().getValue());
List<String> flatProperties = mappingsTraverser.extractFlatNonAliasFields();
assertFalse(flatProperties.contains("source.ip"));
assertFalse(flatProperties.contains("source.port"));
// Try searching by alias field
String query = "{" +
" \"query\": {" +
" \"query_string\": {" +
" \"query\": \"source.port:4444\"" +
" }" +
" }" +
"}";
SearchResponse searchResponse = SecurityAnalyticsClientUtils.executeSearchRequest(testIndexName, query);
assertEquals(1L, searchResponse.getHits().getTotalHits().value);
}
public void testUpdateAndGetMappingSuccess() throws IOException {
String testIndexName = "my_index";
createSampleIndex(testIndexName);
// Execute UpdateMappingsAction to add alias mapping for index
Request updateRequest = new Request("PUT", SecurityAnalyticsPlugin.MAPPER_BASE_URI);
// both req params and req body are supported
updateRequest.setJsonEntity(
"{ \"index_name\":\"" + testIndexName + "\"," +
" \"field\":\"netflow.source_transport_port\","+
" \"alias\":\"source.port\" }"
);
// request.addParameter("indexName", testIndexName);
// request.addParameter("ruleTopic", "netflow");
Response response = client().performRequest(updateRequest);
assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode());
// Execute GetIndexMappingsAction and verify mappings
Request getRequest = new Request("GET", SecurityAnalyticsPlugin.MAPPER_BASE_URI);
getRequest.addParameter("index_name", testIndexName);
response = client().performRequest(getRequest);
XContentParser parser = createParser(JsonXContent.jsonXContent, new String(response.getEntity().getContent().readAllBytes(), StandardCharsets.UTF_8));
assertTrue(
(((Map)((Map)((Map)((Map)((Map)parser.map()
.get(testIndexName))
.get("mappings"))
.get("properties"))
.get("source"))
.get("properties"))
.containsKey("port"))
);
// Try searching by alias field
String query = "{" +
" \"query\": {" +
" \"query_string\": {" +
" \"query\": \"source.port:4444\"" +
" }" +
" }" +
"}";
SearchResponse searchResponse = SecurityAnalyticsClientUtils.executeSearchRequest(testIndexName, query);
assertEquals(1L, searchResponse.getHits().getTotalHits().value);
}
// Tests the case when alias mappings are not present on the index
public void testUpdateAndGetMapping_notFound_Success() throws IOException {
String testIndexName = "my_index";
createSampleIndex(testIndexName);
// Execute UpdateMappingsAction to add other settings except alias mapping for index
Request updateRequest = new Request("PUT", SecurityAnalyticsPlugin.MAPPER_BASE_URI);
// both req params and req body are supported
updateRequest.setJsonEntity(
"{ \"index_name\":\"" + testIndexName + "\"," +
" \"field\":\"netflow.source_transport_port\","+
" \"alias\":\"\\u0000\" }"
);
Response response = client().performRequest(updateRequest);
assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode());
// Execute GetIndexMappingsAction and verify mappings
Request getRequest = new Request("GET", SecurityAnalyticsPlugin.MAPPER_BASE_URI);
getRequest.addParameter("index_name", testIndexName);
response = client().performRequest(getRequest);
XContentParser parser = createParser(JsonXContent.jsonXContent, new String(response.getEntity().getContent().readAllBytes(), StandardCharsets.UTF_8));
assertTrue(
(((Map)((Map)parser.map()
.get(testIndexName))
.get("mappings"))
.containsKey("properties")));
}
public void testExistingMappingsAreUntouched() throws IOException {
String testIndexName = "existing_mappings_ok";
createSampleIndex(testIndexName);
// Execute CreateMappingsAction to add alias mapping for index
Request request = new Request("POST", SecurityAnalyticsPlugin.MAPPER_BASE_URI);
// both req params and req body are supported
request.setJsonEntity(
"{ \"index_name\":\"" + testIndexName + "\"," +
" \"rule_topic\":\"netflow\"," +
" \"partial\":true }"
);
Response response = client().performRequest(request);
assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode());
// Verify mappings
GetMappingsResponse getMappingsResponse = SecurityAnalyticsClientUtils.executeGetMappingsRequest(testIndexName);
Map<String, Object> properties =
(Map<String, Object>) getMappingsResponse.getMappings().get(testIndexName)
.getSourceAsMap().get("properties");
// Verify that there is still mapping for integer field "plain1"
assertTrue(((Map<String, Object>)properties.get("plain1")).get("type").equals("integer"));
}
public void testCreateIndexMappingsIndexMappingsEmpty() throws IOException {
String testIndexName = "my_index_alias_fail_1";
createIndex(testIndexName, Settings.EMPTY);
// Execute UpdateMappingsAction to add alias mapping for index
Request request = new Request("POST", SecurityAnalyticsPlugin.MAPPER_BASE_URI);
// both req params and req body are supported
request.setJsonEntity(
"{ \"index_name\":\"" + testIndexName + "\"," +
" \"rule_topic\":\"netflow\"," +
" \"partial\":true }"
);
try {
client().performRequest(request);
} catch (ResponseException e) {
assertTrue(e.getMessage().contains("Failed applying mappings to index"));
}
}
public void testIndexNotExists() {
String indexName = java.util.UUID.randomUUID().toString();
Request request = new Request("PUT", SecurityAnalyticsPlugin.MAPPER_BASE_URI);
request.addParameter("index_name", indexName);
request.addParameter("field", "field1");
request.addParameter("alias", "alias123");
try {
client().performRequest(request);
} catch (Exception e) {
assertTrue(e.getMessage().contains("Could not find index [" + indexName + "]"));
}
}
public void testGetMappingsViewSuccess() throws IOException {
String testIndexName = "get_mappings_view_index";
createSampleIndex(testIndexName);
// Execute GetMappingsViewAction to add alias mapping for index
Request request = new Request("GET", SecurityAnalyticsPlugin.MAPPINGS_VIEW_BASE_URI);
// both req params and req body are supported
request.addParameter("index_name", testIndexName);
request.addParameter("rule_topic", "netflow");
Response response = client().performRequest(request);
assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode());
Map<String, Object> respMap = responseAsMap(response);
// Verify alias mappings
Map<String, Object> props = (Map<String, Object>) respMap.get("properties");
assertEquals(4, props.size());
assertTrue(props.containsKey("source.ip"));
assertTrue(props.containsKey("destination.ip"));
assertTrue(props.containsKey("source.port"));
assertTrue(props.containsKey("destination.port"));
// Verify unmapped index fields
List<String> unmappedIndexFields = (List<String>) respMap.get("unmapped_index_fields");
assertEquals(6, unmappedIndexFields.size());
// Verify unmapped field aliases
List<String> unmappedFieldAliases = (List<String>) respMap.get("unmapped_field_aliases");
assertEquals(3, unmappedFieldAliases.size());
List<HashMap<String, Object>> iocFieldsList = (List<HashMap<String, Object>>) respMap.get(GetMappingsViewResponse.THREAT_INTEL_FIELD_ALIASES);
assertEquals(iocFieldsList.size(), 1);
}
public void testGetMappingsViewLinuxSuccess() throws IOException {
String testIndexName = "get_mappings_view_index";
createSampleIndex(testIndexName);
// Execute GetMappingsViewAction to add alias mapping for index
Request request = new Request("GET", SecurityAnalyticsPlugin.MAPPINGS_VIEW_BASE_URI);
// both req params and req body are supported
request.addParameter("index_name", testIndexName);
request.addParameter("rule_topic", "linux");
Response response = client().performRequest(request);
assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode());
}
// Tests mappings where multiple raw fields correspond to one ecs value
public void testGetMappingsViewWindowsSuccess() throws IOException {
String testIndexName = "get_mappings_view_index";
createSampleWindex(testIndexName);
// Execute GetMappingsViewAction to add alias mapping for index
Request request = new Request("GET", SecurityAnalyticsPlugin.MAPPINGS_VIEW_BASE_URI);
// both req params and req body are supported
request.addParameter("index_name", testIndexName);
request.addParameter("rule_topic", "windows");
Response response = client().performRequest(request);
assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode());
Map<String, Object> respMap = responseAsMap(response);
// Verify alias mappings
Map<String, Object> props = (Map<String, Object>) respMap.get("properties");
assertEquals(3, props.size());
assertTrue(props.containsKey("winlog.event_data.LogonType"));
assertTrue(props.containsKey("winlog.provider_name"));
assertTrue(props.containsKey("host.hostname"));
// Verify unmapped index fields
List<String> unmappedIndexFields = (List<String>) respMap.get("unmapped_index_fields");
assertEquals(3, unmappedIndexFields.size());
assert(unmappedIndexFields.contains("plain1"));
assert(unmappedIndexFields.contains("ParentUser.first"));
assert(unmappedIndexFields.contains("ParentUser.last"));
// Verify unmapped field aliases
List<String> filteredUnmappedFieldAliases = (List<String>) respMap.get("unmapped_field_aliases");
assertEquals(191, filteredUnmappedFieldAliases.size());
assert(!filteredUnmappedFieldAliases.contains("winlog.event_data.LogonType"));
assert(!filteredUnmappedFieldAliases.contains("winlog.provider_name"));
assert(!filteredUnmappedFieldAliases.contains("host.hostname"));
List<HashMap<String, Object>> iocFieldsList = (List<HashMap<String, Object>>) respMap.get(GetMappingsViewResponse.THREAT_INTEL_FIELD_ALIASES);
assertEquals(iocFieldsList.size(), 1);
// Index a doc for a field with multiple raw fields corresponding to one ecs field
indexDoc(testIndexName, "1", "{ \"EventID\": 1 }");
// Execute GetMappingsViewAction to add alias mapping for index
request = new Request("GET", SecurityAnalyticsPlugin.MAPPINGS_VIEW_BASE_URI);
// both req params and req body are supported
request.addParameter("index_name", testIndexName);
request.addParameter("rule_topic", "windows");
response = client().performRequest(request);
assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode());
respMap = responseAsMap(response);
// Verify alias mappings
props = (Map<String, Object>) respMap.get("properties");
assertEquals(4, props.size());
assertTrue(props.containsKey("winlog.event_id"));
// verify unmapped index fields
unmappedIndexFields = (List<String>) respMap.get("unmapped_index_fields");
assertEquals(3, unmappedIndexFields.size());
// verify unmapped field aliases
filteredUnmappedFieldAliases = (List<String>) respMap.get("unmapped_field_aliases");
assertEquals(190, filteredUnmappedFieldAliases.size());
assert(!filteredUnmappedFieldAliases.contains("winlog.event_id"));
}
// Tests mappings where multiple raw fields correspond to one ecs value and all fields are present in the index
public void testGetMappingsViewMulitpleRawFieldsSuccess() throws IOException {
String testIndexName = "get_mappings_view_index";
createSampleWindex(testIndexName);
String sampleDoc = "{" +
" \"EventID\": 1," +
" \"EventId\": 2," +
" \"event_uid\": 3" +
"}";
indexDoc(testIndexName, "1", sampleDoc);
// Execute GetMappingsViewAction to add alias mapping for index
Request request = new Request("GET", SecurityAnalyticsPlugin.MAPPINGS_VIEW_BASE_URI);
// both req params and req body are supported
request.addParameter("index_name", testIndexName);
request.addParameter("rule_topic", "windows");
Response response = client().performRequest(request);
assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode());
Map<String, Object> respMap = responseAsMap(response);
// Verify alias mappings
Map<String, Object> props = (Map<String, Object>) respMap.get("properties");
assertEquals(4, props.size());
assertTrue(props.containsKey("winlog.event_data.LogonType"));
assertTrue(props.containsKey("winlog.provider_name"));
assertTrue(props.containsKey("host.hostname"));
assertTrue(props.containsKey("winlog.event_id"));
// Verify unmapped index fields
List<String> unmappedIndexFields = (List<String>) respMap.get("unmapped_index_fields");
assertEquals(5, unmappedIndexFields.size());
// Verify unmapped field aliases
List<String> filteredUnmappedFieldAliases = (List<String>) respMap.get("unmapped_field_aliases");
assertEquals(190, filteredUnmappedFieldAliases.size());
assert(!filteredUnmappedFieldAliases.contains("winlog.event_data.LogonType"));
assert(!filteredUnmappedFieldAliases.contains("winlog.provider_name"));
assert(!filteredUnmappedFieldAliases.contains("host.hostname"));
assert(!filteredUnmappedFieldAliases.contains("winlog.event_id"));
}
public void testCreateMappings_withDatastream_success() throws IOException {
String datastream = "test_datastream";
String datastreamMappings = "\"properties\": {" +
" \"@timestamp\":{ \"type\": \"date\" }," +
" \"netflow.destination_transport_port\":{ \"type\": \"long\" }," +
" \"netflow.destination_ipv4_address\":{ \"type\": \"ip\" }" +
"}";
createSampleDatastream(datastream, datastreamMappings);
// Execute CreateMappingsAction to add alias mapping for index
createMappingsAPI(datastream, "netflow");
// Verify mappings
Map<String, Object> props = getIndexMappingsAPIFlat(datastream);
assertEquals(5, props.size());
assertTrue(props.containsKey("@timestamp"));
assertTrue(props.containsKey("netflow.destination_transport_port"));
assertTrue(props.containsKey("netflow.destination_ipv4_address"));
assertTrue(props.containsKey("destination.ip"));
assertTrue(props.containsKey("destination.port"));
// Verify that index template applied mappings
Response response = makeRequest(client(), "POST", datastream + "/_rollover", Collections.emptyMap(), null);
assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode());
// Insert doc to index to add additional fields to mapping
String sampleDoc = "{" +
" \"@timestamp\":\"2023-01-06T00:05:00\"," +
" \"netflow.source_ipv4_address\":\"10.50.221.10\"," +
" \"netflow.source_transport_port\":4444" +
"}";
indexDoc(datastream, "2", sampleDoc);
// Execute CreateMappingsAction to add alias mapping for index
createMappingsAPI(datastream, "netflow");
String writeIndex = getDatastreamWriteIndex(datastream);
// Verify mappings
props = getIndexMappingsAPIFlat(writeIndex);
assertEquals(9, props.size());
assertTrue(props.containsKey("@timestamp"));
assertTrue(props.containsKey("netflow.source_ipv4_address"));
assertTrue(props.containsKey("netflow.source_transport_port"));
assertTrue(props.containsKey("netflow.destination_transport_port"));
assertTrue(props.containsKey("netflow.destination_ipv4_address"));
assertTrue(props.containsKey("destination.ip"));
assertTrue(props.containsKey("destination.port"));
assertTrue(props.containsKey("source.ip"));
assertTrue(props.containsKey("source.port"));
// Get applied mappings
props = getIndexMappingsSAFlat(datastream);
assertTrue(props.containsKey("destination.ip"));
assertTrue(props.containsKey("destination.port"));
assertTrue(props.containsKey("source.ip"));
assertTrue(props.containsKey("source.port"));
deleteDatastreamAPI(datastream);
}
public void testCreateMappings_withDatastream_withTemplateField_success() throws IOException {
String datastream = "test_datastream";
String datastreamMappings = "\"properties\": {" +
" \"@timestamp\":{ \"type\": \"date\" }," +
" \"netflow.destination_transport_port\":{ \"type\": \"long\" }," +
" \"netflow.destination_ipv4_address\":{ \"type\": \"ip\" }" +
"}";
createSampleDatastream(datastream, datastreamMappings, false);
// Execute CreateMappingsAction to add alias mapping for index
createMappingsAPI(datastream, "netflow");
// Verify mappings
Map<String, Object> props = getIndexMappingsAPIFlat(datastream);
assertEquals(5, props.size());
assertTrue(props.containsKey("@timestamp"));
assertTrue(props.containsKey("netflow.destination_transport_port"));
assertTrue(props.containsKey("netflow.destination_ipv4_address"));
assertTrue(props.containsKey("destination.ip"));
assertTrue(props.containsKey("destination.port"));
// Verify that index template applied mappings
Response response = makeRequest(client(), "POST", datastream + "/_rollover", Collections.emptyMap(), null);
assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode());
// Insert doc to index to add additional fields to mapping
String sampleDoc = "{" +
" \"@timestamp\":\"2023-01-06T00:05:00\"," +
" \"netflow.source_ipv4_address\":\"10.50.221.10\"," +
" \"netflow.source_transport_port\":4444" +
"}";
indexDoc(datastream, "2", sampleDoc);
// Execute CreateMappingsAction to add alias mapping for index
createMappingsAPI(datastream, "netflow");
String writeIndex = getDatastreamWriteIndex(datastream);
// Verify mappings
props = getIndexMappingsAPIFlat(writeIndex);
assertEquals(9, props.size());
assertTrue(props.containsKey("@timestamp"));
assertTrue(props.containsKey("netflow.source_ipv4_address"));
assertTrue(props.containsKey("netflow.source_transport_port"));
assertTrue(props.containsKey("netflow.destination_transport_port"));
assertTrue(props.containsKey("netflow.destination_ipv4_address"));
assertTrue(props.containsKey("destination.ip"));
assertTrue(props.containsKey("destination.port"));
assertTrue(props.containsKey("source.ip"));
assertTrue(props.containsKey("source.port"));
// Get applied mappings
props = getIndexMappingsSAFlat(datastream);
assertTrue(props.containsKey("destination.ip"));
assertTrue(props.containsKey("destination.port"));
assertTrue(props.containsKey("source.ip"));
assertTrue(props.containsKey("source.port"));
deleteDatastreamAPI(datastream);
}
public void testCreateMappings_withIndexPattern_existing_indexTemplate_update_success() throws IOException {
String indexName1 = "test_index_1";
String indexName2 = "test_index_2";
String indexName3 = "test_index_3";
String indexPattern = "test_index*";
String componentTemplateMappings = "\"properties\": {" +
" \"netflow.destination_transport_port\":{ \"type\": \"long\" }," +
" \"netflow.destination_ipv4_address\":{ \"type\": \"ip\" }" +
"}";
// Setup index_template
createComponentTemplateWithMappings(
IndexTemplateUtils.computeComponentTemplateName(indexPattern),
componentTemplateMappings
);
createComposableIndexTemplate(
IndexTemplateUtils.computeIndexTemplateName(indexPattern),
List.of(indexPattern),
IndexTemplateUtils.computeComponentTemplateName(indexPattern),
null,
false
);
createIndex(indexName1, Settings.EMPTY, null);
// Execute CreateMappingsAction to apply alias mappings - index template should be updated
createMappingsAPI(indexPattern, "netflow");
// Create new index to verify that index template is updated
createIndex(indexName2, Settings.EMPTY, null);
// Verify that template applied mappings
Map<String, Object> props = getIndexMappingsAPIFlat(indexName2);
assertEquals(4, props.size());
assertTrue(props.containsKey("netflow.destination_transport_port"));
assertTrue(props.containsKey("netflow.destination_ipv4_address"));
assertTrue(props.containsKey("destination.ip"));
assertTrue(props.containsKey("destination.port"));
// Verify our GetIndexMappings -- applied mappings
props = getIndexMappingsSAFlat(indexPattern);
assertEquals(2, props.size());
assertTrue(props.containsKey("destination.ip"));
assertTrue(props.containsKey("destination.port"));
// Insert doc to index to add additional fields to mapping
String sampleDoc = "{" +
" \"netflow.source_ipv4_address\":\"10.50.221.10\"," +
" \"netflow.source_transport_port\":4444" +
"}";
indexDoc(indexName2, "1", sampleDoc);
// Call CreateMappings API and expect index template to be updated with 2 additional aliases
createMappingsAPI(indexPattern, "netflow");
// Create new index to verify that index template was updated correctly
createIndex(indexName3, Settings.EMPTY, null);
// Verify mappings
props = getIndexMappingsAPIFlat(indexName3);
assertEquals(8, props.size());
assertTrue(props.containsKey("source.ip"));
assertTrue(props.containsKey("destination.ip"));
assertTrue(props.containsKey("source.port"));
assertTrue(props.containsKey("destination.port"));
assertTrue(props.containsKey("netflow.source_transport_port"));
assertTrue(props.containsKey("netflow.source_ipv4_address"));
assertTrue(props.containsKey("netflow.destination_transport_port"));
assertTrue(props.containsKey("netflow.destination_ipv4_address"));
// Verify our GetIndexMappings -- applied mappings
props = getIndexMappingsSAFlat(indexPattern);
assertEquals(4, props.size());
assertTrue(props.containsKey("source.ip"));
assertTrue(props.containsKey("destination.ip"));
assertTrue(props.containsKey("source.port"));
assertTrue(props.containsKey("destination.port"));
}
public void testCreateMappings_withIndexPattern_differentMappings_indexTemplateCleanup_success() throws IOException, InterruptedException {
String indexName1 = "test_index_1";
String indexName2 = "test_index_2";
String indexPattern = "test_index*";
createIndex(indexName1, Settings.EMPTY, null);
createIndex(indexName2, Settings.EMPTY, null);
// client().performRequest(new Request("POST", "_refresh"));
// Insert sample docs
String sampleDoc1 = "{" +
" \"netflow.source_ipv4_address\":\"10.50.221.10\"," +
" \"netflow.destination_transport_port\":1234," +
" \"netflow.source_transport_port\":4444" +
"}";
String sampleDoc2 = "{" +
" \"netflow.destination_transport_port\":1234," +
" \"netflow.destination_ipv4_address\":\"10.53.111.14\"" +
"}";
indexDoc(indexName1, "1", sampleDoc1);
indexDoc(indexName2, "1", sampleDoc2);
// client().performRequest(new Request("POST", "_refresh"));
// Execute CreateMappingsAction to add alias mapping for index
createMappingsAPI(indexPattern, "netflow");
DetectorInput input = new DetectorInput("", List.of(indexPattern), List.of(),
getRandomPrePackagedRules().stream().map(DetectorRule::new).collect(Collectors.toList()));
String detectorId = createDetector(TestHelpers.randomDetectorWithInputs(List.of((input))));
refreshAllIndices();
List<Object> componentTemplates = getAllComponentTemplates();
assertEquals(1, componentTemplates.size());
List<Object> composableIndexTemplates = getAllComposableIndexTemplates();
assertEquals(2, composableIndexTemplates.size());
deleteDetector(detectorId);
// Wait for clusterState update to be published/applied
OpenSearchTestCase.waitUntil(() -> {
try {
List<Object> ct = getAllComponentTemplates();
if (ct.size() == 0) {
return true;
} else {
return false;
}
} catch (IOException e) {
}
return false;
});
OpenSearchTestCase.waitUntil(() -> {
try {
List<Object> cct = getAllComposableIndexTemplates();
if (cct.size() == 1) {
return true;
} else {
return false;
}
} catch (IOException e) {
}
return false;
});
componentTemplates = getAllComponentTemplates();
assertEquals(0, componentTemplates.size());
composableIndexTemplates = getAllComposableIndexTemplates();
assertEquals(1, composableIndexTemplates.size());
}
public void testCreateMappings_withIndexPattern_indexTemplate_createAndUpdate_success() throws IOException {
String indexName1 = "test_index_1";
String indexName2 = "test_index_2";
String indexName3 = "test_index_3";
String indexName4 = "test_index_4";
String indexPattern = "test_index*";
createIndex(indexName1, Settings.EMPTY, null);
createIndex(indexName2, Settings.EMPTY, null);
// client().performRequest(new Request("POST", "_refresh"));
// Insert sample doc
String sampleDoc1 = "{" +
" \"netflow.destination_transport_port\":1234," +
" \"netflow.destination_ipv4_address\":\"10.53.111.14\"" +
"}";
indexDoc(indexName1, "1", sampleDoc1);
indexDoc(indexName2, "1", sampleDoc1);
// client().performRequest(new Request("POST", "_refresh"));
// Execute CreateMappingsAction to add alias mapping for index
createMappingsAPI(indexPattern, "netflow");
// Verify that index template is up
createIndex(indexName3, Settings.EMPTY, null);
// Execute CreateMappingsAction to add alias mapping for index
Request request = new Request("GET", indexName3 + "/_mapping");
Response response = client().performRequest(request);
assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode());
Map<String, Object> respMap = (Map<String, Object>) responseAsMap(response).get(indexName3);
MappingsTraverser mappingsTraverser = new MappingsTraverser((Map<String, Object>) respMap.get("mappings"), Set.of());
Map<String, Object> flatMappings = mappingsTraverser.traverseAndCopyAsFlat();
// Verify mappings
Map<String, Object> props = (Map<String, Object>) flatMappings.get("properties");
assertEquals(4, props.size());
assertTrue(props.containsKey("destination.ip"));
assertTrue(props.containsKey("destination.port"));
assertTrue(props.containsKey("netflow.destination_transport_port"));
assertTrue(props.containsKey("netflow.destination_ipv4_address"));
String sampleDoc2 = "{" +
" \"netflow.source_ipv4_address\":\"10.50.221.10\"," +
" \"netflow.destination_transport_port\":1234," +
" \"netflow.destination_ipv4_address\":\"10.53.111.14\"," +
" \"netflow.source_transport_port\":4444" +
"}";
indexDoc(indexName3, "1", sampleDoc2);
// Execute CreateMappingsAction to add alias mapping for index
createMappingsAPI(indexPattern, "netflow");
// Verify that index template is updated
createIndex(indexName4, Settings.EMPTY, null);
// Execute CreateMappingsAction to add alias mapping for index
request = new Request("GET", indexName4 + "/_mapping");
response = client().performRequest(request);
assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode());
respMap = (Map<String, Object>) responseAsMap(response).get(indexName4);
mappingsTraverser = new MappingsTraverser((Map<String, Object>) respMap.get("mappings"), Set.of());
flatMappings = mappingsTraverser.traverseAndCopyAsFlat();
// Verify mappings
props = (Map<String, Object>) flatMappings.get("properties");
assertEquals(8, props.size());
assertTrue(props.containsKey("source.ip"));
assertTrue(props.containsKey("destination.ip"));
assertTrue(props.containsKey("source.port"));
assertTrue(props.containsKey("destination.port"));
assertTrue(props.containsKey("netflow.source_transport_port"));
assertTrue(props.containsKey("netflow.source_ipv4_address"));
assertTrue(props.containsKey("netflow.destination_transport_port"));
assertTrue(props.containsKey("netflow.destination_ipv4_address"));
// Verify applied mappings
props = getIndexMappingsSAFlat(indexName4);
assertEquals(4, props.size());
assertTrue(props.containsKey("source.ip"));
assertTrue(props.containsKey("destination.ip"));
assertTrue(props.containsKey("source.port"));
assertTrue(props.containsKey("destination.port"));
}
public void testCreateMappings_withIndexPattern_oneNoMappings_failure() throws IOException {
String indexName1 = "test_index_1";
String indexName2 = "test_index_2";
String indexPattern = "test_index*";
createIndex(indexName1, Settings.EMPTY, null);
createIndex(indexName2, Settings.EMPTY, null);
// client().performRequest(new Request("POST", "_refresh"));
// Insert sample docs
String sampleDoc1 = "{" +
" \"netflow.source_ipv4_address\":\"10.50.221.10\"," +
" \"netflow.destination_transport_port\":1234," +
" \"netflow.source_transport_port\":4444" +
"}";
indexDoc(indexName1, "1", sampleDoc1);
// client().performRequest(new Request("POST", "_refresh"));
// Execute CreateMappingsAction to add alias mapping for index
try {
createMappingsAPI(indexPattern, "netflow");
fail("expected 500 failure!");
} catch (ResponseException e) {
assertEquals(HttpStatus.SC_INTERNAL_SERVER_ERROR, e.getResponse().getStatusLine().getStatusCode());
}
}
public void testGetMappingsView_index_pattern_two_indices_Success() throws IOException {
String testIndexName1 = "get_mappings_view_index111";
String testIndexName2 = "get_mappings_view_index122";
String testIndexName3 = "get_mappings_view_index";
String indexPattern = "get_mappings_view_index1*";
String indexPattern2 = "get_mappings_view_index*";
createSampleIndex(testIndexName1);
createSampleIndex(testIndexName2);
indexDoc(testIndexName2, "987654", "{ \"extra_field\": 12345 }");
// Execute CreateMappingsAction to add alias mapping for index
Request request = new Request("GET", SecurityAnalyticsPlugin.MAPPINGS_VIEW_BASE_URI);
// both req params and req body are supported
request.addParameter("index_name", indexPattern);
request.addParameter("rule_topic", "netflow");
Response response = client().performRequest(request);
assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode());
Map<String, Object> respMap = responseAsMap(response);
// Verify alias mappings
Map<String, Object> props = (Map<String, Object>) respMap.get("properties");
assertEquals(4, props.size());
assertTrue(props.containsKey("source.ip"));
assertTrue(props.containsKey("destination.ip"));
assertTrue(props.containsKey("source.port"));
assertTrue(props.containsKey("destination.port"));
// Verify unmapped index fields
List<String> unmappedIndexFields = (List<String>) respMap.get("unmapped_index_fields");
assertEquals(7, unmappedIndexFields.size());
// Verify that we got Mappings View of concrete index testIndexName2 because it is newest of all under this alias
Optional<String> extraField = unmappedIndexFields.stream().filter(e -> e.equals("extra_field")).findFirst();
assertTrue(extraField.isPresent());
// Verify unmapped field aliases
List<String> unmappedFieldAliases = (List<String>) respMap.get("unmapped_field_aliases");
assertEquals(3, unmappedFieldAliases.size());
}
public void testGetMappingsView_alias_without_writeindex_Success() throws IOException {
String testIndexName1 = "get_mappings_view_index11";
String testIndexName2 = "get_mappings_view_index22";
String indexAlias = "index_alias";
createSampleIndex(testIndexName1, Settings.EMPTY, "\"" + indexAlias + "\":{}");
createSampleIndex(testIndexName2, Settings.EMPTY, "\"" + indexAlias + "\":{}");
indexDoc(testIndexName2, "987654", "{ \"extra_field\": 12345 }");
// Execute CreateMappingsAction to add alias mapping for index
Request request = new Request("GET", SecurityAnalyticsPlugin.MAPPINGS_VIEW_BASE_URI);
// both req params and req body are supported
request.addParameter("index_name", indexAlias);
request.addParameter("rule_topic", "netflow");
Response response = client().performRequest(request);
assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode());
Map<String, Object> respMap = responseAsMap(response);
// Verify alias mappings
Map<String, Object> props = (Map<String, Object>) respMap.get("properties");
assertEquals(4, props.size());
assertTrue(props.containsKey("source.ip"));
assertTrue(props.containsKey("destination.ip"));
assertTrue(props.containsKey("source.port"));
assertTrue(props.containsKey("destination.port"));
// Verify unmapped index fields
List<String> unmappedIndexFields = (List<String>) respMap.get("unmapped_index_fields");
assertEquals(7, unmappedIndexFields.size());
// Verify that we got Mappings View of concrete index testIndexName2 because it is newest of all under this alias
Optional<String> extraField = unmappedIndexFields.stream().filter(e -> e.equals("extra_field")).findFirst();
assertTrue(extraField.isPresent());
// Verify unmapped field aliases
List<String> unmappedFieldAliases = (List<String>) respMap.get("unmapped_field_aliases");
assertEquals(3, unmappedFieldAliases.size());
}
public void testGetMappingsView_alias_with_writeindex_Success() throws IOException {
String testIndexName1 = "get_mappings_view_index11";
String testIndexName2 = "get_mappings_view_index22";
String indexAlias = "index_alias";
createSampleIndex(testIndexName2, Settings.EMPTY, "\"" + indexAlias + "\":{}");
createSampleIndex(testIndexName1, Settings.EMPTY, "\"" + indexAlias + "\":{ \"is_write_index\":true }");
// Add extra field by inserting doc to index #1 to differentiate two easier
indexDoc(testIndexName1, "987654", "{ \"extra_field\": 12345 }");
// Execute CreateMappingsAction to add alias mapping for index
Request request = new Request("GET", SecurityAnalyticsPlugin.MAPPINGS_VIEW_BASE_URI);