plain 0.57.0__tar.gz → 0.59.0__tar.gz

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.
Files changed (173) hide show
  1. {plain-0.57.0 → plain-0.59.0}/PKG-INFO +1 -1
  2. {plain-0.57.0 → plain-0.59.0}/plain/CHANGELOG.md +28 -0
  3. {plain-0.57.0 → plain-0.59.0}/plain/cli/agent.py +6 -0
  4. {plain-0.57.0 → plain-0.59.0}/plain/cli/upgrade.py +1 -0
  5. plain-0.59.0/plain/csrf/README.md +75 -0
  6. plain-0.59.0/plain/csrf/middleware.py +134 -0
  7. {plain-0.57.0 → plain-0.59.0}/plain/exceptions.py +29 -13
  8. {plain-0.57.0 → plain-0.59.0}/plain/forms/README.md +0 -2
  9. {plain-0.57.0 → plain-0.59.0}/plain/internal/middleware/https.py +5 -3
  10. {plain-0.57.0 → plain-0.59.0}/plain/runtime/global_settings.py +51 -52
  11. plain-0.59.0/plain/runtime/utils.py +20 -0
  12. {plain-0.57.0 → plain-0.59.0}/plain/templates/README.md +0 -1
  13. {plain-0.57.0 → plain-0.59.0}/plain/test/client.py +2 -10
  14. {plain-0.57.0 → plain-0.59.0}/plain/views/README.md +0 -2
  15. {plain-0.57.0 → plain-0.59.0}/plain/views/objects.py +39 -66
  16. {plain-0.57.0 → plain-0.59.0}/plain/views/templates.py +6 -18
  17. {plain-0.57.0 → plain-0.59.0}/pyproject.toml +1 -1
  18. plain-0.59.0/tests/test_csrf.py +356 -0
  19. plain-0.57.0/plain/csrf/README.md +0 -23
  20. plain-0.57.0/plain/csrf/middleware.py +0 -445
  21. plain-0.57.0/plain/views/csrf.py +0 -4
  22. {plain-0.57.0 → plain-0.59.0}/.gitignore +0 -0
  23. {plain-0.57.0 → plain-0.59.0}/LICENSE +0 -0
  24. {plain-0.57.0 → plain-0.59.0}/README.md +0 -0
  25. {plain-0.57.0 → plain-0.59.0}/plain/README.md +0 -0
  26. {plain-0.57.0 → plain-0.59.0}/plain/__main__.py +0 -0
  27. {plain-0.57.0 → plain-0.59.0}/plain/assets/README.md +0 -0
  28. {plain-0.57.0 → plain-0.59.0}/plain/assets/__init__.py +0 -0
  29. {plain-0.57.0 → plain-0.59.0}/plain/assets/compile.py +0 -0
  30. {plain-0.57.0 → plain-0.59.0}/plain/assets/finders.py +0 -0
  31. {plain-0.57.0 → plain-0.59.0}/plain/assets/fingerprints.py +0 -0
  32. {plain-0.57.0 → plain-0.59.0}/plain/assets/urls.py +0 -0
  33. {plain-0.57.0 → plain-0.59.0}/plain/assets/views.py +0 -0
  34. {plain-0.57.0 → plain-0.59.0}/plain/chores/README.md +0 -0
  35. {plain-0.57.0 → plain-0.59.0}/plain/chores/__init__.py +0 -0
  36. {plain-0.57.0 → plain-0.59.0}/plain/chores/registry.py +0 -0
  37. {plain-0.57.0 → plain-0.59.0}/plain/cli/README.md +0 -0
  38. {plain-0.57.0 → plain-0.59.0}/plain/cli/__init__.py +0 -0
  39. {plain-0.57.0 → plain-0.59.0}/plain/cli/build.py +0 -0
  40. {plain-0.57.0 → plain-0.59.0}/plain/cli/changelog.py +0 -0
  41. {plain-0.57.0 → plain-0.59.0}/plain/cli/chores.py +0 -0
  42. {plain-0.57.0 → plain-0.59.0}/plain/cli/core.py +0 -0
  43. {plain-0.57.0 → plain-0.59.0}/plain/cli/docs.py +0 -0
  44. {plain-0.57.0 → plain-0.59.0}/plain/cli/formatting.py +0 -0
  45. {plain-0.57.0 → plain-0.59.0}/plain/cli/help.py +0 -0
  46. {plain-0.57.0 → plain-0.59.0}/plain/cli/install.py +0 -0
  47. {plain-0.57.0 → plain-0.59.0}/plain/cli/output.py +0 -0
  48. {plain-0.57.0 → plain-0.59.0}/plain/cli/preflight.py +0 -0
  49. {plain-0.57.0 → plain-0.59.0}/plain/cli/print.py +0 -0
  50. {plain-0.57.0 → plain-0.59.0}/plain/cli/registry.py +0 -0
  51. {plain-0.57.0 → plain-0.59.0}/plain/cli/scaffold.py +0 -0
  52. {plain-0.57.0 → plain-0.59.0}/plain/cli/settings.py +0 -0
  53. {plain-0.57.0 → plain-0.59.0}/plain/cli/shell.py +0 -0
  54. {plain-0.57.0 → plain-0.59.0}/plain/cli/startup.py +0 -0
  55. {plain-0.57.0 → plain-0.59.0}/plain/cli/urls.py +0 -0
  56. {plain-0.57.0 → plain-0.59.0}/plain/cli/utils.py +0 -0
  57. {plain-0.57.0 → plain-0.59.0}/plain/csrf/views.py +0 -0
  58. {plain-0.57.0 → plain-0.59.0}/plain/debug.py +0 -0
  59. {plain-0.57.0 → plain-0.59.0}/plain/forms/__init__.py +0 -0
  60. {plain-0.57.0 → plain-0.59.0}/plain/forms/boundfield.py +0 -0
  61. {plain-0.57.0 → plain-0.59.0}/plain/forms/exceptions.py +0 -0
  62. {plain-0.57.0 → plain-0.59.0}/plain/forms/fields.py +0 -0
  63. {plain-0.57.0 → plain-0.59.0}/plain/forms/forms.py +0 -0
  64. {plain-0.57.0 → plain-0.59.0}/plain/http/README.md +0 -0
  65. {plain-0.57.0 → plain-0.59.0}/plain/http/__init__.py +0 -0
  66. {plain-0.57.0 → plain-0.59.0}/plain/http/cookie.py +0 -0
  67. {plain-0.57.0 → plain-0.59.0}/plain/http/multipartparser.py +0 -0
  68. {plain-0.57.0 → plain-0.59.0}/plain/http/request.py +0 -0
  69. {plain-0.57.0 → plain-0.59.0}/plain/http/response.py +0 -0
  70. {plain-0.57.0 → plain-0.59.0}/plain/internal/__init__.py +0 -0
  71. {plain-0.57.0 → plain-0.59.0}/plain/internal/files/__init__.py +0 -0
  72. {plain-0.57.0 → plain-0.59.0}/plain/internal/files/base.py +0 -0
  73. {plain-0.57.0 → plain-0.59.0}/plain/internal/files/locks.py +0 -0
  74. {plain-0.57.0 → plain-0.59.0}/plain/internal/files/move.py +0 -0
  75. {plain-0.57.0 → plain-0.59.0}/plain/internal/files/temp.py +0 -0
  76. {plain-0.57.0 → plain-0.59.0}/plain/internal/files/uploadedfile.py +0 -0
  77. {plain-0.57.0 → plain-0.59.0}/plain/internal/files/uploadhandler.py +0 -0
  78. {plain-0.57.0 → plain-0.59.0}/plain/internal/files/utils.py +0 -0
  79. {plain-0.57.0 → plain-0.59.0}/plain/internal/handlers/__init__.py +0 -0
  80. {plain-0.57.0 → plain-0.59.0}/plain/internal/handlers/base.py +0 -0
  81. {plain-0.57.0 → plain-0.59.0}/plain/internal/handlers/exception.py +0 -0
  82. {plain-0.57.0 → plain-0.59.0}/plain/internal/handlers/wsgi.py +0 -0
  83. {plain-0.57.0 → plain-0.59.0}/plain/internal/middleware/__init__.py +0 -0
  84. {plain-0.57.0 → plain-0.59.0}/plain/internal/middleware/headers.py +0 -0
  85. {plain-0.57.0 → plain-0.59.0}/plain/internal/middleware/slash.py +0 -0
  86. {plain-0.57.0 → plain-0.59.0}/plain/json.py +0 -0
  87. {plain-0.57.0 → plain-0.59.0}/plain/logs/README.md +0 -0
  88. {plain-0.57.0 → plain-0.59.0}/plain/logs/__init__.py +0 -0
  89. {plain-0.57.0 → plain-0.59.0}/plain/logs/configure.py +0 -0
  90. {plain-0.57.0 → plain-0.59.0}/plain/logs/loggers.py +0 -0
  91. {plain-0.57.0 → plain-0.59.0}/plain/logs/utils.py +0 -0
  92. {plain-0.57.0 → plain-0.59.0}/plain/packages/README.md +0 -0
  93. {plain-0.57.0 → plain-0.59.0}/plain/packages/__init__.py +0 -0
  94. {plain-0.57.0 → plain-0.59.0}/plain/packages/config.py +0 -0
  95. {plain-0.57.0 → plain-0.59.0}/plain/packages/registry.py +0 -0
  96. {plain-0.57.0 → plain-0.59.0}/plain/paginator.py +0 -0
  97. {plain-0.57.0 → plain-0.59.0}/plain/preflight/README.md +0 -0
  98. {plain-0.57.0 → plain-0.59.0}/plain/preflight/__init__.py +0 -0
  99. {plain-0.57.0 → plain-0.59.0}/plain/preflight/files.py +0 -0
  100. {plain-0.57.0 → plain-0.59.0}/plain/preflight/messages.py +0 -0
  101. {plain-0.57.0 → plain-0.59.0}/plain/preflight/registry.py +0 -0
  102. {plain-0.57.0 → plain-0.59.0}/plain/preflight/security.py +0 -0
  103. {plain-0.57.0 → plain-0.59.0}/plain/preflight/urls.py +0 -0
  104. {plain-0.57.0 → plain-0.59.0}/plain/runtime/README.md +0 -0
  105. {plain-0.57.0 → plain-0.59.0}/plain/runtime/__init__.py +0 -0
  106. {plain-0.57.0 → plain-0.59.0}/plain/runtime/user_settings.py +0 -0
  107. {plain-0.57.0 → plain-0.59.0}/plain/signals/README.md +0 -0
  108. {plain-0.57.0 → plain-0.59.0}/plain/signals/__init__.py +0 -0
  109. {plain-0.57.0 → plain-0.59.0}/plain/signals/dispatch/__init__.py +0 -0
  110. {plain-0.57.0 → plain-0.59.0}/plain/signals/dispatch/dispatcher.py +0 -0
  111. {plain-0.57.0 → plain-0.59.0}/plain/signals/dispatch/license.txt +0 -0
  112. {plain-0.57.0 → plain-0.59.0}/plain/signing.py +0 -0
  113. {plain-0.57.0 → plain-0.59.0}/plain/templates/__init__.py +0 -0
  114. {plain-0.57.0 → plain-0.59.0}/plain/templates/core.py +0 -0
  115. {plain-0.57.0 → plain-0.59.0}/plain/templates/jinja/__init__.py +0 -0
  116. {plain-0.57.0 → plain-0.59.0}/plain/templates/jinja/environments.py +0 -0
  117. {plain-0.57.0 → plain-0.59.0}/plain/templates/jinja/extensions.py +0 -0
  118. {plain-0.57.0 → plain-0.59.0}/plain/templates/jinja/filters.py +0 -0
  119. {plain-0.57.0 → plain-0.59.0}/plain/templates/jinja/globals.py +0 -0
  120. {plain-0.57.0 → plain-0.59.0}/plain/test/README.md +0 -0
  121. {plain-0.57.0 → plain-0.59.0}/plain/test/__init__.py +0 -0
  122. {plain-0.57.0 → plain-0.59.0}/plain/test/encoding.py +0 -0
  123. {plain-0.57.0 → plain-0.59.0}/plain/test/exceptions.py +0 -0
  124. {plain-0.57.0 → plain-0.59.0}/plain/urls/README.md +0 -0
  125. {plain-0.57.0 → plain-0.59.0}/plain/urls/__init__.py +0 -0
  126. {plain-0.57.0 → plain-0.59.0}/plain/urls/converters.py +0 -0
  127. {plain-0.57.0 → plain-0.59.0}/plain/urls/exceptions.py +0 -0
  128. {plain-0.57.0 → plain-0.59.0}/plain/urls/patterns.py +0 -0
  129. {plain-0.57.0 → plain-0.59.0}/plain/urls/resolvers.py +0 -0
  130. {plain-0.57.0 → plain-0.59.0}/plain/urls/routers.py +0 -0
  131. {plain-0.57.0 → plain-0.59.0}/plain/urls/utils.py +0 -0
  132. {plain-0.57.0 → plain-0.59.0}/plain/utils/README.md +0 -0
  133. {plain-0.57.0 → plain-0.59.0}/plain/utils/__init__.py +0 -0
  134. {plain-0.57.0 → plain-0.59.0}/plain/utils/cache.py +0 -0
  135. {plain-0.57.0 → plain-0.59.0}/plain/utils/crypto.py +0 -0
  136. {plain-0.57.0 → plain-0.59.0}/plain/utils/datastructures.py +0 -0
  137. {plain-0.57.0 → plain-0.59.0}/plain/utils/dateparse.py +0 -0
  138. {plain-0.57.0 → plain-0.59.0}/plain/utils/deconstruct.py +0 -0
  139. {plain-0.57.0 → plain-0.59.0}/plain/utils/decorators.py +0 -0
  140. {plain-0.57.0 → plain-0.59.0}/plain/utils/duration.py +0 -0
  141. {plain-0.57.0 → plain-0.59.0}/plain/utils/encoding.py +0 -0
  142. {plain-0.57.0 → plain-0.59.0}/plain/utils/functional.py +0 -0
  143. {plain-0.57.0 → plain-0.59.0}/plain/utils/hashable.py +0 -0
  144. {plain-0.57.0 → plain-0.59.0}/plain/utils/html.py +0 -0
  145. {plain-0.57.0 → plain-0.59.0}/plain/utils/http.py +0 -0
  146. {plain-0.57.0 → plain-0.59.0}/plain/utils/inspect.py +0 -0
  147. {plain-0.57.0 → plain-0.59.0}/plain/utils/ipv6.py +0 -0
  148. {plain-0.57.0 → plain-0.59.0}/plain/utils/itercompat.py +0 -0
  149. {plain-0.57.0 → plain-0.59.0}/plain/utils/module_loading.py +0 -0
  150. {plain-0.57.0 → plain-0.59.0}/plain/utils/regex_helper.py +0 -0
  151. {plain-0.57.0 → plain-0.59.0}/plain/utils/safestring.py +0 -0
  152. {plain-0.57.0 → plain-0.59.0}/plain/utils/text.py +0 -0
  153. {plain-0.57.0 → plain-0.59.0}/plain/utils/timesince.py +0 -0
  154. {plain-0.57.0 → plain-0.59.0}/plain/utils/timezone.py +0 -0
  155. {plain-0.57.0 → plain-0.59.0}/plain/utils/tree.py +0 -0
  156. {plain-0.57.0 → plain-0.59.0}/plain/validators.py +0 -0
  157. {plain-0.57.0 → plain-0.59.0}/plain/views/__init__.py +0 -0
  158. {plain-0.57.0 → plain-0.59.0}/plain/views/base.py +0 -0
  159. {plain-0.57.0 → plain-0.59.0}/plain/views/errors.py +0 -0
  160. {plain-0.57.0 → plain-0.59.0}/plain/views/exceptions.py +0 -0
  161. {plain-0.57.0 → plain-0.59.0}/plain/views/forms.py +0 -0
  162. {plain-0.57.0 → plain-0.59.0}/plain/views/redirect.py +0 -0
  163. {plain-0.57.0 → plain-0.59.0}/plain/wsgi.py +0 -0
  164. {plain-0.57.0 → plain-0.59.0}/tests/.gitignore +0 -0
  165. {plain-0.57.0 → plain-0.59.0}/tests/app/.gitignore +0 -0
  166. {plain-0.57.0 → plain-0.59.0}/tests/app/settings.py +0 -0
  167. {plain-0.57.0 → plain-0.59.0}/tests/app/test/__init__.py +0 -0
  168. {plain-0.57.0 → plain-0.59.0}/tests/app/test/default_settings.py +0 -0
  169. {plain-0.57.0 → plain-0.59.0}/tests/app/urls.py +0 -0
  170. {plain-0.57.0 → plain-0.59.0}/tests/conftest.py +0 -0
  171. {plain-0.57.0 → plain-0.59.0}/tests/test_cli.py +0 -0
  172. {plain-0.57.0 → plain-0.59.0}/tests/test_runtime.py +0 -0
  173. {plain-0.57.0 → plain-0.59.0}/tests/test_wsgi.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: plain
3
- Version: 0.57.0
3
+ Version: 0.59.0
4
4
  Summary: A web framework for building products with Python.
5
5
  Author-email: Dave Gaeddert <dave.gaeddert@dropseed.dev>
6
6
  License-File: LICENSE
@@ -1,5 +1,33 @@
1
1
  # plain changelog
2
2
 
3
+ ## [0.59.0](https://github.com/dropseed/plain/releases/plain@0.59.0) (2025-08-22)
4
+
5
+ ### What's changed
6
+
7
+ - Added new `APP_NAME` setting that defaults to the project name from `pyproject.toml` ([1a4d60e](https://github.com/dropseed/plain/commit/1a4d60e787))
8
+ - Template views now validate that `get_template_names()` returns a list instead of a string ([428a64f](https://github.com/dropseed/plain/commit/428a64f8cc))
9
+ - Object views now use cached properties for `.object` and `.objects` to improve performance ([bd0507a](https://github.com/dropseed/plain/commit/bd0507a72c))
10
+ - Improved `plain upgrade` command to suggest using subagents when there are more than 3 package updates ([497c30d](https://github.com/dropseed/plain/commit/497c30d445))
11
+
12
+ ### Upgrade instructions
13
+
14
+ - In object views, `self.load_object()` is no longer necessary as `self.object` is now a cached property.
15
+
16
+ ## [0.58.0](https://github.com/dropseed/plain/releases/plain@0.58.0) (2025-08-19)
17
+
18
+ ### What's changed
19
+
20
+ - Complete rewrite of CSRF protection using modern Sec-Fetch-Site headers and origin validation ([955150800c](https://github.com/dropseed/plain/commit/955150800c))
21
+ - Replaced CSRF view mixin with path-based exemptions using `CSRF_EXEMPT_PATHS` setting ([2a50a9154e](https://github.com/dropseed/plain/commit/2a50a9154e))
22
+ - Renamed `HTTPS_REDIRECT_EXEMPT` to `HTTPS_REDIRECT_EXEMPT_PATHS` with leading slash requirement ([b53d3bb7a7](https://github.com/dropseed/plain/commit/b53d3bb7a7))
23
+ - Agent commands now print prompts directly when running in Claude Code or Codex Sandbox environments ([6eaed8ae3b](https://github.com/dropseed/plain/commit/6eaed8ae3b))
24
+
25
+ ### Upgrade instructions
26
+
27
+ - 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)
28
+ - Replace `HTTPS_REDIRECT_EXEMPT` with `HTTPS_REDIRECT_EXEMPT_PATHS` and ensure patterns include leading slash (ex. `[r"^/health$", r"/api/internal/.*"]`)
29
+ - Remove all CSRF cookie and token related settings - the new implementation doesn't use cookies or tokens (ex. `{{ csrf_input }}` and `{{ csrf_token }}`)
30
+
3
31
  ## [0.57.0](https://github.com/dropseed/plain/releases/plain@0.57.0) (2025-08-15)
4
32
 
5
33
  ### What's 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:
@@ -158,6 +158,7 @@ def build_prompt(before_after: dict[str, tuple[str | None, str | None]]) -> str:
158
158
  "",
159
159
  "3. **Available tools:**",
160
160
  " - Python shell: `uv run python`",
161
+ " - If you have a subagents feature and there are more than three packages here, use subagents",
161
162
  "",
162
163
  "4. **Workflow:**",
163
164
  " - Review changelog for each package → Apply changes → Move to next package",
@@ -0,0 +1,75 @@
1
+ # CSRF
2
+
3
+ **Cross-Site Request Forgery (CSRF) protection using modern request headers.**
4
+
5
+ - [Overview](#overview)
6
+ - [Usage](#usage)
7
+ - [CSRF Exempt Paths](#csrf-exempt-paths)
8
+ - [Trusted Origins](#trusted-origins)
9
+
10
+ ## Overview
11
+
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.
13
+
14
+ ## Usage
15
+
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.**
17
+
18
+ ## CSRF Exempt Paths
19
+
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
+ ]
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.
@@ -0,0 +1,134 @@
1
+ import logging
2
+ import re
3
+ from urllib.parse import urlparse
4
+
5
+ from plain.exceptions import DisallowedHost
6
+ from plain.logs import log_response
7
+ from plain.runtime import settings
8
+
9
+ from .views import CsrfFailureView
10
+
11
+ logger = logging.getLogger("plain.security.csrf")
12
+
13
+
14
+ class CsrfViewMiddleware:
15
+ """
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/).
18
+
19
+ Note: This provides same-origin (not same-site) protection. Same-site origins
20
+ like subdomains can have different trust levels and are rejected.
21
+ """
22
+
23
+ def __init__(self, get_response):
24
+ self.get_response = get_response
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
+
29
+ def __call__(self, request):
30
+ allowed, reason = self.should_allow_request(request)
31
+
32
+ if allowed:
33
+ return self.get_response(request)
34
+ else:
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
+ )
49
+
50
+ origin = request.headers.get("Origin")
51
+ sec_fetch_site = request.headers.get("Sec-Fetch-Site", "").lower()
52
+
53
+ # 3. Check trusted origins allow-list
54
+
55
+ if origin and origin in settings.CSRF_TRUSTED_ORIGINS:
56
+ return True, f"Trusted origin: {origin}"
57
+
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
+ )
69
+
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
+ )
95
+
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
115
+
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
+ )
121
+
122
+ def reject(self, request, reason):
123
+ """Reject a request with a 403 Forbidden response."""
124
+
125
+ response = CsrfFailureView.as_view()(request, reason=reason)
126
+ log_response(
127
+ "Forbidden (%s): %s",
128
+ reason,
129
+ request.path,
130
+ response=response,
131
+ request=request,
132
+ logger=logger,
133
+ )
134
+ return response
@@ -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 PackageRegistryNotReady(Exception):
17
- """The plain.packages registry is not populated yet"""
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
- class ImproperlyConfigured(Exception):
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
 
@@ -33,8 +33,6 @@ Then in your template, you can render the form fields.
33
33
  {% block content %}
34
34
 
35
35
  <form method="post">
36
- {{ csrf_input }}
37
-
38
36
  <!-- Render general form errors -->
39
37
  {% for error in form.non_field_errors %}
40
38
  <div>{{ error }}</div>
@@ -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.HTTPS_REDIRECT_EXEMPT
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(pattern.search(path) for pattern in self.https_redirect_exempt)
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(
@@ -3,31 +3,24 @@ Default Plain settings. Override these with settings in the module pointed to
3
3
  by the PLAIN_SETTINGS_MODULE environment variable.
4
4
  """
5
5
 
6
- ####################
7
- # CORE #
8
- ####################
6
+ from .utils import get_app_name_from_pyproject
7
+
8
+ # MARK: Core Settings
9
9
 
10
10
  DEBUG: bool = False
11
11
 
12
- # Hosts/domain names that are valid for this site.
13
- # "*" matches anything, ".example.com" matches example.com and all subdomains
14
- ALLOWED_HOSTS: list[str] = []
15
-
16
- # Local time zone for this installation. All choices can be found here:
17
- # https://en.wikipedia.org/wiki/List_of_tz_zones_by_name (although not all
18
- # systems may support all possibilities). This is interpreted as the default
19
- # user time zone.
20
- TIME_ZONE: str = "UTC"
21
-
22
- # Default charset to use for all Response objects, if a MIME type isn't
23
- # manually specified. It's used to construct the Content-Type header.
24
- DEFAULT_CHARSET = "utf-8"
12
+ APP_NAME: str = get_app_name_from_pyproject()
25
13
 
26
14
  # List of strings representing installed packages.
27
15
  INSTALLED_PACKAGES: list[str] = []
28
16
 
29
- # Whether to append trailing slashes to URLs.
30
- APPEND_SLASH = True
17
+ URLS_ROUTER: str
18
+
19
+ # MARK: HTTP and Security
20
+
21
+ # Hosts/domain names that are valid for this site.
22
+ # "*" matches anything, ".example.com" matches example.com and all subdomains
23
+ ALLOWED_HOSTS: list[str] = []
31
24
 
32
25
  # Default headers for all responses.
33
26
  DEFAULT_RESPONSE_HEADERS = {
@@ -42,7 +35,13 @@ DEFAULT_RESPONSE_HEADERS = {
42
35
 
43
36
  # Whether to redirect all non-HTTPS requests to HTTPS.
44
37
  HTTPS_REDIRECT_ENABLED = True
45
- HTTPS_REDIRECT_EXEMPT = []
38
+
39
+ # Regex patterns for paths that should be exempt from HTTPS redirect
40
+ # Examples: [r"^/health$", r"/api/internal/.*", r"/dev/.*"]
41
+ HTTPS_REDIRECT_EXEMPT_PATHS: list[str] = []
42
+
43
+ # Custom host to redirect to for HTTPS. If None, uses the same host as the request.
44
+ # Useful for redirecting to a different domain (e.g., "secure.example.com")
46
45
  HTTPS_REDIRECT_HOST = None
47
46
 
48
47
  # If your Plain app is behind a proxy that sets a header to specify secure
@@ -68,7 +67,24 @@ SECRET_KEY: str
68
67
  # secret key rotation.
69
68
  SECRET_KEY_FALLBACKS: list[str] = []
70
69
 
71
- URLS_ROUTER: str
70
+ # MARK: Internationalization
71
+
72
+ # Local time zone for this installation. All choices can be found here:
73
+ # https://en.wikipedia.org/wiki/List_of_tz_zones_by_name (although not all
74
+ # systems may support all possibilities). This is interpreted as the default
75
+ # user time zone.
76
+ TIME_ZONE: str = "UTC"
77
+
78
+ # Default charset to use for all Response objects, if a MIME type isn't
79
+ # manually specified. It's used to construct the Content-Type header.
80
+ DEFAULT_CHARSET = "utf-8"
81
+
82
+ # MARK: URL Configuration
83
+
84
+ # Whether to append trailing slashes to URLs.
85
+ APPEND_SLASH = True
86
+
87
+ # MARK: File Uploads
72
88
 
73
89
  # List of upload handler classes to be applied in order.
74
90
  FILE_UPLOAD_HANDLERS = [
@@ -100,41 +116,30 @@ FILE_UPLOAD_TEMP_DIR = None
100
116
  # User-defined overrides for error views by status code
101
117
  HTTP_ERROR_VIEWS: dict[int] = {}
102
118
 
103
- ##############
104
- # MIDDLEWARE #
105
- ##############
119
+ # MARK: Middleware
106
120
 
107
121
  # List of middleware to use. Order is important; in the request phase, these
108
122
  # middleware will be applied in the order given, and in the response
109
123
  # phase the middleware will be applied in reverse order.
110
124
  MIDDLEWARE: list[str] = []
111
125
 
112
- ########
113
- # CSRF #
114
- ########
115
-
116
- # Settings for CSRF cookie.
117
- CSRF_COOKIE_NAME = "csrftoken"
118
- CSRF_COOKIE_AGE = 60 * 60 * 24 * 7 * 52 # 1 year
119
- CSRF_COOKIE_DOMAIN = None
120
- CSRF_COOKIE_PATH = "/"
121
- CSRF_COOKIE_SECURE = True
122
- CSRF_COOKIE_HTTPONLY = False
123
- CSRF_COOKIE_SAMESITE = "Lax"
124
- CSRF_HEADER_NAME = "CSRF-Token"
125
- CSRF_FIELD_NAME = "_csrftoken"
126
+ # MARK: CSRF
127
+
128
+ # A list of trusted origins for unsafe (POST/PUT/DELETE etc.) requests.
129
+ # These origins will be allowed regardless of the normal CSRF checks.
130
+ # Each origin should be a full origin like "https://example.com" or "https://sub.example.com:8080"
126
131
  CSRF_TRUSTED_ORIGINS: list[str] = []
127
132
 
128
- ###########
129
- # LOGGING #
130
- ###########
133
+ # Regex patterns for paths that should be exempt from CSRF protection
134
+ # Examples: [r"^/api/", r"/webhooks/.*", r"/health$"]
135
+ CSRF_EXEMPT_PATHS: list[str] = []
136
+
137
+ # MARK: Logging
131
138
 
132
139
  # Custom logging configuration.
133
140
  LOGGING = {}
134
141
 
135
- ###############
136
- # ASSETS #
137
- ###############
142
+ # MARK: Assets
138
143
 
139
144
  # Whether to redirect the original asset path to the fingerprinted path.
140
145
  ASSETS_REDIRECT_ORIGINAL = True
@@ -143,9 +148,7 @@ ASSETS_REDIRECT_ORIGINAL = True
143
148
  # Ex. "https://cdn.example.com/assets/"
144
149
  ASSETS_BASE_URL: str = ""
145
150
 
146
- ####################
147
- # PREFLIGHT CHECKS #
148
- ####################
151
+ # MARK: Preflight Checks
149
152
 
150
153
  # List of all issues generated by system checks that should be silenced. Light
151
154
  # issues like warnings, infos or debugs will not generate a message. Silencing
@@ -153,14 +156,10 @@ ASSETS_BASE_URL: str = ""
153
156
  # message, but Plain will not stop you from e.g. running server.
154
157
  PREFLIGHT_SILENCED_CHECKS = []
155
158
 
156
- #############
157
- # Templates #
158
- #############
159
+ # MARK: Templates
159
160
 
160
161
  TEMPLATES_JINJA_ENVIRONMENT = "plain.templates.jinja.DefaultEnvironment"
161
162
 
162
- #########
163
- # Shell #
164
- #########
163
+ # MARK: Shell
165
164
 
166
165
  SHELL_IMPORT: str = ""
@@ -0,0 +1,20 @@
1
+ import tomllib
2
+ from pathlib import Path
3
+
4
+
5
+ def get_app_name_from_pyproject():
6
+ """Get the project name from the nearest pyproject.toml file."""
7
+ current_path = Path.cwd()
8
+
9
+ # Walk up the directory tree looking for pyproject.toml
10
+ for path in [current_path] + list(current_path.parents):
11
+ pyproject_path = path / "pyproject.toml"
12
+ if pyproject_path.exists():
13
+ try:
14
+ with pyproject_path.open("rb") as f:
15
+ pyproject = tomllib.load(f)
16
+ return pyproject.get("project", {}).get("name", "App")
17
+ except (tomllib.TOMLDecodeError, OSError):
18
+ continue
19
+
20
+ return "App"
@@ -70,7 +70,6 @@ class HTMXJSExtension(InclusionTagExtension):
70
70
 
71
71
  def get_context(self, context, *args, **kwargs):
72
72
  return {
73
- "csrf_token": context["csrf_token"],
74
73
  "DEBUG": settings.DEBUG,
75
74
  "extensions": kwargs.get("extensions", []),
76
75
  }
@@ -114,8 +114,7 @@ class ClientHandler(BaseHandler):
114
114
  the originating WSGIRequest attached to its ``wsgi_request`` attribute.
115
115
  """
116
116
 
117
- def __init__(self, enforce_csrf_checks=True, *args, **kwargs):
118
- self.enforce_csrf_checks = enforce_csrf_checks
117
+ def __init__(self, *args, **kwargs):
119
118
  super().__init__(*args, **kwargs)
120
119
 
121
120
  def __call__(self, environ):
@@ -126,12 +125,6 @@ class ClientHandler(BaseHandler):
126
125
 
127
126
  request_started.send(sender=self.__class__, environ=environ)
128
127
  request = WSGIRequest(environ)
129
- # sneaky little hack so that we can easily get round
130
- # CsrfViewMiddleware. This makes life easier, and is probably
131
- # required for backwards compatibility with external tests against
132
- # admin views.
133
- if not self.enforce_csrf_checks:
134
- request.csrf_exempt = True
135
128
 
136
129
  # Request goes through middleware.
137
130
  response = self.get_response(request)
@@ -420,14 +413,13 @@ class Client(RequestFactory):
420
413
 
421
414
  def __init__(
422
415
  self,
423
- enforce_csrf_checks=False,
424
416
  raise_request_exception=True,
425
417
  *,
426
418
  headers=None,
427
419
  **defaults,
428
420
  ):
429
421
  super().__init__(headers=headers, **defaults)
430
- self.handler = ClientHandler(enforce_csrf_checks)
422
+ self.handler = ClientHandler()
431
423
  self.raise_request_exception = raise_request_exception
432
424
  self.exc_info = None
433
425
  self.extra = None
@@ -142,8 +142,6 @@ Rendering forms is done directly in the HTML.
142
142
  {% block content %}
143
143
 
144
144
  <form method="post">
145
- {{ csrf_input }}
146
-
147
145
  <!-- Render general form errors -->
148
146
  {% for error in form.non_field_errors %}
149
147
  <div>{{ error }}</div>