def test_kill_script(self, user_id, expected_exception):
     self._assert_throws_exception(expected_exception,
                                   self.executor_service.kill_script,
                                   self.execution_id,
                                   User(user_id, {}),
                                   has_results=False)
 def test_is_running(self, user_id, expected_exception):
     self._assert_throws_exception(expected_exception,
                                   self.executor_service.is_running,
                                   self.execution_id, User(user_id, {}))
from parameterized import parameterized

from auth.authorization import Authorizer, ANY_USER, EmptyGroupProvider
from auth.user import User
from execution import executor
from execution.execution_service import ExecutionService
from execution.executor import create_process_wrapper
from model.model_helper import AccessProhibitedException
from model.script_config import ConfigModel
from tests import test_utils
from tests.test_utils import mock_object, create_audit_names, _MockProcessWrapper, _IdGeneratorMock
from utils import audit_utils

DEFAULT_USER_ID = 'test_user'
DEFAULT_AUDIT_NAMES = create_audit_names(auth_username=DEFAULT_USER_ID)
DEFAULT_USER = User(DEFAULT_USER_ID, DEFAULT_AUDIT_NAMES)

execution_owners = {}


class ExecutionServiceTest(unittest.TestCase):
    def test_start_script(self):
        execution_service = self.create_execution_service()
        execution_id = self._start(execution_service)

        self.assertEqual(self.get_last_id(), execution_id)

    def test_is_running_after_start(self):
        execution_service = self.create_execution_service()
        execution_id = self._start(execution_service)
class ExecutionServiceAuthorizationTest(unittest.TestCase):
    owner_user = User('user_x', {audit_utils.AUTH_USERNAME: '******'})

    @parameterized.expand([(owner_user.user_id, None),
                           ('another_user', AccessProhibitedException),
                           ('admin_user', AccessProhibitedException),
                           ('history_user', AccessProhibitedException)])
    def test_get_active_executor(self, user_id, expected_exception):
        self._assert_throws_exception(
            expected_exception, self.executor_service.get_active_executor,
            self.execution_id, User(user_id, {}))

    @parameterized.expand([(owner_user.user_id, None),
                           ('another_user', AccessProhibitedException),
                           ('admin_user', AccessProhibitedException),
                           ('history_user', AccessProhibitedException)])
    def test_stop_script(self, user_id, expected_exception):
        self._assert_throws_exception(expected_exception,
                                      self.executor_service.stop_script,
                                      self.execution_id,
                                      User(user_id, {}),
                                      has_results=False)

    @parameterized.expand([(owner_user.user_id, None),
                           ('another_user', AccessProhibitedException),
                           ('admin_user', AccessProhibitedException),
                           ('history_user', AccessProhibitedException)])
    def test_kill_script(self, user_id, expected_exception):
        self._assert_throws_exception(expected_exception,
                                      self.executor_service.kill_script,
                                      self.execution_id,
                                      User(user_id, {}),
                                      has_results=False)

    @parameterized.expand([(owner_user.user_id, None),
                           ('another_user', AccessProhibitedException),
                           ('admin_user', None), ('history_user', None)])
    def test_is_running(self, user_id, expected_exception):
        self._assert_throws_exception(expected_exception,
                                      self.executor_service.is_running,
                                      self.execution_id, User(user_id, {}))

    @parameterized.expand([(owner_user.user_id, None),
                           ('another_user', AccessProhibitedException),
                           ('admin_user', AccessProhibitedException),
                           ('history_user', AccessProhibitedException)])
    def test_get_config(self, user_id, expected_exception):
        self._assert_throws_exception(expected_exception,
                                      self.executor_service.get_config,
                                      self.execution_id, User(user_id, {}))

    @parameterized.expand([(owner_user.user_id, None),
                           ('another_user', AccessProhibitedException),
                           ('admin_user', AccessProhibitedException),
                           ('history_user', AccessProhibitedException)])
    def test_cleanup(self, user_id, expected_exception):
        self.executor_service.stop_script(self.execution_id, self.owner_user)

        self._assert_throws_exception(expected_exception,
                                      self.executor_service.cleanup_execution,
                                      self.execution_id,
                                      User(user_id, {}),
                                      has_results=False)

        self.script_cleaned = True

    def _assert_throws_exception(self,
                                 expected_exception,
                                 func,
                                 *parameters,
                                 has_results=True):
        try:
            result = func(*parameters)
            if expected_exception:
                self.fail('Should throw ' + str(expected_exception) +
                          ', but did not')
            if has_results:
                self.assertIsNotNone(result)

        except Exception as e:
            self.assertIsInstance(e, expected_exception)

    def setUp(self) -> None:
        super().setUp()

        def create_process(executor, command, working_directory,
                           env_variables):
            return _MockProcessWrapper(executor, command, working_directory,
                                       env_variables)

        executor._process_creator = create_process

        authorizer = Authorizer([ANY_USER], ['admin_user'], ['history_user'],
                                [], EmptyGroupProvider())
        self.executor_service = ExecutionService(authorizer,
                                                 _IdGeneratorMock())

        self.execution_id = _start(self.executor_service,
                                   self.owner_user.user_id)

        self.script_cleaned = False

    def tearDown(self) -> None:
        super().tearDown()

        executor._process_creator = create_process_wrapper

        if not self.script_cleaned:
            self.executor_service.kill_script(self.execution_id,
                                              self.owner_user)
            self.executor_service.cleanup_execution(self.execution_id,
                                                    self.owner_user)
Esempio n. 5
0
async def create_user_handler(*_null, **extra_args) -> Response:
    return await compose(
        create_user(extra_args['request'].app['pool']),
        send_create_user_message(extra_args['request'].app['mq']['channel']),
        to_dict, return_201)(User(**(await extra_args['request'].json())))
Esempio n. 6
0
async def update_user_handler(username, **extra_args) -> Response:
    return await compose(
        verify_username(User(**(await extra_args['request'].json()))),
        update_user(extra_args['request'].app['pool']), logger.error, to_dict,
        return_204)(username)
 def test_load_config_when_non_admin(self):
     _create_script_config_file('ConfX')
     user = User('user1', {})
     self.assertRaises(AdminAccessRequiredException,
                       self.config_service.load_config, 'ConfX', user)
Esempio n. 8
0
    def setUp(self):
        super().setUp()
        test_utils.setup()

        self.user = User('ConfigServiceTest', {AUTH_USERNAME: '******'})
        self.config_service = ConfigService(AnyUserAuthorizer(), test_utils.temp_folder)
Esempio n. 9
0
def get_user(request_handler):
    user_id = identify_user(request_handler)
    audit_names = audit_utils.get_all_audit_names(request_handler)

    return User(user_id, audit_names)
Esempio n. 10
0
import json
import unittest
from collections import defaultdict, OrderedDict

from auth.user import User
from communications import destination_email
from features.executions_callback_feature import ExecutionsCallbackFeature
from tests.communications.communication_test_utils import mock_communicators
from tests.test_utils import create_config_model
from utils.string_utils import values_to_string

user_x = User('userX', {})


@mock_communicators
class TestExecutionsCallbackFeature(unittest.TestCase):
    def test_init_http_communicator(self):
        self.create_feature(['http'])

        self.assert_created_destinations(['http1'])

    def test_init_email_communicator(self):
        self.create_feature(['email'])

        self.assert_created_destinations(['email1'])

    def test_init_script_communicator(self):
        self.create_feature(['script'])

        self.assert_created_destinations(['script1'])
Esempio n. 11
0
from auth.authenticate import authenticate, identity
from auth.user import User

_user = User(username="******", id_=1, password="******")


def test_authenticate_pass():
    # given
    # when
    user = authenticate(username=_user.username, password=_user.password)

    # then
    assert _user == user


def test_identify_pass():
    # given
    # when
    user = identity(payload={'identity': 1})

    # then
    assert _user == user


def test_authenticate_fail():
    # given
    bad_password = "******"

    # when
    user = authenticate(username=_user.username, password=bad_password)
def register():
    return User().register()
Esempio n. 13
0
File: app.py Progetto: mp5k/work
#read config
app.config.from_object('config.RuleConciergeConfig')
app.secret_key = app.config['SECRET_KEY']
DEBUG = app.config['DEBUG']

#ssl settings
if DEBUG:
    sslcontext = ssl.SSLContext(app.config['PROTOCOL'])
    sslcontext.load_cert_chain(app.config['SERVER_CERT'], app.config['SERVER_KEY'])

#login settings
login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = 'login' #login_viewのroute
users_repository = UsersRepository()
users_repository.save_user(User(username='******', password='******', id=1))

@login_manager.user_loader
def load_user(user_id):
    """
    user loader for login manager
    """
    return users_repository.get_user_by_id(user_id)


#init chatbot instance
chatbot = Chatbot(
    version=app.config['ASSISTANT_VERSION'],
    username=app.config['ASSISTANT_USERNAME'],
    password=app.config['ASSISTANT_PASSWORD'],
    workspace_id=app.config['ASSISTANT_WORKSPACE'],
Esempio n. 14
0
 def test_get_config(self, user_id, expected_exception):
     self._assert_throws_exception(expected_exception,
                                   self.executor_service.get_config,
                                   self.execution_id, User(user_id, {}))
from auth.authorization import Authorizer, EmptyGroupProvider
from auth.user import User
from execution import executor
from execution.execution_service import ExecutionService
from execution.logging import ScriptOutputLogger, ExecutionLoggingService, OUTPUT_STARTED_MARKER, \
    LogNameCreator, ExecutionLoggingController
from model.model_helper import AccessProhibitedException
from model.script_config import OUTPUT_FORMAT_TERMINAL
from react.observable import Observable
from tests import test_utils
from tests.test_utils import _IdGeneratorMock, create_config_model, _MockProcessWrapper, create_audit_names, \
    create_script_param_config, wait_observable_close_notification, AnyUserAuthorizer
from utils import file_utils, audit_utils
from utils.date_utils import get_current_millis, ms_to_datetime, to_millis

USER_X = User('userX', [])


def default_values_decorator(func):
    @functools.wraps(func)
    def wrapper(self, *args, **kwargs):
        spec = inspect.getfullargspec(func)
        defaults = spec.kwonlydefaults

        for key, value in defaults.items():
            if key in kwargs and kwargs[key] is None:
                kwargs[key] = value

        return func(self, *args, **kwargs)

    return wrapper
Esempio n. 16
0
from hashlib import md5
import datetime
import time
from urllib import parse
import json
import requests
from flask import request, session, redirect, render_template, url_for, make_response
from lib.MysqlDB import *
from utils.MakeToken import gen_token
from auth.user import User

logger = get_log()
config = get_config()
mysqldb = MysqlDB()
__MAX_AGE = int(config['auth']['max_age'])
user_handler = User(logger, __MAX_AGE)


@server.route('/login', methods=['GET', 'POST'])
def Login():
    status = 1
    try:
        if request.method == 'GET':
            info = {
                'ip': request.remote_addr,
                'url': request.url,
                'interface': "Login",
                'method': 'GET'
            }
            info_str = json.dumps(info, ensure_ascii=False)
            logger.info(info_str)
Esempio n. 17
0
    def test_non_admin_access(self):
        config = _prepare_script_config_object('conf1', description='My wonderful test config')

        self.assertRaises(AdminAccessRequiredException, self.config_service.update_config,
                          User('my_user', {}), config, 'confX.json')