def write_conjurrc(cls, conjurrc_file_path: str, conjurrc_data: ConjurrcData, force_overwrite_flag: bool) -> bool: """ Method for writing the conjurrc configuration details needed to create a connection to Conjur """ if not force_overwrite_flag and os.path.exists(conjurrc_file_path): return False conjurrc_data.write_to_file(conjurrc_file_path) return True
def _run_command_flow(self, args, resource): ssl_verification_meta_data = get_ssl_verification_meta_data_from_conjurrc(args.ssl_verify) client = Client(ssl_verification_mode=ssl_verification_meta_data.mode, connection_info=ConjurrcData.load_from_file().get_client_connection_info(), debug=args.debug, credentials_provider=self.credential_provider, async_mode=False) if resource == 'list': cli_actions.handle_list_logic(args, client) elif resource == 'whoami': result = client.whoami() print(json.dumps(result, indent=4)) elif resource == 'variable': cli_actions.handle_variable_logic(args, client) elif resource == 'policy': policy_data = PolicyData(action=args.action, branch=args.branch, file=args.file) cli_actions.handle_policy_logic(policy_data, client) elif resource == 'user': cli_actions.handle_user_logic(self.credential_provider, args, client) elif resource == 'host': cli_actions.handle_host_logic(args, client) elif resource == 'hostfactory': cli_actions.handle_hostfactory_logic(args, client)
def test_user_rotate_api_key_without_param_rotates_logged_in_user(self): some_user_api_key = self.invoke_cli( self.cli_auth_params, ['user', 'rotate-api-key', '-i', 'someuser']) # extract the API key from the returned message extract_api_key_from_message = some_user_api_key.split(":")[1].strip() self.invoke_cli( self.cli_auth_params, ['login', '-i', 'someuser', '-p', extract_api_key_from_message]) credential_store = CredentialStoreFactory.create_credential_store() loaded_conjurrc = ConjurrcData.load_from_file() old_api_key = credential_store.load( loaded_conjurrc.conjur_url).password some_user_api_key = self.invoke_cli(self.cli_auth_params, ['user', 'rotate-api-key']) extract_api_key_from_message = some_user_api_key.split(":")[1].strip() assert old_api_key != extract_api_key_from_message, "the API keys are the same!" credential_store = CredentialStoreFactory.create_credential_store() new_api_key = credential_store.load( loaded_conjurrc.conjur_url).password assert new_api_key.strip( ) == extract_api_key_from_message, "the API keys are not the same!"
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
def get_credentials() -> CredentialsData: try: cred_store = create_cred_store() conjurrc = ConjurrcData.load_from_file() return cred_store.load(conjurrc.conjur_url) except: print("Unable to fetch credentials")
def is_credentials_exist(conjur_url=None) -> bool: try: cred_store = create_cred_store() if conjur_url is None: conjur_url = ConjurrcData.load_from_file().conjur_url return cred_store.is_exists(conjur_url) except: print("Unable to validate that credentials exist")
def delete_credentials(): try: cred_store = create_cred_store() conjurrc = ConjurrcData.load_from_file() if cred_store.is_exists(conjurrc.conjur_url): return cred_store.remove_credentials(conjurrc.conjur_url) except: # this is a util test not throwing for now. user should make sure conjurrc file exists pass
def _perofrm_auth_if_not_login(self, args): self._run_init_if_not_occur() # If the user runs a command without logging into the CLI, # we request they do so before executing their request if not self.is_testing_env: loaded_conjurrc = ConjurrcData.load_from_file() if not self.credential_provider.is_exists(loaded_conjurrc.conjur_url): # The below message when a user implicitly requested to init # pylint: disable=logging-fstring-interpolation sys.stdout.write(f"{LOGIN_IS_REQUIRED}\n") cli_actions.handle_login_logic(self.credential_provider, ssl_verify=args.ssl_verify)
def test_raise_CertificateVerificationException_on_HttpSslError(self): with self.assertRaises(CertificateVerificationException): with patch('conjur_api.Client.login', side_effect=HttpSslError) as mock: mock_credential_store = FileCredentialsProvider() mock_login_logic = LoginLogic(mock_credential_store) ssl_verification_metadata = SslVerificationMetadata( SslVerificationMode.TRUST_STORE) mock_login_logic.get_api_key(ssl_verification_metadata, MockCredentialsData, 'somepass', ConjurrcData())
def fetch_account_from_server( cls, conjurrc_data: ConjurrcData, ssl_verification_metadata: SslVerificationMetadata): """ Fetches the account from the Conjur Enterprise server by making a request to the /info endpoint. This endpoint only exists in the Conjur Enterprise server """ logging.debug( "Attempting to fetch the account from the Conjur server...") client = Client( connection_info=conjurrc_data.get_client_connection_info(), ssl_verification_mode=ssl_verification_metadata.mode, credentials_provider=SimpleCredentialsProvider(), async_mode=False) response = client.get_server_info() conjurrc_data.conjur_account = response['configuration']['conjur'][ 'account'] logging.debug( "Account '%s' successfully fetched from the Conjur server", conjurrc_data.conjur_account)
def handle_init_logic(url: str = None, account: str = None, cert: str = None, force: bool = None, ssl_verify=None, is_self_signed: bool = False): """ Method that wraps the init call logic Initializes the client, creating the .conjurrc file """ try: init_utils.validate_init_action_ssl_verification_input( cert, is_self_signed, ssl_verify) except ConflictingParametersException: raise ConflictingParametersException( "Can't accept more than one of the following " "arguments:" "\n1. --ca-cert" "\n2. --self-signed" "\n3. --insecure (skip certificate validation)") except FileNotFoundException: raise FileNotFoundException( f"Couldn't find '{cert}'. Make sure correct path is provided") except InvalidFilePermissionsException: raise InvalidFilePermissionsException(f"No read access for: {cert}") ssl_verification_data = init_utils.get_ssl_verification_meta_data_from_cli_params( cert, is_self_signed, ssl_verify) ssl_service = SSLClient() # TODO conjurrcData creation should move to controller conjurrc_data = ConjurrcData(conjur_url=url, account=account, cert_file=cert) init_logic = InitLogic(ssl_service) input_controller = InitController( conjurrc_data=conjurrc_data, init_logic=init_logic, force=force, ssl_verification_data=ssl_verification_data) input_controller.load()
import conjur_api from conjur_api.models import SslVerificationMetadata, SslVerificationMode, ConjurConnectionInfo from conjur_api.errors.errors import HttpSslError from conjur.data_object import ConjurrcData from conjur.errors import CertificateVerificationException from conjur.logic.credential_provider.file_credentials_provider import FileCredentialsProvider from conjur.logic.login_logic import LoginLogic class MockCredentialsData: machine = 'https://someurl' username = '******' password = '******' MockConjurrc = ConjurrcData('https://someurl', 'someacc', 'some/path/to/pem') class MockConjurrcEmptyCertEntry: conjur_url = 'https://someurl' conjur_account = 'someacc' cert_file = '' class MockClientResponse: def __init__(self, text='myretval', content='mycontent'): setattr(self, 'content', content.encode('utf-8')) setattr(self, 'text', text) class LoginLogicTest(unittest.TestCase):
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) @patch.object(KeystoreWrapper, 'set_password', side_effect=Exception)
def test_get_ssl_verification_meta_data_from_conjurrc_self_sign(self): data = ConjurrcData(conjur_url="https://foo.com", account="some_account", cert_file=DEFAULT_CERTIFICATE_FILE) res = utils.get_ssl_verification_meta_data_from_conjurrc(True, data) self.assertEquals(res.mode, SslVerificationMode.SELF_SIGN)
def test_get_ssl_verification_meta_data_from_conjurrc_trust_store(self): data = ConjurrcData(conjur_url="https://foo.com", account="some_account", cert_file="") res = utils.get_ssl_verification_meta_data_from_conjurrc(True, data) self.assertEquals(res.mode, SslVerificationMode.TRUST_STORE)
def test_get_ssl_verification_meta_data_from_conjurrc_ca_bundle(self): data = ConjurrcData(conjur_url="https://foo.com", account="some_account", cert_file="cert") res = utils.get_ssl_verification_meta_data_from_conjurrc(True, data) self.assertEquals(res.mode, SslVerificationMode.CA_BUNDLE)
def test_logout_remove_credentials_calls_remove_credentials( self, mock_credentials): conjurrc = ConjurrcData("someurl") mock_logout_logic = LogoutLogic(mock_credentials) mock_logout_logic.remove_credentials(conjurrc) mock_credentials.remove_credentials.assert_called_once_with("someurl")
def test_get_ssl_verification_meta_data_from_conjurrc_no_ssl(self): data = ConjurrcData(conjur_url="https://foo.com", account="some_account", cert_file="cert") res = utils.get_ssl_verification_meta_data_from_conjurrc(False, data) self.assertEquals(res.mode, SslVerificationMode.INSECURE)