diff --git a/ipa/ipa_gce.py b/ipa/ipa_gce.py index 2b1426ce..831dc397 100644 --- a/ipa/ipa_gce.py +++ b/ipa/ipa_gce.py @@ -133,8 +133,21 @@ def _get_service_account_info(self): with open(self.service_account_file, 'r') as f: info = json.load(f) - self.service_account_email = info['client_email'] - self.service_account_project = info['project_id'] + self.service_account_email = info.get('client_email') + if not self.service_account_email: + raise GCEProviderException( + 'Service account JSON file is invalid for GCE. ' + 'client_email key is expected. See getting started ' + 'docs for information on GCE configuration.' + ) + + self.service_account_project = info.get('project_id') + if not self.service_account_project: + raise GCEProviderException( + 'Service account JSON file is invalid for GCE. ' + 'project_id key is expected. See getting started ' + 'docs for information on GCE configuration.' + ) def _get_driver(self): """Get authenticated GCE driver.""" diff --git a/tests/gce/invalid-service-account.json b/tests/gce/invalid-service-account.json new file mode 100644 index 00000000..b55217cd --- /dev/null +++ b/tests/gce/invalid-service-account.json @@ -0,0 +1,11 @@ +{ + "type": "service_account", + "project_id": "test", + "private_key_id": "1111", + "private_key": "", + "client_id": "1111", + "auth_uri": "https://accounts.google.com/o/oauth2/auth", + "token_uri": "https://accounts.google.com/o/oauth2/token", + "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs", + "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/test%40test.iam.gserviceaccount.com" +} diff --git a/tests/test_ipa_gce.py b/tests/test_ipa_gce.py index cb935586..29e54c55 100644 --- a/tests/test_ipa_gce.py +++ b/tests/test_ipa_gce.py @@ -85,6 +85,29 @@ def test_gce_get_service_account_info(self, 'test@test.iam.gserviceaccount.com' assert provider.service_account_project == 'test' + @patch.object(GCEProvider, '_get_ssh_public_key') + @patch.object(GCEProvider, '_get_driver') + def test_gce_get_service_account_info_invalid( + self, + mock_get_driver, + mock_get_ssh_key + ): + """Test get service account info method.""" + mock_get_driver.return_value = None + mock_get_ssh_key.return_value = None + provider = GCEProvider(**self.kwargs) + + provider.service_account_file = \ + 'tests/gce/invalid-service-account.json' + + with pytest.raises(GCEProviderException) as error: + provider._get_service_account_info() + + msg = 'Service account JSON file is invalid for GCE. ' \ + 'client_email key is expected. See getting started ' \ + 'docs for information on GCE configuration.' + assert str(error.value) == msg + @patch.object(GCEProvider, '_get_ssh_public_key') @patch('libcloud.compute.drivers.gce.GCENodeDriver') def test_gce_get_driver(self,