aboutsummaryrefslogtreecommitdiffstats
path: root/keystone-moon/keystone/contrib/endpoint_policy/core.py
blob: 1aa032674adfc2c29856005e272a94bda5811dd2 (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
# Copyright 2014 IBM Corp.
#
# 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 abc

from oslo_config import cfg
from oslo_log import log
import six

from keystone.common import dependency
from keystone.common import manager
from keystone import exception
from keystone.i18n import _, _LE, _LW

CONF = cfg.CONF
LOG = log.getLogger(__name__)


@dependency.provider('endpoint_policy_api')
@dependency.requires('catalog_api', 'policy_api')
class Manager(manager.Manager):
    """Default pivot point for the Endpoint Policy backend.

    See :mod:`keystone.common.manager.Manager` for more details on how this
    dynamically calls the backend.

    """

    def __init__(self):
        super(Manager, self).__init__(CONF.endpoint_policy.driver)

    def _assert_valid_association(self, endpoint_id, service_id, region_id):
        """Assert that the association is supported.

        There are three types of association supported:

        - Endpoint (in which case service and region must be None)
        - Service and region (in which endpoint must be None)
        - Service (in which case endpoint and region must be None)

        """
        if (endpoint_id is not None and
                service_id is None and region_id is None):
            return
        if (service_id is not None and region_id is not None and
                endpoint_id is None):
            return
        if (service_id is not None and
                endpoint_id is None and region_id is None):
            return

        raise exception.InvalidPolicyAssociation(endpoint_id=endpoint_id,
                                                 service_id=service_id,
                                                 region_id=region_id)

    def create_policy_association(self, policy_id, endpoint_id=None,
                                  service_id=None, region_id=None):
        self._assert_valid_association(endpoint_id, service_id, region_id)
        self.driver.create_policy_association(policy_id, endpoint_id,
                                              service_id, region_id)

    def check_policy_association(self, policy_id, endpoint_id=None,
                                 service_id=None, region_id=None):
        self._assert_valid_association(endpoint_id, service_id, region_id)
        self.driver.check_policy_association(policy_id, endpoint_id,
                                             service_id, region_id)

    def delete_policy_association(self, policy_id, endpoint_id=None,
                                  service_id=None, region_id=None):
        self._assert_valid_association(endpoint_id, service_id, region_id)
        self.driver.delete_policy_association(policy_id, endpoint_id,
                                              service_id, region_id)

    def list_endpoints_for_policy(self, policy_id):

        def _get_endpoint(endpoint_id, policy_id):
            try:
                return self.catalog_api.get_endpoint(endpoint_id)
            except exception.EndpointNotFound:
                msg = _LW('Endpoint %(endpoint_id)s referenced in '
                          'association for policy %(policy_id)s not found.')
                LOG.warning(msg, {'policy_id': policy_id,
                                  'endpoint_id': endpoint_id})
                raise

        def _get_endpoints_for_service(service_id, endpoints):
            # TODO(henry-nash): Consider optimizing this in the future by
            # adding an explicit list_endpoints_for_service to the catalog API.
            return [ep for ep in endpoints if ep['service_id'] == service_id]

        def _get_endpoints_for_service_and_region(
                service_id, region_id, endpoints, regions):
            # TODO(henry-nash): Consider optimizing this in the future.
            # The lack of a two-way pointer in the region tree structure
            # makes this somewhat inefficient.

            def _recursively_get_endpoints_for_region(
                region_id, service_id, endpoint_list, region_list,
                    endpoints_found, regions_examined):
                """Recursively search down a region tree for endpoints.

                :param region_id: the point in the tree to examine
                :param service_id: the service we are interested in
                :param endpoint_list: list of all endpoints
                :param region_list: list of all regions
                :param endpoints_found: list of matching endpoints found so
                                        far - which will be updated if more are
                                        found in this iteration
                :param regions_examined: list of regions we have already looked
                                         at - used to spot illegal circular
                                         references in the tree to avoid never
                                         completing search
                :returns: list of endpoints that match

                """

                if region_id in regions_examined:
                    msg = _LE('Circular reference or a repeated entry found '
                              'in region tree - %(region_id)s.')
                    LOG.error(msg, {'region_id': ref.region_id})
                    return

                regions_examined.append(region_id)
                endpoints_found += (
                    [ep for ep in endpoint_list if
                     ep['service_id'] == service_id and
                     ep['region_id'] == region_id])

                for region in region_list:
                    if region['parent_region_id'] == region_id:
                        _recursively_get_endpoints_for_region(
                            region['id'], service_id, endpoints, regions,
                            endpoints_found, regions_examined)

            endpoints_found = []
            regions_examined = []

            # Now walk down the region tree
            _recursively_get_endpoints_for_region(
                region_id, service_id, endpoints, regions,
                endpoints_found, regions_examined)

            return endpoints_found

        matching_endpoints = []
        endpoints = self.catalog_api.list_endpoints()
        regions = self.catalog_api.list_regions()
        for ref in self.driver.list_associations_for_policy(policy_id):
            if ref.get('endpoint_id') is not None:
                matching_endpoints.append(
                    _get_endpoint(ref['endpoint_id'], policy_id))
                continue

            if (ref.get('service_id') is not None and
                    ref.get('region_id') is None):
                matching_endpoints += _get_endpoints_for_service(
                    ref['service_id'], endpoints)
                continue

            if (ref.get('service_id') is not None and
                    ref.get('region_id') is not None):
                matching_endpoints += (
                    _get_endpoints_for_service_and_region(
                        ref['service_id'], ref['region_id'],
                        endpoints, regions))
                continue

            msg = _LW('Unsupported policy association found - '
                      'Policy %(policy_id)s, Endpoint %(endpoint_id)s, '
                      'Service %(service_id)s, Region %(region_id)s, ')
            LOG.warning(msg, {'policy_id': policy_id,
                              'endpoint_id': ref['endpoint_id'],
                              'service_id': ref['service_id'],
                              'region_id': ref['region_id']})

        return matching_endpoints

    def get_policy_for_endpoint(self, endpoint_id):

        def _get_policy(policy_id, endpoint_id):
            try:
                return self.policy_api.get_policy(policy_id)
            except exception.PolicyNotFound:
                msg = _LW('Policy %(policy_id)s referenced in association '
                          'for endpoint %(endpoint_id)s not found.')
                LOG.warning(msg, {'policy_id': policy_id,
                                  'endpoint_id': endpoint_id})
                raise

        def _look_for_policy_for_region_and_service(endpoint):
            """Look in the region and its parents for a policy.

            Examine the region of the endpoint for a policy appropriate for
            the service of the endpoint. If there isn't a match, then chase up
            the region tree to find one.

            """
            region_id = endpoint['region_id']
            regions_examined = []
            while region_id is not None:
                try:
                    ref = self.driver.get_policy_association(
                        service_id=endpoint['service_id'],
                        region_id=region_id)
                    return ref['policy_id']
                except exception.PolicyAssociationNotFound:
                    pass

                # There wasn't one for that region & service, let's
                # chase up the region tree
                regions_examined.append(region_id)
                region = self.catalog_api.get_region(region_id)
                region_id = None
                if region.get('parent_region_id') is not None:
                    region_id = region['parent_region_id']
                    if region_id in regions_examined:
                        msg = _LE('Circular reference or a repeated entry '
                                  'found in region tree - %(region_id)s.')
                        LOG.error(msg, {'region_id': region_id})
                        break

        # First let's see if there is a policy explicitly defined for
        # this endpoint.

        try:
            ref = self.driver.get_policy_association(endpoint_id=endpoint_id)
            return _get_policy(ref['policy_id'], endpoint_id)
        except exception.PolicyAssociationNotFound:
            pass

        # There wasn't a policy explicitly defined for this endpoint, so
        # now let's see if there is one for the Region & Service.

        endpoint = self.catalog_api.get_endpoint(endpoint_id)
        policy_id = _look_for_policy_for_region_and_service(endpoint)
        if policy_id is not None:
            return _get_policy(policy_id, endpoint_id)

        # Finally, just check if there is one for the service.
        try:
            ref = self.driver.get_policy_association(
                service_id=endpoint['service_id'])
            return _get_policy(ref['policy_id'], endpoint_id)
        except exception.PolicyAssociationNotFound:
            pass

        msg = _('No policy is associated with endpoint '
                '%(endpoint_id)s.') % {'endpoint_id': endpoint_id}
        raise exception.NotFound(msg)


@six.add_metaclass(abc.ABCMeta)
class Driver(object):
    """Interface description for an Endpoint Policy driver."""

    @abc.abstractmethod
    def create_policy_association(self, policy_id, endpoint_id=None,
                                  service_id=None, region_id=None):
        """Creates a policy association.

        :param policy_id: identity of policy that is being associated
        :type policy_id: string
        :param endpoint_id: identity of endpoint to associate
        :type endpoint_id: string
        :param service_id: identity of the service to associate
        :type service_id: string
        :param region_id: identity of the region to associate
        :type region_id: string
        :returns: None

        There are three types of association permitted:

        - Endpoint (in which case service and region must be None)
        - Service and region (in which endpoint must be None)
        - Service (in which case endpoint and region must be None)

        """
        raise exception.NotImplemented()  # pragma: no cover

    @abc.abstractmethod
    def check_policy_association(self, policy_id, endpoint_id=None,
                                 service_id=None, region_id=None):
        """Checks existence a policy association.

        :param policy_id: identity of policy that is being associated
        :type policy_id: string
        :param endpoint_id: identity of endpoint to associate
        :type endpoint_id: string
        :param service_id: identity of the service to associate
        :type service_id: string
        :param region_id: identity of the region to associate
        :type region_id: string
        :raises: keystone.exception.PolicyAssociationNotFound if there is no
                 match for the specified association
        :returns: None

        """
        raise exception.NotImplemented()  # pragma: no cover

    @abc.abstractmethod
    def delete_policy_association(self, policy_id, endpoint_id=None,
                                  service_id=None, region_id=None):
        """Deletes a policy association.

        :param policy_id: identity of policy that is being associated
        :type policy_id: string
        :param endpoint_id: identity of endpoint to associate
        :type endpoint_id: string
        :param service_id: identity of the service to associate
        :type service_id: string
        :param region_id: identity of the region to associate
        :type region_id: string
        :returns: None

        """
        raise exception.NotImplemented()  # pragma: no cover

    @abc.abstractmethod
    def get_policy_association(self, endpoint_id=None,
                               service_id=None, region_id=None):
        """Gets the policy for an explicit association.

        This method is not exposed as a public API, but is used by
        get_policy_for_endpoint().

        :param endpoint_id: identity of endpoint
        :type endpoint_id: string
        :param service_id: identity of the service
        :type service_id: string
        :param region_id: identity of the region
        :type region_id: string
        :raises: keystone.exception.PolicyAssociationNotFound if there is no
                 match for the specified association
        :returns: dict containing policy_id

        """
        raise exception.NotImplemented()  # pragma: no cover

    @abc.abstractmethod
    def list_associations_for_policy(self, policy_id):
        """List the associations for a policy.

        This method is not exposed as a public API, but is used by
        list_endpoints_for_policy().

        :param policy_id: identity of policy
        :type policy_id: string
        :returns: List of association dicts

        """
        raise exception.NotImplemented()  # pragma: no cover

    @abc.abstractmethod
    def list_endpoints_for_policy(self, policy_id):
        """List all the endpoints using a given policy.

        :param policy_id: identity of policy that is being associated
        :type policy_id: string
        :returns: list of endpoints that have an effective association with
                  that policy

        """
        raise exception.NotImplemented()  # pragma: no cover

    @abc.abstractmethod
    def get_policy_for_endpoint(self, endpoint_id):
        """Get the appropriate policy for a given endpoint.

        :param endpoint_id: identity of endpoint
        :type endpoint_id: string
        :returns: Policy entity for the endpoint


        """
        raise exception.NotImplemented()  # pragma: no cover

    @abc.abstractmethod
    def delete_association_by_endpoint(self, endpoint_id):
        """Removes all the policy associations with the specific endpoint.

        :param endpoint_id: identity of endpoint to check
        :type endpoint_id: string
        :returns: None

        """
        raise exception.NotImplemented()  # pragma: no cover

    @abc.abstractmethod
    def delete_association_by_service(self, service_id):
        """Removes all the policy associations with the specific service.

        :param service_id: identity of endpoint to check
        :type service_id: string
        :returns: None

        """
        raise exception.NotImplemented()  # pragma: no cover

    @abc.abstractmethod
    def delete_association_by_region(self, region_id):
        """Removes all the policy associations with the specific region.

        :param region_id: identity of endpoint to check
        :type region_id: string
        :returns: None

        """
        raise exception.NotImplemented()  # pragma: no cover

    @abc.abstractmethod
    def delete_association_by_policy(self, policy_id):
        """Removes all the policy associations with the specific policy.

        :param policy_id: identity of endpoint to check
        :type policy_id: string
        :returns: None

        """
        raise exception.NotImplemented()  # pragma: no cover