Ejemplo n.º 1
0
def test_server_uri_sanitization(check, instance):
    # Batch with `sanitize_username` set to False
    server_names = (
        ("mongodb://*****:*****@localhost:27017/admin",
         "mongodb://*****:*****@localhost:27017/admin"),
        # pymongo parses the password as `pass_%2`
        ("mongodb://*****:*****@localhost:27017/admin",
         "mongodb://*****:*****@localhost:27017/admin"),
        # pymongo parses the password as `pass_%` (`%25` is url-decoded to `%`)
        ("mongodb://*****:*****@localhost:27017/admin",
         "mongodb://*****:*****@localhost:27017/admin"),
        # same thing here, parsed username: `user%2`
        ("mongodb://user%2@localhost:27017/admin",
         "mongodb://user%2@localhost:27017/admin"),
        # with the current sanitization approach, we expect the username to be decoded in the clean name
        ("mongodb://user%25@localhost:27017/admin",
         "mongodb://user%@localhost:27017/admin"),
    )

    for server, expected_clean_name in server_names:
        _, _, _, _, clean_name, _ = parse_mongo_uri(server,
                                                    sanitize_username=False)
        assert expected_clean_name == clean_name

    # Batch with `sanitize_username` set to True
    server_names = (
        ("mongodb://*****:*****@localhost:27017/admin",
         "mongodb://*****@localhost:27017/admin"),
        ("mongodb://*****:*****@localhost:27017/admin",
         "mongodb://*****@localhost:27017/admin"),
        ("mongodb://*****:*****@localhost:27017/admin",
         "mongodb://*****@localhost:27017/admin"),
        ("mongodb://user%2@localhost:27017/admin",
         "mongodb://*****:*****@localhost:27017/admin",
         "mongodb://localhost:27017/admin"),
    )

    for server, expected_clean_name in server_names:
        _, _, _, _, clean_name, _ = parse_mongo_uri(server,
                                                    sanitize_username=True)
        assert expected_clean_name == clean_name
Ejemplo n.º 2
0
 def _get_clean_server_name(self):
     if not self.server:
         server = build_connection_string(
             self.hosts,
             username=self.username,
             password=self.password,
             scheme=self.scheme,
             database=self.db_name,
             options=self.additional_options,
         )
     else:
         server = self.server
     return parse_mongo_uri(server,
                            sanitize_username=bool(self.ssl_params))[4]
Ejemplo n.º 3
0
def test_uri_fields(check, instance):
    """
    Unit test for functionality of parse_mongo_uri
    """
    server_names = ((
        "mongodb://*****:*****@mongodb0.example.com:27017/?authSource=authDB",
        (
            "myDBReader",
            "D1fficultP@ssw0rd",
            None,
            [('mongodb0.example.com', 27017)],
            'mongodb://*****:*****@mongodb0.example.com:27017/?authSource=authDB',
            'authDB',
        ),
    ), )

    for server, expected_parse in server_names:
        assert expected_parse == parse_mongo_uri(server)
Ejemplo n.º 4
0
    def _get_clean_server_name(self):
        try:
            if not self.server:
                server = build_connection_string(
                    self.hosts,
                    username=self.username,
                    password=self.password,
                    scheme=self.scheme,
                    database=self.db_name,
                    options=self.additional_options,
                )
            else:
                server = self.server

            self.log.debug("Parsing mongo uri with server: %s", server)
            return parse_mongo_uri(server,
                                   sanitize_username=bool(self.ssl_params))[4]
        except Exception as e:
            raise ConfigurationError(
                "Could not build a mongo uri with the given hosts: %s. Error: %s"
                % (self.hosts, repr(e)))
Ejemplo n.º 5
0
    def __init__(self, instance, log):
        self.log = log

        # x.509 authentication
        self.ssl_params = exclude_undefined_keys({
            'ssl':
            instance.get('ssl', None),
            'ssl_keyfile':
            instance.get('ssl_keyfile', None),
            'ssl_certfile':
            instance.get('ssl_certfile', None),
            'ssl_cert_reqs':
            instance.get('ssl_cert_reqs', None),
            'ssl_ca_certs':
            instance.get('ssl_ca_certs', None),
        })

        if 'server' in instance:
            self.server = instance['server']
            (
                self.username,
                self.password,
                self.db_name,
                self.hosts,
                _,
                self.auth_source,
            ) = parse_mongo_uri(self.server,
                                sanitize_username=bool(self.ssl_params))
            self.scheme = None
            self.additional_options = {}
            self.hosts = ["%s:%s" % (host[0], host[1]) for host in self.hosts]
        else:
            self.server = None
            self.hosts = instance.get('hosts', [])
            self.username = instance.get('username')
            self.password = instance.get('password')
            # Deprecated
            self.scheme = instance.get('connection_scheme', 'mongodb')
            self.db_name = instance.get('database')
            self.additional_options = instance.get('options', {})
            self.auth_source = self.additional_options.get(
                'authSource') or self.db_name or 'admin'

        if not self.hosts:
            raise ConfigurationError('No `hosts` specified')

        self.clean_server_name = self._get_clean_server_name()
        if self.password and not self.username:
            raise ConfigurationError(
                '`username` must be set when a `password` is specified')

        if self.scheme != 'mongodb':
            self.log.info(
                "connection_scheme is deprecated and shouldn't be set to a value other than 'mongodb'"
            )

        if not self.db_name:
            self.log.info(
                'No MongoDB database found in URI. Defaulting to admin.')
            self.db_name = 'admin'

        self.timeout = float(instance.get('timeout', DEFAULT_TIMEOUT)) * 1000
        self.additional_metrics = instance.get('additional_metrics', [])

        # Authenticate
        self.do_auth = True
        self.use_x509 = self.ssl_params and not self.password
        if not self.username:
            self.log.info(
                "Disabling authentication because a username was not provided."
            )
            self.do_auth = False

        self.replica_check = is_affirmative(instance.get(
            'replica_check', True))
        self.collections_indexes_stats = is_affirmative(
            instance.get('collections_indexes_stats'))
        self.coll_names = instance.get('collections', [])
        self.custom_queries = instance.get("custom_queries", [])

        self._base_tags = list(set(instance.get('tags', [])))
        self.service_check_tags = self._compute_service_check_tags()
        self.metric_tags = self._compute_metric_tags()