summaryrefslogtreecommitdiff
path: root/nova/tests/unit/policies/test_flavor_extra_specs.py
blob: 3129cb621332522dd58ec2aa40821f480983f60f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
#    Licensed under the Apache License, Version 2.0 (the "License"); you may
#    not use this file except in compliance with the License. You may obtain
#    a copy of the License at
#
#         http://www.apache.org/licenses/LICENSE-2.0
#
#    Unless required by applicable law or agreed to in writing, software
#    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
#    License for the specific language governing permissions and limitations
#    under the License.

import fixtures
import mock
from oslo_utils.fixture import uuidsentinel as uuids

from nova.api.openstack.compute import flavor_manage
from nova.api.openstack.compute import flavors
from nova.api.openstack.compute import flavors_extraspecs
from nova.api.openstack.compute import servers
from nova.compute import vm_states
from nova import objects
from nova.policies import flavor_extra_specs as policies
from nova.policies import flavor_manage as fm_policies
from nova.policies import servers as s_policies
from nova.tests.unit.api.openstack import fakes
from nova.tests.unit import fake_flavor
from nova.tests.unit import fake_instance
from nova.tests.unit.policies import base


class FlavorExtraSpecsPolicyTest(base.BasePolicyTest):
    """Test Flavor Extra Specs APIs policies with all possible context.
    This class defines the set of context with different roles
    which are allowed and not allowed to pass the policy checks.
    With those set of context, it will call the API operation and
    verify the expected behaviour.
    """

    def setUp(self):
        super(FlavorExtraSpecsPolicyTest, self).setUp()
        self.controller = flavors_extraspecs.FlavorExtraSpecsController()
        self.flavor_ctrl = flavors.FlavorsController()
        self.fm_ctrl = flavor_manage.FlavorManageController()
        self.server_ctrl = servers.ServersController()
        self.req = fakes.HTTPRequest.blank('')
        self.server_ctrl._view_builder._add_security_grps = mock.MagicMock()
        self.server_ctrl._view_builder._get_metadata = mock.MagicMock()
        self.server_ctrl._view_builder._get_addresses = mock.MagicMock()
        self.server_ctrl._view_builder._get_host_id = mock.MagicMock()
        self.server_ctrl._view_builder._get_fault = mock.MagicMock()
        self.server_ctrl._view_builder._add_host_status = mock.MagicMock()

        self.instance = fake_instance.fake_instance_obj(
                self.project_member_context,
                id=1, uuid=uuids.fake_id, project_id=self.project_id,
                vm_state=vm_states.ACTIVE)

        self.mock_get = self.useFixture(
            fixtures.MockPatch('nova.api.openstack.common.get_instance')).mock
        self.mock_get.return_value = self.instance

        fakes.stub_out_secgroup_api(
            self, security_groups=[{'name': 'default'}])
        self.mock_get_all = self.useFixture(fixtures.MockPatchObject(
            self.server_ctrl.compute_api, 'get_all')).mock
        self.mock_get_all.return_value = objects.InstanceList(
            objects=[self.instance])

        def get_flavor_extra_specs(context, flavor_id):
            return fake_flavor.fake_flavor_obj(
                self.project_member_context,
                id=1, uuid=uuids.fake_id, project_id=self.project_id,
                is_public=False, extra_specs={'hw:cpu_policy': 'shared'},
                expected_attrs='extra_specs')

        self.stub_out('nova.api.openstack.common.get_flavor',
                      get_flavor_extra_specs)

        # Check that all are able to get flavor extra specs.
        self.all_authorized_contexts = [
            self.legacy_admin_context, self.system_admin_context,
            self.project_admin_context, self.project_member_context,
            self.project_reader_context, self.project_foo_context,
            self.system_member_context, self.system_reader_context,
            self.system_foo_context,
            self.other_project_member_context,
            self.other_project_reader_context
        ]
        self.all_unauthorized_contexts = []
        # Check that all system scoped are able to get flavor extra specs.
        self.all_system_authorized_contexts = [
            self.legacy_admin_context, self.system_admin_context,
            self.project_admin_context, self.project_member_context,
            self.project_reader_context, self.project_foo_context,
            self.system_member_context, self.system_reader_context,
            self.system_foo_context,
            self.other_project_member_context,
            self.other_project_reader_context
        ]
        self.all_system_unauthorized_contexts = []

        # Check that admin is able to create, update and delete flavor
        # extra specs.
        self.admin_authorized_contexts = [
            self.legacy_admin_context, self.system_admin_context,
            self.project_admin_context]
        # Check that non-admin is not able to create, update and
        # delete flavor extra specs.
        self.admin_unauthorized_contexts = [
            self.system_member_context, self.system_reader_context,
            self.system_foo_context, self.project_member_context,
            self.project_reader_context, self.project_foo_context,
            self.other_project_member_context,
            self.other_project_reader_context
        ]

    @mock.patch('nova.objects.Flavor.save')
    def test_create_flavor_extra_specs_policy(self, mock_save):
        body = {'extra_specs': {'hw:numa_nodes': '1'}}
        rule_name = policies.POLICY_ROOT % 'create'
        self.common_policy_check(self.admin_authorized_contexts,
                                 self.admin_unauthorized_contexts,
                                 rule_name,
                                 self.controller.create,
                                 self.req, '1234',
                                 body=body)

    @mock.patch('nova.objects.Flavor._flavor_extra_specs_del')
    @mock.patch('nova.objects.Flavor.save')
    def test_delete_flavor_extra_specs_policy(self, mock_save, mock_delete):
        rule_name = policies.POLICY_ROOT % 'delete'
        self.common_policy_check(self.admin_authorized_contexts,
                                 self.admin_unauthorized_contexts,
                                 rule_name,
                                 self.controller.delete,
                                 self.req, '1234', 'hw:cpu_policy')

    @mock.patch('nova.objects.Flavor.save')
    def test_update_flavor_extra_specs_policy(self, mock_save):
        body = {'hw:cpu_policy': 'shared'}
        rule_name = policies.POLICY_ROOT % 'update'
        self.common_policy_check(self.admin_authorized_contexts,
                                 self.admin_unauthorized_contexts,
                                 rule_name,
                                 self.controller.update,
                                 self.req, '1234', 'hw:cpu_policy',
                                 body=body)

    def test_show_flavor_extra_specs_policy(self):
        rule_name = policies.POLICY_ROOT % 'show'
        self.common_policy_check(self.all_authorized_contexts,
                                 self.all_unauthorized_contexts,
                                 rule_name,
                                 self.controller.show,
                                 self.req, '1234',
                                 'hw:cpu_policy')

    def test_index_flavor_extra_specs_policy(self):
        rule_name = policies.POLICY_ROOT % 'index'
        self.common_policy_check(self.all_authorized_contexts,
                                 self.all_unauthorized_contexts,
                                 rule_name,
                                 self.controller.index,
                                 self.req, '1234')

    def test_flavor_detail_with_extra_specs_policy(self):
        fakes.stub_out_flavor_get_all(self)
        rule_name = policies.POLICY_ROOT % 'index'
        req = fakes.HTTPRequest.blank('', version='2.61')
        authorize_res, unauthorize_res = self.common_policy_check(
            self.all_authorized_contexts, self.all_unauthorized_contexts,
            rule_name, self.flavor_ctrl.detail, req,
            fatal=False)
        for resp in authorize_res:
            self.assertIn('extra_specs', resp['flavors'][0])
        for resp in unauthorize_res:
            self.assertNotIn('extra_specs', resp['flavors'][0])

    def test_flavor_show_with_extra_specs_policy(self):
        fakes.stub_out_flavor_get_by_flavor_id(self)
        rule_name = policies.POLICY_ROOT % 'index'
        req = fakes.HTTPRequest.blank('', version='2.61')
        authorize_res, unauthorize_res = self.common_policy_check(
            self.all_authorized_contexts, self.all_unauthorized_contexts,
            rule_name, self.flavor_ctrl.show, req, '1',
            fatal=False)
        for resp in authorize_res:
            self.assertIn('extra_specs', resp['flavor'])
        for resp in unauthorize_res:
            self.assertNotIn('extra_specs', resp['flavor'])

    def test_flavor_create_with_extra_specs_policy(self):
        rule_name = policies.POLICY_ROOT % 'index'
        # 'create' policy is checked before flavor extra specs 'index' policy
        # so we have to allow it for everyone otherwise it will fail first
        # for unauthorized contexts.
        rule = fm_policies.POLICY_ROOT % 'create'
        self.policy.set_rules({rule: "@"}, overwrite=False)
        req = fakes.HTTPRequest.blank('', version='2.61')

        def fake_create(newflavor):
            newflavor['flavorid'] = uuids.fake_id
            newflavor["name"] = 'test'
            newflavor["memory_mb"] = 512
            newflavor["vcpus"] = 2
            newflavor["root_gb"] = 1
            newflavor["ephemeral_gb"] = 1
            newflavor["swap"] = 512
            newflavor["rxtx_factor"] = 1.0
            newflavor["is_public"] = True
            newflavor["disabled"] = False
            newflavor["extra_specs"] = {}

        self.stub_out("nova.objects.Flavor.create", fake_create)
        body = {
            "flavor": {
                "name": "test",
                "ram": 512,
                "vcpus": 2,
                "disk": 1,
            }
        }
        authorize_res, unauthorize_res = self.common_policy_check(
            self.all_system_authorized_contexts,
            self.all_system_unauthorized_contexts,
            rule_name, self.fm_ctrl._create, req, body=body,
            fatal=False)
        for resp in authorize_res:
            self.assertIn('extra_specs', resp['flavor'])
        for resp in unauthorize_res:
            self.assertNotIn('extra_specs', resp['flavor'])

    @mock.patch('nova.objects.Flavor.save')
    def test_flavor_update_with_extra_specs_policy(self, mock_save):
        fakes.stub_out_flavor_get_by_flavor_id(self)
        rule_name = policies.POLICY_ROOT % 'index'
        # 'update' policy is checked before flavor extra specs 'index' policy
        # so we have to allow it for everyone otherwise it will fail first
        # for unauthorized contexts.
        rule = fm_policies.POLICY_ROOT % 'update'
        self.policy.set_rules({rule: "@"}, overwrite=False)
        req = fakes.HTTPRequest.blank('', version='2.61')

        authorize_res, unauthorize_res = self.common_policy_check(
            self.all_system_authorized_contexts,
            self.all_system_unauthorized_contexts,
            rule_name, self.fm_ctrl._update, req, '1',
            body={'flavor': {'description': None}},
            fatal=False)
        for resp in authorize_res:
            self.assertIn('extra_specs', resp['flavor'])
        for resp in unauthorize_res:
            self.assertNotIn('extra_specs', resp['flavor'])

    def test_server_detail_with_extra_specs_policy(self):
        rule = s_policies.SERVERS % 'detail'
        # server 'detail' policy is checked before flavor extra specs 'index'
        # policy so we have to allow it for everyone otherwise it will fail
        # first for unauthorized contexts.
        self.policy.set_rules({rule: "@"}, overwrite=False)
        req = fakes.HTTPRequest.blank('', version='2.47')
        rule_name = policies.POLICY_ROOT % 'index'
        authorize_res, unauthorize_res = self.common_policy_check(
            self.all_authorized_contexts, self.all_unauthorized_contexts,
            rule_name, self.server_ctrl.detail, req,
            fatal=False)
        for resp in authorize_res:
            self.assertIn('extra_specs', resp['servers'][0]['flavor'])
        for resp in unauthorize_res:
            self.assertNotIn('extra_specs', resp['servers'][0]['flavor'])

    @mock.patch('nova.objects.BlockDeviceMappingList.bdms_by_instance_uuid')
    @mock.patch('nova.compute.api.API.get_instance_host_status')
    def test_server_show_with_extra_specs_policy(self, mock_get, mock_block):
        rule = s_policies.SERVERS % 'show'
        # server 'show' policy is checked before flavor extra specs 'index'
        # policy so we have to allow it for everyone otherwise it will fail
        # first for unauthorized contexts.
        self.policy.set_rules({rule: "@"}, overwrite=False)
        req = fakes.HTTPRequest.blank('', version='2.47')
        rule_name = policies.POLICY_ROOT % 'index'
        authorize_res, unauthorize_res = self.common_policy_check(
            self.all_authorized_contexts,
            self.all_unauthorized_contexts,
            rule_name, self.server_ctrl.show, req, 'fake',
            fatal=False)
        for resp in authorize_res:
            self.assertIn('extra_specs', resp['server']['flavor'])
        for resp in unauthorize_res:
            self.assertNotIn('extra_specs', resp['server']['flavor'])

    @mock.patch('nova.objects.BlockDeviceMappingList.bdms_by_instance_uuid')
    @mock.patch('nova.compute.api.API.get_instance_host_status')
    @mock.patch('nova.compute.api.API.rebuild')
    def test_server_rebuild_with_extra_specs_policy(self, mock_rebuild,
        mock_get, mock_bdm):
        rule = s_policies.SERVERS % 'rebuild'
        # server 'rebuild' policy is checked before flavor extra specs 'index'
        # policy so we have to allow it for everyone otherwise it will fail
        # first for unauthorized contexts.
        self.policy.set_rules({rule: "@"}, overwrite=False)
        req = fakes.HTTPRequest.blank('', version='2.47')
        rule_name = policies.POLICY_ROOT % 'index'
        authorize_res, unauthorize_res = self.common_policy_check(
            self.all_authorized_contexts,
            self.all_unauthorized_contexts,
            rule_name, self.server_ctrl._action_rebuild,
            req, self.instance.uuid,
            body={'rebuild': {"imageRef": uuids.fake_id}},
            fatal=False)
        for resp in authorize_res:
            self.assertIn('extra_specs', resp.obj['server']['flavor'])
        for resp in unauthorize_res:
            self.assertNotIn('extra_specs', resp.obj['server']['flavor'])

    @mock.patch('nova.compute.api.API.update_instance')
    def test_server_update_with_extra_specs_policy(self, mock_update):
        rule = s_policies.SERVERS % 'update'
        # server 'update' policy is checked before flavor extra specs 'index'
        # policy so we have to allow it for everyone otherwise it will fail
        # first for unauthorized contexts.
        self.policy.set_rules({rule: "@"}, overwrite=False)
        req = fakes.HTTPRequest.blank('', version='2.47')
        rule_name = policies.POLICY_ROOT % 'index'
        authorize_res, unauthorize_res = self.common_policy_check(
            self.all_authorized_contexts,
            self.all_unauthorized_contexts,
            rule_name, self.server_ctrl.update,
            req, self.instance.uuid,
            body={'server': {'name': 'test'}},
            fatal=False)
        for resp in authorize_res:
            self.assertIn('extra_specs', resp['server']['flavor'])
        for resp in unauthorize_res:
            self.assertNotIn('extra_specs', resp['server']['flavor'])


class FlavorExtraSpecsScopeTypePolicyTest(FlavorExtraSpecsPolicyTest):
    """Test Flavor Extra Specs APIs policies with system scope enabled.
    This class set the nova.conf [oslo_policy] enforce_scope to True
    so that we can switch on the scope checking on oslo policy side.
    It defines the set of context with scoped token
    which are allowed and not allowed to pass the policy checks.
    With those set of context, it will run the API operation and
    verify the expected behaviour.
    """

    def setUp(self):
        super(FlavorExtraSpecsScopeTypePolicyTest, self).setUp()
        self.flags(enforce_scope=True, group="oslo_policy")

        # Check that all system scoped are able to get flavor extra specs.
        self.all_system_authorized_contexts = [
            self.system_admin_context, self.system_member_context,
            self.system_reader_context, self.system_foo_context
        ]
        self.all_system_unauthorized_contexts = [
            self.legacy_admin_context,
            self.project_admin_context, self.project_member_context,
            self.project_reader_context, self.project_foo_context,
            self.other_project_member_context,
            self.other_project_reader_context
        ]
        # Check that system admin is able to create, update and delete flavor
        # extra specs.
        self.admin_authorized_contexts = [
            self.system_admin_context]
        # Check that non-system admin is not able to create, update and
        # delete flavor extra specs.
        self.admin_unauthorized_contexts = [
            self.legacy_admin_context, self.project_admin_context,
            self.system_member_context, self.system_reader_context,
            self.system_foo_context, self.project_member_context,
            self.project_reader_context, self.project_foo_context,
            self.other_project_member_context,
            self.other_project_reader_context
        ]


class FlavorExtraSpecsNoLegacyPolicyTest(FlavorExtraSpecsScopeTypePolicyTest):
    """Test Flavor Extra Specs APIs policies with system scope enabled,
    and no more deprecated rules that allow the legacy admin API to
    access system_admin_or_owner APIs.
    """
    without_deprecated_rules = True

    def setUp(self):
        super(FlavorExtraSpecsNoLegacyPolicyTest, self).setUp()
        # Check that system or project reader are able to get flavor
        # extra specs.
        self.all_authorized_contexts = [
            self.legacy_admin_context, self.system_admin_context,
            self.project_admin_context, self.project_member_context,
            self.project_reader_context, self.system_member_context,
            self.system_reader_context, self.other_project_member_context,
            self.other_project_reader_context
        ]
        self.all_unauthorized_contexts = [
            self.project_foo_context, self.system_foo_context
        ]
        # Check that all system scoped reader are able to get flavor
        # extra specs.
        self.all_system_authorized_contexts = [
            self.system_admin_context, self.system_member_context,
            self.system_reader_context
        ]
        self.all_system_unauthorized_contexts = [
            self.legacy_admin_context, self.system_foo_context,
            self.project_admin_context, self.project_member_context,
            self.project_reader_context, self.project_foo_context,
            self.other_project_member_context,
            self.other_project_reader_context
        ]