def test_find_obj_by_id(self, many_test_data, session, monkeypatch): obj_class = many_test_data['class'] test_data = many_test_data persisted_obj = test_data['factory'].create() session.add(persisted_obj) session.commit() mapper_manager = MapperManager() mapper_manager.createMappers(persisted_obj.workspace.name) def mock_unsafe_io_with_server(host, test_data, server_io_function, server_expected_response, server_url, **payload): mocked_response = test_data['mocked_response'] assert '{0}/ws/{1}/{2}/{3}/'.format(_create_server_api_url(), persisted_obj.workspace.name, test_data['api_end_point'], persisted_obj.id) == server_url return MockResponse(mocked_response, 200) monkeypatch.setattr( faraday_client.persistence.server.server, '_unsafe_io_with_server', partial(mock_unsafe_io_with_server, persisted_obj, test_data)) found_obj = mapper_manager.find(obj_class.class_signature, persisted_obj.id) serialized_obj = test_data['get_properties_function'](found_obj) if obj_class not in [Command]: metadata = serialized_obj.pop('metadata') assert serialized_obj == test_data['serialized_expected_results']
def __init__(self, args): self._original_excepthook = sys.excepthook self.args = args self._mappers_manager = MapperManager() pending_actions = Queue() self._model_controller = ModelController(self._mappers_manager, pending_actions) self._plugin_manager = PluginManager( None, pending_actions=pending_actions, ) self._workspace_manager = WorkspaceManager(self._mappers_manager) # Create a PluginController and send this to UI selected. self._plugin_controller = PluginController('PluginController', self._plugin_manager, self._mappers_manager, pending_actions) if self.args.cli: self.app = CliApp(self._workspace_manager, self._plugin_controller) CONF.setMergeStrategy("new") else: self.app = UiFactory.create(self._model_controller, self._plugin_manager, self._workspace_manager, self._plugin_controller, self.args.gui)
def test_find(get, url_endpoint, test_data, session): if 'api_result' in test_data: get.return_value = test_data['api_result'] mappers_manager = MapperManager() pending_actions = Queue() controller = ModelController(mappers_manager, pending_actions) workspace = WorkspaceFactory.create() mappers_manager.createMappers(workspace.name) obj = test_data['factory'].create(workspace=workspace) session.add(obj) session.commit() result = controller.find(test_data['class_signature'], obj.id) assert get.called print(get.mock_calls[0][1][0]) assert get.mock_calls[0][1][0].endswith('/_api/v2/ws/{0}/{1}/{2}/'.format( workspace.name, url_endpoint, obj.id))
def test_end_pluging_multiple_times(): mappers_manager = MapperManager() pending_actions = Queue() controller = ModelController(mappers_manager, pending_actions) controller._pluginEnd('test', None) controller._pluginEnd('test', None) assert controller.active_plugins_count == 0 assert controller.processing is False
def test_only_start_plugin(): mappers_manager = MapperManager() pending_actions = Queue() controller = ModelController(mappers_manager, pending_actions) controller._pluginStart('test', None) assert controller.active_plugins_count == 1 assert controller.processing controller._pluginStart('test', None) assert controller.active_plugins_count == 2
def test_controller_stop_when_is_not_processing(): mappers_manager = MapperManager() pending_actions = Queue() controller = ModelController(mappers_manager, pending_actions) assert controller.processing is False assert controller._must_stop is False controller.start() assert controller.is_alive() controller.stop() controller.join() assert controller._must_stop is True assert controller.is_alive() is False
def test_controller_plugin_start_action_updates_internal_state(): mappers_manager = MapperManager() pending_actions = Queue() controller = ModelController(mappers_manager, pending_actions) controller.start() controller.add_action((Modelactions.PLUGINSTART, "test", None)) time.sleep(1) assert controller.active_plugins_count == 1 assert controller.processing controller.add_action((Modelactions.PLUGINEND, "test", None)) time.sleep(1) assert controller.active_plugins_count == 0 assert controller.processing is False controller.stop() controller.join() assert controller.is_alive() is False
def test_update_without_command(self, many_test_data, monkeypatch, session): obj_class = many_test_data['class'] workspace = WorkspaceFactory.create(name='test') mapper_manager = MapperManager() mapper_manager.createMappers(workspace.name) test_data = many_test_data relational_model = test_data['factory'].create() session.add(relational_model) session.commit() raw_data = test_data['data'] if test_data['parent']: parent = test_data['parent']['parent_factory'].create() session.add(parent) session.commit() test_data['data']['parent'] = parent.id test_data['data']['parent_type'] = test_data['parent'][ 'parent_type'] if obj_class not in [Note, Command]: test_data['expected_payload']['parent'] = parent.id if obj_class in [Vuln, Credential]: test_data['expected_payload']['parent_type'] = test_data[ 'parent']['parent_type'] def mock_server_put(test_data, put_url, update=False, expected_response=201, **params): assert put_url == '{0}/ws/test/{1}/{2}/'.format( _create_server_api_url(), test_data['api_end_point'], test_data['id']) assert expected_response == 200 assert update == False if obj_class not in [Command]: metadata = params.pop('metadata') assert metadata['owner'] == test_data['expected_payload'][ 'owner'] params.pop('command_id', None) test_data['expected_payload'].pop('command_id', None) assert params == test_data['expected_payload'] return {'id': 1, 'ok': True, 'rev': ''} raw_data['id'] = relational_model.id test_data['id'] = relational_model.id monkeypatch.setattr(faraday_client.persistence.server.server, '_put', partial(mock_server_put, test_data)) obj = obj_class(raw_data, workspace.name) mapper_manager.update(obj)
def test_controller_cant_be_stopped_when_is_processing(): """ If someone tells the controller to stop and it is processing then it will stop when the processing finishes """ mappers_manager = MapperManager() pending_actions = Queue() controller = ModelController(mappers_manager, pending_actions) assert controller.processing is False assert controller._must_stop is False controller.start() controller.processing = True controller.active_plugins_count = 1 assert controller.is_alive() controller.stop() assert controller._must_stop is True assert controller.processing controller.join(timeout=2) assert controller.is_alive() controller.processing = False controller.join() assert controller.is_alive() is False
def test_update_with_command(self, many_test_data, monkeypatch, session): obj_class = many_test_data['class'] if obj_class in [Command]: return workspace = WorkspaceFactory.create(name='test') command = CommandFactory.create(workspace=workspace) session.add(command) session.commit() mapper_manager = MapperManager() mapper_manager.createMappers(workspace.name) test_data = many_test_data raw_data = test_data['data'] if test_data['parent']: parent = test_data['parent']['parent_factory'].create() session.add(parent) session.commit() test_data['data']['parent'] = parent.id test_data['data']['parent_type'] = test_data['parent'][ 'parent_type'] test_data['expected_payload']['parent'] = parent.id if obj_class in [Vuln, Credential]: test_data['expected_payload']['parent_type'] = test_data[ 'parent']['parent_type'] relational_model = test_data['factory'].create() session.add(relational_model) session.commit() def mock_server_put(put_url, update=False, expected_response=201, **params): assert put_url == '{0}/ws/test/{1}/{2}/?command_id={3}'.format( _create_server_api_url(), test_data['api_end_point'], test_data['id'], params['command_id']) assert expected_response == 200 assert update == False return {'id': 1, 'ok': True, 'rev': ''} raw_data['id'] = relational_model.id test_data['id'] = relational_model.id monkeypatch.setattr(faraday_client.persistence.server.server, '_put', mock_server_put) obj = obj_class(raw_data, workspace.name) mapper_manager.update(obj, command.id)
def test_save_with_command(self, many_test_data, monkeypatch, session): obj_class = many_test_data['class'] if obj_class == Command: return workspace = WorkspaceFactory.create(name='test') command = CommandFactory.create(workspace=workspace) session.commit() mapper_manager = MapperManager() mapper_manager.createMappers(workspace.name) test_data = many_test_data raw_data = test_data['data'] if test_data['parent']: parent = test_data['parent']['parent_factory'].create() session.commit() test_data['data']['parent'] = parent.id test_data['data']['parent_type'] = test_data['parent'][ 'parent_type'] if obj_class not in [Note]: test_data['expected_payload']['parent'] = parent.id if obj_class in [Vuln, Credential]: test_data['expected_payload']['parent_type'] = test_data[ 'parent']['parent_type'] def mock_server_post(test_data, post_url, update=False, expected_response=201, **params): assert post_url == '{0}/ws/test/{1}/?command_id={2}'.format( _create_server_api_url(), test_data['api_end_point'], params['command_id']) assert expected_response == 201 assert update == False metadata = params.pop('metadata') assert metadata['owner'] == test_data['expected_payload']['owner'] params.pop('command_id') test_data['expected_payload'].pop('command_id') assert params == test_data['expected_payload'] return {'id': 1, 'ok': True, 'rev': ''} monkeypatch.setattr(faraday_client.persistence.server.server, '_post', partial(mock_server_post, test_data)) obj = obj_class(raw_data, workspace.name) mapper_manager.save(obj, command.id)
def dispatch(args, unknown, user_help, username, password): if username and password: session_cookie = login_user(args.url, username, password) if not session_cookie: raise UserWarning('Invalid credentials!') CONF.setFaradaySessionCookies(session_cookie) if '--' in unknown: unknown.remove('--') # We need the ModelController to register all available models mappers_manager = MapperManager() pending_actions = Queue() model_controller = ModelController(mappers_manager, pending_actions) if not args.command: print(user_help) if not args.interactive: sys.exit(1) if args.command not in list(plugins.keys()): sys.stderr.write(Fore.RED + ("ERROR: Plugin %s not found.\n" % args.command) + Fore.RESET) if args.interactive: return None else: sys.exit(1) import faraday_client as client # pylint:disable=import-outside-toplevel faraday_directory = os.path.dirname( os.path.realpath(os.path.join(client.__file__))) plugin_path = os.path.join(faraday_directory, "bin/", args.command + '.py') # Get filename and import this loader = SourceFileLoader('module_fplugin', plugin_path) module_fplugin = loader.load_module() module_fplugin.models.server.FARADAY_UP = False module_fplugin.models.server.SERVER_URL = args.url module_fplugin.models.server.AUTH_USER = username module_fplugin.models.server.AUTH_PASS = password call_main = getattr(module_fplugin, 'main', None) if call_main is None: sys.stderr.write(Fore.RED + "ERROR: Main function not found.\n" + Fore.RESET) if args.interactive: return None else: sys.exit(1) # Inspect the main function imported from the plugin and decide the best calling option main_argspec = inspect.getfullargspec(call_main) if main_argspec != CURRENT_MAIN_ARGSPEC: # Function argspec does not match current API. # Warn the user and call with original parameteres. sys.stderr.write( Fore.YELLOW + "WARNING: Plugin does not follow current call signature. Please update it! [%s.py]\n" % args.command + Fore.RESET) obj_id = None if {'args', 'parser'} <= set(main_argspec.args): # Function accepts args and parser arguments new_parser = argparse.ArgumentParser( description=plugins[args.command]['description'], prog="fplugin %s" % args.command, formatter_class=RawDescriptionAndDefaultsHelpFormatter) ret, obj_id = call_main(workspace=args.workspace, args=unknown, parser=new_parser) if obj_id is not None: print(obj_id) else: # Use old API to call plugin sys.stderr.write( Fore.YELLOW + "WARNING: Call with arguments and parser not supported.\n" + Fore.RESET) ret = call_main(workspace=args.workspace) if ret is None: ret = 0 if args.interactive: # print ('code = %d' % ret) return obj_id else: sys.exit(ret)