summaryrefslogtreecommitdiff
path: root/troveclient/compat/auth.py
blob: 1a331bc5fcbe75cd9c084a49bc81eb1bb01481c1 (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
#    Copyright 2012 OpenStack Foundation
#
#    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 six
from troveclient.compat import exceptions


def get_authenticator_cls(cls_or_name):
    """Factory method to retrieve Authenticator class."""
    if isinstance(cls_or_name, type):
        return cls_or_name
    elif isinstance(cls_or_name, six.string_types):
        if cls_or_name == "keystone":
            return KeyStoneV3Authenticator
        elif cls_or_name == "auth1.1":
            return Auth1_1
        elif cls_or_name == "fake":
            return FakeAuth

    raise ValueError("Could not determine authenticator class from the given "
                     "value %r." % cls_or_name)


class Authenticator(object):
    """Helper class to perform Keystone or other miscellaneous authentication.

    The "authenticate" method returns a ServiceCatalog, which can be used
    to obtain a token.

    """

    URL_REQUIRED = True

    def __init__(self, client, type, url, username, password, tenant,
                 region=None, service_type=None, service_name=None,
                 service_url=None):
        self.client = client
        self.type = type
        self.url = url
        self.username = username
        self.password = password
        self.tenant = tenant
        self.region = region
        self.service_type = service_type
        self.service_name = service_name
        self.service_url = service_url

    def _authenticate(self, url, body, root_key='access'):
        """Authenticate and extract the service catalog."""
        # Make sure we follow redirects when trying to reach Keystone
        tmp_follow_all_redirects = self.client.follow_all_redirects
        self.client.follow_all_redirects = True

        try:
            resp, body = self.client._time_request(url, "POST", body=body)
        finally:
            self.client.follow_all_redirects = tmp_follow_all_redirects

        if resp.status == 201:  # Keystone v3
            try:
                token = resp.get('x-subject-token')
                return ServiceCatalog3(body, region=self.region,
                                       service_type=self.service_type,
                                       service_name=self.service_name,
                                       service_url=self.service_url,
                                       token=token)
            except exceptions.AmbiguousEndpoints:
                print("Found more than one valid endpoint. Use a more "
                      "restrictive filter")
                raise
            except KeyError:
                raise exceptions.AuthorizationFailure()
            except exceptions.EndpointNotFound:
                print("Could not find any suitable endpoint. Correct region?")
                raise
        elif resp.status == 200:  # Keystone pre-v3
            try:
                return ServiceCatalog(body, region=self.region,
                                      service_type=self.service_type,
                                      service_name=self.service_name,
                                      service_url=self.service_url,
                                      root_key=root_key)
            except exceptions.AmbiguousEndpoints:
                print("Found more than one valid endpoint. Use a more "
                      "restrictive filter")
                raise
            except KeyError:
                raise exceptions.AuthorizationFailure()
            except exceptions.EndpointNotFound:
                print("Could not find any suitable endpoint. Correct region?")
                raise

        elif resp.status == 305:
            return resp['location']
        else:
            raise exceptions.from_response(resp, body)

    def authenticate(self):
        raise NotImplementedError("Missing authenticate method.")


class KeyStoneV3Authenticator(Authenticator):
    def __init__(self, client, type, url, username, password, tenant,
                 region=None, service_type=None, service_name=None,
                 service_url=None):
        super(KeyStoneV3Authenticator, self).\
            __init__(client, type, url, username, password, tenant,
                     region=region, service_type=service_type,
                     service_name=service_name, service_url=service_url)

        # The Auth obect is needed because
        # troveclient.v1.instances.Instances._get_swift_client assumes
        # its v3 auth path is using a client which inherits from
        # keystone1.adapter.Adapter and then further goes after that
        # adapter's internal attributes to fetch them and send them
        # to the Swift client it creates.
        class Auth(object):
            def __init__(self, auth_url, username, password, project_name):
                token_str = "/auth/tokens"
                if auth_url.endswith(token_str):
                    auth_url = auth_url[:-len(token_str)]

                self.auth_url = auth_url
                self._username = username
                self._password = password
                self._project_name = project_name

        self.auth = Auth(url, username, password, tenant)

    def authenticate(self):
        if self.url is None:
            raise exceptions.AuthUrlNotGiven()
        return self._v3_auth(self.url)

    def _v3_auth(self, url):
        """Authenticate against a v3.0 auth service."""
        body = {'auth': {
                'identity': {
                    'methods': ['password'],
                    'password': {
                        'user': {
                            'domain': {'name': 'Default'},
                            'name': self.username,
                            'password': self.password
                        }
                    }
                }}}

        if self.tenant:
            body['auth']['scope'] = {'project': {
                                     'domain': {'name': 'Default'},
                                     'name': self.tenant}}

        return self._authenticate(url, body)


class KeyStoneV2Authenticator(Authenticator):
    def authenticate(self):
        if self.url is None:
            raise exceptions.AuthUrlNotGiven()
        return self._v2_auth(self.url)

    def _v2_auth(self, url):
        """Authenticate against a v2.0 auth service."""
        body = {"auth": {
            "passwordCredentials": {
                "username": self.username,
                "password": self.password}
        }
        }

        if self.tenant:
            body['auth']['tenantName'] = self.tenant

        return self._authenticate(url, body)


class Auth1_1(Authenticator):
    def authenticate(self):
        """Authenticate against a v2.0 auth service."""
        if self.url is None:
            raise exceptions.AuthUrlNotGiven()
        auth_url = self.url
        body = {
            "credentials": {
                "username": self.username,
                "key": self.password
            }}
        return self._authenticate(auth_url, body, root_key='auth')


class FakeAuth(Authenticator):
    """Useful for faking auth."""

    def authenticate(self):
        class FakeCatalog(object):
            def __init__(self, auth):
                self.auth = auth

            def get_public_url(self):
                return "%s/%s" % ('http://localhost:8779/v1.0',
                                  self.auth.tenant)

            def get_token(self):
                return self.auth.tenant

        return FakeCatalog(self)


class ServiceCatalog(object):
    """Represents a Keystone Service Catalog which describes a service.

    This class has methods to obtain a valid token as well as a public service
    url and a management url.

    """

    def __init__(self, resource_dict, region=None, service_type=None,
                 service_name=None, service_url=None, root_key='access'):
        self.catalog = resource_dict
        self.region = region
        self.service_type = service_type
        self.service_name = service_name
        self.service_url = service_url
        self.management_url = None
        self.public_url = None
        self.root_key = root_key
        self._load()

    def _load(self):
        if not self.service_url:
            self.public_url = self._url_for(attr='region',
                                            filter_value=self.region,
                                            endpoint_type="publicURL")
            self.management_url = self._url_for(attr='region',
                                                filter_value=self.region,
                                                endpoint_type="adminURL")
        else:
            self.public_url = self.service_url
            self.management_url = self.service_url

    def get_token(self):
        return self.catalog[self.root_key]['token']['id']

    def get_management_url(self):
        return self.management_url

    def get_public_url(self):
        return self.public_url

    def _url_for(self, attr=None, filter_value=None,
                 endpoint_type='publicURL'):
        """Fetch requested URL.

        Fetch the public URL from the Trove service for a particular
        endpoint attribute. If none given, return the first.
        """
        matching_endpoints = []
        if 'endpoints' in self.catalog:
            # We have a bastardized service catalog. Treat it special. :/
            for endpoint in self.catalog['endpoints']:
                if not filter_value or endpoint[attr] == filter_value:
                    matching_endpoints.append(endpoint)
            if not matching_endpoints:
                raise exceptions.EndpointNotFound()

        # We don't always get a service catalog back ...
        if 'serviceCatalog' not in self.catalog[self.root_key]:
            raise exceptions.EndpointNotFound()

        # Full catalog ...
        catalog = self.catalog[self.root_key]['serviceCatalog']

        for service in catalog:
            if service.get("type") != self.service_type:
                continue

            if (self.service_name and self.service_type == 'database' and
                    service.get('name') != self.service_name):
                continue

            endpoints = service['endpoints']
            for endpoint in endpoints:
                if not filter_value or endpoint.get(attr) == filter_value:
                    endpoint["serviceName"] = service.get("name")
                    matching_endpoints.append(endpoint)

        if not matching_endpoints:
            raise exceptions.EndpointNotFound()
        elif len(matching_endpoints) > 1:
            raise exceptions.AmbiguousEndpoints(endpoints=matching_endpoints)
        else:
            return matching_endpoints[0].get(endpoint_type, None)


class ServiceCatalog3(object):
    """Represents a Keystone Service Catalog which describes a service.

    This class has methods to obtain a valid token as well as a public service
    url and a management url.

    """

    def __init__(self, resource_dict, region=None, service_type=None,
                 service_name=None, service_url=None, token=None):
        self.body = resource_dict
        self.region = region
        self.service_type = service_type
        self.service_name = service_name
        self.service_url = service_url
        self.management_url = None
        self.public_url = None
        self.token = token
        self._load()

    def _load(self):
        if not self.service_url:
            self.public_url = self._url_for(attr='region',
                                            filter_value=self.region,
                                            endpoint_type="public")
            self.management_url = self._url_for(attr='region',
                                                filter_value=self.region,
                                                endpoint_type="admin")
        else:
            self.public_url = self.service_url
            self.management_url = self.service_url

    def get_token(self):
        return self.token

    def get_management_url(self):
        return self.management_url

    def get_public_url(self):
        return self.public_url

    def _url_for(self, attr=None, filter_value=None,
                 endpoint_type='public'):
        """Fetch requested URL.

        Fetch the public URL from the Trove service for a particular
        endpoint attribute. If none given, return the first.
        """
        """Fetch the requested end point URL.
         """
        matching_endpoints = []
        catalog = self.body['token']['catalog']
        for service in catalog:
            if service.get("type") != self.service_type:
                continue
            if (self.service_name and self.service_type == 'database' and
                    service.get('name') != self.service_name):
                continue
            endpoints = service['endpoints']
            for endpoint in endpoints:
                if endpoint.get('interface') == endpoint_type and \
                        (not filter_value or
                         endpoint.get(attr) == filter_value):
                    matching_endpoints.append(endpoint)
        if not matching_endpoints:
            raise exceptions.EndpointNotFound()
        else:
            return matching_endpoints[0].get('url')