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

Feature: optional API Key authentication instead of HMAC #385

Merged
merged 3 commits into from
Mar 10, 2015
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions rd_ui/app/scripts/controllers/query_view.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,10 @@
$scope.queryExecuting = lock;
};

$scope.showApiKey = function() {
alert("API Key for this query:\n" + $scope.query.api_key);
};

$scope.saveQuery = function(options, data) {
if (data) {
data.id = $scope.query.id;
Expand Down
6 changes: 5 additions & 1 deletion rd_ui/app/views/query.html
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,11 @@ <h2>
ng-show="!query.is_archived && query.id != undefined && (isQueryOwner || currentUser.hasPermission('admin'))">
<i class="fa fa-archive" title="Archive Query"></i>
</a>


<button class="btn btn-default btn-sm" ng-show="query.id != undefined" ng-click="showApiKey()">
<i class="fa fa-key" title="Show API Key"></i>
</button>

<div class="modal fade" id="archive-confirmation-modal" tabindex="-1" role="dialog" aria-labelledby="archiveConfirmationModal" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
Expand Down
66 changes: 48 additions & 18 deletions redash/authentication.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
import logging

from flask import request, make_response, redirect, url_for
from flask.ext.login import LoginManager, login_user, current_user
from flask.ext.login import LoginManager, login_user, current_user, logout_user

from redash import models, settings, google_oauth

Expand All @@ -23,9 +23,38 @@ def sign(key, path, expires):
return h.hexdigest()


class HMACAuthentication(object):
@staticmethod
def api_key_authentication():
class Authentication(object):
def verify_authentication(self):
return False

def required(self, fn):
@functools.wraps(fn)
def decorated(*args, **kwargs):
if current_user.is_authenticated() or self.verify_authentication():
return fn(*args, **kwargs)

return make_response(redirect(url_for("login", next=request.url)))

return decorated


class ApiKeyAuthentication(Authentication):
def verify_authentication(self):
api_key = request.args.get('api_key')
query_id = request.view_args.get('query_id', None)

if query_id and api_key:
query = models.Query.get(models.Query.id == query_id)

if query.api_key and api_key == query.api_key:
login_user(models.ApiUser(query.api_key), remember=False)
return True

return False


class HMACAuthentication(Authentication):
def verify_authentication(self):
signature = request.args.get('signature')
expires = float(request.args.get('expires') or 0)
query_id = request.view_args.get('query_id', None)
Expand All @@ -41,22 +70,14 @@ def api_key_authentication():

return False

def required(self, fn):
@functools.wraps(fn)
def decorated(*args, **kwargs):
if current_user.is_authenticated():
return fn(*args, **kwargs)

if self.api_key_authentication():
return fn(*args, **kwargs)

return make_response(redirect(url_for("login", next=request.url)))

return decorated


@login_manager.user_loader
def load_user(user_id):
# If the user was previously logged in as api user, the user_id will be the api key and will raise an exception as
# it can't be casted to int.
if isinstance(user_id, basestring) and not user_id.isdigit():
return None

return models.User.select().where(models.User.id == user_id).first()


Expand All @@ -66,4 +87,13 @@ def setup_authentication(app):
app.secret_key = settings.COOKIE_SECRET
app.register_blueprint(google_oauth.blueprint)

return HMACAuthentication()
if settings.AUTH_TYPE == 'hmac':
auth = HMACAuthentication()
elif settings.AUTH_TYPE == 'api_key':
auth = ApiKeyAuthentication()
else:
logger.warning("Unknown authentication type ({}). Using default (HMAC).".format(settings.AUTH_TYPE))
auth = HMACAuthentication()

return auth

3 changes: 3 additions & 0 deletions redash/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,9 @@ class ApiUser(UserMixin, PermissionsCheckMixin):
def __init__(self, api_key):
self.id = api_key

def __repr__(self):
return u"<ApiUser: {}>".format(self.id)

@property
def permissions(self):
return ['view_query']
Expand Down
2 changes: 2 additions & 0 deletions redash/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,8 @@ def parse_boolean(str):
# proved to be "safe".
QUERY_RESULTS_CLEANUP_ENABLED = parse_boolean(os.environ.get("REDASH_QUERY_RESULTS_CLEANUP_ENABLED", "false"))

AUTH_TYPE = os.environ.get("REDASH_AUTH_TYPE", "hmac")

# Google Apps domain to allow access from; any user with email in this Google Apps will be allowed
# access
GOOGLE_APPS_DOMAIN = os.environ.get("REDASH_GOOGLE_APPS_DOMAIN", "")
Expand Down
39 changes: 38 additions & 1 deletion tests/test_authentication.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,45 @@
from flask.ext.login import current_user
from mock import patch
from tests import BaseTestCase
from redash import models
from redash.google_oauth import create_and_login_user
from tests.factories import user_factory
from redash.authentication import ApiKeyAuthentication
from tests.factories import user_factory, query_factory
from redash.wsgi import app


class TestApiKeyAuthentication(BaseTestCase):
#
# This is a bad way to write these tests, but the way Flask works doesn't make it easy to write them properly...
#
def setUp(self):
super(TestApiKeyAuthentication, self).setUp()
self.api_key = 10
self.query = query_factory.create(api_key=self.api_key)

def test_no_api_key(self):
auth = ApiKeyAuthentication()
with app.test_client() as c:
rv = c.get('/api/queries/{0}'.format(self.query.id))
self.assertFalse(auth.verify_authentication())

def test_wrong_api_key(self):
auth = ApiKeyAuthentication()
with app.test_client() as c:
rv = c.get('/api/queries/{0}'.format(self.query.id), query_string={'api_key': 'whatever'})
self.assertFalse(auth.verify_authentication())

def test_correct_api_key(self):
auth = ApiKeyAuthentication()
with app.test_client() as c:
rv = c.get('/api/queries/{0}'.format(self.query.id), query_string={'api_key': self.api_key})
self.assertTrue(auth.verify_authentication())

def test_no_query_id(self):
auth = ApiKeyAuthentication()
with app.test_client() as c:
rv = c.get('/api/queries', query_string={'api_key': self.api_key})
self.assertFalse(auth.verify_authentication())


class TestCreateAndLoginUser(BaseTestCase):
Expand Down