From b8c756ecdd7cced1db4300935484e8c83701c82e Mon Sep 17 00:00:00 2001 From: WuKong Date: Tue, 30 Jun 2015 18:47:29 +0200 Subject: migrate moon code from github to opnfv Change-Id: Ice53e368fd1114d56a75271aa9f2e598e3eba604 Signed-off-by: WuKong --- keystone-moon/keystone/credential/__init__.py | 17 +++ .../keystone/credential/backends/__init__.py | 0 keystone-moon/keystone/credential/backends/sql.py | 104 +++++++++++++++ keystone-moon/keystone/credential/controllers.py | 108 ++++++++++++++++ keystone-moon/keystone/credential/core.py | 140 +++++++++++++++++++++ keystone-moon/keystone/credential/routers.py | 28 +++++ keystone-moon/keystone/credential/schema.py | 62 +++++++++ 7 files changed, 459 insertions(+) create mode 100644 keystone-moon/keystone/credential/__init__.py create mode 100644 keystone-moon/keystone/credential/backends/__init__.py create mode 100644 keystone-moon/keystone/credential/backends/sql.py create mode 100644 keystone-moon/keystone/credential/controllers.py create mode 100644 keystone-moon/keystone/credential/core.py create mode 100644 keystone-moon/keystone/credential/routers.py create mode 100644 keystone-moon/keystone/credential/schema.py (limited to 'keystone-moon/keystone/credential') diff --git a/keystone-moon/keystone/credential/__init__.py b/keystone-moon/keystone/credential/__init__.py new file mode 100644 index 00000000..fc7b6317 --- /dev/null +++ b/keystone-moon/keystone/credential/__init__.py @@ -0,0 +1,17 @@ +# Copyright 2013 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. + +from keystone.credential import controllers # noqa +from keystone.credential.core import * # noqa +from keystone.credential import routers # noqa diff --git a/keystone-moon/keystone/credential/backends/__init__.py b/keystone-moon/keystone/credential/backends/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/keystone-moon/keystone/credential/backends/sql.py b/keystone-moon/keystone/credential/backends/sql.py new file mode 100644 index 00000000..12daed3f --- /dev/null +++ b/keystone-moon/keystone/credential/backends/sql.py @@ -0,0 +1,104 @@ +# Copyright 2013 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. + +from keystone.common import sql +from keystone import credential +from keystone import exception + + +class CredentialModel(sql.ModelBase, sql.DictBase): + __tablename__ = 'credential' + attributes = ['id', 'user_id', 'project_id', 'blob', 'type'] + id = sql.Column(sql.String(64), primary_key=True) + user_id = sql.Column(sql.String(64), + nullable=False) + project_id = sql.Column(sql.String(64)) + blob = sql.Column(sql.JsonBlob(), nullable=False) + type = sql.Column(sql.String(255), nullable=False) + extra = sql.Column(sql.JsonBlob()) + + +class Credential(credential.Driver): + + # credential crud + + @sql.handle_conflicts(conflict_type='credential') + def create_credential(self, credential_id, credential): + session = sql.get_session() + with session.begin(): + ref = CredentialModel.from_dict(credential) + session.add(ref) + return ref.to_dict() + + @sql.truncated + def list_credentials(self, hints): + session = sql.get_session() + credentials = session.query(CredentialModel) + credentials = sql.filter_limit_query(CredentialModel, + credentials, hints) + return [s.to_dict() for s in credentials] + + def list_credentials_for_user(self, user_id): + session = sql.get_session() + query = session.query(CredentialModel) + refs = query.filter_by(user_id=user_id).all() + return [ref.to_dict() for ref in refs] + + def _get_credential(self, session, credential_id): + ref = session.query(CredentialModel).get(credential_id) + if ref is None: + raise exception.CredentialNotFound(credential_id=credential_id) + return ref + + def get_credential(self, credential_id): + session = sql.get_session() + return self._get_credential(session, credential_id).to_dict() + + @sql.handle_conflicts(conflict_type='credential') + def update_credential(self, credential_id, credential): + session = sql.get_session() + with session.begin(): + ref = self._get_credential(session, credential_id) + old_dict = ref.to_dict() + for k in credential: + old_dict[k] = credential[k] + new_credential = CredentialModel.from_dict(old_dict) + for attr in CredentialModel.attributes: + if attr != 'id': + setattr(ref, attr, getattr(new_credential, attr)) + ref.extra = new_credential.extra + return ref.to_dict() + + def delete_credential(self, credential_id): + session = sql.get_session() + + with session.begin(): + ref = self._get_credential(session, credential_id) + session.delete(ref) + + def delete_credentials_for_project(self, project_id): + session = sql.get_session() + + with session.begin(): + query = session.query(CredentialModel) + query = query.filter_by(project_id=project_id) + query.delete() + + def delete_credentials_for_user(self, user_id): + session = sql.get_session() + + with session.begin(): + query = session.query(CredentialModel) + query = query.filter_by(user_id=user_id) + query.delete() diff --git a/keystone-moon/keystone/credential/controllers.py b/keystone-moon/keystone/credential/controllers.py new file mode 100644 index 00000000..65c17278 --- /dev/null +++ b/keystone-moon/keystone/credential/controllers.py @@ -0,0 +1,108 @@ +# Copyright 2013 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 hashlib + +from oslo_serialization import jsonutils + +from keystone.common import controller +from keystone.common import dependency +from keystone.common import validation +from keystone.credential import schema +from keystone import exception +from keystone.i18n import _ + + +@dependency.requires('credential_api') +class CredentialV3(controller.V3Controller): + collection_name = 'credentials' + member_name = 'credential' + + def __init__(self): + super(CredentialV3, self).__init__() + self.get_member_from_driver = self.credential_api.get_credential + + def _assign_unique_id(self, ref, trust_id=None): + # Generates and assigns a unique identifier to + # a credential reference. + if ref.get('type', '').lower() == 'ec2': + try: + blob = jsonutils.loads(ref.get('blob')) + except (ValueError, TypeError): + raise exception.ValidationError( + message=_('Invalid blob in credential')) + if not blob or not isinstance(blob, dict): + raise exception.ValidationError(attribute='blob', + target='credential') + if blob.get('access') is None: + raise exception.ValidationError(attribute='access', + target='blob') + ret_ref = ref.copy() + ret_ref['id'] = hashlib.sha256(blob['access']).hexdigest() + # Update the blob with the trust_id, so credentials created + # with a trust scoped token will result in trust scoped + # tokens when authentication via ec2tokens happens + if trust_id is not None: + blob['trust_id'] = trust_id + ret_ref['blob'] = jsonutils.dumps(blob) + return ret_ref + else: + return super(CredentialV3, self)._assign_unique_id(ref) + + @controller.protected() + @validation.validated(schema.credential_create, 'credential') + def create_credential(self, context, credential): + trust_id = self._get_trust_id_for_request(context) + ref = self._assign_unique_id(self._normalize_dict(credential), + trust_id) + ref = self.credential_api.create_credential(ref['id'], ref) + return CredentialV3.wrap_member(context, ref) + + @staticmethod + def _blob_to_json(ref): + # credentials stored via ec2tokens before the fix for #1259584 + # need json serializing, as that's the documented API format + blob = ref.get('blob') + if isinstance(blob, dict): + new_ref = ref.copy() + new_ref['blob'] = jsonutils.dumps(blob) + return new_ref + else: + return ref + + @controller.filterprotected('user_id') + def list_credentials(self, context, filters): + hints = CredentialV3.build_driver_hints(context, filters) + refs = self.credential_api.list_credentials(hints) + ret_refs = [self._blob_to_json(r) for r in refs] + return CredentialV3.wrap_collection(context, ret_refs, + hints=hints) + + @controller.protected() + def get_credential(self, context, credential_id): + ref = self.credential_api.get_credential(credential_id) + ret_ref = self._blob_to_json(ref) + return CredentialV3.wrap_member(context, ret_ref) + + @controller.protected() + @validation.validated(schema.credential_update, 'credential') + def update_credential(self, context, credential_id, credential): + self._require_matching_id(credential_id, credential) + + ref = self.credential_api.update_credential(credential_id, credential) + return CredentialV3.wrap_member(context, ref) + + @controller.protected() + def delete_credential(self, context, credential_id): + return self.credential_api.delete_credential(credential_id) diff --git a/keystone-moon/keystone/credential/core.py b/keystone-moon/keystone/credential/core.py new file mode 100644 index 00000000..d3354ea3 --- /dev/null +++ b/keystone-moon/keystone/credential/core.py @@ -0,0 +1,140 @@ +# Copyright 2013 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. + +"""Main entry point into the Credentials service.""" + +import abc + +from oslo_config import cfg +from oslo_log import log +import six + +from keystone.common import dependency +from keystone.common import driver_hints +from keystone.common import manager +from keystone import exception + + +CONF = cfg.CONF + +LOG = log.getLogger(__name__) + + +@dependency.provider('credential_api') +class Manager(manager.Manager): + """Default pivot point for the Credential 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.credential.driver) + + @manager.response_truncated + def list_credentials(self, hints=None): + return self.driver.list_credentials(hints or driver_hints.Hints()) + + +@six.add_metaclass(abc.ABCMeta) +class Driver(object): + # credential crud + + @abc.abstractmethod + def create_credential(self, credential_id, credential): + """Creates a new credential. + + :raises: keystone.exception.Conflict + + """ + raise exception.NotImplemented() # pragma: no cover + + @abc.abstractmethod + def list_credentials(self, hints): + """List all credentials. + + :param hints: contains the list of filters yet to be satisfied. + Any filters satisfied here will be removed so that + the caller will know if any filters remain. + + :returns: a list of credential_refs or an empty list. + + """ + raise exception.NotImplemented() # pragma: no cover + + @abc.abstractmethod + def list_credentials_for_user(self, user_id): + """List credentials for a user. + + :param user_id: ID of a user to filter credentials by. + + :returns: a list of credential_refs or an empty list. + + """ + raise exception.NotImplemented() # pragma: no cover + + @abc.abstractmethod + def get_credential(self, credential_id): + """Get a credential by ID. + + :returns: credential_ref + :raises: keystone.exception.CredentialNotFound + + """ + raise exception.NotImplemented() # pragma: no cover + + @abc.abstractmethod + def update_credential(self, credential_id, credential): + """Updates an existing credential. + + :raises: keystone.exception.CredentialNotFound, + keystone.exception.Conflict + + """ + raise exception.NotImplemented() # pragma: no cover + + @abc.abstractmethod + def delete_credential(self, credential_id): + """Deletes an existing credential. + + :raises: keystone.exception.CredentialNotFound + + """ + raise exception.NotImplemented() # pragma: no cover + + @abc.abstractmethod + def delete_credentials_for_project(self, project_id): + """Deletes all credentials for a project.""" + self._delete_credentials(lambda cr: cr['project_id'] == project_id) + + @abc.abstractmethod + def delete_credentials_for_user(self, user_id): + """Deletes all credentials for a user.""" + self._delete_credentials(lambda cr: cr['user_id'] == user_id) + + def _delete_credentials(self, match_fn): + """Do the actual credential deletion work (default implementation). + + :param match_fn: function that takes a credential dict as the + parameter and returns true or false if the + identifier matches the credential dict. + """ + for cr in self.list_credentials(): + if match_fn(cr): + try: + self.credential_api.delete_credential(cr['id']) + except exception.CredentialNotFound: + LOG.debug('Deletion of credential is not required: %s', + cr['id']) diff --git a/keystone-moon/keystone/credential/routers.py b/keystone-moon/keystone/credential/routers.py new file mode 100644 index 00000000..db3651f4 --- /dev/null +++ b/keystone-moon/keystone/credential/routers.py @@ -0,0 +1,28 @@ +# Copyright 2013 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. + +"""WSGI Routers for the Credentials service.""" + +from keystone.common import router +from keystone.common import wsgi +from keystone.credential import controllers + + +class Routers(wsgi.RoutersBase): + + def append_v3_routers(self, mapper, routers): + routers.append( + router.Router(controllers.CredentialV3(), + 'credentials', 'credential', + resource_descriptions=self.v3_resources)) diff --git a/keystone-moon/keystone/credential/schema.py b/keystone-moon/keystone/credential/schema.py new file mode 100644 index 00000000..749f0c0a --- /dev/null +++ b/keystone-moon/keystone/credential/schema.py @@ -0,0 +1,62 @@ +# 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. + + +_credential_properties = { + 'blob': { + 'type': 'string' + }, + 'project_id': { + 'type': 'string' + }, + 'type': { + 'type': 'string' + }, + 'user_id': { + 'type': 'string' + } +} + +credential_create = { + 'type': 'object', + 'properties': _credential_properties, + 'additionalProperties': True, + 'oneOf': [ + { + 'title': 'ec2 credential requires project_id', + 'required': ['blob', 'type', 'user_id', 'project_id'], + 'properties': { + 'type': { + 'enum': ['ec2'] + } + } + }, + { + 'title': 'non-ec2 credential does not require project_id', + 'required': ['blob', 'type', 'user_id'], + 'properties': { + 'type': { + 'not': { + 'enum': ['ec2'] + } + } + } + } + ] +} + +credential_update = { + 'type': 'object', + 'properties': _credential_properties, + 'minProperties': 1, + 'additionalProperties': True +} -- cgit 1.2.3-korg