diff --git a/awx/main/middleware.py b/awx/main/middleware.py index 5a79aa54a5..1ec6ab8129 100644 --- a/awx/main/middleware.py +++ b/awx/main/middleware.py @@ -1,6 +1,8 @@ # Copyright (c) 2015 Ansible, Inc. # All Rights Reserved. +import base64 +import json import logging import threading import uuid @@ -9,12 +11,15 @@ import time import cProfile import pstats import os +import re from django.conf import settings from django.contrib.auth.models import User +from django.core.exceptions import ObjectDoesNotExist from django.db.models.signals import post_save from django.db.migrations.executor import MigrationExecutor from django.db import IntegrityError, connection +from django.http import HttpResponse from django.utils.functional import curry from django.shortcuts import get_object_or_404, redirect from django.apps import apps @@ -204,6 +209,56 @@ class URLModificationMiddleware(object): request.path_info = new_path +class DeprecatedAuthTokenMiddleware(object): + """ + Used to emulate support for the old Auth Token endpoint to ease the + transition to OAuth2.0. Specifically, this middleware: + + 1. Intercepts POST requests to `/api/v2/authtoken/` (which now no longer + _actually_ exists in our urls.py) + 2. Rewrites `request.path` to `/api/v2/users/N/personal_tokens/` + 3. Detects the username and password in the request body (either in JSON, + or form-encoded variables) and builds an appropriate HTTP_AUTHORIZATION + Bearer header + """ + + def process_request(self, request): + if re.match('^/api/v[12]/authtoken/?$', request.path): + if request.method != 'POST': + return HttpResponse('HTTP {} is not allowed.'.format(request.method), status=405) + try: + payload = json.loads(request.body) + except (ValueError, TypeError): + payload = request.POST + if 'username' not in payload or 'password' not in payload: + return HttpResponse('Unable to login with provided credentials.', status=401) + username = payload['username'] + password = payload['password'] + try: + pk = User.objects.get(username=username).pk + except ObjectDoesNotExist: + return HttpResponse('Unable to login with provided credentials.', status=401) + new_path = reverse('api:user_personal_token_list', kwargs={ + 'pk': pk, + 'version': 'v2' + }) + request._body = '' + request.META['CONTENT_TYPE'] = 'application/json' + request.path = request.path_info = new_path + auth = ' '.join([ + 'Basic', + base64.b64encode( + six.text_type('{}:{}').format(username, password) + ) + ]) + request.environ['HTTP_AUTHORIZATION'] = auth + logger.warn( + 'The Auth Token API (/api/v2/authtoken/) is deprecated and will ' + 'be replaced with OAuth2.0 in the next version of Ansible Tower ' + '(see /api/o/ for more details).' + ) + + class MigrationRanCheckMiddleware(object): def process_request(self, request): diff --git a/awx/main/tests/functional/api/test_oauth.py b/awx/main/tests/functional/api/test_oauth.py index ad24ecadfb..b497a7d45f 100644 --- a/awx/main/tests/functional/api/test_oauth.py +++ b/awx/main/tests/functional/api/test_oauth.py @@ -5,7 +5,10 @@ import json from django.db import connection from django.test.utils import override_settings from django.test import Client +from django.core.urlresolvers import resolve +from rest_framework.test import APIRequestFactory +from awx.main.middleware import DeprecatedAuthTokenMiddleware from awx.main.utils.encryption import decrypt_value, get_encryption_key from awx.api.versioning import reverse, drf_reverse from awx.main.models.oauth import (OAuth2Application as Application, @@ -358,3 +361,43 @@ def test_revoke_refreshtoken(oauth_application, post, get, delete, admin): new_refresh_token = RefreshToken.objects.all().first() assert refresh_token == new_refresh_token assert new_refresh_token.revoked + + +@pytest.mark.django_db +@pytest.mark.parametrize('fmt', ['json', 'multipart']) +def test_deprecated_authtoken_support(alice, fmt): + kwargs = { + 'data': {'username': 'alice', 'password': 'alice'}, + 'format': fmt + } + request = getattr(APIRequestFactory(), 'post')('/api/v2/authtoken/', **kwargs) + DeprecatedAuthTokenMiddleware().process_request(request) + assert request.path == request.path_info == '/api/v2/users/{}/personal_tokens/'.format(alice.pk) + view, view_args, view_kwargs = resolve(request.path) + resp = view(request, *view_args, **view_kwargs) + assert resp.status_code == 201 + assert 'token' in resp.data + assert resp.data['refresh_token'] is None + assert resp.data['scope'] == 'write' + + +@pytest.mark.django_db +def test_deprecated_authtoken_invalid_username(alice): + kwargs = { + 'data': {'username': 'nobody', 'password': 'nobody'}, + 'format': 'json' + } + request = getattr(APIRequestFactory(), 'post')('/api/v2/authtoken/', **kwargs) + resp = DeprecatedAuthTokenMiddleware().process_request(request) + assert resp.status_code == 401 + + +@pytest.mark.django_db +def test_deprecated_authtoken_missing_credentials(alice): + kwargs = { + 'data': {}, + 'format': 'json' + } + request = getattr(APIRequestFactory(), 'post')('/api/v2/authtoken/', **kwargs) + resp = DeprecatedAuthTokenMiddleware().process_request(request) + assert resp.status_code == 401 diff --git a/awx/settings/defaults.py b/awx/settings/defaults.py index 926e47ebe8..1939d323d0 100644 --- a/awx/settings/defaults.py +++ b/awx/settings/defaults.py @@ -261,6 +261,7 @@ MIDDLEWARE_CLASSES = ( # NOQA 'awx.sso.middleware.SocialAuthMiddleware', 'crum.CurrentRequestUserMiddleware', 'awx.main.middleware.URLModificationMiddleware', + 'awx.main.middleware.DeprecatedAuthTokenMiddleware', 'awx.main.middleware.SessionTimeoutMiddleware', )