def __func(workflow): try: errors = workflow_schema.load(data, instance=workflow).errors if errors: return Problem.from_crud_resource( INVALID_INPUT_ERROR, 'workflow', 'update', 'Could not update workflow {}. Invalid input.'.format( workflow_id), ext=errors) except InvalidExecutionElement as e: executiondb.execution_db.session.rollback() current_app.logger.error(e.message) return Problem.from_crud_resource( INVALID_INPUT_ERROR, 'workflow', 'update', 'Could not update workflow {}. Invalid input.'.format( workflow_id)) try: executiondb.execution_db.session.commit() except IntegrityError: executiondb.execution_db.session.rollback() current_app.logger.error( 'Could not update workflow {}. Unique constraint failed'. format(workflow_id)) return unique_constraint_problem('workflow', 'update', workflow_id) current_app.logger.info('Updated workflow {0}'.format(workflow_id)) return workflow_schema.dump(workflow).data, SUCCESS
def __func(): if request.files and 'file' in request.files: f = request.files['file'] add_device_json = json.loads(f.read().decode('utf-8')) else: add_device_json = request.get_json() if current_app.running_context.execution_db.session.query( Device).filter(Device.name == add_device_json['name']).first() is not None: current_app.logger.error('Could not create device {0}. ' 'Device already exists.'.format( add_device_json['name'])) return Problem.from_crud_resource( OBJECT_EXISTS_ERROR, 'device', 'create', 'Device with name {} already exists.'.format( add_device_json['name'])) fields = { field['name']: field['value'] for field in add_device_json['fields'] } app = add_device_json['app_name'] device_type = add_device_json['type'] try: device_api = get_app_device_api(app, device_type) device_fields_api = device_api['fields'] validate_device_fields(device_fields_api, fields, device_type, app) except (UnknownApp, UnknownDevice, InvalidArgument) as e: return __crud_device_error_handler('create', e, app, device_type) else: fields = add_device_json['fields'] add_configuration_keys_to_device_json(fields, device_fields_api) app = current_app.running_context.execution_db.session.query( App).filter(App.name == app).first() if app is None: current_app.logger.error( 'SEVERE: App defined in api does not have corresponding entry in database. ' 'Cannot add device') return Problem.from_crud_resource( INVALID_INPUT_ERROR, 'device', 'create', 'App {} does not exist.'.format( add_device_json['app_name'])) device = Device.from_json(add_device_json) app.add_device(device) current_app.running_context.execution_db.session.add(device) current_app.running_context.execution_db.session.commit() device_json = get_device_json_with_app_name(device) return device_json, OBJECT_CREATED
def improper_json_problem(type_, operation, id_, errors=None): return Problem.from_crud_resource( BAD_REQUEST, type_, operation, 'Could not {} {} {}. Invalid JSON'.format(operation, type_, id_), ext={'errors': errors})
def __func(): config_in = request.get_json() if not _reset_token_durations(access_token_duration=config_in.get('access_token_duration', None), refresh_token_duration=config_in.get('refresh_token_duration', None)): return Problem.from_crud_resource( BAD_REQUEST, 'configuration', 'update', 'Access token duration must be less than refresh token duration.') for config, config_value in config_in.items(): if hasattr(walkoff.config.Config, config.upper()): setattr(walkoff.config.Config, config.upper(), config_value) elif hasattr(current_app.config, config.upper()): setattr(current_app.config, config.upper(), config_value) current_app.logger.info('Changed configuration') try: walkoff.config.Config.write_values_to_file() return __get_current_configuration(), SUCCESS except (IOError, OSError) as e: current_app.logger.error('Could not write changes to configuration to file') return Problem( IO_ERROR, 'Could not write changes to file.', 'Could not write configuration changes to file. Problem: {}'.format(format_exception_message(e)))
def __func(): if not _reset_token_durations(access_token_duration=configuration.get( 'access_token_duration', None), refresh_token_duration=configuration.get( 'refresh_token_duration', None)): return Problem.from_crud_resource( BAD_REQUEST, 'configuration', 'update', 'Access token duration must be less than refresh token duration.' ) for config, config_value in configuration.items(): if hasattr(walkoff.config.paths, config): setattr(walkoff.config.paths, config, config_value) elif hasattr(walkoff.config.config, config): setattr(walkoff.config.config, config, config_value) current_app.logger.info('Changed configuration') try: walkoff.config.config.write_values_to_file() return __get_current_configuration(), SUCCESS except (IOError, OSError) as e: current_app.logger.error( 'Could not write changes to configuration to file') return Problem( IO_ERROR, 'Could not write changes to file.', 'Could not write configuration changes to file. Problem: {}'. format(format_exception_message(e)))
def __func(): data = request.get_json() case_obj = CaseSubscription.query.filter_by(id=data['id']).first() if case_obj: original_name = case_obj.name case_name = data['name'] if 'name' in data else original_name if 'note' in data and data['note']: case_obj.note = data['note'] if 'name' in data and data['name']: case_subscription.rename_case(case_obj.name, data['name']) case_obj.name = data['name'] db.session.commit() current_app.logger.debug( 'Case name changed from {0} to {1}'.format( original_name, data['name'])) if 'subscriptions' in data: case_obj.subscriptions = data['subscriptions'] subscriptions = { subscription['id']: subscription['events'] for subscription in data['subscriptions'] } for uid, events in subscriptions.items(): case_subscription.modify_subscription( case_name, uid, events) db.session.commit() return case_obj.as_json(), SUCCESS else: current_app.logger.error( 'Cannot update case {0}. Case does not exist.'.format( data['id'])) return Problem.from_crud_resource( OBJECT_DNE_ERROR, 'case.', 'update', 'Case {} does not exist.'.format(data['id']))
def __func(): if request.files and 'file' in request.files: f = request.files['file'] data = json.loads(f.read().decode('utf-8')) else: data = request.get_json() case_name = data['name'] case_obj = CaseSubscription.query.filter_by(name=case_name).first() if case_obj is None: case_subscription = CaseSubscription(**data) db.session.add(case_subscription) db.session.commit() case = case_database.Case(name=case_name) current_app.running_context.case_db.session.add(case) current_app.running_context.case_db.commit() if 'subscriptions' in data: subscriptions = convert_subscriptions(data['subscriptions']) subscriptions, controller_subscriptions = split_subscriptions( subscriptions) current_app.running_context.executor.create_case( case.id, subscriptions) if controller_subscriptions: current_app.running_context.case_logger.add_subscriptions( case.id, subscriptions) current_app.logger.debug('Case added: {0}'.format(case_name)) return case_subscription.as_json(), OBJECT_CREATED else: current_app.logger.warning( 'Cannot create case {0}. Case already exists.'.format( case_name)) return Problem.from_crud_resource( OBJECT_EXISTS_ERROR, 'case', 'create', 'Case with name {} already exists.'.format(case_name))
def __func(): if request.files and 'file' in request.files: f = request.files['file'] add_device_json = json.loads(f.read().decode('utf-8')) else: add_device_json = request.get_json() if current_app.running_context.execution_db.session.query(Device).filter( Device.name == add_device_json['name']).first() is not None: current_app.logger.error('Could not create device {0}. ' 'Device already exists.'.format(add_device_json['name'])) return Problem.from_crud_resource( OBJECT_EXISTS_ERROR, 'device', 'create', 'Device with name {} already exists.'.format(add_device_json['name'])) fields = {field['name']: field['value'] for field in add_device_json['fields']} app = add_device_json['app_name'] device_type = add_device_json['type'] try: device_api = get_app_device_api(app, device_type) device_fields_api = device_api['fields'] validate_device_fields(device_fields_api, fields, device_type, app) except (UnknownApp, UnknownDevice, InvalidArgument) as e: return __crud_device_error_handler('create', e, app, device_type) else: fields = add_device_json['fields'] add_configuration_keys_to_device_json(fields, device_fields_api) app = current_app.running_context.execution_db.session.query(App).filter(App.name == app).first() if app is None: current_app.logger.error('SEVERE: App defined in api does not have corresponding entry in database. ' 'Cannot add device') return Problem.from_crud_resource( INVALID_INPUT_ERROR, 'device', 'create', 'App {} does not exist.'.format(add_device_json['app_name'])) device = Device.from_json(add_device_json) app.add_device(device) current_app.running_context.execution_db.session.add(device) current_app.running_context.execution_db.session.commit() device_json = get_device_json_with_app_name(device) return device_json, OBJECT_CREATED
def __func(user): if user.id != get_jwt_identity(): db.session.delete(user) db.session.commit() current_app.logger.info('User {0} deleted'.format(user.username)) return None, NO_CONTENT else: current_app.logger.error( 'Could not delete user {0}. User is current user.'.format( user.id)) return Problem.from_crud_resource( FORBIDDEN_ERROR, 'user', 'delete', 'Current user cannot delete self.')
def __func(): case_obj = CaseSubscription.query.filter_by(id=case_id).first() if case_obj: delete_cases([case_obj.name]) db.session.delete(case_obj) db.session.commit() current_app.logger.debug('Case deleted {0}'.format(case_id)) return None, NO_CONTENT else: current_app.logger.error( 'Cannot delete case {0}. Case does not exist.'.format(case_id)) return Problem.from_crud_resource( OBJECT_DNE_ERROR, 'case', 'delete', 'Case {} does not exist.'.format(case_id))
def __func(workflow): data = request.get_json() if 'name' in data and data['name']: new_workflow_name = data['name'] else: new_workflow_name = workflow.name + "_Copy" workflow_json = workflow_schema.dump(workflow) workflow_json = workflow_json.data workflow_json.pop('id') workflow_json['name'] = new_workflow_name regenerate_workflow_ids(workflow_json) if executiondb.execution_db.session.query( exists().where(Playbook.id == playbook_id)).scalar(): playbook = executiondb.execution_db.session.query( Playbook).filter_by(id=playbook_id).first() else: executiondb.execution_db.session.rollback() current_app.logger.error( 'Could not copy workflow {}. Playbook does not exist'.format( playbook_id)) return Problem.from_crud_resource( OBJECT_DNE_ERROR, 'workflow', 'copy', 'Could not copy workflow {}. Playbook with id {} does not exist.' .format(workflow_id, playbook_id)) try: new_workflow = workflow_schema.load(workflow_json) new_workflow = new_workflow.data executiondb.execution_db.session.add(new_workflow) playbook.add_workflow(new_workflow) executiondb.execution_db.session.commit() except IntegrityError: executiondb.execution_db.session.rollback() current_app.logger.error( 'Could not copy workflow {}. Unique constraint failed'.format( new_workflow_name)) return unique_constraint_problem('workflow', 'copy', new_workflow_name) current_app.logger.info('Workflow {0} copied to {1}'.format( workflow_id, new_workflow.id)) return workflow_schema.dump(new_workflow).data, OBJECT_CREATED
def __func(user): data = request.get_json() current_user = get_jwt_identity() if user.id == current_user: return update_user_fields(data, user) else: response = role_update_user_fields(data, user, update=True) if isinstance(response, tuple) and response[1] == FORBIDDEN_ERROR: current_app.logger.error( 'User {0} does not have permission to ' 'update user {1}'.format(current_user, user.id)) return Problem.from_crud_resource( FORBIDDEN_ERROR, 'user', 'update', 'Current user does not have permission to update user {}.'. format(user_id)) else: return response
def __func(workflow): errors = workflow_schema.load(data, instance=workflow).errors if errors: return Problem.from_crud_resource( INVALID_INPUT_ERROR, 'workflow', 'update', 'Could not update workflow {}. Invalid input.'.format(workflow_id), ext=errors) try: current_app.running_context.execution_db.session.commit() except IntegrityError: current_app.running_context.execution_db.session.rollback() current_app.logger.error('Could not update workflow {}. Unique constraint failed'.format(workflow_id)) return unique_constraint_problem('workflow', 'update', workflow_id) current_app.logger.info('Updated workflow {0}'.format(workflow_id)) return workflow_schema.dump(workflow), SUCCESS
def __func(): data = request.get_json() username = data['username'] if not User.query.filter_by(username=username).first(): user = add_user(username=username, password=data['password']) if 'roles' in data or 'active' in data: role_update_user_fields(data, user) db.session.commit() current_app.logger.info('User added: {0}'.format(user.as_json())) return user.as_json(), OBJECT_CREATED else: current_app.logger.warning( 'Cannot create user {0}. User already exists.'.format( username)) return Problem.from_crud_resource( OBJECT_EXISTS_ERROR, 'user', 'create', 'User with username {} already exists'.format(username))
def __func(): json_data = request.get_json() if not Role.query.filter_by(name=json_data['name']).first(): resources = json_data['resources'] if 'resources' in json_data else [] if '/roles' in resources: resources.remove('/roles') role_params = {'name': json_data['name'], 'description': json_data['description'] if 'description' in json_data else '', 'resources': resources} new_role = Role(**role_params) db.session.add(new_role) db.session.commit() current_app.logger.info('Role added: {0}'.format(role_params)) return new_role.as_json(), OBJECT_CREATED else: current_app.logger.warning('Cannot add role {0}. Role already exists'.format(json_data['name'])) return Problem.from_crud_resource( OBJECT_EXISTS_ERROR, 'role', 'create', 'Role with name {} already exists'.format(json_data['name']))
def __func(workflow): data = request.get_json() if 'name' in data and data['name']: new_workflow_name = data['name'] else: new_workflow_name = workflow.name + "_Copy" workflow_json = workflow_schema.dump(workflow) workflow_json.pop('id') workflow_json.pop('is_valid', None) workflow_json['name'] = new_workflow_name regenerate_workflow_ids(workflow_json) if current_app.running_context.execution_db.session.query(exists().where(Playbook.id == playbook_id)).scalar(): playbook = current_app.running_context.execution_db.session.query(Playbook).filter_by( id=playbook_id).first() else: current_app.running_context.execution_db.session.rollback() current_app.logger.error('Could not copy workflow {}. Playbook does not exist'.format(playbook_id)) return Problem.from_crud_resource( OBJECT_DNE_ERROR, 'workflow', 'copy', 'Could not copy workflow {}. Playbook with id {} does not exist.'.format(workflow_id, playbook_id)) try: new_workflow = workflow_schema.load(workflow_json) current_app.running_context.execution_db.session.add(new_workflow) playbook.add_workflow(new_workflow) current_app.running_context.execution_db.session.commit() except IntegrityError: current_app.running_context.execution_db.session.rollback() current_app.logger.error('Could not copy workflow {}. Unique constraint failed'.format(new_workflow_name)) return unique_constraint_problem('workflow', 'copy', new_workflow_name) current_app.logger.info('Workflow {0} copied to {1}'.format(workflow_id, new_workflow.id)) return workflow_schema.dump(new_workflow), OBJECT_CREATED
def update_user_fields(data, user): original_username = str(user.username) if 'username' in data and data['username']: user_db = User.query.filter_by(username=data['username']).first() if user_db is None or user_db.id == user.id: user.username = data['username'] else: return Problem( BAD_REQUEST, 'Cannot update user.', 'Username {} is already taken.'.format(data['username'])) if 'old_password' in data and 'password' in data: if user.verify_password(data['old_password']): user.password = data['password'] else: user.username = original_username return Problem.from_crud_resource( UNAUTHORIZED_ERROR, 'user', 'update', 'Current password is incorrect.') db.session.commit() current_app.logger.info('Updated user {0}. Updated to: {1}'.format( user.id, user.as_json())) return user.as_json(), SUCCESS
def __func(): case_obj = CaseSubscription.query.filter_by(id=case_id).first() if case_obj: case_name = case_obj.name db.session.delete(case_obj) db.session.commit() case = current_app.running_context.case_db.session.query( case_database.Case).filter( case_database.Case.name == case_name).first() if case: current_app.running_context.executor.delete_case(case_id) current_app.running_context.case_logger.delete_case(case_id) current_app.running_context.case_db.session.delete(case) current_app.running_context.case_db.commit() current_app.logger.debug('Case deleted {0}'.format(case_id)) return None, NO_CONTENT else: current_app.logger.error( 'Cannot delete case {0}. Case does not exist.'.format(case_id)) return Problem.from_crud_resource( OBJECT_DNE_ERROR, 'case', 'delete', 'Case {} does not exist.'.format(case_id))
def unique_constraint_problem(type_, operation, id_): return Problem.from_crud_resource( OBJECT_EXISTS_ERROR, type_, operation, 'Could not {} {} {}, possibly because of invalid or non-unique IDs.'.format(operation, type_, id_))
def unique_constraint_problem(type_, operation, id_): return Problem.from_crud_resource( OBJECT_EXISTS_ERROR, type_, operation, 'Could not {} {} {}, possibly because of invalid or non-unique IDs.'. format(operation, type_, id_))
def resource_not_found_problem(resource, operation, id_): return Problem.from_crud_resource( OBJECT_DNE_ERROR, resource, operation, '{} {} does not exist.'.format(resource.title(), id_))
def invalid_id_problem(resource, operation): return Problem.from_crud_resource(BAD_REQUEST, resource, operation, 'Invalid ID format.')
def scheduled_task_name_already_exists_problem(name, operation): return Problem.from_crud_resource( OBJECT_EXISTS_ERROR, 'scheduled task', operation, 'Could not {} scheduled task. Scheduled task with name {} already exists.' .format(operation, name))
subscriptions = convert_subscriptions(data['subscriptions']) subscriptions, controller_subscriptions = split_subscriptions( subscriptions) current_app.running_context.executor.update_case( case.id, subscriptions) if controller_subscriptions: current_app.running_context.case_logger.update_subscriptions( case.id, subscriptions) db.session.commit() return case_obj.as_json(), SUCCESS else: current_app.logger.error( 'Cannot update case {0}. Case does not exist.'.format( data['id'])) return Problem.from_crud_resource( OBJECT_DNE_ERROR, 'case.', 'update', 'Case {} does not exist.'.format(data['id'])) return __func() def patch_case(): return update_case() def delete_case(case_id): @jwt_required @permissions_accepted_for_resources( ResourcePermissions('cases', ['delete'])) def __func(): case_obj = CaseSubscription.query.filter_by(id=case_id).first()
def scheduled_task_name_already_exists_problem(name, operation): return Problem.from_crud_resource( OBJECT_EXISTS_ERROR, 'scheduled task', operation, 'Could not {} scheduled task. Scheduled task with name {} already exists.'.format(operation, name))
else: data = request.get_json() case_name = data['name'] case_obj = CaseSubscription.query.filter_by(name=case_name).first() if case_obj is None: case = CaseSubscription(**data) db.session.add(case) db.session.commit() current_app.logger.debug('Case added: {0}'.format(case_name)) return case.as_json(), OBJECT_CREATED else: current_app.logger.warning( 'Cannot create case {0}. Case already exists.'.format( case_name)) return Problem.from_crud_resource( OBJECT_EXISTS_ERROR, 'case', 'create', 'Case with name {} already exists.'.format(case_name)) return __func() def read_case(case_id, mode=None): @jwt_required @permissions_accepted_for_resources(ResourcePermissions('cases', ['read'])) @with_case('read', case_id) def __func(case_obj): if mode == "export": f = StringIO() f.write( json.dumps(case_obj.as_json(), sort_keys=True,