def generate_trust_ids(users_to_delete):
    """
    From a list of users to delete, generate a file with a trustid for each
    user. The user is acting as the trustor, delegating in a trustee, which
    will impersonate it to delete its resources.

    :param users_to_delete: a list of trustors.
    :return: this function does not return anything. It creates a file.
    """
    global logger

    osclients = OpenStackClients()
    users_trusted_ids = open('users_trusted_ids.txt', 'w')
    check_users = CheckUsers()

    # Use an alternative URL that allow direct access to the keystone admin
    # endpoint, because the registered one uses an internal IP address.

    osclients.override_endpoint(
        'identity', osclients.region, 'admin', KEYSTONE_ENDPOINT)

    trust_factory = TrustFactory(osclients)
    lines = users_to_delete.readlines()
    total = len(lines)
    count = 0
    if 'TRUSTEE_USER' in env:
        trustee = env['TRUSTEE_USER']
    else:
        trustee = TRUSTEE

    for user in lines:
        user = user.strip()
        if user == '':
            continue
        try:
            count += 1
            (username, trust_id) = trust_factory.create_trust_admin(
                user, trustee)
            users_trusted_ids.write(username + ',' + trust_id + '\n')
            msg = 'Generated trustid for user {0} ({1}/{2})'
            logger.info(msg.format(user, count, total))
        except Exception, e:
            msg = 'Failed getting trust-id from trustor {0}. Reason: {1}'
            logger.error(msg.format(user, str(e)))
def generate_trust_ids(users_to_delete):
    """
    From a list of users to delete, generate a file with a trustid for each
    user. The user is acting as the trustor, delegating in a trustee, which
    will impersonate it to delete its resources.

    :param users_to_delete: a list of trustors.
    :return: this function does not return anything. It creates a file.
    """
    global logger

    osclients = OpenStackClients()
    users_trusted_ids = open('users_trusted_ids.txt', 'w')
    check_users = CheckUsers()

    # Use an alternative URL that allow direct access to the keystone admin
    # endpoint, because the registered one uses an internal IP address.

    osclients.override_endpoint('identity', osclients.region, 'admin',
                                KEYSTONE_ENDPOINT)

    trust_factory = TrustFactory(osclients)
    lines = users_to_delete.readlines()
    total = len(lines)
    count = 0
    if 'TRUSTEE_USER' in env:
        trustee = env['TRUSTEE_USER']
    else:
        trustee = TRUSTEE

    for user in lines:
        user = user.strip()
        if user == '':
            continue
        try:
            count += 1
            (username,
             trust_id) = trust_factory.create_trust_admin(user, trustee)
            users_trusted_ids.write(username + ',' + trust_id + '\n')
            msg = 'Generated trustid for user {0} ({1}/{2})'
            logger.info(msg.format(user, count, total))
        except Exception, e:
            msg = 'Failed getting trust-id from trustor {0}. Reason: {1}'
            logger.error(msg.format(user, str(e)))
Esempio n. 3
0
class TestOSClientsOverrideEndpoint(TestCase):
    """Class to test the endpoint override feature"""

    def setUp(self):
        d = defaultdict(list)
        d['catalog'].append(service)
        self.access = d
        self.osclients = OpenStackClients()
        self.url = 'http://fake.org:9090'
        self.original_url = service['endpoints'][1]['url']

    def restore_catalog(self):
        """restore catalog"""
        service['endpoints'][1]['url'] = self.original_url

    def tearDown(self):
        """restore objects"""
        self.restore_catalog()

    def override_endpoint(self):
        """method that override the endpoint"""
        self.osclients.override_endpoint('object-store', 'Spain2', 'admin', self.url)

    def assertOverrideEndpoint(self):
        """check that the override has been done"""
        self.assertEquals(self.osclients.get_admin_endpoint('object-store', 'Spain2'), self.url)

    def test_override_endpoint_session(self):
        """test that invoking override endpoint does not create a session"""
        self.override_endpoint()

        self.assertFalse(self.osclients._session_v2)
        self.assertFalse(self.osclients._session_v3)

    def test_override_endpoint(self):
        """check that a session catalog is overriden"""
        mock = MagicMock()
        config = {'auth.get_access.return_value': self.access}
        mock.configure_mock(**config)
        self.osclients._session_v3 = mock
        self.override_endpoint()
        self.assertOverrideEndpoint()

    @patch('fiwareskuld.utils.osclients.session')
    def test_override_endpoint_multiple(self, mock):
        """test that override works with an already created session and then
        with a new one without invoking the method again"""
        config = {'Session.return_value.auth.get_access.return_value': self.access}
        mock.configure_mock(**config)
        session = self.osclients.get_session()
        self.override_endpoint()
        self.assertOverrideEndpoint()

        # invalidate and create a new session; ensure than catalog is again
        # the original. Setting a new token invalidate the session. The new
        # one is created at the invocation of get_admin_endpoint.
        self.restore_catalog()
        self.osclients.set_token('faketoken')

        # check again
        self.assertOverrideEndpoint()
            {'name': usertocheck.name})
        return True
    else:
        return False

logger.debug('Getting expired users')
(next_to_expire, expired_users) = ExpiredUsers(
    username=env['OS_USERNAME'], password=env['OS_PASSWORD'],
    tenant=env['OS_TENANT_NAME']).get_yellow_red_users()

osclients = OpenStackClients()

# Use an alternative URL that allow direct access to the keystone admin
# endpoint, because the registered one uses an internal IP address.

osclients.override_endpoint(
    'identity', osclients.region, 'admin', settings.KEYSTONE_ENDPOINT)

keystone = osclients.get_keystoneclientv3()


# build users map
logger.debug('Building user map')
users_by_id = dict()
for user in keystone.users.list():
    users_by_id[user.id] = user

with open('users_to_delete.txt', 'w') as fich_delete:
    logger.debug('Generating user delete list')
    for user_id in expired_users:
        if not is_user_protected(users_by_id[user_id]):
            fich_delete.write(user_id + "\n")
Esempio n. 5
0
class TestOSClientsOverrideEndpoint(TestCase):
    """Class to test the endpoint override feature"""
    def setUp(self):
        d = defaultdict(list)
        d['catalog'].append(service)
        self.access = d
        self.osclients = OpenStackClients()
        self.url = 'http://fake.org:9090'
        self.original_url = service['endpoints'][1]['url']

    def restore_catalog(self):
        """restore catalog"""
        service['endpoints'][1]['url'] = self.original_url

    def tearDown(self):
        """restore objects"""
        self.restore_catalog()

    def override_endpoint(self):
        """method that override the endpoint"""
        self.osclients.override_endpoint('object-store', 'Spain2', 'admin',
                                         self.url)

    def assertOverrideEndpoint(self):
        """check that the override has been done"""
        self.assertEquals(
            self.osclients.get_admin_endpoint('object-store', 'Spain2'),
            self.url)

    def test_override_endpoint_session(self):
        """test that invoking override endpoint does not create a session"""
        self.override_endpoint()

        self.assertFalse(self.osclients._session_v2)
        self.assertFalse(self.osclients._session_v3)

    def test_override_endpoint(self):
        """check that a session catalog is overriden"""
        mock = MagicMock()
        config = {'auth.get_access.return_value': self.access}
        mock.configure_mock(**config)
        self.osclients._session_v3 = mock
        self.override_endpoint()
        self.assertOverrideEndpoint()

    @patch('fiwareskuld.utils.osclients.session')
    def test_override_endpoint_multiple(self, mock):
        """test that override works with an already created session and then
        with a new one without invoking the method again"""
        config = {
            'Session.return_value.auth.get_access.return_value': self.access
        }
        mock.configure_mock(**config)
        session = self.osclients.get_session()
        self.override_endpoint()
        self.assertOverrideEndpoint()

        # invalidate and create a new session; ensure than catalog is again
        # the original. Setting a new token invalidate the session. The new
        # one is created at the invocation of get_admin_endpoint.
        self.restore_catalog()
        self.osclients.set_token('faketoken')

        # check again
        self.assertOverrideEndpoint()