def validate_insert(organization_name, contract, contract_status): list_error = [] # 組織名 if common_utils.is_null(organization_name): list_error.append( common_utils.get_error_validate(MsgConst.ERR_VAL_101, "name", organization_name)) elif not common_utils.is_str(organization_name): list_error.append( common_utils.get_error_validate(MsgConst.ERR_VAL_202, "name", organization_name)) # 契約種別 if common_utils.is_null(contract): list_error.append( common_utils.get_error_validate(MsgConst.ERR_VAL_101, "contract", contract)) elif not common_utils.is_number(contract): list_error.append( common_utils.get_error_validate(MsgConst.ERR_VAL_201, "contract", contract)) # 契約状態 if common_utils.is_null(contract_status): list_error.append( common_utils.get_error_validate(MsgConst.ERR_VAL_101, "contractStatus", contract_status)) elif not common_utils.is_number(contract_status): list_error.append( common_utils.get_error_validate(MsgConst.ERR_VAL_201, "contractStatus", contract_status)) return list_error
def validate_param_apply_change_email(trace_id, mail_lang, caller_service_name, mail_address): list_errors = [] # validate language list_error_language = common_utils.validate_language(mail_lang, param_name="mailLang") if list_error_language: list_errors.extend(list_error_language) # validate callerServiceName if common_utils.is_null(caller_service_name): list_errors.append( common_utils.get_error_validate(MsgConst.ERR_VAL_101, "callerServiceName", caller_service_name)) elif caller_service_name not in LIST_SERVICE_NAME: params = [] params.append(', '.join(LIST_SERVICE_NAME)) list_errors.append( common_utils.get_error_validate(MsgConst.ERR_VAL_302, "callerServiceName", caller_service_name, params)) # validate mailAddress if common_utils.is_null(mail_address): list_errors.append( common_utils.get_error_validate(MsgConst.ERR_VAL_101, "mailAddress", mail_address)) return list_errors
def validate_excluded_resources(region_name, resource_type, resource_name, is_query_string=False): list_error = [] region_name_key = 'regionName' resource_name_key = 'resourceName' resource_type_key = 'resourceType' if is_query_string is True: region_name_key = 'region_name' resource_name_key = 'resource_name' resource_type_key = 'resource_type' # validate region_name if common_utils.is_null(region_name): list_error.append( common_utils.get_error_validate(MsgConst.ERR_VAL_101, region_name_key, region_name)) # validate resource_name if common_utils.is_null(resource_name): list_error.append( common_utils.get_error_validate(MsgConst.ERR_VAL_101, resource_name_key, resource_name)) # validate resource_type if common_utils.is_null(resource_type): list_error.append( common_utils.get_error_validate(MsgConst.ERR_VAL_101, resource_type_key, resource_type)) return list_error
def query_project_index(trace_id, project_id, user_id=None, filter_expression=None, convert_response=None): pm_logger = common_utils.begin_logger(trace_id, __name__, inspect.currentframe()) key_conditions = { 'ProjectID': { 'AttributeValueList': [project_id], 'ComparisonOperator': 'EQ' } } if common_utils.is_null(user_id) is False: key_conditions['UserID'] = { 'AttributeValueList': [user_id], 'ComparisonOperator': 'EQ' } result = DB_utils.query_index(trace_id, Tables.PM_SECURITY_CHECK_WEBHOOK, PROJECT_INDEX, key_conditions, filter_expression) if result and convert_response: result = common_utils.convert_list_response( trace_id, result, RESPONSE_SECURITY_CHECK_WEBHOOK) return common_utils.response(result, pm_logger)
def validate_notifymail(notify_code, users=None): list_error = [] # 通知コード if common_utils.is_null(notify_code): list_error.append( common_utils.get_error_validate(MsgConst.ERR_VAL_101, "notifyCode", notify_code)) elif notify_code not in LIST_NOTIFY_CODE: params = [] params.append(', '.join(LIST_NOTIFY_CODE)) list_error.append( common_utils.get_error_validate(MsgConst.ERR_VAL_302, "notifyCode", notify_code, params)) # 宛先ユーザ if users is not None: if not common_utils.is_list(users): list_error.append( common_utils.get_error_validate(MsgConst.ERR_VAL_204, "users", users)) elif len(users) == 0: list_error.append( common_utils.get_error_validate(MsgConst.ERR_VAL_101, "users", users)) return list_error
def create(trace_id, organization_id, notify_code, webhook_url, mentions, is_cw_logger=False): if (is_cw_logger): common_utils.begin_cw_logger(trace_id, __name__, inspect.currentframe()) else: common_utils.begin_logger(trace_id, __name__, inspect.currentframe()) if common_utils.is_null(mentions): mentions = None date_now = common_utils.get_current_date() org_notify_slack = { "OrganizationID": organization_id, "NotifyCode": notify_code, "WebhookURL": webhook_url, "Mentions": mentions, "CreatedAt": date_now, "UpdatedAt": date_now } DB_utils.create(trace_id, Tables.PM_ORG_NOTIFY_SLACK, org_notify_slack, is_cw_logger=is_cw_logger)
def convert_command_slack(mentions): if common_utils.is_null(mentions): return CommonConst.BLANK mentions_command = re.sub(r'\@(channel|group|here|everyone)', convert_mentions, str(mentions)) + CommonConst.NEW_LINE return mentions_command
def get_data_json_by_key(key, json): result = None if common_utils.check_key( key, json) and common_utils.is_null(json[key]) is False: if (common_utils.is_number(json[key])): result = str(json[key]) else: result = json[key] return result
def get_security_check_detail(trace_id, check_history_id, group_filter=None): pm_logger = common_utils.begin_logger(trace_id, __name__, inspect.currentframe()) if common_utils.is_null(group_filter) is True: filter = Attr('CheckResult').gte(1) else: filter = Attr('CheckResult').gte(1).__and__( Attr('CheckItemCode').begins_with(group_filter)) results = query_check_history_index(trace_id, check_history_id, filter_expression=filter) return common_utils.response(results, pm_logger)
def validate_report(trace_id, report_name, aws_accounts, output_file_type): pm_logger = common_utils.begin_logger(trace_id, __name__, inspect.currentframe()) list_error = [] # レポート名 if common_utils.is_null(report_name): list_error.append( common_utils.get_error_validate(MsgConst.ERR_VAL_101, "name", report_name)) elif not common_utils.is_str(report_name): list_error.append( common_utils.get_error_validate(MsgConst.ERR_VAL_202, "name", report_name)) # AWSアカウントID if not common_utils.is_list(aws_accounts): list_error.append( common_utils.get_error_validate(MsgConst.ERR_VAL_204, "awsAccounts", aws_accounts)) elif len(aws_accounts) == 0: list_error.append( common_utils.get_error_validate(MsgConst.ERR_VAL_101, "awsAccounts", aws_accounts)) # レポート出力するファイル形式 if common_utils.is_null(output_file_type): list_error.append( common_utils.get_error_validate(MsgConst.ERR_VAL_101, "outputFileType", output_file_type)) elif output_file_type not in LIST_TYPE: params = [] params.append(', '.join(LIST_TYPE)) list_error.append( common_utils.get_error_validate(MsgConst.ERR_VAL_302, "outputFileType", output_file_type, params)) return common_utils.response(list_error, pm_logger)
def validate_update(organization_name): list_error = [] # 組織名 if common_utils.is_null(organization_name): list_error.append( common_utils.get_error_validate(MsgConst.ERR_VAL_101, "name", organization_name)) elif not common_utils.is_str(organization_name): list_error.append( common_utils.get_error_validate(MsgConst.ERR_VAL_202, "name", organization_name)) return list_error
def validate_project(trace_id, project_name): pm_logger = common_utils.begin_logger(trace_id, __name__, inspect.currentframe()) list_error = [] if common_utils.is_null(project_name): list_error.append( common_utils.get_error_validate(MsgConst.ERR_VAL_101, "name", project_name)) elif not common_utils.is_str(project_name): list_error.append( common_utils.get_error_validate(MsgConst.ERR_VAL_202, "name", project_name)) return common_utils.response(list_error, pm_logger)
def validate_params_invite(trace_id, mail_address, authority): list_error = [] if common_utils.is_null(mail_address): list_error.append( common_utils.get_error_validate(MsgConst.ERR_VAL_101, "mail_address", mail_address)) if common_utils.validate_authority(trace_id, authority): list_error.append( common_utils.get_error_validate(MsgConst.ERR_VAL_101, "authority", authority)) return list_error
def validate_param_invite_unregistered_user(trace_id, mail_lang, caller_service_name, mail_address, authority): list_error = [] # validate mailLang list_error_language = common_utils.validate_language(mail_lang, param_name="mailLang") if list_error_language: list_error.extend(list_error_language) # validate callerServiceName if common_utils.is_null(caller_service_name): list_error.append( common_utils.get_error_validate(MsgConst.ERR_VAL_101, "callerServiceName", caller_service_name)) elif caller_service_name not in LIST_SERVICE_NAME: params = [] params.append(', '.join(LIST_SERVICE_NAME)) list_error.append( common_utils.get_error_validate(MsgConst.ERR_VAL_302, "callerServiceName", caller_service_name, params)) # validate mailAddress if common_utils.is_null(mail_address): list_error.append( common_utils.get_error_validate(MsgConst.ERR_VAL_101, "mailAddress", mail_address)) # validate authority list_error_authority = common_utils.validate_authority(trace_id, authority) if list_error_authority: list_error.extend(list_error_authority) return list_error
def query_users_organization_index(trace_id, organization_id, invite_status=None, convert_response=None): pm_logger = common_utils.begin_logger(trace_id, __name__, inspect.currentframe()) if common_utils.is_null(invite_status): users = query_organization_index(trace_id, organization_id, convert_response=convert_response) else: filter = Attr('InvitationStatus').eq(int(invite_status)) users = query_organization_index(trace_id, organization_id, filter, convert_response) return common_utils.response(users, pm_logger)
def validate_update_awscoop(aws_account, role_name): list_error = [] # AWSアカウントID if common_utils.is_null(aws_account): list_error.append( common_utils.get_error_validate(MsgConst.ERR_VAL_101, "awsAccount", aws_account)) elif not common_utils.is_str(aws_account): list_error.append( common_utils.get_error_validate(MsgConst.ERR_VAL_202, "awsAccount", aws_account)) # ロール名 if common_utils.is_null(role_name): list_error.append( common_utils.get_error_validate(MsgConst.ERR_VAL_101, "roleName", role_name)) elif not common_utils.is_str(role_name): list_error.append( common_utils.get_error_validate(MsgConst.ERR_VAL_202, "roleName", role_name)) return list_error
def validate_output_report(trace_id, file_type): pm_logger = common_utils.begin_logger(trace_id, __name__, inspect.currentframe()) list_error = [] # レポート出力するファイル形式 if common_utils.is_null(file_type): list_error.append( common_utils.get_error_validate(MsgConst.ERR_VAL_101, "fileType", file_type)) elif file_type not in LIST_TYPE: params = [] params.append(', '.join(LIST_TYPE)) list_error.append( common_utils.get_error_validate(MsgConst.ERR_VAL_302, "fileType", file_type, params)) return common_utils.response(list_error, pm_logger)
def create_project(trace_id, organization_id, data_body): # Get logging pm_logger = common_utils.begin_logger(trace_id, __name__, inspect.currentframe()) # Parse JSON try: body_object = json.loads(data_body) project_name = body_object["name"] description = body_object["description"] except Exception as e: return common_utils.error_exception(MsgConst.ERR_REQUEST_202, HTTPStatus.BAD_REQUEST, e, pm_logger, True) # Validate list_error = validate_project(trace_id, project_name) if list_error: return common_utils.error_validate(MsgConst.ERR_REQUEST_201, HTTPStatus.UNPROCESSABLE_ENTITY, list_error, pm_logger) # Create Project project_id = str(uuid.uuid4()) if common_utils.is_null(description): description = None try: pm_projects.create_projects(trace_id, project_id, project_name, description, organization_id) except PmError as e: return common_utils.error_exception(MsgConst.ERR_DB_403, HTTPStatus.INTERNAL_SERVER_ERROR, e, pm_logger, True) try: project_item = pm_projects.get_projects(trace_id, project_id, convert_response=True) except PmError as e: return common_utils.error_exception(MsgConst.ERR_402, HTTPStatus.INTERNAL_SERVER_ERROR, e, pm_logger, True) # return data response response = common_utils.get_response_by_response_body( HTTPStatus.CREATED, project_item[0]) return common_utils.response(response, pm_logger)
def query_filter_account_refine_code(trace_id, account_refine_code, group_filter=None): pm_logger = common_utils.begin_logger(trace_id, __name__, inspect.currentframe()) key_conditions = { 'AccountRefineCode': { 'AttributeValueList': [account_refine_code], 'ComparisonOperator': 'EQ' } } if common_utils.is_null(group_filter) is False: key_conditions['CheckItemCode'] = { 'AttributeValueList': [CommonConst.GROUP_FILTER_TEMPLATE.format(group_filter)], 'ComparisonOperator': 'BEGINS_WITH' } result = DB_utils.query_index(trace_id, Tables.PM_ASSESSMENT_ITEMS, ACCOUNT_REFINE_INDEX, key_conditions, None) return common_utils.response(result, pm_logger)
def get_list_users(trace_id, organization_id, invite_status): pm_logger = common_utils.begin_logger(trace_id, __name__, inspect.currentframe()) # Validate if not common_utils.is_null(invite_status): list_error = common_utils.validate_invite_status( trace_id, invite_status) if list_error: return common_utils.error_validate(MsgConst.ERR_REQUEST_201, HTTPStatus.UNPROCESSABLE_ENTITY, list_error, pm_logger) try: users = pm_affiliation.query_users_organization_index( trace_id, organization_id, invite_status, convert_response=True) except PmError as err: return common_utils.error_exception(MsgConst.ERR_402, HTTPStatus.INTERNAL_SERVER_ERROR, err, pm_logger, True) # response when do success response = common_utils.get_response_by_response_body(HTTPStatus.OK, users) return common_utils.response(response, pm_logger)
def validate_notifyslack(notify_code, webhook_url=None): list_error = [] # 通知コード if common_utils.is_null(notify_code): list_error.append( common_utils.get_error_validate(MsgConst.ERR_VAL_101, "notifyCode", notify_code)) elif notify_code not in LIST_NOTIFY_CODE: params = [] params.append(', '.join(LIST_NOTIFY_CODE)) list_error.append( common_utils.get_error_validate(MsgConst.ERR_VAL_302, "notifyCode", notify_code, params)) # webhookUrl if webhook_url is not None: if len(webhook_url) == 0: list_error.append( common_utils.get_error_validate(MsgConst.ERR_VAL_101, "webhookUrl", webhook_url)) return list_error
def update_project(trace_id, project_id, organization_id, data_body): # Get logging pm_logger = common_utils.begin_logger(trace_id, __name__, inspect.currentframe()) # Parse JSON try: body_object = json.loads(data_body) project_name = body_object["name"] description = body_object["description"] except Exception as e: return common_utils.error_exception(MsgConst.ERR_REQUEST_202, HTTPStatus.BAD_REQUEST, e, pm_logger, True) # Validate list_error = validate_project(trace_id, project_name) if list_error: return common_utils.error_validate(MsgConst.ERR_REQUEST_201, HTTPStatus.UNPROCESSABLE_ENTITY, list_error, pm_logger) # Get project try: project_item = pm_projects.get_projects_by_organization_id( trace_id, project_id, organization_id) except PmError as err: return common_utils.error_exception(MsgConst.ERR_402, HTTPStatus.INTERNAL_SERVER_ERROR, err, pm_logger, True) if not project_item: return common_utils.error_common(MsgConst.ERR_301, HTTPStatus.NOT_FOUND, pm_logger) # update project if common_utils.is_null(description): description = None attribute = { 'ProjectName': { "Value": project_name }, 'Description': { "Value": description } } updated_at = project_item[0]['UpdatedAt'] try: pm_projects.update_project(trace_id, project_id, attribute, updated_at) except PmError as err: return common_utils.error_exception(MsgConst.ERR_DB_404, HTTPStatus.INTERNAL_SERVER_ERROR, err, pm_logger, True) # Get data update try: project_result = pm_projects.get_projects(trace_id, project_id, convert_response=True) except PmError as err: return common_utils.error_exception(MsgConst.ERR_402, HTTPStatus.INTERNAL_SERVER_ERROR, err, pm_logger, True) response = common_utils.get_response_by_response_body( HTTPStatus.OK, project_result[0]) # return data response return common_utils.response(response, pm_logger)
def update_awscoop(trace_id, project_id, organization_id, coop_id, data_body): pm_logger = common_utils.begin_logger(trace_id, __name__, inspect.currentframe()) # Parse JSON try: body_object = json.loads(data_body) aws_account = body_object["awsAccount"] role_name = body_object["roleName"] description = body_object["description"] aws_account_name = body_object['awsAccountName'] except Exception as e: return common_utils.error_exception(MsgConst.ERR_REQUEST_202, HTTPStatus.BAD_REQUEST, e, pm_logger, True) # Validate list_error = validate_update_awscoop(aws_account, role_name) if list_error: return common_utils.error_validate(MsgConst.ERR_REQUEST_201, HTTPStatus.UNPROCESSABLE_ENTITY, list_error, pm_logger) # Get data AWSアカウント連携 try: awscoops_item = pm_awsAccountCoops.get_awscoops_update( trace_id, coop_id, project_id, organization_id) except PmError as e: return common_utils.error_exception(MsgConst.ERR_402, HTTPStatus.INTERNAL_SERVER_ERROR, e, pm_logger, True) # 組織情報を取得します。 if awscoops_item is None: return common_utils.error_common(MsgConst.ERR_301, HTTPStatus.NOT_FOUND, pm_logger) # ロールのアクセス確認 if common_utils.is_null(description): description = None if common_utils.is_null(aws_account_name): aws_account_name = None external_id = awscoops_item['ExternalID'] effective = Effective.Disable.value members = None if (checkaccess.check_access_to_aws(trace_id, aws_account, role_name, external_id)): effective = Effective.Enable.value # IAMクライアントを用いて、IAMロールcm-membersportalを取得します。 try: session = aws_common.create_session_client(trace_id, aws_account, role_name, external_id) members = IAMUtils.get_membership_aws_account( trace_id, session, aws_account) except PmError as e: common_utils.write_log_pm_error(e, pm_logger, exc_info=True) # update project attribute = { 'AWSAccount': { "Value": aws_account }, 'RoleName': { "Value": role_name }, 'Description': { "Value": description }, 'Effective': { "Value": effective }, 'AWSAccountName': { "Value": aws_account_name } } if (members is not None): attribute['Members'] = {"Value": members} updated_at = awscoops_item['UpdatedAt'] try: pm_awsAccountCoops.update_awscoops(trace_id, coop_id, attribute, updated_at) except PmError as e: return common_utils.error_exception(MsgConst.ERR_DB_403, HTTPStatus.INTERNAL_SERVER_ERROR, e, pm_logger, True) # Get data response try: awscoops_item = pm_awsAccountCoops.query_awscoop_coop_key( trace_id, coop_id, convert_response=True) except PmError as e: return common_utils.error_exception(MsgConst.ERR_402, HTTPStatus.INTERNAL_SERVER_ERROR, e, pm_logger, True) # return data response response = common_utils.get_response_by_response_body( HTTPStatus.OK, awscoops_item) return common_utils.response(response, pm_logger)
def aws_resource_aggregate(check_history_id, log_id): trace_id = check_history_id pm_logger = common_utils.begin_logger(trace_id, __name__, inspect.currentframe()) # バリデーションチェック if common_utils.is_null(check_history_id): pm_logger.error("チェック履歴IDが指定されていません。") raise PmError(message="AGG_SECURITY-001") # ログストリーム名取得 if common_utils.is_null(log_id) is False: try: awsResourceChecker_logic.update_log_stream_name_to_s3( trace_id, check_history_id, log_id) except PmError as e: common_utils.write_log_pm_error(e, pm_logger, exc_info=True) # チェック履歴情報の取得とステータス更新 pm_logger.info("-- チェック履歴情報取得処理開始 ----") try: check_history = pm_checkHistory.query_key(trace_id, check_history_id) except PmError as e: pm_logger.error("チェック履歴情報の取得に失敗しました。: CheckHistoryID=%s", check_history_id) raise common_utils.write_log_pm_error(e, pm_logger, "AGG_SECURITY-002") if (not check_history): pm_logger.error("チェック履歴情報がありません。: CheckHistoryID=%s", check_history_id) pm_error = PmError(message="AGG_SECURITY-002") raise pm_error pm_logger.info("-- チェック履歴情報取得処理終了 ----") # 取得したチェック履歴情報のステータスをチェックします。 pm_logger.info("-- チェック履歴情報ステータスチェック開始 ----") if (check_history['CheckStatus'] != CheckStatus.CheckCompleted): pm_logger.error( "チェック実行ステータスが一致しません。: CheckHistoryID=%s, CheckStatus=%s", check_history_id, check_history['CheckStatus']) pm_error = PmError(message="AGG_SECURITY-003") raise pm_error # チェック履歴情報のステータスを更新します。 attribute = {'CheckStatus': {"Value": CheckStatus.SummaryProgress}} try: pm_checkHistory.update(trace_id, check_history_id, attribute, check_history['UpdatedAt']) pm_logger.info("-- チェック履歴情報ステータスチェック終了 ----") except PmError as e: pm_logger.error("チェック履歴情報のステータス更新に失敗しました。: CheckHistoryID=%s", check_history_id) raise common_utils.write_log_pm_error(e, pm_logger, "AGG_SECURITY-004") # 個別チェック結果取得 pm_logger.info("-- 個別チェック結果取得開始 ----") try: list_check_result_items = pm_checkResultItems.query_check_history_index_fiter_ne_exclusion_flag( trace_id, check_history_id, ExclusionFlag.Enable) except PmError as e: pm_logger.error("個別チェック結果取得に失敗しました。: CheckHistoryID=%s", check_history_id) raise common_utils.write_log_pm_error(e, pm_logger, "AGG_SECURITY-005") if (not list_check_result_items): pm_logger.error("個別チェック結果がありません。: CheckHistoryID=%s", check_history_id) raise PmError(message="AGG_SECURITY-005") pm_logger.info("-- 個別チェック結果取得終了 ----") # 個別チェック結果集計 / チェック結果更新 pm_logger.info("-- 個別チェック結果集計開始 ----") list_check_result_items = sorted(list_check_result_items, key=itemgetter('CheckResultID')) check_result_id = list_check_result_items[0]['CheckResultID'] ok_count = critical_count = ng_count = managed_count = error_count = 0 count = 0 for check_result_item in list_check_result_items: count += 1 check_result = check_result_item['CheckResult'] if (check_result_item['CheckResultID'] == check_result_id): if check_result == CheckResult.Normal: ok_count += 1 elif check_result == CheckResult.MinorInadequacies: ng_count += 1 elif check_result == CheckResult.CriticalDefect: critical_count += 1 elif check_result == CheckResult.MembersManagement: managed_count += 1 elif check_result == CheckResult.Error: error_count += 1 else: update_check_results(trace_id, check_history_id, check_result_id, ok_count, critical_count, ng_count, managed_count, error_count) check_result_id = check_result_item['CheckResultID'] ok_count = critical_count = ng_count = managed_count = error_count = 0 if check_result == CheckResult.Normal: ok_count += 1 elif check_result == CheckResult.MinorInadequacies: ng_count += 1 elif check_result == CheckResult.CriticalDefect: critical_count += 1 elif check_result == CheckResult.MembersManagement: managed_count += 1 elif check_result == CheckResult.Error: error_count += 1 # update data PM_CheckResults if (count == len(list_check_result_items)): update_check_results(trace_id, check_history_id, check_result_id, ok_count, critical_count, ng_count, managed_count, error_count) pm_logger.info("-- 個別チェック結果集計終了 ----") # 最新チェック結果作成 pm_logger.info("-- 最新チェック結果作成開始 ----") organization_id = check_history['OrganizationID'] project_id = check_history['ProjectID'] try: pm_latestCheckResult.create(trace_id, organization_id, project_id, check_history_id) except PmError as e: pm_logger.error("最新チェック結果テーブルのレコード作成に失敗しました。: CheckHistoryID=%s", check_history_id) raise common_utils.write_log_pm_error(e, pm_logger, "AGG_SECURITY-007")
def get_security_check_detail(trace_id, organization_id, project_id, check_history_id=None, group_filter=None): pm_logger = common_utils.begin_logger(trace_id, __name__, inspect.currentframe()) # リソース関連性のバリデーションチェックを行います。 try: project = pm_projects.get_projects_by_organization_id( trace_id, project_id, organization_id) except PmError as e: return common_utils.error_exception(MsgConst.ERR_402, HTTPStatus.INTERNAL_SERVER_ERROR, e, pm_logger, True) if (not project): return common_utils.error_common( MsgConst.ERR_AWS_401, HTTPStatus.UNPROCESSABLE_ENTITY, pm_logger) # 最新チェック結果のチェック履歴ID CheckHistoryIDを取得します。 if check_history_id is None: try: lastest_check_result = pm_latestCheckResult.query_key( trace_id, project_id, organization_id) except PmError as e: return common_utils.error_exception( MsgConst.ERR_402, HTTPStatus.INTERNAL_SERVER_ERROR, e, pm_logger, True) if (not lastest_check_result): response = common_utils.get_response_by_response_body( HTTPStatus.OK, []) return common_utils.response(response, pm_logger) check_history_id = lastest_check_result["CheckHistoryID"] else: try: lastest_check_result = pm_latestCheckResult.query_key_by_check_history_id( trace_id, project_id, organization_id, check_history_id) except PmError as e: return common_utils.error_exception( MsgConst.ERR_402, HTTPStatus.INTERNAL_SERVER_ERROR, e, pm_logger, True) if (not lastest_check_result): return common_utils.error_common(MsgConst.ERR_301, HTTPStatus.NOT_FOUND, pm_logger) # チェック結果詳細情報を取得します。 try: if common_utils.is_null(group_filter) is True: check_result_items = pm_checkResultItems.get_security_check_detail( trace_id, check_history_id) else: check_result_items = pm_checkResultItems.get_security_check_detail( trace_id, check_history_id, CommonConst.GROUP_FILTER_TEMPLATE.format(group_filter)) except PmError as e: return common_utils.error_exception(MsgConst.ERR_402, HTTPStatus.INTERNAL_SERVER_ERROR, e, pm_logger, True) if (not check_result_items): response = common_utils.get_response_by_response_body( HTTPStatus.OK, []) return common_utils.response(response, pm_logger) # 個別チェック結果レコードに対して、各チェック結果に作成されたチェック結果ファイルを取得する。 response_body = [] for check_result_item in check_result_items: try: data = FileUtils.read_json(trace_id, "S3_CHECK_BUCKET", check_result_item["ResultJsonPath"]) except PmError as e: if e.cause_error.response['Error'][ 'Code'] == CommonConst.NO_SUCH_KEY: return common_utils.error_exception( MsgConst.ERR_S3_702, HTTPStatus.INTERNAL_SERVER_ERROR, e, pm_logger, True) else: return common_utils.error_exception( MsgConst.ERR_S3_709, HTTPStatus.INTERNAL_SERVER_ERROR, e, pm_logger, True) response_body.append(get_response_body(check_result_item, data)) # return response data response = common_utils.get_response_by_response_body( HTTPStatus.OK, response_body) return common_utils.response(response, pm_logger)
def execute_change_email(apply_id): pm_logger = common_utils.begin_logger(apply_id, __name__, inspect.currentframe()) # バリデーションチェックを行います if common_utils.is_null(apply_id): return common_utils.error_common(MsgConst.ERR_201, HTTPStatus.UNPROCESSABLE_ENTITY, pm_logger) # set default value caller_service_name = 'insightwatch' # S3から通知メール送信設定ファイルを取得します。 try: config = FileUtils.read_yaml(apply_id, CommonConst.S3_SETTING_BUCKET, CommonConst.NOTIFY_CONFIG_CIS_RESULT_MAIL) except PmError as e: pm_logger.error( "メールアドレス変更通知メール送信設定ファイルの取得に失敗しました。:s3://%s/%s", common_utils.get_environ(CommonConst.S3_SETTING_BUCKET), CommonConst.NOTIFY_CONFIG_CIS_RESULT_MAIL) common_utils.error_exception(MsgConst.ERR_S3_702, HTTPStatus.INTERNAL_SERVER_ERROR, e, pm_logger, True) return common_utils.get_response_by_response_body( HTTPStatus.OK, CommonConst.DEFAULT_RESPONSE_ERROR_PAGE[caller_service_name], is_response_json=False, content_type=CommonConst.CONTENT_TYPE_TEXT_HTML) # set data response error page default response_error_page = config[CommonConst.KEY_RESPONSE_ERROR_PAGE.format( serviceName=caller_service_name)] # メールアドレス変更申請テーブルから申請レコードを取得します。 try: email_change_apply_info = pm_emailChangeApply.query_key( apply_id, apply_id, None) except PmError: pm_logger.error("メールアドレス変更申請テーブルでレコード取得に失敗しました。変更申請ID: %s", apply_id) return common_utils.get_response_by_response_body( HTTPStatus.OK, response_error_page, is_response_json=False, content_type=CommonConst.CONTENT_TYPE_TEXT_HTML) if not email_change_apply_info: pm_logger.warning("メールアドレス変更申請テーブルでレコードが存在しませんでした。変更申請ID: %s", apply_id) return common_utils.get_response_by_response_body( HTTPStatus.OK, response_error_page, is_response_json=False, content_type=CommonConst.CONTENT_TYPE_TEXT_HTML) user_name = email_change_apply_info['UserID'] if common_utils.check_key('CallerServiceName', email_change_apply_info): caller_service_name = email_change_apply_info['CallerServiceName'] # data response page response_error_page = config[CommonConst.KEY_RESPONSE_ERROR_PAGE.format( serviceName=caller_service_name)] response_execute_change_email = config[ CommonConst.KEY_RESPONSE_EXECUTE_CHANGE_EMAIL.format( serviceName=caller_service_name)] # メールアドレス変更申請テーブルから取得した UserID でCognito に合致する該当するユーザー情報を取得します。 try: user_info = aws_common.get_cognito_user_info_by_user_name( apply_id, user_name) except PmError: pm_logger.error("Cognitoから情報取得に失敗しました。") return common_utils.get_response_by_response_body( HTTPStatus.OK, response_error_page, is_response_json=False, content_type=CommonConst.CONTENT_TYPE_TEXT_HTML) if not user_info: pm_logger.warning("Cognitoにユーザーが存在しませんでした。ユーザーID: %s", user_name) return common_utils.get_response_by_response_body( HTTPStatus.OK, response_error_page, is_response_json=False, content_type=CommonConst.CONTENT_TYPE_TEXT_HTML) before_mail_address = email_change_apply_info['BeforeMailAddress'] after_mail_address = email_change_apply_info['AfterMailAddress'] # get cognito email cognito_email = jmespath.search("[?Name=='email'].Value | [0]", user_info['UserAttributes']) if before_mail_address != cognito_email: pm_logger.warning("変更前メールアドレスがCognitoのメールアドレスと合致しませんでした。") return common_utils.get_response_by_response_body( HTTPStatus.OK, response_error_page, is_response_json=False, content_type=CommonConst.CONTENT_TYPE_TEXT_HTML) # Cognitoのメールアドレスを変更する try: user_attributes = [{ 'Name': 'email', 'Value': after_mail_address }, { 'Name': 'email_verified', 'Value': 'true' }] aws_common.update_cognito_user_attributes(apply_id, user_name, user_attributes) except PmError: pm_logger.error("Cognitoの項目変更に失敗しました。") return common_utils.get_response_by_response_body( HTTPStatus.OK, response_error_page, is_response_json=False, content_type=CommonConst.CONTENT_TYPE_TEXT_HTML) # get list affiliations try: affiliations = pm_affiliation.query_userid_key(apply_id, user_name) except PmError: pm_logger.error("ユーザー所属テーブルでレコード取得に失敗しました。") return common_utils.get_response_by_response_body( HTTPStatus.OK, response_error_page, is_response_json=False, content_type=CommonConst.CONTENT_TYPE_TEXT_HTML) for affiliation in affiliations: try: org_notify_mail_destinations = pm_orgNotifyMailDestinations.query_key( apply_id, affiliation['OrganizationID'], CommonConst.NOTIFY_CODE, None) except PmError: pm_logger.error("組織別通知メール宛先テーブルでレコード取得に失敗しました。") return common_utils.get_response_by_response_body( HTTPStatus.OK, response_error_page, is_response_json=False, content_type=CommonConst.CONTENT_TYPE_TEXT_HTML) if org_notify_mail_destinations: destinations_update = [] for destination in org_notify_mail_destinations['Destinations']: if destination['MailAddress'] == before_mail_address: destination['MailAddress'] = after_mail_address destinations_update.append(destination) # update pm_orgNotifyMailDestinations try: attribute = {'Destinations': {"Value": destinations_update}} pm_orgNotifyMailDestinations.update( apply_id, org_notify_mail_destinations['OrganizationID'], org_notify_mail_destinations['NotifyCode'], attribute) except PmError: pm_logger.error("組織別通知メール宛先テーブルでレコード更新に失敗しました。") return common_utils.get_response_by_response_body( HTTPStatus.OK, response_error_page, is_response_json=False, content_type=CommonConst.CONTENT_TYPE_TEXT_HTML) # update pm_affiliation try: attribute = {'MailAddress': {"Value": after_mail_address}} pm_affiliation.update_affiliation(apply_id, affiliation['UserID'], affiliation['OrganizationID'], attribute, affiliation['UpdatedAt']) except PmError: pm_logger.error("ユーザー所属テーブルでレコード更新に失敗しました。") return common_utils.get_response_by_response_body( HTTPStatus.OK, response_error_page, is_response_json=False, content_type=CommonConst.CONTENT_TYPE_TEXT_HTML) # メールアドレス変更申請テーブルで変更申請ID{applyid}をキーにして申請レコードを削除する。 try: pm_emailChangeApply.delete(apply_id, apply_id) except PmError: pm_logger.error("メールアドレス変更申請テーブルでレコード削除に失敗しました。変更申請ID: %s", apply_id) return common_utils.get_response_by_response_body( HTTPStatus.OK, response_error_page, is_response_json=False, content_type=CommonConst.CONTENT_TYPE_TEXT_HTML) # data response response = common_utils.get_response_by_response_body( HTTPStatus.OK, response_execute_change_email, is_response_json=False, content_type=CommonConst.CONTENT_TYPE_TEXT_HTML) return common_utils.response(response, pm_logger)
def list_item_settings(trace_id, organization_id, project_id, coop_id, group_filter): pm_logger = common_utils.begin_logger(trace_id, __name__, inspect.currentframe()) # リソース関連性のバリデーションチェックを行います。 # プロジェクトテーブルに、プロジェクトID{project_id}をキーとしてクエリを実行します。 try: project = pm_projects.get_projects_by_organization_id( trace_id, project_id, organization_id) except Exception as e: return common_utils.error_exception(MsgConst.ERR_402, HTTPStatus.INTERNAL_SERVER_ERROR, e, pm_logger, True) # プロジェクトに該当レコードが存在しなかった場合(取得件数が0件) if (not project): return common_utils.error_common(MsgConst.ERR_AWS_401, HTTPStatus.UNPROCESSABLE_ENTITY, pm_logger) # 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) # チェック項目除外情報を取得します。 account_refine_code = CommonConst.ACCOUNT_REFINE_CODE.format( organization_id, project_id, awscoops_item['AWSAccount']) try: exclusion_items = pm_exclusionitems.query_filter_account_refine_code( trace_id, account_refine_code, group_filter) except Exception as e: return common_utils.error_exception(MsgConst.ERR_402, HTTPStatus.INTERNAL_SERVER_ERROR, e, pm_logger, True) # マニュアル評価情報を取得します。 try: assessment_items = pm_assessmentItems.query_filter_account_refine_code( trace_id, account_refine_code, group_filter) except Exception as e: return common_utils.error_exception(MsgConst.ERR_402, HTTPStatus.INTERNAL_SERVER_ERROR, e, pm_logger, True) # リソース除外情報を取得します。 try: exclusion_resources = pm_exclusionResources.query_filter_account_refine_code( trace_id, account_refine_code, group_filter) except Exception as e: return common_utils.error_exception(MsgConst.ERR_402, HTTPStatus.INTERNAL_SERVER_ERROR, e, pm_logger, True) # メンバーズ加入アカウントの確認をします members = common_utils.get_value('Members', awscoops_item, Members.Disable) if (isinstance(members, Decimal)): members = int(members) # セキュリティチェック項目設定一覧の配列を作成します。 security_item_settings = [] list_check_item_code_exclusion = jmespath.search('[*].CheckItemCode', exclusion_items) list_check_item_code_assessment = jmespath.search('[*].CheckItemCode', assessment_items) list_check_item_code_exclusion_resource = jmespath.search( '[*].CheckItemCode', exclusion_resources) for check_item_code in LIST_CHECK_ITEM_CODE: # リクエストパラメータgroupFilterにてフィルタ文字列が指定されていた場合、その文字列に該当するチェック項目コードを持つチェックだけ配列へ含めます。 if (common_utils.is_null(group_filter) is False and group_filter not in check_item_code): continue # マネージド項目有無managedFlag managed_flag = ManagedFlag.NotManaged if (check_item_code in LIST_CHECK_ITEM_CODE_MANAGED): if members == Members.Enable: managed_flag = ManagedFlag.Managed # チェック項目除外有無exclusionFlag exclusion_flag = ExclusionFlag.Disable if (check_item_code in list_check_item_code_exclusion): exclusion_flag = ExclusionFlag.Enable # マニュアル評価設定有無assessmentFlag assessment_flag = AssessmentFlag.NotManual if (check_item_code in LIST_CHECK_ITEM_CODE_ASSESSMENT): assessment_flag = AssessmentFlag.NotAssessment if (check_item_code in list_check_item_code_assessment): assessment_flag = AssessmentFlag.Assessment # リソース除外設定有無excludedResourceFlag excluded_resource_flag = ExcludedResourceFlag.Other if (check_item_code in LIST_CHECK_ITEM_CODE_EXCLUDED_RESOURCE): excluded_resource_flag = ExcludedResourceFlag.Disable if (check_item_code in list_check_item_code_exclusion_resource): excluded_resource_flag = ExcludedResourceFlag.Enable security_item_setting = { "checkItemCode": check_item_code, "managedFlag": managed_flag, "exclusionFlag": exclusion_flag, "assessmentFlag": assessment_flag, "excludedResourceFlag": excluded_resource_flag } security_item_settings.append(security_item_setting) # 作成したSecurityItemSettingの配列をレスポンスとして作成します。 response = common_utils.get_response_by_response_body( HTTPStatus.OK, security_item_settings) return common_utils.response(response, pm_logger)