File: test_authority.py

package info (click to toggle)
python-adal 1.2.7-5
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 1,344 kB
  • sloc: xml: 12,790; python: 4,656; makefile: 14
file content (224 lines) | stat: -rw-r--r-- 9,585 bytes parent folder | download | duplicates (2)
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
#------------------------------------------------------------------------------
#
# Copyright (c) Microsoft Corporation.
# All rights reserved.
#
# This code is licensed under the MIT License.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files(the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and / or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions :
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
#------------------------------------------------------------------------------

import sys
import requests
import httpretty
import six

try:
    import unittest2 as unittest
except ImportError:
    import unittest

try:
    from unittest import mock
except ImportError:
    import mock

import adal
from adal.authority import Authority
from adal import log
from adal.authentication_context import AuthenticationContext
from tests import util
from tests.util import parameters as cp

try:
    from urllib.parse import urlparse

except ImportError:
    from urlparse import urlparse


class TestAuthority(unittest.TestCase):

    # use this as authority to force dynamic as opposed to static instance
    # discovery.
    nonHardCodedAuthority = 'https://login.doesntexist.com/' + cp['tenant']
    nonHardCodedAuthorizeEndpoint = nonHardCodedAuthority + '/oauth2/authorize'
    dstsTestEndpoint = 'https://test-dsts.dsts.core.azure-test.net/dstsv2/common'


    def setUp(self):
        util.reset_logging()
        util.clear_static_cache()
        return super(TestAuthority, self).setUp()

    def tearDown(self):
        util.reset_logging()
        util.clear_static_cache()
        return super(TestAuthority, self).tearDown()

    def setupExpectedInstanceDiscoveryRequestRetries(self, requestParametersList, authority):
        pass

    @httpretty.activate
    def test_success_dynamic_instance_discovery(self):
        instanceDiscoveryRequest = util.setup_expected_instance_discovery_request(
            200,
            cp['authorityHosts']['global'],
            {'tenant_discovery_endpoint' : 'http://foobar'},
            self.nonHardCodedAuthorizeEndpoint
        )

        responseOptions = { 'authority' : self.nonHardCodedAuthority }
        response = util.create_response(responseOptions)
        wireResponse = response['wireResponse']

        util.setup_expected_client_cred_token_request_response(200, wireResponse, self.nonHardCodedAuthority)

        context = adal.AuthenticationContext(self.nonHardCodedAuthority)
        token_response = context.acquire_token_with_client_credentials(
             response['resource'], cp['clientId'], cp['clientSecret'])
        self.assertTrue(
            util.is_match_token_response(response['cachedResponse'], token_response),
            'The response does not match what was expected.: ' + str(token_response)
        )

    def performStaticInstanceDiscovery(self, authorityHost):
        hardCodedAuthority = 'https://' + authorityHost + '/' + cp['tenant']

        responseOptions = {
            'authority' : hardCodedAuthority
        }
        response = util.create_response(responseOptions)
        wireResponse = response['wireResponse']
        tokenRequest = util.setup_expected_client_cred_token_request_response(200, wireResponse, hardCodedAuthority)

        context = adal.AuthenticationContext(hardCodedAuthority)
        token_response = context.acquire_token_with_client_credentials(
             response['resource'], cp['clientId'], cp['clientSecret'])

        self.assertTrue(
            util.is_match_token_response(response['cachedResponse'], token_response),
            'The response does not match what was expected.: ' + str(token_response)
        )


    @httpretty.activate
    def test_success_static_instance_discovery(self):

        self.performStaticInstanceDiscovery('login.microsoftonline.com')
        self.performStaticInstanceDiscovery('login.chinacloudapi.cn')
        self.performStaticInstanceDiscovery('login.microsoftonline.us')
        self.performStaticInstanceDiscovery('test-dsts.dsts.core.windows.net')
        self.performStaticInstanceDiscovery('test-dsts.dsts.core.chinacloudapi.cn')
        self.performStaticInstanceDiscovery('test-dsts.dsts.core.cloudapi.de')
        self.performStaticInstanceDiscovery('test-dsts.dsts.core.usgovcloudapi.net')
        self.performStaticInstanceDiscovery('test-dsts.dsts.core.azure-test.net')


    @httpretty.activate
    def test_http_error(self):
        util.setup_expected_instance_discovery_request(500, cp['authorityHosts']['global'], None, self.nonHardCodedAuthorizeEndpoint)

        with six.assertRaisesRegex(self, Exception, '500'):
            context = adal.AuthenticationContext(self.nonHardCodedAuthority)
            token_response = context.acquire_token_with_client_credentials(
                 cp['resource'], cp['clientId'], cp['clientSecret'])

    @httpretty.activate
    def test_validation_error(self):
        returnDoc = { 'error' : 'invalid_instance', 'error_description' : 'the instance was invalid' }
        util.setup_expected_instance_discovery_request(400, cp['authorityHosts']['global'], returnDoc, self.nonHardCodedAuthorizeEndpoint)

        with six.assertRaisesRegex(self, Exception, 'instance was invalid'):
            context = adal.AuthenticationContext(self.nonHardCodedAuthority)
            token_response = context.acquire_token_with_client_credentials(
                 cp['resource'], cp['clientId'], cp['clientSecret'])

    @httpretty.activate
    def test_validation_off(self):
        instanceDiscoveryRequest = util.setup_expected_instance_discovery_request(
            200,
            cp['authorityHosts']['global'],
            {'tenant_discovery_endpoint' : 'http://foobar'},
            self.nonHardCodedAuthorizeEndpoint
        )

        responseOptions = { 'authority' : self.nonHardCodedAuthority}
        response = util.create_response(responseOptions)
        wireResponse = response['wireResponse']

        util.setup_expected_client_cred_token_request_response(200, wireResponse, self.nonHardCodedAuthority)

        context = adal.AuthenticationContext(self.nonHardCodedAuthority)
        token_response = context.acquire_token_with_client_credentials(
             response['resource'], cp['clientId'], cp['clientSecret'])
        self.assertTrue(
            util.is_match_token_response(response['cachedResponse'], token_response),
            'The response does not match what was expected.: ' + str(token_response)
        )


    @httpretty.activate
    def test_bad_url_not_https(self):
        with six.assertRaisesRegex(self, ValueError, "The authority url must be an https endpoint\."):
            context = AuthenticationContext('http://this.is.not.https.com/mytenant.com')

    @httpretty.activate
    def test_bad_url_has_query(self):
        with six.assertRaisesRegex(self, ValueError, "The authority url must not have a query string\."):
            context = AuthenticationContext(cp['authorityTenant'] + '?this=should&not=be&here=foo')

    @httpretty.activate
    def test_url_extra_path_elements(self):
        with six.assertRaisesRegex(self, ValueError, "tenant"):  # Some tenant specific error message
            context = AuthenticationContext(self.nonHardCodedAuthority + '/extra/path')

    @httpretty.activate
    def test_dsts_authority(self):
        try:
            context = AuthenticationContext(self.dstsTestEndpoint)
        except:
            self.fail("AuthenticationContext() rased an exception on dstsTestEndpoint")

    @httpretty.activate
    def test_url_extra_slashes(self):
        util.setup_expected_instance_discovery_request(200,
                                                       cp['authorityHosts']['global'],
                                                       {
                                                           'tenant_discovery_endpoint': 'http://foobar'
                                                       },
                                                       self.nonHardCodedAuthorizeEndpoint)

        authority_url = self.nonHardCodedAuthority + '/'  # This should pass for one or more than one slashes
        authority = Authority(authority_url, True)
        obj = util.create_empty_adal_object()
        authority.validate(obj['call_context'])
        req = httpretty.last_request()
        util.match_standard_request_headers(req)

    @httpretty.activate
    def test_url_extra_slashes_change_authority_url(self):
        authority_url = self.nonHardCodedAuthority + '/'  # This should pass for one or more than one slashes
        authority = Authority(authority_url, True)
        self.assertTrue(authority._url.geturl(), self.nonHardCodedAuthority)


if __name__ == '__main__':
    unittest.main()