summaryrefslogtreecommitdiff
path: root/glance/tests/unit/test_policy.py
blob: 03de222854e528f0adf74f97c6330a66499e54c7 (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
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
# Copyright 2012 OpenStack Foundation
# Copyright 2013 IBM Corp.
# All Rights Reserved.
#
#    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 collections
import hashlib
import os.path

import mock
import oslo_config.cfg

import glance.api.policy
from glance.common import exception
import glance.context
from glance.tests.unit import base
import glance.tests.unit.utils as unit_test_utils
from glance.tests import utils as test_utils

UUID1 = 'c80a1a6c-bd1f-41c5-90ee-81afedb1d58d'


class IterableMock(mock.Mock, collections.Iterable):

    def __iter__(self):
        while False:
            yield None


class ImageRepoStub(object):

    def get(self, *args, **kwargs):
        return 'image_from_get'

    def save(self, *args, **kwargs):
        return 'image_from_save'

    def add(self, *args, **kwargs):
        return 'image_from_add'

    def list(self, *args, **kwargs):
        return ['image_from_list_0', 'image_from_list_1']


class ImageStub(object):

    def __init__(self, image_id=None, visibility='private',
                 container_format='bear', disk_format='raw',
                 status='active', extra_properties=None,
                 os_hidden=False):

        if extra_properties is None:
            extra_properties = {}

        self.image_id = image_id
        self.visibility = visibility
        self.container_format = container_format
        self.disk_format = disk_format
        self.status = status
        self.extra_properties = extra_properties
        self.checksum = 'c2e5db72bd7fd153f53ede5da5a06de3'
        self.os_hash_algo = 'sha512'
        self.os_hash_value = hashlib.sha512(b'glance').hexdigest()
        self.created_at = '2013-09-28T15:27:36Z'
        self.updated_at = '2013-09-28T15:27:37Z'
        self.locations = []
        self.min_disk = 0
        self.min_ram = 0
        self.name = 'image_name'
        self.owner = 'tenant1'
        self.protected = False
        self.size = 0
        self.virtual_size = 0
        self.tags = []
        self.os_hidden = os_hidden

    def delete(self):
        self.status = 'deleted'


class ImageFactoryStub(object):

    def new_image(self, image_id=None, name=None, visibility='private',
                  min_disk=0, min_ram=0, protected=False, owner=None,
                  disk_format=None, container_format=None,
                  extra_properties=None, hidden=False, tags=None,
                  **other_args):
        self.visibility = visibility
        self.hidden = hidden
        return 'new_image'


class MemberRepoStub(object):
    image = None

    def add(self, image_member):
        image_member.output = 'member_repo_add'

    def get(self, *args, **kwargs):
        return 'member_repo_get'

    def save(self, image_member, from_state=None):
        image_member.output = 'member_repo_save'

    def list(self, *args, **kwargs):
        return 'member_repo_list'

    def remove(self, image_member):
        image_member.output = 'member_repo_remove'


class ImageMembershipStub(object):

    def __init__(self, output=None):
        self.output = output


class TaskRepoStub(object):

    def get(self, *args, **kwargs):
        return 'task_from_get'

    def add(self, *args, **kwargs):
        return 'task_from_add'

    def list(self, *args, **kwargs):
        return ['task_from_list_0', 'task_from_list_1']


class TaskStub(object):

    def __init__(self, task_id):
        self.task_id = task_id
        self.status = 'pending'

    def run(self, executor):
        self.status = 'processing'


class TaskFactoryStub(object):

    def new_task(self, *args):
        return 'new_task'


class TestPolicyEnforcer(base.IsolatedUnitTest):

    def test_policy_file_default_rules_default_location(self):
        enforcer = glance.api.policy.Enforcer()

        context = glance.context.RequestContext(roles=[])
        enforcer.enforce(context, 'get_image', {})

    def test_policy_file_custom_rules_default_location(self):
        rules = {"get_image": '!'}
        self.set_policy_rules(rules)

        enforcer = glance.api.policy.Enforcer()

        context = glance.context.RequestContext(roles=[])
        self.assertRaises(exception.Forbidden,
                          enforcer.enforce, context, 'get_image', {})

    def test_policy_file_custom_location(self):
        self.config(policy_file=os.path.join(self.test_dir, 'gobble.gobble'),
                    group='oslo_policy')

        rules = {"get_image": '!'}
        self.set_policy_rules(rules)

        enforcer = glance.api.policy.Enforcer()

        context = glance.context.RequestContext(roles=[])
        self.assertRaises(exception.Forbidden,
                          enforcer.enforce, context, 'get_image', {})

    def test_policy_file_check(self):
        self.config(policy_file=os.path.join(self.test_dir, 'gobble.gobble'),
                    group='oslo_policy')

        rules = {"get_image": '!'}
        self.set_policy_rules(rules)

        enforcer = glance.api.policy.Enforcer()

        context = glance.context.RequestContext(roles=[])
        self.assertEqual(False, enforcer.check(context, 'get_image', {}))

    def test_policy_file_get_image_default_everybody(self):
        rules = {"default": ''}
        self.set_policy_rules(rules)

        enforcer = glance.api.policy.Enforcer()

        context = glance.context.RequestContext(roles=[])
        self.assertEqual(True, enforcer.check(context, 'get_image', {}))

    def test_policy_file_get_image_default_nobody(self):
        rules = {"default": '!'}
        self.set_policy_rules(rules)

        enforcer = glance.api.policy.Enforcer()

        context = glance.context.RequestContext(roles=[])
        self.assertRaises(exception.Forbidden,
                          enforcer.enforce, context, 'get_image', {})


class TestPolicyEnforcerNoFile(base.IsolatedUnitTest):

    def test_policy_file_specified_but_not_found(self):
        """Missing defined policy file should result in a default ruleset"""
        self.config(policy_file='gobble.gobble', group='oslo_policy')
        enforcer = glance.api.policy.Enforcer()

        context = glance.context.RequestContext(roles=[])
        self.assertRaises(exception.Forbidden,
                          enforcer.enforce, context, 'manage_image_cache', {})

        admin_context = glance.context.RequestContext(roles=['admin'])
        enforcer.enforce(admin_context, 'manage_image_cache', {})

    def test_policy_file_default_not_found(self):
        """Missing default policy file should result in a default ruleset"""

        def fake_find_file(self, name):
            return None

        self.mock_object(oslo_config.cfg.ConfigOpts, 'find_file',
                         fake_find_file)

        enforcer = glance.api.policy.Enforcer()

        context = glance.context.RequestContext(roles=[])
        self.assertRaises(exception.Forbidden,
                          enforcer.enforce, context, 'manage_image_cache', {})

        admin_context = glance.context.RequestContext(roles=['admin'])
        enforcer.enforce(admin_context, 'manage_image_cache', {})


class TestImagePolicy(test_utils.BaseTestCase):

    def setUp(self):
        self.image_stub = ImageStub(UUID1)
        self.image_repo_stub = ImageRepoStub()
        self.image_factory_stub = ImageFactoryStub()
        self.policy = mock.Mock()
        self.policy.enforce = mock.Mock()
        super(TestImagePolicy, self).setUp()

    def test_publicize_image_not_allowed(self):
        self.policy.enforce.side_effect = exception.Forbidden
        image = glance.api.policy.ImageProxy(self.image_stub, {}, self.policy)
        self.assertRaises(exception.Forbidden,
                          setattr, image, 'visibility', 'public')
        self.assertEqual('private', image.visibility)
        self.policy.enforce.assert_called_once_with({}, "publicize_image",
                                                    image.target)

    def test_publicize_image_allowed(self):
        image = glance.api.policy.ImageProxy(self.image_stub, {}, self.policy)
        image.visibility = 'public'
        self.assertEqual('public', image.visibility)
        self.policy.enforce.assert_called_once_with({}, "publicize_image",
                                                    image.target)

    def test_communitize_image_not_allowed(self):
        self.policy.enforce.side_effect = exception.Forbidden
        image = glance.api.policy.ImageProxy(self.image_stub, {}, self.policy)
        self.assertRaises(exception.Forbidden,
                          setattr, image, 'visibility', 'community')
        self.assertEqual('private', image.visibility)
        self.policy.enforce.assert_called_once_with({}, "communitize_image",
                                                    image.target)

    def test_communitize_image_allowed(self):
        image = glance.api.policy.ImageProxy(self.image_stub, {}, self.policy)
        image.visibility = 'community'
        self.assertEqual('community', image.visibility)
        self.policy.enforce.assert_called_once_with({}, "communitize_image",
                                                    image.target)

    def test_delete_image_not_allowed(self):
        self.policy.enforce.side_effect = exception.Forbidden
        image = glance.api.policy.ImageProxy(self.image_stub, {}, self.policy)
        self.assertRaises(exception.Forbidden, image.delete)
        self.assertEqual('active', image.status)
        self.policy.enforce.assert_called_once_with({}, "delete_image",
                                                    image.target)

    def test_delete_image_allowed(self):
        image = glance.api.policy.ImageProxy(self.image_stub, {}, self.policy)
        args = dict(image.target)
        image.delete()
        self.assertEqual('deleted', image.status)
        self.policy.enforce.assert_called_once_with({}, "delete_image", args)

    def test_get_image_not_allowed(self):
        self.policy.enforce.side_effect = exception.Forbidden
        image_target = IterableMock()
        with mock.patch.object(glance.api.policy, 'ImageTarget') as target:
            target.return_value = image_target
            image_repo = glance.api.policy.ImageRepoProxy(self.image_repo_stub,
                                                          {}, self.policy)
            self.assertRaises(exception.Forbidden, image_repo.get, UUID1)
        self.policy.enforce.assert_called_once_with({}, "get_image",
                                                    dict(image_target))

    def test_get_image_allowed(self):
        image_target = IterableMock()
        with mock.patch.object(glance.api.policy, 'ImageTarget') as target:
            target.return_value = image_target
            image_repo = glance.api.policy.ImageRepoProxy(self.image_repo_stub,
                                                          {}, self.policy)
            output = image_repo.get(UUID1)
        self.assertIsInstance(output, glance.api.policy.ImageProxy)
        self.assertEqual('image_from_get', output.image)
        self.policy.enforce.assert_called_once_with({}, "get_image",
                                                    dict(image_target))

    def test_get_images_not_allowed(self):
        self.policy.enforce.side_effect = exception.Forbidden
        image_repo = glance.api.policy.ImageRepoProxy(self.image_repo_stub,
                                                      {}, self.policy)
        self.assertRaises(exception.Forbidden, image_repo.list)
        self.policy.enforce.assert_called_once_with({}, "get_images", {})

    def test_get_images_allowed(self):
        image_repo = glance.api.policy.ImageRepoProxy(self.image_repo_stub,
                                                      {}, self.policy)
        images = image_repo.list()
        for i, image in enumerate(images):
            self.assertIsInstance(image, glance.api.policy.ImageProxy)
            self.assertEqual('image_from_list_%d' % i, image.image)
            self.policy.enforce.assert_called_once_with({}, "get_images", {})

    def test_modify_image_not_allowed(self):
        self.policy.enforce.side_effect = exception.Forbidden
        image_repo = glance.api.policy.ImageRepoProxy(self.image_repo_stub,
                                                      {}, self.policy)
        image = glance.api.policy.ImageProxy(self.image_stub, {}, self.policy)
        self.assertRaises(exception.Forbidden, image_repo.save, image)
        self.policy.enforce.assert_called_once_with({}, "modify_image",
                                                    image.target)

    def test_modify_image_allowed(self):
        image_repo = glance.api.policy.ImageRepoProxy(self.image_repo_stub,
                                                      {}, self.policy)
        image = glance.api.policy.ImageProxy(self.image_stub, {}, self.policy)
        image_repo.save(image)
        self.policy.enforce.assert_called_once_with({}, "modify_image",
                                                    image.target)

    def test_add_image_not_allowed(self):
        self.policy.enforce.side_effect = exception.Forbidden
        image_repo = glance.api.policy.ImageRepoProxy(self.image_repo_stub,
                                                      {}, self.policy)
        image = glance.api.policy.ImageProxy(self.image_stub, {}, self.policy)
        self.assertRaises(exception.Forbidden, image_repo.add, image)
        self.policy.enforce.assert_called_once_with({}, "add_image",
                                                    image.target)

    def test_add_image_allowed(self):
        image_repo = glance.api.policy.ImageRepoProxy(self.image_repo_stub,
                                                      {}, self.policy)
        image = glance.api.policy.ImageProxy(self.image_stub, {}, self.policy)
        image_repo.add(image)
        self.policy.enforce.assert_called_once_with({}, "add_image",
                                                    image.target)

    def test_new_image_visibility_public_not_allowed(self):
        self.policy.enforce.side_effect = exception.Forbidden
        image_factory = glance.api.policy.ImageFactoryProxy(
            self.image_factory_stub, {}, self.policy)
        self.assertRaises(exception.Forbidden, image_factory.new_image,
                          visibility='public')
        self.policy.enforce.assert_called_once_with({}, "publicize_image", {})

    def test_new_image_visibility_public_allowed(self):
        image_factory = glance.api.policy.ImageFactoryProxy(
            self.image_factory_stub, {}, self.policy)
        image_factory.new_image(visibility='public')
        self.policy.enforce.assert_called_once_with({}, "publicize_image", {})

    def test_new_image_visibility_community_not_allowed(self):
        self.policy.enforce.side_effect = exception.Forbidden
        image_factory = glance.api.policy.ImageFactoryProxy(
            self.image_factory_stub, {}, self.policy)
        self.assertRaises(exception.Forbidden, image_factory.new_image,
                          visibility='community')
        self.policy.enforce.assert_called_once_with({},
                                                    "communitize_image",
                                                    {})

    def test_new_image_visibility_community_allowed(self):
        image_factory = glance.api.policy.ImageFactoryProxy(
            self.image_factory_stub, {}, self.policy)
        image_factory.new_image(visibility='community')
        self.policy.enforce.assert_called_once_with({},
                                                    "communitize_image",
                                                    {})

    def test_image_get_data_policy_enforced_with_target(self):
        extra_properties = {
            'test_key': 'test_4321'
        }
        image_stub = ImageStub(UUID1, extra_properties=extra_properties)
        with mock.patch('glance.api.policy.ImageTarget'):
            image = glance.api.policy.ImageProxy(image_stub, {}, self.policy)
        target = image.target
        self.policy.enforce.side_effect = exception.Forbidden

        self.assertRaises(exception.Forbidden, image.get_data)
        self.policy.enforce.assert_called_once_with({}, "download_image",
                                                    target)


class TestMemberPolicy(test_utils.BaseTestCase):

    def setUp(self):
        self.policy = mock.Mock()
        self.policy.enforce = mock.Mock()
        self.image_stub = ImageStub(UUID1)
        image = glance.api.policy.ImageProxy(self.image_stub, {}, self.policy)
        self.member_repo = glance.api.policy.ImageMemberRepoProxy(
            MemberRepoStub(), image, {}, self.policy)
        self.target = self.member_repo.target
        super(TestMemberPolicy, self).setUp()

    def test_add_member_not_allowed(self):
        self.policy.enforce.side_effect = exception.Forbidden
        self.assertRaises(exception.Forbidden, self.member_repo.add, '')
        self.policy.enforce.assert_called_once_with({}, "add_member",
                                                    self.target)

    def test_add_member_allowed(self):
        image_member = ImageMembershipStub()
        self.member_repo.add(image_member)
        self.assertEqual('member_repo_add', image_member.output)
        self.policy.enforce.assert_called_once_with({}, "add_member",
                                                    self.target)

    def test_get_member_not_allowed(self):
        self.policy.enforce.side_effect = exception.Forbidden
        self.assertRaises(exception.Forbidden, self.member_repo.get, '')
        self.policy.enforce.assert_called_once_with({}, "get_member",
                                                    self.target)

    def test_get_member_allowed(self):
        output = self.member_repo.get('')
        self.assertEqual('member_repo_get', output)
        self.policy.enforce.assert_called_once_with({}, "get_member",
                                                    self.target)

    def test_modify_member_not_allowed(self):
        self.policy.enforce.side_effect = exception.Forbidden
        self.assertRaises(exception.Forbidden, self.member_repo.save, '')
        self.policy.enforce.assert_called_once_with({}, "modify_member",
                                                    self.target)

    def test_modify_member_allowed(self):
        image_member = ImageMembershipStub()
        self.member_repo.save(image_member)
        self.assertEqual('member_repo_save', image_member.output)
        self.policy.enforce.assert_called_once_with({}, "modify_member",
                                                    self.target)

    def test_get_members_not_allowed(self):
        self.policy.enforce.side_effect = exception.Forbidden
        self.assertRaises(exception.Forbidden, self.member_repo.list, '')
        self.policy.enforce.assert_called_once_with({}, "get_members",
                                                    self.target)

    def test_get_members_allowed(self):
        output = self.member_repo.list('')
        self.assertEqual('member_repo_list', output)
        self.policy.enforce.assert_called_once_with({}, "get_members",
                                                    self.target)

    def test_delete_member_not_allowed(self):
        self.policy.enforce.side_effect = exception.Forbidden
        self.assertRaises(exception.Forbidden, self.member_repo.remove, '')
        self.policy.enforce.assert_called_once_with({}, "delete_member",
                                                    self.target)

    def test_delete_member_allowed(self):
        image_member = ImageMembershipStub()
        self.member_repo.remove(image_member)
        self.assertEqual('member_repo_remove', image_member.output)
        self.policy.enforce.assert_called_once_with({}, "delete_member",
                                                    self.target)


class TestTaskPolicy(test_utils.BaseTestCase):

    def setUp(self):
        self.task_stub = TaskStub(UUID1)
        self.task_repo_stub = TaskRepoStub()
        self.task_factory_stub = TaskFactoryStub()
        self.policy = unit_test_utils.FakePolicyEnforcer()
        super(TestTaskPolicy, self).setUp()

    def test_get_task_not_allowed(self):
        rules = {"get_task": False}
        self.policy.set_rules(rules)
        task_repo = glance.api.policy.TaskRepoProxy(
            self.task_repo_stub,
            {},
            self.policy
        )
        self.assertRaises(exception.Forbidden,
                          task_repo.get,
                          UUID1)

    def test_get_task_allowed(self):
        rules = {"get_task": True}
        self.policy.set_rules(rules)
        task_repo = glance.api.policy.TaskRepoProxy(
            self.task_repo_stub,
            {},
            self.policy
        )
        task = task_repo.get(UUID1)
        self.assertIsInstance(task, glance.api.policy.TaskProxy)
        self.assertEqual('task_from_get', task.task)

    def test_get_tasks_not_allowed(self):
        rules = {"get_tasks": False}
        self.policy.set_rules(rules)
        task_repo = glance.api.policy.TaskStubRepoProxy(
            self.task_repo_stub,
            {},
            self.policy
        )
        self.assertRaises(exception.Forbidden, task_repo.list)

    def test_get_tasks_allowed(self):
        rules = {"get_task": True}
        self.policy.set_rules(rules)
        task_repo = glance.api.policy.TaskStubRepoProxy(
            self.task_repo_stub,
            {},
            self.policy
        )
        tasks = task_repo.list()
        for i, task in enumerate(tasks):
            self.assertIsInstance(task, glance.api.policy.TaskStubProxy)
            self.assertEqual('task_from_list_%d' % i, task.task_stub)

    def test_add_task_not_allowed(self):
        rules = {"add_task": False}
        self.policy.set_rules(rules)
        task_repo = glance.api.policy.TaskRepoProxy(
            self.task_repo_stub,
            {},
            self.policy
        )
        task = glance.api.policy.TaskProxy(self.task_stub, {}, self.policy)
        self.assertRaises(exception.Forbidden, task_repo.add, task)

    def test_add_task_allowed(self):
        rules = {"add_task": True}
        self.policy.set_rules(rules)
        task_repo = glance.api.policy.TaskRepoProxy(
            self.task_repo_stub,
            {},
            self.policy
        )
        task = glance.api.policy.TaskProxy(self.task_stub, {}, self.policy)
        task_repo.add(task)


class TestContextPolicyEnforcer(base.IsolatedUnitTest):

    def _do_test_policy_influence_context_admin(self,
                                                policy_admin_role,
                                                context_role,
                                                context_is_admin,
                                                admin_expected):
        self.config(policy_file=os.path.join(self.test_dir, 'gobble.gobble'),
                    group='oslo_policy')

        rules = {'context_is_admin': 'role:%s' % policy_admin_role}
        self.set_policy_rules(rules)

        enforcer = glance.api.policy.Enforcer()

        context = glance.context.RequestContext(roles=[context_role],
                                                is_admin=context_is_admin,
                                                policy_enforcer=enforcer)
        self.assertEqual(admin_expected, context.is_admin)

    def test_context_admin_policy_admin(self):
        self._do_test_policy_influence_context_admin('test_admin',
                                                     'test_admin',
                                                     True,
                                                     True)

    def test_context_nonadmin_policy_admin(self):
        self._do_test_policy_influence_context_admin('test_admin',
                                                     'test_admin',
                                                     False,
                                                     True)

    def test_context_admin_policy_nonadmin(self):
        self._do_test_policy_influence_context_admin('test_admin',
                                                     'demo',
                                                     True,
                                                     True)

    def test_context_nonadmin_policy_nonadmin(self):
        self._do_test_policy_influence_context_admin('test_admin',
                                                     'demo',
                                                     False,
                                                     False)