Python oslo_context.context.RequestContext() Examples

The following are 30 code examples of oslo_context.context.RequestContext(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module oslo_context.context , or try the search function .
Example #1
Source File: test_enginefacade.py    From oslo.db with Apache License 2.0 6 votes vote down vote up
def test_deprecated_async_reader_name(self):
        if sys.version_info >= (3, 7):
            self.skipTest("Test only runs on Python < 3.7")

        context = oslo_context.RequestContext()

        old = getattr(enginefacade.reader, "async")

        @old
        def go1(context):
            context.session.execute("test1")

        go1(context)

        with self._assert_engines() as engines:
            with self._assert_makers(engines) as makers:
                with self._assert_async_reader_session(
                        makers, assert_calls=False) as session:
                    session.execute("test1") 
Example #2
Source File: rest_api_driver.py    From octavia with Apache License 2.0 6 votes vote down vote up
def _process_secret(self, listener, secret_ref, amphora=None, obj_id=None):
        """Get the secret from the cert manager and upload it to the amp.

        :returns: The filename of the secret in the amp.
        """
        if not secret_ref:
            return None
        context = oslo_context.RequestContext(project_id=listener.project_id)
        secret = self.cert_manager.get_secret(context, secret_ref)
        try:
            secret = secret.encode('utf-8')
        except AttributeError:
            pass
        md5 = hashlib.md5(secret).hexdigest()  # nosec
        id = hashlib.sha1(secret).hexdigest()  # nosec
        name = '{id}.pem'.format(id=id)

        if amphora and obj_id:
            self._upload_cert(
                amphora, obj_id, pem=secret, md5=md5, name=name)
        return name 
Example #3
Source File: utils.py    From octavia with Apache License 2.0 6 votes vote down vote up
def _get_secret_data(cert_manager, project_id, secret_ref, for_delete=False):
    """Get the secret from the certificate manager and upload it to the amp.

    :returns: The secret data.
    """
    context = oslo_context.RequestContext(project_id=project_id)
    try:
        secret_data = cert_manager.get_secret(context, secret_ref)
    except Exception as e:
        LOG.warning('Unable to retrieve certificate: %s due to %s.',
                    secret_ref, str(e))
        if for_delete:
            secret_data = None
        else:
            raise exceptions.CertificateRetrievalException(ref=secret_ref)
    return secret_data 
Example #4
Source File: test_barbican_key_manager.py    From castellan with Apache License 2.0 6 votes vote down vote up
def get_context(self):
        username = CONF.identity.username
        password = CONF.identity.password
        project_name = CONF.identity.project_name
        auth_url = CONF.identity.auth_url
        user_domain_name = CONF.identity.user_domain_name
        project_domain_name = CONF.identity.project_domain_name

        auth = identity.V3Password(auth_url=auth_url,
                                   username=username,
                                   password=password,
                                   project_name=project_name,
                                   user_domain_name=user_domain_name,
                                   project_domain_name=project_domain_name)
        sess = session.Session(auth=auth)

        return context.RequestContext(auth_token=auth.get_token(sess),
                                      tenant=auth.get_project_id(sess)) 
Example #5
Source File: test_utils.py    From castellan with Apache License 2.0 6 votes vote down vote up
def test_token_credential_config_override_context(self):
        ctxt_token_value = '00000000000000000000000000000000'
        ctxt = context.RequestContext(auth_token=ctxt_token_value)

        conf_token_value = 'ec9799cd921e4e0a8ab6111c08ebf065'

        self.config_fixture.config(
            auth_type='token',
            token=conf_token_value,
            group='key_manager'
        )

        token_context = utils.credential_factory(conf=CONF, context=ctxt)
        token_context_class = token_context.__class__.__name__

        self.assertEqual('Token', token_context_class)
        self.assertEqual(conf_token_value, token_context.token) 
Example #6
Source File: context.py    From ec2-api with Apache License 2.0 6 votes vote down vote up
def to_dict(self):
        values = super(RequestContext, self).to_dict()
        # FIXME(dims): defensive hasattr() checks need to be
        # removed once we figure out why we are seeing stack
        # traces
        values.update({
            'user_id': getattr(self, 'user_id', None),
            'project_id': getattr(self, 'project_id', None),
            'is_admin': getattr(self, 'is_admin', None),
            'remote_address': getattr(self, 'remote_address', None),
            'timestamp': self.timestamp.strftime(
                timeutils.PERFECT_TIME_FORMAT) if hasattr(
                self, 'timestamp') else None,
            'request_id': getattr(self, 'request_id', None),
            'quota_class': getattr(self, 'quota_class', None),
            'user_name': getattr(self, 'user_name', None),
            'service_catalog': getattr(self, 'service_catalog', None),
            'project_name': getattr(self, 'project_name', None),
            'is_os_admin': getattr(self, 'is_os_admin', None),
            'api_version': getattr(self, 'api_version', None),
        })
        return values 
Example #7
Source File: context.py    From magnum with Apache License 2.0 6 votes vote down vote up
def to_dict(self):
        value = super(RequestContext, self).to_dict()
        value.update({'auth_token': self.auth_token,
                      'auth_url': self.auth_url,
                      'domain_id': self.domain_id,
                      'domain_name': self.domain_name,
                      'user_domain_id': self.user_domain_id,
                      'user_domain_name': self.user_domain_name,
                      'user_name': self.user_name,
                      'user_id': self.user_id,
                      'project_name': self.project_name,
                      'project_id': self.project_id,
                      'is_admin': self.is_admin,
                      'read_only': self.read_only,
                      'roles': self.roles,
                      'show_deleted': self.show_deleted,
                      'request_id': self.request_id,
                      'trust_id': self.trust_id,
                      'auth_token_info': self.auth_token_info,
                      'password': self.password,
                      'all_tenants': self.all_tenants})
        return value 
Example #8
Source File: context.py    From masakari with Apache License 2.0 6 votes vote down vote up
def to_dict(self):
        values = super(RequestContext, self).to_dict()
        # FIXME: defensive hasattr() checks need to be
        # removed once we figure out why we are seeing stack
        # traces
        values.update({
            'user_id': getattr(self, 'user_id', None),
            'project_id': getattr(self, 'project_id', None),
            'is_admin': getattr(self, 'is_admin', None),
            'read_deleted': getattr(self, 'read_deleted', 'no'),
            'remote_address': getattr(self, 'remote_address', None),
            'timestamp': utils.strtime(self.timestamp) if hasattr(
                self, 'timestamp') else None,
            'request_id': getattr(self, 'request_id', None),
            'user_name': getattr(self, 'user_name', None),
            'service_catalog': getattr(self, 'service_catalog', None),
            'project_name': getattr(self, 'project_name', None)
        })
        return values 
Example #9
Source File: hooks.py    From vitrage with Apache License 2.0 6 votes vote down vote up
def before(self, state):
        user_id = state.request.headers.get('X-User-Id')
        user_id = state.request.headers.get('X-User', user_id)
        user_name = state.request.headers.get('X-User-Name', '')
        tenant_id = state.request.headers.get('X-Project-Id')
        auth_token = state.request.headers.get('X-Auth-Token')
        # TODO(DANY) use roles
        # roles = pecan.request.headers.get('X-Roles', '').split(',')
        # roles = [r.strip() for r in roles]
        ctx = context.RequestContext(auth_token=auth_token, user=user_id,
                                     # roles=roles,
                                     tenant=tenant_id,
                                     is_admin=(user_name == 'admin'))

        # Inject the context...
        state.request.context = ctx.to_dict() 
Example #10
Source File: test_context.py    From oslo.context with Apache License 2.0 6 votes vote down vote up
def test_from_dict_unknown_keys(self):
        dct = {
            "auth_token": "token1",
            "user": "user1",
            "read_only": True,
            "roles": "role1,role2,role3",  # future review provides this
            "color": "red",
            "unknown": ""
        }
        ctx = context.RequestContext.from_dict(dct)
        self.assertEqual("token1", ctx.auth_token)
        self.assertEqual("user1", ctx.user_id)
        self.assertIsNone(ctx.project_id)
        self.assertFalse(ctx.is_admin)
        self.assertTrue(ctx.read_only)
        self.assertRaises(KeyError, lambda: ctx.__dict__['color']) 
Example #11
Source File: test_context.py    From oslo.context with Apache License 2.0 6 votes vote down vote up
def test_from_dict_overrides(self):
        dct = {
            "auth_token": "token1",
            "user": "user1",
            "read_only": True,
            "roles": "role1,role2,role3",
            "color": "red",
            "unknown": ""
        }
        ctx = context.RequestContext.from_dict(dct,
                                               user="user2",
                                               project_name="project1")
        self.assertEqual("token1", ctx.auth_token)
        self.assertEqual("user2", ctx.user)
        self.assertEqual("project1", ctx.project_name)
        self.assertIsNone(ctx.tenant)
        self.assertFalse(ctx.is_admin)
        self.assertTrue(ctx.read_only) 
Example #12
Source File: test_enginefacade.py    From oslo.db with Apache License 2.0 6 votes vote down vote up
def test_session_reader_nested_in_connection_reader(self):
        context = oslo_context.RequestContext()

        @enginefacade.reader.connection
        def go1(context):
            context.connection.execute("test1")
            go2(context)

        @enginefacade.reader
        def go2(context):
            context.session.execute("test2")
        go1(context)

        with self._assert_engines() as engines:
            with self._assert_reader_connection(engines) as connection:
                connection.execute("test1")
                with self._assert_makers(engines) as makers:
                    with self._assert_reader_session(
                            makers, connection) as session:
                        session.execute("test2") 
Example #13
Source File: test_enginefacade.py    From oslo.db with Apache License 2.0 6 votes vote down vote up
def test_connection_reader_nested_in_session_reader(self):
        context = oslo_context.RequestContext()

        @enginefacade.reader
        def go1(context):
            context.session.execute("test1")
            go2(context)

        @enginefacade.reader.connection
        def go2(context):
            context.connection.execute("test2")

        go1(context)

        with self._assert_engines() as engines:
            with self._assert_makers(engines) as makers:
                with self._assert_reader_session(makers) as session:
                    session.execute("test1")
                    with self._assert_reader_connection(
                            engines, session) as connection:
                        connection.execute("test2") 
Example #14
Source File: test_enginefacade.py    From oslo.db with Apache License 2.0 6 votes vote down vote up
def test_reader_nested_in_writer_ok(self):
        context = oslo_context.RequestContext()

        @enginefacade.writer
        def go1(context):
            context.session.execute("test1")
            go2(context)

        @enginefacade.reader
        def go2(context):
            context.session.execute("test2")

        go1(context)
        with self._assert_engines() as engines:
            with self._assert_makers(engines) as makers:
                with self._assert_writer_session(makers) as session:
                    session.execute("test1")
                    session.execute("test2") 
Example #15
Source File: test_enginefacade.py    From oslo.db with Apache License 2.0 6 votes vote down vote up
def test_writer_nested_in_reader_raises(self):
        context = oslo_context.RequestContext()

        @enginefacade.reader
        def go1(context):
            context.session.execute("test1")
            go2(context)

        @enginefacade.writer
        def go2(context):
            context.session.execute("test2")

        exc = self.assertRaises(
            TypeError, go1, context
        )
        self.assertEqual(
            "Can't upgrade a READER "
            "transaction to a WRITER mid-transaction",
            exc.args[0]
        ) 
Example #16
Source File: test_enginefacade.py    From oslo.db with Apache License 2.0 6 votes vote down vote up
def test_reader_nested_in_async_reader_raises(self):
        context = oslo_context.RequestContext()

        @enginefacade.reader.async_
        def go1(context):
            context.session.execute("test1")
            go2(context)

        @enginefacade.reader
        def go2(context):
            context.session.execute("test2")

        exc = self.assertRaises(
            TypeError, go1, context
        )
        self.assertEqual(
            "Can't upgrade an ASYNC_READER transaction "
            "to a READER mid-transaction",
            exc.args[0]
        ) 
Example #17
Source File: context.py    From watcher with Apache License 2.0 6 votes vote down vote up
def to_dict(self):
        values = super(RequestContext, self).to_dict()
        # FIXME(dims): defensive hasattr() checks need to be
        # removed once we figure out why we are seeing stack
        # traces
        values.update({
            'user_id': getattr(self, 'user_id', None),
            'user_name': getattr(self, 'user_name', None),
            'project_id': getattr(self, 'project_id', None),
            'project_name': getattr(self, 'project_name', None),
            'domain_id': getattr(self, 'domain_id', None),
            'domain_name': getattr(self, 'domain_name', None),
            'auth_token_info': getattr(self, 'auth_token_info', None),
            'is_admin': getattr(self, 'is_admin', None),
            'timestamp': self.timestamp.isoformat() if hasattr(
                self, 'timestamp') else None,
            'request_id': getattr(self, 'request_id', None),
        })
        return values 
Example #18
Source File: context.py    From zun with Apache License 2.0 6 votes vote down vote up
def to_dict(self):
        value = super(RequestContext, self).to_dict()
        value.update({'auth_token': self.auth_token,
                      'domain_id': self.domain_id,
                      'domain_name': self.domain_name,
                      'user_domain_id': self.user_domain_id,
                      'user_domain_name': self.user_domain_name,
                      'user_name': self.user_name,
                      'user_id': self.user_id,
                      'project_name': self.project_name,
                      'project_id': self.project_id,
                      'is_admin': self.is_admin,
                      'read_only': self.read_only,
                      'roles': self.roles,
                      'show_deleted': self.show_deleted,
                      'request_id': self.request_id,
                      'trust_id': self.trust_id,
                      'auth_token_info': self.auth_token_info,
                      'password': self.password,
                      'all_projects': self.all_projects,
                      'timestamp': timeutils.strtime(self.timestamp) if
                      hasattr(self, 'timestamp') else None
                      })
        return value 
Example #19
Source File: test_enginefacade.py    From oslo.db with Apache License 2.0 6 votes vote down vote up
def test_reader_allow_async_nested_in_async_reader(self):
        context = oslo_context.RequestContext()

        @enginefacade.reader.async_
        def go1(context):
            context.session.execute("test1")
            go2(context)

        @enginefacade.reader.allow_async
        def go2(context):
            context.session.execute("test2")

        go1(context)

        with self._assert_engines() as engines:
            with self._assert_makers(engines) as makers:
                with self._assert_async_reader_session(makers) as session:
                    session.execute("test1")
                    session.execute("test2") 
Example #20
Source File: test_enginefacade.py    From oslo.db with Apache License 2.0 6 votes vote down vote up
def test_reader_allow_async_nested_in_reader(self):
        context = oslo_context.RequestContext()

        @enginefacade.reader.reader
        def go1(context):
            context.session.execute("test1")
            go2(context)

        @enginefacade.reader.allow_async
        def go2(context):
            context.session.execute("test2")

        go1(context)

        with self._assert_engines() as engines:
            with self._assert_makers(engines) as makers:
                with self._assert_reader_session(makers) as session:
                    session.execute("test1")
                    session.execute("test2") 
Example #21
Source File: test_enginefacade.py    From oslo.db with Apache License 2.0 6 votes vote down vote up
def test_writer_nested_in_async_reader_raises(self):
        context = oslo_context.RequestContext()

        @enginefacade.reader.async_
        def go1(context):
            context.session.execute("test1")
            go2(context)

        @enginefacade.writer
        def go2(context):
            context.session.execute("test2")

        exc = self.assertRaises(
            TypeError, go1, context
        )
        self.assertEqual(
            "Can't upgrade an ASYNC_READER transaction to a "
            "WRITER mid-transaction",
            exc.args[0]
        ) 
Example #22
Source File: test_enginefacade.py    From oslo.db with Apache License 2.0 6 votes vote down vote up
def test_reader_then_writer_ok(self):
        context = oslo_context.RequestContext()

        @enginefacade.reader
        def go1(context):
            context.session.execute("test1")

        @enginefacade.writer
        def go2(context):
            context.session.execute("test2")

        go1(context)
        go2(context)

        with self._assert_engines() as engines:
            with self._assert_makers(engines) as makers:
                with self._assert_reader_session(
                        makers, assert_calls=False) as session:
                    session.execute("test1")
                with self._assert_writer_session(makers) as session:
                    session.execute("test2") 
Example #23
Source File: test_context.py    From oslo.context with Apache License 2.0 5 votes vote down vote up
def test_from_environ_no_roles(self):
        ctx = context.RequestContext.from_environ(environ={})
        self.assertEqual([], ctx.roles)

        ctx = context.RequestContext.from_environ(environ={'HTTP_X_ROLES': ''})
        self.assertEqual([], ctx.roles) 
Example #24
Source File: test_context.py    From oslo.context with Apache License 2.0 5 votes vote down vote up
def test_is_user_context(self):
        self.assertFalse(context.is_user_context(None))
        ctx = context.RequestContext(is_admin=True)
        self.assertFalse(context.is_user_context(ctx))
        ctx = context.RequestContext(is_admin=False)
        self.assertTrue(context.is_user_context(ctx))
        self.assertFalse(context.is_user_context("non context object")) 
Example #25
Source File: test_utils.py    From castellan with Apache License 2.0 5 votes vote down vote up
def test_keystone_token_credential_with_context(self):
        token_value = 'ec9799cd921e4e0a8ab6111c08ebf065'
        ctxt = context.RequestContext(auth_token=token_value)

        self.config_fixture.config(
            auth_type='keystone_token',
            group='key_manager'
        )

        ks_token_context = utils.credential_factory(conf=CONF, context=ctxt)
        ks_token_context_class = ks_token_context.__class__.__name__

        self.assertEqual('KeystoneToken', ks_token_context_class)
        self.assertEqual(token_value, ks_token_context.token) 
Example #26
Source File: test_context.py    From oslo.context with Apache License 2.0 5 votes vote down vote up
def test_from_function_and_args(self):
        ctx = context.RequestContext(user="user1")
        arg = []
        kw = dict(c=ctx, s="s")
        fn = context.get_context_from_function_and_args
        ctx1 = context.get_context_from_function_and_args(fn, arg, kw)
        self.assertIs(ctx1, ctx) 
Example #27
Source File: test_context.py    From oslo.context with Apache License 2.0 5 votes vote down vote up
def test_dict_empty_user_identity(self):
        ctx = context.RequestContext()
        d = ctx.to_dict()
        self.assertEqual("- - - - -", d['user_identity']) 
Example #28
Source File: test_context.py    From oslo.context with Apache License 2.0 5 votes vote down vote up
def test_policy_deprecations(self):
        user = uuid.uuid4().hex
        user_domain = uuid.uuid4().hex
        tenant = uuid.uuid4().hex
        project_domain = uuid.uuid4().hex
        roles = [uuid.uuid4().hex, uuid.uuid4().hex, uuid.uuid4().hex]

        ctx = context.RequestContext(user=user,
                                     user_domain=user_domain,
                                     tenant=tenant,
                                     project_domain=project_domain,
                                     roles=roles)

        policy = ctx.to_policy_values()
        key = uuid.uuid4().hex
        val = uuid.uuid4().hex

        with warnings.catch_warnings(record=True) as w:
            warnings.simplefilter("always")

            # no warning triggered by adding key to dict
            policy[key] = val
            self.assertEqual(0, len(w))

            # warning triggered by fetching key from dict
            self.assertIs(val, policy[key])
            self.assertEqual(1, len(w))
            self.assertIn(key, str(w[0].message)) 
Example #29
Source File: test_transaction.py    From pypowervm with Apache License 2.0 5 votes vote down vote up
def test_subtask_thread_local(self):
        """Security context and locks, if set, propagates to WrapperTasks."""
        def verify_no_ctx(wrapper):
            self.assertIsNone(ctx.get_current())
        tx.FeedTask('test_no_context', lpar.LPAR.getter(
            self.adpt)).add_functor_subtask(verify_no_ctx).execute()

        def verify_ctx(wrapper):
            _context = ctx.get_current()
            self.assertIsNotNone(_context)
            self.assertEqual('123', _context.request_id)
            # Copy the base set of locks to expect
            our_locks = list(locks)
            # Add our wrappers uuid since that will be set also.
            our_locks.append(wrapper.uuid)
            self.assertEqual(set(our_locks), set(tx._get_locks()))

        ctx.RequestContext(request_id='123')
        locks = ['L123', 'L456', 'L789']
        tx._set_locks(locks)
        tx.FeedTask('test_set_context', lpar.LPAR.getter(
            self.adpt)).add_functor_subtask(verify_ctx).execute()

        # Context propagates even if FeedTask is executed in a subthread, as
        # long as our executor is used.
        # Make two to ensure they're run in separate threads
        ft1 = tx.FeedTask('subthread1', lpar.LPAR.getter(
            self.adpt)).add_functor_subtask(verify_ctx)
        ft2 = tx.FeedTask('subthread2', lpar.LPAR.getter(
            self.adpt)).add_functor_subtask(verify_ctx)
        self.assertRaises(tf_ex.WrappedFailure, tf_eng.run,
                          tf_uf.Flow('subthread_flow').add(ft1, ft2),
                          engine='parallel')
        tf_eng.run(
            tf_uf.Flow('subthread_flow').add(ft1, ft2), engine='parallel',
            executor=tx.ContextThreadPoolExecutor(2)) 
Example #30
Source File: test_context.py    From oslo.context with Apache License 2.0 5 votes vote down vote up
def test_deprecated_args(self):
        user_id = uuid.uuid4().hex
        project_id = uuid.uuid4().hex
        domain_id = uuid.uuid4().hex
        user_domain_id = uuid.uuid4().hex
        project_domain_id = uuid.uuid4().hex

        ctx = context.RequestContext(user_id=user_id,
                                     project_id=project_id,
                                     domain_id=domain_id,
                                     user_domain_id=user_domain_id,
                                     project_domain_id=project_domain_id)

        self.assertEqual(0, len(self.warnings))
        self.assertEqual(user_id, ctx.user_id)
        self.assertEqual(project_id, ctx.project_id)
        self.assertEqual(domain_id, ctx.domain_id)
        self.assertEqual(user_domain_id, ctx.user_domain_id)
        self.assertEqual(project_domain_id, ctx.project_domain_id)

        self.assertEqual(0, len(self.warnings))
        self.assertEqual(user_id, ctx.user)
        self.assertEqual(1, len(self.warnings))
        self.assertEqual(project_id, ctx.tenant)
        self.assertEqual(2, len(self.warnings))
        self.assertEqual(domain_id, ctx.domain)
        self.assertEqual(3, len(self.warnings))
        self.assertEqual(user_domain_id, ctx.user_domain)
        self.assertEqual(4, len(self.warnings))
        self.assertEqual(project_domain_id, ctx.project_domain)
        self.assertEqual(5, len(self.warnings))