summaryrefslogtreecommitdiff
path: root/keystoneclient/tests/unit/v3/test_auth.py
blob: 9f8797703c376a6a79f8981717ddde6fd59d3011 (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
#    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 testtools import testcase

from keystoneclient import exceptions
from keystoneclient.tests.unit.v3 import utils
from keystoneclient.v3 import client


class AuthenticateAgainstKeystoneTests(utils.TestCase):
    def setUp(self):
        super(AuthenticateAgainstKeystoneTests, self).setUp()
        self.TEST_RESPONSE_DICT = {
            "token": {
                "methods": [
                    "token",
                    "password"
                ],

                "expires_at": "2999-01-01T00:00:10.000123Z",
                "project": {
                    "domain": {
                        "id": self.TEST_DOMAIN_ID,
                        "name": self.TEST_DOMAIN_NAME
                    },
                    "id": self.TEST_TENANT_ID,
                    "name": self.TEST_TENANT_NAME
                },
                "user": {
                    "domain": {
                        "id": self.TEST_DOMAIN_ID,
                        "name": self.TEST_DOMAIN_NAME
                    },
                    "id": self.TEST_USER,
                    "name": self.TEST_USER
                },
                "issued_at": "2013-05-29T16:55:21.468960Z",
                "catalog": self.TEST_SERVICE_CATALOG
            },
        }
        self.TEST_REQUEST_BODY = {
            "auth": {
                "identity": {
                    "methods": ["password"],
                    "password": {
                        "user": {
                            "domain": {
                                "name": self.TEST_DOMAIN_NAME
                            },
                            "name": self.TEST_USER,
                            "password": self.TEST_TOKEN
                        }
                    }
                },
                "scope": {
                    "project": {
                        "id": self.TEST_TENANT_ID
                    },
                }
            }
        }
        self.TEST_REQUEST_HEADERS = {
            'Content-Type': 'application/json',
            'User-Agent': 'python-keystoneclient'
        }
        self.TEST_RESPONSE_HEADERS = {
            'X-Subject-Token': self.TEST_TOKEN
        }

    def test_authenticate_success(self):
        TEST_TOKEN = "abcdef"
        ident = self.TEST_REQUEST_BODY['auth']['identity']
        del ident['password']['user']['domain']
        del ident['password']['user']['name']
        ident['password']['user']['id'] = self.TEST_USER

        self.stub_auth(json=self.TEST_RESPONSE_DICT, subject_token=TEST_TOKEN)

        # Creating a HTTPClient not using session is deprecated.
        with self.deprecations.expect_deprecations_here():
            cs = client.Client(user_id=self.TEST_USER,
                               password=self.TEST_TOKEN,
                               project_id=self.TEST_TENANT_ID,
                               auth_url=self.TEST_URL)
        self.assertEqual(cs.auth_token, TEST_TOKEN)
        self.assertRequestBodyIs(json=self.TEST_REQUEST_BODY)

    def test_authenticate_failure(self):
        ident = self.TEST_REQUEST_BODY['auth']['identity']
        ident['password']['user']['password'] = 'bad_key'
        error = {"unauthorized": {"message": "Unauthorized",
                                  "code": "401"}}

        self.stub_auth(status_code=401, json=error)

        with testcase.ExpectedException(exceptions.Unauthorized):
            with self.deprecations.expect_deprecations_here():
                client.Client(user_domain_name=self.TEST_DOMAIN_NAME,
                              username=self.TEST_USER,
                              password="bad_key",
                              project_id=self.TEST_TENANT_ID,
                              auth_url=self.TEST_URL)

        self.assertRequestBodyIs(json=self.TEST_REQUEST_BODY)

    def test_auth_redirect(self):
        headers = {'Location': self.TEST_ADMIN_URL + '/auth/tokens'}
        self.stub_auth(status_code=305, text='Use proxy', headers=headers)

        self.stub_auth(json=self.TEST_RESPONSE_DICT,
                       base_url=self.TEST_ADMIN_URL)

        # Creating a HTTPClient not using session is deprecated.
        with self.deprecations.expect_deprecations_here():
            cs = client.Client(user_domain_name=self.TEST_DOMAIN_NAME,
                               username=self.TEST_USER,
                               password=self.TEST_TOKEN,
                               project_id=self.TEST_TENANT_ID,
                               auth_url=self.TEST_URL)

        self.assertEqual(cs.management_url,
                         self.TEST_RESPONSE_DICT["token"]["catalog"][3]
                         ['endpoints'][2]["url"])
        self.assertEqual(cs.auth_token,
                         self.TEST_RESPONSE_HEADERS["X-Subject-Token"])

    def test_authenticate_success_domain_username_password_scoped(self):
        self.stub_auth(json=self.TEST_RESPONSE_DICT)

        # Creating a HTTPClient not using session is deprecated.
        with self.deprecations.expect_deprecations_here():
            cs = client.Client(user_domain_name=self.TEST_DOMAIN_NAME,
                               username=self.TEST_USER,
                               password=self.TEST_TOKEN,
                               project_id=self.TEST_TENANT_ID,
                               auth_url=self.TEST_URL)
        self.assertEqual(cs.management_url,
                         self.TEST_RESPONSE_DICT["token"]["catalog"][3]
                         ['endpoints'][2]["url"])
        self.assertEqual(cs.auth_token,
                         self.TEST_RESPONSE_HEADERS["X-Subject-Token"])

    def test_authenticate_success_userid_password_domain_scoped(self):
        ident = self.TEST_REQUEST_BODY['auth']['identity']
        del ident['password']['user']['domain']
        del ident['password']['user']['name']
        ident['password']['user']['id'] = self.TEST_USER

        scope = self.TEST_REQUEST_BODY['auth']['scope']
        del scope['project']
        scope['domain'] = {}
        scope['domain']['id'] = self.TEST_DOMAIN_ID

        token = self.TEST_RESPONSE_DICT['token']
        del token['project']
        token['domain'] = {}
        token['domain']['id'] = self.TEST_DOMAIN_ID
        token['domain']['name'] = self.TEST_DOMAIN_NAME

        self.stub_auth(json=self.TEST_RESPONSE_DICT)

        # Creating a HTTPClient not using session is deprecated.
        with self.deprecations.expect_deprecations_here():
            cs = client.Client(user_id=self.TEST_USER,
                               password=self.TEST_TOKEN,
                               domain_id=self.TEST_DOMAIN_ID,
                               auth_url=self.TEST_URL)
        self.assertEqual(cs.auth_domain_id,
                         self.TEST_DOMAIN_ID)
        self.assertEqual(cs.management_url,
                         self.TEST_RESPONSE_DICT["token"]["catalog"][3]
                         ['endpoints'][2]["url"])
        self.assertEqual(cs.auth_token,
                         self.TEST_RESPONSE_HEADERS["X-Subject-Token"])
        self.assertRequestBodyIs(json=self.TEST_REQUEST_BODY)

    def test_authenticate_success_userid_password_project_scoped(self):
        ident = self.TEST_REQUEST_BODY['auth']['identity']
        del ident['password']['user']['domain']
        del ident['password']['user']['name']
        ident['password']['user']['id'] = self.TEST_USER

        self.stub_auth(json=self.TEST_RESPONSE_DICT)

        # Creating a HTTPClient not using session is deprecated.
        with self.deprecations.expect_deprecations_here():
            cs = client.Client(user_id=self.TEST_USER,
                               password=self.TEST_TOKEN,
                               project_id=self.TEST_TENANT_ID,
                               auth_url=self.TEST_URL)
        self.assertEqual(cs.auth_tenant_id,
                         self.TEST_TENANT_ID)
        self.assertEqual(cs.management_url,
                         self.TEST_RESPONSE_DICT["token"]["catalog"][3]
                         ['endpoints'][2]["url"])
        self.assertEqual(cs.auth_token,
                         self.TEST_RESPONSE_HEADERS["X-Subject-Token"])
        self.assertRequestBodyIs(json=self.TEST_REQUEST_BODY)

    def test_authenticate_success_password_unscoped(self):
        del self.TEST_RESPONSE_DICT['token']['catalog']
        del self.TEST_REQUEST_BODY['auth']['scope']

        self.stub_auth(json=self.TEST_RESPONSE_DICT)

        # Creating a HTTPClient not using session is deprecated.
        with self.deprecations.expect_deprecations_here():
            cs = client.Client(user_domain_name=self.TEST_DOMAIN_NAME,
                               username=self.TEST_USER,
                               password=self.TEST_TOKEN,
                               auth_url=self.TEST_URL)
        self.assertEqual(cs.auth_token,
                         self.TEST_RESPONSE_HEADERS["X-Subject-Token"])
        self.assertNotIn('catalog', cs.service_catalog.catalog)
        self.assertRequestBodyIs(json=self.TEST_REQUEST_BODY)

    def test_auth_url_token_authentication(self):
        fake_token = 'fake_token'
        fake_url = '/fake-url'
        fake_resp = {'result': True}

        self.stub_auth(json=self.TEST_RESPONSE_DICT)
        self.stub_url('GET', [fake_url], json=fake_resp,
                      base_url=self.TEST_ADMIN_IDENTITY_ENDPOINT)

        # Creating a HTTPClient not using session is deprecated.
        with self.deprecations.expect_deprecations_here():
            cl = client.Client(auth_url=self.TEST_URL,
                               token=fake_token)
        body = jsonutils.loads(self.requests_mock.last_request.body)
        self.assertEqual(body['auth']['identity']['token']['id'], fake_token)

        resp, body = cl._adapter.get(fake_url)
        self.assertEqual(fake_resp, body)

        token = self.requests_mock.last_request.headers.get('X-Auth-Token')
        self.assertEqual(self.TEST_TOKEN, token)

    def test_authenticate_success_token_domain_scoped(self):
        ident = self.TEST_REQUEST_BODY['auth']['identity']
        del ident['password']
        ident['methods'] = ['token']
        ident['token'] = {}
        ident['token']['id'] = self.TEST_TOKEN

        scope = self.TEST_REQUEST_BODY['auth']['scope']
        del scope['project']
        scope['domain'] = {}
        scope['domain']['id'] = self.TEST_DOMAIN_ID

        token = self.TEST_RESPONSE_DICT['token']
        del token['project']
        token['domain'] = {}
        token['domain']['id'] = self.TEST_DOMAIN_ID
        token['domain']['name'] = self.TEST_DOMAIN_NAME

        self.TEST_REQUEST_HEADERS['X-Auth-Token'] = self.TEST_TOKEN

        self.stub_auth(json=self.TEST_RESPONSE_DICT)

        # Creating a HTTPClient not using session is deprecated.
        with self.deprecations.expect_deprecations_here():
            cs = client.Client(token=self.TEST_TOKEN,
                               domain_id=self.TEST_DOMAIN_ID,
                               auth_url=self.TEST_URL)
        self.assertEqual(cs.auth_domain_id,
                         self.TEST_DOMAIN_ID)
        self.assertEqual(cs.management_url,
                         self.TEST_RESPONSE_DICT["token"]["catalog"][3]
                         ['endpoints'][2]["url"])
        self.assertEqual(cs.auth_token,
                         self.TEST_RESPONSE_HEADERS["X-Subject-Token"])
        self.assertRequestBodyIs(json=self.TEST_REQUEST_BODY)

    def test_authenticate_success_token_project_scoped(self):
        ident = self.TEST_REQUEST_BODY['auth']['identity']
        del ident['password']
        ident['methods'] = ['token']
        ident['token'] = {}
        ident['token']['id'] = self.TEST_TOKEN
        self.TEST_REQUEST_HEADERS['X-Auth-Token'] = self.TEST_TOKEN

        self.stub_auth(json=self.TEST_RESPONSE_DICT)

        # Creating a HTTPClient not using session is deprecated.
        with self.deprecations.expect_deprecations_here():
            cs = client.Client(token=self.TEST_TOKEN,
                               project_id=self.TEST_TENANT_ID,
                               auth_url=self.TEST_URL)
        self.assertEqual(cs.auth_tenant_id,
                         self.TEST_TENANT_ID)
        self.assertEqual(cs.management_url,
                         self.TEST_RESPONSE_DICT["token"]["catalog"][3]
                         ['endpoints'][2]["url"])
        self.assertEqual(cs.auth_token,
                         self.TEST_RESPONSE_HEADERS["X-Subject-Token"])
        self.assertRequestBodyIs(json=self.TEST_REQUEST_BODY)

    def test_authenticate_success_token_unscoped(self):
        ident = self.TEST_REQUEST_BODY['auth']['identity']
        del ident['password']
        ident['methods'] = ['token']
        ident['token'] = {}
        ident['token']['id'] = self.TEST_TOKEN
        del self.TEST_REQUEST_BODY['auth']['scope']
        del self.TEST_RESPONSE_DICT['token']['catalog']
        self.TEST_REQUEST_HEADERS['X-Auth-Token'] = self.TEST_TOKEN

        self.stub_auth(json=self.TEST_RESPONSE_DICT)

        # Creating a HTTPClient not using session is deprecated.
        with self.deprecations.expect_deprecations_here():
            cs = client.Client(token=self.TEST_TOKEN,
                               auth_url=self.TEST_URL)
        self.assertEqual(cs.auth_token,
                         self.TEST_RESPONSE_HEADERS["X-Subject-Token"])
        self.assertNotIn('catalog', cs.service_catalog.catalog)
        self.assertRequestBodyIs(json=self.TEST_REQUEST_BODY)

    def test_allow_override_of_auth_token(self):
        fake_url = '/fake-url'
        fake_token = 'fake_token'
        fake_resp = {'result': True}

        self.stub_auth(json=self.TEST_RESPONSE_DICT)
        self.stub_url('GET', [fake_url], json=fake_resp,
                      base_url=self.TEST_ADMIN_IDENTITY_ENDPOINT)

        # Creating a HTTPClient not using session is deprecated.
        with self.deprecations.expect_deprecations_here():
            cl = client.Client(username='exampleuser',
                               password='password',
                               project_name='exampleproject',
                               auth_url=self.TEST_URL)

        self.assertEqual(cl.auth_token, self.TEST_TOKEN)

        # the token returned from the authentication will be used
        resp, body = cl._adapter.get(fake_url)
        self.assertEqual(fake_resp, body)

        token = self.requests_mock.last_request.headers.get('X-Auth-Token')
        self.assertEqual(self.TEST_TOKEN, token)

        # then override that token and the new token shall be used
        cl.auth_token = fake_token

        resp, body = cl._adapter.get(fake_url)
        self.assertEqual(fake_resp, body)

        token = self.requests_mock.last_request.headers.get('X-Auth-Token')
        self.assertEqual(fake_token, token)

        # if we clear that overridden token then we fall back to the original
        del cl.auth_token

        resp, body = cl._adapter.get(fake_url)
        self.assertEqual(fake_resp, body)

        token = self.requests_mock.last_request.headers.get('X-Auth-Token')
        self.assertEqual(self.TEST_TOKEN, token)