def SetUp(self): self.adc_file_path = os.path.join(self.temp_path, 'application_default_credentials.json') self.StartObjectPatch( config, 'ADCFilePath', return_value=self.adc_file_path) self.user_creds = creds.FromJson(self.USER_CREDENTIALS_JSON) self.service_creds = creds.FromJson(self.SERVICE_ACCOUNT_CREDENTIALS_JSON) self.p12_service_creds = self.MakeP12ServiceAccountCredentials()
def SetUp(self): self.adc_file_path = os.path.join(self.temp_path, 'application_default_credentials.json') self.StartObjectPatch( config, 'ADCFilePath', return_value=self.adc_file_path) # Mocks the signer of service account credentials. signer = self.StartPatch('oauth2client.crypt.Signer', autospec=True) self.StartObjectPatch(crypt, 'OpenSSLSigner', new=signer) self.user_creds = creds.FromJson(self.USER_CREDENTIALS_JSON) self.service_creds = creds.FromJson(self.SERVICE_ACCOUNT_CREDENTIALS_JSON) self.p12_service_creds = self.MakeP12ServiceAccountCredentials()
def testSetQuotaProject_ExistingServiceCreds(self): creds.ADC(creds.FromJson(_GetJsonServiceADC())).DumpADCToFile() with self.AssertRaisesExceptionMatches( exceptions.BadFileException, 'The application default credentials are not user credentials' ): self.RunSetQuotaProject()
def testLoginWithQuotaProject_WithClientID(self): client_id_file = self.Resource('tests', 'unit', 'surface', 'auth', 'test_data', 'client_id_file.json') self.mock_run_webflow.return_value = creds.FromJson(_GetJsonUserADC()) self.Login(more_args='--client-id-file {file}'.format(file=client_id_file)) self.AssertFileEquals(_GetJsonUserADC(), os.path.join(self.temp_path, 'ADC'))
def testLoginWithWriteToADC_ServiceCreds(self): self.mock_load.return_value = creds.FromJson(_GetJsonServiceADC()) self.Run('auth login [email protected] --update-adc') self.AssertFileNotExists(self.adc_file_path) self.AssertErrContains('Credentials cannot be written') self.AssertErrNotContains('Application default credentials (ADC) were ' 'updated.')
def testWriteGcloudCredentialsToADC_UserCredsWithQuotaProject(self): auth_util.WriteGcloudCredentialsToADC( creds.FromJson(self.USER_CREDENTIALS_JSON), add_quota_project=True) self.AssertErrEquals('') self.AssertFileEquals(self.EXTENDED_USER_CREDENTIALS_JSON, self.adc_file_path) self.mock_prompt.assert_called()
def testLoginAddQuotaProjectWithoutUpdateADC(self): self.mock_load.return_value = creds.FromJson(_GetJsonUserADC()) with self.AssertRaisesExceptionMatches( calliope_exceptions.InvalidArgumentException, '--add-quota-project-to-adc cannot be specified without specifying ' '--update-adc'): self.Run('auth login [email protected] --add-quota-project-to-adc')
def testSetQuotaProject_ExistingUserCreds_NoPermission(self): creds.ADC(creds.FromJson(_GetJsonUserADC())).DumpADCToFile() self.adc_permission_checking.return_value = False with self.AssertRaisesExceptionMatches( auth_util.MissingPermissionOnQuotaProjectError, 'ADC does not have the "serviceusage.services.use" permission' ): self.RunSetQuotaProject()
def testLoginWithWriteToADC_UserCredsWithQuotaProject(self): self.mock_load.return_value = creds.FromJson(_GetJsonUserADC()) self.Run( 'auth login [email protected] --update-adc --add-quota-project-to-adc') self.AssertFileEquals(self.EXTENDED_USER_CREDENTIALS_JSON, self.adc_file_path) self.AssertErrContains( "'my project' is added to ADC as the quota project")
def testLoginWithQuotaProject(self): self.StartObjectPatch( command_auth_util, 'AdcHasGivenPermissionOnProject', return_value=True) self.mock_webflow.return_value = creds.FromJson(_GetJsonUserADC()) self.Login(disable_quota_project=False) self.AssertFileEquals(_GetJsonUserExtendedADC(), os.path.join(self.temp_path, 'ADC')) self.AssertErrContains('Quota project "fake-project" was added to ADC')
def MakeP12ServiceAccountCredentials(self): """Returns P12 service account credentials.""" expiry = datetime.datetime(2001, 2, 3, 14, 15, 16) token_response = {'id_token': 'id-token'} credentials = creds.FromJson(self.P12_SERVICE_ACCOUNT_CREDENTIALS_JSON) credentials.access_token = 'access_token' credentials.token_expiry = expiry credentials.token_response = token_response return credentials
def testLoginWithWriteToADC_UserCreds_CannotFindQuotaProject(self): self.StartObjectPatch(creds, 'GetQuotaProject', return_value=None) self.mock_load.return_value = creds.FromJson(_GetJsonUserADC()) self.Run( 'auth login [email protected] --update-adc --add-quota-project-to-adc') self.AssertFileEquals(_GetJsonUserADC(), self.adc_file_path) self.AssertErrContains( 'Cannot find a project to insert into application ' 'default credentials (ADC) as a quota project')
def testDumpADCRequiredQuotaProject_WithoutPermission(self): self.adc_permission_checking.return_value = False auth_util.WriteGcloudCredentialsToADC( creds.FromJson(self.USER_CREDENTIALS_JSON)) with self.AssertRaisesExceptionMatches( auth_util.MissingPermissionOnQuotaProjectError, 'Cannot add the project "{}" to application default credentials' .format(self.fake_project)): auth_util.AddQuotaProjectToADC(self.fake_project) self.adc_permission_checking.assert_called()
def testDumpADCRequiredQuotaProject_WithPermission(self): self.adc_permission_checking.return_value = True auth_util.WriteGcloudCredentialsToADC( creds.FromJson(self.USER_CREDENTIALS_JSON)) auth_util.AddQuotaProjectToADC(self.fake_project) auth_util.AssertADCExists() self.AssertQuotaProjectEquals(self.fake_project) self.AssertErrContains('Credentials saved to file') self.AssertErrContains('Quota project "{}" was added to ADC'.format( self.fake_project)) self.adc_permission_checking.assert_called()
def testAccessTokenCacheReadonlyRemove(self): access_token_cache = creds.AccessTokenCache( config.Paths().access_token_db_path) credentials = creds.FromJson(self.SERVICE_ACCOUNT_CREDENTIALS_JSON) self.StartObjectPatch( access_token_cache, '_Execute', side_effect=sqlite3.OperationalError( 'attempt to write to read-only database')) access_token_cache.Remove(credentials.service_account_email) self.AssertLogContains('Could not delete access token from cache: ' 'attempt to write to read-only database')
def testFromJson_UserAccount(self): credentials = creds.FromJson(self.USER_CREDENTIALS_JSON) self.AssertCredentialsEqual( credentials, { 'client_id': 'foo.apps.googleusercontent.com', 'client_secret': 'file-secret', 'refresh_token': 'file-token' }) creds_type = creds.CredentialType.FromCredentials(credentials) self.assertEqual(creds.CredentialType.USER_ACCOUNT, creds_type)
def testFromJson_P12ServiceAccount(self): credentials = creds.FromJson(self.P12_SERVICE_ACCOUNT_CREDENTIALS_JSON) self.AssertCredentialsEqual( credentials, { '_service_account_email': '*****@*****.**', '_private_key_password': '******', '_private_key_pkcs12': b'BASE64ENCODED', }) creds_type = creds.CredentialType.FromCredentials(credentials) self.assertEqual(creds.CredentialType.P12_SERVICE_ACCOUNT, creds_type)
def testFromJson_P12ServiceAccount(self): signer = self.StartPatch('oauth2client.crypt.Signer', autospec=True) self.StartObjectPatch(crypt, 'OpenSSLSigner', new=signer) credentials = creds.FromJson(self.P12_SERVICE_ACCOUNT_CREDENTIALS_JSON) self.AssertCredentialsEqual( credentials, { '_service_account_email': '*****@*****.**', '_private_key_password': '******', '_private_key_pkcs12': b'BASE64ENCODED', }) creds_type = creds.CredentialType.FromCredentials(credentials) self.assertEqual(creds.CredentialType.P12_SERVICE_ACCOUNT, creds_type)
def testFromJson_ServiceAccount(self): credentials = creds.FromJson(self.SERVICE_ACCOUNT_CREDENTIALS_JSON) self.AssertCredentialsEqual( credentials, { 'client_id': 'bar.apps.googleusercontent.com', '_service_account_email': '*****@*****.**', '_private_key_id': 'key-id', '_private_key_pkcs8_pem': '-----BEGIN PRIVATE KEY-----\nasdf\n-----END PRIVATE KEY-----\n', }) creds_type = creds.CredentialType.FromCredentials(credentials) self.assertEqual(creds.CredentialType.SERVICE_ACCOUNT, creds_type)
def testAdcHasGivenPermissionOnQuotaProject_HasPermission(self): self.SetUpApitoolsClientMock() auth_util.WriteGcloudCredentialsToADC( creds.FromJson(self.USER_CREDENTIALS_JSON)) requested_permissions = ['storage.buckets.create'] expected_permissions = ['storage.buckets.create'] self.mock_client.projects.TestIamPermissions.Expect( self.messages.CloudresourcemanagerProjectsTestIamPermissionsRequest( resource=self.fake_project, testIamPermissionsRequest=self.messages.TestIamPermissionsRequest( permissions=requested_permissions)), self.messages.TestIamPermissionsResponse( permissions=expected_permissions)) res = auth_util.AdcHasGivenPermissionOnProject(self.fake_project, requested_permissions) self.assertTrue(res)
def testAttachAccessTokenCacheStore(self): access_token_cache = creds.AccessTokenCache( config.Paths().access_token_db_path) credentials = creds.FromJson(self.SERVICE_ACCOUNT_CREDENTIALS_JSON) credentials.token_response = json.loads("""{"id_token": "woweee"}""") self.assertIsNone(credentials.access_token) access_token_cache.Store( credentials.service_account_email, access_token='token1', token_expiry=datetime.datetime.utcnow() + datetime.timedelta(seconds=3600), rapt_token=None, id_token=None) self.assertIsNone(credentials.access_token) new_cred = creds.MaybeAttachAccessTokenCacheStore(credentials) self.assertIsNone(new_cred.token_response) self.assertEqual('token1', new_cred.access_token)
def testAccessTokenCacheReadonlyStore(self): access_token_cache = creds.AccessTokenCache( config.Paths().access_token_db_path) credentials = creds.FromJson(self.SERVICE_ACCOUNT_CREDENTIALS_JSON) credentials.token_response = json.loads("""{"id_token": "woweee"}""") self.assertIsNone(credentials.access_token) self.StartObjectPatch( access_token_cache, '_Execute', side_effect=sqlite3.OperationalError( 'attempt to write to read-only database')) access_token_cache.Store( credentials.service_account_email, access_token='token1', token_expiry=datetime.datetime.utcnow() + datetime.timedelta(seconds=3600), rapt_token=None, id_token=None) self.AssertLogContains('Could not store access token in cache: ' 'attempt to write to read-only database')
def testGetQuotaProjectFromADC_NoQuotaProject(self): creds.ADC(creds.FromJson(self.USER_CREDENTIALS_JSON)).DumpADCToFile() self.assertIsNone(auth_util.GetQuotaProjectFromADC())
def testToJson_UserAccount(self): json_data = self.USER_CREDENTIALS_JSON credentials = creds.FromJson(json_data) self.assertMultiLineEqual(json_data, creds.ToJson(credentials))
def testLoginWithoutQuotaProject(self): self.mock_webflow.return_value = creds.FromJson(_GetJsonUserADC()) self.Login() self.AssertFileEquals(_GetJsonUserADC(), os.path.join(self.temp_path, 'ADC'))
def testGetQuotaProjectFromADC_QuotaProjectExists(self): creds.ADC(creds.FromJson( self.USER_CREDENTIALS_JSON)).DumpExtendedADCToFile() self.assertEqual(auth_util.GetQuotaProjectFromADC(), 'my project')
def testWriteGcloudCredentialsToADC_UserCreds(self): auth_util.WriteGcloudCredentialsToADC( creds.FromJson(self.USER_CREDENTIALS_JSON)) self.AssertErrEquals('') self.AssertFileEquals(self.USER_CREDENTIALS_JSON, self.adc_file_path) self.mock_prompt.assert_called()
def testWriteGcloudCredentialsToADC_ServiceCreds(self): auth_util.WriteGcloudCredentialsToADC( creds.FromJson(self.SERVICE_ACCOUNT_CREDENTIALS_JSON)) self.AssertErrContains('Credentials cannot be written') self.AssertFileNotExists(self.adc_file_path) self.mock_prompt.assert_not_called()
def testLoginWithWriteToADC_UserCreds(self): self.mock_load.return_value = creds.FromJson(_GetJsonUserADC()) self.Run('auth login [email protected] --update-adc') self.AssertFileEquals(_GetJsonUserADC(), self.adc_file_path) self.AssertErrNotContains( "'my project' is added to ADC as the quota project")
def testSetQuotaProject_ExistingUserCreds(self): creds.ADC(creds.FromJson(_GetJsonUserADC())).DumpADCToFile() self.RunSetQuotaProject() self.AssertFileEquals(_GetJsonUserExtendedADC(), self.adc_file_path) self.AssertErrContains('Quota project "fake-project" was added to ADC')