plain 0.56.1__py3-none-any.whl → 0.58.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 CHANGED
@@ -1,5 +1,35 @@
1
1
  # plain changelog
2
2
 
3
+ ## [0.58.0](https://github.com/dropseed/plain/releases/plain@0.58.0) (2025-08-19)
4
+
5
+ ### What's changed
6
+
7
+ - Complete rewrite of CSRF protection using modern Sec-Fetch-Site headers and origin validation ([955150800c](https://github.com/dropseed/plain/commit/955150800c))
8
+ - Replaced CSRF view mixin with path-based exemptions using `CSRF_EXEMPT_PATHS` setting ([2a50a9154e](https://github.com/dropseed/plain/commit/2a50a9154e))
9
+ - Renamed `HTTPS_REDIRECT_EXEMPT` to `HTTPS_REDIRECT_EXEMPT_PATHS` with leading slash requirement ([b53d3bb7a7](https://github.com/dropseed/plain/commit/b53d3bb7a7))
10
+ - Agent commands now print prompts directly when running in Claude Code or Codex Sandbox environments ([6eaed8ae3b](https://github.com/dropseed/plain/commit/6eaed8ae3b))
11
+
12
+ ### Upgrade instructions
13
+
14
+ - Remove any usage of `CsrfExemptViewMixin` and `request.csrf_exempt` and add exempt paths to the `CSRF_EXEMPT_PATHS` setting instead (ex. `CSRF_EXEMPT_PATHS = [r"^/api/", r"/webhooks/.*"]` -- but consider first whether the view still needs CSRF exemption under the new implementation)
15
+ - Replace `HTTPS_REDIRECT_EXEMPT` with `HTTPS_REDIRECT_EXEMPT_PATHS` and ensure patterns include leading slash (ex. `[r"^/health$", r"/api/internal/.*"]`)
16
+ - Remove all CSRF cookie and token related settings - the new implementation doesn't use cookies or tokens (ex. `{{ csrf_input }}` and `{{ csrf_token }}`)
17
+
18
+ ## [0.57.0](https://github.com/dropseed/plain/releases/plain@0.57.0) (2025-08-15)
19
+
20
+ ### What's changed
21
+
22
+ - The `ResponsePermanentRedirect` class has been removed; use `ResponseRedirect` with `status_code=301` instead ([d5735ea](https://github.com/dropseed/plain/commit/d5735ea4f8))
23
+ - The `RedirectView.permanent` attribute has been replaced with `status_code` for more flexible redirect status codes ([12dda16](https://github.com/dropseed/plain/commit/12dda16731))
24
+ - Updated `RedirectView` initialization parameters: `url_name` replaces `pattern_name`, `preserve_query_params` replaces `query_string`, and removed 410 Gone functionality ([3b9ca71](https://github.com/dropseed/plain/commit/3b9ca713bf))
25
+
26
+ ### Upgrade instructions
27
+
28
+ - Replace `ResponsePermanentRedirect` imports with `ResponseRedirect` and pass `status_code=301` to the constructor
29
+ - Update `RedirectView` subclasses to use `status_code=301` instead of `permanent=True`
30
+ - Replace `pattern_name` with `url_name` in RedirectView usage
31
+ - Replace `query_string=True` with `preserve_query_params=True` in RedirectView usage
32
+
3
33
  ## [0.56.1](https://github.com/dropseed/plain/releases/plain@0.56.1) (2025-07-30)
4
34
 
5
35
  ### What's changed
plain/cli/agent.py CHANGED
@@ -1,3 +1,4 @@
1
+ import os
1
2
  import shlex
2
3
  import subprocess
3
4
 
@@ -20,6 +21,11 @@ def prompt_agent(
20
21
  True if the agent command succeeded (or no agent command was provided),
21
22
  False if the agent command failed.
22
23
  """
24
+ # Check if running inside an agent and just print the prompt if so
25
+ if os.environ.get("CLAUDECODE") or os.environ.get("CODEX_SANDBOX"):
26
+ click.echo(prompt)
27
+ return True
28
+
23
29
  if print_only or not agent_command:
24
30
  click.echo(prompt)
25
31
  if not print_only:
plain/csrf/README.md CHANGED
@@ -1,23 +1,75 @@
1
1
  # CSRF
2
2
 
3
- **Cross-Site Request Forgery (CSRF) protection.**
3
+ **Cross-Site Request Forgery (CSRF) protection using modern request headers.**
4
4
 
5
5
  - [Overview](#overview)
6
6
  - [Usage](#usage)
7
+ - [CSRF Exempt Paths](#csrf-exempt-paths)
8
+ - [Trusted Origins](#trusted-origins)
7
9
 
8
10
  ## Overview
9
11
 
10
- Plain protects against [CSRF attacks](https://en.wikipedia.org/wiki/Cross-site_request_forgery) through a [middleware](./middleware.py#CsrfViewMiddleware) that compares the generated `csrftoken` cookie with the CSRF token from the request (either `_csrftoken` in form data or the `CSRF-Token` header).
12
+ Plain provides modern CSRF protection based on [Filippo Valsorda's 2025 research](https://words.filippo.io/csrf/) using `Sec-Fetch-Site` headers and origin validation.
11
13
 
12
14
  ## Usage
13
15
 
14
- The `CsrfViewMiddleware` is [automatically installed](../internal/handlers/base.py#BUILTIN_BEFORE_MIDDLEWARE), so you don't need to add it to your `settings.MIDDLEWARE`.
16
+ The `CsrfViewMiddleware` is [automatically installed](../internal/handlers/base.py#BUILTIN_BEFORE_MIDDLEWARE) and works transparently. **No changes to your forms or templates are needed.**
15
17
 
16
- When you use HTML forms, you should include the CSRF token in the form data via a hidden input:
18
+ ## CSRF Exempt Paths
17
19
 
18
- ```html
19
- <form method="post">
20
- {{ csrf_input }}
21
- <!-- other form fields here -->
22
- </form>
20
+ In some cases, you may need to disable CSRF protection for specific paths (like API endpoints or webhooks). Configure exempt paths using regex patterns in your settings:
21
+
22
+ ```python
23
+ # settings.py
24
+ CSRF_EXEMPT_PATHS = [
25
+ r"^/api/", # All API endpoints
26
+ r"^/api/v\d+/", # Versioned APIs: /api/v1/, /api/v2/, etc.
27
+ r"/webhooks/.*", # All webhook paths
28
+ r"/webhooks/github/", # Specific webhook
29
+ r"/health$", # Exact match for /health endpoint
30
+ ]
23
31
  ```
32
+
33
+ **Pattern Matching**: Exempt paths use Python regex patterns with `re.search()` against the full URL path including the leading slash.
34
+
35
+ **Examples:**
36
+
37
+ - `r"^/api/"` - matches `/api/users/`, `/api/posts/`
38
+ - `r"/webhooks/.*"` - matches `/webhooks/github/push`, `/webhooks/stripe/payment`
39
+ - `r"/health$"` - matches `/health` but not `/health-check`
40
+ - `r"^/api/v\d+/"` - matches `/api/v1/users/`, `/api/v2/posts/`
41
+
42
+ **Common Use Cases:**
43
+
44
+ ```python
45
+ CSRF_EXEMPT_PATHS = [
46
+ # API endpoints (often consumed by JavaScript/mobile apps)
47
+ r"^/api/",
48
+
49
+ # Webhooks (external services posting data)
50
+ r"/webhooks/.*",
51
+
52
+ # Health checks and monitoring
53
+ r"/health$",
54
+ r"/status$",
55
+ r"/metrics$",
56
+
57
+ # File uploads (if using direct POST)
58
+ r"/upload/",
59
+ ]
60
+ ```
61
+
62
+ ## Trusted Origins
63
+
64
+ In some cases, you may need to allow requests from specific external origins (like API clients or mobile apps). You can configure trusted origins in your settings:
65
+
66
+ ```python
67
+ # settings.py
68
+ CSRF_TRUSTED_ORIGINS = [
69
+ "https://api.example.com",
70
+ "https://mobile.example.com:8443",
71
+ "https://trusted-partner.com",
72
+ ]
73
+ ```
74
+
75
+ **Important**: Trusted origins bypass **all** CSRF protection. Only add origins you completely trust, as they can make requests that appear to come from your users.
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 string
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
- def rotate_token(request):
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
- Require a present and correct _csrftoken for POST requests that
160
- have a CSRF cookie, and set an outgoing CSRF cookie.
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 middleware should be used in conjunction with the {% csrf_token %}
163
- template tag.
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
- try:
171
- csrf_secret = self._get_secret(request)
172
- except InvalidTokenFormat:
173
- _add_new_csrf_cookie(request)
30
+ allowed, reason = self.should_allow_request(request)
31
+
32
+ if allowed:
33
+ return self.get_response(request)
174
34
  else:
175
- if csrf_secret is not None:
176
- # Use the same secret next time. If the secret was originally
177
- # masked, this also causes it to be replaced with the unmasked
178
- # form, but only in cases where the secret is already getting
179
- # saved anyways.
180
- request.meta["CSRF_COOKIE"] = csrf_secret
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
- if csrf_response := self._get_csrf_response(request):
183
- return csrf_response
50
+ origin = request.headers.get("Origin")
51
+ sec_fetch_site = request.headers.get("Sec-Fetch-Site", "").lower()
184
52
 
185
- response = self.get_response(request)
53
+ # 3. Check trusted origins allow-list
186
54
 
187
- if request.meta.get("CSRF_COOKIE_NEEDS_UPDATE"):
188
- self._set_csrf_cookie(request, response)
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
- return response
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
- @cached_property
201
- def csrf_trusted_origins_hosts(self):
202
- return [
203
- urlparse(origin).netloc.lstrip("*")
204
- for origin in settings.CSRF_TRUSTED_ORIGINS
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
- @cached_property
208
- def allowed_origins_exact(self):
209
- return {origin for origin in settings.CSRF_TRUSTED_ORIGINS if "*" not in origin}
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
- @cached_property
212
- def allowed_origin_subdomains(self):
213
- """
214
- A mapping of allowed schemes to list of allowed netlocs, where all
215
- subdomains of the netloc are allowed.
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 _reject(self, request, reason):
227
- from .views import CsrfFailureView
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