Projects STRLCPY opencti Commits 7ebe03c9
🤬
  • ■ ■ ■ ■
    opencti-platform/opencti-graphql/script/script-clean-relations.js
    skipped 1 lines
    2 2  import { logApp } from '../src/config/conf';
    3 3  import { executionContext } from '../src/utils/access';
    4 4   
    5  -const context = executionContext();
     5 +const context = executionContext('script');
    6 6  cleanInconsistentRelations(context)
    7 7   .then(() => logApp.info('[SCRIPT] Clean relations done'));
    8 8   
  • ■ ■ ■ ■ ■
    opencti-platform/opencti-graphql/src/database/middleware.js
    skipped 14 lines
    15 15  import {
    16 16   buildPagination,
    17 17   computeAverage,
     18 + EVENT_TYPE_DELETE_DEPENDENCIES,
    18 19   fillTimeSeries,
    19 20   generateCreateMessage,
    20 21   generateUpdateMessage,
    skipped 103 lines
    124 125  } from '../schema/stixCyberObservableRelationship';
    125 126  import {
    126 127   FIELD_TO_META_RELATION,
     128 + isStixMetaRelationship,
    127 129   RELATION_CREATED_BY,
    128 130   RELATION_EXTERNAL_REFERENCE,
    129 131   RELATION_GRANTED_TO,
    skipped 67 lines
    197 199   isBypassUser,
    198 200   isUserCanAccessStoreElement,
    199 201   KNOWLEDGE_ORGANIZATION_RESTRICT,
     202 + RULE_MANAGER_USER,
    200 203   SYSTEM_USER
    201 204  } from '../utils/access';
    202  -import { isRuleUser, RULE_MANAGER_USER, RULES_ATTRIBUTES_BEHAVIOR } from '../rules/rules';
     205 +import { isRuleUser, RULES_ATTRIBUTES_BEHAVIOR } from '../rules/rules';
    203 206  import {
    204 207   FIELD_ATTRIBUTE_TO_EMBEDDED_RELATION,
    205 208   instanceMetaRefsExtractor,
    skipped 2231 lines
    2437 2440   data.internal_id = internalId;
    2438 2441   data.standard_id = standardId;
    2439 2442   data.entity_type = relationshipType;
     2443 + data.relationship_type = relationshipType;
    2440 2444   data.creator_id = user.internal_id;
    2441 2445   data.created_at = today;
    2442 2446   data.updated_at = today;
    skipped 29 lines
    2472 2476   }
    2473 2477   // stix-core-relationship
    2474 2478   if (isStixCoreRelationship(relationshipType)) {
    2475  - data.relationship_type = relationshipType;
    2476 2479   data.description = input.description ? input.description : '';
    2477 2480   data.start_time = isEmptyField(input.start_time) ? new Date(FROM_START) : input.start_time;
    2478 2481   data.stop_time = isEmptyField(input.stop_time) ? new Date(UNTIL_END) : input.stop_time;
    skipped 9 lines
    2488 2491   if (isStixCyberObservableRelationship(relationshipType)) {
    2489 2492   // because spec is only put in all stix except meta, and stix cyber observable is a meta but requires this
    2490 2493   data.spec_version = STIX_SPEC_VERSION;
    2491  - data.relationship_type = relationshipType;
    2492 2494   data.start_time = R.isNil(input.start_time) ? new Date(FROM_START) : input.start_time;
    2493 2495   data.stop_time = R.isNil(input.stop_time) ? new Date(UNTIL_END) : input.stop_time;
    2494 2496   /* istanbul ignore if */
    skipped 659 lines
    3154 3156   const { element: deleted } = await internalDeleteElementById(context, user, elementId, opts);
    3155 3157   return deleted.internal_id;
    3156 3158  };
    3157  -export const deleteInferredRuleElement = async (rule, instance, deletedDependencies) => {
    3158  - const context = executionContext(rule.name);
     3159 +export const deleteInferredRuleElement = async (rule, instance, deletedDependencies, opts = {}) => {
     3160 + const context = executionContext(rule.name, RULE_MANAGER_USER);
    3159 3161   // Check if deletion is really targeting an inference
    3160 3162   const isInferred = isInferredIndex(instance._index);
    3161 3163   if (!isInferred) {
    skipped 25 lines
    3187 3189   // If current inference is only base on one rule, we can safely delete it.
    3188 3190   if (monoRule) {
    3189 3191   logApp.info('Delete inferred element', { rule, id: instance.id });
    3190  - const { event } = await internalDeleteElementById(context, RULE_MANAGER_USER, instance.id);
     3192 + // If inference is a meta relationship just delete and generate an internal event
     3193 + if (isStixMetaRelationship(instance.entity_type)) {
     3194 + // Delete the meta and start an unshare background task if needed
     3195 + const deletionPromise = elDeleteElements(context, RULE_MANAGER_USER, [instance], storeLoadByIdWithRefs);
     3196 + const taskPromise = createContainerSharingTask(context, ACTION_TYPE_UNSHARE, instance);
     3197 + await Promise.all([deletionPromise, taskPromise]);
     3198 + // Deleting meta must be converted to a special dependency deletion
     3199 + // This type of event will be handle by the stream to cleanup inferences.
     3200 + const deleteEvent = { type: EVENT_TYPE_DELETE_DEPENDENCIES, data: { ids: [`${instance.to.internal_id}_ref`] } };
     3201 + derivedEvents.push(deleteEvent);
     3202 + } else {
     3203 + const deletionData = await internalDeleteElementById(context, RULE_MANAGER_USER, instance.id, opts);
     3204 + derivedEvents.push(deletionData.event);
     3205 + }
    3191 3206   logApp.info('Delete inferred element', { id: instance.id, type: instance.entity_type });
    3192  - derivedEvents.push(event);
    3193 3207   } else {
    3194 3208   // If not we need to clean the rule and keep the element for other rules.
    3195 3209   logApp.info('Cleanup inferred element', { rule, id: instance.id });
    skipped 39 lines
  • ■ ■ ■ ■
    opencti-platform/opencti-graphql/src/database/redis.ts
    skipped 519 lines
    520 520  };
    521 521   
    522 522  // Delete
    523  -const buildDeleteEvent = async (
     523 +export const buildDeleteEvent = async (
    524 524   user: AuthUser,
    525 525   instance: StoreObject,
    526 526   message: string,
    skipped 175 lines
  • ■ ■ ■ ■ ■
    opencti-platform/opencti-graphql/src/database/stix-converter.ts
    skipped 131 lines
    132 132   if (type === ENTITY_HASHED_OBSERVABLE_STIX_FILE) {
    133 133   return 'file';
    134 134   }
    135  - if (isStixCoreRelationship(type)) {
     135 + if (isStixCoreRelationship(type) || isStixMetaRelationship(type)) {
    136 136   return 'relationship';
    137 137   }
    138 138   if (isStixSightingRelationship(type)) {
    skipped 49 lines
    188 188   }
    189 189   return date;
    190 190  };
    191  -const convertObjectReferences = (instance: StoreEntity, inferred: boolean) => {
     191 +const convertObjectReferences = (instance: StoreEntity) => {
    192 192   const objectRefs = instance[INPUT_OBJECTS] ?? [];
    193 193   return objectRefs.filter((r) => {
    194 194   // If related relation not available, it's just a creation, so inferred false
    195  - if (!r.i_relation) return !inferred;
     195 + if (!r.i_relation) return true;
    196 196   // If related relation is available, select accordingly
    197  - return isInferredIndex(r.i_relation._index) === inferred;
     197 + return isInferredIndex(r.i_relation._index) === false;
    198 198   }).map((m) => m.standard_id);
    199 199  };
    200 200   
    skipped 381 lines
    582 582   description: instance.description,
    583 583   report_types: instance.report_types,
    584 584   published: instance.published,
    585  - object_refs: convertObjectReferences(instance, false),
    586  - extensions: {
    587  - [STIX_EXT_OCTI]: cleanObject({
    588  - ...report.extensions[STIX_EXT_OCTI],
    589  - object_refs_inferred: convertObjectReferences(instance, true),
    590  - })
    591  - }
     585 + object_refs: convertObjectReferences(instance),
    592 586   };
    593 587  };
    594 588  const convertNoteToStix = (instance: StoreEntity, type: string): SDO.StixNote => {
    skipped 4 lines
    599 593   abstract: instance.attribute_abstract,
    600 594   content: instance.content,
    601 595   authors: instance.authors,
    602  - object_refs: convertObjectReferences(instance, false),
    603  - extensions: {
    604  - [STIX_EXT_OCTI]: cleanObject({
    605  - ...note.extensions[STIX_EXT_OCTI],
    606  - object_refs_inferred: convertObjectReferences(instance, true),
    607  - })
    608  - }
     596 + object_refs: convertObjectReferences(instance),
    609 597   };
    610 598  };
    611 599  const convertObservedDataToStix = (instance: StoreEntity, type: string): SDO.StixObservedData => {
    skipped 4 lines
    616 604   first_observed: instance.first_observed,
    617 605   last_observed: instance.last_observed,
    618 606   number_observed: instance.number_observed,
    619  - object_refs: convertObjectReferences(instance, false),
    620  - extensions: {
    621  - [STIX_EXT_OCTI]: cleanObject({
    622  - ...observedData.extensions[STIX_EXT_OCTI],
    623  - object_refs_inferred: convertObjectReferences(instance, true),
    624  - })
    625  - }
     607 + object_refs: convertObjectReferences(instance),
    626 608   };
    627 609  };
    628 610  const convertOpinionToStix = (instance: StoreEntity, type: string): SDO.StixOpinion => {
    skipped 4 lines
    633 615   explanation: instance.explanation,
    634 616   authors: instance.authors,
    635 617   opinion: instance.opinion,
    636  - object_refs: convertObjectReferences(instance, false),
    637  - extensions: {
    638  - [STIX_EXT_OCTI]: cleanObject({
    639  - ...opinion.extensions[STIX_EXT_OCTI],
    640  - object_refs_inferred: convertObjectReferences(instance, true),
    641  - })
    642  - }
     618 + object_refs: convertObjectReferences(instance),
    643 619   };
    644 620  };
    645 621   
    skipped 836 lines
  • ■ ■ ■ ■ ■
    opencti-platform/opencti-graphql/src/database/stix.ts
    skipped 126 lines
    127 127  import type { StoreRelation } from '../types/store';
    128 128  import { logApp } from '../config/conf';
    129 129  import {
     130 + isStixMetaRelationship,
    130 131   RELATION_CREATED_BY,
    131 132   RELATION_EXTERNAL_REFERENCE,
    132 133   RELATION_GRANTED_TO,
    skipped 1004 lines
    1137 1138  };
    1138 1139   
    1139 1140  export const isRelationBuiltin = (instance: StoreRelation): boolean => {
    1140  - if (isInternalRelationship(instance.entity_type)) {
     1141 + if (isInternalRelationship(instance.entity_type) || isStixMetaRelationship(instance.entity_type)) {
    1141 1142   return false;
    1142 1143   }
    1143 1144   // Any <-> Any relationship type check
    skipped 78 lines
  • ■ ■ ■ ■ ■ ■
    opencti-platform/opencti-graphql/src/domain/user.js
    skipped 33 lines
    34 34   RELATION_MEMBER_OF,
    35 35   RELATION_PARTICIPATE_TO,
    36 36  } from '../schema/internalRelationship';
    37  -import { ABSTRACT_INTERNAL_RELATIONSHIP, OPENCTI_ADMIN_UUID, OPENCTI_SYSTEM_UUID } from '../schema/general';
     37 +import { ABSTRACT_INTERNAL_RELATIONSHIP, OPENCTI_ADMIN_UUID } from '../schema/general';
    38 38  import { findAll as allMarkings } from './markingDefinition';
    39 39  import { findAll as findGroups } from './group';
    40 40  import { generateStandardId } from '../schema/identifier';
    skipped 10 lines
    51 51   USER_DELETION,
    52 52  } from '../config/audit';
    53 53  import { buildPagination, isEmptyField, isNotEmptyField } from '../database/utils';
    54  -import { BYPASS, executionContext, INTERNAL_USERS, isBypassUser, KNOWLEDGE_ORGANIZATION_RESTRICT, SYSTEM_USER } from '../utils/access';
     54 +import {
     55 + BYPASS,
     56 + executionContext,
     57 + INTERNAL_USERS,
     58 + isBypassUser,
     59 + KNOWLEDGE_ORGANIZATION_RESTRICT,
     60 + SYSTEM_USER
     61 +} from '../utils/access';
    55 62  import { ENTITY_TYPE_MARKING_DEFINITION } from '../schema/stixMetaObject';
    56 63  import { ENTITY_TYPE_IDENTITY_INDIVIDUAL, ENTITY_TYPE_IDENTITY_ORGANIZATION } from '../schema/stixDomainObject';
    57 64  import { getEntityFromCache } from '../database/cache';
    skipped 580 lines
    638 645  };
    639 646   
    640 647  export const resolveUserById = async (context, id) => {
    641  - if (id === OPENCTI_SYSTEM_UUID) {
    642  - return SYSTEM_USER;
    643  - }
     648 + if (INTERNAL_USERS[id]) return INTERNAL_USERS[id];
    644 649   const client = await storeLoadById(context, SYSTEM_USER, id, ENTITY_TYPE_USER);
    645 650   return buildCompleteUser(context, client);
    646 651  };
    skipped 157 lines
  • ■ ■ ■ ■ ■ ■
    opencti-platform/opencti-graphql/src/manager/ruleManager.ts
    skipped 24 lines
    25 25  import { RULE_PREFIX } from '../schema/general';
    26 26  import { ENTITY_TYPE_RULE_MANAGER } from '../schema/internalObject';
    27 27  import { TYPE_LOCK_ERROR } from '../config/errors';
    28  -import { RULE_MANAGER_USER, RULES_ATTRIBUTES_BEHAVIOR } from '../rules/rules';
     28 +import { RULES_ATTRIBUTES_BEHAVIOR } from '../rules/rules';
    29 29  import { getParentTypes } from '../schema/schemaUtils';
    30 30  import { isBasicRelationship } from '../schema/stixRelationship';
    31 31  import { isStixSightingRelationship } from '../schema/stixSightingRelationship';
    skipped 15 lines
    47 47   UpdateEvent
    48 48  } from '../types/event';
    49 49  import { getActivatedRules, RULES_DECLARATION } from '../domain/rules';
    50  -import { executionContext } from '../utils/access';
     50 +import { executionContext, RULE_MANAGER_USER } from '../utils/access';
    51 51   
    52 52  const MIN_LIVE_STREAM_EVENT_VERSION = 4;
    53 53   
    skipped 135 lines
    189 189  };
    190 190   
    191 191  const applyCleanupOnDependencyIds = async (deletionIds: Array<string>) => {
    192  - const context = executionContext('rule_cleaner');
     192 + const context = executionContext('rule_cleaner', RULE_MANAGER_USER);
    193 193   const filters = [{ key: `${RULE_PREFIX}*.dependencies`, values: deletionIds, operator: 'wildcard' }];
    194 194   const callback = (elements: Array<BasicStoreCommon>) => {
    195 195   // eslint-disable-next-line @typescript-eslint/no-use-before-define
    skipped 30 lines
    226 226   // In case of direct dependencies deletion (refs), call clean on every dependencies
    227 227   if (type === EVENT_TYPE_DELETE_DEPENDENCIES) {
    228 228   const deleteEvent = event as DependenciesDeleteEvent;
    229  - await applyCleanupOnDependencyIds(deleteEvent.ids);
     229 + await applyCleanupOnDependencyIds(deleteEvent.data.ids);
    230 230   }
    231 231   // In case of update apply the event on every rules
    232 232   if (type === EVENT_TYPE_UPDATE) {
    skipped 60 lines
    293 293  };
    294 294   
    295 295  const ruleStreamHandler = async (streamEvents: Array<StreamEvent>, lastEventId: string) => {
    296  - const context = executionContext('rule_manager');
     296 + const context = executionContext('rule_manager', RULE_MANAGER_USER);
    297 297   // Create list of events to process
    298 298   // Events must be in a compatible version and not inferences events
    299 299   // Inferences directly handle recursively by the manager
    skipped 16 lines
    316 316  };
    317 317   
    318 318  const getInitRuleManager = async (): Promise<BasicStoreEntity> => {
    319  - const context = executionContext('rule_manager');
     319 + const context = executionContext('rule_manager', RULE_MANAGER_USER);
    320 320   const ruleSettingsInput = { internal_id: RULE_ENGINE_ID, errors: [] };
    321 321   const created = await createEntity(context, RULE_MANAGER_USER, ruleSettingsInput, ENTITY_TYPE_RULE_MANAGER);
    322 322   return created as BasicStoreEntity;
    skipped 66 lines
  • ■ ■ ■ ■ ■ ■
    opencti-platform/opencti-graphql/src/manager/taskManager.js
    skipped 50 lines
    51 51   ENTITY_TYPE_CONTAINER,
    52 52   RULE_PREFIX
    53 53  } from '../schema/general';
    54  -import { executionContext, SYSTEM_USER } from '../utils/access';
     54 +import { executionContext, RULE_MANAGER_USER, SYSTEM_USER } from '../utils/access';
    55 55  import { buildInternalEvent, rulesApplyHandler, rulesCleanHandler } from './ruleManager';
    56  -import { RULE_MANAGER_USER } from '../rules/rules';
    57 56  import { buildFilters } from '../database/repository';
    58 57  import { listAllRelations } from '../database/middleware-loader';
    59 58  import { getActivatedRules, getRule } from '../domain/rules';
    skipped 229 lines
    289 288  };
    290 289  const executeRuleElementRescan = async (context, user, actionContext, element) => {
    291 290   const { rules } = actionContext ?? {};
    292  - const activatedRules = await getActivatedRules(context);
     291 + const activatedRules = await getActivatedRules(context, SYSTEM_USER);
    293 292   // Filter activated rules by context specification
    294 293   const rulesToApply = rules ? activatedRules.filter((r) => rules.includes(r.id)) : activatedRules;
    295 294   if (rulesToApply.length > 0) {
    skipped 6 lines
    302 301   await rulesApplyHandler(context, user, [event]);
    303 302   }
    304 303   } else if (isStixObject(element.entity_type)) {
    305  - const args = { connectionFormat: false, fromId: element.internal_id };
    306  - const relations = await listAllRelations(context, user, ABSTRACT_STIX_RELATIONSHIP, args);
    307  - for (let index = 0; index < relations.length; index += 1) {
    308  - const relation = relations[index];
    309  - const needRescan = ruleRescanTypes.includes(relation.entity_type);
    310  - if (needRescan) {
    311  - const data = await stixLoadById(context, user, relation.internal_id);
    312  - const event = buildInternalEvent(EVENT_TYPE_CREATE, data);
    313  - await rulesApplyHandler(context, user, [event], rulesToApply);
     304 + const listCallback = async (relations) => {
     305 + for (let index = 0; index < relations.length; index += 1) {
     306 + const relation = relations[index];
     307 + const needRescan = ruleRescanTypes.includes(relation.entity_type);
     308 + if (needRescan) {
     309 + const data = await stixLoadById(context, user, relation.internal_id);
     310 + const event = buildInternalEvent(EVENT_TYPE_CREATE, data);
     311 + await rulesApplyHandler(context, user, [event], rulesToApply);
     312 + }
    314 313   }
    315  - }
     314 + };
     315 + const args = { connectionFormat: false, fromId: element.internal_id, callback: listCallback };
     316 + await listAllRelations(context, user, ABSTRACT_STIX_RELATIONSHIP, args);
    316 317   }
    317 318   }
    318 319  };
    skipped 78 lines
    397 398   try {
    398 399   // Lock the manager
    399 400   lock = await lockResource([TASK_MANAGER_KEY]);
    400  - const context = executionContext('task_manager');
     401 + const context = executionContext('task_manager', SYSTEM_USER);
    401 402   const task = await findTaskToExecute(context);
    402 403   // region Task checking
    403 404   if (!task) {
    skipped 72 lines
  • ■ ■ ■ ■ ■
    opencti-platform/opencti-graphql/src/resolvers/log.js
    1 1  import { findAll, logsTimeSeries, logsWorkerConfig } from '../domain/log';
    2 2  import { findById } from '../domain/user';
    3  -import { RETENTION_MANAGER_USER, SYSTEM_USER } from '../utils/access';
     3 +import { RETENTION_MANAGER_USER, RULE_MANAGER_USER, SYSTEM_USER } from '../utils/access';
    4 4  import { storeLoadById } from '../database/middleware';
    5 5  import { ENTITY_TYPE_EXTERNAL_REFERENCE } from '../schema/stixMetaObject';
    6  -import { RULE_MANAGER_USER } from '../rules/rules';
    7 6   
    8 7  const logResolvers = {
    9 8   Query: {
    skipped 27 lines
  • ■ ■ ■ ■ ■ ■
    opencti-platform/opencti-graphql/src/rules/containerWithRefsBuilder.ts
    skipped 5 lines
    6 6   createInferredRelation,
    7 7   deleteInferredRuleElement,
    8 8   internalFindByIds,
    9  - storeLoadByIdWithRefs,
     9 + internalLoadById,
    10 10  } from '../database/middleware';
    11 11   
    12 12  import { RELATION_OBJECT } from '../schema/stixMetaRelationship';
    13  -import { createRuleContent, RULE_MANAGER_USER } from './rules';
    14  -import { INPUT_OBJECTS } from '../schema/general';
    15  -import { generateInternalType } from '../schema/schemaUtils';
    16  -import type { RuleDefinition, RelationTypes, RuleRuntime } from '../types/rules';
     13 +import { createRuleContent } from './rules';
     14 +import { generateInternalType, getParentTypes } from '../schema/schemaUtils';
     15 +import type { RelationTypes, RuleDefinition, RuleRuntime } from '../types/rules';
    17 16  import type { StixId, StixObject } from '../types/stix-common';
    18 17  import type { StixReport } from '../types/stix-sdo';
    19 18  import type { StixRelation } from '../types/stix-sro';
    20  -import type { BasicStoreRelation, StoreEntity, StoreObject } from '../types/store';
     19 +import type { BasicStoreEntity, BasicStoreRelation, StoreObject } from '../types/store';
    21 20  import { STIX_EXT_OCTI } from '../types/stix-extensions';
    22 21  import { listAllRelations } from '../database/middleware-loader';
    23 22  import type { DependenciesDeleteEvent, Event, RelationCreation, RuleEvent, UpdateEvent } from '../types/event';
    24 23  import {
    25  - generateUpdateMessage,
     24 + EVENT_TYPE_DELETE_DEPENDENCIES,
    26 25   UPDATE_OPERATION_ADD,
    27 26   UPDATE_OPERATION_REMOVE,
    28 27   UPDATE_OPERATION_REPLACE
    29 28  } from '../database/utils';
    30  -import { storeUpdateEvent } from '../database/redis';
    31 29  import type { AuthContext } from '../types/user';
    32  -import { executionContext } from '../utils/access';
     30 +import { executionContext, RULE_MANAGER_USER } from '../utils/access';
     31 +import { buildCreateEvent } from '../database/redis';
    33 32   
    34  -const INFERRED_OBJECT_REF_PATH = `/extensions/${STIX_EXT_OCTI}/object_refs_inferred`;
    35 33  const buildContainerRefsRule = (ruleDefinition: RuleDefinition, containerType: string, relationTypes: RelationTypes): RuleRuntime => {
    36 34   const { id } = ruleDefinition;
    37 35   const identityRefFilter = (ref: string) => {
    skipped 10 lines
    48 46   ];
    49 47   };
    50 48   type ArrayRefs = Array<{ partOfFromId: string, partOfId: string, partOfTargetId: string }>;
    51  - const createObjectRefsInferences = async (context: AuthContext, reportId: string, refs: ArrayRefs) => {
    52  - const report = await storeLoadByIdWithRefs(context, RULE_MANAGER_USER, reportId) as StoreEntity;
    53  - const reportObjectRefIds = report[INPUT_OBJECTS].map((r) => r.internal_id);
     49 + const createObjectRefsInferences = async (context: AuthContext, reportId: string, refs: ArrayRefs): Promise<Array<Event>> => {
     50 + const events:Array<Event> = [];
     51 + const report = await internalLoadById(context, RULE_MANAGER_USER, reportId) as unknown as BasicStoreEntity;
     52 + const reportObjectRefIds = report[RELATION_OBJECT] ?? [];
    54 53   const opts = { publishStreamEvent: false };
    55  - const targetIds = refs.map((r) => [r.partOfId, r.partOfTargetId]).flat();
    56  - const targetsMap = await internalFindByIds(context, RULE_MANAGER_USER, targetIds, { toMap: true }) as any;
    57  - const createdTargets: Array<StoreEntity> = [];
    58 54   for (let index = 0; index < refs.length; index += 1) {
    59 55   const { partOfFromId, partOfId, partOfTargetId } = refs[index];
    60 56   // When generating inferences, no need to listen internal generated events
    skipped 4 lines
    65 61   const inputForRelation = { fromId: reportId, toId: partOfId, relationship_type: RELATION_OBJECT };
    66 62   const inferredRelation = await createInferredRelation(context, inputForRelation, ruleRelationContent, opts) as RelationCreation;
    67 63   if (inferredRelation.isCreation) {
    68  - const target = targetsMap[partOfId];
    69  - target.i_relation = inferredRelation.element;
    70  - createdTargets.push(target);
     64 + const event = buildCreateEvent(RULE_MANAGER_USER, inferredRelation.element, '');
     65 + events.push(event);
    71 66   }
    72 67   }
    73 68   // -----------------------------------------------------------------------------------------------------------
    skipped 2 lines
    76 71   const inputForIdentity = { fromId: reportId, toId: partOfTargetId, relationship_type: RELATION_OBJECT };
    77 72   const inferredTarget = await createInferredRelation(context, inputForIdentity, ruleIdentityContent, opts) as RelationCreation;
    78 73   if (inferredTarget.isCreation) {
    79  - const target = targetsMap[partOfTargetId];
    80  - target.i_relation = inferredTarget.element;
    81  - createdTargets.push(target);
     74 + const event = buildCreateEvent(RULE_MANAGER_USER, inferredTarget.element, '');
     75 + events.push(event);
    82 76   }
    83 77   }
    84 78   }
    85  - if (createdTargets.length > 0) {
    86  - const updatedReport = { ...report };
    87  - const inputs = [{ key: INPUT_OBJECTS, value: createdTargets, operation: UPDATE_OPERATION_ADD }];
    88  - const message = generateUpdateMessage(inputs);
    89  - updatedReport[INPUT_OBJECTS] = [...(updatedReport[INPUT_OBJECTS] ?? []), ...createdTargets];
    90  - await storeUpdateEvent(context, RULE_MANAGER_USER, report, updatedReport, message);
    91  - }
     79 + return events;
    92 80   };
    93  - const handleReportCreation = async (context: AuthContext, report: StixReport, addedIdentityRefs: Array<string>) => {
     81 + const handleReportCreation = async (context: AuthContext, report: StixReport, addedIdentityRefs: Array<string>): Promise<Array<Event>> => {
    94 82   const objectRefsToCreate: ArrayRefs = [];
    95 83   const { id: reportId } = report.extensions[STIX_EXT_OCTI];
    96 84   const identities = await internalFindByIds(context, RULE_MANAGER_USER, addedIdentityRefs) as Array<StoreObject>;
    skipped 8 lines
    105 93   const listFromArgs = { fromId: fromIds, toTypes: [relationTypes.rightType], callback: listFromCallback };
    106 94   await listAllRelations(context, RULE_MANAGER_USER, relationTypes.creationType, listFromArgs);
    107 95   // update the report
    108  - await createObjectRefsInferences(context, reportId, objectRefsToCreate);
    109  - return [];
     96 + return createObjectRefsInferences(context, reportId, objectRefsToCreate);
    110 97   };
    111  - const handlePartOfRelationCreation = async (context: AuthContext, partOfRelation: StixRelation) => {
     98 + const handlePartOfRelationCreation = async (context: AuthContext, partOfRelation: StixRelation): Promise<Array<Event>> => {
     99 + const events: Array<Event> = [];
    112 100   const { id: partOfId, source_ref: partOfFromId, target_ref: partOfTargetId } = partOfRelation.extensions[STIX_EXT_OCTI];
    113 101   const listFromCallback = async (relationships: Array<BasicStoreRelation>) => {
    114 102   for (let objectRefIndex = 0; objectRefIndex < relationships.length; objectRefIndex += 1) {
    115 103   const { fromId: reportId } = relationships[objectRefIndex];
    116  - await createObjectRefsInferences(context, reportId, [{ partOfFromId, partOfId, partOfTargetId }]);
     104 + const inferredEvents = await createObjectRefsInferences(context, reportId, [{ partOfFromId, partOfId, partOfTargetId }]);
     105 + events.push(...inferredEvents);
    117 106   }
    118 107   };
    119 108   const listReportArgs = { fromTypes: [containerType], toId: partOfFromId, callback: listFromCallback };
    120 109   await listAllRelations(context, RULE_MANAGER_USER, RELATION_OBJECT, listReportArgs);
    121  - return [];
     110 + return events;
     111 + };
     112 + const handleObjectRelationCreation = async (context: AuthContext, objectRelation: StixRelation): Promise<Array<Event>> => {
     113 + const events: Array<Event> = [];
     114 + const { source_ref: reportId, target_type, target_ref: targetId } = objectRelation.extensions[STIX_EXT_OCTI];
     115 + if (target_type === relationTypes.leftType || getParentTypes(target_type).includes(relationTypes.leftType)) {
     116 + const listFromCallback = async (relationships: Array<BasicStoreRelation>) => {
     117 + // Get the list of interesting part-of
     118 + for (let objectRefIndex = 0; objectRefIndex < relationships.length; objectRefIndex += 1) {
     119 + const { fromId: partOfFromId, internal_id: partOfId, toId: partOfTargetId } = relationships[objectRefIndex];
     120 + const inferredEvents = await createObjectRefsInferences(context, reportId, [{ partOfFromId, partOfId, partOfTargetId }]);
     121 + events.push(...inferredEvents);
     122 + }
     123 + };
     124 + // List all partOf from this indicator to observables
     125 + const listReportArgs = { fromId: targetId, toTypes: [relationTypes.rightType], callback: listFromCallback };
     126 + await listAllRelations(context, RULE_MANAGER_USER, relationTypes.creationType, listReportArgs);
     127 + }
     128 + return events;
    122 129   };
    123 130   const applyInsert = async (data: StixObject): Promise<Array<Event>> => {
    124  - const context = executionContext(ruleDefinition.name);
     131 + const context = executionContext(ruleDefinition.name, RULE_MANAGER_USER);
    125 132   const events: Array<Event> = [];
    126 133   const entityType = generateInternalType(data);
    127 134   if (entityType === containerType) {
    skipped 10 lines
    138 145   if (relationType === relationTypes.creationType) {
    139 146   return handlePartOfRelationCreation(context, upsertRelation);
    140 147   }
     148 + if (relationType === RELATION_OBJECT) { // This event can be generated internally
     149 + return handleObjectRelationCreation(context, upsertRelation);
     150 + }
    141 151   return events;
    142 152   };
    143 153   const applyUpdate = async (data: StixObject, event: UpdateEvent): Promise<Array<RuleEvent>> => {
    144  - const context = executionContext(ruleDefinition.name);
     154 + const context = executionContext(ruleDefinition.name, RULE_MANAGER_USER);
    145 155   const events: Array<RuleEvent> = [];
    146 156   const entityType = generateInternalType(data);
    147 157   if (entityType === containerType) {
    skipped 1 lines
    149 159   const operations: Array<Operation> = event.context.patch;
    150 160   const previousPatch = event.context.reverse_patch;
    151 161   const previousData = jsonpatch.applyPatch<StixReport>(R.clone(report), previousPatch).newDocument;
    152  - const refOperations = operations.filter((o) => o.path.startsWith('/object_refs')
    153  - || o.path.startsWith(INFERRED_OBJECT_REF_PATH));
     162 + const refOperations = operations.filter((o) => o.path.startsWith('/object_refs'));
    154 163   const addedRefs: Array<StixId> = [];
    155 164   const removedRefs: Array<StixId> = [];
    156 165   // Replace operations behavior
    skipped 6 lines
    163 172   const removeObjectIndex = R.last(opPath.split('/'));
    164 173   if (removeObjectIndex) {
    165 174   const replaceObjectRefIndex = parseInt(removeObjectIndex, 10);
    166  - const isExtension = replaceOperation.path.startsWith(INFERRED_OBJECT_REF_PATH);
    167  - const baseData = isExtension ? previousData.extensions[STIX_EXT_OCTI].object_refs_inferred : previousData.object_refs;
    168  - const removeRefId = baseData[replaceObjectRefIndex];
     175 + const removeRefId = (previousData.object_refs ?? [])[replaceObjectRefIndex];
    169 176   removedRefs.push(removeRefId);
    170 177   }
    171 178   }
    skipped 9 lines
    181 188   for (let removeIndex = 0; removeIndex < removeOperations.length; removeIndex += 1) {
    182 189   const removeOperation = removeOperations[removeIndex];
    183 190   // For remove op we need to look into the previous data, the deleted element
    184  - const isExtension = removeOperation.path.startsWith(INFERRED_OBJECT_REF_PATH);
    185  - const baseData = isExtension ? previousData.extensions[STIX_EXT_OCTI].object_refs_inferred : previousData.object_refs;
     191 + const previousObjectRefs = previousData.object_refs;
    186 192   const opPath = removeOperation.path.substring(removeOperation.path.indexOf('/object_refs'));
    187 193   const [,, index] = opPath.split('/');
    188 194   if (index) {
    189 195   const replaceObjectRefIndex = parseInt(index, 10);
    190  - const removeRefId = baseData[replaceObjectRefIndex];
     196 + const removeRefId = previousObjectRefs[replaceObjectRefIndex];
    191 197   removedRefs.push(removeRefId);
    192 198   } else {
    193  - const removeRefIds = baseData ?? [];
     199 + const removeRefIds = previousObjectRefs ?? [];
    194 200   removedRefs.push(...removeRefIds);
    195 201   }
    196 202   }
    skipped 10 lines
    207 213   // For meta deletion, generate deletion events
    208 214   const removedRefIdentities = await internalFindByIds(context, RULE_MANAGER_USER, removedIdentityRefs) as Array<StoreObject>;
    209 215   const removedIds = removedRefIdentities.map((i) => i.internal_id);
    210  - const deleteEvent: DependenciesDeleteEvent = { type: 'delete-dependencies', ids: removedIds.map((ref) => `${ref}_ref`) };
     216 + const deleteEvent: DependenciesDeleteEvent = {
     217 + type: EVENT_TYPE_DELETE_DEPENDENCIES,
     218 + data: { ids: removedIds.map((ref) => `${ref}_ref`) }
     219 + };
    211 220   events.push(deleteEvent);
    212 221   }
    213 222   return events;
    skipped 17 lines
  • ■ ■ ■ ■ ■ ■
    opencti-platform/opencti-graphql/src/rules/indicate-sighted/IndicateSightedRule.ts
    skipped 8 lines
    9 9  import type { BasicStoreRelation, StoreObject } from '../../types/store';
    10 10  import { RELATION_OBJECT_MARKING } from '../../schema/stixMetaRelationship';
    11 11  import { computeAverage } from '../../database/utils';
    12  -import { createRuleContent, RULE_MANAGER_USER } from '../rules';
     12 +import { createRuleContent } from '../rules';
    13 13  import { createInferredRelation, deleteInferredRuleElement } from '../../database/middleware';
    14 14  import { listAllRelations, RelationOptions } from '../../database/middleware-loader';
    15 15  import { RELATION_INDICATES, RELATION_TARGETS } from '../../schema/stixCoreRelationship';
    skipped 5 lines
    21 21  } from '../../schema/stixDomainObject';
    22 22  import type { RuleRuntime } from '../../types/rules';
    23 23  import { ENTITY_TYPE_IDENTITY, ENTITY_TYPE_LOCATION } from '../../schema/general';
    24  -import { executionContext } from '../../utils/access';
     24 +import { executionContext, RULE_MANAGER_USER } from '../../utils/access';
    25 25  import type { AuthContext } from '../../types/user';
    26 26   
    27 27  const indicateSightedRuleBuilder = (): RuleRuntime => {
    skipped 94 lines
    122 122   return events;
    123 123   };
    124 124   const applyUpsert = async (data: StixRelation | StixSighting): Promise<Array<Event>> => {
    125  - const context = executionContext(def.name);
     125 + const context = executionContext(def.name, RULE_MANAGER_USER);
    126 126   if (data.extensions[STIX_EXT_OCTI].type === STIX_SIGHTING_RELATIONSHIP) {
    127 127   const sighting: StixSighting = data as StixSighting;
    128 128   return applyFromStixSighting(context, sighting);
    skipped 20 lines
  • ■ ■ ■ ■ ■ ■
    opencti-platform/opencti-graphql/src/rules/localization-of-targets/LocalizationOfTargetsRule.ts
    skipped 2 lines
    3 3  import { buildPeriodFromDates, computeRangeIntersection } from '../../utils/format';
    4 4  import { RELATION_TARGETS } from '../../schema/stixCoreRelationship';
    5 5  import def from './LocalizationOfTargetsDefinition';
    6  -import { createRuleContent, RULE_MANAGER_USER } from '../rules';
     6 +import { createRuleContent } from '../rules';
    7 7  import { computeAverage } from '../../database/utils';
    8 8  import type { StixRelation } from '../../types/stix-sro';
    9 9  import type { Event, RelationCreation } from '../../types/event';
    10 10  import { STIX_EXT_OCTI } from '../../types/stix-extensions';
    11 11  import type { BasicStoreObject, BasicStoreRelation, StoreObject } from '../../types/store';
    12 12  import { RELATION_OBJECT_MARKING } from '../../schema/stixMetaRelationship';
    13  -import { executionContext } from '../../utils/access';
     13 +import { executionContext, RULE_MANAGER_USER } from '../../utils/access';
    14 14   
    15 15  const ruleLocalizationOfTargetsBuilder = () => {
    16 16   // Execution
    17 17   const applyUpsert = async (data: StixRelation): Promise<Array<Event>> => {
    18  - const context = executionContext(def.name);
     18 + const context = executionContext(def.name, RULE_MANAGER_USER);
    19 19   const events: Array<Event> = [];
    20 20   const { extensions } = data;
    21 21   const createdId = extensions[STIX_EXT_OCTI].id;
    skipped 49 lines
  • ■ ■ ■ ■ ■ ■
    opencti-platform/opencti-graphql/src/rules/observed-sighting/ObserveSightingRule.ts
    skipped 8 lines
    9 9  import def from './ObserveSightingDefinition';
    10 10  import { ENTITY_TYPE_CONTAINER_OBSERVED_DATA, ENTITY_TYPE_INDICATOR } from '../../schema/stixDomainObject';
    11 11  import { RELATION_CREATED_BY, RELATION_OBJECT, RELATION_OBJECT_MARKING } from '../../schema/stixMetaRelationship';
    12  -import { createRuleContent, RULE_MANAGER_USER } from '../rules';
     12 +import { createRuleContent } from '../rules';
    13 13  import { STIX_SIGHTING_RELATIONSHIP } from '../../schema/stixSightingRelationship';
    14 14  import { ABSTRACT_STIX_CYBER_OBSERVABLE } from '../../schema/general';
    15 15  import { generateInternalType } from '../../schema/schemaUtils';
    skipped 5 lines
    21 21  import { STIX_EXT_OCTI } from '../../types/stix-extensions';
    22 22  import { listAllRelations } from '../../database/middleware-loader';
    23 23  import type { Event, RelationCreation } from '../../types/event';
    24  -import { executionContext } from '../../utils/access';
     24 +import { executionContext, RULE_MANAGER_USER } from '../../utils/access';
    25 25  import type { AuthContext } from '../../types/user';
    26 26   
    27 27  // 'If **observed-data A** (`created-by` **identity X**) have `object` **observable B** and **indicator C** ' +
    skipped 130 lines
    158 158   return handleIndicatorUpsert(context, baseOnIndicator);
    159 159   };
    160 160   const applyUpsert = async (data: StixObject): Promise<Array<Event>> => {
    161  - const context = executionContext(def.name);
     161 + const context = executionContext(def.name, RULE_MANAGER_USER);
    162 162   const events: Array<Event> = [];
    163 163   const entityType = generateInternalType(data);
    164 164   if (entityType === ENTITY_TYPE_INDICATOR) {
    skipped 28 lines
  • ■ ■ ■ ■ ■ ■
    opencti-platform/opencti-graphql/src/rules/relationToRelationBuilder.ts
    1 1  /* eslint-disable camelcase */
    2 2  import { buildPeriodFromDates, computeRangeIntersection } from '../utils/format';
    3 3  import { createInferredRelation, deleteInferredRuleElement } from '../database/middleware';
    4  -import { createRuleContent, RULE_MANAGER_USER } from './rules';
     4 +import { createRuleContent } from './rules';
    5 5  import { computeAverage } from '../database/utils';
    6 6  import { listAllRelations } from '../database/middleware-loader';
    7 7  import type { RuleRuntime, RuleDefinition, RelationTypes } from '../types/rules';
    skipped 2 lines
    10 10  import type { StixRelation } from '../types/stix-sro';
    11 11  import { STIX_EXT_OCTI } from '../types/stix-extensions';
    12 12  import { RELATION_OBJECT_MARKING } from '../schema/stixMetaRelationship';
    13  -import { executionContext } from '../utils/access';
     13 +import { executionContext, RULE_MANAGER_USER } from '../utils/access';
    14 14   
    15 15  const buildRelationToRelationRule = (ruleDefinition: RuleDefinition, relationTypes: RelationTypes): RuleRuntime => {
    16 16   const { id } = ruleDefinition;
    17 17   const { leftType, rightType, creationType } = relationTypes;
    18 18   // Execution
    19 19   const applyUpsert = async (data: StixRelation): Promise<Array<Event>> => {
    20  - const context = executionContext(ruleDefinition.name);
     20 + const context = executionContext(ruleDefinition.name, RULE_MANAGER_USER);
    21 21   const events: Array<Event> = [];
    22 22   const { extensions } = data;
    23 23   const createdId = extensions[STIX_EXT_OCTI].id;
    skipped 91 lines
  • ■ ■ ■ ■ ■ ■
    opencti-platform/opencti-graphql/src/rules/relationWithRelationBuilder.ts
    1 1  /* eslint-disable camelcase */
    2 2  import { createInferredRelation, deleteInferredRuleElement } from '../database/middleware';
    3 3  import { buildPeriodFromDates, computeRangeIntersection } from '../utils/format';
    4  -import { createRuleContent, RULE_MANAGER_USER } from './rules';
     4 +import { createRuleContent } from './rules';
    5 5  import { computeAverage } from '../database/utils';
    6 6  import { listAllRelations } from '../database/middleware-loader';
    7 7  import type { RelationTypes, RuleRuntime, RuleDefinition } from '../types/rules';
    skipped 2 lines
    10 10  import { STIX_EXT_OCTI } from '../types/stix-extensions';
    11 11  import type { StoreObject, BasicStoreRelation } from '../types/store';
    12 12  import { RELATION_OBJECT_MARKING } from '../schema/stixMetaRelationship';
    13  -import { executionContext } from '../utils/access';
     13 +import { executionContext, RULE_MANAGER_USER } from '../utils/access';
    14 14   
    15 15  const buildRelationWithRelationRule = (ruleDefinition: RuleDefinition, relationTypes: RelationTypes): RuleRuntime => {
    16 16   const { id } = ruleDefinition;
    skipped 1 lines
    18 18   const resolveTypes = { [leftType]: rightType, [rightType]: leftType };
    19 19   // Execution
    20 20   const applyUpsert = async (data: StixRelation): Promise<Array<Event>> => {
    21  - const context = executionContext(ruleDefinition.name);
     21 + const context = executionContext(ruleDefinition.name, RULE_MANAGER_USER);
    22 22   const events: Array<Event> = [];
    23 23   const { extensions } = data;
    24 24   const createdId = extensions[STIX_EXT_OCTI].id;
    skipped 57 lines
  • ■ ■ ■ ■ ■
    opencti-platform/opencti-graphql/src/rules/report-refs-identity-part-of/ReportRefIdentityPartOfDefinition.ts
    1 1  import { RELATION_PART_OF } from '../../schema/stixCoreRelationship';
    2 2  import { ENTITY_TYPE_IDENTITY } from '../../schema/general';
    3 3  import { ENTITY_TYPE_CONTAINER_REPORT } from '../../schema/stixDomainObject';
    4  -import type { RuleDefinition, RuleBehavior, RuleFilters, RuleScope } from '../../types/rules';
     4 +import type { RuleBehavior, RuleDefinition, RuleFilters, RuleScope } from '../../types/rules';
     5 +import { RELATION_OBJECT } from '../../schema/stixMetaRelationship';
    5 6   
    6 7  const id = 'report_ref_identity_part_of';
    7 8  const name = 'Identities propagation in reports';
    skipped 39 lines
    47 48  };
    48 49   
    49 50  // For rescan
    50  -const scan: RuleFilters = { types: [RELATION_PART_OF], fromTypes: [ENTITY_TYPE_IDENTITY], toTypes: [ENTITY_TYPE_IDENTITY] };
     51 +const scan: RuleFilters = { types: [RELATION_OBJECT], fromTypes: [ENTITY_TYPE_CONTAINER_REPORT], toTypes: [ENTITY_TYPE_IDENTITY] };
    51 52   
    52 53  // For live
    53 54  const scopes: Array<RuleScope> = [
    skipped 3 lines
    57 58   },
    58 59   {
    59 60   filters: { types: [RELATION_PART_OF], fromTypes: [ENTITY_TYPE_IDENTITY], toTypes: [ENTITY_TYPE_IDENTITY] },
     61 + attributes: [],
     62 + },
     63 + {
     64 + filters: { types: [RELATION_OBJECT], fromTypes: [ENTITY_TYPE_CONTAINER_REPORT], toTypes: [ENTITY_TYPE_IDENTITY] },
    60 65   attributes: [],
    61 66   },
    62 67  ];
    skipped 5 lines
  • ■ ■ ■ ■ ■
    opencti-platform/opencti-graphql/src/rules/report-refs-indicator-based-on/ReportRefIndicatorBasedOnDefinition.ts
    skipped 1 lines
    2 2  import { ABSTRACT_STIX_CYBER_OBSERVABLE } from '../../schema/general';
    3 3  import { ENTITY_TYPE_CONTAINER_REPORT, ENTITY_TYPE_INDICATOR } from '../../schema/stixDomainObject';
    4 4  import type { RuleBehavior, RuleDefinition, RuleFilters, RuleScope } from '../../types/rules';
     5 +import { RELATION_OBJECT } from '../../schema/stixMetaRelationship';
    5 6   
    6 7  const id = 'report_ref_indicator_based_on';
    7 8  const name = 'Observables propagation in reports';
    skipped 39 lines
    47 48  };
    48 49   
    49 50  // For rescan
    50  -const scan: RuleFilters = { types: [RELATION_BASED_ON], fromTypes: [ENTITY_TYPE_INDICATOR], toTypes: [ABSTRACT_STIX_CYBER_OBSERVABLE] };
     51 +const scan: RuleFilters = { types: [RELATION_OBJECT], fromTypes: [ENTITY_TYPE_CONTAINER_REPORT], toTypes: [ENTITY_TYPE_INDICATOR] };
    51 52   
    52 53  // For live
    53 54  const scopes: Array<RuleScope> = [
    skipped 3 lines
    57 58   },
    58 59   {
    59 60   filters: { types: [RELATION_BASED_ON], fromTypes: [ENTITY_TYPE_INDICATOR], toTypes: [ABSTRACT_STIX_CYBER_OBSERVABLE] },
     61 + attributes: [],
     62 + },
     63 + {
     64 + filters: { types: [RELATION_OBJECT], fromTypes: [ENTITY_TYPE_CONTAINER_REPORT], toTypes: [ENTITY_TYPE_INDICATOR] },
    60 65   attributes: [],
    61 66   },
    62 67  ];
    skipped 5 lines
  • ■ ■ ■ ■ ■
    opencti-platform/opencti-graphql/src/rules/rules.js
    1 1  import * as R from 'ramda';
    2 2  import { UnsupportedError } from '../config/errors';
    3  -import { shortHash, isInternalId } from '../schema/schemaUtils';
     3 +import { isInternalId, shortHash } from '../schema/schemaUtils';
    4 4  import { RULE_PREFIX } from '../schema/general';
    5 5  import { isEmptyField, isNotEmptyField } from '../database/utils';
    6 6  import { logApp } from '../config/conf';
    7  -import { BYPASS, ROLE_ADMINISTRATOR } from '../utils/access';
     7 +import { RULE_MANAGER_USER_UUID } from '../utils/access';
    8 8   
    9 9  // region definition
    10 10  export const RULES_ATTRIBUTES_BEHAVIOR = {
    skipped 23 lines
    34 34   supportedAttributes() {
    35 35   return Object.keys(this._attributes);
    36 36   },
    37  -};
    38  -const RULE_MANAGER_USER_UUID = 'f9d7b43f-b208-4c56-8637-375a1ce84943';
    39  -export const RULE_MANAGER_USER = {
    40  - id: RULE_MANAGER_USER_UUID,
    41  - internal_id: RULE_MANAGER_USER_UUID,
    42  - name: 'RULE MANAGER',
    43  - user_email: 'RULE MANAGER',
    44  - inside_platform_organization: true,
    45  - origin: { user_id: RULE_MANAGER_USER_UUID },
    46  - roles: [{ name: ROLE_ADMINISTRATOR }],
    47  - capabilities: [{ name: BYPASS }],
    48  - organizations: [],
    49  - allowed_organizations: [],
    50  - allowed_marking: [],
    51  - all_marking: [],
    52 37  };
    53 38  // endregion
    54 39   
    skipped 15 lines
  • ■ ■ ■ ■ ■ ■
    opencti-platform/opencti-graphql/src/rules/sighting-incident/SightingIncidentRule.ts
    skipped 6 lines
    7 7  } from '../../database/middleware';
    8 8  import def from './SightingIncidentDefinition';
    9 9  import { ENTITY_TYPE_INCIDENT, ENTITY_TYPE_INDICATOR } from '../../schema/stixDomainObject';
    10  -import { createRuleContent, RULE_MANAGER_USER } from '../rules';
     10 +import { createRuleContent } from '../rules';
    11 11  import { STIX_SIGHTING_RELATIONSHIP } from '../../schema/stixSightingRelationship';
    12 12  import { ENTITY_TYPE_IDENTITY } from '../../schema/general';
    13 13  import { generateInternalType } from '../../schema/schemaUtils';
    skipped 4 lines
    18 18  import type { Event, RelationCreation } from '../../types/event';
    19 19  import { STIX_EXT_OCTI } from '../../types/stix-extensions';
    20 20  import type { BasicStoreRelation, StoreObject } from '../../types/store';
    21  -import { executionContext } from '../../utils/access';
     21 +import { executionContext, RULE_MANAGER_USER } from '../../utils/access';
    22 22  import type { AuthContext } from '../../types/user';
    23 23   
    24 24  // 'If **indicator A** has `revoked` **false** and **indicator A** is `sighted` in ' +
    skipped 62 lines
    87 87   return handleIndicatorUpsert(context, sightingIndicator as StixIndicator);
    88 88   };
    89 89   const applyUpsert = async (data: StixIndicator | StixSighting): Promise<Array<Event>> => {
    90  - const context = executionContext(def.name);
     90 + const context = executionContext(def.name, RULE_MANAGER_USER);
    91 91   const events: Array<Event> = [];
    92 92   const entityType = generateInternalType(data);
    93 93   if (entityType === ENTITY_TYPE_INDICATOR) {
    skipped 23 lines
  • ■ ■ ■ ■ ■ ■
    opencti-platform/opencti-graphql/src/rules/sighting-indicator/SightingIndicatorRule.ts
    skipped 8 lines
    9 9  import type { BasicStoreRelation, StoreObject } from '../../types/store';
    10 10  import { RELATION_OBJECT_MARKING } from '../../schema/stixMetaRelationship';
    11 11  import { computeAverage } from '../../database/utils';
    12  -import { createRuleContent, RULE_MANAGER_USER } from '../rules';
     12 +import { createRuleContent } from '../rules';
    13 13  import { createInferredRelation, deleteInferredRuleElement } from '../../database/middleware';
    14 14  import { listAllRelations, RelationOptions } from '../../database/middleware-loader';
    15 15  import { RELATION_BASED_ON } from '../../schema/stixCoreRelationship';
    16 16  import type { RuleRuntime } from '../../types/rules';
    17 17  import { ABSTRACT_STIX_CYBER_OBSERVABLE, ENTITY_TYPE_IDENTITY, ENTITY_TYPE_LOCATION } from '../../schema/general';
    18 18  import type { AuthContext } from '../../types/user';
    19  -import { executionContext } from '../../utils/access';
     19 +import { executionContext, RULE_MANAGER_USER } from '../../utils/access';
    20 20   
    21 21  /*
    22 22  'If **indicator A** is `sighted` in **identity/location B** and '
    skipped 97 lines
    120 120   return events;
    121 121   };
    122 122   const applyUpsert = async (data: StixRelation | StixSighting): Promise<Array<Event>> => {
    123  - const context = executionContext(def.name);
     123 + const context = executionContext(def.name, RULE_MANAGER_USER);
    124 124   if (data.extensions[STIX_EXT_OCTI].type === STIX_SIGHTING_RELATIONSHIP) {
    125 125   const sighting: StixSighting = data as StixSighting;
    126 126   return applyFromStixSighting(context, sighting);
    skipped 20 lines
  • ■ ■ ■ ■ ■ ■
    opencti-platform/opencti-graphql/src/rules/sighting-observable/SightingObservableRule.ts
    skipped 8 lines
    9 9  import type { BasicStoreRelation, StoreObject } from '../../types/store';
    10 10  import { RELATION_OBJECT_MARKING } from '../../schema/stixMetaRelationship';
    11 11  import { computeAverage } from '../../database/utils';
    12  -import { createRuleContent, RULE_MANAGER_USER } from '../rules';
     12 +import { createRuleContent } from '../rules';
    13 13  import { createInferredRelation, deleteInferredRuleElement } from '../../database/middleware';
    14 14  import { listAllRelations, RelationOptions } from '../../database/middleware-loader';
    15 15  import { RELATION_BASED_ON } from '../../schema/stixCoreRelationship';
    16 16  import { ENTITY_TYPE_INDICATOR } from '../../schema/stixDomainObject';
    17 17  import type { RuleRuntime } from '../../types/rules';
    18 18  import { ENTITY_TYPE_IDENTITY, ENTITY_TYPE_LOCATION } from '../../schema/general';
    19  -import { executionContext } from '../../utils/access';
     19 +import { executionContext, RULE_MANAGER_USER } from '../../utils/access';
    20 20  import type { AuthContext } from '../../types/user';
    21 21   
    22 22  /*
    skipped 98 lines
    121 121   return events;
    122 122   };
    123 123   const applyUpsert = async (data: StixRelation | StixSighting): Promise<Array<Event>> => {
    124  - const context = executionContext(def.name);
     124 + const context = executionContext(def.name, RULE_MANAGER_USER);
    125 125   if (data.extensions[STIX_EXT_OCTI].type === STIX_SIGHTING_RELATIONSHIP) {
    126 126   const sighting: StixSighting = data as StixSighting;
    127 127   return applyFromStixSighting(context, sighting);
    skipped 20 lines
  • ■ ■ ■ ■ ■
    opencti-platform/opencti-graphql/src/types/event.d.ts
    skipped 26 lines
    27 27   
    28 28  interface DependenciesDeleteEvent extends RuleEvent {
    29 29   type: 'delete-dependencies';
    30  - ids: Array<string>;
     30 + data: {
     31 + ids: Array<string>
     32 + };
    31 33  }
    32 34   
    33 35  // stream
    skipped 49 lines
  • ■ ■ ■ ■ ■ ■
    opencti-platform/opencti-graphql/src/types/stix-sdo.d.ts
    skipped 194 lines
    195 195   sample_ref: StixId; // optional
    196 196  }
    197 197   
    198  -interface StixContainerExtension extends StixOpenctiExtension {
    199  - object_refs_inferred: Array<StixId>;
    200  -}
    201  - 
    202 198  // Note Specific Properties
    203 199  // abstract, content, authors, object_refs
    204 200  interface StixNote extends StixDomainObject {
    skipped 103 lines
  • ■ ■ ■ ■ ■
    opencti-platform/opencti-graphql/src/types/store.d.ts
    skipped 45 lines
    46 46   RELATION_CREATED_BY,
    47 47   RELATION_EXTERNAL_REFERENCE,
    48 48   RELATION_GRANTED_TO,
     49 + RELATION_OBJECT,
    49 50   RELATION_OBJECT_MARKING
    50 51  } from '../schema/stixMetaRelationship';
    51 52  import type { PageInfo } from '../generated/graphql';
    skipped 215 lines
    267 268   i_relation: BasicStoreRelation; // internal related relation for refs
    268 269   // rels
    269 270   [RELATION_CREATED_BY]: string;
    270  - [RELATION_OBJECT_MARKING]: Array<string>;
     271 + [RELATION_OBJECT]: Array<string>;
    271 272   // Array
    272 273   x_mitre_permissions_required: Array<string>;
    273 274   x_mitre_platforms: Array<string>;
    skipped 275 lines
  • ■ ■ ■ ■ ■
    opencti-platform/opencti-graphql/src/types/user.d.ts
    skipped 32 lines
    33 33  interface AuthContext {
    34 34   source: string;
    35 35   tracing: TracingContext
     36 + user: AuthUser | undefined;
    36 37  }
    37 38   
  • ■ ■ ■ ■ ■ ■
    opencti-platform/opencti-graphql/src/utils/access.ts
    1 1  import * as R from 'ramda';
    2  -import type { Request } from 'express';
    3 2  import type { Context, Span, Tracer } from '@opentelemetry/api';
     3 +import type { Request } from 'express';
    4 4  import { context as telemetryContext, trace } from '@opentelemetry/api';
    5 5  import { OPENCTI_SYSTEM_UUID } from '../schema/general';
    6 6  import { basePath, baseUrl } from '../config/conf';
    7  -import type { AuthContext, AuthUser } from '../types/user';
    8  -import type { BasicStoreCommon, BasicStoreSettings } from '../types/store';
    9 7  import { RELATION_GRANTED_TO, RELATION_OBJECT_MARKING } from '../schema/stixMetaRelationship';
    10 8  import { getEntityFromCache } from '../database/cache';
    11 9  import { ENTITY_TYPE_SETTINGS } from '../schema/internalObject';
    12 10  import { STIX_EXT_OCTI } from '../types/stix-extensions';
     11 +import type { AuthContext, AuthUser } from '../types/user';
     12 +import type { BasicStoreCommon, BasicStoreSettings } from '../types/store';
    13 13  import type { StixCoreObject } from '../types/stix-common';
    14 14   
    15 15  export const BYPASS = 'BYPASS';
    skipped 1 lines
    17 17  export const KNOWLEDGE_ORGANIZATION_RESTRICT = 'KNOWLEDGE_KNUPDATE_KNORGARESTRICT';
    18 18  export const ROLE_ADMINISTRATOR = 'Administrator';
    19 19  const RETENTION_MANAGER_USER_UUID = '82ed2c6c-eb27-498e-b904-4f2abc04e05f';
    20  - 
    21  -class TracingContext {
    22  - ctx: Context | undefined;
    23  - 
    24  - tracer: Tracer;
    25  - 
    26  - constructor(tracer: Tracer) {
    27  - this.tracer = tracer;
    28  - this.ctx = undefined;
    29  - }
    30  - 
    31  - getCtx() {
    32  - return this.ctx;
    33  - }
    34  - 
    35  - getTracer() {
    36  - return this.tracer;
    37  - }
    38  - 
    39  - setCurrentCtx(span: Span) {
    40  - this.ctx = trace.setSpan(telemetryContext.active(), span);
    41  - }
    42  -}
    43  - 
    44  -export const executionContext = (source: string): AuthContext => {
    45  - const tracer = trace.getTracer('instrumentation-opencti', '1.0.0');
    46  - const tracing = new TracingContext(tracer);
    47  - return { source, tracing };
    48  -};
     20 +export const RULE_MANAGER_USER_UUID = 'f9d7b43f-b208-4c56-8637-375a1ce84943';
    49 21   
    50 22  export const SYSTEM_USER: AuthUser = {
    51 23   id: OPENCTI_SYSTEM_UUID,
    skipped 25 lines
    77 49   all_marking: [],
    78 50  };
    79 51   
     52 +export const RULE_MANAGER_USER: AuthUser = {
     53 + id: RULE_MANAGER_USER_UUID,
     54 + internal_id: RULE_MANAGER_USER_UUID,
     55 + name: 'RULE MANAGER',
     56 + user_email: 'RULE MANAGER',
     57 + inside_platform_organization: true,
     58 + origin: { user_id: RULE_MANAGER_USER_UUID },
     59 + roles: [{ name: ROLE_ADMINISTRATOR }],
     60 + capabilities: [{ name: BYPASS }],
     61 + organizations: [],
     62 + allowed_organizations: [],
     63 + allowed_marking: [],
     64 + all_marking: [],
     65 +};
     66 + 
     67 +class TracingContext {
     68 + ctx: Context | undefined;
     69 + 
     70 + tracer: Tracer;
     71 + 
     72 + constructor(tracer: Tracer) {
     73 + this.tracer = tracer;
     74 + this.ctx = undefined;
     75 + }
     76 + 
     77 + getCtx() {
     78 + return this.ctx;
     79 + }
     80 + 
     81 + getTracer() {
     82 + return this.tracer;
     83 + }
     84 + 
     85 + setCurrentCtx(span: Span) {
     86 + this.ctx = trace.setSpan(telemetryContext.active(), span);
     87 + }
     88 +}
     89 + 
     90 +export const executionContext = (source: string, auth?: AuthUser): AuthContext => {
     91 + const tracer = trace.getTracer('instrumentation-opencti', '1.0.0');
     92 + const tracing = new TracingContext(tracer);
     93 + return { source, tracing, user: auth ?? undefined };
     94 +};
     95 + 
    80 96  export const INTERNAL_USERS = {
    81 97   [SYSTEM_USER.id]: SYSTEM_USER,
    82  - [RETENTION_MANAGER_USER.id]: RETENTION_MANAGER_USER
     98 + [RETENTION_MANAGER_USER.id]: RETENTION_MANAGER_USER,
     99 + [RULE_MANAGER_USER.id]: RULE_MANAGER_USER
    83 100  };
    84 101   
    85 102  export const getBaseUrl = (req: Request): string => {
    skipped 78 lines
  • ■ ■ ■ ■
    opencti-platform/opencti-graphql/tests/02-integration/01-database/middleware-test.js
    skipped 745 lines
    746 746   },
    747 747   },
    748 748   };
    749  - const looking = await elRawSearch(executionContext(), SYSTEM_USER, 'Relastionships', query);
     749 + const looking = await elRawSearch(executionContext('test'), SYSTEM_USER, 'Relastionships', query);
    750 750   const numberOfResult = looking.hits.total.value;
    751 751   return numberOfResult > 0;
    752 752  };
    skipped 314 lines
Please wait...
Page is in error, reload to recover