summaryrefslogtreecommitdiff
path: root/keystone/api/os_oauth2.py
blob: 81f3dbd3dc401425a45f6e6f57ac7fd5d0c7a239 (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
# Copyright 2022 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 flask
from flask import make_response
import http.client
from oslo_log import log
from oslo_serialization import jsonutils

from keystone.api._shared import authentication
from keystone.api._shared import json_home_relations
from keystone.common import provider_api
from keystone.common import utils
from keystone.conf import CONF
from keystone import exception
from keystone.federation import utils as federation_utils
from keystone.i18n import _
from keystone.server import flask as ks_flask

LOG = log.getLogger(__name__)

PROVIDERS = provider_api.ProviderAPIs

_build_resource_relation = json_home_relations.os_oauth2_resource_rel_func


class AccessTokenResource(ks_flask.ResourceBase):

    def _method_not_allowed(self):
        """Raise a method not allowed error."""
        raise exception.OAuth2OtherError(
            int(http.client.METHOD_NOT_ALLOWED),
            http.client.responses[http.client.METHOD_NOT_ALLOWED],
            _('The method is not allowed for the requested URL.'))

    @ks_flask.unenforced_api
    def get(self):
        """The method is not allowed."""
        self._method_not_allowed()

    @ks_flask.unenforced_api
    def head(self):
        """The method is not allowed."""
        self._method_not_allowed()

    @ks_flask.unenforced_api
    def put(self):
        """The method is not allowed."""
        self._method_not_allowed()

    @ks_flask.unenforced_api
    def patch(self):
        """The method is not allowed."""
        self._method_not_allowed()

    @ks_flask.unenforced_api
    def delete(self):
        """The method is not allowed."""
        self._method_not_allowed()

    @ks_flask.unenforced_api
    def post(self):
        """Get an OAuth2.0 Access Token.

        POST /v3/OS-OAUTH2/token
        """
        grant_type = flask.request.form.get('grant_type')
        if grant_type is None:
            error = exception.OAuth2InvalidRequest(
                int(http.client.BAD_REQUEST),
                http.client.responses[http.client.BAD_REQUEST],
                _('The parameter grant_type is required.'))
            LOG.info('Get OAuth2.0 Access Token API: '
                     f'{error.message_format}')
            raise error
        if grant_type != 'client_credentials':
            error = exception.OAuth2UnsupportedGrantType(
                int(http.client.BAD_REQUEST),
                http.client.responses[http.client.BAD_REQUEST],
                _('The parameter grant_type %s is not supported.'
                  ) % grant_type)
            LOG.info('Get OAuth2.0 Access Token API: '
                     f'{error.message_format}')
            raise error

        auth_method = ''
        client_id = flask.request.form.get('client_id')
        client_secret = flask.request.form.get('client_secret')
        client_cert = flask.request.environ.get("SSL_CLIENT_CERT")
        client_auth = flask.request.authorization
        if not client_cert and client_auth and client_auth.type == 'basic':
            client_id = client_auth.username
            client_secret = client_auth.password

        if not client_id:
            error = exception.OAuth2InvalidClient(
                int(http.client.UNAUTHORIZED),
                http.client.responses[http.client.UNAUTHORIZED],
                _('Client authentication failed.'))
            LOG.info('Get OAuth2.0 Access Token API: '
                     'failed to get a client_id from the request.')
            raise error
        if client_cert:
            auth_method = 'tls_client_auth'
        elif client_secret:
            auth_method = 'client_secret_basic'

        if auth_method in CONF.oauth2.oauth2_authn_methods:
            if auth_method == 'tls_client_auth':
                return self._tls_client_auth(client_id, client_cert)
            if auth_method == 'client_secret_basic':
                return self._client_secret_basic(client_id, client_secret)

        error = exception.OAuth2InvalidClient(
            int(http.client.UNAUTHORIZED),
            http.client.responses[http.client.UNAUTHORIZED],
            _('Client authentication failed.'))
        LOG.info('Get OAuth2.0 Access Token API: '
                 'failed to get client credentials from the request.')
        raise error

    def _client_secret_basic(self, client_id, client_secret):
        """Get an OAuth2.0 basic Access Token."""
        auth_data = {
            'identity': {
                'methods': ['application_credential'],
                'application_credential': {
                    'id': client_id,
                    'secret': client_secret
                }
            }
        }
        try:
            token = authentication.authenticate_for_token(auth_data)
        except exception.Error as error:
            if error.code == 401:
                error = exception.OAuth2InvalidClient(
                    error.code, error.title,
                    str(error))
            elif error.code == 400:
                error = exception.OAuth2InvalidRequest(
                    error.code, error.title,
                    str(error))
            else:
                error = exception.OAuth2OtherError(
                    error.code, error.title,
                    'An unknown error occurred and failed to get an OAuth2.0 '
                    'access token.')
            LOG.exception(error)
            raise error
        except Exception as error:
            error = exception.OAuth2OtherError(
                int(http.client.INTERNAL_SERVER_ERROR),
                http.client.responses[http.client.INTERNAL_SERVER_ERROR],
                str(error))
            LOG.exception(error)
            raise error

        resp = make_response({
            'access_token': token.id,
            'token_type': 'Bearer',
            'expires_in': CONF.token.expiration
        })
        resp.status = '200 OK'
        return resp

    def _check_mapped_properties(self, cert_dn, user, user_domain):
        mapping_id = CONF.oauth2.get('oauth2_cert_dn_mapping_id')
        try:
            mapping = PROVIDERS.federation_api.get_mapping(mapping_id)
        except exception.MappingNotFound:
            error = exception.OAuth2InvalidClient(
                int(http.client.UNAUTHORIZED),
                http.client.responses[http.client.UNAUTHORIZED],
                _('Client authentication failed.'))
            LOG.info('Get OAuth2.0 Access Token API: '
                     'mapping id %s is not found. ',
                     mapping_id)
            raise error

        rule_processor = federation_utils.RuleProcessor(
            mapping.get('id'), mapping.get('rules'))
        try:
            mapped_properties = rule_processor.process(cert_dn)
        except exception.Error as error:
            LOG.exception(error)
            error = exception.OAuth2InvalidClient(
                int(http.client.UNAUTHORIZED),
                http.client.responses[http.client.UNAUTHORIZED],
                _('Client authentication failed.'))
            LOG.info('Get OAuth2.0 Access Token API: '
                     'mapping rule process failed. '
                     'mapping_id: %s, rules: %s, data: %s.',
                     mapping_id, mapping.get('rules'),
                     jsonutils.dumps(cert_dn))
            raise error
        except Exception as error:
            LOG.exception(error)
            error = exception.OAuth2OtherError(
                int(http.client.INTERNAL_SERVER_ERROR),
                http.client.responses[http.client.INTERNAL_SERVER_ERROR],
                str(error))
            LOG.info('Get OAuth2.0 Access Token API: '
                     'mapping rule process failed. '
                     'mapping_id: %s, rules: %s, data: %s.',
                     mapping_id, mapping.get('rules'),
                     jsonutils.dumps(cert_dn))
            raise error

        mapping_user = mapped_properties.get('user', {})
        mapping_user_name = mapping_user.get('name')
        mapping_user_id = mapping_user.get('id')
        mapping_user_email = mapping_user.get('email')
        mapping_domain = mapping_user.get('domain', {})
        mapping_user_domain_id = mapping_domain.get('id')
        mapping_user_domain_name = mapping_domain.get('name')
        if mapping_user_name and mapping_user_name != user.get('name'):
            error = exception.OAuth2InvalidClient(
                int(http.client.UNAUTHORIZED),
                http.client.responses[http.client.UNAUTHORIZED],
                _('Client authentication failed.'))
            LOG.info('Get OAuth2.0 Access Token API: %s check failed. '
                     'DN value: %s, DB value: %s.',
                     'user name', mapping_user_name, user.get('name'))
            raise error
        if mapping_user_id and mapping_user_id != user.get('id'):
            error = exception.OAuth2InvalidClient(
                int(http.client.UNAUTHORIZED),
                http.client.responses[http.client.UNAUTHORIZED],
                _('Client authentication failed.'))
            LOG.info('Get OAuth2.0 Access Token API: %s check failed. '
                     'DN value: %s, DB value: %s.',
                     'user id', mapping_user_id, user.get('id'))
            raise error
        if mapping_user_email and mapping_user_email != user.get('email'):
            error = exception.OAuth2InvalidClient(
                int(http.client.UNAUTHORIZED),
                http.client.responses[http.client.UNAUTHORIZED],
                _('Client authentication failed.'))
            LOG.info('Get OAuth2.0 Access Token API: %s check failed. '
                     'DN value: %s, DB value: %s.',
                     'user email', mapping_user_email, user.get('email'))
            raise error
        if (mapping_user_domain_id and
                mapping_user_domain_id != user_domain.get('id')):
            error = exception.OAuth2InvalidClient(
                int(http.client.UNAUTHORIZED),
                http.client.responses[http.client.UNAUTHORIZED],
                _('Client authentication failed.'))
            LOG.info('Get OAuth2.0 Access Token API: %s check failed. '
                     'DN value: %s, DB value: %s.',
                     'user domain id', mapping_user_domain_id,
                     user_domain.get('id'))
            raise error
        if (mapping_user_domain_name and
                mapping_user_domain_name != user_domain.get('name')):
            error = exception.OAuth2InvalidClient(
                int(http.client.UNAUTHORIZED),
                http.client.responses[http.client.UNAUTHORIZED],
                _('Client authentication failed.'))
            LOG.info('Get OAuth2.0 Access Token API: %s check failed. '
                     'DN value: %s, DB value: %s.',
                     'user domain name', mapping_user_domain_name,
                     user_domain.get('name'))
            raise error

    def _tls_client_auth(self, client_id, client_cert):
        """Get an OAuth2.0 certificate-bound Access Token."""
        try:
            cert_subject_dn = utils.get_certificate_subject_dn(client_cert)
        except exception.ValidationError:
            error = exception.OAuth2InvalidClient(
                int(http.client.UNAUTHORIZED),
                http.client.responses[http.client.UNAUTHORIZED],
                _('Client authentication failed.'))
            LOG.info('Get OAuth2.0 Access Token API: '
                     'failed to get the subject DN from the certificate.')
            raise error
        try:
            cert_issuer_dn = utils.get_certificate_issuer_dn(client_cert)
        except exception.ValidationError:
            error = exception.OAuth2InvalidClient(
                int(http.client.UNAUTHORIZED),
                http.client.responses[http.client.UNAUTHORIZED],
                _('Client authentication failed.'))
            LOG.info('Get OAuth2.0 Access Token API: '
                     'failed to get the issuer DN from the certificate.')
            raise error
        client_cert_dn = {}
        for key in cert_subject_dn:
            client_cert_dn['SSL_CLIENT_SUBJECT_DN_%s' %
                           key.upper()] = cert_subject_dn.get(key)
        for key in cert_issuer_dn:
            client_cert_dn['SSL_CLIENT_ISSUER_DN_%s' %
                           key.upper()] = cert_issuer_dn.get(key)

        try:
            user = PROVIDERS.identity_api.get_user(client_id)
        except exception.UserNotFound:
            error = exception.OAuth2InvalidClient(
                int(http.client.UNAUTHORIZED),
                http.client.responses[http.client.UNAUTHORIZED],
                _('Client authentication failed.'))
            LOG.info('Get OAuth2.0 Access Token API: '
                     'the user does not exist. user id: %s.',
                     client_id)
            raise error
        project_id = user.get('default_project_id')
        if not project_id:
            error = exception.OAuth2InvalidClient(
                int(http.client.UNAUTHORIZED),
                http.client.responses[http.client.UNAUTHORIZED],
                _('Client authentication failed.'))
            LOG.info('Get OAuth2.0 Access Token API: '
                     'the user does not have default project. user id: %s.',
                     client_id)
            raise error

        user_domain = PROVIDERS.resource_api.get_domain(
            user.get('domain_id'))
        self._check_mapped_properties(client_cert_dn, user, user_domain)
        thumbprint = utils.get_certificate_thumbprint(client_cert)
        LOG.debug(f'The mTLS certificate thumbprint: {thumbprint}')
        try:
            token = PROVIDERS.token_provider_api.issue_token(
                user_id=client_id,
                method_names=['oauth2_credential'],
                project_id=project_id,
                thumbprint=thumbprint
            )
        except exception.Error as error:
            if error.code == 401:
                error = exception.OAuth2InvalidClient(
                    error.code, error.title,
                    str(error))
            elif error.code == 400:
                error = exception.OAuth2InvalidRequest(
                    error.code, error.title,
                    str(error))
            else:
                error = exception.OAuth2OtherError(
                    error.code, error.title,
                    'An unknown error occurred and failed to get an OAuth2.0 '
                    'access token.')
            LOG.exception(error)
            raise error
        except Exception as error:
            error = exception.OAuth2OtherError(
                int(http.client.INTERNAL_SERVER_ERROR),
                http.client.responses[http.client.INTERNAL_SERVER_ERROR],
                str(error))
            LOG.exception(error)
            raise error

        resp = make_response({
            'access_token': token.id,
            'token_type': 'Bearer',
            'expires_in': CONF.token.expiration
        })
        resp.status = '200 OK'
        return resp


class OSAuth2API(ks_flask.APIBase):
    _name = 'OS-OAUTH2'
    _import_name = __name__
    _api_url_prefix = '/OS-OAUTH2'

    resource_mapping = [
        ks_flask.construct_resource_map(
            resource=AccessTokenResource,
            url='/token',
            rel='token',
            resource_kwargs={},
            resource_relation_func=_build_resource_relation
        )]


APIs = (OSAuth2API,)