Ejemplo n.º 1
0
    def test_basic_authentication(self):
        # Given
        yaml_string = textwrap.dedent("""\
            authentication:
              kind: basic
              auth: {0}
        """.format(UserPasswordAuth("*****@*****.**", "ulysse")._encoded_auth))

        # When
        config = Configuration.from_yaml_filename(StringIO(yaml_string))

        # Then
        self.assertFalse(config.use_webservice)
        self.assertEqual(config.auth,
                         UserPasswordAuth("*****@*****.**", "ulysse"))
Ejemplo n.º 2
0
 def set_auth_from_encoded(self, value):
     try:
         auth = UserPasswordAuth.from_encoded_auth(value)
     except Exception:
         raise InvalidConfiguration("Invalid EPD_auth value")
     else:
         self.update(auth=auth)
Ejemplo n.º 3
0
 def set_auth_from_encoded(self, value):
     try:
         auth = UserPasswordAuth.from_encoded_auth(value)
     except Exception:
         raise InvalidConfiguration("Invalid EPD_auth value")
     else:
         self.update(auth=auth)
Ejemplo n.º 4
0
    def test_with_keyring(self):
        with make_keyring_available_context() as mocked_keyring:
            config = Configuration()
            config.update(auth=(FAKE_USER, FAKE_PASSWORD))

            self.assertEqual(config.auth,
                             UserPasswordAuth(FAKE_USER, FAKE_PASSWORD))
            self.assertFalse(mocked_keyring.set_password.called)
Ejemplo n.º 5
0
    def test_change_empty_config_file_empty_username(self):
        with tempfile.NamedTemporaryFile(delete=False, mode="wt") as fp:
            fp.write("")

        config = Configuration.from_file(fp.name)
        self.assertIsNone(config.auth)

        config.update(auth=(FAKE_USER, FAKE_PASSWORD))
        self.assertEqual(config.auth, UserPasswordAuth(FAKE_USER,
                                                       FAKE_PASSWORD))
Ejemplo n.º 6
0
    def test_change_existing_config_file(self):
        r_new_password = "******"
        with tempfile.NamedTemporaryFile(delete=False, mode="wt") as fp:
            fp.write("EPD_auth = '{0}'".format(FAKE_CREDS))

        config = Configuration.from_file(fp.name)
        self.assertEqual(config.auth, FAKE_AUTH)

        config.update(auth=(FAKE_USER, r_new_password))
        config._change_auth(fp.name)
        new_config = Configuration.from_file(fp.name)

        self.assertEqual(new_config.auth,
                         UserPasswordAuth(FAKE_USER, r_new_password))
Ejemplo n.º 7
0
    def test_simple_authentication(self):
        # Given
        yaml_string = textwrap.dedent("""\
            authentication:
              kind: simple
              username: [email protected]
              password: ulysse
        """)

        # When
        config = Configuration.from_yaml_filename(StringIO(yaml_string))

        # Then
        self.assertFalse(config.use_webservice)
        self.assertEqual(config.auth,
                         UserPasswordAuth("*****@*****.**", "ulysse"))
Ejemplo n.º 8
0
    def test_change_existing_config_file_without_keyring(self):
        # Given
        with tempfile.NamedTemporaryFile(delete=False, mode="wt") as fp:
            fp.write("EPD_auth = '{0}'".format(FAKE_CREDS))

        # When
        config = Configuration.from_file(fp.name)
        config.update(auth=("user", "dummy"))
        config._change_auth(fp.name)

        # Then
        with open(fp.name, "r") as f:
            content = f.read()
            self.assertNotRegex(content, "EPD_username")
            self.assertRegex(content, "EPD_auth")
        config = Configuration.from_file(fp.name)
        self.assertEqual(config.auth, UserPasswordAuth("user", "dummy"))
Ejemplo n.º 9
0
    def _set_auth(self, auth):
        """ Set the internal authentication information.

        Parameters
        ----------
        auth : Auth-like
            The authentication information. May be a (username, password)
            tuple, or an *Auth subclass.
        """
        if isinstance(auth, tuple) and len(auth) == 2:
            username, password = auth
            if username is None:
                raise InvalidConfiguration(
                    "invalid authentication arguments: "
                    "{0}:{1}".format(username, password))
            self._auth = UserPasswordAuth(username, password)
        else:
            self._auth = auth
Ejemplo n.º 10
0
def configure_authentication_or_exit(config, config_filename, session):
    n_trials = 3
    for i in range(n_trials):
        username, password = input_auth()
        if username:
            break
        else:
            msg = "Please enter a non empty username ({0} trial(s) left, " \
                  "Ctrl+C to exit)". format(n_trials - i - 1)
            print(msg)
    else:
        print("No valid username entered (no modification was written).")
        sys.exit(-1)

    auth = UserPasswordAuth(username, password)

    try:
        config._checked_change_auth(auth, session, config_filename)
    except AuthFailedError as exc:
        msg = _invalid_authentication_message(auth, exc)
        print(msg)
        print("\nNo modification was written.")
        sys.exit(-1)
Ejemplo n.º 11
0
from enstaller.auth import APITokenAuth, UserPasswordAuth
from enstaller.config import (prepend_url, print_config,
                              _is_using_epd_username, convert_auth_if_required,
                              _keyring_backend_name, write_default_config)
from enstaller.config import (KEYRING_SERVICE_NAME, Configuration, add_url)
from enstaller.session import Session
from enstaller.errors import (EnstallerException, InvalidConfiguration)
from enstaller.utils import PY_VER

from .common import (make_keyring_available_context, make_keyring_unavailable,
                     mock_print, fake_keyring_context, fake_keyring,
                     DummyAuthenticator)

FAKE_USER = "******"
FAKE_PASSWORD = "******"
FAKE_AUTH = UserPasswordAuth(FAKE_USER, FAKE_PASSWORD)
FAKE_CREDS = UserPasswordAuth(FAKE_USER, FAKE_PASSWORD)._encoded_auth


class TestWriteConfig(unittest.TestCase):
    def setUp(self):
        self.d = tempfile.mkdtemp()
        self.f = os.path.join(self.d, ".enstaller4rc")

    def tearDown(self):
        shutil.rmtree(self.d)

    @make_keyring_unavailable
    def test_simple(self):
        config = Configuration()
        config.update(auth=(FAKE_USER, FAKE_PASSWORD))
Ejemplo n.º 12
0
 def epd_auth_to_auth(epd_auth):
     ret.update(auth=UserPasswordAuth.from_encoded_auth(epd_auth))
Ejemplo n.º 13
0
 def epd_auth_to_auth(epd_auth):
     ret.update(auth=UserPasswordAuth.from_encoded_auth(epd_auth))
Ejemplo n.º 14
0
    def authenticate(self, auth):
        if isinstance(auth, tuple) and len(auth) == 2:
            auth = UserPasswordAuth(auth[0], auth[1])

        self._authenticator.authenticate(self, auth.request_adapter)
        self._raw.auth = self._authenticator._auth
Ejemplo n.º 15
0
def load_configuration_from_yaml(cls, filename_or_fp):
    # FIXME: local import to workaround circular import
    from enstaller.config import STORE_KIND_BROOD

    # Local import to workaround some freezing issues for jaguar and speed up
    # imports a bit when yaml is not used.
    import jsonschema
    from ruamel import yaml

    if isinstance(filename_or_fp, string_types):
        with open(filename_or_fp, "rt") as fp:
            data = yaml.load(fp)
    else:
        data = yaml.load(filename_or_fp)

    if data is None:
        data = {}
    else:
        try:
            jsonschema.validate(data, _SCHEMA)
        except jsonschema.ValidationError as e:
            msg = "Invalid configuration: {0!r}".format(e.message)
            raise InvalidConfiguration(msg)

    config = cls()

    if _AUTHENTICATION in data:
        authentication = data[_AUTHENTICATION]
        authentication_type = authentication.get(_AUTHENTICATION_TYPE,
                                                 _AUTHENTICATION_TYPE_TOKEN)
        if authentication_type == _AUTHENTICATION_TYPE_SIMPLE:
            username = authentication[_USERNAME]
            password = authentication[_PASSWORD]
            auth = UserPasswordAuth(username, password)
        elif authentication_type == _AUTHENTICATION_TYPE_BASIC:
            auth_string = authentication[_AUTH_STRING]
            auth = UserPasswordAuth.from_encoded_auth(auth_string)
        elif authentication_type == _AUTHENTICATION_TYPE_TOKEN:
            token = authentication[_API_TOKEN]
            auth = APITokenAuth(token)
        else:
            msg = "Unknown authentication type {0!r}". \
                  format(authentication_type)
            raise InvalidConfiguration(msg)
        config.update(auth=auth)

    if _STORE_URL in data:
        config.update(store_url=data[_STORE_URL])
    if _REPOSITORIES in data:
        config.set_repositories_from_names(data[_REPOSITORIES])

    if _FILES_CACHE in data:
        files_cache = os.path.expanduser(data[_FILES_CACHE]). \
            replace("{PLATFORM}", custom_plat)
        config._repository_cache = files_cache
    if _MAX_RETRIES in data:
        config.update(max_retries=data[_MAX_RETRIES])
    if _SSL_VERIFY in data and not data[_SSL_VERIFY]:
        config.update(verify_ssl=data[_SSL_VERIFY])

    config.update(use_webservice=False)

    if isinstance(filename_or_fp, string_types):
        config._filename = filename_or_fp

    config._store_kind = STORE_KIND_BROOD
    return config
Ejemplo n.º 16
0
def load_configuration_from_yaml(cls, filename_or_fp):
    # FIXME: local import to workaround circular import
    from enstaller.config import STORE_KIND_BROOD
    if isinstance(filename_or_fp, string_types):
        with open(filename_or_fp, "rt") as fp:
            data = yaml.load(fp)
    else:
        data = yaml.load(filename_or_fp)

    if data is None:
        data = {}
    else:
        try:
            jsonschema.validate(data, _SCHEMA)
        except jsonschema.ValidationError as e:
            msg = "Invalid configuration: {0!r}".format(e.message)
            raise InvalidConfiguration(msg)

    config = cls()

    if _AUTHENTICATION in data:
        authentication = data[_AUTHENTICATION]
        authentication_type = authentication.get(_AUTHENTICATION_TYPE,
                                                 _AUTHENTICATION_TYPE_TOKEN)
        if authentication_type == _AUTHENTICATION_TYPE_SIMPLE:
            username = authentication[_USERNAME]
            password = authentication[_PASSWORD]
            auth = UserPasswordAuth(username, password)
        elif authentication_type == _AUTHENTICATION_TYPE_BASIC:
            auth_string = authentication[_AUTH_STRING]
            auth = UserPasswordAuth.from_encoded_auth(auth_string)
        elif authentication_type == _AUTHENTICATION_TYPE_TOKEN:
            token = authentication[_API_TOKEN]
            auth = APITokenAuth(token)
        else:
            msg = "Unknown authentication type {0!r}". \
                  format(authentication_type)
            raise InvalidConfiguration(msg)
        config.update(auth=auth)

    if _STORE_URL in data:
        config.update(store_url=data[_STORE_URL])
    if _REPOSITORIES in data:
        config.set_repositories_from_names(data[_REPOSITORIES])

    if _FILES_CACHE in data:
        files_cache = os.path.expanduser(data[_FILES_CACHE]). \
            replace("{PLATFORM}", custom_plat)
        config._repository_cache = files_cache
    if _MAX_RETRIES in data:
        config.update(max_retries=data[_MAX_RETRIES])
    if _SSL_VERIFY in data and not data[_SSL_VERIFY]:
        config.update(verify_ssl=data[_SSL_VERIFY])

    config.update(use_webservice=False)

    if isinstance(filename_or_fp, string_types):
        config._filename = filename_or_fp

    config._store_kind = STORE_KIND_BROOD
    return config