-
Notifications
You must be signed in to change notification settings - Fork 798
/
middleware.js
3441 lines (3396 loc) · 165 KB
/
middleware.js
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
import moment from 'moment';
import * as R from 'ramda';
import DataLoader from 'dataloader';
import { Promise } from 'bluebird';
import { compareUnsorted } from 'js-deep-equals';
import { SemanticAttributes } from '@opentelemetry/semantic-conventions';
import * as jsonpatch from 'fast-json-patch';
import {
ALREADY_DELETED_ERROR,
AlreadyDeletedError,
DatabaseError,
ForbiddenAccess,
FunctionalError,
LockTimeoutError,
MissingReferenceError,
TYPE_LOCK_ERROR,
UnsupportedError,
ValidationError,
} from '../config/errors';
import { extractEntityRepresentativeName, extractRepresentative } from './entity-representative';
import {
buildPagination,
computeAverage,
extractIdsFromStoreObject,
fillTimeSeries,
INDEX_INFERRED_RELATIONSHIPS,
inferIndexFromConceptType,
isEmptyField,
isInferredIndex,
isNotEmptyField,
isObjectPathTargetMultipleAttribute,
MAX_EVENT_LOOP_PROCESSING_TIME,
READ_DATA_INDICES,
READ_DATA_INDICES_INFERRED,
READ_INDEX_HISTORY,
READ_INDEX_INFERRED_RELATIONSHIPS,
READ_RELATIONSHIPS_INDICES,
READ_RELATIONSHIPS_INDICES_WITHOUT_INFERRED,
UPDATE_OPERATION_ADD,
UPDATE_OPERATION_REMOVE,
UPDATE_OPERATION_REPLACE
} from './utils';
import {
elAggregationCount,
elAggregationRelationsCount,
elDeleteElements,
elFindByIds,
elHistogramCount,
elIndexElements,
elList,
elPaginate,
elUpdateElement,
elUpdateEntityConnections,
elUpdateRelationConnections,
ES_MAX_CONCURRENCY,
ES_MAX_PAGINATION,
isImpactedTypeAndSide,
MAX_BULK_OPERATIONS,
ROLE_FROM,
ROLE_TO
} from './engine';
import {
FIRST_OBSERVED,
FIRST_SEEN,
generateAliasesId,
generateAliasesIdsForInstance,
generateInternalId,
generateStandardId,
getInputIds,
getInstanceIds,
idGenFromData,
INTERNAL_FROM_FIELD,
INTERNAL_TO_FIELD,
isFieldContributingToStandardId,
isStandardIdDowngraded,
isStandardIdUpgraded,
LAST_OBSERVED,
LAST_SEEN,
NAME_FIELD,
normalizeName,
REVOKED,
START_TIME,
STOP_TIME,
VALID_FROM,
VALID_UNTIL,
VALUE_FIELD,
X_DETECTION,
X_WORKFLOW_ID,
} from '../schema/identifier';
import { lockResource, notify, redisAddDeletions, storeCreateEntityEvent, storeCreateRelationEvent, storeDeleteEvent, storeMergeEvent, storeUpdateEvent } from './redis';
import { cleanStixIds } from './stix';
import {
ABSTRACT_BASIC_RELATIONSHIP,
ABSTRACT_STIX_CORE_OBJECT,
ABSTRACT_STIX_OBJECT,
ABSTRACT_STIX_RELATIONSHIP,
BASE_TYPE_ENTITY,
BASE_TYPE_RELATION,
buildRefRelationKey,
ID_INTERNAL,
ID_STANDARD,
IDS_STIX,
INPUT_EXTERNAL_REFS,
INPUT_GRANTED_REFS,
INPUT_LABELS,
INPUT_MARKINGS,
INTERNAL_IDS_ALIASES,
INTERNAL_PREFIX,
REL_INDEX_PREFIX,
RULE_PREFIX,
} from '../schema/general';
import { getParentTypes, isAnId } from '../schema/schemaUtils';
import {
isStixRefRelationship,
RELATION_CREATED_BY,
RELATION_EXTERNAL_REFERENCE,
RELATION_GRANTED_TO,
RELATION_KILL_CHAIN_PHASE,
RELATION_OBJECT,
RELATION_OBJECT_MARKING,
STIX_REF_RELATIONSHIP_TYPES
} from '../schema/stixRefRelationship';
import { ENTITY_TYPE_SETTINGS, ENTITY_TYPE_STATUS, ENTITY_TYPE_USER, isDatedInternalObject } from '../schema/internalObject';
import { isStixCoreObject, isStixObject } from '../schema/stixCoreObject';
import { isBasicRelationship, isStixRelationshipExceptRef } from '../schema/stixRelationship';
import {
dateForEndAttributes,
dateForLimitsAttributes,
dateForStartAttributes,
extractNotFuzzyHashValues,
isModifiedObject,
isUpdatedAtObject,
noReferenceAttributes,
} from '../schema/fieldDataAdapter';
import { isStixCoreRelationship, RELATION_REVOKED_BY } from '../schema/stixCoreRelationship';
import {
ATTRIBUTE_ADDITIONAL_NAMES,
ATTRIBUTE_ALIASES,
ATTRIBUTE_ALIASES_OPENCTI,
ENTITY_TYPE_CONTAINER_OBSERVED_DATA,
ENTITY_TYPE_IDENTITY_INDIVIDUAL,
isStixDomainObject,
isStixDomainObjectShareableContainer,
isStixObjectAliased,
resolveAliasesField,
STIX_ORGANIZATIONS_UNRESTRICTED,
} from '../schema/stixDomainObject';
import { ENTITY_TYPE_EXTERNAL_REFERENCE, ENTITY_TYPE_LABEL, isStixMetaObject } from '../schema/stixMetaObject';
import { isStixSightingRelationship } from '../schema/stixSightingRelationship';
import { ENTITY_HASHED_OBSERVABLE_ARTIFACT, ENTITY_HASHED_OBSERVABLE_STIX_FILE, isStixCyberObservable, isStixCyberObservableHashedObservable } from '../schema/stixCyberObservable';
import conf, { BUS_TOPICS, logApp } from '../config/conf';
import { FROM_START, FROM_START_STR, mergeDeepRightAll, now, prepareDate, UNTIL_END, UNTIL_END_STR, utcDate } from '../utils/format';
import { checkObservableSyntax } from '../utils/syntax';
import { deleteAllObjectFiles, storeFileConverter, upload } from './file-storage';
import {
BYPASS_REFERENCE,
executionContext,
INTERNAL_USERS,
isBypassUser,
isUserCanAccessStoreElement,
isUserHasCapability,
KNOWLEDGE_ORGANIZATION_RESTRICT,
RULE_MANAGER_USER,
SYSTEM_USER,
userFilterStoreElements,
validateUserAccessOperation
} from '../utils/access';
import { isRuleUser, RULES_ATTRIBUTES_BEHAVIOR } from '../rules/rules-utils';
import { instanceMetaRefsExtractor, isSingleRelationsRef, } from '../schema/stixEmbeddedRelationship';
import { createEntityAutoEnrichment } from '../domain/enrichment';
import { convertExternalReferenceToStix, convertStoreToStix } from './stix-converter';
import {
buildAggregationRelationFilter,
buildEntityFilters,
buildThingsFilters,
internalFindByIds,
internalLoadById,
listAllRelations,
listEntities,
listRelations,
storeLoadById
} from './middleware-loader';
import { checkRelationConsistency, isRelationConsistent } from '../utils/modelConsistency';
import { getEntitiesListFromCache, getEntityFromCache } from './cache';
import { ACTION_TYPE_SHARE, ACTION_TYPE_UNSHARE, createListTask } from '../domain/backgroundTask-common';
import { ENTITY_TYPE_VOCABULARY, vocabularyDefinitions } from '../modules/vocabulary/vocabulary-types';
import { getVocabulariesCategories, getVocabularyCategoryForField, isEntityFieldAnOpenVocabulary, updateElasticVocabularyValue } from '../modules/vocabulary/vocabulary-utils';
import { depsKeysRegister, isDateAttribute, isMultipleAttribute, isNumericAttribute, isObjectAttribute, schemaAttributesDefinition } from '../schema/schema-attributes';
import { fillDefaultValues, getAttributesConfiguration, getEntitySettingFromCache } from '../modules/entitySetting/entitySetting-utils';
import { schemaRelationsRefDefinition } from '../schema/schema-relationsRef';
import { validateInputCreation, validateInputUpdate } from '../schema/schema-validator';
import { telemetry } from '../config/tracing';
import { cleanMarkings, handleMarkingOperations } from '../utils/markingDefinition-utils';
import { generateCreateMessage, generateUpdateMessage } from './generate-message';
import { confidence, creators, xOpenctiStixIds } from '../schema/attribute-definition';
import { ENTITY_TYPE_INDICATOR } from '../modules/indicator/indicator-types';
import { FilterMode, FilterOperator } from '../generated/graphql';
import { getMandatoryAttributesForSetting } from '../modules/entitySetting/entitySetting-attributeUtils';
import {
adaptUpdateInputsConfidence,
controlCreateInputWithUserConfidence,
controlUpsertInputWithUserConfidence,
controlUserConfidenceAgainstElement
} from '../utils/confidence-level';
// region global variables
const MAX_BATCH_SIZE = 300;
// endregion
// region Loader common
export const batchLoader = (loader) => {
const dataLoader = new DataLoader(
(objects) => {
const { context, user, args } = R.head(objects);
const elements = objects.map((i) => i.element);
return loader(context, user, elements, args);
},
{ maxBatchSize: MAX_BATCH_SIZE, cache: false }
);
return {
load: (element, context, user, args = {}) => {
return dataLoader.load({ element, context, user, args });
},
};
};
const checkIfInferenceOperationIsValid = (user, element) => {
const isRuleManaged = isRuleUser(user);
const ifElementInferred = isInferredIndex(element._index);
if (ifElementInferred && !isRuleManaged) {
throw UnsupportedError('Manual inference deletion is not allowed', { id: element.id });
}
};
// endregion
// Standard listing
export const listThings = async (context, user, thingsTypes, args = {}) => {
const { indices = READ_DATA_INDICES } = args;
const paginateArgs = buildThingsFilters(thingsTypes, args);
return elPaginate(context, user, indices, paginateArgs);
};
export const listAllThings = async (context, user, thingsTypes, args = {}) => {
const { indices = READ_DATA_INDICES } = args;
const paginateArgs = buildThingsFilters(thingsTypes, args);
return elList(context, user, indices, paginateArgs);
};
export const paginateAllThings = async (context, user, thingsTypes, args = {}) => {
const result = await listAllThings(context, user, thingsTypes, args);
const nodeResult = result.map((n) => ({ node: n }));
return buildPagination(0, null, nodeResult, nodeResult.length);
};
export const loadEntity = async (context, user, entityTypes, args = {}) => {
const opts = { ...args, connectionFormat: false };
const entities = await listEntities(context, user, entityTypes, opts);
if (entities.length > 1) {
throw DatabaseError('Expect only one response', { entityTypes, args });
}
return R.head(entities);
};
// endregion
// region Loader element
const loadElementMetaDependencies = async (context, user, elements, args = {}) => {
const { onlyMarking = true } = args;
const workingElements = Array.isArray(elements) ? elements : [elements];
const workingElementsMap = new Map(workingElements.map((i) => [i.internal_id, i]));
const workingIds = Array.from(workingElementsMap.keys());
const relTypes = onlyMarking ? [RELATION_OBJECT_MARKING] : STIX_REF_RELATIONSHIP_TYPES;
// Resolve all relations, huge filters are inefficient, splitting will maximize the query speed
const refsRelations = [];
const groupOfWorkingIds = R.splitEvery(ES_MAX_PAGINATION, workingIds);
for (let i = 0; i < groupOfWorkingIds.length; i += 1) {
const fromIds = groupOfWorkingIds[i];
const relationFilter = { mode: FilterMode.And, filters: [{ key: ['fromId'], values: fromIds }], filterGroups: [] };
const refsListed = await listAllRelations(context, user, relTypes, { filters: relationFilter });
refsRelations.push(...refsListed);
}
const refsPerElements = R.groupBy((r) => r.fromId, refsRelations);
// Parallel resolutions
const toResolvedIds = R.uniq(refsRelations.map((rel) => rel.toId));
const toResolvedTypes = R.uniq(refsRelations.map((rel) => rel.toType));
const toResolvedElements = await elFindByIds(context, user, toResolvedIds, { withoutRels: true, type: toResolvedTypes, connectionFormat: false, toMap: true });
const refEntries = Object.entries(refsPerElements);
const loadedElementMap = new Map();
for (let indexRef = 0; indexRef < refEntries.length; indexRef += 1) {
const [refId, dependencies] = refEntries[indexRef];
const element = workingElementsMap.get(refId);
// Build flatten view inside the data for stix meta
const data = {};
if (element) {
const grouped = R.groupBy((a) => a.entity_type, dependencies);
const entries = Object.entries(grouped);
for (let index = 0; index < entries.length; index += 1) {
const [key, values] = entries[index];
const inputKey = schemaRelationsRefDefinition.convertDatabaseNameToInputName(element.entity_type, key);
const resolvedElementsWithRelation = R.map((v) => {
const resolvedElement = toResolvedElements[v.toId];
return resolvedElement ? { ...resolvedElement, i_relation: v } : {};
}, values).filter((d) => isNotEmptyField(d));
const metaRefKey = schemaRelationsRefDefinition.getRelationRef(element.entity_type, inputKey);
if (isEmptyField(metaRefKey)) {
throw UnsupportedError('Schema validation failure when loading dependencies', { key, inputKey, type: element.entity_type });
}
const invalidRelations = values.filter((v) => toResolvedElements[v.toId] === undefined);
if (invalidRelations.length > 0) {
// Some targets can be unresolved in case of potential inconsistency between relation and target
// This kind of situation can happen if:
// - Access rights are asymmetric, should not happen for meta relationships.
// - Relations is invalid, should not happen in platform data consistency.
const relations = invalidRelations.map((v) => ({ relation_id: v.id, target_id: v.toId }));
logApp.warn('Targets of loadElementMetaDependencies not found', { relations });
}
data[key] = !metaRefKey.multiple ? R.head(resolvedElementsWithRelation)?.internal_id : resolvedElementsWithRelation.map((r) => r.internal_id);
data[inputKey] = !metaRefKey.multiple ? R.head(resolvedElementsWithRelation) : resolvedElementsWithRelation;
}
loadedElementMap.set(refId, data);
}
}
return loadedElementMap;
};
const loadElementsWithDependencies = async (context, user, elements, opts = {}) => {
const elementsToDeps = [...elements];
let fromAndToPromise = Promise.resolve();
const targetsToResolved = [];
elements.forEach((e) => {
const isRelation = e.base_type === BASE_TYPE_RELATION;
if (isRelation) {
elementsToDeps.push({ internal_id: e.fromId, entity_type: e.fromType });
elementsToDeps.push({ internal_id: e.toId, entity_type: e.toType });
targetsToResolved.push(...[e.fromId, e.toId]);
}
});
const depsPromise = loadElementMetaDependencies(context, user, elementsToDeps, opts);
if (targetsToResolved.length > 0) {
const args = { toMap: true, connectionFormat: false };
// Load with System user, access rights will be dynamically change after
fromAndToPromise = elFindByIds(context, SYSTEM_USER, targetsToResolved, args);
}
const [fromAndToMap, depsElementsMap] = await Promise.all([fromAndToPromise, depsPromise]);
const loadedElements = [];
let startProcessingTime = new Date().getTime();
for (let i = 0; i < elements.length; i += 1) {
const element = elements[i];
const isRelation = element.base_type === BASE_TYPE_RELATION;
if (isRelation) {
const rawFrom = fromAndToMap[element.fromId];
const rawTo = fromAndToMap[element.toId];
const deps = depsElementsMap.get(element.id);
// Check relations consistency
if (isEmptyField(rawFrom) || isEmptyField(rawTo)) {
const validFrom = isEmptyField(rawFrom) ? 'invalid' : 'valid';
const validTo = isEmptyField(rawTo) ? 'invalid' : 'valid';
const detail = `From ${element.fromId} is ${validFrom}, To ${element.toId} is ${validTo}`;
logApp.warn('Auto delete of invalid relation', { id: element.id, detail });
// Auto deletion of the invalid relation
await elDeleteElements(context, SYSTEM_USER, [element]);
} else {
const from = R.mergeRight(element, { ...rawFrom, ...depsElementsMap.get(element.fromId) });
const to = R.mergeRight(element, { ...rawTo, ...depsElementsMap.get(element.toId) });
// Check relations marking access.
const canAccessFrom = await isUserCanAccessStoreElement(context, user, from);
const canAccessTo = await isUserCanAccessStoreElement(context, user, to);
if (canAccessFrom && canAccessTo) {
loadedElements.push(R.mergeRight(element, { from, to, ...deps }));
}
}
} else {
const deps = depsElementsMap.get(element.id);
loadedElements.push(R.mergeRight(element, { ...deps }));
}
// Prevent event loop locking more than MAX_EVENT_LOOP_PROCESSING_TIME
if (new Date().getTime() - startProcessingTime > MAX_EVENT_LOOP_PROCESSING_TIME) {
startProcessingTime = new Date().getTime();
await new Promise((resolve) => {
setImmediate(resolve);
});
}
}
return loadedElements;
};
const loadByIdsWithDependencies = async (context, user, ids, opts = {}) => {
const elements = await elFindByIds(context, user, ids, { ...opts, withoutRels: true, connectionFormat: false });
if (elements.length > 0) {
return loadElementsWithDependencies(context, user, elements, opts);
}
return [];
};
const loadByFiltersWithDependencies = async (context, user, types, args = {}) => {
const { indices = READ_DATA_INDICES } = args;
const paginateArgs = buildEntityFilters(types, args);
const elements = await elList(context, user, indices, { ...paginateArgs, withoutRels: true, connectionFormat: false });
if (elements.length > 0) {
return loadElementsWithDependencies(context, user, elements, { ...args, onlyMarking: false, withoutRels: true });
}
return [];
};
// Get element with every elements connected element -> rel -> to
export const storeLoadByIdsWithRefs = async (context, user, ids, opts = {}) => {
// When loading with explicit references, data must be loaded without internal rels
// As rels are here for search and sort there is some data that conflict after references explication resolutions
return loadByIdsWithDependencies(context, user, ids, { ...opts, onlyMarking: false, withoutRels: true });
};
export const storeLoadByIdWithRefs = async (context, user, id, opts = {}) => {
const elements = await storeLoadByIdsWithRefs(context, user, [id], opts);
return elements.length > 0 ? R.head(elements) : null;
};
export const stixLoadById = async (context, user, id, opts = {}) => {
const instance = await storeLoadByIdWithRefs(context, user, id, opts);
return instance ? convertStoreToStix(instance) : undefined;
};
export const stixLoadByIds = async (context, user, ids, opts = {}) => {
const elements = await storeLoadByIdsWithRefs(context, user, ids, opts);
// As stix load by ids doesn't respect the ordering we need to remap the result
const loadedInstancesMap = new Map(elements.map((i) => ({ instance: i, ids: extractIdsFromStoreObject(i) }))
.flat().map((o) => o.ids.map((id) => [id, o.instance])).flat());
return ids.map((id) => loadedInstancesMap.get(id)).filter((i) => isNotEmptyField(i)).map((e) => convertStoreToStix(e));
};
export const stixLoadByIdStringify = async (context, user, id) => {
const data = await stixLoadById(context, user, id);
return data ? JSON.stringify(data) : '';
};
export const stixLoadByFilters = async (context, user, types, args) => {
const elements = await loadByFiltersWithDependencies(context, user, types, args);
return elements ? elements.map((element) => convertStoreToStix(element)) : [];
};
// endregion
// region Graphics
const convertAggregateDistributions = async (context, user, limit, orderingFunction, distribution) => {
const data = R.take(limit, R.sortWith([orderingFunction(R.prop('value'))])(distribution));
const resolveLabels = await elFindByIds(context, user, data.map((d) => d.label), { toMap: true });
return data // Depending of user access, info can be empty, must be filtered
.filter((n) => isNotEmptyField(resolveLabels[n.label.toLowerCase()]))
.map((n) => R.assoc('entity', resolveLabels[n.label.toLowerCase()], n));
};
export const timeSeriesHistory = async (context, user, types, args) => {
const { startDate, endDate, interval } = args;
const histogramData = await elHistogramCount(context, user, READ_INDEX_HISTORY, args);
return fillTimeSeries(startDate, endDate, interval, histogramData);
};
export const timeSeriesEntities = async (context, user, types, args) => {
const timeSeriesArgs = buildEntityFilters(types, args);
const histogramData = await elHistogramCount(context, user, args.onlyInferred ? READ_DATA_INDICES_INFERRED : READ_DATA_INDICES, timeSeriesArgs);
const { startDate, endDate, interval } = args;
return fillTimeSeries(startDate, endDate, interval, histogramData);
};
export const timeSeriesRelations = async (context, user, args) => {
const { startDate, endDate, relationship_type: relationshipTypes, interval } = args;
const types = relationshipTypes || ['stix-core-relationship', 'object', 'stix-sighting-relationship'];
const timeSeriesArgs = buildEntityFilters(types, args);
const histogramData = await elHistogramCount(context, user, args.onlyInferred ? INDEX_INFERRED_RELATIONSHIPS : READ_RELATIONSHIPS_INDICES, timeSeriesArgs);
return fillTimeSeries(startDate, endDate, interval, histogramData);
};
export const distributionHistory = async (context, user, types, args) => {
const { limit = 10, order = 'desc', field } = args;
if (field.includes('.') && (!field.endsWith('internal_id') && !field.includes('context_data'))) {
throw FunctionalError('Distribution entities does not support relation aggregation field');
}
let finalField = field;
if (field.includes('.' && !field.includes('context_data'))) {
finalField = REL_INDEX_PREFIX + field;
}
if (field === 'name') {
finalField = 'internal_id';
}
const distributionData = await elAggregationCount(context, user, READ_INDEX_HISTORY, {
...args,
field: finalField,
});
// Take a maximum amount of distribution depending on the ordering.
const orderingFunction = order === 'asc' ? R.ascend : R.descend;
if (field.includes(ID_INTERNAL) || field === 'creator_id' || field === 'user_id' || field === 'group_ids' || field === 'organization_ids' || field.includes('.id') || field.includes('_id')) {
return convertAggregateDistributions(context, user, limit, orderingFunction, distributionData);
}
if (field === 'name' || field === 'context_data.id') {
let result = [];
await convertAggregateDistributions(context, user, limit, orderingFunction, distributionData)
.then((hits) => {
result = hits.map((hit) => ({
label: hit.entity.name ?? extractEntityRepresentativeName(hit.entity),
value: hit.value,
entity: hit.entity,
}));
});
return result;
}
return R.take(limit, R.sortWith([orderingFunction(R.prop('value'))])(distributionData));
};
export const distributionEntities = async (context, user, types, args) => {
const distributionArgs = buildEntityFilters(types, args);
const { limit = 10, order = 'desc', field } = args;
if (field.includes('.') && !field.endsWith('internal_id')) {
throw FunctionalError('Distribution entities does not support relation aggregation field');
}
let finalField = field;
if (field.includes('.')) {
finalField = REL_INDEX_PREFIX + field;
}
if (field === 'name') {
finalField = 'internal_id';
}
const distributionData = await elAggregationCount(context, user, args.onlyInferred ? READ_DATA_INDICES_INFERRED : READ_DATA_INDICES, {
...distributionArgs,
field: finalField
});
// Take a maximum amount of distribution depending on the ordering.
const orderingFunction = order === 'asc' ? R.ascend : R.descend;
if (field.includes(ID_INTERNAL) || field === 'creator_id' || field === 'x_opencti_workflow_id') {
return convertAggregateDistributions(context, user, limit, orderingFunction, distributionData);
}
if (field === 'name') {
let result = [];
await convertAggregateDistributions(context, user, limit, orderingFunction, distributionData)
.then((hits) => {
result = hits.map((hit) => ({
label: hit.entity.name ?? extractEntityRepresentativeName(hit.entity),
value: hit.value,
entity: hit.entity,
}));
});
return result;
}
return R.take(limit, R.sortWith([orderingFunction(R.prop('value'))])(distributionData)); // label not good
};
export const distributionRelations = async (context, user, args) => {
const { field } = args; // Mandatory fields
const { limit = 50, order } = args;
const { relationship_type: relationshipTypes, dateAttribute = 'created_at' } = args;
const types = relationshipTypes || [ABSTRACT_BASIC_RELATIONSHIP];
const distributionDateAttribute = dateAttribute || 'created_at';
let finalField = field;
if (field.includes('.')) {
finalField = REL_INDEX_PREFIX + field;
}
// Using elastic can only be done if the distribution is a count on types
const opts = { ...args, dateAttribute: distributionDateAttribute, field: finalField };
const distributionArgs = buildAggregationRelationFilter(types, opts);
const distributionData = await elAggregationRelationsCount(context, user, args.onlyInferred ? READ_INDEX_INFERRED_RELATIONSHIPS : READ_RELATIONSHIPS_INDICES, distributionArgs);
// Take a maximum amount of distribution depending on the ordering.
const orderingFunction = order === 'asc' ? R.ascend : R.descend;
if (field.includes(ID_INTERNAL) || field === 'creator_id' || field === 'x_opencti_workflow_id') {
return convertAggregateDistributions(context, user, limit, orderingFunction, distributionData);
}
return R.take(limit, R.sortWith([orderingFunction(R.prop('value'))])(distributionData));
};
// endregion
// region mutation common
const depsKeys = (type) => ([
...depsKeysRegister.get(),
...[
// Relationship
{ src: 'fromId', dst: 'from' },
{ src: 'toId', dst: 'to' },
// Other meta refs
...schemaRelationsRefDefinition.getInputNames(type).map((e) => ({ src: e })),
],
]);
const idNormalizeDataEntity = (nameOrId, data) => (isAnId(nameOrId) ? nameOrId : generateAliasesId([nameOrId], data).at(0));
const idLabel = (label) => {
return isAnId(label) ? label : generateStandardId(ENTITY_TYPE_LABEL, { value: normalizeName(label) });
};
const inputResolveRefs = async (context, user, input, type, entitySetting) => {
const inputResolveRefsFn = async () => {
const fetchingIds = [];
const expectedIds = [];
const cleanedInput = { _index: inferIndexFromConceptType(type), ...input };
let embeddedFromResolution;
let forceAliases = false;
const dependencyKeys = depsKeys(type);
for (let index = 0; index < dependencyKeys.length; index += 1) {
const { src, dst, types } = dependencyKeys[index];
const depTypes = types ?? [];
const destKey = dst || src;
const id = input[src];
const isValidType = depTypes.length > 0 ? depTypes.includes(type) : true;
if (isValidType && !R.isNil(id) && !R.isEmpty(id)) {
const isListing = Array.isArray(id);
const hasOpenVocab = isEntityFieldAnOpenVocabulary(destKey, type);
// Handle specific case of object label that can be directly the value instead of the key.
if (src === INPUT_LABELS) {
const elements = R.uniq(id.map((label) => idLabel(label)))
.map((lid) => ({ id: lid, destKey, multiple: true }));
fetchingIds.push(...elements);
expectedIds.push(...elements.map((e) => e.id));
} else if (hasOpenVocab) {
const ids = isListing ? id : [id];
const category = getVocabularyCategoryForField(destKey, type);
const elements = ids.map((i) => idNormalizeDataEntity(i, { category, entity_type: ENTITY_TYPE_VOCABULARY }))
.map((lid) => ({ id: lid, destKey, multiple: isListing }));
fetchingIds.push(...elements);
forceAliases = true;
} else if (isListing) {
const elements = R.uniq(id).map((i) => ({ id: i, destKey, multiple: true }));
fetchingIds.push(...elements);
expectedIds.push(...elements.map((e) => e.id));
} else { // Single
if (dst === 'from' && isStixRefRelationship(type)) {
// If resolution is due to embedded ref, the from must be fully resolved
// This will be used to generated a correct stream message
embeddedFromResolution = id;
} else {
fetchingIds.push({ id, destKey, multiple: false });
}
if (!expectedIds.includes(id)) {
expectedIds.push(id);
}
}
cleanedInput[src] = null;
}
}
// TODO Improve type restriction from targeted ref inferred types
// This information must be added in the model
const findOpts = { forceAliases, indices: READ_DATA_INDICES };
const simpleResolutionsPromise = internalFindByIds(context, user, fetchingIds.map((i) => i.id), findOpts);
let embeddedFromPromise = Promise.resolve();
if (embeddedFromResolution) {
fetchingIds.push({ id: embeddedFromResolution, destKey: 'from', multiple: false });
embeddedFromPromise = storeLoadByIdWithRefs(context, user, embeddedFromResolution);
}
const [resolvedElements, embeddedFrom] = await Promise.all([simpleResolutionsPromise, embeddedFromPromise]);
if (embeddedFrom) {
resolvedElements.push(embeddedFrom);
}
const resolvedElementWithConfGroup = resolvedElements.map((d) => {
const resolvedIds = getInstanceIds(d);
const matchingConfigs = R.filter((a) => resolvedIds.includes(a.id), fetchingIds);
return matchingConfigs.map((c) => ({ ...d, i_group: c }));
});
const allResolvedElements = R.flatten(resolvedElementWithConfGroup);
const uniqElement = (a, b) => a.internal_id === b.internal_id && a.i_group.destKey === b.i_group.destKey;
const filteredElements = R.uniqWith(uniqElement, allResolvedElements);
const groupByTypeElements = R.groupBy((e) => e.i_group.destKey, filteredElements);
const resolved = Object.entries(groupByTypeElements).map(([k, val]) => {
const isMultiple = R.head(val).i_group.multiple;
if (val.length === 1) {
return { [k]: isMultiple ? val : R.head(val) };
}
if (!isMultiple) {
throw UnsupportedError('Input resolve refs expect single value', { key: k, values: val });
}
return { [k]: val };
});
const resolvedIds = R.flatten(
R.map((r) => {
const [, val] = R.head(Object.entries(r));
if (isNotEmptyField(val)) {
const values = Array.isArray(val) ? val : [val];
return R.map((v) => getInstanceIds(v), values);
}
return [];
}, resolved)
);
const unresolvedIds = R.filter((n) => !R.includes(n, resolvedIds), expectedIds);
// In case of missing from / to, fail directly
const expectedUnresolvedIds = unresolvedIds.filter((u) => u === input.fromId || u === input.toId);
if (expectedUnresolvedIds.length > 0) {
throw MissingReferenceError({ input, unresolvedIds: expectedUnresolvedIds });
}
// In case of missing reference NOT from or to, we reject twice before accepting
// TODO this retry must be removed in favor of reworking the workers synchronization
const retryNumber = user.origin?.call_retry_number;
const optionalRefsUnresolvedIds = unresolvedIds.filter((u) => u !== input.fromId || u !== input.toId);
const attributesConfiguration = getAttributesConfiguration(entitySetting);
const defaultValues = attributesConfiguration?.map((attr) => attr.default_values).flat() ?? [];
const expectedUnresolvedIdsNotDefault = optionalRefsUnresolvedIds.filter((id) => !defaultValues.includes(id));
if (isNotEmptyField(retryNumber) && expectedUnresolvedIdsNotDefault.length > 0 && retryNumber <= 2) {
throw MissingReferenceError({ input, unresolvedIds: expectedUnresolvedIdsNotDefault });
}
const complete = { ...cleanedInput, entity_type: type };
const inputResolved = R.mergeRight(complete, R.mergeAll(resolved));
// Check Open vocab in resolved to convert them back to the raw value
const entityVocabs = Object.values(vocabularyDefinitions).filter(({ entity_types }) => entity_types.includes(type));
entityVocabs.forEach(({ fields }) => {
const existingFields = fields.filter(({ key }) => Boolean(input[key]));
existingFields.forEach(({ key, required, multiple }) => {
const resolvedData = inputResolved[key];
if (isEmptyField(resolvedData) && required) {
throw FunctionalError('Missing mandatory attribute for vocabulary', { key });
}
if (isNotEmptyField(resolvedData)) {
const isArrayValues = Array.isArray(resolvedData);
if (isArrayValues && !multiple) {
throw FunctionalError('Find multiple vocabularies for single one', { key, data: resolvedData });
}
inputResolved[key] = isArrayValues ? resolvedData.map(({ name }) => name) : resolvedData.name;
}
});
});
// Check the marking allow for the user and asked inside the input
if (!isBypassUser(user) && inputResolved[INPUT_MARKINGS]) {
const inputMarkingIds = inputResolved[INPUT_MARKINGS].map((marking) => marking.internal_id);
const userMarkingIds = user.allowed_marking.map((marking) => marking.internal_id);
if (!inputMarkingIds.every((v) => userMarkingIds.includes(v))) {
throw MissingReferenceError({ context: 'Missing markings', input });
}
}
return inputResolved;
};
return telemetry(context, user, `INPUTS RESOLVE ${type}`, {
[SemanticAttributes.DB_NAME]: 'middleware',
[SemanticAttributes.DB_OPERATION]: 'resolver',
}, inputResolveRefsFn);
};
const isRelationTargetGrants = (elementGrants, relation, type) => {
const isTargetType = relation.base_type === BASE_TYPE_RELATION && relation.entity_type === RELATION_OBJECT;
if (!isTargetType) return false;
const isUnrestricted = [relation.to.entity_type, ...relation.to.parent_types]
.some((r) => STIX_ORGANIZATIONS_UNRESTRICTED.includes(r));
if (isUnrestricted) return false;
return type === ACTION_TYPE_UNSHARE || !elementGrants.every((v) => (relation.to[RELATION_GRANTED_TO] ?? []).includes(v));
};
const createContainerSharingTask = (context, type, element, relations = []) => {
// If object_refs relations are newly created
// One side is a container, the other side must inherit from the granted_refs
const targetGrantIds = [];
let taskPromise = Promise.resolve();
const elementGrants = (relations ?? []).filter((e) => e.entity_type === RELATION_GRANTED_TO).map((r) => r.to.internal_id);
// If container is granted, we need to grant every new children.
if (element.base_type === BASE_TYPE_ENTITY && isStixDomainObjectShareableContainer(element.entity_type)) {
elementGrants.push(...(element[RELATION_GRANTED_TO] ?? []));
if (elementGrants.length > 0) {
// A container has created or modified (addition of some object_refs)
// We need to compute the granted_refs on the container and apply it on new child
// Apply will be done on a background task to not slow the main ingestion process.
const newChildrenIds = (relations ?? [])
.filter((e) => isRelationTargetGrants(elementGrants, e, type))
.map((r) => r.to.internal_id);
targetGrantIds.push(...newChildrenIds);
}
}
if (element.base_type === BASE_TYPE_RELATION && isStixDomainObjectShareableContainer(element.from.entity_type)) {
elementGrants.push(...(element.from[RELATION_GRANTED_TO] ?? []));
// A new object_ref relation was created between a shareable container and an element
// If this element is compatible we need to apply the granted_refs of the container on this new element
if (elementGrants.length > 0 && isRelationTargetGrants(elementGrants, element, type)) {
targetGrantIds.push(element.to.internal_id);
}
}
// If element needs to be updated, start a SHARE background task
if (targetGrantIds.length > 0) {
const input = { ids: targetGrantIds, scope: 'SETTINGS', actions: [{ type, context: { values: elementGrants } }] };
taskPromise = createListTask(context, context.user, input);
}
return taskPromise;
};
const indexCreatedElement = async (context, user, { element, relations }) => {
// Continue the creation of the element and the connected relations
const indexPromise = elIndexElements(context, user, element.entity_type, [element, ...(relations ?? [])]);
const taskPromise = createContainerSharingTask(context, ACTION_TYPE_SHARE, element, relations);
await Promise.all([taskPromise, indexPromise]);
};
export const updatedInputsToData = (instance, inputs) => {
const inputPairs = R.map((input) => {
const { key, value } = input;
let val = value;
if (!isMultipleAttribute(instance.entity_type, key) && val) {
val = R.head(value);
}
return { [key]: val };
}, inputs);
return mergeDeepRightAll(...inputPairs);
};
export const mergeInstanceWithInputs = (instance, inputs) => {
// standard_id must be maintained
// const inputsWithoutId = inputs.filter((i) => i.key !== ID_STANDARD);
const data = updatedInputsToData(instance, inputs);
const updatedInstance = R.mergeRight(instance, data);
return R.reject(R.equals(null))(updatedInstance);
};
const partialInstanceWithInputs = (instance, inputs) => {
const inputData = updatedInputsToData(instance, inputs);
return {
_index: instance._index,
internal_id: instance.internal_id,
entity_type: instance.entity_type,
representative: extractRepresentative(instance),
...inputData,
};
};
const rebuildAndMergeInputFromExistingData = (rawInput, instance) => {
const { key, value, object_path, operation = UPDATE_OPERATION_REPLACE } = rawInput; // value can be multi valued
const isMultiple = isMultipleAttribute(instance.entity_type, key);
let finalVal;
if (isMultiple) {
const currentValues = (Array.isArray(instance[key]) ? instance[key] : [instance[key]]) ?? [];
if (operation === UPDATE_OPERATION_ADD) {
if (isObjectAttribute(key)) {
const path = object_path ?? key;
const preparedPath = path.startsWith('/') ? path : `/${path}`;
const instanceKeyValues = jsonpatch.getValueByPointer(instance, preparedPath);
let patch;
if (instanceKeyValues === undefined) {
// if the instance has not yet this key, we need to add the full key as a new array
patch = [{ op: operation, path: `${preparedPath}`, value }];
} else {
// otherwise we need to add the values to the existing array, using jsonpatch indexed path
patch = value.map((v, index) => {
const afterIndex = index + instanceKeyValues.length;
return { op: operation, path: `${preparedPath}/${afterIndex}`, value: v };
});
}
const patchedInstance = jsonpatch.applyPatch(structuredClone(instance), patch).newDocument;
finalVal = patchedInstance[key];
} else {
finalVal = R.uniq([...currentValues, value].flat().filter((v) => isNotEmptyField(v)));
}
}
if (operation === UPDATE_OPERATION_REMOVE) {
if (isObjectAttribute(key)) {
const path = object_path ?? key;
const preparedPath = path.startsWith('/') ? path : `/${path}`;
const patch = [{ op: operation, path: preparedPath }];
const patchedInstance = jsonpatch.applyPatch(structuredClone(instance), patch).newDocument;
finalVal = patchedInstance[key];
} else {
finalVal = R.filter((n) => !R.includes(n, value), currentValues);
}
}
if (operation === UPDATE_OPERATION_REPLACE) {
if (isObjectAttribute(key)) {
const path = object_path ?? key;
const preparedPath = path.startsWith('/') ? path : `/${path}`;
const targetIsMultiple = isObjectPathTargetMultipleAttribute(instance, preparedPath);
const patch = [{ op: operation, path: preparedPath, value: targetIsMultiple ? value : R.head(value) }];
const patchedInstance = jsonpatch.applyPatch(structuredClone(instance), patch).newDocument;
finalVal = patchedInstance[key];
} else { // Replace general
finalVal = value;
}
}
if (compareUnsorted(finalVal ?? [], currentValues)) {
return {}; // No need to update the attribute
}
} else if (isObjectAttribute(key) && object_path) {
const preparedPath = object_path.startsWith('/') ? object_path : `/${object_path}`;
const targetIsMultiple = isObjectPathTargetMultipleAttribute(instance, preparedPath);
const patch = [{ op: operation, path: preparedPath, value: targetIsMultiple ? value : R.head(value) }];
const clonedInstance = structuredClone(instance);
clonedInstance[key] = clonedInstance[key] ?? {}; // Patch on complete empty value is not supported by jsonpatch
const patchedInstance = jsonpatch.applyPatch(clonedInstance, patch).newDocument;
if (compareUnsorted(patchedInstance[key], instance[key])) {
return {}; // No need to update the attribute
}
finalVal = [patchedInstance[key]];
} else {
const evaluateValue = value ? R.head(value) : null;
if (isDateAttribute(key)) {
if (isEmptyField(evaluateValue)) {
if (instance[key] === FROM_START_STR || instance[key] === UNTIL_END_STR) {
return {};
}
}
if (utcDate(instance[key]).isSame(utcDate(evaluateValue))) {
return {};
}
}
if (R.equals(instance[key], evaluateValue) || (isEmptyField(instance[key]) && isEmptyField(evaluateValue))) {
return {}; // No need to update the attribute
}
finalVal = value;
}
// endregion
// region cleanup cases
if (key === IDS_STIX) {
// Special stixIds uuid v1 cleanup.
finalVal = cleanStixIds(finalVal);
}
// endregion
if (isDateAttribute(key)) {
const finalValElement = R.head(finalVal);
if (isEmptyField(finalValElement)) {
finalVal = [null];
}
}
if (dateForLimitsAttributes.includes(key)) {
const finalValElement = R.head(finalVal);
if (dateForStartAttributes.includes(key) && isEmptyField(finalValElement)) {
finalVal = [FROM_START_STR];
}
if (dateForEndAttributes.includes(key) && isEmptyField(finalValElement)) {
finalVal = [UNTIL_END_STR];
}
}
return { key, value: finalVal, operation };
};
const mergeInstanceWithUpdateInputs = (instance, inputs) => {
const updates = Array.isArray(inputs) ? inputs : [inputs];
const metaKeys = [...schemaRelationsRefDefinition.getStixNames(instance.entity_type), ...schemaRelationsRefDefinition.getInputNames(instance.entity_type)];
const attributes = updates.filter((e) => !metaKeys.includes(e.key));
const mergeInput = (input) => rebuildAndMergeInputFromExistingData(input, instance);
const remappedInputs = R.map((i) => mergeInput(i), attributes);
const resolvedInputs = R.filter((f) => !R.isEmpty(f), remappedInputs);
return mergeInstanceWithInputs(instance, resolvedInputs);
};
const listEntitiesByHashes = async (context, user, type, hashes) => {
if (isEmptyField(hashes)) {
return [];
}
const searchHashes = extractNotFuzzyHashValues(hashes); // Search hashes must filter the fuzzy hashes
if (searchHashes.length === 0) {
return [];
}
return listEntities(context, user, [type], {
filters: {
mode: 'and',
filters: [{ key: 'hashes.*', values: searchHashes, operator: 'wildcard' }],
filterGroups: [],
},
noFiltersChecking: true,
connectionFormat: false,
});
};
export const hashMergeValidation = (instances) => {
// region Specific check for observables with hashes
// If multiple results start by checking the possible merge validity
const allHashes = instances.map((h) => h.hashes).filter((e) => isNotEmptyField(e));
if (allHashes.length > 0) {
const elements = allHashes.map((e) => Object.entries(e)).flat();
const groupElements = R.groupBy(([key]) => key, elements);
Object.entries(groupElements).forEach(([algo, values]) => {
const hashes = R.uniq(values.map(([, data]) => data));
if (hashes.length > 1) {
const field = `hashes_${algo.toUpperCase()}`;
const message = { message: `Hashes collision for ${algo} algorithm` };
throw ValidationError(field, message);
}
});
}
};
// endregion
// region mutation update
const ed = (date) => isEmptyField(date) || date === FROM_START_STR || date === UNTIL_END_STR;
const noDate = (e) => ed(e.first_seen) && ed(e.last_seen) && ed(e.start_time) && ed(e.stop_time);
const filterTargetByExisting = async (context, targetEntity, redirectSide, sourcesDependencies, targetDependencies) => {
const cache = [];
const filtered = [];
const sources = sourcesDependencies[`i_relations_${redirectSide}`];
const targets = targetDependencies[`i_relations_${redirectSide}`];
const markingSources = sources.filter((r) => r.i_relation.entity_type === RELATION_OBJECT_MARKING);
const markingTargets = targets.filter((r) => r.i_relation.entity_type === RELATION_OBJECT_MARKING);
const markings = [...markingSources, ...markingTargets];
const filteredMarkings = await cleanMarkings(context, markings.map((m) => m.internal_id));
const filteredMarkingIds = filteredMarkings.map((m) => m.internal_id);
const markingTargetDeletions = markingTargets.filter((m) => !filteredMarkingIds.includes(m.internal_id)).map((m) => m.i_relation);
for (let index = 0; index < sources.length; index += 1) {
const source = sources[index];
// If the relation source is already in target = filtered
const finder = (t) => {
const sameTarget = t.internal_id === source.internal_id;
const sameRelationType = t.i_relation.entity_type === source.i_relation.entity_type;
return sameRelationType && sameTarget && noDate(t.i_relation);
};
// In case of single meta to move, check if the target have not already this relation.
// If yes, we keep it, if not we rewrite it
const isSingleMeta = isSingleRelationsRef(source.i_relation.fromType, source.i_relation.entity_type);
const relationInputName = schemaRelationsRefDefinition.convertDatabaseNameToInputName(targetEntity.entity_type, source.i_relation.entity_type);
const existingSingleMeta = isSingleMeta && isNotEmptyField(targetEntity[relationInputName]);
// For single meta only rely on entity type to prevent relation duplications
const id = isSingleMeta ? source.i_relation.entity_type : `${source.i_relation.entity_type}-${source.internal_id}`;
// Self ref relationships is not allowed, need to compare the side that will be kept with the target
const relationSideToKeep = redirectSide === 'from' ? 'toId' : 'fromId';
const isSelfMeta = isStixRefRelationship(source.i_relation.entity_type) && (targetEntity.internal_id === source.i_relation[relationSideToKeep]);
// Markings duplication definition group
const isMarkingToKeep = source.i_relation.entity_type === RELATION_OBJECT_MARKING ? filteredMarkingIds.includes(source.internal_id) : true;
// Check and add the relation in the processing list if needed
if (!existingSingleMeta && !isSelfMeta && isMarkingToKeep && !R.find(finder, targets) && !cache.includes(id)) {
filtered.push(source);
cache.push(id);
}
}
return { deletions: markingTargetDeletions, redirects: filtered };
};
const mergeEntitiesRaw = async (context, user, targetEntity, sourceEntities, targetDependencies, sourcesDependencies, opts = {}) => {
const { chosenFields = {} } = opts;
// 01 Check if everything is fully resolved.
const elements = [targetEntity, ...sourceEntities];
logApp.info(`[OPENCTI] Merging ${sourceEntities.map((i) => i.internal_id).join(',')} in ${targetEntity.internal_id}`);
// Pre-checks
// - No self merge
const sourceIds = R.map((e) => e.internal_id, sourceEntities);
if (R.includes(targetEntity.internal_id, sourceIds)) {
throw FunctionalError('Cannot merge an entity on itself', {
dest: targetEntity.internal_id,
source: sourceIds,
});
}
// - No inferences
const elementsInferences = elements.filter((s) => isInferredIndex(s._index));
if (elementsInferences.length > 0) {
throw FunctionalError('Cannot merge inferred entities', {
inferences: elementsInferences.map((e) => e.internal_id)
});