Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add keystone auth backend #1732

Merged
merged 11 commits into from
Jul 21, 2015
100 changes: 100 additions & 0 deletions st2auth/st2auth/backends/keystone.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
# Licensed to the StackStorm, Inc ('StackStorm') under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You 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 st2common import log as logging
from st2auth.backends.base import BaseAuthenticationBackend
import requests

try:
from urlparse import urlparse
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We depend on six so you can instead use:

from six.moves.urllib import parse as urlparse
from six.moves.urllib.parse import urljoin

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

IDD! Much easier!

from urlparse import urljoin
except ImportError:
from urllib.parse import urlparse # pylint: disable=E0611
from urllib.parse import urljoin # pylint: disable=E0611

__all__ = [
'KeystoneAuthenticationBackend'
]

LOG = logging.getLogger(__name__)


class KeystoneAuthenticationBackend(BaseAuthenticationBackend):
"""
Backend which reads authentication information from keystone

Note: This backend depends on the "requests" library.
"""

def __init__(self, keystone_url, keystone_version=2):
"""
:param keystone_url: Url of the Keystone server to authenticate against.
:type keystone_url: ``str``
:param keystone_version: Keystone version to authenticate against (default to 2).
:type keystone_version: ``int``
"""
url = urlparse(keystone_url)
if url.path != '' or url.query != '' or url.fragment != '':
raise Exception("The Keystone url {} does not seem to be correct.\n"
"Please only set the scheme+url+port "
"(e.x.: http://example.com:5000)".format(keystone_url))
self._keystone_url = keystone_url
self._keystone_version = keystone_version
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks like this argument is unused and we only support v2 right now?

If so, we should make that clear and throw if an unsupported version is provided.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

On a related note, it might be better to just use python-keystoneclient.

Ideally, eventually we would also switch to using setup.py entry_points for plugins and provide plugins as separate Python packages with it's own requirements.txt file, but for now I'm OK with putting keystone-client dependency to the shared requirements.txt file.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actually, Im doing the v2/v3 split now and some other checks. I wanted the PR to go up quick due to the testing question.

Re: keystone client. Totally against that tbh. It turns a simple authentication plugin with one dependency into dependency hell and also ties into a big external projects, while requests is one package with minimal dependencies and probably already installed on every decent python env which needs to do a network call.

And this auth backend just needs to do one simple call. To have keystoneclient as dependency is overkill IMO.


def authenticate(self, username, password):
if self._keystone_version == 2:
creds = {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Heh. _get_v2_creds() and _get_v3_creds() would have been nicer ;)

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed :)

"auth": {
"passwordCredentials": {
"username": username,
"password": password
}
}
}
login = requests.post(urljoin(self._keystone_url, 'v2.0/tokens'), json=creds)

elif self._keystone_version == 3:
creds = {
"auth": {
"identity": {
"methods": [
"password"
],
"password": {
"domain": {
"id": "default"
},
"user": {
"name": username,
"password": password
}
}
}
}
}
login = requests.post(urljoin(self._keystone_url, 'v3/auth/tokens'), json=creds)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just curious, is it v3.0 or just v3? I see v2.0 for the version 2 APIs :). <3 to openstack.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just v3. Its the openstack way (tm) of never agreeing to use the same thing from release to release :D

else:
raise Exception("Keystone version {} not supported".format(self._keystone_version))

if login.status_code in [200, 201]:
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor style thing - httlib.OK, httplib.CREATED :)

LOG.debug('Authentication for user "{}" successful'.format(username))
return True
else:
LOG.debug('Authentication for user "{}" failed: {}'.format(username, login.content))
return False

def get_user(self, username):
pass
29 changes: 29 additions & 0 deletions st2auth/tests/unit/test_auth_backends.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,15 @@
import os

import unittest2
import mock
from requests.models import Response

from st2tests.config import parse_args
parse_args()

from st2auth.backends.flat_file import FlatFileAuthenticationBackend
from st2auth.backends.mongodb import MongoDBAuthenticationBackend
from st2auth.backends.keystone import KeystoneAuthenticationBackend

BASE_DIR = os.path.dirname(os.path.abspath(__file__))

Expand Down Expand Up @@ -80,3 +83,29 @@ def test_authenticate(self):

# Valid password
self.assertTrue(self._backend.authenticate(username='test1', password='testpassword'))


class KeystoneAuthenticationBackendTestCase(unittest2.TestCase):
def _mock_keystone(self, *args, **kwargs):
return_codes = {'goodv2': 200, 'goodv3': 201, 'bad': 400}
json = kwargs.get('json')
res = Response()
try:
# v2
res.status_code = return_codes[json['auth']['passwordCredentials']['user']]
except KeyError:
# v3
res.status_code = return_codes[json['auth']['identity']['password']['user']['name']]
return res

@mock.patch('requests.post', side_effect=_mock_keystone)
def test_authenticate(self):
backendv2 = KeystoneAuthenticationBackend(keystone_url="http://fake.com:5000", version=2)
backendv3 = KeystoneAuthenticationBackend(keystone_url="http://fake.com:5000", version=3)

# good users
self.assertTrue(backendv2.authenticate('goodv2', 'password'))
self.assertTrue(backendv3.authenticate('goodv3', 'password'))
# bad ones
self.assertFalse(backendv2.authenticate('bad', 'password'))
self.assertFalse(backendv3.authenticate('bad', 'password'))