spiderweb-framework 0.12.0__tar.gz → 1.0.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 (38) hide show
  1. spiderweb_framework-1.0.0/LICENSE.txt +48 -0
  2. {spiderweb_framework-0.12.0 → spiderweb_framework-1.0.0}/PKG-INFO +39 -25
  3. spiderweb_framework-1.0.0/README.md +78 -0
  4. {spiderweb_framework-0.12.0 → spiderweb_framework-1.0.0}/pyproject.toml +1 -1
  5. spiderweb_framework-1.0.0/spiderweb/constants.py +27 -0
  6. {spiderweb_framework-0.12.0 → spiderweb_framework-1.0.0}/spiderweb/exceptions.py +4 -0
  7. {spiderweb_framework-0.12.0 → spiderweb_framework-1.0.0}/spiderweb/main.py +75 -20
  8. {spiderweb_framework-0.12.0 → spiderweb_framework-1.0.0}/spiderweb/middleware/__init__.py +13 -2
  9. spiderweb_framework-1.0.0/spiderweb/middleware/cors.py +158 -0
  10. {spiderweb_framework-0.12.0 → spiderweb_framework-1.0.0}/spiderweb/middleware/csrf.py +67 -16
  11. {spiderweb_framework-0.12.0 → spiderweb_framework-1.0.0}/spiderweb/request.py +13 -8
  12. {spiderweb_framework-0.12.0 → spiderweb_framework-1.0.0}/spiderweb/response.py +13 -10
  13. {spiderweb_framework-0.12.0 → spiderweb_framework-1.0.0}/spiderweb/routes.py +2 -2
  14. {spiderweb_framework-0.12.0 → spiderweb_framework-1.0.0}/spiderweb/tests/helpers.py +5 -3
  15. {spiderweb_framework-0.12.0 → spiderweb_framework-1.0.0}/spiderweb/tests/middleware.py +5 -0
  16. spiderweb_framework-1.0.0/spiderweb/tests/test_middleware.py +734 -0
  17. {spiderweb_framework-0.12.0 → spiderweb_framework-1.0.0}/spiderweb/tests/test_responses.py +7 -13
  18. {spiderweb_framework-0.12.0 → spiderweb_framework-1.0.0}/spiderweb/tests/views_for_tests.py +9 -0
  19. {spiderweb_framework-0.12.0 → spiderweb_framework-1.0.0}/spiderweb/utils.py +44 -0
  20. spiderweb_framework-0.12.0/LICENSE.txt +0 -21
  21. spiderweb_framework-0.12.0/README.md +0 -64
  22. spiderweb_framework-0.12.0/spiderweb/constants.py +0 -10
  23. spiderweb_framework-0.12.0/spiderweb/tests/test_middleware.py +0 -256
  24. {spiderweb_framework-0.12.0 → spiderweb_framework-1.0.0}/spiderweb/__init__.py +0 -0
  25. {spiderweb_framework-0.12.0 → spiderweb_framework-1.0.0}/spiderweb/converters.py +0 -0
  26. {spiderweb_framework-0.12.0 → spiderweb_framework-1.0.0}/spiderweb/db.py +0 -0
  27. {spiderweb_framework-0.12.0 → spiderweb_framework-1.0.0}/spiderweb/decorators.py +0 -0
  28. {spiderweb_framework-0.12.0 → spiderweb_framework-1.0.0}/spiderweb/default_views.py +0 -0
  29. {spiderweb_framework-0.12.0 → spiderweb_framework-1.0.0}/spiderweb/example_validator.py +0 -0
  30. {spiderweb_framework-0.12.0 → spiderweb_framework-1.0.0}/spiderweb/local_server.py +0 -0
  31. {spiderweb_framework-0.12.0 → spiderweb_framework-1.0.0}/spiderweb/middleware/base.py +0 -0
  32. {spiderweb_framework-0.12.0 → spiderweb_framework-1.0.0}/spiderweb/middleware/pydantic.py +0 -0
  33. {spiderweb_framework-0.12.0 → spiderweb_framework-1.0.0}/spiderweb/middleware/sessions.py +0 -0
  34. {spiderweb_framework-0.12.0 → spiderweb_framework-1.0.0}/spiderweb/secrets.py +0 -0
  35. {spiderweb_framework-0.12.0 → spiderweb_framework-1.0.0}/spiderweb/server_checks.py +0 -0
  36. {spiderweb_framework-0.12.0 → spiderweb_framework-1.0.0}/spiderweb/tests/__init__.py +0 -0
  37. {spiderweb_framework-0.12.0 → spiderweb_framework-1.0.0}/spiderweb/tests/test.html +0 -0
  38. {spiderweb_framework-0.12.0 → spiderweb_framework-1.0.0}/spiderweb/tests/test_variable_urls.py +0 -0
@@ -0,0 +1,48 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Joe Kaufeld
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
22
+
23
+ ---
24
+
25
+ Substantial portions of spiderweb/middleware/cors.py and docs/middleware/cors.md
26
+ are from django-cors-headers and are subject to the following license:
27
+
28
+ MIT License
29
+
30
+ Copyright (c) 2017 Otto Yiu (https://ottoyiu.com) and other contributors.
31
+
32
+ Permission is hereby granted, free of charge, to any person obtaining a copy
33
+ of this software and associated documentation files (the "Software"), to deal
34
+ in the Software without restriction, including without limitation the rights
35
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
36
+ copies of the Software, and to permit persons to whom the Software is
37
+ furnished to do so, subject to the following conditions:
38
+
39
+ The above copyright notice and this permission notice shall be included in all
40
+ copies or substantial portions of the Software.
41
+
42
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
43
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
44
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
45
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
46
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
47
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
48
+ SOFTWARE.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: spiderweb-framework
3
- Version: 0.12.0
3
+ Version: 1.0.0
4
4
  Summary: A small web framework, just big enough for a spider.
5
5
  License: LICENSE.txt
6
6
  Author: Joe Kaufeld
@@ -12,8 +12,8 @@ Classifier: Intended Audience :: Developers
12
12
  Classifier: License :: Other/Proprietary License
13
13
  Classifier: Programming Language :: Python :: 3
14
14
  Classifier: Programming Language :: Python :: 3.11
15
- Classifier: Programming Language :: Python :: 3.12
16
15
  Classifier: Programming Language :: Python :: 3 :: Only
16
+ Classifier: Programming Language :: Python :: 3.12
17
17
  Classifier: Programming Language :: Python :: 3.13
18
18
  Classifier: Topic :: Internet :: WWW/HTTP :: HTTP Servers
19
19
  Classifier: Topic :: Internet :: WWW/HTTP :: WSGI
@@ -28,6 +28,21 @@ Description-Content-Type: text/markdown
28
28
 
29
29
  # spiderweb
30
30
 
31
+ <p align="center">
32
+ <img
33
+ src="https://img.shields.io/pypi/v/spiderweb-framework.svg?style=for-the-badge"
34
+ alt="PyPI release version for Spiderweb"
35
+ />
36
+ <img
37
+ src="https://img.shields.io/badge/gitmoji-%20😜%20😍-FFDD67.svg?style=for-the-badge"
38
+ alt="Gitmoji"
39
+ />
40
+ <img
41
+ src="https://img.shields.io/badge/code%20style-black-000000.svg?style=for-the-badge"
42
+ alt="Code style: Black"
43
+ />
44
+ </p>
45
+
31
46
  As a professional web developer focusing on arcane uses of Django for arcane purposes, it occurred to me a little while ago that I didn't actually know how a web framework _worked_.
32
47
 
33
48
  So I built one.
@@ -54,6 +69,8 @@ if __name__ == "__main__":
54
69
  app.start()
55
70
  ```
56
71
 
72
+ ## [View the docs here!](https://itsthejoker.github.io/spiderweb/#/)
73
+
57
74
  My goal with this framework was to do three things:
58
75
 
59
76
  1. Learn a lot
@@ -62,31 +79,28 @@ My goal with this framework was to do three things:
62
79
 
63
80
  And, honestly, I think I got there. Here's a non-exhaustive list of things this can do:
64
81
 
65
- * Function-based views
66
- * Optional Flask-style URL routing
67
- * Optional Django-style URL routing
68
- * URLs with variables in them a lá Django
69
- * Gunicorn support
70
- * Full middleware implementation
71
- * Limit routes by HTTP verbs
72
- * Custom error routes
73
- * Built-in dev server
74
- * HTML templates with Jinja2
75
- * Static files support
76
- * Cookies (reading and setting)
77
- * Optional append_slash (with automatic redirects!)
78
- * ~~CSRF middleware implementation~~ (it's there, but it's crappy and unsafe. I'm working on it.)
79
- * Optional POST data validation middleware with Pydantic
80
- * Database support (using Peewee, but the end user can use whatever they want as long as there's a Peewee driver for it)
81
- * Session middleware
82
-
83
- The TODO list:
84
-
85
- * Tests (important)
86
- * Fix CSRF middleware
82
+ - Function-based views
83
+ - Optional Flask-style URL routing
84
+ - Optional Django-style URL routing
85
+ - URLs with variables in them a lá Django
86
+ - Full middleware implementation
87
+ - Limit routes by HTTP verbs
88
+ - Custom error routes
89
+ - Built-in dev server
90
+ - Gunicorn support
91
+ - HTML templates with Jinja2
92
+ - Static files support
93
+ - Cookies (reading and setting)
94
+ - Optional append_slash (with automatic redirects!)
95
+ - CSRF middleware
96
+ - CORS middleware
97
+ - Optional POST data validation middleware with Pydantic
98
+ - Session middleware with built-in session store
99
+ - Database support (using Peewee, but you can use whatever you want as long as there's a Peewee driver for it)
100
+ - Tests (currently a little over 80% coverage)
87
101
 
88
102
  Once tests are in and proven to work, then I'll release as version 1.0.
89
103
 
90
- More documentation to follow!
104
+ - currently missing tests for cors middleware
91
105
 
92
106
  If you're reading this on GitHub, this repository is a public mirror of https://git.joekaufeld.com/jkaufeld/spiderweb.
@@ -0,0 +1,78 @@
1
+ # spiderweb
2
+
3
+ <p align="center">
4
+ <img
5
+ src="https://img.shields.io/pypi/v/spiderweb-framework.svg?style=for-the-badge"
6
+ alt="PyPI release version for Spiderweb"
7
+ />
8
+ <img
9
+ src="https://img.shields.io/badge/gitmoji-%20😜%20😍-FFDD67.svg?style=for-the-badge"
10
+ alt="Gitmoji"
11
+ />
12
+ <img
13
+ src="https://img.shields.io/badge/code%20style-black-000000.svg?style=for-the-badge"
14
+ alt="Code style: Black"
15
+ />
16
+ </p>
17
+
18
+ As a professional web developer focusing on arcane uses of Django for arcane purposes, it occurred to me a little while ago that I didn't actually know how a web framework _worked_.
19
+
20
+ So I built one.
21
+
22
+ `spiderweb` is a small web framework, just big enough to hold a spider. Getting started is easy:
23
+
24
+ ```shell
25
+ poetry add spiderweb-framework
26
+ ```
27
+
28
+ Create a new file and drop this in it:
29
+
30
+ ```python
31
+ from spiderweb import SpiderwebRouter
32
+ from spiderweb.response import HttpResponse
33
+
34
+ app = SpiderwebRouter()
35
+
36
+ @app.route("/")
37
+ def index(request):
38
+ return HttpResponse("HELLO, WORLD!")
39
+
40
+ if __name__ == "__main__":
41
+ app.start()
42
+ ```
43
+
44
+ ## [View the docs here!](https://itsthejoker.github.io/spiderweb/#/)
45
+
46
+ My goal with this framework was to do three things:
47
+
48
+ 1. Learn a lot
49
+ 2. Create an unholy blend of Django and Flask
50
+ 3. Not look at any existing code. Go off of vibes alone and try to solve all the problems I could think of in my own way
51
+
52
+ And, honestly, I think I got there. Here's a non-exhaustive list of things this can do:
53
+
54
+ - Function-based views
55
+ - Optional Flask-style URL routing
56
+ - Optional Django-style URL routing
57
+ - URLs with variables in them a lá Django
58
+ - Full middleware implementation
59
+ - Limit routes by HTTP verbs
60
+ - Custom error routes
61
+ - Built-in dev server
62
+ - Gunicorn support
63
+ - HTML templates with Jinja2
64
+ - Static files support
65
+ - Cookies (reading and setting)
66
+ - Optional append_slash (with automatic redirects!)
67
+ - CSRF middleware
68
+ - CORS middleware
69
+ - Optional POST data validation middleware with Pydantic
70
+ - Session middleware with built-in session store
71
+ - Database support (using Peewee, but you can use whatever you want as long as there's a Peewee driver for it)
72
+ - Tests (currently a little over 80% coverage)
73
+
74
+ Once tests are in and proven to work, then I'll release as version 1.0.
75
+
76
+ - currently missing tests for cors middleware
77
+
78
+ If you're reading this on GitHub, this repository is a public mirror of https://git.joekaufeld.com/jkaufeld/spiderweb.
@@ -1,6 +1,6 @@
1
1
  [tool.poetry]
2
2
  name = "spiderweb-framework"
3
- version = "0.12.0"
3
+ version = "1.0.0"
4
4
  description = "A small web framework, just big enough for a spider."
5
5
  authors = ["Joe Kaufeld <opensource@joekaufeld.com>"]
6
6
  readme = "README.md"
@@ -0,0 +1,27 @@
1
+ from peewee import DatabaseProxy
2
+
3
+ DEFAULT_ALLOWED_METHODS = ["POST", "GET", "PUT", "PATCH", "DELETE"]
4
+ DEFAULT_ENCODING = "UTF-8"
5
+ __version__ = "1.0.0"
6
+
7
+ # https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie
8
+ REGEX_COOKIE_NAME = r"^[a-zA-Z0-9\s\(\)<>@,;:\/\\\[\]\?=\{\}\"\t]*$"
9
+
10
+ DATABASE_PROXY = DatabaseProxy()
11
+
12
+ DEFAULT_CORS_ALLOW_METHODS = (
13
+ "DELETE",
14
+ "GET",
15
+ "OPTIONS",
16
+ "PATCH",
17
+ "POST",
18
+ "PUT",
19
+ )
20
+ DEFAULT_CORS_ALLOW_HEADERS = (
21
+ "accept",
22
+ "authorization",
23
+ "content-type",
24
+ "user-agent",
25
+ "x-csrftoken",
26
+ "x-requested-with",
27
+ )
@@ -86,3 +86,7 @@ class UnusedMiddleware(SpiderwebException):
86
86
 
87
87
  class NoResponseError(SpiderwebException):
88
88
  pass
89
+
90
+
91
+ class StartupErrors(ExceptionGroup):
92
+ pass
@@ -1,16 +1,22 @@
1
1
  import inspect
2
2
  import logging
3
3
  import pathlib
4
+ import re
4
5
  import traceback
5
6
  import urllib.parse as urlparse
7
+ from logging import Logger
6
8
  from threading import Thread
7
- from typing import Optional, Callable
9
+ from typing import Optional, Callable, Sequence, LiteralString, Literal
8
10
  from wsgiref.simple_server import WSGIServer
9
11
 
10
12
  from jinja2 import BaseLoader, Environment, FileSystemLoader
11
13
  from peewee import Database, SqliteDatabase
12
14
 
13
15
  from spiderweb.middleware import MiddlewareMixin
16
+ from spiderweb.constants import (
17
+ DEFAULT_CORS_ALLOW_METHODS,
18
+ DEFAULT_CORS_ALLOW_HEADERS,
19
+ )
14
20
  from spiderweb.constants import (
15
21
  DATABASE_PROXY,
16
22
  DEFAULT_ENCODING,
@@ -30,7 +36,7 @@ from spiderweb.request import Request
30
36
  from spiderweb.response import HttpResponse, TemplateResponse, JsonResponse
31
37
  from spiderweb.routes import RoutesMixin
32
38
  from spiderweb.secrets import FernetMixin
33
- from spiderweb.utils import get_http_status_by_code
39
+ from spiderweb.utils import get_http_status_by_code, convert_url_to_regex
34
40
 
35
41
  console_logger = logging.getLogger(__name__)
36
42
  logging.basicConfig(level=logging.INFO)
@@ -42,21 +48,33 @@ class SpiderwebRouter(LocalServerMixin, MiddlewareMixin, RoutesMixin, FernetMixi
42
48
  *,
43
49
  addr: str = None,
44
50
  port: int = None,
51
+ allowed_hosts: Sequence[str | re.Pattern] = None,
52
+ cors_allowed_origins: Sequence[str] = None,
53
+ cors_allowed_origin_regexes: Sequence[str] = None,
54
+ cors_allow_all_origins: bool = False,
55
+ cors_urls_regex: str | re.Pattern[str] = r"^.*$",
56
+ cors_allow_methods: Sequence[str] = None,
57
+ cors_allow_headers: Sequence[str] = None,
58
+ cors_expose_headers: Sequence[str] = None,
59
+ cors_preflight_max_age: int = 86400,
60
+ cors_allow_credentials: bool = False,
61
+ cors_allow_private_network: bool = False,
62
+ csrf_trusted_origins: Sequence[str] = None,
45
63
  db: Optional[Database] = None,
46
- templates_dirs: list[str] = None,
47
- middleware: list[str] = None,
64
+ templates_dirs: Sequence[str] = None,
65
+ middleware: Sequence[str] = None,
48
66
  append_slash: bool = False,
49
- staticfiles_dirs: list[str] = None,
50
- routes: list[tuple[str, Callable] | tuple[str, Callable, dict]] = None,
67
+ staticfiles_dirs: Sequence[str] = None,
68
+ routes: Sequence[tuple[str, Callable] | tuple[str, Callable, dict]] = None,
51
69
  error_routes: dict[int, Callable] = None,
52
70
  secret_key: str = None,
53
- session_max_age=60 * 60 * 24 * 14, # 2 weeks
54
- session_cookie_name="swsession",
55
- session_cookie_secure=False, # should be true if serving over HTTPS
56
- session_cookie_http_only=True,
57
- session_cookie_same_site="lax",
58
- session_cookie_path="/",
59
- log=None,
71
+ session_max_age: int = 60 * 60 * 24 * 14, # 2 weeks
72
+ session_cookie_name: str = "swsession",
73
+ session_cookie_secure: bool = False, # should be true if serving over HTTPS
74
+ session_cookie_http_only: bool = True,
75
+ session_cookie_same_site: Literal["strict", "lax", "none"] = "lax",
76
+ session_cookie_path: str = "/",
77
+ log: Logger = None,
60
78
  **kwargs,
61
79
  ):
62
80
  self._routes = {}
@@ -69,9 +87,27 @@ class SpiderwebRouter(LocalServerMixin, MiddlewareMixin, RoutesMixin, FernetMixi
69
87
  self.append_slash = append_slash
70
88
  self.templates_dirs = templates_dirs
71
89
  self.staticfiles_dirs = staticfiles_dirs
72
- self._middleware: list[str] = middleware if middleware else []
90
+ self._middleware: list[str] = middleware or []
73
91
  self.middleware: list[Callable] = []
74
92
  self.secret_key = secret_key if secret_key else self.generate_key()
93
+ self._allowed_hosts = allowed_hosts or ["*"]
94
+ self.allowed_hosts = [convert_url_to_regex(i) for i in self._allowed_hosts]
95
+
96
+ self.cors_allowed_origins = cors_allowed_origins or []
97
+ self.cors_allowed_origin_regexes = cors_allowed_origin_regexes or []
98
+ self.cors_allow_all_origins = cors_allow_all_origins
99
+ self.cors_urls_regex = cors_urls_regex
100
+ self.cors_allow_methods = cors_allow_methods or DEFAULT_CORS_ALLOW_METHODS
101
+ self.cors_allow_headers = cors_allow_headers or DEFAULT_CORS_ALLOW_HEADERS
102
+ self.cors_expose_headers = cors_expose_headers or []
103
+ self.cors_preflight_max_age = cors_preflight_max_age
104
+ self.cors_allow_credentials = cors_allow_credentials
105
+ self.cors_allow_private_network = cors_allow_private_network
106
+
107
+ self._csrf_trusted_origins = csrf_trusted_origins or []
108
+ self.csrf_trusted_origins = [
109
+ convert_url_to_regex(i) for i in self._csrf_trusted_origins
110
+ ]
75
111
 
76
112
  self.extra_data = kwargs
77
113
 
@@ -134,12 +170,20 @@ class SpiderwebRouter(LocalServerMixin, MiddlewareMixin, RoutesMixin, FernetMixi
134
170
  try:
135
171
  status = get_http_status_by_code(resp.status_code)
136
172
  cookies = []
137
- if "Set-Cookie" in resp.headers:
138
- cookies = resp.headers["Set-Cookie"]
139
- del resp.headers["Set-Cookie"]
173
+ varies = []
174
+ resp.headers = {k.replace("_", "-"): v for k, v in resp.headers.items()}
175
+ if "set-cookie" in resp.headers:
176
+ cookies = resp.headers["set-cookie"]
177
+ del resp.headers["set-cookie"]
178
+ if "vary" in resp.headers:
179
+ varies = resp.headers["vary"]
180
+ del resp.headers["vary"]
181
+ resp.headers = {k: str(v) for k, v in resp.headers.items()}
140
182
  headers = list(resp.headers.items())
141
183
  for c in cookies:
142
- headers.append(("Set-Cookie", c))
184
+ headers.append(("set-cookie", str(c)))
185
+ for v in varies:
186
+ headers.append(("vary", str(v)))
143
187
 
144
188
  start_response(status, headers)
145
189
 
@@ -180,7 +224,7 @@ class SpiderwebRouter(LocalServerMixin, MiddlewareMixin, RoutesMixin, FernetMixi
180
224
  ):
181
225
  try:
182
226
  status = get_http_status_by_code(500)
183
- headers = [("Content-type", "text/plain; charset=utf-8")]
227
+ headers = [("Content-Type", "text/plain; charset=utf-8")]
184
228
 
185
229
  start_response(status, headers)
186
230
 
@@ -217,10 +261,18 @@ class SpiderwebRouter(LocalServerMixin, MiddlewareMixin, RoutesMixin, FernetMixi
217
261
  start_response, request, self.get_error_route(500)(request)
218
262
  )
219
263
 
264
+ def check_valid_host(self, request) -> bool:
265
+ host = request.headers.get("http_host")
266
+ if not host:
267
+ return False
268
+ for option in self.allowed_hosts:
269
+ if re.match(option, host):
270
+ return True
271
+ return False
272
+
220
273
  def __call__(self, environ, start_response, *args, **kwargs):
221
274
  """Entry point for WSGI apps."""
222
275
  request = self.get_request(environ)
223
-
224
276
  try:
225
277
  handler, additional_args, allowed_methods = self.get_route(request.path)
226
278
  except NotFound:
@@ -233,6 +285,9 @@ class SpiderwebRouter(LocalServerMixin, MiddlewareMixin, RoutesMixin, FernetMixi
233
285
  # replace the potentially valid handler with the error route
234
286
  handler = self.get_error_route(405)
235
287
 
288
+ if not self.check_valid_host(request):
289
+ handler = self.get_error_route(403)
290
+
236
291
  if request.is_form_request():
237
292
  form_data = urlparse.parse_qs(request.content)
238
293
  for key, value in form_data.items():
@@ -1,9 +1,11 @@
1
1
  from typing import Callable, ClassVar
2
+ import sys
2
3
 
3
4
  from .base import SpiderwebMiddleware as SpiderwebMiddleware
5
+ from .cors import CorsMiddleware as CorsMiddleware
4
6
  from .csrf import CSRFMiddleware as CSRFMiddleware
5
7
  from .sessions import SessionMiddleware as SessionMiddleware
6
- from ..exceptions import ConfigError, UnusedMiddleware
8
+ from ..exceptions import ConfigError, UnusedMiddleware, StartupErrors
7
9
  from ..request import Request
8
10
  from ..response import HttpResponse
9
11
  from ..utils import import_by_string
@@ -27,10 +29,19 @@ class MiddlewareMixin:
27
29
  self.middleware = middleware_by_reference
28
30
 
29
31
  def run_middleware_checks(self):
32
+ errors = []
30
33
  for middleware in self.middleware:
31
34
  if hasattr(middleware, "checks"):
32
35
  for check in middleware.checks:
33
- check(server=self).check()
36
+ if issue := check(server=self).check():
37
+ errors.append(issue)
38
+
39
+ if errors:
40
+ # just show the messages
41
+ sys.tracebacklimit = 1
42
+ raise StartupErrors(
43
+ "Problems were identified during startup — cannot continue.", errors
44
+ )
34
45
 
35
46
  def process_request_middleware(self, request: Request) -> None | bool:
36
47
  for middleware in self.middleware:
@@ -0,0 +1,158 @@
1
+ import re
2
+ from urllib.parse import urlsplit, SplitResult
3
+
4
+ from spiderweb.exceptions import ConfigError
5
+ from spiderweb.request import Request
6
+ from spiderweb.response import HttpResponse
7
+ from spiderweb.middleware import SpiderwebMiddleware
8
+ from spiderweb.server_checks import ServerCheck
9
+
10
+ ACCESS_CONTROL_ALLOW_ORIGIN = "access-control-allow-origin"
11
+ ACCESS_CONTROL_EXPOSE_HEADERS = "access-control-expose-headers"
12
+ ACCESS_CONTROL_ALLOW_CREDENTIALS = "access-control-allow-credentials"
13
+ ACCESS_CONTROL_ALLOW_HEADERS = "access-control-allow-headers"
14
+ ACCESS_CONTROL_ALLOW_METHODS = "access-control-allow-methods"
15
+ ACCESS_CONTROL_MAX_AGE = "access-control-max-age"
16
+ ACCESS_CONTROL_REQUEST_PRIVATE_NETWORK = "access-control-request-private-network"
17
+ ACCESS_CONTROL_ALLOW_PRIVATE_NETWORK = "access-control-allow-private-network"
18
+
19
+
20
+ class VerifyValidCorsSetting(ServerCheck):
21
+ INVALID_BASE_CONFIG = (
22
+ "To enable CORS, one of the three primary configurations must be set:"
23
+ " `cors_allowed_origins`, `cors_allowed_origin_regexes`, or"
24
+ " `cors_allow_all_origins`.",
25
+ )
26
+
27
+ def check(self):
28
+ if (
29
+ not self.server.cors_allowed_origins
30
+ and not self.server.cors_allowed_origin_regexes
31
+ and not self.server.cors_allow_all_origins
32
+ ):
33
+ return ConfigError(self.INVALID_BASE_CONFIG)
34
+
35
+
36
+ class CorsMiddleware(SpiderwebMiddleware):
37
+ # heavily 'based' on https://github.com/adamchainz/django-cors-headers,
38
+ # which is provided under the MIT license. This is essentially a direct
39
+ # port, since django-cors-headers is battle-tested code that has been
40
+ # around for a long time and it works well. Shoutouts to Otto, Adam, and
41
+ # crew for helping make this a complete non-issue in Django for a very long
42
+ # time.
43
+ checks = [VerifyValidCorsSetting]
44
+
45
+ def is_enabled(self, request: Request):
46
+ return bool(re.match(self.server.cors_urls_regex, request.path))
47
+
48
+ def add_response_headers(self, request: Request, response: HttpResponse):
49
+ enabled = getattr(request, "_cors_enabled", None)
50
+ if enabled is None:
51
+ enabled = self.is_enabled(request)
52
+ if not enabled:
53
+ return response
54
+
55
+ if "vary" in response.headers:
56
+ response.headers["vary"].append("origin")
57
+ else:
58
+ response.headers["vary"] = ["origin"]
59
+
60
+ origin = request.headers.get("http_origin")
61
+ if not origin:
62
+ return response
63
+
64
+ try:
65
+ url = urlsplit(origin)
66
+ except ValueError:
67
+ return response
68
+
69
+ if (
70
+ not self.server.cors_allow_all_origins
71
+ and not self.origin_found_in_allow_lists(origin, url)
72
+ ):
73
+ return response
74
+
75
+ if (
76
+ self.server.cors_allow_all_origins
77
+ and not self.server.cors_allow_credentials
78
+ ):
79
+ response.headers[ACCESS_CONTROL_ALLOW_ORIGIN] = "*"
80
+ else:
81
+ response.headers[ACCESS_CONTROL_ALLOW_ORIGIN] = origin
82
+
83
+ if self.server.cors_allow_credentials:
84
+ response.headers[ACCESS_CONTROL_ALLOW_CREDENTIALS] = "true"
85
+
86
+ if len(self.server.cors_expose_headers):
87
+ response.headers[ACCESS_CONTROL_EXPOSE_HEADERS] = ", ".join(
88
+ self.server.cors_expose_headers
89
+ )
90
+
91
+ if request.method == "OPTIONS":
92
+ response.headers[ACCESS_CONTROL_ALLOW_HEADERS] = ", ".join(
93
+ self.server.cors_allow_headers
94
+ )
95
+ response.headers[ACCESS_CONTROL_ALLOW_METHODS] = ", ".join(
96
+ self.server.cors_allow_methods
97
+ )
98
+ if self.server.cors_preflight_max_age:
99
+ response.headers[ACCESS_CONTROL_MAX_AGE] = str(
100
+ self.server.cors_preflight_max_age
101
+ )
102
+ if (
103
+ self.server.cors_allow_private_network
104
+ and request.headers.get(ACCESS_CONTROL_REQUEST_PRIVATE_NETWORK.replace("-", "_")) == "true"
105
+ ):
106
+ response.headers[ACCESS_CONTROL_ALLOW_PRIVATE_NETWORK] = "true"
107
+
108
+ return response
109
+
110
+ def origin_found_in_allow_lists(self, origin: str, url: SplitResult) -> bool:
111
+ return (
112
+ (origin == "null" and origin in self.server.cors_allowed_origins)
113
+ or self._url_in_allowlist(url)
114
+ or self.regex_domain_match(origin)
115
+ )
116
+
117
+ def _url_in_allowlist(self, url: SplitResult) -> bool:
118
+ origins = [urlsplit(o) for o in self.server.cors_allowed_origins]
119
+ return any(
120
+ origin.scheme == url.scheme and origin.netloc == url.netloc
121
+ for origin in origins
122
+ )
123
+
124
+ def regex_domain_match(self, origin: str) -> bool:
125
+ return any(
126
+ re.match(domain_pattern, origin)
127
+ for domain_pattern in self.server.cors_allowed_origin_regexes
128
+ )
129
+
130
+ def process_request(self, request: Request) -> HttpResponse | None:
131
+ # Identify and handle a preflight request
132
+ request._cors_enabled = self.is_enabled(request)
133
+ request.META["cors_ran"] = True
134
+ if (
135
+ request._cors_enabled
136
+ and request.method == "OPTIONS"
137
+ and "access-control-request-method" in request.headers
138
+ ):
139
+ # this should be 204, but according to mozilla, not all browsers
140
+ # parse that correctly. See [204] comment below.
141
+ resp = HttpResponse(
142
+ "",
143
+ status_code=200,
144
+ headers={"content-type": "text/plain", "content-length": 0},
145
+ )
146
+ self.add_response_headers(request, resp)
147
+ return resp
148
+
149
+ def process_response(self, request: Request, response: HttpResponse) -> None:
150
+ if not request.META.get("cors_ran"):
151
+ # something happened and process_request didn't run. Abort early.
152
+ # We're not relying on request._cors_enabled because it's more
153
+ # visible and the view may have destroyed it accidentally.
154
+ return
155
+ self.add_response_headers(request, response)
156
+
157
+
158
+ # [204]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/OPTIONS#status_code