def test_https_credentials_does_not_remove_irrelevant_entry_keyring(self):
        creds = CredentialsData(self.client_params.hostname, "admin", self.client_params.env_api_key)
        utils.save_credentials(creds)

        creds = CredentialsData("somemachine", "somelogin", "somepass")
        utils.save_credentials(creds)

        self.invoke_cli(self.cli_auth_params,
                        ['logout'])
        cred_store = utils.create_cred_store()
        assert cred_store.is_exists("somemachine")
        assert not cred_store.is_exists(self.client_params.hostname)
Exemplo n.º 2
0
 def get_api_key(ssl_verification_metadata: SslVerificationMetadata,
                 credential_data: CredentialsData, password: str,
                 conjurrc: ConjurrcData) -> str:
     """
     Method to fetch the user/host's API key from Conjur
     """
     # pylint: disable=logging-fstring-interpolation,raise-missing-from
     logging.debug(
         f"Attempting to fetch '{credential_data.username}' API key from Conjur..."
     )
     try:
         credentials_provider = SimpleCredentialsProvider()
         credentials_provider.save(
             CredentialsData(machine=conjurrc.conjur_url,
                             username=credential_data.username,
                             password=password))
         client = Client(
             connection_info=conjurrc.get_client_connection_info(),
             ssl_verification_mode=ssl_verification_metadata.mode,
             credentials_provider=credentials_provider,
             async_mode=False)
         api_key = client.login()
     except HttpSslError:
         if not conjurrc.cert_file and not ssl_verification_metadata.is_insecure_mode:
             raise CertificateVerificationException
     logging.debug("API key retrieved from Conjur")
     return api_key
Exemplo n.º 3
0
    def test_https_netrc_is_created_with_host_netrc(self,
                                                    keystore_disable_mock):
        utils.setup_cli(self)
        # Setup for fetching the API key of a host. To fetch we need to login
        credentials = CredentialsData(self.client_params.hostname, "admin",
                                      self.client_params.env_api_key)
        utils.save_credentials(credentials)

        self.invoke_cli(self.cli_auth_params, [
            'policy', 'replace', '-b', 'root', '-f',
            self.environment.path_provider.get_policy_path('conjur')
        ])

        host_api_key = self.invoke_cli(
            self.cli_auth_params, ['host', 'rotate-api-key', '-i', 'somehost'])

        extract_api_key_from_message = host_api_key.split(":")[1].strip()

        self.invoke_cli(self.cli_auth_params, ['logout'])

        output = self.invoke_cli(self.cli_auth_params, [
            'login', '-i', 'host/somehost', '-p',
            f'{extract_api_key_from_message}'
        ])

        self.validate_netrc(f"{self.client_params.hostname}", "host/somehost",
                            extract_api_key_from_message)
        self.assertIn("Successfully logged in to Conjur", output.strip())
Exemplo n.º 4
0
 def test_login_user_does_not_provide_password_prompts_for_one(
         self, mock_input):
     mock_credential_data = CredentialsData('somemachine', None, 'somepass')
     mock_login_controller = LoginController(self.mock_ssl_verify, None,
                                             mock_credential_data,
                                             LoginLogic)
     mock_login_controller.get_password()
Exemplo n.º 5
0
 def test_loaded_credentials_returns_proper_object(self):
     netrc.netrc = MagicMock(return_value=MockNetrc)
     netrc.netrc.hosts = MagicMock()
     netrc.netrc.return_value.authenticators = MagicMock(return_value=('somelogin', None, 'somepass'))
     with patch.object(FileCredentialsProvider, 'is_exists', return_value=True):
         credentials = FileCredentialsProvider()
         self.assertEquals(credentials.load("https://someurl"),
                           CredentialsData(machine='https://someurl', password='******', username='******'))
Exemplo n.º 6
0
 def test_login_raises_error_when_not_provided_username(self, mock_input):
     mock_credential_data = CredentialsData('somemachine', None, 'somepass')
     mock_login_controller = LoginController(self.mock_ssl_verify,
                                             'someuserpass',
                                             mock_credential_data,
                                             LoginLogic)
     with self.assertRaises(MissingRequiredParameterException):
         mock_login_controller.get_username()
Exemplo n.º 7
0
    def load(self, conjur_url: str) -> CredentialsData:
        """
        Method for fetching user credentials from the system's keyring
        """
        loaded_credentials = {}
        if not self.is_exists(conjur_url):
            raise CredentialRetrievalException

        for attr in KEYSTORE_ATTRIBUTES:
            loaded_credentials[attr] = KeystoreWrapper.get_password(
                conjur_url, attr)
        return CredentialsData.convert_dict_to_obj(loaded_credentials)
Exemplo n.º 8
0
    def test_https_cli_fails_if_cert_is_not_provided(self):
        conjurrc = ConfigFile(account=self.client_params.account,
                              conjur_url=self.client_params.hostname,
                              cert_file="")
        conjurrc.dump_to_file()
        cred_store = utils.create_cred_store()
        credential_data = CredentialsData(machine=self.client_params.hostname,
                                          username="******",
                                          password=self.client_params.env_api_key)
        cred_store.save(credential_data)
        self.setup_cli_params({})

        self.print_instead_of_raise_error(HttpSslError, "SSL: CERTIFICATE_VERIFY_FAILED", exit_code=1)
Exemplo n.º 9
0
    def test_https_cli_fails_if_cert_is_bad(self):
        # bad conjurrc
        conjurrc = ConfigFile(account=self.client_params.account,
                              conjur_url=self.client_params.hostname,
                              cert_file=self.environment.path_provider.nginx_conf_path)
        conjurrc.dump_to_file()
        cred_store = utils.create_cred_store()
        credential_data = CredentialsData(machine=self.client_params.hostname,
                                          username="******",
                                          password=self.client_params.env_api_key)
        cred_store.save(credential_data)
        self.setup_cli_params({})

        self.print_instead_of_raise_error(HttpSslError, "ssl", exit_code=1)
Exemplo n.º 10
0
def handle_login_logic(credential_provider: CredentialsProviderInterface,
                       identifier: str = None,
                       password: str = None,
                       ssl_verify: bool = True):
    """
    Method wraps the login call logic
    """
    credential_data = CredentialsData(username=identifier)
    login_logic = LoginLogic(credential_provider)
    ssl_verification_metadata = util_functions.get_ssl_verification_meta_data_from_conjurrc(
        ssl_verify)
    login_controller = LoginController(
        ssl_verification_metadata=ssl_verification_metadata,
        user_password=password,
        credential_data=credential_data,
        login_logic=login_logic)
    login_controller.load()

    sys.stdout.write("Successfully logged in to Conjur\n")
    def _get_credentials_from_file(
            self, conjur_url: str) -> CredentialsData:  # pragma: no cover
        try:
            loaded_credentials = {}
            netrc_auth = ""
            netrc_obj = netrc.netrc(self.netrc_path)

            logging.debug(
                f"Retrieving credentials from file '{self.netrc_path}'...")
            for host in netrc_obj.hosts:
                if conjur_url in host:
                    netrc_host_url = host
                    netrc_auth = netrc_obj.authenticators(netrc_host_url)
                    break

            login, _, password = netrc_auth
            loaded_credentials[MACHINE] = netrc_host_url
            loaded_credentials[PASSWORD] = password
            loaded_credentials[USERNAME] = login
            return CredentialsData.convert_dict_to_obj(loaded_credentials)
        except netrc.NetrcParseError as netrc_error:
            raise InvalidFormatException(
                "Error: netrc is in an invalid format. "
                f"Reason: {netrc_error}") from netrc_error
# Builtin
import unittest
from unittest.mock import patch, call
# Third-Party
import keyring
# Internal
from conjur.constants import TEST_HOSTNAME, PASSWORD, USERNAME, MACHINE, TEST_KEYRING
from conjur.data_object import ConjurrcData
from conjur_api.models import CredentialsData
from conjur.errors import OperationNotCompletedException, CredentialRetrievalException, KeyringWrapperGeneralError
from conjur.logic.credential_provider import KeystoreCredentialsProvider
from conjur.wrapper import KeystoreWrapper

MockCredentials = CredentialsData(machine=TEST_HOSTNAME,
                                  username='******',
                                  password='******')
MockConjurrcData = ConjurrcData(conjur_url=TEST_HOSTNAME, account="admin")


class KeystoreCredentialsProviderTest(unittest.TestCase):
    @patch.object(KeystoreWrapper, 'set_password')
    def test_save_calls_methods_properly(self, mock_store_wrapper):
        credential_provider = KeystoreCredentialsProvider()
        credential_provider.save(MockCredentials)
        calls = [
            call(TEST_HOSTNAME, MACHINE, TEST_HOSTNAME),
            call(TEST_HOSTNAME, USERNAME, 'somelogin'),
            call(TEST_HOSTNAME, PASSWORD, 'somepass')
        ]
        mock_store_wrapper.assert_has_calls(calls)
import unittest
from unittest.mock import MagicMock, patch

from conjur_api import Client
from conjur_api.models import CredentialsData
from conjur_api.errors.errors import HttpError
from conjur.errors import OperationNotCompletedException

from conjur.data_object.conjurrc_data import ConjurrcData
from conjur.logic.credential_provider.file_credentials_provider import FileCredentialsProvider
from conjur.logic.user_logic import UserLogic

MockCredentials = CredentialsData(username='******', password='******')


class MockConjurrc:
    conjur_url = 'someurl'
    account = 'someacc'
    cert_file = 'some/path/to/pem'


CONJURRC_DICT = {
    'conjur_url': 'someurl',
    'account': 'someacc',
    'cert_file': 'some/path/to/pem'
}


class UserLogicTest(unittest.TestCase):
    conjurrc_data = ConjurrcData('someurl', 'someacc', 'some/path/to/pem')
    credential_provider = FileCredentialsProvider()
 def test_credentials_data_object_representation(self):
     credentals_data = CredentialsData("https://someurl", "someid",
                                       "somepass")
     rep_obj = credentals_data.__repr__()
     self.assertEquals(str(EXPECTED_REP_OBJECT), rep_obj)