class DataPmAssessmentItems(): TIME_TO_LIVE_DATE = date_utils.get_current_date() + timedelta(days=180) TIME_TO_LIVE = Decimal(TIME_TO_LIVE_DATE.timestamp()) DATE_NOW = common_utils.get_current_date() ORGANIZATION_ID = copy.deepcopy( DataCommon.ORGANIZATION_ID_TEST.format(str(3))) PROJECT_ID = copy.deepcopy(DataCommon.PROJECT_ID.format(str(3))) USER_ID = copy.deepcopy(DataCommon.USER_ID_TEST.format(str(3))) ACCOUNT_REFINE_CODE_TEMPLATE = "{0}_{1}_{2}" AWS_ACCOUNT = copy.deepcopy(DataCommon.AWS_ACCOUNT) CHECK_CIS12_ITEM_4_04 = "CHECK_CIS12_ITEM_4_04" ACCOUNT_REFINE_CODE = ACCOUNT_REFINE_CODE_TEMPLATE.format( ORGANIZATION_ID, PROJECT_ID, AWS_ACCOUNT) ASSESSMENTITEM_ID_TEMPLATE = "{0}_{1}_{2}_{3}" ASSESSMENT_ITEM_ID = ASSESSMENTITEM_ID_TEMPLATE.format( ORGANIZATION_ID, PROJECT_ID, AWS_ACCOUNT, CHECK_CIS12_ITEM_4_04) DATA_SIMPLE = { "AccountRefineCode": ACCOUNT_REFINE_CODE, "AssessmentComment": "20190416145500に確認しました", "AssessmentItemID": ASSESSMENT_ITEM_ID, "AWSAccount": AWS_ACCOUNT, "CheckItemCode": CHECK_CIS12_ITEM_4_04, "CreatedAt": DATE_NOW, "MailAddress": "*****@*****.**", "OrganizationID": ORGANIZATION_ID, "ProjectID": PROJECT_ID, 'TimeToLive': TIME_TO_LIVE, "UpdatedAt": DATE_NOW, "UserID": USER_ID }
class DataPmExclusionItems(): TIME_TO_LIVE_DATE = date_utils.get_current_date() + timedelta(days=180) TIME_TO_LIVE = Decimal(TIME_TO_LIVE_DATE.timestamp()) DATE_NOW = common_utils.get_current_date() ORGANIZATION_ID = copy.deepcopy( DataCommon.ORGANIZATION_ID_TEST.format(str(3))) PROJECT_ID = copy.deepcopy(DataCommon.PROJECT_ID.format(str(3))) USER_ID = copy.deepcopy(DataCommon.USER_ID_TEST.format(str(3))) ACCOUNT_REFINE_CODE_TEMPLATE = "{0}_{1}_{2}" AWS_ACCOUNT = copy.deepcopy(DataCommon.AWS_ACCOUNT) CHECK_CIS12_ITEM_1_02 = "CHECK_CIS12_ITEM_1_02" ACCOUNT_REFINE_CODE = ACCOUNT_REFINE_CODE_TEMPLATE.format( ORGANIZATION_ID, PROJECT_ID, AWS_ACCOUNT) EXCLUSIONITEM_ID_TEMPLATE = "{0}_{1}_{2}_{3}" EXCLUSIONITEM_ID = EXCLUSIONITEM_ID_TEMPLATE.format( ORGANIZATION_ID, PROJECT_ID, AWS_ACCOUNT, CHECK_CIS12_ITEM_1_02) DATA_SIMPLE = { "AccountRefineCode": ACCOUNT_REFINE_CODE, "AWSAccount": AWS_ACCOUNT, "CheckItemCode": CHECK_CIS12_ITEM_1_02, "CreatedAt": DATE_NOW, "ExclusionComment": "テストコメントです", "ExclusionItemID": EXCLUSIONITEM_ID, "MailAddress": "*****@*****.**", "OrganizationID": ORGANIZATION_ID, "ProjectID": PROJECT_ID, "TimeToLive": TIME_TO_LIVE, "UpdatedAt": DATE_NOW, "UserID": USER_ID }
import copy from premembers.common import common_utils from tests.mock.data.aws.dynamodb.data_common import DataCommon from decimal import Decimal from datetime import timedelta from premembers.common import date_utils user_id = copy.deepcopy(DataCommon.USER_ID_TEST.format(str(3))) time_to_live_date = date_utils.get_current_date() + timedelta(days=180) time_to_live = Decimal(time_to_live_date.timestamp()) class DataPmEmailChangeApply(): APPLY_ID = "eb3b5f76-8945-11e7-b15a-8f7e5433dada-{}" BEFORE_MAIL_ADDRESS = "*****@*****.**" AFTER_MAIL_ADDRESS = "*****@*****.**" DATA_CALLER_SERVICE_NAME_INSIGHTWATCH = { "ApplyID": APPLY_ID.format(str(3)), "UserID": user_id, "BeforeMailAddress": BEFORE_MAIL_ADDRESS, "AfterMailAddress": AFTER_MAIL_ADDRESS, "TimeToLive": time_to_live, "CreatedAt": common_utils.get_current_date(), "UpdatedAt": common_utils.get_current_date(), "CallerServiceName": "insightwatch" } DATA_CALLER_SERVICE_NAME_OPSWITCH = { "ApplyID": APPLY_ID.format(str(3)), "UserID": user_id,
class DataPmExclusionResources(): TIME_TO_LIVE_DATE = date_utils.get_current_date() + timedelta(days=180) TIME_TO_LIVE = Decimal(TIME_TO_LIVE_DATE.timestamp()) DATE_NOW = common_utils.get_current_date() ORGANIZATION_ID = copy.deepcopy( DataCommon.ORGANIZATION_ID_TEST.format(str(3))) PROJECT_ID = copy.deepcopy(DataCommon.PROJECT_ID.format(str(3))) USER_ID = copy.deepcopy(DataCommon.USER_ID_TEST.format(str(3))) EXCLUSION_COMMENT_UPDATE = "exclusion_comment_update" CHECK_ITEM_CODE_NOT_OBJECT_RESOURCE = "CHECK_CIS12_ITEM_1_07" CHECK_ITEM_REFINE_CODE_TEMPLATE = "{0}_{1}_{2}_{3}" ACCOUNT_REFINE_CODE_TEMPLATE = "{0}_{1}_{2}" AWS_ACCOUNT = copy.deepcopy(DataCommon.AWS_ACCOUNT) GROUP_FILTER = "CIS12" CHECK_CIS12_ITEM_1_21 = "CHECK_CIS12_ITEM_1_21" CHECK_CIS_ITEM_2_02 = "CHECK_CIS_ITEM_2_02" ACCOUNT_REFINE_CODE = ACCOUNT_REFINE_CODE_TEMPLATE.format( ORGANIZATION_ID, PROJECT_ID, AWS_ACCOUNT) CHECK_ITEM_REFINE_CODE_CIS = CHECK_ITEM_REFINE_CODE_TEMPLATE.format( ORGANIZATION_ID, PROJECT_ID, AWS_ACCOUNT, CHECK_CIS_ITEM_2_02) CHECK_ITEM_REFINE_CODE_CIS12 = CHECK_ITEM_REFINE_CODE_TEMPLATE.format( ORGANIZATION_ID, PROJECT_ID, AWS_ACCOUNT, CHECK_CIS12_ITEM_1_21) RESOURCE_TYPE_SECURITY_GROUPS = "SecurityGroups" RESOURCE_TYPE_GROUP_ID = "GroupId" RESOURCE_TYPE_USER = "******" RESOURCE_TYPE_ROLE = "role" RESOURCE_TYPE_GROUP = "group" RESOURCE_TYPE_INSTANCE_ID = "InstanceId" RESOURCE_TYPE_S3_BUCKET_NAME = "S3BucketName" RESOURCE_TYPE_CLOUD_TRAIL_NAME = "CloudTrailName" RESOURCE_TYPE_KEY_ID = "KeyId" RESOURCE_TYPE_VCP_ID = "VpcId" S3_BUCKET_NAME = "s3_bucket_name_test" CLOUD_TRAIL_NAME = "cloud_trail_name_test" KEY_ID = "key_id_test" DATA_SIMPLE = { 'ExclusionResourceID': "aa4fee9c-790f-478d-9f5d-7aeef688d54f", 'OrganizationID': ORGANIZATION_ID, 'ProjectID': PROJECT_ID, 'AWSAccount': "693642053048", 'CheckItemCode': CHECK_CIS12_ITEM_1_21, 'ResourceType': "resource_type", 'RegionName': "region_name", 'ResourceName': "resource_name", 'ExclusionComment': "exclusion_comment", 'UserID': USER_ID, 'MailAddress': "*****@*****.**", 'AccountRefineCode': ACCOUNT_REFINE_CODE, 'CheckItemRefineCode': CHECK_ITEM_REFINE_CODE_CIS12, 'TimeToLive': TIME_TO_LIVE, "CreatedAt": DATE_NOW, "UpdatedAt": DATE_NOW } DATA_EXCLUSION_RESOURCES = [{ "ExclusionResourceID": "555e9b62-00d8-4aef-b19c-51471401ffd1", "MailAddress": "*****@*****.**", "TimeToLive": 1580627834.190638, "AWSAccount": "216054658829", "ResourceName": "sg-ee5d9e87", "CreatedAt": "2019-08-06 07:17:18.110", "ProjectID": "2458d17c-8dff-4983-9a36-e9e964058fd7", "ResourceType": RESOURCE_TYPE_GROUP_ID, "OrganizationID": "3c9381d8-9267-47b8-83b9-4281250f8d96", "UpdatedAt": "2019-08-06 07:17:18.110", "AccountRefineCode": "3c9381d8-9267-47b8-83b9-4281250f8d96_2458d17c-8dff-4983-9a36-e9e964058fd7_216054658829", "RegionName": copy.deepcopy(data_common_aws.REGION_EU_NORTH_1), "UserID": "eb3b5f76-8945-11e7-b15a-8f7e5433dada", "CheckItemRefineCode": "d5823ac0-e7fd-4b54-8a46-981d6fe68412_2a59525e-96ee-4614-bcd3-ad0fbaf0e384_693642053048_CHECK_CIS12_ITEM_4_01", "CheckItemCode": "CHECK_CIS12_ITEM_4_01", "ExclusionComment": "test_exclusion_comment" }, { "ExclusionResourceID": "not_is_object_clusion_resources", "MailAddress": "*****@*****.**", "TimeToLive": 1580627834.190638, "AWSAccount": "216054658829", "ResourceName": "sg-ee5d9e87", "CreatedAt": "2019-08-06 07:17:18.110", "ProjectID": "2458d17c-8dff-4983-9a36-e9e964058fd7", "ResourceType": RESOURCE_TYPE_GROUP_ID, "OrganizationID": "3c9381d8-9267-47b8-83b9-4281250f8d96", "UpdatedAt": "2019-08-06 07:17:18.110", "AccountRefineCode": "3c9381d8-9267-47b8-83b9-4281250f8d96_2458d17c-8dff-4983-9a36-e9e964058fd7_216054658829", "RegionName": copy.deepcopy(data_common_aws.REGION_EU_NORTH_1), "UserID": "eb3b5f76-8945-11e7-b15a-8f7e5433dada", "CheckItemRefineCode": "d5823ac0-e7fd-4b54-8a46-981d6fe68412_2a59525e-96ee-4614-bcd3-ad0fbaf0e384_693642053048_CHECK_CIS12_ITEM_4_04", "CheckItemCode": "CHECK_CIS12_ITEM_4_04", "ExclusionComment": "test_exclusion_comment" }] EXCLUSION_RESOURCES_NOT_DELETE = { "ExclusionResourceID": "exclusionresourceid_not_delete", "AWSAccount": AWS_ACCOUNT, "AccountRefineCode": ACCOUNT_REFINE_CODE, "CheckItemCode": check_item_code, "CheckItemRefineCode": CHECK_ITEM_REFINE_CODE_CIS12, "CreatedAt": "2019-08-06 07:20:06.355", "ExclusionComment": "ExclusionComment", "MailAddress": "test-user{}@example.com", "OrganizationID": ORGANIZATION_ID, "ProjectID": PROJECT_ID, "RegionName": "RegionName_not_matching", "ResourceName": "ResourceName_not_matching", "ResourceType": "ResourceType_not_matching", "TimeToLive": "2019-08-06 07:20:06.355", "UpdatedAt": "2019-08-06 07:20:09.423", "UserID": user_id_authority_owner } DATA_EXCLUSION_RESOURCE_CHECK_ITEM_CODE_CIS = { 'ExclusionResourceID': "aa4fee9c-790f-478d-9f5d-7aeef688d54h", 'OrganizationID': ORGANIZATION_ID, 'ProjectID': PROJECT_ID, 'AWSAccount': "693642053048", 'CheckItemCode': CHECK_CIS_ITEM_2_02, 'RegionName': "region_name", 'ResourceName': "resource_name", 'ResourceType': "resource_type", 'ExclusionComment': "exclusion_comment", 'UserID': USER_ID, 'MailAddress': "*****@*****.**", 'AccountRefineCode': ACCOUNT_REFINE_CODE, 'CheckItemRefineCode': CHECK_ITEM_REFINE_CODE_CIS, 'TimeToLive': TIME_TO_LIVE, "CreatedAt": DATE_NOW, "UpdatedAt": DATE_NOW } LIST_CHECK_ITEM_CODE_EXCLUDED_RESOURCE = [ "CHECK_CIS12_ITEM_1_02", "CHECK_CIS12_ITEM_1_03", "CHECK_CIS12_ITEM_1_04", "CHECK_CIS12_ITEM_1_16", "CHECK_CIS12_ITEM_1_19", "CHECK_CIS12_ITEM_1_21", "CHECK_CIS12_ITEM_1_22", "CHECK_CIS12_ITEM_2_02", "CHECK_CIS12_ITEM_2_03", "CHECK_CIS12_ITEM_2_04", "CHECK_CIS12_ITEM_2_06", "CHECK_CIS12_ITEM_2_07", "CHECK_CIS12_ITEM_2_08", "CHECK_CIS12_ITEM_2_09", "CHECK_CIS12_ITEM_4_01", "CHECK_CIS12_ITEM_4_02", "CHECK_CIS12_ITEM_4_03" ]
def get_time_to_live(days): time_to_live_date = date_utils.get_current_date() + timedelta(days=days) return Decimal(time_to_live_date.timestamp())
def test_execute_force_invites_handler_success_case_exists_username_in_record_pm_user_attribute(self): ses_region = "us-west-2" mail_from = "*****@*****.**" mail_subject = "[insightwatch(DEV)]へ招待されました" temporary_password = "******" record_organization = { "Contract": 0, "ContractStatus": 1, "CreatedAt": "2019-05-17 06:32:31.728", "OrganizationID": "OrganizationID", "OrganizationName": "OrganizationName", "UpdatedAt": "2019-05-17 06:32:31.728" } template_body_mail = "{{mailAddress}} 様\n\n{{userName}} 様から insightwatch (https://insightwatch.io/) への招待がありました。\n\n下記のURLをクリックしてinsightwatchにアクセスいただき、記載されたログインIDおよび初期パスワードを入力してユーザー登録をお願いします。\nユーザー登録後に招待された組織 [{{organizationName}}] へ参加することができます。\n\nhttps://insightwatch.io/app/\n\nログインID:\n{{mailAddress}}\n\n初期パスワード:\n{{temporaryPassword}}\n\nこの招待は、 {{timeToLive}} まで有効です。\n有効期限を過ぎてしまった場合、ログインできません。\n招待者へ再度、招待を依頼してください。\n\n--\n本メールは送信専用メールアドレスから送信されています。返信はできませんのでご了承ください。\nお問い合わせは下記フォームからお送りください。\nhttps://insightwatch.zendesk.com/hc/ja/requests/new\n\nClassmethod, Inc.\nhttps://classmethod.jp/\n" bcc_addresses = [ regist_user_pool_body["mailAddress"] ] template_body_mail_object = Template(template_body_mail) user_name_sign_in = copy.deepcopy(DataPmUserAttribute.DATA_SIMPLE['UserName']) organization_name = record_organization['OrganizationName'] # get time to live time_zone = date_utils.get_time_zone_by_language( regist_user_pool_body['mailLang']) time_to_live_date = date_utils.get_current_date() + timedelta(days=6) time_to_live = date_utils.toString(time_to_live_date, date_utils.PATTERN_YYYYMMDD_SLASH, time_zone) context = { 'mailAddress': regist_user_pool_body["mailAddress"], 'userName': user_name_sign_in, 'organizationName': organization_name, 'temporaryPassword': temporary_password, 'timeToLive': time_to_live } body_mail = template_body_mail_object.render(context) # mock object patch_get_cognito_user_pools = patch("premembers.common.aws_common.get_cognito_user_pools") patch_process_admin_create_user_pools = patch("premembers.common.aws_common.process_admin_create_user_pools") patch_update_cognito_user_pools = patch("premembers.common.aws_common.update_cognito_user_attributes") patch_get_affiliation = patch("premembers.repository.pm_affiliation.get_affiliation") patch_get_organization = patch("premembers.repository.pm_organizations.get_organization") patch_create_affiliation = patch("premembers.repository.pm_affiliation.create_affiliation") patch_query_key_pm_user_attribute = patch('premembers.repository.pm_userAttribute.query_key') patch_read_yaml = patch("premembers.common.FileUtils.read_yaml") patch_read_decode = patch("premembers.common.FileUtils.read_decode") patch_send_email = patch("premembers.common.aws_common.send_email") patch_get_uuid4 = patch("premembers.common.common_utils.get_uuid4") patch_get_password_temporary = patch("premembers.common.common_utils.get_password_temporary") patch_date_utils_to_string = patch("premembers.common.date_utils.toString") # start mock object mock_get_cognito_user_pools = patch_get_cognito_user_pools.start() mock_process_admin_create_user_pools = patch_process_admin_create_user_pools.start() mock_update_cognito_user_pools = patch_update_cognito_user_pools.start() mock_get_affiliation = patch_get_affiliation.start() mock_get_organization = patch_get_organization.start() mock_create_affiliation = patch_create_affiliation.start() mock_query_key_pm_user_attribute = patch_query_key_pm_user_attribute.start() mock_read_yaml = patch_read_yaml.start() mock_read_decode = patch_read_decode.start() mock_send_email = patch_send_email.start() mock_get_uuid4 = patch_get_uuid4.start() mock_get_password_temporary = patch_get_password_temporary.start() mock_date_utils_to_string = patch_date_utils_to_string.start() # mock data mock_get_cognito_user_pools.return_value = [] mock_process_admin_create_user_pools.return_value = True mock_update_cognito_user_pools.side_effect = None mock_get_affiliation.side_effect = mock_side_effect_get_affiliation mock_get_uuid4.return_value = user_invite mock_get_organization.return_value = record_organization mock_create_affiliation.side_effect = None mock_query_key_pm_user_attribute.return_value = copy.deepcopy( DataPmUserAttribute.DATA_SIMPLE) mock_read_yaml.return_value = { "ses.region": ses_region, "ja.invite_mail.insightwatch.subject": mail_subject, "ja.invite_mail.insightwatch.body.text.filepath": "check/notify/mail/insightwatch_user_invite_template_ja.tpl", "en.invite_mail.insightwatch.subject": "You're Invited: insightwatch(DEV)", "en.invite_mail.insightwatch.body.text.filepath": "check/notify/mail/insightwatch_user_invite_template_en.tpl", "invite_mail.insightwatch.from": mail_from } mock_read_decode.return_value = template_body_mail mock_get_password_temporary.return_value = temporary_password mock_date_utils_to_string.return_value = time_to_live # addCleanup stop mock object self.addCleanup(patch_get_cognito_user_pools.stop) self.addCleanup(patch_process_admin_create_user_pools.stop) self.addCleanup(patch_update_cognito_user_pools.stop) self.addCleanup(patch_get_affiliation.stop) self.addCleanup(patch_get_organization.stop) self.addCleanup(patch_create_affiliation.stop) self.addCleanup(patch_query_key_pm_user_attribute.stop) self.addCleanup(patch_read_yaml.stop) self.addCleanup(patch_read_decode.stop) self.addCleanup(patch_send_email.stop) self.addCleanup(patch_get_password_temporary.stop) # call Function test response = organizations.execute_force_invites_handler( event_mock, {}) # assert output function # check call function send mail mock_send_email.assert_called_once_with( user_invite, ses_region, mail_from, bcc_addresses, mail_subject, body_mail) # check data respone status_code = response['statusCode'] response_body = json.loads(response['body']) self.assertEqual(status_code, HTTPStatus.CREATED) self.assertEqual(regist_user_pool_body['authority'], response_body['Authority']) self.assertEqual(regist_user_pool_body['mailAddress'], response_body['MailAddress']) self.assertEqual(organization_id, response_body['OrganizationID']) self.assertEqual(user_id_authority_owner, response_body['UserID'])
def execute_force_invites(trace_id, body_object, organization_id): pm_logger = common_utils.begin_logger(trace_id, __name__, inspect.currentframe()) # parse json try: body_object_json = json.loads(body_object) except Exception as e: return common_utils.error_exception(MsgConst.ERR_REQUEST_202, HTTPStatus.BAD_REQUEST, e, pm_logger, True) caller_service_name = common_utils.get_value("callerServiceName", body_object_json, None) mail_lang = common_utils.get_value("mailLang", body_object_json, None) mail_address = common_utils.get_value("mailAddress", body_object_json, None) authority = common_utils.get_value("authority", body_object_json, None) # validate param execute invite unregistered list_error = validate_param_invite_unregistered_user( trace_id, mail_lang, caller_service_name, mail_address, authority) if list_error: return common_utils.error_validate(MsgConst.ERR_REQUEST_201, HTTPStatus.UNPROCESSABLE_ENTITY, list_error, pm_logger) # get list cognito users try: list_users = aws_common.get_cognito_user_pools(trace_id, mail_address) except PmError as e: return common_utils.error_exception(MsgConst.ERR_COGNITO_501, HTTPStatus.INTERNAL_SERVER_ERROR, e, pm_logger, True) if list_users: return common_utils.error_common(MsgConst.ERR_302, HTTPStatus.CONFLICT, pm_logger) # regist Cognito UserPools temporary_password = '' pattern = re.compile(CommonConst.FORMAT_PASSWORD_TEMPORARY) while pattern.match(temporary_password) is None: temporary_password = common_utils.get_password_temporary( CommonConst.NUMBER_CHARACTERS_PASSWORD_TEMPORARY) user_attributes = [{"Name": "email", "Value": mail_address}] user_name = common_utils.get_uuid4() message_action = MessageAction.Suppress try: aws_common.process_admin_create_user_pools(trace_id, user_name, user_attributes, temporary_password, message_action) except PmError as e: return common_utils.error_exception(MsgConst.ERR_COGNITO_501, HTTPStatus.INTERNAL_SERVER_ERROR, e, pm_logger, True) # enable confirm email try: user_attributes = [{'Name': 'email_verified', 'Value': 'true'}] aws_common.update_cognito_user_attributes(trace_id, user_name, user_attributes) except PmError as e: return common_utils.error_exception(MsgConst.ERR_COGNITO_501, HTTPStatus.INTERNAL_SERVER_ERROR, e, pm_logger, True) # get affiliation try: affiliation = pm_affiliation.get_affiliation(user_name, organization_id) except PmError as e: return common_utils.error_exception(MsgConst.ERR_402, HTTPStatus.INTERNAL_SERVER_ERROR, e, pm_logger, True) if affiliation and affiliation["InvitationStatus"] != InvitationStatus.Deny: return common_utils.error_common(MsgConst.ERR_302, HTTPStatus.CONFLICT, pm_logger) # get organization try: organization = pm_organizations.get_organization( trace_id, organization_id) except PmError as e: return common_utils.error_exception(MsgConst.ERR_402, HTTPStatus.INTERNAL_SERVER_ERROR, e, pm_logger, True) if len(organization) == 0: return common_utils.error_common(MsgConst.ERR_301, HTTPStatus.NOT_FOUND, pm_logger) # create affiliation try: pm_affiliation.create_affiliation(trace_id, mail_address, user_name, organization_id, authority, InvitationStatus.Invited) except PmError as e: return common_utils.error_exception(MsgConst.ERR_DB_403, HTTPStatus.INTERNAL_SERVER_ERROR, e, pm_logger, True) # Get data affiliation try: affiliation_result = pm_affiliation.get_affiliation( user_name, organization_id, True) except PmError as e: return common_utils.error_exception(MsgConst.ERR_402, HTTPStatus.INTERNAL_SERVER_ERROR, e, pm_logger, True) # Get data user_attribute try: user_attribute = pm_userAttribute.query_key(trace_id) except PmError as e: return common_utils.error_exception(MsgConst.ERR_402, HTTPStatus.INTERNAL_SERVER_ERROR, e, pm_logger, True) # S3から通知メール送信設定ファイルを取得します。 try: config = FileUtils.read_yaml(trace_id, CommonConst.S3_SETTING_BUCKET, CommonConst.NOTIFY_CONFIG_CIS_RESULT_MAIL) except PmError as e: pm_logger.error("メール送信設定ファイルの取得に失敗しました。:s3://{0}/{1}".format( common_utils.get_environ(CommonConst.S3_SETTING_BUCKET), CommonConst.NOTIFY_CONFIG_CIS_RESULT_MAIL)) return common_utils.error_exception(MsgConst.ERR_S3_702, HTTPStatus.INTERNAL_SERVER_ERROR, e, pm_logger, True) # メッセージ本文を作成します。 path_file_template = config[ CommonConst.KEY_GET_PATH_FILE_TEMPLATE_USER_INVITE_MAIL.format( language=mail_lang, serviceName=caller_service_name)] try: template_body_mail = FileUtils.read_decode( trace_id, CommonConst.S3_SETTING_BUCKET, path_file_template) except PmError as e: pm_logger.error("招待メール本文テンプレートファイルの取得に失敗しました。:s3://{0}/{1}".format( common_utils.get_environ(CommonConst.S3_SETTING_BUCKET), path_file_template)) return common_utils.error_exception(MsgConst.ERR_S3_702, HTTPStatus.INTERNAL_SERVER_ERROR, e, pm_logger, True) # SESで通知メールを送信します。 bcc_addresses = [mail_address] user_name_sign_in = common_utils.get_value("UserName", user_attribute, None) if not user_name_sign_in: try: affiliation_sign_in = pm_affiliation.get_affiliation( trace_id, organization_id) except PmError as e: return common_utils.error_exception( MsgConst.ERR_402, HTTPStatus.INTERNAL_SERVER_ERROR, e, pm_logger, True) user_name_sign_in = common_utils.get_value("MailAddress", affiliation_sign_in, None) organization_name = common_utils.get_value("OrganizationName", organization, None) time_zone = date_utils.get_time_zone_by_language(mail_lang) time_to_live_date = date_utils.get_current_date() + timedelta(days=6) time_to_live = date_utils.toString(time_to_live_date, date_utils.PATTERN_YYYYMMDD_SLASH, time_zone) template_body_mail = Template(template_body_mail) context = { 'mailAddress': mail_address, 'userName': user_name_sign_in, 'organizationName': organization_name, 'temporaryPassword': temporary_password, 'timeToLive': time_to_live } body_mail = template_body_mail.render(context) mail_subject = config[CommonConst.KEY_MAIL_SUBJECT_USER_INVITE.format( language=mail_lang, serviceName=caller_service_name)] mail_from = config[CommonConst.KEY_INVITE_MAIL_FROM_SERVICE.format( serviceName=caller_service_name)] ses_region = config['ses.region'] try: aws_common.send_email(user_name, ses_region, mail_from, bcc_addresses, mail_subject, body_mail) except PmError as e: pm_logger.error("通知メール送信に失敗しました。") return common_utils.error_exception(MsgConst.ERR_SES_801, HTTPStatus.INTERNAL_SERVER_ERROR, e, pm_logger, True) response = common_utils.get_response_by_response_body( HTTPStatus.CREATED, affiliation_result) # return data response return common_utils.response(response, pm_logger)
def create_excluesion_item(trace_id, user_id, organization_id, project_id, email, check_item_code, coop_id, data_body): pm_logger = common_utils.begin_logger(trace_id, __name__, inspect.currentframe()) # リソース関連性のバリデーションチェックを行います。 try: awscoop_item = pm_awsAccountCoops.query_awscoop_coop_key( trace_id, coop_id) except Exception as err: return common_utils.error_exception(MsgConst.ERR_402, HTTPStatus.INTERNAL_SERVER_ERROR, err, pm_logger, True) if not awscoop_item: return common_utils.error_common(MsgConst.ERR_AWS_401, HTTPStatus.UNPROCESSABLE_ENTITY, pm_logger) # リクエストボディのJSONでパースエラーが発生した場合は、エラーログを出力してエラーレスポンスを返します。 try: body_object = json.loads(data_body) exclusion_comment = body_object["exclusionComment"].strip() except Exception as err: return common_utils.error_exception(MsgConst.ERR_REQUEST_202, HTTPStatus.BAD_REQUEST, err, pm_logger, True) # 全てのチェックを行い、エラーがあった場合はエラーログを出力してエラーレスポンスを返します。 list_error = validate_insert(exclusion_comment) if list_error: return common_utils.error_validate(MsgConst.ERR_REQUEST_201, HTTPStatus.UNPROCESSABLE_ENTITY, list_error, pm_logger) # チェック項目除外設定テーブルに除外設定レコードを作成します。 aws_account = awscoop_item['AWSAccount'] exclusion_item_id = CommonConst.EXCLUSIONITEM_ID.format( organization_id, project_id, aws_account, check_item_code) account_refine_code = CommonConst.ACCOUNT_REFINE_CODE.format( organization_id, project_id, aws_account) time_to_live_date = date_utils.get_current_date() + timedelta(days=180) time_to_live = Decimal(time_to_live_date.timestamp()) try: pm_exclusionitems.create(trace_id, exclusion_item_id, organization_id, project_id, aws_account, check_item_code, time_to_live, exclusion_comment, user_id, email, account_refine_code) except Exception as e: return common_utils.error_common(MsgConst.ERR_DB_403, HTTPStatus.INTERNAL_SERVER_ERROR, pm_logger) try: exclusion_item = pm_exclusionitems.query_key(trace_id, exclusion_item_id, True) except Exception as err: return common_utils.error_exception(MsgConst.ERR_402, HTTPStatus.INTERNAL_SERVER_ERROR, err, pm_logger, True) # return response data response = common_utils.get_response_by_response_body( HTTPStatus.CREATED, exclusion_item) return common_utils.response(response, pm_logger)
def create_excluded_resources(trace_id, user_id, organization_id, project_id, coop_id, check_item_code, email, data_body): pm_logger = common_utils.begin_logger(trace_id, __name__, inspect.currentframe()) # AWSアカウントAWSAccountは、AWSアカウント連携テーブルに、AWSアカウント連携ID{coop_id}をキーとしてクエリを実行します。 try: awscoops_item = pm_awsAccountCoops.query_awscoop_coop_key( trace_id, coop_id) except Exception as e: return common_utils.error_exception(MsgConst.ERR_402, HTTPStatus.INTERNAL_SERVER_ERROR, e, pm_logger, True) # 有効なAWSアカウントが存在しなかった場合(取得件数が0件) if (not awscoops_item): return common_utils.error_common(MsgConst.ERR_AWS_401, HTTPStatus.UNPROCESSABLE_ENTITY, pm_logger) # チェック項目コード if check_item_code not in LIST_CHECK_ITEM_CODE_EXCLUDED_RESOURCE: return common_utils.error_common(MsgConst.ERR_AWS_401, HTTPStatus.UNPROCESSABLE_ENTITY, pm_logger) # リクエストボディのJSONでパースエラーが発生した場合は、エラーログを出力してエラーレスポンスを返します。 try: body_object = json.loads(data_body) except Exception as e: return common_utils.error_exception(MsgConst.ERR_REQUEST_202, HTTPStatus.BAD_REQUEST, e, pm_logger, True) region_name = common_utils.get_value("regionName", body_object, None) resource_type = common_utils.get_value("resourceType", body_object, None) resource_name = common_utils.get_value("resourceName", body_object, None) exclusion_comment = common_utils.get_value("exclusionComment", body_object, None).strip() # 全てのチェックを行い、エラーがあった場合はエラーログを出力してエラーレスポンスを返します。 list_error = validate_create_excluded_resources(region_name, resource_type, resource_name, exclusion_comment) if list_error: return common_utils.error_validate(MsgConst.ERR_REQUEST_201, HTTPStatus.UNPROCESSABLE_ENTITY, list_error, pm_logger) aws_account = awscoops_item['AWSAccount'] check_item_refine_code = CommonConst.CHECK_ITEM_REFINE_CODE.format( organization_id, project_id, aws_account, check_item_code) try: excluded_resource = pm_exclusionResources.query_filter_region_name_and_resource_name( trace_id, check_item_refine_code, region_name, resource_type, resource_name) except Exception as e: return common_utils.error_exception(MsgConst.ERR_402, HTTPStatus.INTERNAL_SERVER_ERROR, e, pm_logger, True) if not excluded_resource: exclusion_resource_id = common_utils.get_uuid4() account_refine_code = CommonConst.ACCOUNT_REFINE_CODE.format( organization_id, project_id, aws_account) time_to_live_date = date_utils.get_current_date() + timedelta(days=180) time_to_live = Decimal(time_to_live_date.timestamp()) # リソース除外設定テーブルに除外設定レコードを作成します。 try: pm_exclusionResources.create( user_id, exclusion_resource_id, organization_id, project_id, aws_account, check_item_code, region_name, resource_type, resource_name, exclusion_comment, email, account_refine_code, check_item_refine_code, time_to_live) except Exception as e: return common_utils.error_exception( MsgConst.ERR_DB_403, HTTPStatus.INTERNAL_SERVER_ERROR, e, pm_logger, True) else: exclusion_resource_id = excluded_resource[0]["ExclusionResourceID"] attribute = {'ExclusionComment': {"Value": exclusion_comment}} try: pm_exclusionResources.update(trace_id, exclusion_resource_id, attribute) except Exception as e: return common_utils.error_exception( MsgConst.ERR_DB_404, HTTPStatus.INTERNAL_SERVER_ERROR, e, pm_logger, True) try: excluded_resource_new = pm_exclusionResources.query_key( trace_id, exclusion_resource_id, True) except Exception as e: return common_utils.error_exception(MsgConst.ERR_402, HTTPStatus.INTERNAL_SERVER_ERROR, e, pm_logger, True) # return response data response = common_utils.get_response_by_response_body( HTTPStatus.CREATED, excluded_resource_new) return common_utils.response(response, pm_logger)
def create_assessment_item(trace_id, user_id, organization_id, project_id, coop_id, check_item_code, email, data_body): pm_logger = common_utils.begin_logger(trace_id, __name__, inspect.currentframe()) # AWSアカウントAWSAccountは、AWSアカウント連携テーブルに、AWSアカウント連携ID{coop_id}をキーとしてクエリを実行します。 try: awscoops_item = pm_awsAccountCoops.query_awscoop_coop_key( trace_id, coop_id) except Exception as e: return common_utils.error_exception(MsgConst.ERR_402, HTTPStatus.INTERNAL_SERVER_ERROR, e, pm_logger, True) # 有効なAWSアカウントが存在しなかった場合(取得件数が0件) if (not awscoops_item): return common_utils.error_common(MsgConst.ERR_AWS_401, HTTPStatus.UNPROCESSABLE_ENTITY, pm_logger) # リクエストボディのJSONでパースエラーが発生した場合は、エラーログを出力してエラーレスポンスを返します。 try: body_object = json.loads(data_body) assessment_comment = body_object["assessmentComment"].strip() except Exception as e: return common_utils.error_exception(MsgConst.ERR_REQUEST_202, HTTPStatus.BAD_REQUEST, e, pm_logger, True) # 全てのチェックを行い、エラーがあった場合はエラーログを出力してエラーレスポンスを返します。 list_error = validate_insert_assessment(check_item_code, assessment_comment) if list_error: return common_utils.error_validate(MsgConst.ERR_REQUEST_201, HTTPStatus.UNPROCESSABLE_ENTITY, list_error, pm_logger) # 評価結果テーブルに評価レコードを作成します。 aws_account = awscoops_item['AWSAccount'] assessment_item_id = CommonConst.ASSESSMENTITEM_ID.format( organization_id, project_id, aws_account, check_item_code) account_refine_code = CommonConst.ACCOUNT_REFINE_CODE.format( organization_id, project_id, aws_account) time_to_live_date = date_utils.get_current_date() + timedelta(days=180) time_to_live = Decimal(time_to_live_date.timestamp()) try: pm_assessmentItems.create(trace_id, assessment_item_id, organization_id, project_id, aws_account, check_item_code, time_to_live, assessment_comment, user_id, email, account_refine_code) except Exception: return common_utils.error_common(MsgConst.ERR_DB_403, HTTPStatus.INTERNAL_SERVER_ERROR, pm_logger) try: assessment_item = pm_assessmentItems.query_key(trace_id, assessment_item_id, True) except Exception as e: return common_utils.error_exception(MsgConst.ERR_402, HTTPStatus.INTERNAL_SERVER_ERROR, e, pm_logger, True) # return response data response = common_utils.get_response_by_response_body( HTTPStatus.CREATED, assessment_item) return common_utils.response(response, pm_logger)