def test_authenticate_success(self): cs = client.Client("username", "password", "project_id", "auth_url") management_url = 'https://localhost/v1.1/443470' auth_response = utils.TestResponse({ 'status_code': 204, 'headers': { 'x-server-management-url': management_url, 'x-auth-token': '1b751d74-de0c-46ae-84f0-915744b582d1', }, }) mock_request = mock.Mock(return_value=(auth_response)) @mock.patch.object(requests, "request", mock_request) def test_auth_call(): cs.client.authenticate() headers = { 'Accept': 'application/json', 'X-Auth-User': '******', 'X-Auth-Key': 'password', 'X-Auth-Project-Id': 'project_id', 'User-Agent': cs.client.USER_AGENT } mock_request.assert_called_with("GET", cs.client.auth_url, headers=headers, **self.TEST_REQUEST_BASE) self.assertEqual(cs.client.management_url, auth_response.headers['x-server-management-url']) self.assertEqual(cs.client.auth_token, auth_response.headers['x-auth-token']) test_auth_call()
def test_ambiguous_endpoints(self): cs = client.Client("username", "password", "project_id", "auth_url/v2.0", service_type='compute') resp = { "access": { "token": { "expires": "12345", "id": "FAKE_ID", }, "serviceCatalog": [ { "adminURL": "http://*****:*****@mock.patch.object(requests, "request", mock_request) def test_auth_call(): self.assertRaises(exceptions.AmbiguousEndpoints, cs.client.authenticate) test_auth_call()
def test_auth_manual(self): cs = client.Client("username", "password", "project_id", "auth_url") @mock.patch.object(cs.client, 'authenticate') def test_auth_call(m): cs.authenticate() m.assert_called() test_auth_call()
def test_authenticate_failure(self): cs = client.Client("username", "password", "project_id", "auth_url") auth_response = utils.TestResponse({"status_code": 401}) mock_request = mock.Mock(return_value=(auth_response)) @mock.patch.object(requests, "request", mock_request) def test_auth_call(): self.assertRaises(exceptions.Unauthorized, cs.client.authenticate) test_auth_call()
def test_auth_automatic(self): cs = client.Client("username", "password", "project_id", "auth_url") http_client = cs.client http_client.management_url = '' mock_request = mock.Mock(return_value=(None, None)) @mock.patch.object(http_client, 'request', mock_request) @mock.patch.object(http_client, 'authenticate') def test_auth_call(m): http_client.get('/') m.assert_called() mock_request.assert_called() test_auth_call()
def test_authenticate_failure(self): cs = client.Client("username", "password", "project_id", "auth_url/v2.0") resp = {"unauthorized": {"message": "Unauthorized", "code": "401"}} auth_response = utils.TestResponse({ "status_code": 401, "text": json.dumps(resp), }) mock_request = mock.Mock(return_value=(auth_response)) @mock.patch.object(requests, "request", mock_request) def test_auth_call(): self.assertRaises(exceptions.Unauthorized, cs.client.authenticate) test_auth_call()
from monitorclient.v1 import client ec = client.Client('monitor', 'keystone_monitor_password', 'service', 'http://192.168.111.11:5000/v2.0/') ret = ec.monitors.test_service() print ret
def test_authenticate_tenant_id(self): cs = client.Client("username", "password", auth_url="auth_url/v2.0", tenant_id='tenant_id', service_type='compute') resp = { "access": { "token": { "expires": "12345", "id": "FAKE_ID", "tenant": { "description": None, "enabled": True, "id": "tenant_id", "name": "demo" } # tenant associated with token }, "serviceCatalog": [ { "type": "compute", "endpoints": [ { "region": "RegionOne", "adminURL": "http://*****:*****@mock.patch.object(requests, "request", mock_request) def test_auth_call(): cs.client.authenticate() headers = { 'User-Agent': cs.client.USER_AGENT, 'Content-Type': 'application/json', 'Accept': 'application/json', } body = { 'auth': { 'passwordCredentials': { 'username': cs.client.user, 'password': cs.client.password, }, 'tenantId': cs.client.tenant_id, }, } token_url = cs.client.auth_url + "/tokens" mock_request.assert_called_with("POST", token_url, headers=headers, data=json.dumps(body), allow_redirects=True, **self.TEST_REQUEST_BASE) endpoints = resp["access"]["serviceCatalog"][0]['endpoints'] public_url = endpoints[0]["publicURL"].rstrip('/') self.assertEqual(cs.client.management_url, public_url) token_id = resp["access"]["token"]["id"] self.assertEqual(cs.client.auth_token, token_id) tenant_id = resp["access"]["token"]["tenant"]["id"] self.assertEqual(cs.client.tenant_id, tenant_id) test_auth_call()
def test_auth_redirect(self): cs = client.Client("username", "password", "project_id", "auth_url/v1", service_type='compute') dict_correct_response = { "access": { "token": { "expires": "12345", "id": "FAKE_ID", }, "serviceCatalog": [ { "type": "compute", "endpoints": [ { "adminURL": "http://*****:*****@mock.patch.object(requests, "request", mock_request) def test_auth_call(): cs.client.authenticate() headers = { 'User-Agent': cs.client.USER_AGENT, 'Content-Type': 'application/json', 'Accept': 'application/json', } body = { 'auth': { 'passwordCredentials': { 'username': cs.client.user, 'password': cs.client.password, }, 'tenantName': cs.client.projectid, }, } token_url = cs.client.auth_url + "/tokens" mock_request.assert_called_with("POST", token_url, headers=headers, data=json.dumps(body), allow_redirects=True, **self.TEST_REQUEST_BASE) resp = dict_correct_response endpoints = resp["access"]["serviceCatalog"][0]['endpoints'] public_url = endpoints[0]["publicURL"].rstrip('/') self.assertEqual(cs.client.management_url, public_url) token_id = resp["access"]["token"]["id"] self.assertEqual(cs.client.auth_token, token_id) test_auth_call()
def __init__(self, app, conf): #self.LOG = logging.getLogger(conf.get('log_name', __name__)) logger = logging.getLogger() handler = logging.FileHandler("/var/log/monitor/monitor-client.log") logger.addHandler(handler) logger.setLevel(logging.NOTSET) self.LOG = logger self.LOG.info('Starting monitor auth_token middleware') self.conf = conf self.app = app # delay_auth_decision means we still allow unauthenticated requests # through and we let the downstream service make the final decision self.delay_auth_decision = (self._conf_get('delay_auth_decision') in (True, 'true', 't', '1', 'on', 'yes', 'y')) # where to find the auth service (we use this to validate tokens) self.auth_host = self._conf_get('auth_host') self.auth_port = int(self._conf_get('auth_port')) self.auth_protocol = self._conf_get('auth_protocol') if not self._conf_get('http_handler'): if self.auth_protocol == 'http': self.http_client_class = httplib.HTTPConnection else: self.http_client_class = httplib.HTTPSConnection else: # Really only used for unit testing, since we need to # have a fake handler set up before we issue an http # request to get the list of versions supported by the # server at the end of this initialization self.http_client_class = self._conf_get('http_handler') self.auth_admin_prefix = self._conf_get('auth_admin_prefix') self.auth_uri = self._conf_get('auth_uri') if self.auth_uri is None: self.auth_uri = '%s://%s:%s' % (self.auth_protocol, self.auth_host, self.auth_port) # SSL self.cert_file = self._conf_get('certfile') self.key_file = self._conf_get('keyfile') # signing self.signing_dirname = self._conf_get('signing_dir') if self.signing_dirname is None: self.signing_dirname = tempfile.mkdtemp(prefix='monitor-signing-') self.LOG.info('Using %s as cache directory for signing certificate' % self.signing_dirname) if os.path.exists(self.signing_dirname): if not os.access(self.signing_dirname, os.W_OK): raise ConfigurationError('unable to access signing_dir %s' % self.signing_dirname) if os.stat(self.signing_dirname).st_uid != os.getuid(): self.LOG.warning('signing_dir is not owned by %s' % os.getlogin()) current_mode = stat.S_IMODE(os.stat(self.signing_dirname).st_mode) if current_mode != stat.S_IRWXU: self.LOG.warning('signing_dir mode is %s instead of %s' % (oct(current_mode), oct(stat.S_IRWXU))) else: os.makedirs(self.signing_dirname, stat.S_IRWXU) val = '%s/signing_cert.pem' % self.signing_dirname self.signing_cert_file_name = val val = '%s/cacert.pem' % self.signing_dirname self.ca_file_name = val val = '%s/revoked.pem' % self.signing_dirname self.revoked_file_name = val # Credentials used to verify this component with the Auth service since # validating tokens is a privileged call self.admin_token = self._conf_get('admin_token') self.admin_token_expiry = None self.admin_user = self._conf_get('admin_user') self.admin_password = self._conf_get('admin_password') self.admin_tenant_name = self._conf_get('admin_tenant_name') auth_url = 'http://%s:5000/v2.0/' % self.auth_host self.ec = client.Client(self.admin_user, self.admin_password, self.admin_tenant_name, auth_url) # Token caching via memcache self._cache = None self._use_monitor_cache = False self._cache_initialized = False # cache already initialzied? # memcache value treatment, ENCRYPT or MAC self._memcache_security_strategy = \ self._conf_get('memcache_security_strategy') if self._memcache_security_strategy is not None: self._memcache_security_strategy = \ self._memcache_security_strategy.upper() self._memcache_secret_key = \ self._conf_get('memcache_secret_key') self._assert_valid_memcache_protection_config() # By default the token will be cached for 5 minutes self.token_cache_time = int(self._conf_get('token_cache_time')) self._token_revocation_list = None self._token_revocation_list_fetched_time = None self.token_revocation_list_cache_timeout = datetime.timedelta( seconds=self._conf_get('revocation_cache_time')) http_connect_timeout_cfg = self._conf_get('http_connect_timeout') self.http_connect_timeout = (http_connect_timeout_cfg and int(http_connect_timeout_cfg)) self.auth_version = None