| 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 | class SSPAssemble(AuthorCommonCommand):
    """Assemble markdown files of controls into an SSP json file."""
    name = 'ssp-assemble'
    def _init_arguments(self) -> None:
        name_help_str = (
            'Optional name of the ssp model in the trestle workspace that is being modified.  '
            'If not provided the output name is used.'
        )
        self.add_argument('-n', '--name', help=name_help_str, required=False, type=str)
        file_help_str = 'Name of the input markdown file directory'
        self.add_argument('-m', '--markdown', help=file_help_str, required=True, type=str)
        output_help_str = 'Name of the output generated json SSP'
        self.add_argument('-cd', '--compdefs', help=const.HELP_COMPDEFS, required=False, type=str)
        self.add_argument('-o', '--output', help=output_help_str, required=True, type=str)
        self.add_argument('-r', '--regenerate', action='store_true', help=const.HELP_REGENERATE)
        self.add_argument('-vn', '--version', help=const.HELP_VERSION, required=False, type=str)
    @staticmethod
    def _get_ssp_component(ssp: ossp.SystemSecurityPlan, gen_comp: generic.GenericComponent) -> ossp.SystemComponent:
        for component in as_list(ssp.system_implementation.components):
            if component.title == gen_comp.title:
                return component
        # if this is a new system component assign its status as operational by default
        # the status of the system components are not stored in the markdown
        gen_comp.status.state = const.STATUS_OPERATIONAL
        new_component = gen_comp.as_system_component()
        return new_component
    @staticmethod
    def _merge_by_comps(stat: ossp.Statement, statement: ossp.Statement, set_params: List[ossp.SetParameter]) -> None:
        for by_comp in as_list(statement.by_components):
            found = False
            for dest_by_comp in as_list(stat.by_components):
                if dest_by_comp.component_uuid == by_comp.component_uuid:
                    dest_by_comp.description = by_comp.description
                    dest_by_comp.props = as_list(dest_by_comp.props)
                    dest_by_comp.props.extend(as_list(statement.props))
                    dest_by_comp.props = none_if_empty(ControlInterface.clean_props(by_comp.props))
                    dest_by_comp.implementation_status = by_comp.implementation_status
                    dest_by_comp.set_parameters = none_if_empty(set_params)
                    found = True
                    break
            if not found:
                stat.by_components = as_list(stat.by_components)
                by_comp.set_parameters = none_if_empty(set_params)
                stat.by_components.append(by_comp)
    @staticmethod
    def _merge_statement(
        imp_req: ossp.ImplementedRequirement,
        statement: generic.GenericStatement,
        set_params: List[ossp.SetParameter],
    ) -> None:
        """Merge the generic statement into the statements of the imp_req."""
        # if the statement id is already in the imp_req, merge its by_comps into the existing statement
        for stat in as_list(imp_req.statements):
            if stat.statement_id == statement.statement_id:
                SSPAssemble._merge_by_comps(stat, statement, set_params)
                return
        # otherwise just ad the statement - but only if it has by_comps
        if statement.by_components:
            imp_req.statements = as_list(imp_req.statements)
            imp_req.statements.append(statement)
    @staticmethod
    def _merge_imp_req_into_imp_req(
        imp_req: ossp.ImplementedRequirement,
        gen_imp_req: generic.GenericImplementedRequirement,
        set_params: List[ossp.SetParameter]
    ) -> None:
        """Merge comp def imp req into existing imp req."""
        # convert generic imp req from comp defs into ssp form
        src_imp_req = gen_imp_req.as_ssp()
        imp_req.props = none_if_empty(
            ControlInterface.clean_props(gen_imp_req.props, remove_imp_status=True, remove_all_rule_info=True)
        )
        for statement in as_list(src_imp_req.statements):
            SSPAssemble._merge_statement(imp_req, statement, set_params)
    @staticmethod
    def _get_params_for_rules(context: ControlContext, rules_list: List[str],
                              set_params: List[ossp.SetParameter]) -> List[ossp.SetParameter]:
        """Get all set_params needed by the rules along with non-rule set_params."""
        needed_param_ids: Set[str] = set()
        rule_dict = context.rules_params_dict.get(context.comp_name, {})
        # find param_ids needed by rules
        for rule_id in rules_list:
            # get list of param_ids associated with this rule_id
            param_ids = [
                param['name'] for params in rule_dict.values() for param in params if param['rule-id'] == rule_id
            ]
            needed_param_ids.update(param_ids)
        all_rule_param_ids = [param['name'] for params in rule_dict.values() for param in params]
        # any set_param that isn't associated with a rule should be included as a normal control set param with no rule
        for set_param in set_params:
            if set_param.param_id not in all_rule_param_ids:
                needed_param_ids.add(set_param.param_id)
        param_ids_list = sorted(needed_param_ids)
        needed_set_params: List[ossp.SetParameter] = []
        for param_id in param_ids_list:
            set_param = None
            for sp in set_params:
                if sp.param_id == param_id:
                    set_param = sp
                    break
            if set_param:
                needed_set_params.append(set_param)
            else:
                logger.warning(f'No set param found for param {param_id}')
        return needed_set_params
    @staticmethod
    def _add_imp_req_to_ssp(
        ssp: ossp.SystemSecurityPlan,
        gen_comp: generic.GenericComponent,
        gen_imp_req: generic.GenericImplementedRequirement,
        set_params: List[ossp.SetParameter],
        context: ControlContext
    ) -> None:
        """Add imp req from control implementation into new ssp being assembled."""
        # the incoming gen_imp_req comes directly from the comp def
        # but the imp_req here is pulled from the ssp and created if not already there
        imp_req = CatalogReader._get_imp_req_for_control(ssp, gen_imp_req.control_id)
        local_set_params = as_list(set_params)[:]
        local_set_params.extend(as_list(imp_req.set_parameters))
        local_set_params = ControlInterface.uniquify_set_params(local_set_params)
        # get any rules set at control level, if present
        rules_list, _ = ControlInterface.get_rule_list_for_item(gen_imp_req)  # type: ignore
        # There should be no rule content at top level of imp_req in ssp so strip them out
        imp_req.props = none_if_empty(
            ControlInterface.clean_props(gen_imp_req.props, remove_imp_status=True, remove_all_rule_info=True)
        )
        # if we have rules applying or need to make set_params, we need to make a by_comp
        control_set_params = SSPAssemble._get_params_for_rules(context, rules_list, local_set_params)
        if rules_list or control_set_params:
            by_comp = gens.generate_sample_model(ossp.ByComponent)
            by_comp.component_uuid = gen_comp.uuid
            by_comp.description = gen_imp_req.description
            by_comp.set_parameters = none_if_empty(control_set_params)
            by_comp.implementation_status = ControlInterface.get_status_from_props(gen_imp_req)  # type: ignore
            by_comp.props = none_if_empty(ControlInterface.clean_props(gen_imp_req.props))
            imp_req.by_components = as_list(imp_req.by_components)
            imp_req.by_components.append(by_comp)
        # each statement in ci corresponds to by_comp in an ssp imp req
        # so insert the new by_comp directly into the ssp, generating parts as needed
        imp_req.statements = as_list(imp_req.statements)
        for statement in as_list(gen_imp_req.statements):
            if ControlInterface.item_has_rules(statement):  # type: ignore
                imp_req = CatalogReader._get_imp_req_for_statement(ssp, gen_imp_req.control_id, statement.statement_id)
                by_comp = CatalogReader._get_by_comp_from_imp_req(imp_req, statement.statement_id, gen_comp.uuid)
                by_comp.description = statement.description
                by_comp.props = none_if_empty(ControlInterface.clean_props(statement.props))
                rules_list, _ = ControlInterface.get_rule_list_for_item(statement)  # type: ignore
                by_comp.set_parameters = none_if_empty(
                    SSPAssemble._get_params_for_rules(context, rules_list, local_set_params)
                )
        imp_req.statements = none_if_empty(imp_req.statements)
        ssp.control_implementation.implemented_requirements = as_list(
            ssp.control_implementation.implemented_requirements
        )
    @staticmethod
    def _merge_imp_req_into_ssp(
        ssp: ossp.SystemSecurityPlan,
        gen_imp_req: generic.GenericImplementedRequirement,
        set_params: List[ossp.SetParameter],
    ) -> None:
        """Merge the new imp_reqs into the ssp."""
        for imp_req in as_list(ssp.control_implementation.implemented_requirements):
            if imp_req.control_id == gen_imp_req.control_id:
                SSPAssemble._merge_imp_req_into_imp_req(imp_req, gen_imp_req, set_params)
                return
        new_imp_req = gen_imp_req.as_ssp()
        imp_req.props = none_if_empty(
            ControlInterface.clean_props(gen_imp_req.props, remove_imp_status=True, remove_all_rule_info=True)
        )
        ssp.control_implementation.implemented_requirements.append(new_imp_req)
    def _merge_comp_defs(
        self,
        ssp: ossp.SystemSecurityPlan,
        comp_dict: Dict[str, generic.GenericComponent],
        context: ControlContext,
        catalog_interface: CatalogInterface
    ) -> None:
        """Merge the original generic comp defs into the ssp."""
        all_comps: List[ossp.SystemComponent] = []
        # determine if this is a new and empty ssp
        new_ssp = not ssp.control_implementation.implemented_requirements
        for _, gen_comp in comp_dict.items():
            context.comp_name = gen_comp.title
            all_ci_props: List[com.Property] = []
            ssp_comp = SSPAssemble._get_ssp_component(ssp, gen_comp)
            set_params: List[ossp.SetParameter] = []
            for ci in as_list(gen_comp.control_implementations):
                all_ci_props.extend(as_list(ci.props))
                # get the list of set_params in the control implementation - for this component
                for sp in as_list(ci.set_parameters):
                    set_params.append(sp.to_ssp())
                for imp_req in as_list(ci.implemented_requirements):
                    # ignore any controls not in the ssp profile (resolved catalog)
                    if not catalog_interface.get_control(imp_req.control_id):
                        logger.debug(f'Ignoring imp_req for control {imp_req.control_id} not in ssp profile')
                        continue
                    if new_ssp:
                        SSPAssemble._add_imp_req_to_ssp(ssp, gen_comp, imp_req, set_params, context)
                    else:
                        # compile all new uuids for new component definitions
                        comp_uuids = [x.uuid for x in comp_dict.values()]
                        for imp_requirement in as_list(ssp.control_implementation.implemented_requirements):
                            to_delete = []
                            for i, by_comp in enumerate(imp_requirement.by_components):
                                if by_comp.component_uuid not in comp_uuids:
                                    logger.warning(
                                        f'By_component {by_comp.component_uuid} removed from implemented requirement '
                                        f'{imp_requirement.control_id} because the corresponding component is not in '
                                        'the specified compdefs '
                                    )
                                    to_delete.append(i)
                            if to_delete:
                                delete_list_from_list(imp_requirement.by_components, to_delete)
                        SSPAssemble._merge_imp_req_into_ssp(ssp, imp_req, set_params)
            ssp_comp.props = as_list(gen_comp.props)
            ssp_comp.props.extend(all_ci_props)
            ssp_comp.props = none_if_empty(ControlInterface.clean_props(ssp_comp.props))
            all_comps.append(ssp_comp)
        ssp.system_implementation.components = none_if_empty(all_comps)
    def _generate_roles_in_metadata(self, ssp: ossp.SystemSecurityPlan) -> bool:
        """Find all roles referenced by imp reqs and create role in metadata as needed."""
        metadata = ssp.metadata
        metadata.roles = as_list(metadata.roles)
        known_role_ids = [role.id for role in metadata.roles]
        changed = False
        for imp_req in ssp.control_implementation.implemented_requirements:
            role_ids = [resp_role.role_id for resp_role in as_list(imp_req.responsible_roles)]
            for role_id in role_ids:
                if role_id not in known_role_ids:
                    role = com.Role(id=role_id, title=role_id)
                    metadata.roles.append(role)
                    known_role_ids.append(role_id)
                    changed = True
        metadata.roles = none_if_empty(metadata.roles)
        return changed
    @staticmethod
    def _build_comp_dict_from_comp_defs(
        trestle_root: pathlib.Path, comp_def_name_list: List[str], create_sys_comp: bool
    ) -> Dict[str, generic.GenericComponent]:
        comp_dict: Dict[str, generic.GenericComponent] = {}
        for comp_name in comp_def_name_list:
            comp_def, _ = ModelUtils.load_model_for_class(trestle_root, comp_name, comp.ComponentDefinition)
            for def_comp in as_list(comp_def.components):
                gen_def_comp = generic.GenericComponent.from_defined_component(def_comp)
                comp_dict[def_comp.title] = gen_def_comp
        if create_sys_comp:
            sys_comp = generic.GenericComponent.generate()
            sys_comp.type = const.THIS_SYSTEM_AS_KEY
            sys_comp.title = const.SSP_MAIN_COMP_NAME
            comp_dict[sys_comp.title] = sys_comp
        return comp_dict
    @staticmethod
    def _get_this_system_as_gen_comp(ssp: ossp.SystemSecurityPlan) -> Optional[generic.GenericComponent]:
        for component in as_list(ssp.system_implementation.components):
            if component.title == const.SSP_MAIN_COMP_NAME:
                return generic.GenericComponent.from_defined_component(component)
        return None
    def _run(self, args: argparse.Namespace) -> int:
        try:
            log.set_log_level_from_args(args)
            trestle_root = pathlib.Path(args.trestle_root)
            md_path = trestle_root / args.markdown
            # the original, reference ssp name defaults to same as output if name not specified
            # thus in cyclic editing you are reading and writing same json ssp
            orig_ssp_name = args.output
            if args.name:
                orig_ssp_name = args.name
            new_ssp_name = args.output
            _, profile_href = ComponentAssemble._get_profile_title_and_href_from_dir(md_path)
            res_cat = ProfileResolver.get_resolved_profile_catalog(
                trestle_root, profile_href, param_rep=ParameterRep.LEAVE_MOUSTACHE
            )
            catalog_interface = CatalogInterface(res_cat)
            new_file_content_type = FileContentType.JSON
            # if output ssp already exists, load it to see if new one is different
            existing_ssp: Optional[ossp.SystemSecurityPlan] = None
            new_ssp_path = ModelUtils.get_model_path_for_name_and_class(
                trestle_root, new_ssp_name, ossp.SystemSecurityPlan
            )
            if new_ssp_path:
                _, _, existing_ssp = ModelUtils.load_distributed(new_ssp_path, trestle_root)
                new_file_content_type = FileContentType.path_to_content_type(new_ssp_path)
            ssp: ossp.SystemSecurityPlan
            # if orig ssp exists - need to load it rather than instantiate new one
            orig_ssp_path = ModelUtils.get_model_path_for_name_and_class(
                trestle_root, orig_ssp_name, ossp.SystemSecurityPlan
            )
            context = ControlContext.generate(ContextPurpose.SSP, True, trestle_root, md_path)
            context.comp_def_name_list = comma_sep_to_list(args.compdefs)
            part_id_map_by_id = catalog_interface.get_statement_part_id_map(False)
            catalog_interface.generate_control_rule_info(part_id_map_by_id, context)
            # load all original comp defs
            # only additions from markdown will be imp_req prose and status
            # and param vals
            # if this is a new ssp then create system component in the comp_dict
            comp_dict = SSPAssemble._build_comp_dict_from_comp_defs(
                trestle_root, context.comp_def_name_list, not orig_ssp_path
            )
            part_id_map_by_label = catalog_interface.get_statement_part_id_map(True)
            # if ssp already exists use it as container for new content
            if orig_ssp_path:
                # load the existing json ssp
                _, _, ssp = ModelUtils.load_distributed(orig_ssp_path, trestle_root)
                # add the This System comp to the comp dict so its uuid is known
                sys_comp = SSPAssemble._get_this_system_as_gen_comp(ssp)
                if not sys_comp:
                    raise TrestleError('Original ssp has no system component.')
                comp_dict[const.SSP_MAIN_COMP_NAME] = sys_comp
                ssp_sys_imp_comps = ssp.system_implementation.components
                # Gather the leveraged components to add back after the merge
                leveraged_comps: Dict[str, ossp.SystemComponent] = {}
                for sys_comp in ssp_sys_imp_comps:
                    if sys_comp.props is not None:
                        prop_names = [x.name for x in sys_comp.props]
                        if const.LEV_AUTH_UUID in prop_names:
                            leveraged_comps[sys_comp.title] = sys_comp
                # Verifies older compdefs in an ssp no longer exist in newly provided ones
                comp_titles = [x.title for x in comp_dict.values()]
                diffs = [x for x in ssp_sys_imp_comps if x.title not in comp_titles and x.title not in leveraged_comps]
                if diffs:
                    for diff in diffs:
                        logger.warning(
                            f'Component named: {diff.title} was removed from system components from ssp '
                            'because the corresponding component is not in '
                            'the specified compdefs '
                        )
                    index_list = [ssp_sys_imp_comps.index(value) for value in diffs if value in ssp_sys_imp_comps]
                    delete_list_from_list(ssp.system_implementation.components, index_list)
                self._merge_comp_defs(ssp, comp_dict, context, catalog_interface)
                CatalogReader.read_ssp_md_content(md_path, ssp, comp_dict, part_id_map_by_label, context)
                new_file_content_type = FileContentType.path_to_content_type(orig_ssp_path)
                # Add the leveraged comps back to the final ssp
                ssp.system_implementation.components.extend(list(leveraged_comps.values()))
            else:
                # create a sample ssp to hold all the parts
                ssp = gens.generate_sample_model(ossp.SystemSecurityPlan)
                ssp.control_implementation.implemented_requirements = []
                ssp.control_implementation.description = const.SSP_SYSTEM_CONTROL_IMPLEMENTATION_TEXT
                ssp.system_implementation.components = []
                self._merge_comp_defs(ssp, comp_dict, context, catalog_interface)
                CatalogReader.read_ssp_md_content(md_path, ssp, comp_dict, part_id_map_by_label, context)
                import_profile: ossp.ImportProfile = gens.generate_sample_model(ossp.ImportProfile)
                import_profile.href = const.REPLACE_ME
                ssp.import_profile = import_profile
            # now that we know the complete list of needed components, add them to the sys_imp
            # TODO if the ssp already existed then components may need to be removed if not ref'd by imp_reqs
            self._generate_roles_in_metadata(ssp)
            # If this is a leveraging SSP, update it with the retrieved exports from the leveraged SSP
            inheritance_markdown_path = md_path.joinpath(const.INHERITANCE_VIEW_DIR)
            if os.path.exists(inheritance_markdown_path):
                SSPInheritanceAPI(inheritance_markdown_path, trestle_root).update_ssp_inheritance(ssp)
            ssp.import_profile.href = profile_href
            if args.version:
                ssp.metadata.version = args.version
            if ModelUtils.models_are_equivalent(existing_ssp, ssp):
                logger.info('No changes to assembled ssp so ssp not written out.')
                return CmdReturnCodes.SUCCESS.value
            if args.regenerate:
                ssp, _, _ = ModelUtils.regenerate_uuids(ssp)
            ModelUtils.update_last_modified(ssp)
            # validate model rules before saving
            args_validate = argparse.Namespace(mode=const.VAL_MODE_RULES)
            validator: Validator = validator_factory.get(args_validate)
            if not validator.model_is_valid(ssp, True, trestle_root):
                logger.error(
                    'Validation of file to be imported did not pass. Rule parameter values validation failed, '
                    'please check values are correct for shared parameters in current model'
                )
                return CmdReturnCodes.COMMAND_ERROR.value
            # write out the ssp as json
            ModelUtils.save_top_level_model(ssp, trestle_root, new_ssp_name, new_file_content_type)
            return CmdReturnCodes.SUCCESS.value
        except Exception as e:  # pragma: no cover
            return handle_generic_command_exception(e, logger, 'Error while assembling SSP')
 |