|
| 1 | +from __future__ import unicode_literals |
| 2 | + |
| 3 | +import calendar |
| 4 | +import datetime |
| 5 | + |
| 6 | +from django.conf.urls import include, url |
| 7 | +from django.contrib.auth import get_user_model |
| 8 | +from django.http import HttpResponse |
| 9 | +from django.test import override_settings, TestCase |
| 10 | +from django.utils import timezone |
| 11 | +from oauthlib.common import Request |
| 12 | + |
| 13 | +from oauth2_provider.models import get_access_token_model, get_application_model |
| 14 | +from oauth2_provider.oauth2_validators import OAuth2Validator |
| 15 | +from oauth2_provider.settings import oauth2_settings |
| 16 | +from oauth2_provider.views import ScopedProtectedResourceView |
| 17 | + |
| 18 | +try: |
| 19 | + from unittest import mock |
| 20 | +except ImportError: |
| 21 | + import mock |
| 22 | + |
| 23 | + |
| 24 | +Application = get_application_model() |
| 25 | +AccessToken = get_access_token_model() |
| 26 | +UserModel = get_user_model() |
| 27 | + |
| 28 | +exp = datetime.datetime.now() + datetime.timedelta(days=1) |
| 29 | + |
| 30 | + |
| 31 | +class ScopeResourceView(ScopedProtectedResourceView): |
| 32 | + required_scopes = ["dolphin"] |
| 33 | + |
| 34 | + def get(self, request, *args, **kwargs): |
| 35 | + return HttpResponse("This is a protected resource", 200) |
| 36 | + |
| 37 | + def post(self, request, *args, **kwargs): |
| 38 | + return HttpResponse("This is a protected resource", 200) |
| 39 | + |
| 40 | + |
| 41 | +def mocked_requests_post(url, data, *args, **kwargs): |
| 42 | + """ |
| 43 | + Mock the response from the authentication server |
| 44 | + """ |
| 45 | + class MockResponse: |
| 46 | + def __init__(self, json_data, status_code): |
| 47 | + self.json_data = json_data |
| 48 | + self.status_code = status_code |
| 49 | + |
| 50 | + def json(self): |
| 51 | + return self.json_data |
| 52 | + |
| 53 | + if "token" in data and data["token"] and data["token"] != "12345678900": |
| 54 | + return MockResponse({ |
| 55 | + "active": True, |
| 56 | + "scope": "read write dolphin", |
| 57 | + "client_id": "client_id_{}".format(data["token"]), |
| 58 | + "username": "{}_user".format(data["token"]), |
| 59 | + "exp": int(calendar.timegm(exp.timetuple())), |
| 60 | + }, 200) |
| 61 | + |
| 62 | + return MockResponse({ |
| 63 | + "active": False, |
| 64 | + }, 200) |
| 65 | + |
| 66 | + |
| 67 | +urlpatterns = [ |
| 68 | + url(r"^oauth2/", include("oauth2_provider.urls")), |
| 69 | + url(r"^oauth2-test-resource/$", ScopeResourceView.as_view()), |
| 70 | +] |
| 71 | + |
| 72 | + |
| 73 | +@override_settings(ROOT_URLCONF=__name__) |
| 74 | +class TestTokenIntrospectionAuth(TestCase): |
| 75 | + """ |
| 76 | + Tests for Authorization through token introspection |
| 77 | + """ |
| 78 | + def setUp(self): |
| 79 | + self.validator = OAuth2Validator() |
| 80 | + self.request = mock.MagicMock(wraps=Request) |
| 81 | + self.resource_server_user = UserModel.objects.create_user( |
| 82 | + "resource_server", "test@example.com", "123456" |
| 83 | + ) |
| 84 | + |
| 85 | + self.application = Application( |
| 86 | + name="Test Application", |
| 87 | + redirect_uris="http://localhost http://example.com http://example.org", |
| 88 | + user=self.resource_server_user, |
| 89 | + client_type=Application.CLIENT_CONFIDENTIAL, |
| 90 | + authorization_grant_type=Application.GRANT_AUTHORIZATION_CODE, |
| 91 | + ) |
| 92 | + self.application.save() |
| 93 | + |
| 94 | + self.resource_server_token = AccessToken.objects.create( |
| 95 | + user=self.resource_server_user, token="12345678900", |
| 96 | + application=self.application, |
| 97 | + expires=timezone.now() + datetime.timedelta(days=1), |
| 98 | + scope="read write introspection" |
| 99 | + ) |
| 100 | + |
| 101 | + self.invalid_token = AccessToken.objects.create( |
| 102 | + user=self.resource_server_user, token="12345678901", |
| 103 | + application=self.application, |
| 104 | + expires=timezone.now() + datetime.timedelta(days=-1), |
| 105 | + scope="read write dolphin" |
| 106 | + ) |
| 107 | + |
| 108 | + oauth2_settings._SCOPES = ["read", "write", "introspection", "dolphin"] |
| 109 | + oauth2_settings.RESOURCE_SERVER_INTROSPECTION_URL = "http://example.org/introspection" |
| 110 | + oauth2_settings.RESOURCE_SERVER_AUTH_TOKEN = self.resource_server_token.token |
| 111 | + oauth2_settings.READ_SCOPE = "read" |
| 112 | + oauth2_settings.WRITE_SCOPE = "write" |
| 113 | + |
| 114 | + def tearDown(self): |
| 115 | + oauth2_settings._SCOPES = ["read", "write"] |
| 116 | + oauth2_settings.RESOURCE_SERVER_INTROSPECTION_URL = None |
| 117 | + oauth2_settings.RESOURCE_SERVER_AUTH_TOKEN = None |
| 118 | + self.resource_server_token.delete() |
| 119 | + self.application.delete() |
| 120 | + AccessToken.objects.all().delete() |
| 121 | + UserModel.objects.all().delete() |
| 122 | + |
| 123 | + @mock.patch("requests.post", side_effect=mocked_requests_post) |
| 124 | + def test_get_token_from_authentication_server_not_existing_token(self, mock_get): |
| 125 | + """ |
| 126 | + Test method _get_token_from_authentication_server with non existing token |
| 127 | + """ |
| 128 | + token = self.validator._get_token_from_authentication_server( |
| 129 | + self.resource_server_token.token, |
| 130 | + oauth2_settings.RESOURCE_SERVER_INTROSPECTION_URL, |
| 131 | + oauth2_settings.RESOURCE_SERVER_AUTH_TOKEN |
| 132 | + ) |
| 133 | + self.assertIsNone(token) |
| 134 | + |
| 135 | + @mock.patch("requests.post", side_effect=mocked_requests_post) |
| 136 | + def test_get_token_from_authentication_server_existing_token(self, mock_get): |
| 137 | + """ |
| 138 | + Test method _get_token_from_authentication_server with existing token |
| 139 | + """ |
| 140 | + token = self.validator._get_token_from_authentication_server( |
| 141 | + "foo", |
| 142 | + oauth2_settings.RESOURCE_SERVER_INTROSPECTION_URL, |
| 143 | + oauth2_settings.RESOURCE_SERVER_AUTH_TOKEN |
| 144 | + ) |
| 145 | + self.assertIsInstance(token, AccessToken) |
| 146 | + self.assertEqual(token.user.username, "foo_user") |
| 147 | + self.assertEqual(token.scope, "read write dolphin") |
| 148 | + |
| 149 | + @mock.patch("requests.post", side_effect=mocked_requests_post) |
| 150 | + def test_validate_bearer_token(self, mock_get): |
| 151 | + """ |
| 152 | + Test method validate_bearer_token |
| 153 | + """ |
| 154 | + # with token = None |
| 155 | + self.assertFalse(self.validator.validate_bearer_token(None, ["dolphin"], self.request)) |
| 156 | + # with valid token and scope |
| 157 | + self.assertTrue(self.validator.validate_bearer_token(self.resource_server_token.token, ["introspection"], self.request)) |
| 158 | + # with initially invalid token, but validated through request |
| 159 | + self.assertTrue(self.validator.validate_bearer_token(self.invalid_token.token, ["dolphin"], self.request)) |
| 160 | + # with locally unavailable token, but validated through request |
| 161 | + self.assertTrue(self.validator.validate_bearer_token("butzi", ["dolphin"], self.request)) |
| 162 | + # with valid token but invalid scope |
| 163 | + self.assertFalse(self.validator.validate_bearer_token("foo", ["kaudawelsch"], self.request)) |
| 164 | + # with token validated through request, but invalid scope |
| 165 | + self.assertFalse(self.validator.validate_bearer_token("butz", ["kaudawelsch"], self.request)) |
| 166 | + # with token validated through request and valid scope |
| 167 | + self.assertTrue(self.validator.validate_bearer_token("butzi", ["dolphin"], self.request)) |
| 168 | + |
| 169 | + @mock.patch("requests.post", side_effect=mocked_requests_post) |
| 170 | + def test_get_resource(self, mock_get): |
| 171 | + """ |
| 172 | + Test that we can access the resource with a get request and a remotely validated token |
| 173 | + """ |
| 174 | + auth_headers = { |
| 175 | + "HTTP_AUTHORIZATION": "Bearer bar", |
| 176 | + } |
| 177 | + response = self.client.get("/oauth2-test-resource/", **auth_headers) |
| 178 | + self.assertEqual(response.content.decode("utf-8"), "This is a protected resource") |
| 179 | + |
| 180 | + @mock.patch("requests.post", side_effect=mocked_requests_post) |
| 181 | + def test_post_resource(self, mock_get): |
| 182 | + """ |
| 183 | + Test that we can access the resource with a post request and a remotely validated token |
| 184 | + """ |
| 185 | + auth_headers = { |
| 186 | + "HTTP_AUTHORIZATION": "Bearer batz", |
| 187 | + } |
| 188 | + response = self.client.post("/oauth2-test-resource/", **auth_headers) |
| 189 | + self.assertEqual(response.content.decode("utf-8"), "This is a protected resource") |
0 commit comments