File: conftest.py

package info (click to toggle)
django-oauth-toolkit 3.0.1-1
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 2,156 kB
  • sloc: python: 11,100; makefile: 159; javascript: 9; sh: 6
file content (307 lines) | stat: -rw-r--r-- 9,895 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
import uuid
from datetime import timedelta
from types import SimpleNamespace
from urllib.parse import parse_qs, urlparse

import pytest
from django import VERSION
from django.conf import settings as test_settings
from django.contrib.auth import get_user_model
from django.urls import reverse
from django.utils import dateformat, timezone
from jwcrypto import jwk, jwt

from oauth2_provider.models import get_application_model, get_id_token_model
from oauth2_provider.settings import oauth2_settings as _oauth2_settings

from . import presets


Application = get_application_model()
UserModel = get_user_model()

CLEARTEXT_SECRET = "1234567890abcdefghijklmnopqrstuvwxyz"


class OAuthSettingsWrapper:
    """
    A wrapper around oauth2_settings to ensure that when an overridden value is
    set, it also records it in _cached_attrs, so that the settings can be reset.
    """

    def __init__(self, settings, user_settings):
        self.settings = settings
        if not user_settings:
            user_settings = {}
        self.update(user_settings)

    def update(self, user_settings):
        self.settings.OAUTH2_PROVIDER = user_settings
        _oauth2_settings.reload()
        # Reload OAuthlibCore for every view request during tests
        self.ALWAYS_RELOAD_OAUTHLIB_CORE = True

    def __setattr__(self, attr, value):
        if attr == "settings":
            super().__setattr__(attr, value)
        else:
            setattr(_oauth2_settings, attr, value)
            _oauth2_settings._cached_attrs.add(attr)

    def __delattr__(self, attr):
        delattr(_oauth2_settings, attr)
        if attr in _oauth2_settings._cached_attrs:
            _oauth2_settings._cached_attrs.remove(attr)

    def __getattr__(self, attr):
        return getattr(_oauth2_settings, attr)

    def finalize(self):
        self.settings.finalize()
        _oauth2_settings.reload()


@pytest.fixture
def oauth2_settings(request, settings):
    """
    A fixture that provides a simple way to override OAUTH2_PROVIDER settings.

    It can be used two ways - either setting things on the fly, or by reading
    configuration data from the pytest marker oauth2_settings.

    If used on a standard pytest function, you can use argument dependency
    injection to get the wrapper. If used on a unittest.TestCase, the wrapper
    is made available on the class instance, as `oauth2_settings`.

    Anything overridden will be restored at the end of the test case, ensuring
    that there is no configuration leakage between test cases.
    """
    marker = request.node.get_closest_marker("oauth2_settings")
    user_settings = {}
    if marker is not None:
        user_settings = marker.args[0]
    wrapper = OAuthSettingsWrapper(settings, user_settings)
    if request.instance is not None:
        request.instance.oauth2_settings = wrapper
    yield wrapper
    wrapper.finalize()


@pytest.fixture(scope="session")
def oidc_key_():
    return jwk.JWK.from_pem(test_settings.OIDC_RSA_PRIVATE_KEY.encode("utf8"))


@pytest.fixture
def oidc_key(request, oidc_key_):
    if request.instance is not None:
        request.instance.key = oidc_key_
    return oidc_key_


@pytest.fixture
def application():
    return Application.objects.create(
        name="Test Application",
        redirect_uris="http://example.org",
        post_logout_redirect_uris="http://example.org",
        client_type=Application.CLIENT_CONFIDENTIAL,
        authorization_grant_type=Application.GRANT_AUTHORIZATION_CODE,
        algorithm=Application.RS256_ALGORITHM,
        client_secret=CLEARTEXT_SECRET,
    )


@pytest.fixture
def public_application():
    return Application.objects.create(
        name="Other Application",
        redirect_uris="http://other.org",
        post_logout_redirect_uris="http://other.org",
        client_type=Application.CLIENT_PUBLIC,
        authorization_grant_type=Application.GRANT_AUTHORIZATION_CODE,
        algorithm=Application.RS256_ALGORITHM,
        client_secret=CLEARTEXT_SECRET,
    )


@pytest.fixture
def cors_application():
    return Application.objects.create(
        name="Test CORS Application",
        client_type=Application.CLIENT_CONFIDENTIAL,
        authorization_grant_type=Application.GRANT_AUTHORIZATION_CODE,
        algorithm=Application.RS256_ALGORITHM,
        client_secret=CLEARTEXT_SECRET,
        allowed_origins="https://example.com http://example.com",
    )


@pytest.fixture
def logged_in_client(test_user):
    from django.test.client import Client

    client = Client()
    client.force_login(test_user)
    return client


@pytest.fixture
def hybrid_application(application):
    application.authorization_grant_type = application.GRANT_OPENID_HYBRID
    application.client_secret = CLEARTEXT_SECRET
    application.save()
    return application


@pytest.fixture
def test_user():
    return UserModel.objects.create_user("test_user", "test@example.com", "123456")


@pytest.fixture
def other_user():
    return UserModel.objects.create_user("other_user", "other@example.com", "123456")


@pytest.fixture
def rp_settings(oauth2_settings):
    oauth2_settings.update(presets.OIDC_SETTINGS_RP_LOGOUT)
    return oauth2_settings


def generate_access_token(oauth2_settings, application, test_user, client, settings, scope, redirect_uri):
    """
    A helper function that generates an access_token and ID Token for a given Application and User.
    """
    oauth2_settings.update(settings)
    client.force_login(test_user)
    auth_rsp = client.post(
        reverse("oauth2_provider:authorize"),
        data={
            "client_id": application.client_id,
            "state": "random_state_string",
            "scope": scope,
            "redirect_uri": redirect_uri,
            "response_type": "code",
            "allow": True,
        },
    )
    assert auth_rsp.status_code == 302
    code = parse_qs(urlparse(auth_rsp["Location"]).query)["code"]
    client.logout()
    token_rsp = client.post(
        reverse("oauth2_provider:token"),
        data={
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": redirect_uri,
            "client_id": application.client_id,
            "client_secret": CLEARTEXT_SECRET,
            "scope": scope,
        },
    )
    assert token_rsp.status_code == 200
    token_data = token_rsp.json()
    return SimpleNamespace(
        user=test_user,
        application=application,
        access_token=token_data["access_token"],
        id_token=token_data["id_token"],
        oauth2_settings=oauth2_settings,
    )


@pytest.fixture
def expired_id_token(oauth2_settings, oidc_key, test_user, application):
    payload = generate_id_token_payload(oauth2_settings, application, oidc_key)
    return generate_id_token(test_user, payload, oidc_key, application)


@pytest.fixture
def id_token_wrong_aud(oauth2_settings, oidc_key, test_user, application):
    payload = generate_id_token_payload(oauth2_settings, application, oidc_key)
    payload[1]["aud"] = ""
    return generate_id_token(test_user, payload, oidc_key, application)


@pytest.fixture
def id_token_wrong_iss(oauth2_settings, oidc_key, test_user, application):
    payload = generate_id_token_payload(oauth2_settings, application, oidc_key)
    payload[1]["iss"] = ""
    return generate_id_token(test_user, payload, oidc_key, application)


def generate_id_token_payload(oauth2_settings, application, oidc_key):
    # Default leeway of JWT in jwcrypto is 60 seconds. This means that tokens that expired up to 60 seconds
    # ago are still accepted.
    expiration_time = timezone.now() - timedelta(seconds=61)
    # Calculate values for the IDToken
    exp = int(dateformat.format(expiration_time, "U"))
    jti = str(uuid.uuid4())
    aud = application.client_id
    iss = oauth2_settings.OIDC_ISS_ENDPOINT
    # Construct and sign the IDToken
    header = {"typ": "JWT", "alg": "RS256", "kid": oidc_key.thumbprint()}
    id_token = {"exp": exp, "jti": jti, "aud": aud, "iss": iss}
    return header, id_token, jti, expiration_time


def generate_id_token(user, payload, oidc_key, application):
    header, id_token, jti, expiration_time = payload
    jwt_token = jwt.JWT(header=header, claims=id_token)
    jwt_token.make_signed_token(oidc_key)
    # Save the IDToken in the DB. Required for later lookups from e.g. RP-Initiated Logout.
    IDToken = get_id_token_model()
    IDToken.objects.create(user=user, scope="", expires=expiration_time, jti=jti, application=application)
    # Return the token as a string.
    return jwt_token.token.serialize(compact=True)


@pytest.fixture
def oidc_tokens(oauth2_settings, application, test_user, client):
    return generate_access_token(
        oauth2_settings,
        application,
        test_user,
        client,
        presets.OIDC_SETTINGS_RW,
        "openid",
        "http://example.org",
    )


@pytest.fixture
def oidc_email_scope_tokens(oauth2_settings, application, test_user, client):
    return generate_access_token(
        oauth2_settings,
        application,
        test_user,
        client,
        presets.OIDC_SETTINGS_EMAIL_SCOPE,
        "openid email",
        "http://example.org",
    )


@pytest.fixture
def oidc_non_confidential_tokens(oauth2_settings, public_application, test_user, client):
    return generate_access_token(
        oauth2_settings,
        public_application,
        test_user,
        client,
        presets.OIDC_SETTINGS_EMAIL_SCOPE,
        "openid",
        "http://other.org",
    )


@pytest.fixture(autouse=True)
def django_login_required_middleware(settings, request):
    if "nologinrequiredmiddleware" in request.keywords:
        return

    # Django 5.1 introduced LoginRequiredMiddleware
    if VERSION[0] >= 5 and VERSION[1] >= 1:
        settings.MIDDLEWARE = [*settings.MIDDLEWARE, "django.contrib.auth.middleware.LoginRequiredMiddleware"]