aboutsummaryrefslogtreecommitdiffstats
path: root/keystone-moon/keystone/contrib/revoke/core.py
blob: c7335690b7f5f64856151afc9bd139f222e4c9d4 (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
# 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
import datetime

from oslo_config import cfg
from oslo_log import log
from oslo_utils import timeutils
import six

from keystone.common import cache
from keystone.common import dependency
from keystone.common import extension
from keystone.common import manager
from keystone.contrib.revoke import model
from keystone import exception
from keystone.i18n import _
from keystone import notifications
from keystone.openstack.common import versionutils


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


EXTENSION_DATA = {
    'name': 'OpenStack Revoke API',
    'namespace': 'http://docs.openstack.org/identity/api/ext/'
                 'OS-REVOKE/v1.0',
    'alias': 'OS-REVOKE',
    'updated': '2014-02-24T20:51:0-00:00',
    'description': 'OpenStack revoked token reporting mechanism.',
    'links': [
        {
            'rel': 'describedby',
            'type': 'text/html',
            'href': ('https://github.com/openstack/identity-api/blob/master/'
                     'openstack-identity-api/v3/src/markdown/'
                     'identity-api-v3-os-revoke-ext.md'),
        }
    ]}
extension.register_admin_extension(EXTENSION_DATA['alias'], EXTENSION_DATA)
extension.register_public_extension(EXTENSION_DATA['alias'], EXTENSION_DATA)

MEMOIZE = cache.get_memoization_decorator(section='revoke')


def revoked_before_cutoff_time():
    expire_delta = datetime.timedelta(
        seconds=CONF.token.expiration + CONF.revoke.expiration_buffer)
    oldest = timeutils.utcnow() - expire_delta
    return oldest


@dependency.provider('revoke_api')
class Manager(manager.Manager):
    """Revoke API Manager.

    Performs common logic for recording revocations.

    """

    def __init__(self):
        super(Manager, self).__init__(CONF.revoke.driver)
        self._register_listeners()
        self.model = model

    def _user_callback(self, service, resource_type, operation,
                       payload):
        self.revoke_by_user(payload['resource_info'])

    def _role_callback(self, service, resource_type, operation,
                       payload):
        self.revoke(
            model.RevokeEvent(role_id=payload['resource_info']))

    def _project_callback(self, service, resource_type, operation,
                          payload):
        self.revoke(
            model.RevokeEvent(project_id=payload['resource_info']))

    def _domain_callback(self, service, resource_type, operation,
                         payload):
        self.revoke(
            model.RevokeEvent(domain_id=payload['resource_info']))

    def _trust_callback(self, service, resource_type, operation,
                        payload):
        self.revoke(
            model.RevokeEvent(trust_id=payload['resource_info']))

    def _consumer_callback(self, service, resource_type, operation,
                           payload):
        self.revoke(
            model.RevokeEvent(consumer_id=payload['resource_info']))

    def _access_token_callback(self, service, resource_type, operation,
                               payload):
        self.revoke(
            model.RevokeEvent(access_token_id=payload['resource_info']))

    def _group_callback(self, service, resource_type, operation, payload):
        user_ids = (u['id'] for u in self.identity_api.list_users_in_group(
            payload['resource_info']))
        for uid in user_ids:
            self.revoke(model.RevokeEvent(user_id=uid))

    def _register_listeners(self):
        callbacks = {
            notifications.ACTIONS.deleted: [
                ['OS-TRUST:trust', self._trust_callback],
                ['OS-OAUTH1:consumer', self._consumer_callback],
                ['OS-OAUTH1:access_token', self._access_token_callback],
                ['role', self._role_callback],
                ['user', self._user_callback],
                ['project', self._project_callback],
            ],
            notifications.ACTIONS.disabled: [
                ['user', self._user_callback],
                ['project', self._project_callback],
                ['domain', self._domain_callback],
            ],
            notifications.ACTIONS.internal: [
                [notifications.INVALIDATE_USER_TOKEN_PERSISTENCE,
                 self._user_callback],
            ]
        }

        for event, cb_info in six.iteritems(callbacks):
            for resource_type, callback_fns in cb_info:
                notifications.register_event_callback(event, resource_type,
                                                      callback_fns)

    def revoke_by_user(self, user_id):
        return self.revoke(model.RevokeEvent(user_id=user_id))

    def _assert_not_domain_and_project_scoped(self, domain_id=None,
                                              project_id=None):
        if domain_id is not None and project_id is not None:
            msg = _('The revoke call must not have both domain_id and '
                    'project_id. This is a bug in the Keystone server. The '
                    'current request is aborted.')
            raise exception.UnexpectedError(exception=msg)

    @versionutils.deprecated(as_of=versionutils.deprecated.JUNO,
                             remove_in=0)
    def revoke_by_expiration(self, user_id, expires_at,
                             domain_id=None, project_id=None):

        self._assert_not_domain_and_project_scoped(domain_id=domain_id,
                                                   project_id=project_id)

        self.revoke(
            model.RevokeEvent(user_id=user_id,
                              expires_at=expires_at,
                              domain_id=domain_id,
                              project_id=project_id))

    def revoke_by_audit_id(self, audit_id):
        self.revoke(model.RevokeEvent(audit_id=audit_id))

    def revoke_by_audit_chain_id(self, audit_chain_id, project_id=None,
                                 domain_id=None):

        self._assert_not_domain_and_project_scoped(domain_id=domain_id,
                                                   project_id=project_id)

        self.revoke(model.RevokeEvent(audit_chain_id=audit_chain_id,
                                      domain_id=domain_id,
                                      project_id=project_id))

    def revoke_by_grant(self, role_id, user_id=None,
                        domain_id=None, project_id=None):
        self.revoke(
            model.RevokeEvent(user_id=user_id,
                              role_id=role_id,
                              domain_id=domain_id,
                              project_id=project_id))

    def revoke_by_user_and_project(self, user_id, project_id):
        self.revoke(
            model.RevokeEvent(project_id=project_id, user_id=user_id))

    def revoke_by_project_role_assignment(self, project_id, role_id):
        self.revoke(model.RevokeEvent(project_id=project_id, role_id=role_id))

    def revoke_by_domain_role_assignment(self, domain_id, role_id):
        self.revoke(model.RevokeEvent(domain_id=domain_id, role_id=role_id))

    @MEMOIZE
    def _get_revoke_tree(self):
        events = self.driver.list_events()
        revoke_tree = model.RevokeTree(revoke_events=events)

        return revoke_tree

    def check_token(self, token_values):
        """Checks the values from a token against the revocation list

        :param  token_values: dictionary of values from a token,
         normalized for differences between v2 and v3. The checked values are a
         subset of the attributes of model.TokenEvent

        :raises exception.TokenNotFound: if the token is invalid

         """
        if self._get_revoke_tree().is_revoked(token_values):
            raise exception.TokenNotFound(_('Failed to validate token'))

    def revoke(self, event):
        self.driver.revoke(event)
        self._get_revoke_tree.invalidate(self)


@six.add_metaclass(abc.ABCMeta)
class Driver(object):
    """Interface for recording and reporting revocation events."""

    @abc.abstractmethod
    def list_events(self, last_fetch=None):
        """return the revocation events, as a list of objects

        :param last_fetch:   Time of last fetch.  Return all events newer.
        :returns: A list of keystone.contrib.revoke.model.RevokeEvent
                  newer than `last_fetch.`
                  If no last_fetch is specified, returns all events
                  for tokens issued after the expiration cutoff.

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

    @abc.abstractmethod
    def revoke(self, event):
        """register a revocation event

        :param event: An instance of
            keystone.contrib.revoke.model.RevocationEvent

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