From 28512e042b4dfe16ef75d39aea79f2d82459b3a9 Mon Sep 17 00:00:00 2001 From: Ryan Petrello Date: Fri, 26 Oct 2018 10:02:43 -0400 Subject: [PATCH] remove DeprecatedAuthTokenMiddleware --- awx/main/middleware.py | 60 +-------------------- awx/main/tests/functional/api/test_oauth.py | 52 ------------------ awx/settings/defaults.py | 1 - 3 files changed, 1 insertion(+), 112 deletions(-) diff --git a/awx/main/middleware.py b/awx/main/middleware.py index fb681639b5..1005e9982f 100644 --- a/awx/main/middleware.py +++ b/awx/main/middleware.py @@ -1,25 +1,20 @@ # Copyright (c) 2015 Ansible, Inc. # All Rights Reserved. -import base64 -import json +import uuid import logging import threading -import uuid import six 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 @@ -209,59 +204,6 @@ 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 - Basic 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).' - ) - elif request.environ.get('HTTP_AUTHORIZATION', '').startswith('Token '): - token = request.environ['HTTP_AUTHORIZATION'].split(' ', 1)[-1].strip() - request.environ['HTTP_AUTHORIZATION'] = six.text_type('Bearer {}').format(token) - - 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 dc7de68fd7..ad24ecadfb 100644 --- a/awx/main/tests/functional/api/test_oauth.py +++ b/awx/main/tests/functional/api/test_oauth.py @@ -5,10 +5,7 @@ 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, @@ -361,52 +358,3 @@ 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' - - for _type in ('Token', 'Bearer'): - request = getattr(APIRequestFactory(), 'get')( - '/api/v2/me/', - HTTP_AUTHORIZATION=' '.join([_type, resp.data['token']]) - ) - DeprecatedAuthTokenMiddleware().process_request(request) - view, view_args, view_kwargs = resolve(request.path) - assert view(request, *view_args, **view_kwargs).status_code == 200 - - -@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 ac347c43c2..4d875acc29 100644 --- a/awx/settings/defaults.py +++ b/awx/settings/defaults.py @@ -262,7 +262,6 @@ MIDDLEWARE_CLASSES = ( # NOQA 'awx.sso.middleware.SocialAuthMiddleware', 'crum.CurrentRequestUserMiddleware', 'awx.main.middleware.URLModificationMiddleware', - 'awx.main.middleware.DeprecatedAuthTokenMiddleware', 'awx.main.middleware.SessionTimeoutMiddleware', )