summaryrefslogtreecommitdiff
path: root/glance/tests/unit/test_auth.py
blob: f3600e997836887b10f4a11f255ebb6e9e9b7056 (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
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
# Copyright 2011 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.

from oslo_serialization import jsonutils
from six.moves import http_client as http
import webob

from glance.api import authorization
from glance.common import auth
from glance.common import exception
from glance.common import timeutils
import glance.domain
from glance.tests.unit import utils as unittest_utils
from glance.tests import utils


TENANT1 = '6838eb7b-6ded-434a-882c-b344c77fe8df'
TENANT2 = '2c014f32-55eb-467d-8fcb-4bd706012f81'

UUID1 = 'c80a1a6c-bd1f-41c5-90ee-81afedb1d58d'
UUID2 = 'a85abd86-55b3-4d5b-b0b4-5d0a6e6042fc'


class FakeResponse(object):
    """
    Simple class that masks the inconsistency between
    webob.Response.status_int and httplib.Response.status
    """
    def __init__(self, resp):
        self.resp = resp

    def __getitem__(self, key):
        return self.resp.headers.get(key)

    @property
    def status(self):
        return self.resp.status_int


class V2Token(object):
    def __init__(self):
        self.tok = self.base_token

    def add_service_no_type(self):
        catalog = self.tok['access']['serviceCatalog']
        service_type = {"name": "glance_no_type"}
        catalog.append(service_type)
        service = catalog[-1]
        service['endpoints'] = [self.base_endpoint]

    def add_service(self, s_type, region_list=None):
        if region_list is None:
            region_list = []

        catalog = self.tok['access']['serviceCatalog']
        service_type = {"type": s_type, "name": "glance"}
        catalog.append(service_type)
        service = catalog[-1]
        endpoint_list = []

        if not region_list:
            endpoint_list.append(self.base_endpoint)
        else:
            for region in region_list:
                endpoint = self.base_endpoint
                endpoint['region'] = region
                endpoint_list.append(endpoint)

        service['endpoints'] = endpoint_list

    @property
    def token(self):
        return self.tok

    @property
    def base_endpoint(self):
        return {
            "adminURL": "http://localhost:9292",
            "internalURL": "http://localhost:9292",
            "publicURL": "http://localhost:9292"
        }

    @property
    def base_token(self):
        return {
            "access": {
                "token": {
                    "expires": "2010-11-23T16:40:53.321584",
                    "id": "5c7f8799-2e54-43e4-851b-31f81871b6c",
                    "tenant": {"id": "1", "name": "tenant-ok"}
                },
                "serviceCatalog": [
                ],
                "user": {
                    "id": "2",
                    "roles": [{
                        "tenantId": "1",
                        "id": "1",
                        "name": "Admin"
                    }],
                    "name": "joeadmin"
                }
            }
        }


class TestKeystoneAuthPlugin(utils.BaseTestCase):
    """Test that the Keystone auth plugin works properly"""

    def setUp(self):
        super(TestKeystoneAuthPlugin, self).setUp()

    def test_get_plugin_from_strategy_keystone(self):
        strategy = auth.get_plugin_from_strategy('keystone')
        self.assertIsInstance(strategy, auth.KeystoneStrategy)
        self.assertTrue(strategy.configure_via_auth)

    def test_get_plugin_from_strategy_keystone_configure_via_auth_false(self):
        strategy = auth.get_plugin_from_strategy('keystone',
                                                 configure_via_auth=False)
        self.assertIsInstance(strategy, auth.KeystoneStrategy)
        self.assertFalse(strategy.configure_via_auth)

    def test_required_creds(self):
        """
        Test that plugin created without required
        credential pieces raises an exception
        """
        bad_creds = [
            {},  # missing everything
            {
                'username': 'user1',
                'strategy': 'keystone',
                'password': 'pass'
            },  # missing auth_url
            {
                'password': 'pass',
                'strategy': 'keystone',
                'auth_url': 'http://localhost/v1'
            },  # missing username
            {
                'username': 'user1',
                'strategy': 'keystone',
                'auth_url': 'http://localhost/v1'
            },  # missing password
            {
                'username': 'user1',
                'password': 'pass',
                'auth_url': 'http://localhost/v1'
            },  # missing strategy
            {
                'username': 'user1',
                'password': 'pass',
                'strategy': 'keystone',
                'auth_url': 'http://localhost/v2.0/'
            },  # v2.0: missing tenant
            {
                'username': None,
                'password': 'pass',
                'auth_url': 'http://localhost/v2.0/'
            },  # None parameter
            {
                'username': 'user1',
                'password': 'pass',
                'auth_url': 'http://localhost/v2.0/',
                'tenant': None
            }  # None tenant
        ]
        for creds in bad_creds:
            try:
                plugin = auth.KeystoneStrategy(creds)
                plugin.authenticate()
                self.fail("Failed to raise correct exception when supplying "
                          "bad credentials: %r" % creds)
            except exception.MissingCredentialError:
                continue  # Expected

    def test_invalid_auth_url_v1(self):
        """
        Test that a 400 during authenticate raises exception.AuthBadRequest
        """
        def fake_do_request(*args, **kwargs):
            resp = webob.Response()
            resp.status = http.BAD_REQUEST
            return FakeResponse(resp), ""

        self.mock_object(auth.KeystoneStrategy, '_do_request', fake_do_request)

        bad_creds = {
            'username': 'user1',
            'auth_url': 'http://localhost/badauthurl/',
            'password': 'pass',
            'strategy': 'keystone',
            'region': 'RegionOne'
        }

        plugin = auth.KeystoneStrategy(bad_creds)
        self.assertRaises(exception.AuthBadRequest, plugin.authenticate)

    def test_invalid_auth_url_v2(self):
        """
        Test that a 400 during authenticate raises exception.AuthBadRequest
        """
        def fake_do_request(*args, **kwargs):
            resp = webob.Response()
            resp.status = http.BAD_REQUEST
            return FakeResponse(resp), ""

        self.mock_object(auth.KeystoneStrategy, '_do_request', fake_do_request)

        bad_creds = {
            'username': 'user1',
            'auth_url': 'http://localhost/badauthurl/v2.0/',
            'password': 'pass',
            'tenant': 'tenant1',
            'strategy': 'keystone',
            'region': 'RegionOne'
        }

        plugin = auth.KeystoneStrategy(bad_creds)
        self.assertRaises(exception.AuthBadRequest, plugin.authenticate)

    def test_v1_auth(self):
        """Test v1 auth code paths"""
        def fake_do_request(cls, url, method, headers=None, body=None):
            if url.find("2.0") != -1:
                self.fail("Invalid v1.0 token path (%s)" % url)
            headers = headers or {}

            resp = webob.Response()

            if (headers.get('X-Auth-User') != 'user1' or
                    headers.get('X-Auth-Key') != 'pass'):
                resp.status = http.UNAUTHORIZED
            else:
                resp.status = http.OK
                resp.headers.update({"x-image-management-url": "example.com"})

            return FakeResponse(resp), ""

        self.mock_object(auth.KeystoneStrategy, '_do_request', fake_do_request)

        unauthorized_creds = [
            {
                'username': 'wronguser',
                'auth_url': 'http://localhost/badauthurl/',
                'strategy': 'keystone',
                'region': 'RegionOne',
                'password': 'pass'
            },  # wrong username
            {
                'username': 'user1',
                'auth_url': 'http://localhost/badauthurl/',
                'strategy': 'keystone',
                'region': 'RegionOne',
                'password': 'badpass'
            },  # bad password...
        ]

        for creds in unauthorized_creds:
            try:
                plugin = auth.KeystoneStrategy(creds)
                plugin.authenticate()
                self.fail("Failed to raise NotAuthenticated when supplying "
                          "bad credentials: %r" % creds)
            except exception.NotAuthenticated:
                continue  # Expected

        no_strategy_creds = {
            'username': 'user1',
            'auth_url': 'http://localhost/redirect/',
            'password': 'pass',
            'region': 'RegionOne'
        }

        try:
            plugin = auth.KeystoneStrategy(no_strategy_creds)
            plugin.authenticate()
            self.fail("Failed to raise MissingCredentialError when "
                      "supplying no strategy: %r" % no_strategy_creds)
        except exception.MissingCredentialError:
            pass  # Expected

        good_creds = [
            {
                'username': 'user1',
                'auth_url': 'http://localhost/redirect/',
                'password': 'pass',
                'strategy': 'keystone',
                'region': 'RegionOne'
            }
        ]

        for creds in good_creds:
            plugin = auth.KeystoneStrategy(creds)
            self.assertIsNone(plugin.authenticate())
            self.assertEqual("example.com", plugin.management_url)

        # Assert it does not update management_url via auth response
        for creds in good_creds:
            plugin = auth.KeystoneStrategy(creds, configure_via_auth=False)
            self.assertIsNone(plugin.authenticate())
            self.assertIsNone(plugin.management_url)

    def test_v2_auth(self):
        """Test v2 auth code paths"""
        mock_token = None

        def fake_do_request(cls, url, method, headers=None, body=None):
            if (not url.rstrip('/').endswith('v2.0/tokens') or
                    url.count("2.0") != 1):
                self.fail("Invalid v2.0 token path (%s)" % url)

            creds = jsonutils.loads(body)['auth']
            username = creds['passwordCredentials']['username']
            password = creds['passwordCredentials']['password']
            tenant = creds['tenantName']
            resp = webob.Response()

            if (username != 'user1' or password != 'pass' or
                    tenant != 'tenant-ok'):
                resp.status = http.UNAUTHORIZED
            else:
                resp.status = http.OK
                body = mock_token.token

            return FakeResponse(resp), jsonutils.dumps(body)

        mock_token = V2Token()
        mock_token.add_service('image', ['RegionOne'])
        self.mock_object(auth.KeystoneStrategy, '_do_request', fake_do_request)

        unauthorized_creds = [
            {
                'username': 'wronguser',
                'auth_url': 'http://localhost/v2.0',
                'password': 'pass',
                'tenant': 'tenant-ok',
                'strategy': 'keystone',
                'region': 'RegionOne'
            },  # wrong username
            {
                'username': 'user1',
                'auth_url': 'http://localhost/v2.0',
                'password': 'badpass',
                'tenant': 'tenant-ok',
                'strategy': 'keystone',
                'region': 'RegionOne'
            },  # bad password...
            {
                'username': 'user1',
                'auth_url': 'http://localhost/v2.0',
                'password': 'pass',
                'tenant': 'carterhayes',
                'strategy': 'keystone',
                'region': 'RegionOne'
            },  # bad tenant...
        ]

        for creds in unauthorized_creds:
            try:
                plugin = auth.KeystoneStrategy(creds)
                plugin.authenticate()
                self.fail("Failed to raise NotAuthenticated when supplying "
                          "bad credentials: %r" % creds)
            except exception.NotAuthenticated:
                continue  # Expected

        no_region_creds = {
            'username': 'user1',
            'tenant': 'tenant-ok',
            'auth_url': 'http://localhost/redirect/v2.0/',
            'password': 'pass',
            'strategy': 'keystone'
        }

        plugin = auth.KeystoneStrategy(no_region_creds)
        self.assertIsNone(plugin.authenticate())
        self.assertEqual('http://localhost:9292', plugin.management_url)

        # Add another image service, with a different region
        mock_token.add_service('image', ['RegionTwo'])

        try:
            plugin = auth.KeystoneStrategy(no_region_creds)
            plugin.authenticate()
            self.fail("Failed to raise RegionAmbiguity when no region present "
                      "and multiple regions exist: %r" % no_region_creds)
        except exception.RegionAmbiguity:
            pass  # Expected

        wrong_region_creds = {
            'username': 'user1',
            'tenant': 'tenant-ok',
            'auth_url': 'http://localhost/redirect/v2.0/',
            'password': 'pass',
            'strategy': 'keystone',
            'region': 'NonExistentRegion'
        }

        try:
            plugin = auth.KeystoneStrategy(wrong_region_creds)
            plugin.authenticate()
            self.fail("Failed to raise NoServiceEndpoint when supplying "
                      "wrong region: %r" % wrong_region_creds)
        except exception.NoServiceEndpoint:
            pass  # Expected

        no_strategy_creds = {
            'username': 'user1',
            'tenant': 'tenant-ok',
            'auth_url': 'http://localhost/redirect/v2.0/',
            'password': 'pass',
            'region': 'RegionOne'
        }

        try:
            plugin = auth.KeystoneStrategy(no_strategy_creds)
            plugin.authenticate()
            self.fail("Failed to raise MissingCredentialError when "
                      "supplying no strategy: %r" % no_strategy_creds)
        except exception.MissingCredentialError:
            pass  # Expected

        bad_strategy_creds = {
            'username': 'user1',
            'tenant': 'tenant-ok',
            'auth_url': 'http://localhost/redirect/v2.0/',
            'password': 'pass',
            'region': 'RegionOne',
            'strategy': 'keypebble'
        }

        try:
            plugin = auth.KeystoneStrategy(bad_strategy_creds)
            plugin.authenticate()
            self.fail("Failed to raise BadAuthStrategy when supplying "
                      "bad auth strategy: %r" % bad_strategy_creds)
        except exception.BadAuthStrategy:
            pass  # Expected

        mock_token = V2Token()
        mock_token.add_service('image', ['RegionOne', 'RegionTwo'])

        good_creds = [
            {
                'username': 'user1',
                'auth_url': 'http://localhost/v2.0/',
                'password': 'pass',
                'tenant': 'tenant-ok',
                'strategy': 'keystone',
                'region': 'RegionOne'
            },  # auth_url with trailing '/'
            {
                'username': 'user1',
                'auth_url': 'http://localhost/v2.0',
                'password': 'pass',
                'tenant': 'tenant-ok',
                'strategy': 'keystone',
                'region': 'RegionOne'
            },   # auth_url without trailing '/'
            {
                'username': 'user1',
                'auth_url': 'http://localhost/v2.0',
                'password': 'pass',
                'tenant': 'tenant-ok',
                'strategy': 'keystone',
                'region': 'RegionTwo'
            }   # Second region
        ]

        for creds in good_creds:
            plugin = auth.KeystoneStrategy(creds)
            self.assertIsNone(plugin.authenticate())
            self.assertEqual('http://localhost:9292', plugin.management_url)

        ambiguous_region_creds = {
            'username': 'user1',
            'auth_url': 'http://localhost/v2.0/',
            'password': 'pass',
            'tenant': 'tenant-ok',
            'strategy': 'keystone',
            'region': 'RegionOne'
        }

        mock_token = V2Token()
        # Add two identical services
        mock_token.add_service('image', ['RegionOne'])
        mock_token.add_service('image', ['RegionOne'])

        try:
            plugin = auth.KeystoneStrategy(ambiguous_region_creds)
            plugin.authenticate()
            self.fail("Failed to raise RegionAmbiguity when "
                      "non-unique regions exist: %r" % ambiguous_region_creds)
        except exception.RegionAmbiguity:
            pass

        mock_token = V2Token()
        mock_token.add_service('bad-image', ['RegionOne'])

        good_creds = {
            'username': 'user1',
            'auth_url': 'http://localhost/v2.0/',
            'password': 'pass',
            'tenant': 'tenant-ok',
            'strategy': 'keystone',
            'region': 'RegionOne'
        }

        try:
            plugin = auth.KeystoneStrategy(good_creds)
            plugin.authenticate()
            self.fail("Failed to raise NoServiceEndpoint when bad service "
                      "type encountered")
        except exception.NoServiceEndpoint:
            pass

        mock_token = V2Token()
        mock_token.add_service_no_type()

        try:
            plugin = auth.KeystoneStrategy(good_creds)
            plugin.authenticate()
            self.fail("Failed to raise NoServiceEndpoint when bad service "
                      "type encountered")
        except exception.NoServiceEndpoint:
            pass

        try:
            plugin = auth.KeystoneStrategy(good_creds,
                                           configure_via_auth=False)
            plugin.authenticate()
        except exception.NoServiceEndpoint:
            self.fail("NoServiceEndpoint was raised when authenticate "
                      "should not check for endpoint.")


class TestEndpoints(utils.BaseTestCase):

    def setUp(self):
        super(TestEndpoints, self).setUp()

        self.service_catalog = [
            {
                'endpoint_links': [],
                'endpoints': [
                    {
                        'adminURL': 'http://localhost:8080/',
                        'region': 'RegionOne',
                        'internalURL': 'http://internalURL/',
                        'publicURL': 'http://publicURL/',
                    },
                ],
                'type': 'object-store',
                'name': 'Object Storage Service',
            }
        ]

    def test_get_endpoint_with_custom_server_type(self):
        endpoint = auth.get_endpoint(self.service_catalog,
                                     service_type='object-store')
        self.assertEqual('http://publicURL/', endpoint)

    def test_get_endpoint_with_custom_endpoint_type(self):
        endpoint = auth.get_endpoint(self.service_catalog,
                                     service_type='object-store',
                                     endpoint_type='internalURL')
        self.assertEqual('http://internalURL/', endpoint)

    def test_get_endpoint_raises_with_invalid_service_type(self):
        self.assertRaises(exception.NoServiceEndpoint,
                          auth.get_endpoint,
                          self.service_catalog,
                          service_type='foo')

    def test_get_endpoint_raises_with_invalid_endpoint_type(self):
        self.assertRaises(exception.NoServiceEndpoint,
                          auth.get_endpoint,
                          self.service_catalog,
                          service_type='object-store',
                          endpoint_type='foo')

    def test_get_endpoint_raises_with_invalid_endpoint_region(self):
        self.assertRaises(exception.NoServiceEndpoint,
                          auth.get_endpoint,
                          self.service_catalog,
                          service_type='object-store',
                          endpoint_region='foo',
                          endpoint_type='internalURL')


class TestImageMutability(utils.BaseTestCase):

    def setUp(self):
        super(TestImageMutability, self).setUp()
        self.image_factory = glance.domain.ImageFactory()

    def _is_mutable(self, tenant, owner, is_admin=False):
        context = glance.context.RequestContext(tenant=tenant,
                                                is_admin=is_admin)
        image = self.image_factory.new_image(owner=owner)
        return authorization.is_image_mutable(context, image)

    def test_admin_everything_mutable(self):
        self.assertTrue(self._is_mutable(None, None, is_admin=True))
        self.assertTrue(self._is_mutable(None, TENANT1, is_admin=True))
        self.assertTrue(self._is_mutable(TENANT1, None, is_admin=True))
        self.assertTrue(self._is_mutable(TENANT1, TENANT1, is_admin=True))
        self.assertTrue(self._is_mutable(TENANT1, TENANT2, is_admin=True))

    def test_no_tenant_nothing_mutable(self):
        self.assertFalse(self._is_mutable(None, None))
        self.assertFalse(self._is_mutable(None, TENANT1))

    def test_regular_user(self):
        self.assertFalse(self._is_mutable(TENANT1, None))
        self.assertFalse(self._is_mutable(TENANT1, TENANT2))
        self.assertTrue(self._is_mutable(TENANT1, TENANT1))


class TestImmutableImage(utils.BaseTestCase):
    def setUp(self):
        super(TestImmutableImage, self).setUp()
        image_factory = glance.domain.ImageFactory()
        self.context = glance.context.RequestContext(tenant=TENANT1)
        image = image_factory.new_image(
            image_id=UUID1,
            name='Marvin',
            owner=TENANT1,
            disk_format='raw',
            container_format='bare',
            extra_properties={'foo': 'bar'},
            tags=['ping', 'pong'],
        )
        self.image = authorization.ImmutableImageProxy(image, self.context)

    def _test_change(self, attr, value):
        self.assertRaises(exception.Forbidden,
                          setattr, self.image, attr, value)
        self.assertRaises(exception.Forbidden,
                          delattr, self.image, attr)

    def test_change_id(self):
        self._test_change('image_id', UUID2)

    def test_change_name(self):
        self._test_change('name', 'Freddie')

    def test_change_owner(self):
        self._test_change('owner', TENANT2)

    def test_change_min_disk(self):
        self._test_change('min_disk', 100)

    def test_change_min_ram(self):
        self._test_change('min_ram', 1024)

    def test_change_disk_format(self):
        self._test_change('disk_format', 'vhd')

    def test_change_container_format(self):
        self._test_change('container_format', 'ova')

    def test_change_visibility(self):
        self._test_change('visibility', 'public')

    def test_change_status(self):
        self._test_change('status', 'active')

    def test_change_created_at(self):
        self._test_change('created_at', timeutils.utcnow())

    def test_change_updated_at(self):
        self._test_change('updated_at', timeutils.utcnow())

    def test_change_locations(self):
        self._test_change('locations', ['http://a/b/c'])
        self.assertRaises(exception.Forbidden,
                          self.image.locations.append, 'http://a/b/c')
        self.assertRaises(exception.Forbidden,
                          self.image.locations.extend, ['http://a/b/c'])
        self.assertRaises(exception.Forbidden,
                          self.image.locations.insert, 'foo')
        self.assertRaises(exception.Forbidden,
                          self.image.locations.pop)
        self.assertRaises(exception.Forbidden,
                          self.image.locations.remove, 'foo')
        self.assertRaises(exception.Forbidden,
                          self.image.locations.reverse)
        self.assertRaises(exception.Forbidden,
                          self.image.locations.sort)
        self.assertRaises(exception.Forbidden,
                          self.image.locations.__delitem__, 0)
        self.assertRaises(exception.Forbidden,
                          self.image.locations.__delslice__, 0, 2)
        self.assertRaises(exception.Forbidden,
                          self.image.locations.__setitem__, 0, 'foo')
        self.assertRaises(exception.Forbidden,
                          self.image.locations.__setslice__,
                          0, 2, ['foo', 'bar'])
        self.assertRaises(exception.Forbidden,
                          self.image.locations.__iadd__, 'foo')
        self.assertRaises(exception.Forbidden,
                          self.image.locations.__imul__, 2)

    def test_change_size(self):
        self._test_change('size', 32)

    def test_change_tags(self):
        self.assertRaises(exception.Forbidden,
                          delattr, self.image, 'tags')
        self.assertRaises(exception.Forbidden,
                          setattr, self.image, 'tags', ['king', 'kong'])
        self.assertRaises(exception.Forbidden, self.image.tags.pop)
        self.assertRaises(exception.Forbidden, self.image.tags.clear)
        self.assertRaises(exception.Forbidden, self.image.tags.add, 'king')
        self.assertRaises(exception.Forbidden, self.image.tags.remove, 'ping')
        self.assertRaises(exception.Forbidden,
                          self.image.tags.update, set(['king', 'kong']))
        self.assertRaises(exception.Forbidden,
                          self.image.tags.intersection_update, set([]))
        self.assertRaises(exception.Forbidden,
                          self.image.tags.difference_update, set([]))
        self.assertRaises(exception.Forbidden,
                          self.image.tags.symmetric_difference_update,
                          set([]))

    def test_change_properties(self):
        self.assertRaises(exception.Forbidden,
                          delattr, self.image, 'extra_properties')
        self.assertRaises(exception.Forbidden,
                          setattr, self.image, 'extra_properties', {})
        self.assertRaises(exception.Forbidden,
                          self.image.extra_properties.__delitem__, 'foo')
        self.assertRaises(exception.Forbidden,
                          self.image.extra_properties.__setitem__, 'foo', 'b')
        self.assertRaises(exception.Forbidden,
                          self.image.extra_properties.__setitem__, 'z', 'j')
        self.assertRaises(exception.Forbidden,
                          self.image.extra_properties.pop)
        self.assertRaises(exception.Forbidden,
                          self.image.extra_properties.popitem)
        self.assertRaises(exception.Forbidden,
                          self.image.extra_properties.setdefault, 'p', 'j')
        self.assertRaises(exception.Forbidden,
                          self.image.extra_properties.update, {})

    def test_delete(self):
        self.assertRaises(exception.Forbidden, self.image.delete)

    def test_set_data(self):
        self.assertRaises(exception.Forbidden,
                          self.image.set_data, 'blah', 4)

    def test_deactivate_image(self):
        self.assertRaises(exception.Forbidden, self.image.deactivate)

    def test_reactivate_image(self):
        self.assertRaises(exception.Forbidden, self.image.reactivate)

    def test_get_data(self):
        class FakeImage(object):
            def get_data(self):
                return 'tiddlywinks'

        image = glance.api.authorization.ImmutableImageProxy(
            FakeImage(), self.context)
        self.assertEqual('tiddlywinks', image.get_data())


class TestImageFactoryProxy(utils.BaseTestCase):
    def setUp(self):
        super(TestImageFactoryProxy, self).setUp()
        factory = glance.domain.ImageFactory()
        self.context = glance.context.RequestContext(tenant=TENANT1)
        self.image_factory = authorization.ImageFactoryProxy(factory,
                                                             self.context)

    def test_default_owner_is_set(self):
        image = self.image_factory.new_image()
        self.assertEqual(TENANT1, image.owner)

    def test_wrong_owner_cannot_be_set(self):
        self.assertRaises(exception.Forbidden,
                          self.image_factory.new_image, owner=TENANT2)

    def test_cannot_set_owner_to_none(self):
        self.assertRaises(exception.Forbidden,
                          self.image_factory.new_image, owner=None)

    def test_admin_can_set_any_owner(self):
        self.context.is_admin = True
        image = self.image_factory.new_image(owner=TENANT2)
        self.assertEqual(TENANT2, image.owner)

    def test_admin_can_set_owner_to_none(self):
        self.context.is_admin = True
        image = self.image_factory.new_image(owner=None)
        self.assertIsNone(image.owner)

    def test_admin_still_gets_default_tenant(self):
        self.context.is_admin = True
        image = self.image_factory.new_image()
        self.assertEqual(TENANT1, image.owner)


class TestImageRepoProxy(utils.BaseTestCase):

    class ImageRepoStub(object):
        def __init__(self, fixtures):
            self.fixtures = fixtures

        def get(self, image_id):
            for f in self.fixtures:
                if f.image_id == image_id:
                    return f
            else:
                raise ValueError(image_id)

        def list(self, *args, **kwargs):
            return self.fixtures

    def setUp(self):
        super(TestImageRepoProxy, self).setUp()
        image_factory = glance.domain.ImageFactory()
        self.fixtures = [
            image_factory.new_image(owner=TENANT1),
            image_factory.new_image(owner=TENANT2, visibility='public'),
            image_factory.new_image(owner=TENANT2),
        ]
        self.context = glance.context.RequestContext(tenant=TENANT1)
        image_repo = self.ImageRepoStub(self.fixtures)
        self.image_repo = authorization.ImageRepoProxy(image_repo,
                                                       self.context)

    def test_get_mutable_image(self):
        image = self.image_repo.get(self.fixtures[0].image_id)
        self.assertEqual(image.image_id, self.fixtures[0].image_id)

    def test_get_immutable_image(self):
        image = self.image_repo.get(self.fixtures[1].image_id)
        self.assertRaises(exception.Forbidden,
                          setattr, image, 'name', 'Vince')

    def test_list(self):
        images = self.image_repo.list()
        self.assertEqual(images[0].image_id, self.fixtures[0].image_id)
        self.assertRaises(exception.Forbidden,
                          setattr, images[1], 'name', 'Wally')
        self.assertRaises(exception.Forbidden,
                          setattr, images[2], 'name', 'Calvin')


class TestImmutableTask(utils.BaseTestCase):
    def setUp(self):
        super(TestImmutableTask, self).setUp()
        task_factory = glance.domain.TaskFactory()
        self.context = glance.context.RequestContext(tenant=TENANT2)
        task_type = 'import'
        owner = TENANT2
        task = task_factory.new_task(task_type, owner)
        self.task = authorization.ImmutableTaskProxy(task)

    def _test_change(self, attr, value):
        self.assertRaises(
            exception.Forbidden,
            setattr,
            self.task,
            attr,
            value
        )
        self.assertRaises(
            exception.Forbidden,
            delattr,
            self.task,
            attr
        )

    def test_change_id(self):
        self._test_change('task_id', UUID2)

    def test_change_type(self):
        self._test_change('type', 'fake')

    def test_change_status(self):
        self._test_change('status', 'success')

    def test_change_owner(self):
        self._test_change('owner', 'fake')

    def test_change_expires_at(self):
        self._test_change('expires_at', 'fake')

    def test_change_created_at(self):
        self._test_change('created_at', 'fake')

    def test_change_updated_at(self):
        self._test_change('updated_at', 'fake')

    def test_begin_processing(self):
        self.assertRaises(
            exception.Forbidden,
            self.task.begin_processing
        )

    def test_succeed(self):
        self.assertRaises(
            exception.Forbidden,
            self.task.succeed,
            'result'
        )

    def test_fail(self):
        self.assertRaises(
            exception.Forbidden,
            self.task.fail,
            'message'
        )


class TestImmutableTaskStub(utils.BaseTestCase):
    def setUp(self):
        super(TestImmutableTaskStub, self).setUp()
        task_factory = glance.domain.TaskFactory()
        self.context = glance.context.RequestContext(tenant=TENANT2)
        task_type = 'import'
        owner = TENANT2
        task = task_factory.new_task(task_type, owner)
        self.task = authorization.ImmutableTaskStubProxy(task)

    def _test_change(self, attr, value):
        self.assertRaises(
            exception.Forbidden,
            setattr,
            self.task,
            attr,
            value
        )
        self.assertRaises(
            exception.Forbidden,
            delattr,
            self.task,
            attr
        )

    def test_change_id(self):
        self._test_change('task_id', UUID2)

    def test_change_type(self):
        self._test_change('type', 'fake')

    def test_change_status(self):
        self._test_change('status', 'success')

    def test_change_owner(self):
        self._test_change('owner', 'fake')

    def test_change_expires_at(self):
        self._test_change('expires_at', 'fake')

    def test_change_created_at(self):
        self._test_change('created_at', 'fake')

    def test_change_updated_at(self):
        self._test_change('updated_at', 'fake')


class TestTaskFactoryProxy(utils.BaseTestCase):
    def setUp(self):
        super(TestTaskFactoryProxy, self).setUp()
        factory = glance.domain.TaskFactory()
        self.context = glance.context.RequestContext(tenant=TENANT1)
        self.context_owner_is_none = glance.context.RequestContext()
        self.task_factory = authorization.TaskFactoryProxy(
            factory,
            self.context
        )
        self.task_type = 'import'
        self.task_input = '{"loc": "fake"}'
        self.owner = 'foo'

        self.request1 = unittest_utils.get_fake_request(tenant=TENANT1)
        self.request2 = unittest_utils.get_fake_request(tenant=TENANT2)

    def test_task_create_default_owner(self):
        owner = self.request1.context.owner
        task = self.task_factory.new_task(task_type=self.task_type,
                                          owner=owner)
        self.assertEqual(TENANT1, task.owner)

    def test_task_create_wrong_owner(self):
        self.assertRaises(exception.Forbidden,
                          self.task_factory.new_task,
                          task_type=self.task_type,
                          task_input=self.task_input,
                          owner=self.owner)

    def test_task_create_owner_as_None(self):
        self.assertRaises(exception.Forbidden,
                          self.task_factory.new_task,
                          task_type=self.task_type,
                          task_input=self.task_input,
                          owner=None)

    def test_task_create_admin_context_owner_as_None(self):
        self.context.is_admin = True
        self.assertRaises(exception.Forbidden,
                          self.task_factory.new_task,
                          task_type=self.task_type,
                          task_input=self.task_input,
                          owner=None)


class TestTaskRepoProxy(utils.BaseTestCase):

    class TaskRepoStub(object):
        def __init__(self, fixtures):
            self.fixtures = fixtures

        def get(self, task_id):
            for f in self.fixtures:
                if f.task_id == task_id:
                    return f
            else:
                raise ValueError(task_id)

    class TaskStubRepoStub(object):
        def __init__(self, fixtures):
            self.fixtures = fixtures

        def list(self, *args, **kwargs):
            return self.fixtures

    def setUp(self):
        super(TestTaskRepoProxy, self).setUp()
        task_factory = glance.domain.TaskFactory()
        task_type = 'import'
        owner = None
        self.fixtures = [
            task_factory.new_task(task_type, owner),
            task_factory.new_task(task_type, owner),
            task_factory.new_task(task_type, owner),
        ]
        self.context = glance.context.RequestContext(tenant=TENANT1)
        task_repo = self.TaskRepoStub(self.fixtures)
        task_stub_repo = self.TaskStubRepoStub(self.fixtures)
        self.task_repo = authorization.TaskRepoProxy(
            task_repo,
            self.context
        )
        self.task_stub_repo = authorization.TaskStubRepoProxy(
            task_stub_repo,
            self.context
        )

    def test_get_mutable_task(self):
        task = self.task_repo.get(self.fixtures[0].task_id)
        self.assertEqual(task.task_id, self.fixtures[0].task_id)

    def test_get_immutable_task(self):
        task_id = self.fixtures[1].task_id
        task = self.task_repo.get(task_id)
        self.assertRaises(exception.Forbidden,
                          setattr, task, 'input', 'foo')

    def test_list(self):
        tasks = self.task_stub_repo.list()
        self.assertEqual(tasks[0].task_id, self.fixtures[0].task_id)
        self.assertRaises(exception.Forbidden,
                          setattr,
                          tasks[1],
                          'owner',
                          'foo')
        self.assertRaises(exception.Forbidden,
                          setattr,
                          tasks[2],
                          'owner',
                          'foo')