Tenant to project migration for RequestContext

As of the oslo.context 4.0.0 release, RequestContext objects no
longer have a tenant attribute, instead expecting callers to use
project_id for that purpose. Update all context.tenant references to
context.project_id in order to facilitate this transition.

Change-Id: I2830ccf840bf4d1d8a516287adee51c46d2a5583
This commit is contained in:
Jeremy Stanley 2022-03-28 19:26:18 +00:00 committed by zhurong
parent f0258fc843
commit 8f994a7d4e
18 changed files with 34 additions and 35 deletions

View File

@ -2,7 +2,6 @@
templates: templates:
- check-requirements - check-requirements
- openstack-cover-jobs - openstack-cover-jobs
- openstack-lower-constraints-jobs
- openstack-python3-yoga-jobs - openstack-python3-yoga-jobs
- periodic-stable-jobs - periodic-stable-jobs
- publish-openstack-docs-pti - publish-openstack-docs-pti

View File

@ -44,7 +44,7 @@ class ContextMiddleware(wsgi.Middleware):
roles = [r.strip() for r in req.headers.get('X-Roles').split(',')] roles = [r.strip() for r in req.headers.get('X-Roles').split(',')]
kwargs = { kwargs = {
'user': req.headers.get('X-User-Id'), 'user': req.headers.get('X-User-Id'),
'tenant': req.headers.get('X-Tenant-Id'), 'project_id': req.headers.get('X-Tenant-Id'),
'auth_token': req.headers.get('X-Auth-Token'), 'auth_token': req.headers.get('X-Auth-Token'),
'session': req.headers.get('X-Configuration-Session'), 'session': req.headers.get('X-Configuration-Session'),
'is_admin': CONF.admin_role in roles, 'is_admin': CONF.admin_role in roles,

View File

@ -273,7 +273,7 @@ class Controller(object):
raise exc.HTTPBadRequest(explanation=msg) raise exc.HTTPBadRequest(explanation=msg)
try: try:
package = db_api.package_upload( package = db_api.package_upload(
package_meta, req.context.tenant) package_meta, req.context.project_id)
except db_exc.DBDuplicateEntry: except db_exc.DBDuplicateEntry:
msg = _('Package with specified full ' msg = _('Package with specified full '
'name is already registered') 'name is already registered')

View File

@ -50,7 +50,7 @@ class Controller(object):
if all_environments: if all_environments:
query = unit.query(models.Environment) \ query = unit.query(models.Environment) \
.options(load_only('tenant_id')) \ .options(load_only('tenant_id')) \
.filter_by(tenant_id=request.context.tenant) \ .filter_by(tenant_id=request.context.project_id) \
.join(models.Task) \ .join(models.Task) \
.order_by(desc(models.Task.created)) .order_by(desc(models.Task.created))
result = query.all() result = query.all()

View File

@ -65,7 +65,7 @@ class Controller(object):
else: else:
policy.check('list_environments', request.context) policy.check('list_environments', request.context)
# Only environments from same tenant as user should be returned # Only environments from same tenant as user should be returned
filters = {'tenant_id': request.context.tenant} filters = {'tenant_id': request.context.project_id}
environments = envs.EnvironmentServices.get_environments_by(filters) environments = envs.EnvironmentServices.get_environments_by(filters)
environments = [env.to_dict() for env in environments] environments = [env.to_dict() for env in environments]

View File

@ -55,13 +55,13 @@ def stats_count(api, method):
ts = time.time() ts = time.time()
result = func(*args, **kwargs) result = func(*args, **kwargs)
te = time.time() te = time.time()
tenant = args[1].context.tenant tenant = args[1].context.project_id
update_count(api, method, te - ts, update_count(api, method, te - ts,
tenant) tenant)
return result return result
except Exception: except Exception:
te = time.time() te = time.time()
tenant = args[1].context.tenant tenant = args[1].context.project_id
LOG.exception('API {api} method {method} raised an ' LOG.exception('API {api} method {method} raised an '
'exception'.format(api=api, method=method)) 'exception'.format(api=api, method=method))
update_error_count(api, method, te - te, tenant) update_error_count(api, method, te - te, tenant)

View File

@ -36,7 +36,7 @@ class Controller(object):
package_name = request.GET.get('packageName') package_name = request.GET.get('packageName')
credentials = { credentials = {
'token': request.context.auth_token, 'token': request.context.auth_token,
'project_id': request.context.tenant 'project_id': request.context.project_id
} }
try: try:

View File

@ -47,7 +47,7 @@ class Controller(object):
credentials = { credentials = {
'token': request.context.auth_token, 'token': request.context.auth_token,
'project_id': request.context.tenant, 'project_id': request.context.project_id,
'user_id': request.context.user 'user_id': request.context.user
} }

View File

@ -43,7 +43,7 @@ class Controller(object):
""" """
LOG.debug('EnvTemplates:List') LOG.debug('EnvTemplates:List')
policy.check('list_env_templates', request.context) policy.check('list_env_templates', request.context)
tenant_id = request.context.tenant tenant_id = request.context.project_id
filters = {} filters = {}
if request.GET.get('is_public'): if request.GET.get('is_public'):
is_public = request.GET.get('is_public', 'false').lower() == 'true' is_public = request.GET.get('is_public', 'false').lower() == 'true'
@ -84,7 +84,7 @@ class Controller(object):
LOG.debug('ENV TEMP NAME: {templ_name}>'. LOG.debug('ENV TEMP NAME: {templ_name}>'.
format(templ_name=body['name'])) format(templ_name=body['name']))
template = env_temps.EnvTemplateServices.create( template = env_temps.EnvTemplateServices.create(
body.copy(), request.context.tenant) body.copy(), request.context.project_id)
return template.to_dict() return template.to_dict()
except db_exc.DBDuplicateEntry: except db_exc.DBDuplicateEntry:
msg = _('Env Template with specified name already exists') msg = _('Env Template with specified name already exists')
@ -245,7 +245,7 @@ class Controller(object):
try: try:
is_public = body.get('is_public', False) is_public = body.get('is_public', False)
template = env_temps.EnvTemplateServices.clone( template = env_temps.EnvTemplateServices.clone(
env_template_id, request.context.tenant, body['name'], env_template_id, request.context.project_id, body['name'],
is_public) is_public)
except db_exc.DBDuplicateEntry: except db_exc.DBDuplicateEntry:
msg = _('Env template with specified name already exists') msg = _('Env template with specified name already exists')
@ -258,7 +258,7 @@ class Controller(object):
env_template = self._validate_exists(env_template_id) env_template = self._validate_exists(env_template_id)
if env_template.is_public or request.context.is_admin: if env_template.is_public or request.context.is_admin:
return return
if env_template.tenant_id != request.context.tenant: if env_template.tenant_id != request.context.project_id:
msg = _('User has no access to these resources.') msg = _('User has no access to these resources.')
LOG.error(msg) LOG.error(msg)
raise exc.HTTPForbidden(explanation=msg) raise exc.HTTPForbidden(explanation=msg)

View File

@ -51,17 +51,17 @@ def _package_get(package_id, session):
def _authorize_package(package, context, allow_public=False): def _authorize_package(package, context, allow_public=False):
if package.owner_id != context.tenant: if package.owner_id != context.project_id:
if not allow_public: if not allow_public:
msg = _("Package '{pkg_id}' is not owned by tenant " msg = _("Package '{pkg_id}' is not owned by tenant "
"'{tenant}'").format(pkg_id=package.id, "'{tenant}'").format(pkg_id=package.id,
tenant=context.tenant) tenant=context.project_id)
LOG.error(msg) LOG.error(msg)
raise exc.HTTPForbidden(explanation=msg) raise exc.HTTPForbidden(explanation=msg)
if not package.is_public: if not package.is_public:
msg = _("Package '{pkg_id}' is not public and not owned by " msg = _("Package '{pkg_id}' is not public and not owned by "
"tenant '{tenant}' ").format(pkg_id=package.id, "tenant '{tenant}' ").format(pkg_id=package.id,
tenant=context.tenant) tenant=context.project_id)
LOG.error(msg) LOG.error(msg)
raise exc.HTTPForbidden(explanation=msg) raise exc.HTTPForbidden(explanation=msg)
@ -298,23 +298,23 @@ def package_search(filters, context, manage_public=False,
if catalog: if catalog:
# Only show packages one can deploy, i.e. own + public # Only show packages one can deploy, i.e. own + public
query = query.filter(or_(pkg.owner_id == context.tenant, query = query.filter(or_(pkg.owner_id == context.project_id,
pkg.is_public)) pkg.is_public))
else: else:
# Show packages one can edit. # Show packages one can edit.
if not context.is_admin: if not context.is_admin:
if manage_public: if manage_public:
query = query.filter(or_(pkg.owner_id == context.tenant, query = query.filter(or_(pkg.owner_id == context.project_id,
pkg.is_public)) pkg.is_public))
else: else:
query = query.filter(pkg.owner_id == context.tenant) query = query.filter(pkg.owner_id == context.project_id)
# No else here admin can edit everything. # No else here admin can edit everything.
if not filters.get('include_disabled', '').lower() == 'true': if not filters.get('include_disabled', '').lower() == 'true':
query = query.filter(pkg.enabled) query = query.filter(pkg.enabled)
if filters.get('owned', '').lower() == 'true': if filters.get('owned', '').lower() == 'true':
query = query.filter(pkg.owner_id == context.tenant) query = query.filter(pkg.owner_id == context.project_id)
if 'type' in filters.keys(): if 'type' in filters.keys():
query = query.filter(pkg.type == filters['type'].title()) query = query.filter(pkg.type == filters['type'].title())
@ -446,10 +446,10 @@ def package_delete(package_id, context):
with session.begin(): with session.begin():
package = _package_get(package_id, session) package = _package_get(package_id, session)
if not context.is_admin and package.owner_id != context.tenant: if not context.is_admin and package.owner_id != context.project_id:
raise exc.HTTPForbidden( raise exc.HTTPForbidden(
explanation="Package is not owned by the" explanation="Package is not owned by the"
" tenant '{0}'".format(context.tenant)) " tenant '{0}'".format(context.project_id))
session.delete(package) session.delete(package)

View File

@ -111,11 +111,11 @@ class EnvironmentServices(object):
data = { data = {
'Objects': objects, 'Objects': objects,
'Attributes': [], 'Attributes': [],
'project_id': context.tenant, 'project_id': context.project_id,
'user_id': context.user 'user_id': context.user
} }
environment_params['tenant_id'] = context.tenant environment_params['tenant_id'] = context.project_id
environment = models.Environment() environment = models.Environment()
environment.update(environment_params) environment.update(environment_params)
@ -273,7 +273,7 @@ class EnvironmentServices(object):
return driver return driver
session = auth_utils.get_token_client_session( session = auth_utils.get_token_client_session(
context.auth_token, context.tenant) context.auth_token, context.project_id)
try: try:
session.get_endpoint(service_type='network') session.get_endpoint(service_type='network')
except ks_exceptions.EndpointNotFound: except ks_exceptions.EndpointNotFound:

View File

@ -31,7 +31,7 @@ class ActionServices(object):
'action': action, 'action': action,
'model': session.description, 'model': session.description,
'token': context.auth_token, 'token': context.auth_token,
'project_id': context.tenant, 'project_id': context.project_id,
'user_id': context.user, 'user_id': context.user,
'id': environment.id 'id': environment.id
} }

View File

@ -30,7 +30,7 @@ class MiddlewareContextTest(base.MuranoTestCase):
request_headers = { request_headers = {
'X-Roles': 'admin', 'X-Roles': 'admin',
'X-User-Id': "", 'X-User-Id': "",
'X-Tenant-Id': "", 'X-Project-Id': "",
'X-Configuration-Session': "", 'X-Configuration-Session': "",
} }
request = webob.Request.blank('/environments', request = webob.Request.blank('/environments',

View File

@ -994,7 +994,7 @@ class TestCatalogApi(test_base.ControllerTest, test_base.MuranoApiTestCase):
del test_package_meta[attr] del test_package_meta[attr]
mock_request = mock.MagicMock(context=mock.MagicMock( mock_request = mock.MagicMock(context=mock.MagicMock(
tenant=self.tenant)) project_id=self.tenant))
mock_load_from_file.return_value = pkg_to_upload mock_load_from_file.return_value = pkg_to_upload
mock_policy_check.return_value = True mock_policy_check.return_value = True

View File

@ -40,7 +40,7 @@ class TestActions(test_base.MuranoTestCase):
} }
mock_session = mock.MagicMock(description=mock_description) mock_session = mock.MagicMock(description=mock_description)
mock_context = mock.Mock(auth_token='test_token', mock_context = mock.Mock(auth_token='test_token',
tenant='test_tenant', project_id='test_tenant',
user='test_user') user='test_user')
expected_task = { expected_task = {
'action': { 'action': {
@ -123,7 +123,7 @@ class TestActions(test_base.MuranoTestCase):
test_session = 'test_session' test_session = 'test_session'
context = mock.Mock() context = mock.Mock()
context.auth_token = 'test_token' context.auth_token = 'test_token'
context.tenant = 'test_tenant' context.project_id = 'test_tenant'
context.user = 'test_user' context.user = 'test_user'
test_unit = 'test_unit' test_unit = 'test_unit'

View File

@ -30,7 +30,7 @@ class TestUtils(test_base.MuranoTestCase):
"""Test check env.""" """Test check env."""
mock_request = mock.MagicMock(context=test_utils.dummy_context()) mock_request = mock.MagicMock(context=test_utils.dummy_context())
mock_env = mock.MagicMock(environment_id='test_env_id', mock_env = mock.MagicMock(environment_id='test_env_id',
tenant_id=mock_request.context.tenant) tenant_id=mock_request.context.project_id)
mock_db_session.get_session().query().get.return_value = mock_env mock_db_session.get_session().query().get.return_value = mock_env
env = utils.check_env(mock_request, mock_env.environment_id) env = utils.check_env(mock_request, mock_env.environment_id)
@ -117,7 +117,7 @@ class TestUtils(test_base.MuranoTestCase):
def test_verify_env_template_with_invalid_tenant(self, mock_db_session): def test_verify_env_template_with_invalid_tenant(self, mock_db_session):
"""Test session validation failure throws expected exception.""" """Test session validation failure throws expected exception."""
mock_request = mock.MagicMock(context=test_utils.dummy_context()) mock_request = mock.MagicMock(context=test_utils.dummy_context())
mock_request.context.tenant = mock.MagicMock( mock_request.context.project_id = mock.MagicMock(
return_value='test_tenant_id') return_value='test_tenant_id')
mock_env_template = mock.MagicMock(tenant_id='another_test_tenant_id') mock_env_template = mock.MagicMock(tenant_id='another_test_tenant_id')
mock_db_session.get_session().query().get.return_value =\ mock_db_session.get_session().query().get.return_value =\

View File

@ -35,7 +35,7 @@ def dummy_context(user='test_username', tenant_id='test_tenant_id',
# prevent it being generated by oslo during tests. # prevent it being generated by oslo during tests.
params = { params = {
'request_id': request_id, 'request_id': request_id,
'tenant': tenant_id, 'project_id': tenant_id,
'user': user, 'user': user,
} }
params.update(kwargs) params.update(kwargs)

View File

@ -40,7 +40,7 @@ def check_env(request, environment_id):
raise exc.HTTPNotFound(explanation=msg) raise exc.HTTPNotFound(explanation=msg)
if hasattr(request, 'context'): if hasattr(request, 'context'):
if (environment.tenant_id != request.context.tenant and not if (environment.tenant_id != request.context.project_id and not
request.context.is_admin): request.context.is_admin):
msg = _('User is not authorized to access' msg = _('User is not authorized to access'
' these tenant resources') ' these tenant resources')
@ -87,7 +87,7 @@ def verify_env_template(func):
raise exc.HTTPNotFound(explanation=msg) raise exc.HTTPNotFound(explanation=msg)
if hasattr(request, 'context'): if hasattr(request, 'context'):
if template.tenant_id != request.context.tenant: if template.tenant_id != request.context.project_id:
msg = _('User is not authorized to access' msg = _('User is not authorized to access'
' this tenant resources') ' this tenant resources')
LOG.error(msg) LOG.error(msg)