Exemple #1
0
    def test_validation_missing_required_param(self):
        try:
            params = {'param1': 1}
            name = 'param2'
            required = True
            param_type = int
            expected = {
                'message':
                'the required parameter "' + name + '" was not provided',
                'type': 'input',
                'code': 'missing',
                'info': {
                    'key': name
                }
            }

            result, err = Validation.check_param(params, name, required,
                                                 param_type)
            self.assertIsNone(result)
            self.assertIsNotNone(err)

            self.assertIsInstance(err, dict)
            self.assertDictEqual(err, expected)

        except Exception as ex:
            self.assertTrue(False)
Exemple #2
0
    def __init__(self, config):
        #BEGIN_CONSTRUCTOR
        config = Validation.validate_config(config)

        self.auth_url = config['auth-url']
        #END_CONSTRUCTOR
        pass
    def is_admin_user(self, ctx, param):
        """
        :param param: instance of type "IsAdminUserParam" -> structure:
           parameter "username" of type "Username"
        :returns: multiple set - (1) parameter "is_admin" of type "Boolean",
           (2) parameter "error" of type "Error" -> structure: parameter
           "message" of String, parameter "type" of String, parameter "code"
           of String, parameter "info" of unspecified object
        """
        # ctx is the context object
        # return variables are: is_admin, error
        #BEGIN is_admin_user
        param, error = Validation.validate_is_admin_user(param, ctx)
        if error:
            return None, error

        # This uses the admin user stored in the model...
        model = UIServiceModel(auth_url=self.auth_url,
                               admin_users=self.admin_users,
                               token=ctx['token'],
                               username=ctx['user_id'],
                               db_config=self.db_config)
        is_admin = model.is_admin_user(param['username'])
        return [is_admin, None]
        #END is_admin_user

        # At some point might do deeper type checking...
        if not isinstance(is_admin, int):
            raise ValueError('Method is_admin_user return value ' +
                             'is_admin is not type int as required.')
        if not isinstance(error, dict):
            raise ValueError('Method is_admin_user return value ' +
                             'error is not type dict as required.')
        # return the results
        return [is_admin, error]
    def search_alerts(self, ctx, query):
        """
        :param query: instance of type "AlertQuery" (typedef structure {
           string path; string op; string value; } SearchField; typedef
           structure { string op; list<SearchField> args; }
           SearchSubExpression; typedef structure { SearchField field;
           SearchSubExpression expression; } SearchArg; typedef structure {
           string op; list<SearchArg> args; } SearchExpression;) ->
           structure: parameter "query" of type "SearchExpression" (I give up
           ...) -> unspecified object, parameter "paging" of type
           "PagingSpec" (search_alerts) -> structure: parameter "start" of
           Long, parameter "limit" of Long, parameter "sorting" of list of
           type "SortSpec" -> structure: parameter "field" of String,
           parameter "is_descending" of type "Boolean"
        :returns: multiple set - (1) parameter "result" of type
           "SearchAlertsResult" -> structure: parameter "alerts" of list of
           type "Alert" -> structure: parameter "id" of type "AlertID",
           parameter "start_at" of type "Timestamp" (BASE Types), parameter
           "end_at" of type "Timestamp" (BASE Types), parameter "type" of
           type "AlertType", parameter "title" of String, parameter "message"
           of String, parameter "status" of type "AlertStatus", parameter
           "created_at" of type "Timestamp" (BASE Types), parameter
           "created_by" of String, parameter "updated_at" of type "Timestamp"
           (BASE Types), parameter "updated_by" of String, (2) parameter
           "error" of type "Error" -> structure: parameter "message" of
           String, parameter "type" of String, parameter "code" of String,
           parameter "info" of unspecified object
        """
        # ctx is the context object
        # return variables are: result, error
        #BEGIN search_alerts
        query2, error = Validation.validate_search_alerts_parameter(query, ctx)
        if error:
            return None, error

        model = UIServiceModel(auth_url=self.auth_url,
                               admin_users=self.admin_users,
                               token=ctx['token'],
                               username=ctx['user_id'],
                               db_config=self.db_config)

        result, error = model.search_alerts(query2)
        if error:
            return None, error

        return [{'alerts': result}, None]

        #END search_alerts

        # At some point might do deeper type checking...
        if not isinstance(result, dict):
            raise ValueError('Method search_alerts return value ' +
                             'result is not type dict as required.')
        if not isinstance(error, dict):
            raise ValueError('Method search_alerts return value ' +
                             'error is not type dict as required.')
        # return the results
        return [result, error]
    def __init__(self, config):
        #BEGIN_CONSTRUCTOR
        # self.admin_users = string.split(os.environ.get('ADMIN_USERS', ''), ' ')
        self.admin_users = string.split(config['admin-users'], ' ')

        config = Validation.validate_config(config)

        self.db_config = config['mongo']

        self.auth_url = config['auth-url']

        #END_CONSTRUCTOR
        pass
Exemple #6
0
    def test_validation_missing_optional_param(self):
        try:
            params = {'param1': 1}
            name = 'param2'
            required = False
            param_type = int

            result, err = Validation.check_param(params, name, required,
                                                 param_type)
            self.assertIsNone(err)
            self.assertIsNone(result)

        except Exception as ex:
            self.assertTrue(False)
Exemple #7
0
    def test_validation_url_should_be_secure_and_is(self):
        try:
            url = 'https://a.b.c'
            must_be_secure = True
            expected = 'https://a.b.c'

            result, err = Validation.check_url(url, must_be_secure)
            self.assertIsNotNone(result)
            self.assertIsNone(err)

            self.assertIsInstance(result, str)
            self.assertEqual(result, expected)

        except Exception as ex:
            self.assertTrue(False)
    def test_validation_home_url_good_param(self):
        try:
            param = {
                'url': urlBase + '/test1.html',
                'timeout': 1000
            }
            expected = {
                'url': urlBase + '/test1.html',
                'timeout': 1000
            }
            result, err = Validation.validate_check_html_url_param(param, None)
            self.assertIsNone(err, 'Good param failed: %s' % (str(err)))
            self.assertIsNotNone(result)
            
            self.assertIsInstance(result, dict)
            self.assertDictEqual(result, expected)

        except Exception as ex:
            self.assertTrue(False, 'Unexpected exception: %s' % str(ex))
    def get_alert(self, ctx, param):
        """
        :param param: instance of type "GetAlertParam" (get_alert) ->
           structure: parameter "id" of type "AlertID"
        :returns: multiple set - (1) parameter "alert" of type "Alert" ->
           structure: parameter "id" of type "AlertID", parameter "start_at"
           of type "Timestamp" (BASE Types), parameter "end_at" of type
           "Timestamp" (BASE Types), parameter "type" of type "AlertType",
           parameter "title" of String, parameter "message" of String,
           parameter "status" of type "AlertStatus", parameter "created_at"
           of type "Timestamp" (BASE Types), parameter "created_by" of
           String, parameter "updated_at" of type "Timestamp" (BASE Types),
           parameter "updated_by" of String, (2) parameter "error" of type
           "Error" -> structure: parameter "message" of String, parameter
           "type" of String, parameter "code" of String, parameter "info" of
           unspecified object
        """
        # ctx is the context object
        # return variables are: alert, error
        #BEGIN get_alert
        input, error = Validation.validate_get_alert_parameter(param, ctx)
        if error:
            return None, error

        model = UIServiceModel(auth_url=self.auth_url,
                               admin_users=self.admin_users,
                               token=ctx['token'],
                               username=ctx['user_id'],
                               db_config=self.db_config)
        alert, error = model.get_alert(input['id'])
        return [alert, error]
        #END get_alert

        # At some point might do deeper type checking...
        if not isinstance(alert, dict):
            raise ValueError('Method get_alert return value ' +
                             'alert is not type dict as required.')
        if not isinstance(error, dict):
            raise ValueError('Method get_alert return value ' +
                             'error is not type dict as required.')
        # return the results
        return [alert, error]
Exemple #10
0
    def test_validation_url_invalid_format(self):
        try:
            url = 'xhttp://a.b.c'
            must_be_secure = True
            expected = {
                'message': ('does not match a valid url'),
                'type': 'input',
                'code': 'wrong-format',
                'info': {}
            }

            result, err = Validation.check_url(url, must_be_secure)
            self.assertIsNone(result)
            self.assertIsNotNone(err)

            self.assertIsInstance(err, dict)
            self.assertDictEqual(err, expected)

        except Exception as ex:
            self.assertTrue(False)
Exemple #11
0
    def test_validation_url_should_be_secure_but_not(self):
        try:
            url = 'http://a.b.c'
            must_be_secure = True
            expected = {
                'message': ('this url parameter must be secure'),
                'type': 'input',
                'code': 'wrong-format',
                'info': {}
            }

            result, err = Validation.check_url(url, must_be_secure)
            self.assertIsNone(result)
            self.assertIsNotNone(err)

            self.assertIsInstance(err, dict)
            self.assertDictEqual(err, expected)

        except Exception as ex:
            self.assertTrue(False)
    def search_alerts_summary(self, ctx, query):
        """
        :param query: instance of type "SearchExpression" (I give up ...) ->
           unspecified object
        :returns: multiple set - (1) parameter "result" of type
           "SearchAlertsSummaryResult" -> structure: parameter "statuses" of
           mapping from String to Long, (2) parameter "error" of type "Error"
           -> structure: parameter "message" of String, parameter "type" of
           String, parameter "code" of String, parameter "info" of
           unspecified object
        """
        # ctx is the context object
        # return variables are: result, error
        #BEGIN search_alerts_summary
        query2, error = Validation.validate_search_alerts_summary_parameter(
            query, ctx)
        if error:
            return None, error

        model = UIServiceModel(auth_url=self.auth_url,
                               admin_users=self.admin_users,
                               token=ctx['token'],
                               username=ctx['user_id'],
                               db_config=self.db_config)

        result, error = model.search_alerts_summary(query2)
        if error:
            return None, error

        return [{'alerts_summary': result}, None]
        #END search_alerts_summary

        # At some point might do deeper type checking...
        if not isinstance(result, dict):
            raise ValueError('Method search_alerts_summary return value ' +
                             'result is not type dict as required.')
        if not isinstance(error, dict):
            raise ValueError('Method search_alerts_summary return value ' +
                             'error is not type dict as required.')
        # return the results
        return [result, error]
Exemple #13
0
    def test_validation_image_url_good_url(self):
        try:
            param1 = {
                'url': urlBase + '/test1.png',
                'timeout': 1000,
                'verify_ssl': 0
            }
            expected1 = {
                'url': urlBase + '/test1.png',
                'timeout': 1000,
                'verify_ssl': False
            }
            result1, err = Validation.validate_check_image_url_param(
                param1, None)
            self.assertIsNone(err, 'Good url failed: %s' % (str(err)))
            self.assertIsNotNone(result1)

            self.assertIsInstance(result1, dict)
            self.assertDictEqual(result1, expected1)

        except Exception as ex:
            self.assertTrue(False)
    def test_validation_home_url_missing_url_param(self):
        try:
            param = {
                'timeout': 1000
            }
            expected = { 
                'message': 'the required parameter "url" was not provided', 
                'type': 'input', 
                'code': 'missing', 
                'info': { 
                    'key': 'url' 
                } 
            } 
            result, err = Validation.validate_check_html_url_param(param, None)
            self.assertIsNone(result)
            self.assertIsNotNone(err)
            
            self.assertIsInstance(err, dict)
            self.assertDictEqual(err, expected)

        except Exception as ex:
            self.assertTrue(False, 'Unexpected exception: %s' % str(ex))
    def test_model_no_token(self):
        auth_url = self.cfg['auth-url']
        admin_users = self.cfg['admin-users']
        token = self.ctx['token']
        username = self.ctx['user_id']
        config = Validation.validate_config(self.cfg)
        db_config = config['mongo']

        try:
            uis = UIServiceModel(auth_url, None, username, admin_users,
                                 db_config)
            uis.delete_alert('abc')
            self.assertTrue(False)
        except Exception as ex:
            self.assertTrue(True)

        try:
            uis = UIServiceModel(auth_url, token, 'not_an_admin', admin_users,
                                 db_config)
            uis.delete_alert('abc')
            self.assertTrue(False)
        except Exception as ex:
            self.assertTrue(True)
Exemple #16
0
    def check_html_url(self, ctx, param):
        """
        :param param: instance of type "CheckHTMLURLParams" (Check html url)
           -> structure: parameter "url" of String, parameter "timeout" of
           Long
        :returns: multiple set - (1) parameter "result" of type
           "CheckHTMLURLResult" -> structure: parameter "is_valid" of type
           "Boolean", parameter "error" of type "CheckError" -> structure:
           parameter "code" of String, parameter "info" of unspecified
           object, (2) parameter "error" of type "Error" -> structure:
           parameter "message" of String, parameter "type" of String,
           parameter "code" of String, parameter "info" of unspecified object
        """
        # ctx is the context object
        # return variables are: result, error
        #BEGIN check_html_url
        param, error = Validation.validate_check_html_url_param(param, ctx)
        if error:
            return [None, error]

        try:
            header = {'User-Agent': self.USER_AGENT_STRING}
            # header = {
            #     'User-Agent': ''
            # }
            timeout = param['timeout'] / 1000
            response = requests.head(url=param['url'],
                                     allow_redirects=True,
                                     timeout=timeout,
                                     headers=header)
            if response.status_code == 404:
                return [{
                    'is_valid': False,
                    'error': {
                        'code': 'not-found'
                    }
                }, None]

            if response.status_code not in [200, 301, 302]:
                return [{
                    'is_valid': False,
                    'error': {
                        'code': 'unexpected-response-status-code',
                        'info': {
                            'status_code': response.status_code
                        }
                    }
                }, None]

            if 'content-type' not in response.headers:
                return [{
                    'is_valid': False,
                    'error': {
                        'code': 'missing-content-type',
                        'info': {}
                    }
                }, None]

            content_type = response.headers['content-type']
            image_re = re.compile('^text/html')
            if not re.match(image_re, content_type):
                return [{
                    'is_valid': False,
                    'error': {
                        'code': 'invalid-content-type',
                        'info': {
                            'content_type': content_type
                        }
                    }
                }, None]

            return [{
                'is_valid': True,
            }, None]

        except Exception as ex:
            return [
                None, {
                    'message': ('exception requesting html page'),
                    'type': 'value',
                    'code': 'error-response',
                    'info': {
                        'exception': str(ex)
                    }
                }
            ]
        #END check_html_url

        # At some point might do deeper type checking...
        if not isinstance(result, dict):
            raise ValueError('Method check_html_url return value ' +
                             'result is not type dict as required.')
        if not isinstance(error, dict):
            raise ValueError('Method check_html_url return value ' +
                             'error is not type dict as required.')
        # return the results
        return [result, error]