plain 0.57.0__py3-none-any.whl → 0.59.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- plain/CHANGELOG.md +28 -0
- plain/cli/agent.py +6 -0
- plain/cli/upgrade.py +1 -0
- plain/csrf/README.md +61 -9
- plain/csrf/middleware.py +95 -406
- plain/exceptions.py +29 -13
- plain/forms/README.md +0 -2
- plain/internal/middleware/https.py +5 -3
- plain/runtime/global_settings.py +51 -52
- plain/runtime/utils.py +20 -0
- plain/templates/README.md +0 -1
- plain/test/client.py +2 -10
- plain/views/README.md +0 -2
- plain/views/objects.py +39 -66
- plain/views/templates.py +6 -18
- {plain-0.57.0.dist-info → plain-0.59.0.dist-info}/METADATA +1 -1
- {plain-0.57.0.dist-info → plain-0.59.0.dist-info}/RECORD +20 -20
- plain/views/csrf.py +0 -4
- {plain-0.57.0.dist-info → plain-0.59.0.dist-info}/WHEEL +0 -0
- {plain-0.57.0.dist-info → plain-0.59.0.dist-info}/entry_points.txt +0 -0
- {plain-0.57.0.dist-info → plain-0.59.0.dist-info}/licenses/LICENSE +0 -0
plain/csrf/middleware.py
CHANGED
@@ -1,230 +1,126 @@
|
|
1
|
-
"""
|
2
|
-
Cross Site Request Forgery Middleware.
|
3
|
-
|
4
|
-
This module provides a middleware that implements protection
|
5
|
-
against request forgeries from other sites.
|
6
|
-
"""
|
7
|
-
|
8
1
|
import logging
|
9
|
-
import
|
10
|
-
from collections import defaultdict
|
11
|
-
from functools import cached_property
|
2
|
+
import re
|
12
3
|
from urllib.parse import urlparse
|
13
4
|
|
14
5
|
from plain.exceptions import DisallowedHost
|
15
|
-
from plain.http import HttpHeaders, UnreadablePostError
|
16
6
|
from plain.logs import log_response
|
17
7
|
from plain.runtime import settings
|
18
|
-
from plain.utils.cache import patch_vary_headers
|
19
|
-
from plain.utils.crypto import constant_time_compare, get_random_string
|
20
|
-
from plain.utils.http import is_same_domain
|
21
|
-
from plain.utils.regex_helper import _lazy_re_compile
|
22
|
-
|
23
|
-
logger = logging.getLogger("plain.security.csrf")
|
24
|
-
# This matches if any character is not in CSRF_ALLOWED_CHARS.
|
25
|
-
invalid_token_chars_re = _lazy_re_compile("[^a-zA-Z0-9]")
|
26
|
-
|
27
|
-
REASON_BAD_ORIGIN = "Origin checking failed - %s does not match any trusted origins."
|
28
|
-
REASON_NO_REFERER = "Referer checking failed - no Referer."
|
29
|
-
REASON_BAD_REFERER = "Referer checking failed - %s does not match any trusted origins."
|
30
|
-
REASON_NO_CSRF_COOKIE = "CSRF cookie not set."
|
31
|
-
REASON_CSRF_TOKEN_MISSING = "CSRF token missing."
|
32
|
-
REASON_MALFORMED_REFERER = "Referer checking failed - Referer is malformed."
|
33
|
-
REASON_INSECURE_REFERER = (
|
34
|
-
"Referer checking failed - Referer is insecure while host is secure."
|
35
|
-
)
|
36
|
-
# The reason strings below are for passing to InvalidTokenFormat. They are
|
37
|
-
# phrases without a subject because they can be in reference to either the CSRF
|
38
|
-
# cookie or non-cookie token.
|
39
|
-
REASON_INCORRECT_LENGTH = "has incorrect length"
|
40
|
-
REASON_INVALID_CHARACTERS = "has invalid characters"
|
41
|
-
|
42
|
-
CSRF_SECRET_LENGTH = 32
|
43
|
-
CSRF_TOKEN_LENGTH = 2 * CSRF_SECRET_LENGTH
|
44
|
-
CSRF_ALLOWED_CHARS = string.ascii_letters + string.digits
|
45
|
-
|
46
|
-
|
47
|
-
def _get_new_csrf_string():
|
48
|
-
return get_random_string(CSRF_SECRET_LENGTH, allowed_chars=CSRF_ALLOWED_CHARS)
|
49
|
-
|
50
|
-
|
51
|
-
def _mask_cipher_secret(secret):
|
52
|
-
"""
|
53
|
-
Given a secret (assumed to be a string of CSRF_ALLOWED_CHARS), generate a
|
54
|
-
token by adding a mask and applying it to the secret.
|
55
|
-
"""
|
56
|
-
mask = _get_new_csrf_string()
|
57
|
-
chars = CSRF_ALLOWED_CHARS
|
58
|
-
pairs = zip((chars.index(x) for x in secret), (chars.index(x) for x in mask))
|
59
|
-
cipher = "".join(chars[(x + y) % len(chars)] for x, y in pairs)
|
60
|
-
return mask + cipher
|
61
|
-
|
62
|
-
|
63
|
-
def _unmask_cipher_token(token):
|
64
|
-
"""
|
65
|
-
Given a token (assumed to be a string of CSRF_ALLOWED_CHARS, of length
|
66
|
-
CSRF_TOKEN_LENGTH, and that its first half is a mask), use it to decrypt
|
67
|
-
the second half to produce the original secret.
|
68
|
-
"""
|
69
|
-
mask = token[:CSRF_SECRET_LENGTH]
|
70
|
-
token = token[CSRF_SECRET_LENGTH:]
|
71
|
-
chars = CSRF_ALLOWED_CHARS
|
72
|
-
pairs = zip((chars.index(x) for x in token), (chars.index(x) for x in mask))
|
73
|
-
return "".join(chars[x - y] for x, y in pairs) # Note negative values are ok
|
74
|
-
|
75
|
-
|
76
|
-
def _add_new_csrf_cookie(request):
|
77
|
-
"""Generate a new random CSRF_COOKIE value, and add it to request.meta."""
|
78
|
-
csrf_secret = _get_new_csrf_string()
|
79
|
-
request.meta.update(
|
80
|
-
{
|
81
|
-
"CSRF_COOKIE": csrf_secret,
|
82
|
-
"CSRF_COOKIE_NEEDS_UPDATE": True,
|
83
|
-
}
|
84
|
-
)
|
85
|
-
return csrf_secret
|
86
|
-
|
87
|
-
|
88
|
-
def get_token(request):
|
89
|
-
"""
|
90
|
-
Return the CSRF token required for a POST form. The token is an
|
91
|
-
alphanumeric value. A new token is created if one is not already set.
|
92
|
-
|
93
|
-
A side effect of calling this function is to make the csrf_protect
|
94
|
-
decorator and the CsrfViewMiddleware add a CSRF cookie and a 'Vary: Cookie'
|
95
|
-
header to the outgoing response. For this reason, you may need to use this
|
96
|
-
function lazily, as is done by the csrf context processor.
|
97
|
-
"""
|
98
|
-
if "CSRF_COOKIE" in request.meta:
|
99
|
-
csrf_secret = request.meta["CSRF_COOKIE"]
|
100
|
-
# Since the cookie is being used, flag to send the cookie in
|
101
|
-
# process_response() (even if the client already has it) in order to
|
102
|
-
# renew the expiry timer.
|
103
|
-
request.meta["CSRF_COOKIE_NEEDS_UPDATE"] = True
|
104
|
-
else:
|
105
|
-
csrf_secret = _add_new_csrf_cookie(request)
|
106
|
-
return _mask_cipher_secret(csrf_secret)
|
107
8
|
|
9
|
+
from .views import CsrfFailureView
|
108
10
|
|
109
|
-
|
110
|
-
"""
|
111
|
-
Change the CSRF token in use for a request - should be done on login
|
112
|
-
for security purposes.
|
113
|
-
"""
|
114
|
-
_add_new_csrf_cookie(request)
|
115
|
-
|
116
|
-
|
117
|
-
class InvalidTokenFormat(Exception):
|
118
|
-
def __init__(self, reason):
|
119
|
-
self.reason = reason
|
120
|
-
|
121
|
-
|
122
|
-
def _check_token_format(token):
|
123
|
-
"""
|
124
|
-
Raise an InvalidTokenFormat error if the token has an invalid length or
|
125
|
-
characters that aren't allowed. The token argument can be a CSRF cookie
|
126
|
-
secret or non-cookie CSRF token, and either masked or unmasked.
|
127
|
-
"""
|
128
|
-
if len(token) not in (CSRF_TOKEN_LENGTH, CSRF_SECRET_LENGTH):
|
129
|
-
raise InvalidTokenFormat(REASON_INCORRECT_LENGTH)
|
130
|
-
# Make sure all characters are in CSRF_ALLOWED_CHARS.
|
131
|
-
if invalid_token_chars_re.search(token):
|
132
|
-
raise InvalidTokenFormat(REASON_INVALID_CHARACTERS)
|
133
|
-
|
134
|
-
|
135
|
-
def _does_token_match(request_csrf_token, csrf_secret):
|
136
|
-
"""
|
137
|
-
Return whether the given CSRF token matches the given CSRF secret, after
|
138
|
-
unmasking the token if necessary.
|
139
|
-
|
140
|
-
This function assumes that the request_csrf_token argument has been
|
141
|
-
validated to have the correct length (CSRF_SECRET_LENGTH or
|
142
|
-
CSRF_TOKEN_LENGTH characters) and allowed characters, and that if it has
|
143
|
-
length CSRF_TOKEN_LENGTH, it is a masked secret.
|
144
|
-
"""
|
145
|
-
# Only unmask tokens that are exactly CSRF_TOKEN_LENGTH characters long.
|
146
|
-
if len(request_csrf_token) == CSRF_TOKEN_LENGTH:
|
147
|
-
request_csrf_token = _unmask_cipher_token(request_csrf_token)
|
148
|
-
assert len(request_csrf_token) == CSRF_SECRET_LENGTH
|
149
|
-
return constant_time_compare(request_csrf_token, csrf_secret)
|
150
|
-
|
151
|
-
|
152
|
-
class RejectRequest(Exception):
|
153
|
-
def __init__(self, reason):
|
154
|
-
self.reason = reason
|
11
|
+
logger = logging.getLogger("plain.security.csrf")
|
155
12
|
|
156
13
|
|
157
14
|
class CsrfViewMiddleware:
|
158
15
|
"""
|
159
|
-
|
160
|
-
|
16
|
+
Modern CSRF protection middleware using Sec-Fetch-Site headers and origin validation.
|
17
|
+
Based on Filippo Valsorda's 2025 research (https://words.filippo.io/csrf/).
|
161
18
|
|
162
|
-
This
|
163
|
-
|
19
|
+
Note: This provides same-origin (not same-site) protection. Same-site origins
|
20
|
+
like subdomains can have different trust levels and are rejected.
|
164
21
|
"""
|
165
22
|
|
166
23
|
def __init__(self, get_response):
|
167
24
|
self.get_response = get_response
|
168
25
|
|
26
|
+
# Compile CSRF exempt patterns once for performance
|
27
|
+
self.csrf_exempt_patterns = [re.compile(r) for r in settings.CSRF_EXEMPT_PATHS]
|
28
|
+
|
169
29
|
def __call__(self, request):
|
170
|
-
|
171
|
-
|
172
|
-
|
173
|
-
|
30
|
+
allowed, reason = self.should_allow_request(request)
|
31
|
+
|
32
|
+
if allowed:
|
33
|
+
return self.get_response(request)
|
174
34
|
else:
|
175
|
-
|
176
|
-
|
177
|
-
|
178
|
-
|
179
|
-
|
180
|
-
|
35
|
+
return self.reject(request, reason)
|
36
|
+
|
37
|
+
def should_allow_request(self, request) -> tuple[bool, str]:
|
38
|
+
# 1. Allow safe methods (GET, HEAD, OPTIONS)
|
39
|
+
if request.method in ("GET", "HEAD", "OPTIONS"):
|
40
|
+
return True, f"Safe HTTP method: {request.method}"
|
41
|
+
|
42
|
+
# 2. Path-based exemption (regex patterns)
|
43
|
+
for pattern in self.csrf_exempt_patterns:
|
44
|
+
if pattern.search(request.path_info):
|
45
|
+
return (
|
46
|
+
True,
|
47
|
+
f"Path {request.path_info} matches exempt pattern {pattern.pattern}",
|
48
|
+
)
|
181
49
|
|
182
|
-
|
183
|
-
|
50
|
+
origin = request.headers.get("Origin")
|
51
|
+
sec_fetch_site = request.headers.get("Sec-Fetch-Site", "").lower()
|
184
52
|
|
185
|
-
|
53
|
+
# 3. Check trusted origins allow-list
|
186
54
|
|
187
|
-
if
|
188
|
-
|
189
|
-
# Unset the flag to prevent _set_csrf_cookie() from being
|
190
|
-
# unnecessarily called again in process_response() by other
|
191
|
-
# instances of CsrfViewMiddleware. This can happen e.g. when both a
|
192
|
-
# decorator and middleware are used. However,
|
193
|
-
# CSRF_COOKIE_NEEDS_UPDATE is still respected in subsequent calls
|
194
|
-
# e.g. in case rotate_token() is called in process_response() later
|
195
|
-
# by custom middleware but before those subsequent calls.
|
196
|
-
request.meta["CSRF_COOKIE_NEEDS_UPDATE"] = False
|
55
|
+
if origin and origin in settings.CSRF_TRUSTED_ORIGINS:
|
56
|
+
return True, f"Trusted origin: {origin}"
|
197
57
|
|
198
|
-
|
58
|
+
# 4. Primary protection: Check Sec-Fetch-Site header
|
59
|
+
if sec_fetch_site in ("same-origin", "none"):
|
60
|
+
return (
|
61
|
+
True,
|
62
|
+
f"Same-origin request from Sec-Fetch-Site: {sec_fetch_site}",
|
63
|
+
)
|
64
|
+
elif sec_fetch_site in ("cross-site", "same-site"):
|
65
|
+
return (
|
66
|
+
False,
|
67
|
+
f"Cross-origin request detected from Sec-Fetch-Site: {sec_fetch_site}",
|
68
|
+
)
|
199
69
|
|
200
|
-
|
201
|
-
|
202
|
-
|
203
|
-
|
204
|
-
|
205
|
-
|
70
|
+
# 5. No fetch metadata or Origin headers - allow (non-browser requests)
|
71
|
+
if not origin and not sec_fetch_site:
|
72
|
+
return (
|
73
|
+
True,
|
74
|
+
"No Origin or Sec-Fetch-Site header - likely non-browser or old browser",
|
75
|
+
)
|
76
|
+
|
77
|
+
# 6. Fallback: Origin vs Host comparison for older browsers
|
78
|
+
# Note: On pre-2023 browsers, HTTP→HTTPS transitions may cause mismatches
|
79
|
+
# (Origin shows :443, request sees :80 if TLS terminated upstream).
|
80
|
+
# HSTS helps here; otherwise add external origins to CSRF_TRUSTED_ORIGINS.
|
81
|
+
if origin == "null":
|
82
|
+
return False, "Cross-origin request detected - null Origin header"
|
83
|
+
|
84
|
+
try:
|
85
|
+
if (parsed_origin := urlparse(origin)) and (host := request.get_host()):
|
86
|
+
# Scheme-agnostic host:port comparison
|
87
|
+
origin_host = parsed_origin.hostname
|
88
|
+
origin_port = parsed_origin.port or (
|
89
|
+
80
|
90
|
+
if parsed_origin.scheme == "http"
|
91
|
+
else 443
|
92
|
+
if parsed_origin.scheme == "https"
|
93
|
+
else None
|
94
|
+
)
|
206
95
|
|
207
|
-
|
208
|
-
|
209
|
-
|
96
|
+
# Extract hostname from request host (similar to how we parse origin)
|
97
|
+
# Use a fake scheme since we only care about host parsing
|
98
|
+
parsed_host = urlparse(f"http://{host}")
|
99
|
+
request_host = parsed_host.hostname or host
|
100
|
+
request_port = request.get_port()
|
101
|
+
|
102
|
+
# Compare hostname and port (scheme-agnostic)
|
103
|
+
# Both origin_host and request_host are normalized by urlparse (IPv6 brackets stripped)
|
104
|
+
if origin_host and origin_port and request_host and request_port:
|
105
|
+
if (
|
106
|
+
origin_host.lower() == request_host.lower()
|
107
|
+
and origin_port == int(request_port)
|
108
|
+
):
|
109
|
+
return (
|
110
|
+
True,
|
111
|
+
f"Same-origin request - Origin {origin} matches Host {host}",
|
112
|
+
)
|
113
|
+
except (ValueError, DisallowedHost):
|
114
|
+
pass
|
210
115
|
|
211
|
-
|
212
|
-
|
213
|
-
|
214
|
-
|
215
|
-
|
216
|
-
"""
|
217
|
-
allowed_origin_subdomains = defaultdict(list)
|
218
|
-
for parsed in (
|
219
|
-
urlparse(origin)
|
220
|
-
for origin in settings.CSRF_TRUSTED_ORIGINS
|
221
|
-
if "*" in origin
|
222
|
-
):
|
223
|
-
allowed_origin_subdomains[parsed.scheme].append(parsed.netloc.lstrip("*"))
|
224
|
-
return allowed_origin_subdomains
|
116
|
+
# Origin present but doesn't match host
|
117
|
+
return (
|
118
|
+
False,
|
119
|
+
f"Cross-origin request detected - Origin {origin} does not match Host",
|
120
|
+
)
|
225
121
|
|
226
|
-
def
|
227
|
-
|
122
|
+
def reject(self, request, reason):
|
123
|
+
"""Reject a request with a 403 Forbidden response."""
|
228
124
|
|
229
125
|
response = CsrfFailureView.as_view()(request, reason=reason)
|
230
126
|
log_response(
|
@@ -236,210 +132,3 @@ class CsrfViewMiddleware:
|
|
236
132
|
logger=logger,
|
237
133
|
)
|
238
134
|
return response
|
239
|
-
|
240
|
-
def _get_secret(self, request):
|
241
|
-
"""
|
242
|
-
Return the CSRF secret originally associated with the request, or None
|
243
|
-
if it didn't have one.
|
244
|
-
|
245
|
-
If the CSRF_USE_SESSIONS setting is false, raises InvalidTokenFormat if
|
246
|
-
the request's secret has invalid characters or an invalid length.
|
247
|
-
"""
|
248
|
-
try:
|
249
|
-
csrf_secret = request.cookies[settings.CSRF_COOKIE_NAME]
|
250
|
-
except KeyError:
|
251
|
-
csrf_secret = None
|
252
|
-
else:
|
253
|
-
# This can raise InvalidTokenFormat.
|
254
|
-
_check_token_format(csrf_secret)
|
255
|
-
|
256
|
-
if csrf_secret is None:
|
257
|
-
return None
|
258
|
-
return csrf_secret
|
259
|
-
|
260
|
-
def _set_csrf_cookie(self, request, response):
|
261
|
-
response.set_cookie(
|
262
|
-
settings.CSRF_COOKIE_NAME,
|
263
|
-
request.meta["CSRF_COOKIE"],
|
264
|
-
max_age=settings.CSRF_COOKIE_AGE,
|
265
|
-
domain=settings.CSRF_COOKIE_DOMAIN,
|
266
|
-
path=settings.CSRF_COOKIE_PATH,
|
267
|
-
secure=settings.CSRF_COOKIE_SECURE,
|
268
|
-
httponly=settings.CSRF_COOKIE_HTTPONLY,
|
269
|
-
samesite=settings.CSRF_COOKIE_SAMESITE,
|
270
|
-
)
|
271
|
-
# Set the Vary header since content varies with the CSRF cookie.
|
272
|
-
patch_vary_headers(response, ("Cookie",))
|
273
|
-
|
274
|
-
def _origin_verified(self, request):
|
275
|
-
request_origin = request.meta["HTTP_ORIGIN"]
|
276
|
-
try:
|
277
|
-
good_host = request.get_host()
|
278
|
-
except DisallowedHost:
|
279
|
-
pass
|
280
|
-
else:
|
281
|
-
good_origin = "{}://{}".format(
|
282
|
-
"https" if request.is_https() else "http",
|
283
|
-
good_host,
|
284
|
-
)
|
285
|
-
if request_origin == good_origin:
|
286
|
-
return True
|
287
|
-
if request_origin in self.allowed_origins_exact:
|
288
|
-
return True
|
289
|
-
try:
|
290
|
-
parsed_origin = urlparse(request_origin)
|
291
|
-
except ValueError:
|
292
|
-
return False
|
293
|
-
request_scheme = parsed_origin.scheme
|
294
|
-
request_netloc = parsed_origin.netloc
|
295
|
-
return any(
|
296
|
-
is_same_domain(request_netloc, host)
|
297
|
-
for host in self.allowed_origin_subdomains.get(request_scheme, ())
|
298
|
-
)
|
299
|
-
|
300
|
-
def _check_referer(self, request):
|
301
|
-
referer = request.meta.get("HTTP_REFERER")
|
302
|
-
if referer is None:
|
303
|
-
raise RejectRequest(REASON_NO_REFERER)
|
304
|
-
|
305
|
-
try:
|
306
|
-
referer = urlparse(referer)
|
307
|
-
except ValueError:
|
308
|
-
raise RejectRequest(REASON_MALFORMED_REFERER)
|
309
|
-
|
310
|
-
# Make sure we have a valid URL for Referer.
|
311
|
-
if "" in (referer.scheme, referer.netloc):
|
312
|
-
raise RejectRequest(REASON_MALFORMED_REFERER)
|
313
|
-
|
314
|
-
# Ensure that our Referer is also secure.
|
315
|
-
if referer.scheme != "https":
|
316
|
-
raise RejectRequest(REASON_INSECURE_REFERER)
|
317
|
-
|
318
|
-
if any(
|
319
|
-
is_same_domain(referer.netloc, host)
|
320
|
-
for host in self.csrf_trusted_origins_hosts
|
321
|
-
):
|
322
|
-
return
|
323
|
-
# Allow matching the configured cookie domain.
|
324
|
-
good_referer = settings.CSRF_COOKIE_DOMAIN
|
325
|
-
if good_referer is None:
|
326
|
-
# If no cookie domain is configured, allow matching the current
|
327
|
-
# host:port exactly if it's permitted by ALLOWED_HOSTS.
|
328
|
-
try:
|
329
|
-
# request.get_host() includes the port.
|
330
|
-
good_referer = request.get_host()
|
331
|
-
except DisallowedHost:
|
332
|
-
raise RejectRequest(REASON_BAD_REFERER % referer.geturl())
|
333
|
-
else:
|
334
|
-
server_port = request.get_port()
|
335
|
-
if server_port not in ("443", "80"):
|
336
|
-
good_referer = f"{good_referer}:{server_port}"
|
337
|
-
|
338
|
-
if not is_same_domain(referer.netloc, good_referer):
|
339
|
-
raise RejectRequest(REASON_BAD_REFERER % referer.geturl())
|
340
|
-
|
341
|
-
def _bad_token_message(self, reason, token_source):
|
342
|
-
if token_source != "POST":
|
343
|
-
# Assume it is a settings.CSRF_HEADER_NAME value.
|
344
|
-
header_name = HttpHeaders.parse_header_name(token_source)
|
345
|
-
token_source = f"the {header_name!r} HTTP header"
|
346
|
-
return f"CSRF token from {token_source} {reason}."
|
347
|
-
|
348
|
-
def _check_token(self, request):
|
349
|
-
# Access csrf_secret via self._get_secret() as rotate_token() may have
|
350
|
-
# been called by an authentication middleware during the
|
351
|
-
# process_request() phase.
|
352
|
-
try:
|
353
|
-
csrf_secret = self._get_secret(request)
|
354
|
-
except InvalidTokenFormat as exc:
|
355
|
-
raise RejectRequest(f"CSRF cookie {exc.reason}.")
|
356
|
-
|
357
|
-
if csrf_secret is None:
|
358
|
-
# No CSRF cookie. For POST requests, we insist on a CSRF cookie,
|
359
|
-
# and in this way we can avoid all CSRF attacks, including login
|
360
|
-
# CSRF.
|
361
|
-
raise RejectRequest(REASON_NO_CSRF_COOKIE)
|
362
|
-
|
363
|
-
# Check non-cookie token for match.
|
364
|
-
request_csrf_token = ""
|
365
|
-
if request.method == "POST":
|
366
|
-
try:
|
367
|
-
request_csrf_token = request.data.get(settings.CSRF_FIELD_NAME, "")
|
368
|
-
except UnreadablePostError:
|
369
|
-
# Handle a broken connection before we've completed reading the
|
370
|
-
# POST data. process_view shouldn't raise any exceptions, so
|
371
|
-
# we'll ignore and serve the user a 403 (assuming they're still
|
372
|
-
# listening, which they probably aren't because of the error).
|
373
|
-
pass
|
374
|
-
|
375
|
-
if request_csrf_token == "":
|
376
|
-
# Fall back to X-CSRFToken, to make things easier for AJAX, and
|
377
|
-
# possible for PUT/DELETE.
|
378
|
-
try:
|
379
|
-
# This can have length CSRF_SECRET_LENGTH or CSRF_TOKEN_LENGTH,
|
380
|
-
# depending on whether the client obtained the token from
|
381
|
-
# the DOM or the cookie (and if the cookie, whether the cookie
|
382
|
-
# was masked or unmasked).
|
383
|
-
request_csrf_token = request.headers[settings.CSRF_HEADER_NAME]
|
384
|
-
except KeyError:
|
385
|
-
raise RejectRequest(REASON_CSRF_TOKEN_MISSING)
|
386
|
-
token_source = settings.CSRF_HEADER_NAME
|
387
|
-
else:
|
388
|
-
token_source = "POST"
|
389
|
-
|
390
|
-
try:
|
391
|
-
_check_token_format(request_csrf_token)
|
392
|
-
except InvalidTokenFormat as exc:
|
393
|
-
reason = self._bad_token_message(exc.reason, token_source)
|
394
|
-
raise RejectRequest(reason)
|
395
|
-
|
396
|
-
if not _does_token_match(request_csrf_token, csrf_secret):
|
397
|
-
reason = self._bad_token_message("incorrect", token_source)
|
398
|
-
raise RejectRequest(reason)
|
399
|
-
|
400
|
-
def _get_csrf_response(self, request):
|
401
|
-
# Wait until request.meta["CSRF_COOKIE"] has been manipulated before
|
402
|
-
# bailing out, so that get_token still works
|
403
|
-
if getattr(request, "csrf_exempt", True):
|
404
|
-
return None
|
405
|
-
|
406
|
-
# Assume that anything not defined as 'safe' by RFC 9110 needs protection
|
407
|
-
if request.method in ("GET", "HEAD", "OPTIONS", "TRACE"):
|
408
|
-
return None
|
409
|
-
|
410
|
-
# Reject the request if the Origin header doesn't match an allowed
|
411
|
-
# value.
|
412
|
-
if "HTTP_ORIGIN" in request.meta:
|
413
|
-
if not self._origin_verified(request):
|
414
|
-
return self._reject(
|
415
|
-
request, REASON_BAD_ORIGIN % request.meta["HTTP_ORIGIN"]
|
416
|
-
)
|
417
|
-
elif request.is_https():
|
418
|
-
# If the Origin header wasn't provided, reject HTTPS requests if
|
419
|
-
# the Referer header doesn't match an allowed value.
|
420
|
-
#
|
421
|
-
# Suppose user visits http://example.com/
|
422
|
-
# An active network attacker (man-in-the-middle, MITM) sends a
|
423
|
-
# POST form that targets https://example.com/detonate-bomb/ and
|
424
|
-
# submits it via JavaScript.
|
425
|
-
#
|
426
|
-
# The attacker will need to provide a CSRF cookie and token, but
|
427
|
-
# that's no problem for a MITM and the session-independent secret
|
428
|
-
# we're using. So the MITM can circumvent the CSRF protection. This
|
429
|
-
# is true for any HTTP connection, but anyone using HTTPS expects
|
430
|
-
# better! For this reason, for https://example.com/ we need
|
431
|
-
# additional protection that treats http://example.com/ as
|
432
|
-
# completely untrusted. Under HTTPS, Barth et al. found that the
|
433
|
-
# Referer header is missing for same-domain requests in only about
|
434
|
-
# 0.2% of cases or less, so we can use strict Referer checking.
|
435
|
-
try:
|
436
|
-
self._check_referer(request)
|
437
|
-
except RejectRequest as exc:
|
438
|
-
return self._reject(request, exc.reason)
|
439
|
-
|
440
|
-
try:
|
441
|
-
self._check_token(request)
|
442
|
-
except RejectRequest as exc:
|
443
|
-
return self._reject(request, exc.reason)
|
444
|
-
|
445
|
-
return None
|
plain/exceptions.py
CHANGED
@@ -6,6 +6,23 @@ import operator
|
|
6
6
|
|
7
7
|
from plain.utils.hashable import make_hashable
|
8
8
|
|
9
|
+
# MARK: Configuration and Registry
|
10
|
+
|
11
|
+
|
12
|
+
class PackageRegistryNotReady(Exception):
|
13
|
+
"""The plain.packages registry is not populated yet"""
|
14
|
+
|
15
|
+
pass
|
16
|
+
|
17
|
+
|
18
|
+
class ImproperlyConfigured(Exception):
|
19
|
+
"""Plain is somehow improperly configured"""
|
20
|
+
|
21
|
+
pass
|
22
|
+
|
23
|
+
|
24
|
+
# MARK: Model and Field Errors
|
25
|
+
|
9
26
|
|
10
27
|
class FieldDoesNotExist(Exception):
|
11
28
|
"""The requested model field does not exist"""
|
@@ -13,8 +30,8 @@ class FieldDoesNotExist(Exception):
|
|
13
30
|
pass
|
14
31
|
|
15
32
|
|
16
|
-
class
|
17
|
-
"""
|
33
|
+
class FieldError(Exception):
|
34
|
+
"""Some kind of problem with a model field."""
|
18
35
|
|
19
36
|
pass
|
20
37
|
|
@@ -31,6 +48,9 @@ class MultipleObjectsReturned(Exception):
|
|
31
48
|
pass
|
32
49
|
|
33
50
|
|
51
|
+
# MARK: Security and Suspicious Operations
|
52
|
+
|
53
|
+
|
34
54
|
class SuspiciousOperation(Exception):
|
35
55
|
"""The user did something suspicious"""
|
36
56
|
|
@@ -80,6 +100,9 @@ class RequestDataTooBig(SuspiciousOperation):
|
|
80
100
|
pass
|
81
101
|
|
82
102
|
|
103
|
+
# MARK: HTTP and Request Errors
|
104
|
+
|
105
|
+
|
83
106
|
class BadRequest(Exception):
|
84
107
|
"""The request is malformed and cannot be processed."""
|
85
108
|
|
@@ -92,17 +115,7 @@ class PermissionDenied(Exception):
|
|
92
115
|
pass
|
93
116
|
|
94
117
|
|
95
|
-
|
96
|
-
"""Plain is somehow improperly configured"""
|
97
|
-
|
98
|
-
pass
|
99
|
-
|
100
|
-
|
101
|
-
class FieldError(Exception):
|
102
|
-
"""Some kind of problem with a model field."""
|
103
|
-
|
104
|
-
pass
|
105
|
-
|
118
|
+
# MARK: Validation
|
106
119
|
|
107
120
|
NON_FIELD_ERRORS = "__all__"
|
108
121
|
|
@@ -205,6 +218,9 @@ class ValidationError(Exception):
|
|
205
218
|
return hash(tuple(sorted(self.error_list, key=operator.attrgetter("message"))))
|
206
219
|
|
207
220
|
|
221
|
+
# MARK: Database
|
222
|
+
|
223
|
+
|
208
224
|
class EmptyResultSet(Exception):
|
209
225
|
"""A database query predicate is impossible."""
|
210
226
|
|
plain/forms/README.md
CHANGED
@@ -12,7 +12,7 @@ class HttpsRedirectMiddleware:
|
|
12
12
|
self.https_redirect_enabled = settings.HTTPS_REDIRECT_ENABLED
|
13
13
|
self.https_redirect_host = settings.HTTPS_REDIRECT_HOST
|
14
14
|
self.https_redirect_exempt = [
|
15
|
-
re.compile(r) for r in settings.
|
15
|
+
re.compile(r) for r in settings.HTTPS_REDIRECT_EXEMPT_PATHS
|
16
16
|
]
|
17
17
|
|
18
18
|
def __call__(self, request):
|
@@ -26,11 +26,13 @@ class HttpsRedirectMiddleware:
|
|
26
26
|
return self.get_response(request)
|
27
27
|
|
28
28
|
def maybe_https_redirect(self, request):
|
29
|
-
path = request.path.lstrip("/")
|
30
29
|
if (
|
31
30
|
self.https_redirect_enabled
|
32
31
|
and not request.is_https()
|
33
|
-
and not any(
|
32
|
+
and not any(
|
33
|
+
pattern.search(request.path_info)
|
34
|
+
for pattern in self.https_redirect_exempt
|
35
|
+
)
|
34
36
|
):
|
35
37
|
host = self.https_redirect_host or request.get_host()
|
36
38
|
return ResponseRedirect(
|