1
# vim: tabstop=4 shiftwidth=4 softtabstop=4
3
# Copyright 2012 OpenStack LLC
5
# Licensed under the Apache License, Version 2.0 (the "License"); you may
6
# not use this file except in compliance with the License. You may obtain
7
# a copy of the License at
9
# http://www.apache.org/licenses/LICENSE-2.0
11
# Unless required by applicable law or agreed to in writing, software
12
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
13
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
14
# License for the specific language governing permissions and limitations
17
"""Main entry point into the EC2 Credentials service.
19
This service allows the creation of access/secret credentials used for
20
the ec2 interop layer of OpenStack.
22
A user can create as many access/secret pairs, each of which map to a
23
specific tenant. This is required because OpenStack supports a user
24
belonging to multiple tenants, whereas the signatures created on ec2-style
25
requests don't allow specification of which tenant the user wishs to act
28
To complete the cycle, we provide a method that OpenStack services can
29
use to validate a signature and get a corresponding openstack token. This
30
token allows method calls to other services within the context the
31
access/secret was created. As an example, nova requests keystone to validate
32
the signature of a request, receives a token, and then makes a request to
33
glance to list images needed to perform the requested task.
39
from keystone import catalog
40
from keystone.common import manager
41
from keystone.common import utils
42
from keystone.common import wsgi
43
from keystone import config
44
from keystone import exception
45
from keystone import identity
46
from keystone import policy
47
from keystone import service
48
from keystone import token
54
class Manager(manager.Manager):
55
"""Default pivot point for the EC2 Credentials backend.
57
See :mod:`keystone.common.manager.Manager` for more details on how this
58
dynamically calls the backend.
63
super(Manager, self).__init__(CONF.ec2.driver)
66
class Ec2Extension(wsgi.ExtensionRouter):
67
def add_routes(self, mapper):
68
ec2_controller = Ec2Controller()
72
controller=ec2_controller,
73
action='authenticate',
74
conditions=dict(method=['POST']))
78
'/users/{user_id}/credentials/OS-EC2',
79
controller=ec2_controller,
80
action='create_credential',
81
conditions=dict(method=['POST']))
83
'/users/{user_id}/credentials/OS-EC2',
84
controller=ec2_controller,
85
action='get_credentials',
86
conditions=dict(method=['GET']))
88
'/users/{user_id}/credentials/OS-EC2/{credential_id}',
89
controller=ec2_controller,
90
action='get_credential',
91
conditions=dict(method=['GET']))
93
'/users/{user_id}/credentials/OS-EC2/{credential_id}',
94
controller=ec2_controller,
95
action='delete_credential',
96
conditions=dict(method=['DELETE']))
99
class Ec2Controller(wsgi.Application):
101
self.catalog_api = catalog.Manager()
102
self.identity_api = identity.Manager()
103
self.token_api = token.Manager()
104
self.policy_api = policy.Manager()
105
self.ec2_api = Manager()
106
super(Ec2Controller, self).__init__()
108
def check_signature(self, creds_ref, credentials):
109
signer = utils.Ec2Signer(creds_ref['secret'])
110
signature = signer.generate(credentials)
111
if utils.auth_str_equal(credentials['signature'], signature):
113
# NOTE(vish): Some libraries don't use the port when signing
114
# requests, so try again without port.
115
elif ':' in credentials['signature']:
116
hostname, _port = credentials['host'].split(':')
117
credentials['host'] = hostname
118
signature = signer.generate(credentials)
119
if not utils.auth_str_equal(credentials.signature, signature):
120
raise exception.Unauthorized(message='Invalid EC2 signature.')
122
raise exception.Unauthorized(message='EC2 signature not supplied.')
124
def authenticate(self, context, credentials=None, ec2Credentials=None):
125
"""Validate a signed EC2 request and provide a token.
127
Other services (such as Nova) use this **admin** call to determine
128
if a request they signed received is from a valid user.
130
If it is a valid signature, an openstack token that maps
131
to the user/tenant is returned to the caller, along with
132
all the other details returned from a normal token validation
135
The returned token is useful for making calls to other
136
OpenStack services within the context of the request.
138
:param context: standard context
139
:param credentials: dict of ec2 signature
140
:param ec2Credentials: DEPRECATED dict of ec2 signature
141
:returns: token: openstack token equivalent to access key along
142
with the corresponding service catalog and roles
145
# FIXME(ja): validate that a service token was used!
147
# NOTE(termie): backwards compat hack
148
if not credentials and ec2Credentials:
149
credentials = ec2Credentials
151
if not 'access' in credentials:
152
raise exception.Unauthorized(message='EC2 signature not supplied.')
154
creds_ref = self._get_credentials(context,
155
credentials['access'])
156
self.check_signature(creds_ref, credentials)
158
# TODO(termie): don't create new tokens every time
159
# TODO(termie): this is copied from TokenController.authenticate
160
token_id = uuid.uuid4().hex
161
tenant_ref = self.identity_api.get_tenant(
163
tenant_id=creds_ref['tenant_id'])
164
user_ref = self.identity_api.get_user(
166
user_id=creds_ref['user_id'])
167
metadata_ref = self.identity_api.get_metadata(
169
user_id=user_ref['id'],
170
tenant_id=tenant_ref['id'])
172
# TODO(termie): optimize this call at some point and put it into the
173
# the return for metadata
174
# fill out the roles in the metadata
175
roles = metadata_ref.get('roles', [])
177
raise exception.Unauthorized(message='User not valid for tenant.')
178
roles_ref = [self.identity_api.get_role(context, role_id)
179
for role_id in roles]
181
catalog_ref = self.catalog_api.get_catalog(
183
user_id=user_ref['id'],
184
tenant_id=tenant_ref['id'],
185
metadata=metadata_ref)
187
token_ref = self.token_api.create_token(
188
context, token_id, dict(id=token_id,
191
metadata=metadata_ref))
193
# TODO(termie): make this a util function or something
194
# TODO(termie): i don't think the ec2 middleware currently expects a
195
# full return, but it contains a note saying that it
196
# would be better to expect a full return
197
token_controller = service.TokenController()
198
return token_controller._format_authenticate(
199
token_ref, roles_ref, catalog_ref)
201
def create_credential(self, context, user_id, tenant_id):
202
"""Create a secret/access pair for use with ec2 style auth.
204
Generates a new set of credentials that map the the user/tenant
207
:param context: standard context
208
:param user_id: id of user
209
:param tenant_id: id of tenant
210
:returns: credential: dict of ec2 credential
212
if not self._is_admin(context):
213
self._assert_identity(context, user_id)
215
self._assert_valid_user_id(context, user_id)
216
self._assert_valid_tenant_id(context, tenant_id)
218
cred_ref = {'user_id': user_id,
219
'tenant_id': tenant_id,
220
'access': uuid.uuid4().hex,
221
'secret': uuid.uuid4().hex}
222
self.ec2_api.create_credential(context, cred_ref['access'], cred_ref)
223
return {'credential': cred_ref}
225
def get_credentials(self, context, user_id):
226
"""List all credentials for a user.
228
:param context: standard context
229
:param user_id: id of user
230
:returns: credentials: list of ec2 credential dicts
232
if not self._is_admin(context):
233
self._assert_identity(context, user_id)
234
self._assert_valid_user_id(context, user_id)
235
return {'credentials': self.ec2_api.list_credentials(context, user_id)}
237
def get_credential(self, context, user_id, credential_id):
238
"""Retreive a user's access/secret pair by the access key.
240
Grab the full access/secret pair for a given access key.
242
:param context: standard context
243
:param user_id: id of user
244
:param credential_id: access key for credentials
245
:returns: credential: dict of ec2 credential
247
if not self._is_admin(context):
248
self._assert_identity(context, user_id)
249
self._assert_valid_user_id(context, user_id)
250
creds = self._get_credentials(context, credential_id)
251
return {'credential': creds}
253
def delete_credential(self, context, user_id, credential_id):
254
"""Delete a user's access/secret pair.
256
Used to revoke a user's access/secret pair
258
:param context: standard context
259
:param user_id: id of user
260
:param credential_id: access key for credentials
261
:returns: bool: success
263
if not self._is_admin(context):
264
self._assert_identity(context, user_id)
265
self._assert_owner(context, user_id, credential_id)
267
self._assert_valid_user_id(context, user_id)
268
self._get_credentials(context, credential_id)
269
return self.ec2_api.delete_credential(context, credential_id)
271
def _get_credentials(self, context, credential_id):
272
"""Return credentials from an ID.
274
:param context: standard context
275
:param credential_id: id of credential
276
:raises exception.Unauthorized: when credential id is invalid
277
:returns: credential: dict of ec2 credential.
279
creds = self.ec2_api.get_credential(context,
282
raise exception.Unauthorized(message='EC2 access key not found.')
285
def _assert_identity(self, context, user_id):
286
"""Check that the provided token belongs to the user.
288
:param context: standard context
289
:param user_id: id of user
290
:raises exception.Forbidden: when token is invalid
294
token_ref = self.token_api.get_token(
296
token_id=context['token_id'])
297
except exception.TokenNotFound:
298
raise exception.Unauthorized()
299
token_user_id = token_ref['user'].get('id')
300
if not token_user_id == user_id:
301
raise exception.Forbidden()
303
def _is_admin(self, context):
304
"""Wrap admin assertion error return statement.
306
:param context: standard context
307
:returns: bool: success
311
self.assert_admin(context)
313
except exception.Forbidden:
316
def _assert_owner(self, context, user_id, credential_id):
317
"""Ensure the provided user owns the credential.
319
:param context: standard context
320
:param user_id: expected credential owner
321
:param credential_id: id of credential object
322
:raises exception.Forbidden: on failure
325
cred_ref = self.ec2_api.get_credential(context, credential_id)
326
if not user_id == cred_ref['user_id']:
327
raise exception.Forbidden()
329
def _assert_valid_user_id(self, context, user_id):
330
"""Ensure a valid user id.
332
:param context: standard context
333
:param user_id: expected credential owner
334
:raises exception.UserNotFound: on failure
337
user_ref = self.identity_api.get_user(
341
raise exception.UserNotFound(user_id=user_id)
343
def _assert_valid_tenant_id(self, context, tenant_id):
344
"""Ensure a valid tenant id.
346
:param context: standard context
347
:param user_id: expected credential owner
348
:raises exception.UserNotFound: on failure
351
tenant_ref = self.identity_api.get_tenant(
355
raise exception.TenantNotFound(tenant_id=tenant_id)