def test_will_expire_soon(self):
     expires = timeutils.utcnow() + datetime.timedelta(minutes=5)
     UNSCOPED_TOKEN["access"]["token"]["expires"] = expires.isoformat()
     auth_ref = access.AccessInfo.factory(body=UNSCOPED_TOKEN)
     self.assertFalse(auth_ref.will_expire_soon(stale_duration=120))
     self.assertTrue(auth_ref.will_expire_soon(stale_duration=300))
     self.assertFalse(auth_ref.will_expire_soon())
 def test_will_expire_soon(self):
     expires = timeutils.utcnow() + datetime.timedelta(minutes=5)
     UNSCOPED_TOKEN['access']['token']['expires'] = expires.isoformat()
     auth_ref = access.AccessInfo(UNSCOPED_TOKEN['access'])
     self.assertFalse(auth_ref.will_expire_soon(stale_duration=120))
     self.assertTrue(auth_ref.will_expire_soon(stale_duration=300))
     self.assertFalse(auth_ref.will_expire_soon())
    def test_set_and_get_keyring_expired(self):
        cl = httpclient.HTTPClient(username=USERNAME,
                                   password=PASSWORD,
                                   tenant_id=TENANT_ID,
                                   auth_url=AUTH_URL,
                                   use_keyring=True)

        # set an expired token into the keyring
        auth_ref = access.AccessInfo.factory(body=PROJECT_SCOPED_TOKEN)
        expired = timeutils.utcnow() - datetime.timedelta(minutes=30)
        auth_ref['token']['expires'] = timeutils.isotime(expired)
        self.memory_keyring.password = pickle.dumps(auth_ref)

        # stub and check that a new token is received, so not using expired
        with mock.patch.object(cl, 'get_raw_token_from_identity_service') \
                as meth:
            meth.return_value = (True, PROJECT_SCOPED_TOKEN)

            self.assertTrue(cl.authenticate())

            meth.assert_called_once()

        # check that a value was returned from the keyring
        self.assertTrue(self.memory_keyring.fetched)

        # check that the new token has been loaded into the keyring
        new_auth_ref = pickle.loads(self.memory_keyring.password)
        self.assertEqual(new_auth_ref['token']['expires'],
                         PROJECT_SCOPED_TOKEN['access']['token']['expires'])
Example #4
0
    def test_authenticate_success_expired(self):
        # Build an expired token
        self.TEST_RESPONSE_DICT['access']['token']['expires'] = \
            (timeutils.utcnow() - datetime.timedelta(1)).isoformat()

        exp_resp = httpretty.Response(body=json.dumps(self.TEST_RESPONSE_DICT),
                                      content_type='application/json')

        # Build a new response
        TEST_TOKEN = "abcdef"
        self.TEST_RESPONSE_DICT['access']['token']['expires'] = \
            '2020-01-01T00:00:10.000123Z'
        self.TEST_RESPONSE_DICT['access']['token']['id'] = TEST_TOKEN

        new_resp = httpretty.Response(body=json.dumps(self.TEST_RESPONSE_DICT),
                                      content_type='application/json')

        # return expired first, and then the new response
        self.stub_auth(responses=[exp_resp, new_resp])

        cs = client.Client(tenant_id=self.TEST_TENANT_ID,
                           auth_url=self.TEST_URL,
                           username=self.TEST_USER,
                           password=self.TEST_TOKEN)

        self.assertEqual(
            cs.management_url, self.TEST_RESPONSE_DICT["access"]
            ["serviceCatalog"][3]['endpoints'][0]["adminURL"])

        self.assertEqual(cs.auth_token, TEST_TOKEN)
        self.assertRequestBodyIs(json=self.TEST_REQUEST_BODY)
    def test_authenticate_success_expired(self):
        # Build an expired token
        self.TEST_RESPONSE_DICT['access']['token']['expires'] = (
            (timeutils.utcnow() - datetime.timedelta(1)).isoformat())

        exp_resp = httpretty.Response(body=json.dumps(self.TEST_RESPONSE_DICT),
                                      content_type='application/json')

        # Build a new response
        TEST_TOKEN = "abcdef"
        self.TEST_RESPONSE_DICT['access']['token']['expires'] = (
            '2020-01-01T00:00:10.000123Z')
        self.TEST_RESPONSE_DICT['access']['token']['id'] = TEST_TOKEN

        new_resp = httpretty.Response(body=json.dumps(self.TEST_RESPONSE_DICT),
                                      content_type='application/json')

        # return expired first, and then the new response
        self.stub_auth(responses=[exp_resp, new_resp])

        cs = client.Client(tenant_id=self.TEST_TENANT_ID,
                           auth_url=self.TEST_URL,
                           username=self.TEST_USER,
                           password=self.TEST_TOKEN)

        self.assertEqual(cs.management_url,
                         self.TEST_RESPONSE_DICT["access"]["serviceCatalog"][3]
                         ['endpoints'][0]["adminURL"])

        self.assertEqual(cs.auth_token, TEST_TOKEN)
        self.assertRequestBodyIs(json=self.TEST_REQUEST_BODY)
    def test_set_and_get_keyring_expired(self):
        cl = httpclient.HTTPClient(username=USERNAME, password=PASSWORD,
                                   tenant_id=TENANT_ID, auth_url=AUTH_URL,
                                   use_keyring=True)

        # set an expired token into the keyring
        auth_ref = access.AccessInfo.factory(body=PROJECT_SCOPED_TOKEN)
        expired = timeutils.utcnow() - datetime.timedelta(minutes=30)
        auth_ref['token']['expires'] = timeutils.isotime(expired)
        self.memory_keyring.password = pickle.dumps(auth_ref)

        # stub and check that a new token is received, so not using expired
        with mock.patch.object(cl, 'get_raw_token_from_identity_service') \
                as meth:
            meth.return_value = (True, PROJECT_SCOPED_TOKEN)

            self.assertTrue(cl.authenticate())

            self.assertEqual(1, meth.call_count)

        # check that a value was returned from the keyring
        self.assertTrue(self.memory_keyring.fetched)

        # check that the new token has been loaded into the keyring
        new_auth_ref = pickle.loads(self.memory_keyring.password)
        self.assertEqual(new_auth_ref['token']['expires'],
                         PROJECT_SCOPED_TOKEN['access']['token']['expires'])
    def test_authenticate_success_expired(self):
        resp_a = copy.deepcopy(self.TEST_RESPONSE_DICT)
        resp_b = copy.deepcopy(self.TEST_RESPONSE_DICT)
        headers = {'Content-Type': 'application/json'}

        # Build an expired token
        resp_a['access']['token']['expires'] = (
            (timeutils.utcnow() - datetime.timedelta(1)).isoformat())

        # Build a new response
        TEST_TOKEN = "abcdef"
        resp_b['access']['token']['expires'] = '2020-01-01T00:00:10.000123Z'
        resp_b['access']['token']['id'] = TEST_TOKEN

        # return expired first, and then the new response
        self.stub_auth(response_list=[{'json': resp_a, 'headers': headers},
                                      {'json': resp_b, 'headers': headers}])

        cs = client.Client(tenant_id=self.TEST_TENANT_ID,
                           auth_url=self.TEST_URL,
                           username=self.TEST_USER,
                           password=self.TEST_TOKEN)

        self.assertEqual(cs.management_url,
                         self.TEST_RESPONSE_DICT["access"]["serviceCatalog"][3]
                         ['endpoints'][0]["adminURL"])

        self.assertEqual(cs.auth_token, TEST_TOKEN)
        self.assertRequestBodyIs(json=self.TEST_REQUEST_BODY)
    def test_authenticate_success_expired(self):
        resp_a = copy.deepcopy(self.TEST_RESPONSE_DICT)
        resp_b = copy.deepcopy(self.TEST_RESPONSE_DICT)
        headers = {'Content-Type': 'application/json'}

        # Build an expired token
        resp_a['access']['token']['expires'] = ((
            timeutils.utcnow() - datetime.timedelta(1)).isoformat())

        # Build a new response
        TEST_TOKEN = "abcdef"
        resp_b['access']['token']['expires'] = '2020-01-01T00:00:10.000123Z'
        resp_b['access']['token']['id'] = TEST_TOKEN

        # return expired first, and then the new response
        self.stub_auth(response_list=[{
            'json': resp_a,
            'headers': headers
        }, {
            'json': resp_b,
            'headers': headers
        }])

        cs = client.Client(tenant_id=self.TEST_TENANT_ID,
                           auth_url=self.TEST_URL,
                           username=self.TEST_USER,
                           password=self.TEST_TOKEN)

        self.assertEqual(
            cs.management_url, self.TEST_RESPONSE_DICT["access"]
            ["serviceCatalog"][3]['endpoints'][0]["adminURL"])

        self.assertEqual(cs.auth_token, TEST_TOKEN)
        self.assertRequestBodyIs(json=self.TEST_REQUEST_BODY)
Example #9
0
    def __init__(self, token_id=None, expires=None, issued=None,
                 tenant_id=None, tenant_name=None, user_id=None,
                 user_name=None, trust_id=None, trustee_user_id=None):
        super(Token, self).__init__()

        self.token_id = token_id or uuid.uuid4().hex
        self.user_id = user_id or uuid.uuid4().hex
        self.user_name = user_name or uuid.uuid4().hex

        if not issued:
            issued = timeutils.utcnow() - datetime.timedelta(minutes=2)
        if not expires:
            expires = issued + datetime.timedelta(hours=1)

        try:
            self.issued = issued
        except (TypeError, AttributeError):
            # issued should be able to be passed as a string so ignore
            self.issued_str = issued

        try:
            self.expires = expires
        except (TypeError, AttributeError):
            # expires should be able to be passed as a string so ignore
            self.expires_str = expires

        if tenant_id or tenant_name:
            self.set_scope(tenant_id, tenant_name)

        if trust_id or trustee_user_id:
            # the trustee_user_id will generally be the same as the user_id as
            # the token is being issued to the trustee
            self.set_trust(id=trust_id,
                           trustee_user_id=trustee_user_id or user_id)
Example #10
0
    def __init__(self,
                 token_id=None,
                 expires=None,
                 issued=None,
                 tenant_id=None,
                 tenant_name=None,
                 user_id=None,
                 user_name=None):
        super(Token, self).__init__()

        self.token_id = token_id or uuid.uuid4().hex
        self.user_id = user_id or uuid.uuid4().hex
        self.user_name = user_name or uuid.uuid4().hex

        if not issued:
            issued = timeutils.utcnow() - datetime.timedelta(minutes=2)
        if not expires:
            expires = issued + datetime.timedelta(hours=1)

        try:
            self.issued = issued
        except (TypeError, AttributeError):
            # issued should be able to be passed as a string so ignore
            self.issued_str = issued

        try:
            self.expires = expires
        except (TypeError, AttributeError):
            # expires should be able to be passed as a string so ignore
            self.expires_str = expires

        if tenant_id or tenant_name:
            self.set_scope(tenant_id, tenant_name)
    def _cache_get(self, token_id, ignore_expires=False):
        """Return token information from cache.

        If token is invalid raise InvalidUserToken
        return token only if fresh (not expired).
        """

        if self._cache and token_id:
            if self._memcache_security_strategy is None:
                key = CACHE_KEY_TEMPLATE % token_id
                serialized = self._cache.get(key)
            else:
                keys = memcache_crypt.derive_keys(
                    token_id,
                    self._memcache_secret_key,
                    self._memcache_security_strategy)
                cache_key = CACHE_KEY_TEMPLATE % (
                    memcache_crypt.get_cache_key(keys))
                raw_cached = self._cache.get(cache_key)
                try:
                    # unprotect_data will return None if raw_cached is None
                    serialized = memcache_crypt.unprotect_data(keys,
                                                               raw_cached)
                except Exception:
                    msg = 'Failed to decrypt/verify cache data'
                    self.LOG.exception(msg)
                    # this should have the same effect as data not
                    # found in cache
                    serialized = None

            if serialized is None:
                return None

            # Note that 'invalid' and (data, expires) are the only
            # valid types of serialized cache entries, so there is not
            # a collision with jsonutils.loads(serialized) == None.
            cached = jsonutils.loads(serialized)
            if cached == 'invalid':
                self.LOG.debug('Cached Token %s is marked unauthorized',
                               token_id)
                raise InvalidUserToken('Token authorization failed')

            data, expires = cached

            try:
                expires = timeutils.parse_isotime(expires)
            except ValueError:
                # Gracefully handle upgrade of expiration times from *nix
                # timestamps to ISO 8601 formatted dates by ignoring old cached
                # values.
                return

            expires = timeutils.normalize_time(expires)
            utcnow = timeutils.utcnow()
            if ignore_expires or utcnow < expires:
                self.LOG.debug('Returning cached token %s', token_id)
                return data
            else:
                self.LOG.debug('Cached Token %s seems expired', token_id)
 def test_will_expire_soon(self):
     expires = timeutils.utcnow() + datetime.timedelta(minutes=5)
     UNSCOPED_TOKEN['token']['expires_at'] = expires.isoformat()
     auth_ref = access.AccessInfo.factory(resp=TOKEN_RESPONSE,
                                          body=UNSCOPED_TOKEN)
     self.assertFalse(auth_ref.will_expire_soon(stale_duration=120))
     self.assertTrue(auth_ref.will_expire_soon(stale_duration=300))
     self.assertFalse(auth_ref.will_expire_soon())
Example #13
0
 def test_will_expire_soon(self):
     expires = timeutils.utcnow() + datetime.timedelta(minutes=5)
     UNSCOPED_TOKEN['token']['expires_at'] = expires.isoformat()
     auth_ref = access.AccessInfo.factory(resp=TOKEN_RESPONSE,
                                          body=UNSCOPED_TOKEN)
     self.assertFalse(auth_ref.will_expire_soon(stale_duration=120))
     self.assertTrue(auth_ref.will_expire_soon(stale_duration=300))
     self.assertFalse(auth_ref.will_expire_soon())
Example #14
0
 def __init__(self, **kwargs):
     for k in REVOKE_KEYS:
         v = kwargs.get(k, None)
         setattr(self, k, v)
     if self.revoked_at is None:
         self.revoked_at = timeutils.utcnow()
     if self.issued_before is None:
         self.issued_before = self.revoked_at
 def test_will_expire_soon(self):
     token = client_fixtures.unscoped_token()
     expires = timeutils.utcnow() + datetime.timedelta(minutes=5)
     token.expires = expires
     auth_ref = access.AccessInfo.factory(body=token)
     self.assertFalse(auth_ref.will_expire_soon(stale_duration=120))
     self.assertTrue(auth_ref.will_expire_soon(stale_duration=300))
     self.assertFalse(auth_ref.will_expire_soon())
Example #16
0
def will_expire_soon(expiry):
    """ Determines if expiration is about to occur.

    :param expiry: a datetime of the expected expiration
    :returns: boolean : true if expiration is within 30 seconds
    """
    soon = (timeutils.utcnow() + datetime.timedelta(seconds=30))
    return expiry < soon
Example #17
0
 def __init__(self, **kwargs):
     for k in REVOKE_KEYS:
         v = kwargs.get(k, None)
         setattr(self, k, v)
     if self.revoked_at is None:
         self.revoked_at = timeutils.utcnow()
     if self.issued_before is None:
         self.issued_before = self.revoked_at
def will_expire_soon(expiry):
    """Determines if expiration is about to occur.

    :param expiry: a datetime of the expected expiration
    :returns: boolean : true if expiration is within 30 seconds
    """
    soon = (timeutils.utcnow() + datetime.timedelta(seconds=30))
    return expiry < soon
    def _cache_get(self, token_id, ignore_expires=False):
        """Return token information from cache.

        If token is invalid raise InvalidUserToken
        return token only if fresh (not expired).
        """

        if self._cache and token_id:
            if self._memcache_security_strategy is None:
                key = CACHE_KEY_TEMPLATE % token_id
                serialized = self._cache.get(key)
            else:
                keys = memcache_crypt.derive_keys(
                    token_id, self._memcache_secret_key,
                    self._memcache_security_strategy)
                cache_key = CACHE_KEY_TEMPLATE % (
                    memcache_crypt.get_cache_key(keys))
                raw_cached = self._cache.get(cache_key)
                try:
                    # unprotect_data will return None if raw_cached is None
                    serialized = memcache_crypt.unprotect_data(
                        keys, raw_cached)
                except Exception:
                    msg = 'Failed to decrypt/verify cache data'
                    self.LOG.exception(msg)
                    # this should have the same effect as data not
                    # found in cache
                    serialized = None

            if serialized is None:
                return None

            # Note that 'invalid' and (data, expires) are the only
            # valid types of serialized cache entries, so there is not
            # a collision with jsonutils.loads(serialized) == None.
            cached = jsonutils.loads(serialized)
            if cached == 'invalid':
                self.LOG.debug('Cached Token %s is marked unauthorized',
                               token_id)
                raise InvalidUserToken('Token authorization failed')

            data, expires = cached

            try:
                expires = timeutils.parse_isotime(expires)
            except ValueError:
                # Gracefully handle upgrade of expiration times from *nix
                # timestamps to ISO 8601 formatted dates by ignoring old cached
                # values.
                return

            expires = timeutils.normalize_time(expires)
            utcnow = timeutils.utcnow()
            if ignore_expires or utcnow < expires:
                self.LOG.debug('Returning cached token %s', token_id)
                return data
            else:
                self.LOG.debug('Cached Token %s seems expired', token_id)
Example #20
0
    def __init__(self, expires=None, issued=None, user_id=None, user_name=None,
                 user_domain_id=None, user_domain_name=None, methods=None,
                 project_id=None, project_name=None, project_domain_id=None,
                 project_domain_name=None, domain_id=None, domain_name=None,
                 trust_id=None, trust_impersonation=None, trustee_user_id=None,
                 trustor_user_id=None, oauth_access_token_id=None,
                 oauth_consumer_id=None):
        super(Token, self).__init__()

        self.user_id = user_id or uuid.uuid4().hex
        self.user_name = user_name or uuid.uuid4().hex
        self.user_domain_id = user_domain_id or uuid.uuid4().hex
        self.user_domain_name = user_domain_name or uuid.uuid4().hex

        if not methods:
            methods = ['password']
        self.methods.extend(methods)

        if not issued:
            issued = timeutils.utcnow() - datetime.timedelta(minutes=2)

        try:
            self.issued = issued
        except (TypeError, AttributeError):
            # issued should be able to be passed as a string so ignore
            self.issued_str = issued

        if not expires:
            expires = self.issued + datetime.timedelta(hours=1)

        try:
            self.expires = expires
        except (TypeError, AttributeError):
            # expires should be able to be passed as a string so ignore
            self.expires_str = expires

        if (project_id or project_name or
                project_domain_id or project_domain_name):
            self.set_project_scope(id=project_id,
                                   name=project_name,
                                   domain_id=project_domain_id,
                                   domain_name=project_domain_name)

        if domain_id or domain_name:
            self.set_domain_scope(id=domain_id, name=domain_name)

        if (trust_id or (trust_impersonation is not None) or
                trustee_user_id or trustor_user_id):
            self.set_trust_scope(id=trust_id,
                                 impersonation=trust_impersonation,
                                 trustee_user_id=trustee_user_id,
                                 trustor_user_id=trustor_user_id)

        if oauth_access_token_id or oauth_consumer_id:
            self.set_oauth(access_token_id=oauth_access_token_id,
                           consumer_id=oauth_consumer_id)
Example #21
0
    def __init__(self, expires=None, issued=None, user_id=None, user_name=None,
                 user_domain_id=None, user_domain_name=None, methods=None,
                 project_id=None, project_name=None, project_domain_id=None,
                 project_domain_name=None, domain_id=None, domain_name=None,
                 trust_id=None, trust_impersonation=None, trustee_user_id=None,
                 trustor_user_id=None, oauth_access_token_id=None,
                 oauth_consumer_id=None):
        super(Token, self).__init__()

        self.user_id = user_id or uuid.uuid4().hex
        self.user_name = user_name or uuid.uuid4().hex
        self.user_domain_id = user_domain_id or uuid.uuid4().hex
        self.user_domain_name = user_domain_name or uuid.uuid4().hex

        if not methods:
            methods = ['password']
        self.methods.extend(methods)

        if not issued:
            issued = timeutils.utcnow() - datetime.timedelta(minutes=2)

        try:
            self.issued = issued
        except (TypeError, AttributeError):
            # issued should be able to be passed as a string so ignore
            self.issued_str = issued

        if not expires:
            expires = self.issued + datetime.timedelta(hours=1)

        try:
            self.expires = expires
        except (TypeError, AttributeError):
            # expires should be able to be passed as a string so ignore
            self.expires_str = expires

        if (project_id or project_name or
                project_domain_id or project_domain_name):
            self.set_project_scope(id=project_id,
                                   name=project_name,
                                   domain_id=project_domain_id,
                                   domain_name=project_domain_name)

        if domain_id or domain_name:
            self.set_domain_scope(id=domain_id, name=domain_name)

        if (trust_id or (trust_impersonation is not None) or
                trustee_user_id or trustor_user_id):
            self.set_trust_scope(id=trust_id,
                                 impersonation=trust_impersonation,
                                 trustee_user_id=trustee_user_id,
                                 trustor_user_id=trustor_user_id)

        if oauth_access_token_id or oauth_consumer_id:
            self.set_oauth(access_token_id=oauth_access_token_id,
                           consumer_id=oauth_consumer_id)
    def token_revocation_list(self, value):
        """Save a revocation list to memory and to disk.

        :param value: A json-encoded revocation list

        """
        self._token_revocation_list = jsonutils.loads(value)
        self.token_revocation_list_fetched_time = timeutils.utcnow()
        with open(self.revoked_file_name, 'w') as f:
            f.write(value)
Example #23
0
    def token_revocation_list(self, value):
        """Save a revocation list to memory and to disk.

        :param value: A json-encoded revocation list

        """
        self._token_revocation_list = jsonutils.loads(value)
        self.token_revocation_list_fetched_time = timeutils.utcnow()
        with open(self.revoked_file_name, 'w') as f:
            f.write(value)
 def get_revocation_list_json(self, token_ids=None):
     if token_ids is None:
         token_ids = [REVOKED_TOKEN_HASH]
     revocation_list = {
         'revoked': [{
             'id': x,
             'expires': timeutils.utcnow()
         } for x in token_ids]
     }
     return jsonutils.dumps(revocation_list)
 def token_revocation_list(self):
     timeout = self.token_revocation_list_fetched_time + self.token_revocation_list_cache_timeout
     list_is_current = timeutils.utcnow() < timeout
     if list_is_current:
         # Load the list from disk if required
         if not self._token_revocation_list:
             with open(self.revoked_file_name, "r") as f:
                 self._token_revocation_list = jsonutils.loads(f.read())
     else:
         self.token_revocation_list = self.fetch_revocation_list()
     return self._token_revocation_list
    def _create_expired_auth_plugin(self, **kwargs):
        expires = timeutils.utcnow() - datetime.timedelta(minutes=20)
        expired_token = self.get_auth_data(expires=expires)
        expired_auth_ref = access.AccessInfo.factory(body=expired_token)

        body = "SUCCESS"
        self.stub_url("GET", ["path"], base_url=self.TEST_COMPUTE_ADMIN, body=body)

        a = self.create_auth_plugin(**kwargs)
        a.auth_ref = expired_auth_ref
        return a
Example #27
0
 def token_revocation_list(self):
     timeout = (self.token_revocation_list_fetched_time +
                self.token_revocation_list_cache_timeout)
     list_is_current = timeutils.utcnow() < timeout
     if list_is_current:
         # Load the list from disk if required
         if not self._token_revocation_list:
             with open(self.revoked_file_name, 'r') as f:
                 self._token_revocation_list = jsonutils.loads(f.read())
     else:
         self.token_revocation_list = self.fetch_revocation_list()
     return self._token_revocation_list
    def will_expire_soon(self, stale_duration=None):
        """Determines if expiration is about to occur.

        :return: boolean : true if expiration is within the given duration

        """
        stale_duration = STALE_TOKEN_DURATION if stale_duration is None else stale_duration
        norm_expires = timeutils.normalize_time(self.expires)
        # (gyee) should we move auth_token.will_expire_soon() to timeutils
        # instead of duplicating code here?
        soon = timeutils.utcnow() + datetime.timedelta(seconds=stale_duration)
        return norm_expires < soon
    def __init__(self, id, status=None, updated=None):
        """Create a new structure.

        :param string id: The version id for this version entry.
        :param string status: The status of this entry.
        :param DateTime updated: When the API was last updated.
        """
        super(DiscoveryBase, self).__init__()

        self.id = id
        self.status = status or "stable"
        self.updated = updated or (timeutils.utcnow() - datetime.timedelta(days=_DEFAULT_DAYS_AGO))
    def __init__(self, id, status=None, updated=None):
        """Create a new structure.

        :param string id: The version id for this version entry.
        :param string status: The status of this entry.
        :param DateTime updated: When the API was last updated.
        """
        super(DiscoveryBase, self).__init__()

        self.id = id
        self.status = status or 'stable'
        self.updated = updated or (timeutils.utcnow() -
                                   datetime.timedelta(days=_DEFAULT_DAYS_AGO))
    def _create_expired_auth_plugin(self, **kwargs):
        expires = timeutils.utcnow() - datetime.timedelta(minutes=20)
        expired_token = self.get_auth_data(expires=expires)
        expired_auth_ref = access.AccessInfo.factory(body=expired_token)

        body = 'SUCCESS'
        self.stub_url('GET', ['path'],
                      base_url=self.TEST_COMPUTE_ADMIN,
                      text=body)

        a = self.create_auth_plugin(**kwargs)
        a.auth_ref = expired_auth_ref
        return a
Example #32
0
    def will_expire_soon(self, stale_duration=None):
        """ Determines if expiration is about to occur.

        :return: boolean : true if expiration is within the given duration

        """
        stale_duration = stale_duration or TALE_TOKEN_DURATION
        norm_expires = timeutils.normalize_time(self.expires)
        # (gyee) should we move auth_token.will_expire_soon() to timeutils
        # instead of duplicating code here?
        soon = (timeutils.utcnow() +
                datetime.timedelta(seconds=stale_duration))
        return norm_expires < soon
    def test_get_keyring(self):
        cl = httpclient.HTTPClient(username=USERNAME, password=PASSWORD,
                                   tenant_id=TENANT_ID, auth_url=AUTH_URL,
                                   use_keyring=True)

        # set an token into the keyring
        auth_ref = access.AccessInfo.factory(body=PROJECT_SCOPED_TOKEN)
        future = timeutils.utcnow() + datetime.timedelta(minutes=30)
        auth_ref['token']['expires'] = timeutils.isotime(future)
        self.memory_keyring.password = pickle.dumps(auth_ref)

        # don't stub get_raw_token so will fail if authenticate happens

        self.assertTrue(cl.authenticate())
        self.assertTrue(self.memory_keyring.fetched)
def confirm_token_not_expired(data):
    if not data:
        raise InvalidUserToken('Token authorization failed')
    if _token_is_v2(data):
        timestamp = data['access']['token']['expires']
    elif _token_is_v3(data):
        timestamp = data['token']['expires_at']
    else:
        raise InvalidUserToken('Token authorization failed')
    expires = timeutils.parse_isotime(timestamp)
    expires = timeutils.normalize_time(expires)
    utcnow = timeutils.utcnow()
    if utcnow >= expires:
        raise InvalidUserToken('Token authorization failed')
    return timeutils.isotime(at=expires, subsecond=True)
def confirm_token_not_expired(data):
    if not data:
        raise InvalidUserToken('Token authorization failed')
    if _token_is_v2(data):
        timestamp = data['access']['token']['expires']
    elif _token_is_v3(data):
        timestamp = data['token']['expires_at']
    else:
        raise InvalidUserToken('Token authorization failed')
    expires = timeutils.parse_isotime(timestamp)
    expires = timeutils.normalize_time(expires)
    utcnow = timeutils.utcnow()
    if utcnow >= expires:
        raise InvalidUserToken('Token authorization failed')
    return timeutils.isotime(at=expires, subsecond=True)
    def test_get_keyring(self):
        cl = httpclient.HTTPClient(username=USERNAME,
                                   password=PASSWORD,
                                   tenant_id=TENANT_ID,
                                   auth_url=AUTH_URL,
                                   use_keyring=True)

        # set an token into the keyring
        auth_ref = access.AccessInfo.factory(body=PROJECT_SCOPED_TOKEN)
        future = timeutils.utcnow() + datetime.timedelta(minutes=30)
        auth_ref['token']['expires'] = timeutils.isotime(future)
        self.memory_keyring.password = pickle.dumps(auth_ref)

        # don't stub get_raw_token so will fail if authenticate happens

        self.assertTrue(cl.authenticate())
        self.assertTrue(self.memory_keyring.fetched)
    def test_authenticate_success_expired(self):
        # Build an expired token
        self.TEST_RESPONSE_DICT['access']['token']['expires'] = \
            (timeutils.utcnow() - timedelta(1)).isoformat()
        resp = utils.TestResponse({
            "status_code": 200,
            "text": json.dumps(self.TEST_RESPONSE_DICT),
        })

        kwargs = copy.copy(self.TEST_REQUEST_BASE)
        kwargs['headers'] = self.TEST_REQUEST_HEADERS
        kwargs['data'] = json.dumps(self.TEST_REQUEST_BODY)
        requests.request('POST',
                         self.TEST_URL + "/tokens",
                         **kwargs).AndReturn((resp))
        self.mox.ReplayAll()

        cs = client.Client(tenant_id=self.TEST_TENANT_ID,
                           auth_url=self.TEST_URL,
                           username=self.TEST_USER,
                           password=self.TEST_TOKEN)
        self.assertEqual(cs.management_url,
                         self.TEST_RESPONSE_DICT["access"]["serviceCatalog"][3]
                         ['endpoints'][0]["adminURL"])

        # Build a new response
        self.mox.ResetAll()
        TEST_TOKEN = "abcdef"
        self.TEST_RESPONSE_DICT['access']['token']['expires'] = \
            '2020-01-01T00:00:10.000123Z'
        self.TEST_RESPONSE_DICT['access']['token']['id'] = TEST_TOKEN

        resp = utils.TestResponse({
            "status_code": 200,
            "text": json.dumps(self.TEST_RESPONSE_DICT),
        })
        requests.request('POST',
                         self.TEST_URL + "/tokens",
                         **kwargs).AndReturn((resp))
        self.mox.ReplayAll()

        self.assertEqual(cs.auth_token, TEST_TOKEN)
Example #38
0
    def __init__(self, token_id=None,
                 expires=None, tenant_id=None, tenant_name=None, user_id=None,
                 user_name=None):
        super(Token, self).__init__()

        self.token_id = token_id or uuid.uuid4().hex
        self.user_id = user_id or uuid.uuid4().hex
        self.user_name = user_name or uuid.uuid4().hex

        if not expires:
            expires = timeutils.utcnow() + datetime.timedelta(hours=1)

        try:
            self.expires = expires
        except (TypeError, AttributeError):
            # expires should be able to be passed as a string so ignore
            self.expires_str = expires

        if tenant_id or tenant_name:
            self.set_scope(tenant_id, tenant_name)
    def test_set_and_get_keyring_expired(self):
        cl = httpclient.HTTPClient(username=USERNAME, password=PASSWORD,
                                   tenant_id=TENANT_ID, auth_url=AUTH_URL,
                                   use_keyring=True)
        keyring_key = cl._build_keyring_key(auth_url=AUTH_URL,
                                            username=USERNAME,
                                            tenant_name=TENANT,
                                            tenant_id=TENANT_ID,
                                            token=TOKEN)

        cl.auth_ref = access.AccessInfo.factory(body=PROJECT_SCOPED_TOKEN)
        expired = timeutils.utcnow() - datetime.timedelta(minutes=30)
        cl.auth_ref['token']['expires'] = timeutils.isotime(expired)
        cl.store_auth_ref_into_keyring(keyring_key)
        (keyring_key, auth_ref) = cl.get_auth_ref_from_keyring(
            auth_url=AUTH_URL,
            username=USERNAME,
            tenant_name=TENANT,
            tenant_id=TENANT_ID,
            token=TOKEN)
        self.assertIsNone(auth_ref)
Example #40
0
    def test_authenticate_success_expired(self):
        # Build an expired token
        self.TEST_RESPONSE_DICT['access']['token']['expires'] = \
            (timeutils.utcnow() - timedelta(1)).isoformat()
        resp = utils.TestResponse({
            "status_code": 200,
            "text": json.dumps(self.TEST_RESPONSE_DICT),
        })

        kwargs = copy.copy(self.TEST_REQUEST_BASE)
        kwargs['headers'] = self.TEST_REQUEST_HEADERS
        kwargs['data'] = json.dumps(self.TEST_REQUEST_BODY)
        requests.request('POST', self.TEST_URL + "/tokens",
                         **kwargs).AndReturn((resp))
        self.mox.ReplayAll()

        cs = client.Client(tenant_id=self.TEST_TENANT_ID,
                           auth_url=self.TEST_URL,
                           username=self.TEST_USER,
                           password=self.TEST_TOKEN)
        self.assertEqual(
            cs.management_url, self.TEST_RESPONSE_DICT["access"]
            ["serviceCatalog"][3]['endpoints'][0]["adminURL"])

        # Build a new response
        self.mox.ResetAll()
        TEST_TOKEN = "abcdef"
        self.TEST_RESPONSE_DICT['access']['token']['expires'] = \
            "2999-01-01T00:00:10Z"
        self.TEST_RESPONSE_DICT['access']['token']['id'] = TEST_TOKEN

        resp = utils.TestResponse({
            "status_code": 200,
            "text": json.dumps(self.TEST_RESPONSE_DICT),
        })
        requests.request('POST', self.TEST_URL + "/tokens",
                         **kwargs).AndReturn((resp))
        self.mox.ReplayAll()

        self.assertEqual(cs.auth_token, TEST_TOKEN)
    def test_set_and_get_keyring_expired(self):
        cl = client.HTTPClient(username=USERNAME,
                               password=PASSWORD,
                               tenant_id=TENANT_ID,
                               auth_url=AUTH_URL,
                               use_keyring=True)
        keyring_key = cl._build_keyring_key(auth_url=AUTH_URL,
                                            username=USERNAME,
                                            tenant_name=TENANT,
                                            tenant_id=TENANT_ID,
                                            token=TOKEN)

        cl.auth_ref = access.AccessInfo.factory(body=PROJECT_SCOPED_TOKEN)
        expired = timeutils.utcnow() - datetime.timedelta(minutes=30)
        cl.auth_ref['token']['expires'] = timeutils.isotime(expired)
        cl.store_auth_ref_into_keyring(keyring_key)
        (keyring_key,
         auth_ref) = cl.get_auth_ref_from_keyring(auth_url=AUTH_URL,
                                                  username=USERNAME,
                                                  tenant_name=TENANT,
                                                  tenant_id=TENANT_ID,
                                                  token=TOKEN)
        self.assertIsNone(auth_ref)
with open(os.path.join(CERTDIR, 'signing_cert.pem')) as f:
    SIGNING_CERT = f.read()
with open(os.path.join(CERTDIR, 'cacert.pem')) as f:
    SIGNING_CA = f.read()

UUID_TOKEN_DEFAULT = "ec6c0710ec2f471498484c1b53ab4f9d"
UUID_TOKEN_NO_SERVICE_CATALOG = '8286720fbe4941e69fa8241723bb02df'
UUID_TOKEN_UNSCOPED = '731f903721c14827be7b2dc912af7776'
VALID_DIABLO_TOKEN = 'b0cf19b55dbb4f20a6ee18e6c6cf1726'
v3_UUID_TOKEN_DEFAULT = '5603457654b346fdbb93437bfe76f2f1'
v3_UUID_TOKEN_UNSCOPED = 'd34835fdaec447e695a0a024d84f8d79'
v3_UUID_TOKEN_DOMAIN_SCOPED = 'e8a7b63aaa4449f38f0c5c05c3581792'

REVOKED_TOKEN_HASH = utils.hash_signed_token(REVOKED_TOKEN)
REVOKED_TOKEN_LIST = {'revoked': [{'id': REVOKED_TOKEN_HASH,
                                   'expires': timeutils.utcnow()}]}
REVOKED_TOKEN_LIST_JSON = jsonutils.dumps(REVOKED_TOKEN_LIST)

REVOKED_v3_TOKEN_HASH = utils.hash_signed_token(REVOKED_v3_TOKEN)
REVOKED_v3_TOKEN_LIST = {'revoked': [{'id': REVOKED_v3_TOKEN_HASH,
                                      'expires': timeutils.utcnow()}]}
REVOKED_v3_TOKEN_LIST_JSON = jsonutils.dumps(REVOKED_v3_TOKEN_LIST)

SIGNED_TOKEN_SCOPED_KEY = cms.cms_hash_token(SIGNED_TOKEN_SCOPED)
SIGNED_TOKEN_UNSCOPED_KEY = cms.cms_hash_token(SIGNED_TOKEN_UNSCOPED)
SIGNED_v3_TOKEN_SCOPED_KEY = cms.cms_hash_token(SIGNED_v3_TOKEN_SCOPED)

INVALID_SIGNED_TOKEN = \
    "MIIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" \
    "BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB" \
    "CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC" \
 def test_will_expire_soon(self):
     expires = timeutils.utcnow() + datetime.timedelta(minutes=5)
     UNSCOPED_TOKEN['access']['token']['expires'] = expires.isoformat()
     auth_ref = access.AccessInfo(UNSCOPED_TOKEN['access'])
     self.assertFalse(auth_ref.will_expire_soon(stale_duration=120))
     self.assertTrue(auth_ref.will_expire_soon(stale_duration=300))
SIGNING_CA_FILE = os.path.join(CERTDIR, 'cacert.pem')
with open(SIGNING_CA_FILE) as f:
    SIGNING_CA = f.read()

UUID_TOKEN_DEFAULT = "ec6c0710ec2f471498484c1b53ab4f9d"
UUID_TOKEN_NO_SERVICE_CATALOG = '8286720fbe4941e69fa8241723bb02df'
UUID_TOKEN_UNSCOPED = '731f903721c14827be7b2dc912af7776'
VALID_DIABLO_TOKEN = 'b0cf19b55dbb4f20a6ee18e6c6cf1726'
v3_UUID_TOKEN_DEFAULT = '5603457654b346fdbb93437bfe76f2f1'
v3_UUID_TOKEN_UNSCOPED = 'd34835fdaec447e695a0a024d84f8d79'
v3_UUID_TOKEN_DOMAIN_SCOPED = 'e8a7b63aaa4449f38f0c5c05c3581792'

REVOKED_TOKEN_HASH = utils.hash_signed_token(REVOKED_TOKEN)
REVOKED_TOKEN_LIST = {'revoked': [{'id': REVOKED_TOKEN_HASH,
                                   'expires': timeutils.utcnow()}]}
REVOKED_TOKEN_LIST_JSON = jsonutils.dumps(REVOKED_TOKEN_LIST)

REVOKED_v3_TOKEN_HASH = utils.hash_signed_token(REVOKED_v3_TOKEN)
REVOKED_v3_TOKEN_LIST = {'revoked': [{'id': REVOKED_v3_TOKEN_HASH,
                                      'expires': timeutils.utcnow()}]}
REVOKED_v3_TOKEN_LIST_JSON = jsonutils.dumps(REVOKED_v3_TOKEN_LIST)

SIGNED_TOKEN_SCOPED_KEY = cms.cms_hash_token(SIGNED_TOKEN_SCOPED)
SIGNED_TOKEN_UNSCOPED_KEY = cms.cms_hash_token(SIGNED_TOKEN_UNSCOPED)
SIGNED_v3_TOKEN_SCOPED_KEY = cms.cms_hash_token(SIGNED_v3_TOKEN_SCOPED)

INVALID_SIGNED_TOKEN = \
    "MIIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" \
    "BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB" \
    "CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC" \
 def get_revocation_list_json(self, token_ids=None):
     if token_ids is None:
         token_ids = [self.token_dict['revoked_token_hash']]
     revocation_list = {'revoked': [{'id': x, 'expires': timeutils.utcnow()}
                                    for x in token_ids]}
     return jsonutils.dumps(revocation_list)
    def setUp(self):
        super(Examples, self).setUp()

        # The data for several tests are signed using openssl and are stored in
        # files in the signing subdirectory.  In order to keep the values
        # consistent between the tests and the signed documents, we read them
        # in for use in the tests.

        with open(os.path.join(CMSDIR, 'auth_token_scoped.pem')) as f:
            self.SIGNED_TOKEN_SCOPED = cms.cms_to_token(f.read())
        with open(os.path.join(CMSDIR, 'auth_token_unscoped.pem')) as f:
            self.SIGNED_TOKEN_UNSCOPED = cms.cms_to_token(f.read())
        with open(os.path.join(CMSDIR, 'auth_v3_token_scoped.pem')) as f:
            self.SIGNED_v3_TOKEN_SCOPED = cms.cms_to_token(f.read())
        with open(os.path.join(CMSDIR, 'auth_token_revoked.pem')) as f:
            self.REVOKED_TOKEN = cms.cms_to_token(f.read())
        with open(os.path.join(CMSDIR, 'auth_token_scoped_expired.pem')) as f:
            self.SIGNED_TOKEN_SCOPED_EXPIRED = cms.cms_to_token(f.read())
        with open(os.path.join(CMSDIR, 'auth_v3_token_revoked.pem')) as f:
            self.REVOKED_v3_TOKEN = cms.cms_to_token(f.read())
        with open(os.path.join(CMSDIR, 'revocation_list.json')) as f:
            self.REVOCATION_LIST = jsonutils.loads(f.read())
        with open(os.path.join(CMSDIR, 'revocation_list.pem')) as f:
            self.SIGNED_REVOCATION_LIST = jsonutils.dumps({'signed': f.read()})

        self.SIGNING_CERT_FILE = os.path.join(CERTDIR, 'signing_cert.pem')
        with open(self.SIGNING_CERT_FILE) as f:
            self.SIGNING_CERT = f.read()

        self.KERBEROS_BIND = 'USER@REALM'

        self.SIGNING_KEY_FILE = os.path.join(KEYDIR, 'signing_key.pem')
        with open(self.SIGNING_KEY_FILE) as f:
            self.SIGNING_KEY = f.read()

        self.SIGNING_CA_FILE = os.path.join(CERTDIR, 'cacert.pem')
        with open(self.SIGNING_CA_FILE) as f:
            self.SIGNING_CA = f.read()

        self.UUID_TOKEN_DEFAULT = "ec6c0710ec2f471498484c1b53ab4f9d"
        self.UUID_TOKEN_NO_SERVICE_CATALOG = '8286720fbe4941e69fa8241723bb02df'
        self.UUID_TOKEN_UNSCOPED = '731f903721c14827be7b2dc912af7776'
        self.UUID_TOKEN_BIND = '3fc54048ad64405c98225ce0897af7c5'
        self.UUID_TOKEN_UNKNOWN_BIND = '8885fdf4d42e4fb9879e6379fa1eaf48'
        self.VALID_DIABLO_TOKEN = 'b0cf19b55dbb4f20a6ee18e6c6cf1726'
        self.v3_UUID_TOKEN_DEFAULT = '5603457654b346fdbb93437bfe76f2f1'
        self.v3_UUID_TOKEN_UNSCOPED = 'd34835fdaec447e695a0a024d84f8d79'
        self.v3_UUID_TOKEN_DOMAIN_SCOPED = 'e8a7b63aaa4449f38f0c5c05c3581792'
        self.v3_UUID_TOKEN_BIND = '2f61f73e1c854cbb9534c487f9bd63c2'
        self.v3_UUID_TOKEN_UNKNOWN_BIND = '7ed9781b62cd4880b8d8c6788ab1d1e2'

        self.REVOKED_TOKEN_HASH = utils.hash_signed_token(self.REVOKED_TOKEN)
        self.REVOKED_TOKEN_LIST = (
            {'revoked': [{'id': self.REVOKED_TOKEN_HASH,
                          'expires': timeutils.utcnow()}]})
        self.REVOKED_TOKEN_LIST_JSON = jsonutils.dumps(self.REVOKED_TOKEN_LIST)

        self.REVOKED_v3_TOKEN_HASH = utils.hash_signed_token(
            self.REVOKED_v3_TOKEN)
        self.REVOKED_v3_TOKEN_LIST = (
            {'revoked': [{'id': self.REVOKED_v3_TOKEN_HASH,
                          'expires': timeutils.utcnow()}]})
        self.REVOKED_v3_TOKEN_LIST_JSON = jsonutils.dumps(
            self.REVOKED_v3_TOKEN_LIST)

        self.SIGNED_TOKEN_SCOPED_KEY = cms.cms_hash_token(
            self.SIGNED_TOKEN_SCOPED)
        self.SIGNED_TOKEN_UNSCOPED_KEY = cms.cms_hash_token(
            self.SIGNED_TOKEN_UNSCOPED)
        self.SIGNED_v3_TOKEN_SCOPED_KEY = cms.cms_hash_token(
            self.SIGNED_v3_TOKEN_SCOPED)

        self.INVALID_SIGNED_TOKEN = (
            "MIIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
            "BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB"
            "CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC"
            "DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD"
            "EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE"
            "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
            "0000000000000000000000000000000000000000000000000000000000000000"
            "1111111111111111111111111111111111111111111111111111111111111111"
            "2222222222222222222222222222222222222222222222222222222222222222"
            "3333333333333333333333333333333333333333333333333333333333333333"
            "4444444444444444444444444444444444444444444444444444444444444444"
            "5555555555555555555555555555555555555555555555555555555555555555"
            "6666666666666666666666666666666666666666666666666666666666666666"
            "7777777777777777777777777777777777777777777777777777777777777777"
            "8888888888888888888888888888888888888888888888888888888888888888"
            "9999999999999999999999999999999999999999999999999999999999999999"
            "0000000000000000000000000000000000000000000000000000000000000000")

        # JSON responses keyed by token ID
        self.TOKEN_RESPONSES = {
            self.UUID_TOKEN_DEFAULT: {
                'access': {
                    'token': {
                        'id': self.UUID_TOKEN_DEFAULT,
                        'expires': '2020-01-01T00:00:10.000123Z',
                        'tenant': {
                            'id': 'tenant_id1',
                            'name': 'tenant_name1',
                        },
                    },
                    'user': {
                        'id': 'user_id1',
                        'name': 'user_name1',
                        'roles': [
                            {'name': 'role1'},
                            {'name': 'role2'},
                        ],
                    },
                    'serviceCatalog': {}
                },
            },
            self.VALID_DIABLO_TOKEN: {
                'access': {
                    'token': {
                        'id': self.VALID_DIABLO_TOKEN,
                        'expires': '2020-01-01T00:00:10.000123Z',
                        'tenantId': 'tenant_id1',
                    },
                    'user': {
                        'id': 'user_id1',
                        'name': 'user_name1',
                        'roles': [
                            {'name': 'role1'},
                            {'name': 'role2'},
                        ],
                    },
                },
            },
            self.UUID_TOKEN_UNSCOPED: {
                'access': {
                    'token': {
                        'id': self.UUID_TOKEN_UNSCOPED,
                        'expires': '2020-01-01T00:00:10.000123Z',
                    },
                    'user': {
                        'id': 'user_id1',
                        'name': 'user_name1',
                        'roles': [
                            {'name': 'role1'},
                            {'name': 'role2'},
                        ],
                    },
                },
            },
            self.UUID_TOKEN_NO_SERVICE_CATALOG: {
                'access': {
                    'token': {
                        'id': 'valid-token',
                        'expires': '2020-01-01T00:00:10.000123Z',
                        'tenant': {
                            'id': 'tenant_id1',
                            'name': 'tenant_name1',
                        },
                    },
                    'user': {
                        'id': 'user_id1',
                        'name': 'user_name1',
                        'roles': [
                            {'name': 'role1'},
                            {'name': 'role2'},
                        ],
                    }
                },
            },
            self.UUID_TOKEN_BIND: {
                'access': {
                    'token': {
                        'bind': {'kerberos': self.KERBEROS_BIND},
                        'id': self.UUID_TOKEN_BIND,
                        'expires': '2020-01-01T00:00:10.000123Z',
                        'tenant': {
                            'id': 'tenant_id1',
                            'name': 'tenant_name1',
                        },
                    },
                    'user': {
                        'id': 'user_id1',
                        'name': 'user_name1',
                        'roles': [
                            {'name': 'role1'},
                            {'name': 'role2'},
                        ],
                    },
                    'serviceCatalog': {}
                },
            },
            self.UUID_TOKEN_UNKNOWN_BIND: {
                'access': {
                    'token': {
                        'bind': {'FOO': 'BAR'},
                        'id': self.UUID_TOKEN_UNKNOWN_BIND,
                        'expires': '2020-01-01T00:00:10.000123Z',
                        'tenant': {
                            'id': 'tenant_id1',
                            'name': 'tenant_name1',
                        },
                    },
                    'user': {
                        'id': 'user_id1',
                        'name': 'user_name1',
                        'roles': [
                            {'name': 'role1'},
                            {'name': 'role2'},
                        ],
                    },
                    'serviceCatalog': {}
                },
            },
            self.v3_UUID_TOKEN_DEFAULT: {
                'token': {
                    'expires_at': '2020-01-01T00:00:10.000123Z',
                    'user': {
                        'id': 'user_id1',
                        'name': 'user_name1',
                        'domain': {
                            'id': 'domain_id1',
                            'name': 'domain_name1'
                        }
                    },
                    'project': {
                        'id': 'tenant_id1',
                        'name': 'tenant_name1',
                        'domain': {
                            'id': 'domain_id1',
                            'name': 'domain_name1'
                        }
                    },
                    'roles': [
                        {'name': 'role1', 'id': 'Role1'},
                        {'name': 'role2', 'id': 'Role2'},
                    ],
                    'catalog': {}
                }
            },
            self.v3_UUID_TOKEN_UNSCOPED: {
                'token': {
                    'expires_at': '2020-01-01T00:00:10.000123Z',
                    'user': {
                        'id': 'user_id1',
                        'name': 'user_name1',
                        'domain': {
                            'id': 'domain_id1',
                            'name': 'domain_name1'
                        }
                    }
                }
            },
            self.v3_UUID_TOKEN_DOMAIN_SCOPED: {
                'token': {
                    'expires_at': '2020-01-01T00:00:10.000123Z',
                    'user': {
                        'id': 'user_id1',
                        'name': 'user_name1',
                        'domain': {
                            'id': 'domain_id1',
                            'name': 'domain_name1'
                        }
                    },
                    'domain': {
                        'id': 'domain_id1',
                        'name': 'domain_name1',
                    },
                    'roles': [
                        {'name': 'role1', 'id': 'Role1'},
                        {'name': 'role2', 'id': 'Role2'},
                    ],
                    'catalog': {}
                }
            },
            self.SIGNED_TOKEN_SCOPED_KEY: {
                'access': {
                    'token': {
                        'id': self.SIGNED_TOKEN_SCOPED_KEY,
                    },
                    'user': {
                        'id': 'user_id1',
                        'name': 'user_name1',
                        'tenantId': 'tenant_id1',
                        'tenantName': 'tenant_name1',
                        'roles': [
                            {'name': 'role1'},
                            {'name': 'role2'},
                        ],
                    },
                },
            },
            self.SIGNED_TOKEN_UNSCOPED_KEY: {
                'access': {
                    'token': {
                        'id': self.SIGNED_TOKEN_UNSCOPED_KEY,
                    },
                    'user': {
                        'id': 'user_id1',
                        'name': 'user_name1',
                        'roles': [
                            {'name': 'role1'},
                            {'name': 'role2'},
                        ],
                    },
                },
            },
            self.SIGNED_v3_TOKEN_SCOPED_KEY: {
                'token': {
                    'expires': '2020-01-01T00:00:10.000123Z',
                    'user': {
                        'id': 'user_id1',
                        'name': 'user_name1',
                        'domain': {
                            'id': 'domain_id1',
                            'name': 'domain_name1'
                        }
                    },
                    'project': {
                        'id': 'tenant_id1',
                        'name': 'tenant_name1',
                        'domain': {
                            'id': 'domain_id1',
                            'name': 'domain_name1'
                        }
                    },
                    'roles': [
                        {'name': 'role1'},
                        {'name': 'role2'}
                    ],
                    'catalog': {}
                }
            },
            self.v3_UUID_TOKEN_BIND: {
                'token': {
                    'bind': {'kerberos': self.KERBEROS_BIND},
                    'expires_at': '2020-01-01T00:00:10.000123Z',
                    'user': {
                        'id': 'user_id1',
                        'name': 'user_name1',
                        'domain': {
                            'id': 'domain_id1',
                            'name': 'domain_name1'
                        }
                    },
                    'project': {
                        'id': 'tenant_id1',
                        'name': 'tenant_name1',
                        'domain': {
                            'id': 'domain_id1',
                            'name': 'domain_name1'
                        }
                    },
                    'roles': [
                        {'name': 'role1', 'id': 'Role1'},
                        {'name': 'role2', 'id': 'Role2'},
                    ],
                    'catalog': {}
                }
            },
            self.v3_UUID_TOKEN_UNKNOWN_BIND: {
                'token': {
                    'bind': {'FOO': 'BAR'},
                    'expires_at': '2020-01-01T00:00:10.000123Z',
                    'user': {
                        'id': 'user_id1',
                        'name': 'user_name1',
                        'domain': {
                            'id': 'domain_id1',
                            'name': 'domain_name1'
                        }
                    },
                    'project': {
                        'id': 'tenant_id1',
                        'name': 'tenant_name1',
                        'domain': {
                            'id': 'domain_id1',
                            'name': 'domain_name1'
                        }
                    },
                    'roles': [
                        {'name': 'role1', 'id': 'Role1'},
                        {'name': 'role2', 'id': 'Role2'},
                    ],
                    'catalog': {}
                }
            },
        }

        self.JSON_TOKEN_RESPONSES = dict([(k, jsonutils.dumps(v)) for k, v in
                                          six.iteritems(self.TOKEN_RESPONSES)])
 def get_revocation_list_json(self, token_ids=None):
     if token_ids is None:
         token_ids = [self.token_dict['revoked_token_hash']]
     revocation_list = {'revoked': [{'id': x, 'expires': timeutils.utcnow()}
                                    for x in token_ids]}
     return jsonutils.dumps(revocation_list)
Example #48
0
with open(os.path.join(CERTDIR, 'cacert.pem')) as f:
    SIGNING_CA = f.read()

UUID_TOKEN_DEFAULT = "ec6c0710ec2f471498484c1b53ab4f9d"
UUID_TOKEN_NO_SERVICE_CATALOG = '8286720fbe4941e69fa8241723bb02df'
UUID_TOKEN_UNSCOPED = '731f903721c14827be7b2dc912af7776'
VALID_DIABLO_TOKEN = 'b0cf19b55dbb4f20a6ee18e6c6cf1726'
v3_UUID_TOKEN_DEFAULT = '5603457654b346fdbb93437bfe76f2f1'
v3_UUID_TOKEN_UNSCOPED = 'd34835fdaec447e695a0a024d84f8d79'
v3_UUID_TOKEN_DOMAIN_SCOPED = 'e8a7b63aaa4449f38f0c5c05c3581792'

REVOKED_TOKEN_HASH = utils.hash_signed_token(REVOKED_TOKEN)
REVOKED_TOKEN_LIST = {
    'revoked': [{
        'id': REVOKED_TOKEN_HASH,
        'expires': timeutils.utcnow()
    }]
}
REVOKED_TOKEN_LIST_JSON = jsonutils.dumps(REVOKED_TOKEN_LIST)

REVOKED_v3_TOKEN_HASH = utils.hash_signed_token(REVOKED_v3_TOKEN)
REVOKED_v3_TOKEN_LIST = {
    'revoked': [{
        'id': REVOKED_v3_TOKEN_HASH,
        'expires': timeutils.utcnow()
    }]
}
REVOKED_v3_TOKEN_LIST_JSON = jsonutils.dumps(REVOKED_v3_TOKEN_LIST)

SIGNED_TOKEN_SCOPED_KEY = cms.cms_hash_token(SIGNED_TOKEN_SCOPED)
SIGNED_TOKEN_UNSCOPED_KEY = cms.cms_hash_token(SIGNED_TOKEN_UNSCOPED)
 def get_revocation_list_json(self, token_ids=None):
     if token_ids is None:
         token_ids = [REVOKED_TOKEN_HASH]
     revocation_list = {'revoked': [{'id': x, 'expires': timeutils.utcnow()}
                                    for x in token_ids]}
     return jsonutils.dumps(revocation_list)
    def setUp(self):
        super(Examples, self).setUp()

        # The data for several tests are signed using openssl and are stored in
        # files in the signing subdirectory.  In order to keep the values
        # consistent between the tests and the signed documents, we read them
        # in for use in the tests.

        with open(os.path.join(CMSDIR, "auth_token_scoped.pem")) as f:
            self.SIGNED_TOKEN_SCOPED = cms.cms_to_token(f.read())
        with open(os.path.join(CMSDIR, "auth_token_unscoped.pem")) as f:
            self.SIGNED_TOKEN_UNSCOPED = cms.cms_to_token(f.read())
        with open(os.path.join(CMSDIR, "auth_v3_token_scoped.pem")) as f:
            self.SIGNED_v3_TOKEN_SCOPED = cms.cms_to_token(f.read())
        with open(os.path.join(CMSDIR, "auth_token_revoked.pem")) as f:
            self.REVOKED_TOKEN = cms.cms_to_token(f.read())
        with open(os.path.join(CMSDIR, "auth_token_scoped_expired.pem")) as f:
            self.SIGNED_TOKEN_SCOPED_EXPIRED = cms.cms_to_token(f.read())
        with open(os.path.join(CMSDIR, "auth_v3_token_revoked.pem")) as f:
            self.REVOKED_v3_TOKEN = cms.cms_to_token(f.read())
        with open(os.path.join(CMSDIR, "revocation_list.json")) as f:
            self.REVOCATION_LIST = jsonutils.loads(f.read())
        with open(os.path.join(CMSDIR, "revocation_list.pem")) as f:
            self.SIGNED_REVOCATION_LIST = jsonutils.dumps({"signed": f.read()})

        self.SIGNING_CERT_FILE = os.path.join(CERTDIR, "signing_cert.pem")
        with open(self.SIGNING_CERT_FILE) as f:
            self.SIGNING_CERT = f.read()

        self.KERBEROS_BIND = "USER@REALM"

        self.SIGNING_KEY_FILE = os.path.join(KEYDIR, "signing_key.pem")
        with open(self.SIGNING_KEY_FILE) as f:
            self.SIGNING_KEY = f.read()

        self.SIGNING_CA_FILE = os.path.join(CERTDIR, "cacert.pem")
        with open(self.SIGNING_CA_FILE) as f:
            self.SIGNING_CA = f.read()

        self.UUID_TOKEN_DEFAULT = "ec6c0710ec2f471498484c1b53ab4f9d"
        self.UUID_TOKEN_NO_SERVICE_CATALOG = "8286720fbe4941e69fa8241723bb02df"
        self.UUID_TOKEN_UNSCOPED = "731f903721c14827be7b2dc912af7776"
        self.UUID_TOKEN_BIND = "3fc54048ad64405c98225ce0897af7c5"
        self.UUID_TOKEN_UNKNOWN_BIND = "8885fdf4d42e4fb9879e6379fa1eaf48"
        self.VALID_DIABLO_TOKEN = "b0cf19b55dbb4f20a6ee18e6c6cf1726"
        self.v3_UUID_TOKEN_DEFAULT = "5603457654b346fdbb93437bfe76f2f1"
        self.v3_UUID_TOKEN_UNSCOPED = "d34835fdaec447e695a0a024d84f8d79"
        self.v3_UUID_TOKEN_DOMAIN_SCOPED = "e8a7b63aaa4449f38f0c5c05c3581792"
        self.v3_UUID_TOKEN_BIND = "2f61f73e1c854cbb9534c487f9bd63c2"
        self.v3_UUID_TOKEN_UNKNOWN_BIND = "7ed9781b62cd4880b8d8c6788ab1d1e2"

        revoked_token = self.REVOKED_TOKEN
        if isinstance(revoked_token, six.text_type):
            revoked_token = revoked_token.encode("utf-8")
        self.REVOKED_TOKEN_HASH = utils.hash_signed_token(revoked_token)
        self.REVOKED_TOKEN_LIST = {"revoked": [{"id": self.REVOKED_TOKEN_HASH, "expires": timeutils.utcnow()}]}
        self.REVOKED_TOKEN_LIST_JSON = jsonutils.dumps(self.REVOKED_TOKEN_LIST)

        revoked_v3_token = self.REVOKED_v3_TOKEN
        if isinstance(revoked_v3_token, six.text_type):
            revoked_v3_token = revoked_v3_token.encode("utf-8")
        self.REVOKED_v3_TOKEN_HASH = utils.hash_signed_token(revoked_v3_token)
        self.REVOKED_v3_TOKEN_LIST = {"revoked": [{"id": self.REVOKED_v3_TOKEN_HASH, "expires": timeutils.utcnow()}]}
        self.REVOKED_v3_TOKEN_LIST_JSON = jsonutils.dumps(self.REVOKED_v3_TOKEN_LIST)

        self.SIGNED_TOKEN_SCOPED_KEY = cms.cms_hash_token(self.SIGNED_TOKEN_SCOPED)
        self.SIGNED_TOKEN_UNSCOPED_KEY = cms.cms_hash_token(self.SIGNED_TOKEN_UNSCOPED)
        self.SIGNED_v3_TOKEN_SCOPED_KEY = cms.cms_hash_token(self.SIGNED_v3_TOKEN_SCOPED)

        self.INVALID_SIGNED_TOKEN = (
            "MIIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
            "BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB"
            "CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC"
            "DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD"
            "EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE"
            "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
            "0000000000000000000000000000000000000000000000000000000000000000"
            "1111111111111111111111111111111111111111111111111111111111111111"
            "2222222222222222222222222222222222222222222222222222222222222222"
            "3333333333333333333333333333333333333333333333333333333333333333"
            "4444444444444444444444444444444444444444444444444444444444444444"
            "5555555555555555555555555555555555555555555555555555555555555555"
            "6666666666666666666666666666666666666666666666666666666666666666"
            "7777777777777777777777777777777777777777777777777777777777777777"
            "8888888888888888888888888888888888888888888888888888888888888888"
            "9999999999999999999999999999999999999999999999999999999999999999"
            "0000000000000000000000000000000000000000000000000000000000000000"
        )

        # JSON responses keyed by token ID
        self.TOKEN_RESPONSES = {
            self.UUID_TOKEN_DEFAULT: {
                "access": {
                    "token": {
                        "id": self.UUID_TOKEN_DEFAULT,
                        "expires": "2020-01-01T00:00:10.000123Z",
                        "tenant": {"id": "tenant_id1", "name": "tenant_name1"},
                    },
                    "user": {"id": "user_id1", "name": "user_name1", "roles": [{"name": "role1"}, {"name": "role2"}]},
                    "serviceCatalog": {},
                }
            },
            self.VALID_DIABLO_TOKEN: {
                "access": {
                    "token": {
                        "id": self.VALID_DIABLO_TOKEN,
                        "expires": "2020-01-01T00:00:10.000123Z",
                        "tenantId": "tenant_id1",
                    },
                    "user": {"id": "user_id1", "name": "user_name1", "roles": [{"name": "role1"}, {"name": "role2"}]},
                }
            },
            self.UUID_TOKEN_UNSCOPED: {
                "access": {
                    "token": {"id": self.UUID_TOKEN_UNSCOPED, "expires": "2020-01-01T00:00:10.000123Z"},
                    "user": {"id": "user_id1", "name": "user_name1", "roles": [{"name": "role1"}, {"name": "role2"}]},
                }
            },
            self.UUID_TOKEN_NO_SERVICE_CATALOG: {
                "access": {
                    "token": {
                        "id": "valid-token",
                        "expires": "2020-01-01T00:00:10.000123Z",
                        "tenant": {"id": "tenant_id1", "name": "tenant_name1"},
                    },
                    "user": {"id": "user_id1", "name": "user_name1", "roles": [{"name": "role1"}, {"name": "role2"}]},
                }
            },
            self.UUID_TOKEN_BIND: {
                "access": {
                    "token": {
                        "bind": {"kerberos": self.KERBEROS_BIND},
                        "id": self.UUID_TOKEN_BIND,
                        "expires": "2020-01-01T00:00:10.000123Z",
                        "tenant": {"id": "tenant_id1", "name": "tenant_name1"},
                    },
                    "user": {"id": "user_id1", "name": "user_name1", "roles": [{"name": "role1"}, {"name": "role2"}]},
                    "serviceCatalog": {},
                }
            },
            self.UUID_TOKEN_UNKNOWN_BIND: {
                "access": {
                    "token": {
                        "bind": {"FOO": "BAR"},
                        "id": self.UUID_TOKEN_UNKNOWN_BIND,
                        "expires": "2020-01-01T00:00:10.000123Z",
                        "tenant": {"id": "tenant_id1", "name": "tenant_name1"},
                    },
                    "user": {"id": "user_id1", "name": "user_name1", "roles": [{"name": "role1"}, {"name": "role2"}]},
                    "serviceCatalog": {},
                }
            },
            self.v3_UUID_TOKEN_DEFAULT: {
                "token": {
                    "expires_at": "2020-01-01T00:00:10.000123Z",
                    "user": {
                        "id": "user_id1",
                        "name": "user_name1",
                        "domain": {"id": "domain_id1", "name": "domain_name1"},
                    },
                    "project": {
                        "id": "tenant_id1",
                        "name": "tenant_name1",
                        "domain": {"id": "domain_id1", "name": "domain_name1"},
                    },
                    "roles": [{"name": "role1", "id": "Role1"}, {"name": "role2", "id": "Role2"}],
                    "catalog": {},
                }
            },
            self.v3_UUID_TOKEN_UNSCOPED: {
                "token": {
                    "expires_at": "2020-01-01T00:00:10.000123Z",
                    "user": {
                        "id": "user_id1",
                        "name": "user_name1",
                        "domain": {"id": "domain_id1", "name": "domain_name1"},
                    },
                }
            },
            self.v3_UUID_TOKEN_DOMAIN_SCOPED: {
                "token": {
                    "expires_at": "2020-01-01T00:00:10.000123Z",
                    "user": {
                        "id": "user_id1",
                        "name": "user_name1",
                        "domain": {"id": "domain_id1", "name": "domain_name1"},
                    },
                    "domain": {"id": "domain_id1", "name": "domain_name1"},
                    "roles": [{"name": "role1", "id": "Role1"}, {"name": "role2", "id": "Role2"}],
                    "catalog": {},
                }
            },
            self.SIGNED_TOKEN_SCOPED_KEY: {
                "access": {
                    "token": {"id": self.SIGNED_TOKEN_SCOPED_KEY},
                    "user": {
                        "id": "user_id1",
                        "name": "user_name1",
                        "tenantId": "tenant_id1",
                        "tenantName": "tenant_name1",
                        "roles": [{"name": "role1"}, {"name": "role2"}],
                    },
                }
            },
            self.SIGNED_TOKEN_UNSCOPED_KEY: {
                "access": {
                    "token": {"id": self.SIGNED_TOKEN_UNSCOPED_KEY},
                    "user": {"id": "user_id1", "name": "user_name1", "roles": [{"name": "role1"}, {"name": "role2"}]},
                }
            },
            self.SIGNED_v3_TOKEN_SCOPED_KEY: {
                "token": {
                    "expires": "2020-01-01T00:00:10.000123Z",
                    "user": {
                        "id": "user_id1",
                        "name": "user_name1",
                        "domain": {"id": "domain_id1", "name": "domain_name1"},
                    },
                    "project": {
                        "id": "tenant_id1",
                        "name": "tenant_name1",
                        "domain": {"id": "domain_id1", "name": "domain_name1"},
                    },
                    "roles": [{"name": "role1"}, {"name": "role2"}],
                    "catalog": {},
                }
            },
            self.v3_UUID_TOKEN_BIND: {
                "token": {
                    "bind": {"kerberos": self.KERBEROS_BIND},
                    "expires_at": "2020-01-01T00:00:10.000123Z",
                    "user": {
                        "id": "user_id1",
                        "name": "user_name1",
                        "domain": {"id": "domain_id1", "name": "domain_name1"},
                    },
                    "project": {
                        "id": "tenant_id1",
                        "name": "tenant_name1",
                        "domain": {"id": "domain_id1", "name": "domain_name1"},
                    },
                    "roles": [{"name": "role1", "id": "Role1"}, {"name": "role2", "id": "Role2"}],
                    "catalog": {},
                }
            },
            self.v3_UUID_TOKEN_UNKNOWN_BIND: {
                "token": {
                    "bind": {"FOO": "BAR"},
                    "expires_at": "2020-01-01T00:00:10.000123Z",
                    "user": {
                        "id": "user_id1",
                        "name": "user_name1",
                        "domain": {"id": "domain_id1", "name": "domain_name1"},
                    },
                    "project": {
                        "id": "tenant_id1",
                        "name": "tenant_name1",
                        "domain": {"id": "domain_id1", "name": "domain_name1"},
                    },
                    "roles": [{"name": "role1", "id": "Role1"}, {"name": "role2", "id": "Role2"}],
                    "catalog": {},
                }
            },
        }

        self.JSON_TOKEN_RESPONSES = dict([(k, jsonutils.dumps(v)) for k, v in six.iteritems(self.TOKEN_RESPONSES)])
 def get_revocation_list_json(self, token_ids=None):
     if token_ids is None:
         token_ids = [self.token_dict["revoked_token_hash"]]
     revocation_list = {"revoked": [{"id": x, "expires": timeutils.utcnow()} for x in token_ids]}
     return jsonutils.dumps(revocation_list)
    SIGNED_REVOCATION_LIST = jsonutils.dumps({"signed": f.read()})
with open(os.path.join(CERTDIR, "signing_cert.pem")) as f:
    SIGNING_CERT = f.read()
with open(os.path.join(CERTDIR, "cacert.pem")) as f:
    SIGNING_CA = f.read()

UUID_TOKEN_DEFAULT = "ec6c0710ec2f471498484c1b53ab4f9d"
UUID_TOKEN_NO_SERVICE_CATALOG = "8286720fbe4941e69fa8241723bb02df"
UUID_TOKEN_UNSCOPED = "731f903721c14827be7b2dc912af7776"
VALID_DIABLO_TOKEN = "b0cf19b55dbb4f20a6ee18e6c6cf1726"
v3_UUID_TOKEN_DEFAULT = "5603457654b346fdbb93437bfe76f2f1"
v3_UUID_TOKEN_UNSCOPED = "d34835fdaec447e695a0a024d84f8d79"
v3_UUID_TOKEN_DOMAIN_SCOPED = "e8a7b63aaa4449f38f0c5c05c3581792"

REVOKED_TOKEN_HASH = utils.hash_signed_token(REVOKED_TOKEN)
REVOKED_TOKEN_LIST = {"revoked": [{"id": REVOKED_TOKEN_HASH, "expires": timeutils.utcnow()}]}
REVOKED_TOKEN_LIST_JSON = jsonutils.dumps(REVOKED_TOKEN_LIST)

REVOKED_v3_TOKEN_HASH = utils.hash_signed_token(REVOKED_v3_TOKEN)
REVOKED_v3_TOKEN_LIST = {"revoked": [{"id": REVOKED_v3_TOKEN_HASH, "expires": timeutils.utcnow()}]}
REVOKED_v3_TOKEN_LIST_JSON = jsonutils.dumps(REVOKED_v3_TOKEN_LIST)

SIGNED_TOKEN_SCOPED_KEY = cms.cms_hash_token(SIGNED_TOKEN_SCOPED)
SIGNED_TOKEN_UNSCOPED_KEY = cms.cms_hash_token(SIGNED_TOKEN_UNSCOPED)
SIGNED_v3_TOKEN_SCOPED_KEY = cms.cms_hash_token(SIGNED_v3_TOKEN_SCOPED)

INVALID_SIGNED_TOKEN = (
    "MIIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
    "BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB"
    "CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC"
    "DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD"
    def setUp(self):
        super(Examples, self).setUp()

        # The data for several tests are signed using openssl and are stored in
        # files in the signing subdirectory.  In order to keep the values
        # consistent between the tests and the signed documents, we read them
        # in for use in the tests.

        with open(os.path.join(CMSDIR, 'auth_token_scoped.pem')) as f:
            self.SIGNED_TOKEN_SCOPED = cms.cms_to_token(f.read())
        with open(os.path.join(CMSDIR, 'auth_token_unscoped.pem')) as f:
            self.SIGNED_TOKEN_UNSCOPED = cms.cms_to_token(f.read())
        with open(os.path.join(CMSDIR, 'auth_v3_token_scoped.pem')) as f:
            self.SIGNED_v3_TOKEN_SCOPED = cms.cms_to_token(f.read())
        with open(os.path.join(CMSDIR, 'auth_token_revoked.pem')) as f:
            self.REVOKED_TOKEN = cms.cms_to_token(f.read())
        with open(os.path.join(CMSDIR, 'auth_token_scoped_expired.pem')) as f:
            self.SIGNED_TOKEN_SCOPED_EXPIRED = cms.cms_to_token(f.read())
        with open(os.path.join(CMSDIR, 'auth_v3_token_revoked.pem')) as f:
            self.REVOKED_v3_TOKEN = cms.cms_to_token(f.read())
        with open(os.path.join(CMSDIR, 'revocation_list.json')) as f:
            self.REVOCATION_LIST = jsonutils.loads(f.read())
        with open(os.path.join(CMSDIR, 'revocation_list.pem')) as f:
            self.SIGNED_REVOCATION_LIST = jsonutils.dumps({'signed': f.read()})

        self.SIGNING_CERT_FILE = os.path.join(CERTDIR, 'signing_cert.pem')
        with open(self.SIGNING_CERT_FILE) as f:
            self.SIGNING_CERT = f.read()

        self.KERBEROS_BIND = 'USER@REALM'

        self.SIGNING_KEY_FILE = os.path.join(KEYDIR, 'signing_key.pem')
        with open(self.SIGNING_KEY_FILE) as f:
            self.SIGNING_KEY = f.read()

        self.SIGNING_CA_FILE = os.path.join(CERTDIR, 'cacert.pem')
        with open(self.SIGNING_CA_FILE) as f:
            self.SIGNING_CA = f.read()

        self.UUID_TOKEN_DEFAULT = "ec6c0710ec2f471498484c1b53ab4f9d"
        self.UUID_TOKEN_NO_SERVICE_CATALOG = '8286720fbe4941e69fa8241723bb02df'
        self.UUID_TOKEN_UNSCOPED = '731f903721c14827be7b2dc912af7776'
        self.UUID_TOKEN_BIND = '3fc54048ad64405c98225ce0897af7c5'
        self.UUID_TOKEN_UNKNOWN_BIND = '8885fdf4d42e4fb9879e6379fa1eaf48'
        self.VALID_DIABLO_TOKEN = 'b0cf19b55dbb4f20a6ee18e6c6cf1726'
        self.v3_UUID_TOKEN_DEFAULT = '5603457654b346fdbb93437bfe76f2f1'
        self.v3_UUID_TOKEN_UNSCOPED = 'd34835fdaec447e695a0a024d84f8d79'
        self.v3_UUID_TOKEN_DOMAIN_SCOPED = 'e8a7b63aaa4449f38f0c5c05c3581792'
        self.v3_UUID_TOKEN_BIND = '2f61f73e1c854cbb9534c487f9bd63c2'
        self.v3_UUID_TOKEN_UNKNOWN_BIND = '7ed9781b62cd4880b8d8c6788ab1d1e2'

        revoked_token = self.REVOKED_TOKEN
        if isinstance(revoked_token, six.text_type):
            revoked_token = revoked_token.encode('utf-8')
        self.REVOKED_TOKEN_HASH = utils.hash_signed_token(revoked_token)
        self.REVOKED_TOKEN_LIST = (
            {'revoked': [{'id': self.REVOKED_TOKEN_HASH,
                          'expires': timeutils.utcnow()}]})
        self.REVOKED_TOKEN_LIST_JSON = jsonutils.dumps(self.REVOKED_TOKEN_LIST)

        revoked_v3_token = self.REVOKED_v3_TOKEN
        if isinstance(revoked_v3_token, six.text_type):
            revoked_v3_token = revoked_v3_token.encode('utf-8')
        self.REVOKED_v3_TOKEN_HASH = utils.hash_signed_token(revoked_v3_token)
        self.REVOKED_v3_TOKEN_LIST = (
            {'revoked': [{'id': self.REVOKED_v3_TOKEN_HASH,
                          'expires': timeutils.utcnow()}]})
        self.REVOKED_v3_TOKEN_LIST_JSON = jsonutils.dumps(
            self.REVOKED_v3_TOKEN_LIST)

        self.SIGNED_TOKEN_SCOPED_KEY = cms.cms_hash_token(
            self.SIGNED_TOKEN_SCOPED)
        self.SIGNED_TOKEN_UNSCOPED_KEY = cms.cms_hash_token(
            self.SIGNED_TOKEN_UNSCOPED)
        self.SIGNED_v3_TOKEN_SCOPED_KEY = cms.cms_hash_token(
            self.SIGNED_v3_TOKEN_SCOPED)

        self.INVALID_SIGNED_TOKEN = (
            "MIIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
            "BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB"
            "CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC"
            "DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD"
            "EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE"
            "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
            "0000000000000000000000000000000000000000000000000000000000000000"
            "1111111111111111111111111111111111111111111111111111111111111111"
            "2222222222222222222222222222222222222222222222222222222222222222"
            "3333333333333333333333333333333333333333333333333333333333333333"
            "4444444444444444444444444444444444444444444444444444444444444444"
            "5555555555555555555555555555555555555555555555555555555555555555"
            "6666666666666666666666666666666666666666666666666666666666666666"
            "7777777777777777777777777777777777777777777777777777777777777777"
            "8888888888888888888888888888888888888888888888888888888888888888"
            "9999999999999999999999999999999999999999999999999999999999999999"
            "0000000000000000000000000000000000000000000000000000000000000000")

        # JSON responses keyed by token ID
        self.TOKEN_RESPONSES = {
            self.UUID_TOKEN_DEFAULT: {
                'access': {
                    'token': {
                        'id': self.UUID_TOKEN_DEFAULT,
                        'expires': '2020-01-01T00:00:10.000123Z',
                        'tenant': {
                            'id': 'tenant_id1',
                            'name': 'tenant_name1',
                        },
                    },
                    'user': {
                        'id': 'user_id1',
                        'name': 'user_name1',
                        'roles': [
                            {'name': 'role1'},
                            {'name': 'role2'},
                        ],
                    },
                    'serviceCatalog': {}
                },
            },
            self.VALID_DIABLO_TOKEN: {
                'access': {
                    'token': {
                        'id': self.VALID_DIABLO_TOKEN,
                        'expires': '2020-01-01T00:00:10.000123Z',
                        'tenantId': 'tenant_id1',
                    },
                    'user': {
                        'id': 'user_id1',
                        'name': 'user_name1',
                        'roles': [
                            {'name': 'role1'},
                            {'name': 'role2'},
                        ],
                    },
                },
            },
            self.UUID_TOKEN_UNSCOPED: {
                'access': {
                    'token': {
                        'id': self.UUID_TOKEN_UNSCOPED,
                        'expires': '2020-01-01T00:00:10.000123Z',
                    },
                    'user': {
                        'id': 'user_id1',
                        'name': 'user_name1',
                        'roles': [
                            {'name': 'role1'},
                            {'name': 'role2'},
                        ],
                    },
                },
            },
            self.UUID_TOKEN_NO_SERVICE_CATALOG: {
                'access': {
                    'token': {
                        'id': 'valid-token',
                        'expires': '2020-01-01T00:00:10.000123Z',
                        'tenant': {
                            'id': 'tenant_id1',
                            'name': 'tenant_name1',
                        },
                    },
                    'user': {
                        'id': 'user_id1',
                        'name': 'user_name1',
                        'roles': [
                            {'name': 'role1'},
                            {'name': 'role2'},
                        ],
                    }
                },
            },
            self.UUID_TOKEN_BIND: {
                'access': {
                    'token': {
                        'bind': {'kerberos': self.KERBEROS_BIND},
                        'id': self.UUID_TOKEN_BIND,
                        'expires': '2020-01-01T00:00:10.000123Z',
                        'tenant': {
                            'id': 'tenant_id1',
                            'name': 'tenant_name1',
                        },
                    },
                    'user': {
                        'id': 'user_id1',
                        'name': 'user_name1',
                        'roles': [
                            {'name': 'role1'},
                            {'name': 'role2'},
                        ],
                    },
                    'serviceCatalog': {}
                },
            },
            self.UUID_TOKEN_UNKNOWN_BIND: {
                'access': {
                    'token': {
                        'bind': {'FOO': 'BAR'},
                        'id': self.UUID_TOKEN_UNKNOWN_BIND,
                        'expires': '2020-01-01T00:00:10.000123Z',
                        'tenant': {
                            'id': 'tenant_id1',
                            'name': 'tenant_name1',
                        },
                    },
                    'user': {
                        'id': 'user_id1',
                        'name': 'user_name1',
                        'roles': [
                            {'name': 'role1'},
                            {'name': 'role2'},
                        ],
                    },
                    'serviceCatalog': {}
                },
            },
            self.v3_UUID_TOKEN_DEFAULT: {
                'token': {
                    'expires_at': '2020-01-01T00:00:10.000123Z',
                    'user': {
                        'id': 'user_id1',
                        'name': 'user_name1',
                        'domain': {
                            'id': 'domain_id1',
                            'name': 'domain_name1'
                        }
                    },
                    'project': {
                        'id': 'tenant_id1',
                        'name': 'tenant_name1',
                        'domain': {
                            'id': 'domain_id1',
                            'name': 'domain_name1'
                        }
                    },
                    'roles': [
                        {'name': 'role1', 'id': 'Role1'},
                        {'name': 'role2', 'id': 'Role2'},
                    ],
                    'catalog': {}
                }
            },
            self.v3_UUID_TOKEN_UNSCOPED: {
                'token': {
                    'expires_at': '2020-01-01T00:00:10.000123Z',
                    'user': {
                        'id': 'user_id1',
                        'name': 'user_name1',
                        'domain': {
                            'id': 'domain_id1',
                            'name': 'domain_name1'
                        }
                    }
                }
            },
            self.v3_UUID_TOKEN_DOMAIN_SCOPED: {
                'token': {
                    'expires_at': '2020-01-01T00:00:10.000123Z',
                    'user': {
                        'id': 'user_id1',
                        'name': 'user_name1',
                        'domain': {
                            'id': 'domain_id1',
                            'name': 'domain_name1'
                        }
                    },
                    'domain': {
                        'id': 'domain_id1',
                        'name': 'domain_name1',
                    },
                    'roles': [
                        {'name': 'role1', 'id': 'Role1'},
                        {'name': 'role2', 'id': 'Role2'},
                    ],
                    'catalog': {}
                }
            },
            self.SIGNED_TOKEN_SCOPED_KEY: {
                'access': {
                    'token': {
                        'id': self.SIGNED_TOKEN_SCOPED_KEY,
                    },
                    'user': {
                        'id': 'user_id1',
                        'name': 'user_name1',
                        'tenantId': 'tenant_id1',
                        'tenantName': 'tenant_name1',
                        'roles': [
                            {'name': 'role1'},
                            {'name': 'role2'},
                        ],
                    },
                },
            },
            self.SIGNED_TOKEN_UNSCOPED_KEY: {
                'access': {
                    'token': {
                        'id': self.SIGNED_TOKEN_UNSCOPED_KEY,
                    },
                    'user': {
                        'id': 'user_id1',
                        'name': 'user_name1',
                        'roles': [
                            {'name': 'role1'},
                            {'name': 'role2'},
                        ],
                    },
                },
            },
            self.SIGNED_v3_TOKEN_SCOPED_KEY: {
                'token': {
                    'expires': '2020-01-01T00:00:10.000123Z',
                    'user': {
                        'id': 'user_id1',
                        'name': 'user_name1',
                        'domain': {
                            'id': 'domain_id1',
                            'name': 'domain_name1'
                        }
                    },
                    'project': {
                        'id': 'tenant_id1',
                        'name': 'tenant_name1',
                        'domain': {
                            'id': 'domain_id1',
                            'name': 'domain_name1'
                        }
                    },
                    'roles': [
                        {'name': 'role1'},
                        {'name': 'role2'}
                    ],
                    'catalog': {}
                }
            },
            self.v3_UUID_TOKEN_BIND: {
                'token': {
                    'bind': {'kerberos': self.KERBEROS_BIND},
                    'expires_at': '2020-01-01T00:00:10.000123Z',
                    'user': {
                        'id': 'user_id1',
                        'name': 'user_name1',
                        'domain': {
                            'id': 'domain_id1',
                            'name': 'domain_name1'
                        }
                    },
                    'project': {
                        'id': 'tenant_id1',
                        'name': 'tenant_name1',
                        'domain': {
                            'id': 'domain_id1',
                            'name': 'domain_name1'
                        }
                    },
                    'roles': [
                        {'name': 'role1', 'id': 'Role1'},
                        {'name': 'role2', 'id': 'Role2'},
                    ],
                    'catalog': {}
                }
            },
            self.v3_UUID_TOKEN_UNKNOWN_BIND: {
                'token': {
                    'bind': {'FOO': 'BAR'},
                    'expires_at': '2020-01-01T00:00:10.000123Z',
                    'user': {
                        'id': 'user_id1',
                        'name': 'user_name1',
                        'domain': {
                            'id': 'domain_id1',
                            'name': 'domain_name1'
                        }
                    },
                    'project': {
                        'id': 'tenant_id1',
                        'name': 'tenant_name1',
                        'domain': {
                            'id': 'domain_id1',
                            'name': 'domain_name1'
                        }
                    },
                    'roles': [
                        {'name': 'role1', 'id': 'Role1'},
                        {'name': 'role2', 'id': 'Role2'},
                    ],
                    'catalog': {}
                }
            },
        }

        self.JSON_TOKEN_RESPONSES = dict([(k, jsonutils.dumps(v)) for k, v in
                                          six.iteritems(self.TOKEN_RESPONSES)])