authentik.providers.oauth2.tests.test_utils

Test OAuth2 utility helpers

  1"""Test OAuth2 utility helpers"""
  2
  3from django.http import HttpResponse
  4from django.test import TestCase
  5
  6from authentik.core.tests.utils import RequestFactory
  7from authentik.providers.oauth2.models import RedirectURI, RedirectURIMatchingMode
  8from authentik.providers.oauth2.utils import cors_allow
  9
 10
 11class TestCorsAllow(TestCase):
 12    """Tests for ``cors_allow``: ensures regex-mode redirect URI entries are honoured
 13    for CORS origin validation, not only for the authorize-step redirect_uri check."""
 14
 15    def setUp(self):
 16        self.factory = RequestFactory()
 17
 18    def test_strict_match(self):
 19        """Strict origin entry matches scheme + host + port (regression)."""
 20        request = self.factory.post("/", HTTP_ORIGIN="http://local.invalid")
 21        response = cors_allow(
 22            request,
 23            HttpResponse(),
 24            [RedirectURI(RedirectURIMatchingMode.STRICT, "http://local.invalid/callback")],
 25        )
 26        self.assertEqual(response["Access-Control-Allow-Origin"], "http://local.invalid")
 27        self.assertEqual(response["Access-Control-Allow-Credentials"], "true")
 28
 29    def test_strict_no_match(self):
 30        """Strict entry on a different host does not allow the origin."""
 31        request = self.factory.post("/", HTTP_ORIGIN="http://other.invalid")
 32        response = cors_allow(
 33            request,
 34            HttpResponse(),
 35            [RedirectURI(RedirectURIMatchingMode.STRICT, "http://local.invalid/callback")],
 36        )
 37        self.assertNotIn("Access-Control-Allow-Origin", response)
 38
 39    def test_regex_match(self):
 40        """Regex entry matching the Origin sets the CORS header."""
 41        request = self.factory.post("/", HTTP_ORIGIN="https://app-abc123.example.com")
 42        response = cors_allow(
 43            request,
 44            HttpResponse(),
 45            [
 46                RedirectURI(
 47                    RedirectURIMatchingMode.REGEX,
 48                    r"https://app-\w+\.example\.com",
 49                )
 50            ],
 51        )
 52        self.assertEqual(response["Access-Control-Allow-Origin"], "https://app-abc123.example.com")
 53
 54    def test_regex_no_match(self):
 55        """Regex entry that does not match the Origin must not allow the request."""
 56        request = self.factory.post("/", HTTP_ORIGIN="https://evil.example.com")
 57        response = cors_allow(
 58            request,
 59            HttpResponse(),
 60            [
 61                RedirectURI(
 62                    RedirectURIMatchingMode.REGEX,
 63                    r"https://app-\w+\.example\.com",
 64                )
 65            ],
 66        )
 67        self.assertNotIn("Access-Control-Allow-Origin", response)
 68
 69    def test_regex_with_optional_path_group(self):
 70        """A regex written as ``host(/path)?`` should match the bare Origin (without path)
 71        as well as the full redirect URI used by the authorize step."""
 72        regex = r"https://app-\w+\.example\.com(/callback)?"
 73        # Origin (no path)
 74        response = cors_allow(
 75            self.factory.post("/", HTTP_ORIGIN="https://app-foo.example.com"),
 76            HttpResponse(),
 77            [RedirectURI(RedirectURIMatchingMode.REGEX, regex)],
 78        )
 79        self.assertEqual(response["Access-Control-Allow-Origin"], "https://app-foo.example.com")
 80        # Origin equal to a wrong host: must not match.
 81        response = cors_allow(
 82            self.factory.post("/", HTTP_ORIGIN="https://other.example.com"),
 83            HttpResponse(),
 84            [RedirectURI(RedirectURIMatchingMode.REGEX, regex)],
 85        )
 86        self.assertNotIn("Access-Control-Allow-Origin", response)
 87
 88    def test_regex_full_redirect_uri_does_not_match_bare_origin(self):
 89        """A regex written for the full redirect URI (including a mandatory path) will
 90        not match a bare Origin header. This is the documented behavior: users wanting
 91        regex CORS support should write ``host(/path)?`` or add a separate origin entry."""
 92        request = self.factory.post("/", HTTP_ORIGIN="https://app-abc.example.com")
 93        response = cors_allow(
 94            request,
 95            HttpResponse(),
 96            [
 97                RedirectURI(
 98                    RedirectURIMatchingMode.REGEX,
 99                    r"https://app-\w+\.example\.com/callback",
100                )
101            ],
102        )
103        self.assertNotIn("Access-Control-Allow-Origin", response)
104
105    def test_malformed_regex_is_skipped(self):
106        """Malformed regexes are logged and skipped; a later valid entry still matches."""
107        request = self.factory.post("/", HTTP_ORIGIN="https://good.example.com")
108        response = cors_allow(
109            request,
110            HttpResponse(),
111            [
112                RedirectURI(RedirectURIMatchingMode.REGEX, r"["),  # invalid regex
113                RedirectURI(RedirectURIMatchingMode.REGEX, r"https://good\.example\.com"),
114            ],
115        )
116        self.assertEqual(response["Access-Control-Allow-Origin"], "https://good.example.com")
117
118    def test_malformed_regex_alone_does_not_500(self):
119        """A malformed regex with no other allowed entries must return the response
120        unchanged rather than raising."""
121        request = self.factory.post("/", HTTP_ORIGIN="https://anything.example.com")
122        response = cors_allow(
123            request,
124            HttpResponse(),
125            [RedirectURI(RedirectURIMatchingMode.REGEX, r"[")],
126        )
127        self.assertNotIn("Access-Control-Allow-Origin", response)
128
129    def test_options_request_allowed_without_match(self):
130        """Pre-flight OPTIONS requests are allowed through without an entry match
131        (regression: existing behavior)."""
132        request = self.factory.options(
133            "/",
134            HTTP_ORIGIN="https://anywhere.example.com",
135            HTTP_ACCESS_CONTROL_REQUEST_HEADERS="content-type",
136        )
137        response = cors_allow(request, HttpResponse(), [])
138        self.assertEqual(response["Access-Control-Allow-Origin"], "https://anywhere.example.com")
139
140    def test_bare_string_treated_as_strict(self):
141        """Backwards compatibility: bare string entries are treated as STRICT."""
142        request = self.factory.post("/", HTTP_ORIGIN="http://local.invalid")
143        response = cors_allow(request, HttpResponse(), ["http://local.invalid/callback"])
144        self.assertEqual(response["Access-Control-Allow-Origin"], "http://local.invalid")
145
146    def test_mixed_strict_and_regex(self):
147        """A provider with one strict and one regex entry honours both."""
148        entries = (
149            RedirectURI(RedirectURIMatchingMode.STRICT, "http://local.invalid/callback"),
150            RedirectURI(RedirectURIMatchingMode.REGEX, r"https://app-\w+\.example\.com"),
151        )
152        # Strict origin matches via the strict entry.
153        response = cors_allow(
154            self.factory.post("/", HTTP_ORIGIN="http://local.invalid"), HttpResponse(), entries
155        )
156        self.assertEqual(response["Access-Control-Allow-Origin"], "http://local.invalid")
157        # Regex origin matches via the regex entry.
158        response = cors_allow(
159            self.factory.post("/", HTTP_ORIGIN="https://app-xyz.example.com"),
160            HttpResponse(),
161            entries,
162        )
163        self.assertEqual(response["Access-Control-Allow-Origin"], "https://app-xyz.example.com")
class TestCorsAllow(django.test.testcases.TestCase):
 12class TestCorsAllow(TestCase):
 13    """Tests for ``cors_allow``: ensures regex-mode redirect URI entries are honoured
 14    for CORS origin validation, not only for the authorize-step redirect_uri check."""
 15
 16    def setUp(self):
 17        self.factory = RequestFactory()
 18
 19    def test_strict_match(self):
 20        """Strict origin entry matches scheme + host + port (regression)."""
 21        request = self.factory.post("/", HTTP_ORIGIN="http://local.invalid")
 22        response = cors_allow(
 23            request,
 24            HttpResponse(),
 25            [RedirectURI(RedirectURIMatchingMode.STRICT, "http://local.invalid/callback")],
 26        )
 27        self.assertEqual(response["Access-Control-Allow-Origin"], "http://local.invalid")
 28        self.assertEqual(response["Access-Control-Allow-Credentials"], "true")
 29
 30    def test_strict_no_match(self):
 31        """Strict entry on a different host does not allow the origin."""
 32        request = self.factory.post("/", HTTP_ORIGIN="http://other.invalid")
 33        response = cors_allow(
 34            request,
 35            HttpResponse(),
 36            [RedirectURI(RedirectURIMatchingMode.STRICT, "http://local.invalid/callback")],
 37        )
 38        self.assertNotIn("Access-Control-Allow-Origin", response)
 39
 40    def test_regex_match(self):
 41        """Regex entry matching the Origin sets the CORS header."""
 42        request = self.factory.post("/", HTTP_ORIGIN="https://app-abc123.example.com")
 43        response = cors_allow(
 44            request,
 45            HttpResponse(),
 46            [
 47                RedirectURI(
 48                    RedirectURIMatchingMode.REGEX,
 49                    r"https://app-\w+\.example\.com",
 50                )
 51            ],
 52        )
 53        self.assertEqual(response["Access-Control-Allow-Origin"], "https://app-abc123.example.com")
 54
 55    def test_regex_no_match(self):
 56        """Regex entry that does not match the Origin must not allow the request."""
 57        request = self.factory.post("/", HTTP_ORIGIN="https://evil.example.com")
 58        response = cors_allow(
 59            request,
 60            HttpResponse(),
 61            [
 62                RedirectURI(
 63                    RedirectURIMatchingMode.REGEX,
 64                    r"https://app-\w+\.example\.com",
 65                )
 66            ],
 67        )
 68        self.assertNotIn("Access-Control-Allow-Origin", response)
 69
 70    def test_regex_with_optional_path_group(self):
 71        """A regex written as ``host(/path)?`` should match the bare Origin (without path)
 72        as well as the full redirect URI used by the authorize step."""
 73        regex = r"https://app-\w+\.example\.com(/callback)?"
 74        # Origin (no path)
 75        response = cors_allow(
 76            self.factory.post("/", HTTP_ORIGIN="https://app-foo.example.com"),
 77            HttpResponse(),
 78            [RedirectURI(RedirectURIMatchingMode.REGEX, regex)],
 79        )
 80        self.assertEqual(response["Access-Control-Allow-Origin"], "https://app-foo.example.com")
 81        # Origin equal to a wrong host: must not match.
 82        response = cors_allow(
 83            self.factory.post("/", HTTP_ORIGIN="https://other.example.com"),
 84            HttpResponse(),
 85            [RedirectURI(RedirectURIMatchingMode.REGEX, regex)],
 86        )
 87        self.assertNotIn("Access-Control-Allow-Origin", response)
 88
 89    def test_regex_full_redirect_uri_does_not_match_bare_origin(self):
 90        """A regex written for the full redirect URI (including a mandatory path) will
 91        not match a bare Origin header. This is the documented behavior: users wanting
 92        regex CORS support should write ``host(/path)?`` or add a separate origin entry."""
 93        request = self.factory.post("/", HTTP_ORIGIN="https://app-abc.example.com")
 94        response = cors_allow(
 95            request,
 96            HttpResponse(),
 97            [
 98                RedirectURI(
 99                    RedirectURIMatchingMode.REGEX,
100                    r"https://app-\w+\.example\.com/callback",
101                )
102            ],
103        )
104        self.assertNotIn("Access-Control-Allow-Origin", response)
105
106    def test_malformed_regex_is_skipped(self):
107        """Malformed regexes are logged and skipped; a later valid entry still matches."""
108        request = self.factory.post("/", HTTP_ORIGIN="https://good.example.com")
109        response = cors_allow(
110            request,
111            HttpResponse(),
112            [
113                RedirectURI(RedirectURIMatchingMode.REGEX, r"["),  # invalid regex
114                RedirectURI(RedirectURIMatchingMode.REGEX, r"https://good\.example\.com"),
115            ],
116        )
117        self.assertEqual(response["Access-Control-Allow-Origin"], "https://good.example.com")
118
119    def test_malformed_regex_alone_does_not_500(self):
120        """A malformed regex with no other allowed entries must return the response
121        unchanged rather than raising."""
122        request = self.factory.post("/", HTTP_ORIGIN="https://anything.example.com")
123        response = cors_allow(
124            request,
125            HttpResponse(),
126            [RedirectURI(RedirectURIMatchingMode.REGEX, r"[")],
127        )
128        self.assertNotIn("Access-Control-Allow-Origin", response)
129
130    def test_options_request_allowed_without_match(self):
131        """Pre-flight OPTIONS requests are allowed through without an entry match
132        (regression: existing behavior)."""
133        request = self.factory.options(
134            "/",
135            HTTP_ORIGIN="https://anywhere.example.com",
136            HTTP_ACCESS_CONTROL_REQUEST_HEADERS="content-type",
137        )
138        response = cors_allow(request, HttpResponse(), [])
139        self.assertEqual(response["Access-Control-Allow-Origin"], "https://anywhere.example.com")
140
141    def test_bare_string_treated_as_strict(self):
142        """Backwards compatibility: bare string entries are treated as STRICT."""
143        request = self.factory.post("/", HTTP_ORIGIN="http://local.invalid")
144        response = cors_allow(request, HttpResponse(), ["http://local.invalid/callback"])
145        self.assertEqual(response["Access-Control-Allow-Origin"], "http://local.invalid")
146
147    def test_mixed_strict_and_regex(self):
148        """A provider with one strict and one regex entry honours both."""
149        entries = (
150            RedirectURI(RedirectURIMatchingMode.STRICT, "http://local.invalid/callback"),
151            RedirectURI(RedirectURIMatchingMode.REGEX, r"https://app-\w+\.example\.com"),
152        )
153        # Strict origin matches via the strict entry.
154        response = cors_allow(
155            self.factory.post("/", HTTP_ORIGIN="http://local.invalid"), HttpResponse(), entries
156        )
157        self.assertEqual(response["Access-Control-Allow-Origin"], "http://local.invalid")
158        # Regex origin matches via the regex entry.
159        response = cors_allow(
160            self.factory.post("/", HTTP_ORIGIN="https://app-xyz.example.com"),
161            HttpResponse(),
162            entries,
163        )
164        self.assertEqual(response["Access-Control-Allow-Origin"], "https://app-xyz.example.com")

Tests for cors_allow: ensures regex-mode redirect URI entries are honoured for CORS origin validation, not only for the authorize-step redirect_uri check.

def setUp(self):
16    def setUp(self):
17        self.factory = RequestFactory()

Hook method for setting up the test fixture before exercising it.

def test_strict_match(self):
19    def test_strict_match(self):
20        """Strict origin entry matches scheme + host + port (regression)."""
21        request = self.factory.post("/", HTTP_ORIGIN="http://local.invalid")
22        response = cors_allow(
23            request,
24            HttpResponse(),
25            [RedirectURI(RedirectURIMatchingMode.STRICT, "http://local.invalid/callback")],
26        )
27        self.assertEqual(response["Access-Control-Allow-Origin"], "http://local.invalid")
28        self.assertEqual(response["Access-Control-Allow-Credentials"], "true")

Strict origin entry matches scheme + host + port (regression).

def test_strict_no_match(self):
30    def test_strict_no_match(self):
31        """Strict entry on a different host does not allow the origin."""
32        request = self.factory.post("/", HTTP_ORIGIN="http://other.invalid")
33        response = cors_allow(
34            request,
35            HttpResponse(),
36            [RedirectURI(RedirectURIMatchingMode.STRICT, "http://local.invalid/callback")],
37        )
38        self.assertNotIn("Access-Control-Allow-Origin", response)

Strict entry on a different host does not allow the origin.

def test_regex_match(self):
40    def test_regex_match(self):
41        """Regex entry matching the Origin sets the CORS header."""
42        request = self.factory.post("/", HTTP_ORIGIN="https://app-abc123.example.com")
43        response = cors_allow(
44            request,
45            HttpResponse(),
46            [
47                RedirectURI(
48                    RedirectURIMatchingMode.REGEX,
49                    r"https://app-\w+\.example\.com",
50                )
51            ],
52        )
53        self.assertEqual(response["Access-Control-Allow-Origin"], "https://app-abc123.example.com")

Regex entry matching the Origin sets the CORS header.

def test_regex_no_match(self):
55    def test_regex_no_match(self):
56        """Regex entry that does not match the Origin must not allow the request."""
57        request = self.factory.post("/", HTTP_ORIGIN="https://evil.example.com")
58        response = cors_allow(
59            request,
60            HttpResponse(),
61            [
62                RedirectURI(
63                    RedirectURIMatchingMode.REGEX,
64                    r"https://app-\w+\.example\.com",
65                )
66            ],
67        )
68        self.assertNotIn("Access-Control-Allow-Origin", response)

Regex entry that does not match the Origin must not allow the request.

def test_regex_with_optional_path_group(self):
70    def test_regex_with_optional_path_group(self):
71        """A regex written as ``host(/path)?`` should match the bare Origin (without path)
72        as well as the full redirect URI used by the authorize step."""
73        regex = r"https://app-\w+\.example\.com(/callback)?"
74        # Origin (no path)
75        response = cors_allow(
76            self.factory.post("/", HTTP_ORIGIN="https://app-foo.example.com"),
77            HttpResponse(),
78            [RedirectURI(RedirectURIMatchingMode.REGEX, regex)],
79        )
80        self.assertEqual(response["Access-Control-Allow-Origin"], "https://app-foo.example.com")
81        # Origin equal to a wrong host: must not match.
82        response = cors_allow(
83            self.factory.post("/", HTTP_ORIGIN="https://other.example.com"),
84            HttpResponse(),
85            [RedirectURI(RedirectURIMatchingMode.REGEX, regex)],
86        )
87        self.assertNotIn("Access-Control-Allow-Origin", response)

A regex written as host(/path)? should match the bare Origin (without path) as well as the full redirect URI used by the authorize step.

def test_regex_full_redirect_uri_does_not_match_bare_origin(self):
 89    def test_regex_full_redirect_uri_does_not_match_bare_origin(self):
 90        """A regex written for the full redirect URI (including a mandatory path) will
 91        not match a bare Origin header. This is the documented behavior: users wanting
 92        regex CORS support should write ``host(/path)?`` or add a separate origin entry."""
 93        request = self.factory.post("/", HTTP_ORIGIN="https://app-abc.example.com")
 94        response = cors_allow(
 95            request,
 96            HttpResponse(),
 97            [
 98                RedirectURI(
 99                    RedirectURIMatchingMode.REGEX,
100                    r"https://app-\w+\.example\.com/callback",
101                )
102            ],
103        )
104        self.assertNotIn("Access-Control-Allow-Origin", response)

A regex written for the full redirect URI (including a mandatory path) will not match a bare Origin header. This is the documented behavior: users wanting regex CORS support should write host(/path)? or add a separate origin entry.

def test_malformed_regex_is_skipped(self):
106    def test_malformed_regex_is_skipped(self):
107        """Malformed regexes are logged and skipped; a later valid entry still matches."""
108        request = self.factory.post("/", HTTP_ORIGIN="https://good.example.com")
109        response = cors_allow(
110            request,
111            HttpResponse(),
112            [
113                RedirectURI(RedirectURIMatchingMode.REGEX, r"["),  # invalid regex
114                RedirectURI(RedirectURIMatchingMode.REGEX, r"https://good\.example\.com"),
115            ],
116        )
117        self.assertEqual(response["Access-Control-Allow-Origin"], "https://good.example.com")

Malformed regexes are logged and skipped; a later valid entry still matches.

def test_malformed_regex_alone_does_not_500(self):
119    def test_malformed_regex_alone_does_not_500(self):
120        """A malformed regex with no other allowed entries must return the response
121        unchanged rather than raising."""
122        request = self.factory.post("/", HTTP_ORIGIN="https://anything.example.com")
123        response = cors_allow(
124            request,
125            HttpResponse(),
126            [RedirectURI(RedirectURIMatchingMode.REGEX, r"[")],
127        )
128        self.assertNotIn("Access-Control-Allow-Origin", response)

A malformed regex with no other allowed entries must return the response unchanged rather than raising.

def test_options_request_allowed_without_match(self):
130    def test_options_request_allowed_without_match(self):
131        """Pre-flight OPTIONS requests are allowed through without an entry match
132        (regression: existing behavior)."""
133        request = self.factory.options(
134            "/",
135            HTTP_ORIGIN="https://anywhere.example.com",
136            HTTP_ACCESS_CONTROL_REQUEST_HEADERS="content-type",
137        )
138        response = cors_allow(request, HttpResponse(), [])
139        self.assertEqual(response["Access-Control-Allow-Origin"], "https://anywhere.example.com")

Pre-flight OPTIONS requests are allowed through without an entry match (regression: existing behavior).

def test_bare_string_treated_as_strict(self):
141    def test_bare_string_treated_as_strict(self):
142        """Backwards compatibility: bare string entries are treated as STRICT."""
143        request = self.factory.post("/", HTTP_ORIGIN="http://local.invalid")
144        response = cors_allow(request, HttpResponse(), ["http://local.invalid/callback"])
145        self.assertEqual(response["Access-Control-Allow-Origin"], "http://local.invalid")

Backwards compatibility: bare string entries are treated as STRICT.

def test_mixed_strict_and_regex(self):
147    def test_mixed_strict_and_regex(self):
148        """A provider with one strict and one regex entry honours both."""
149        entries = (
150            RedirectURI(RedirectURIMatchingMode.STRICT, "http://local.invalid/callback"),
151            RedirectURI(RedirectURIMatchingMode.REGEX, r"https://app-\w+\.example\.com"),
152        )
153        # Strict origin matches via the strict entry.
154        response = cors_allow(
155            self.factory.post("/", HTTP_ORIGIN="http://local.invalid"), HttpResponse(), entries
156        )
157        self.assertEqual(response["Access-Control-Allow-Origin"], "http://local.invalid")
158        # Regex origin matches via the regex entry.
159        response = cors_allow(
160            self.factory.post("/", HTTP_ORIGIN="https://app-xyz.example.com"),
161            HttpResponse(),
162            entries,
163        )
164        self.assertEqual(response["Access-Control-Allow-Origin"], "https://app-xyz.example.com")

A provider with one strict and one regex entry honours both.