site-paths 0.1.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.
site_paths/__init__.py ADDED
@@ -0,0 +1,24 @@
1
+ """Keeps a part of a site from whoever the site does not let in.
2
+
3
+ Most sites answer one way for a private route that exists and another
4
+ for one that does not, so anybody can list what a site has by asking.
5
+ A wall asks the site's own decision before a route is looked up, and
6
+ answers every path of the part alike, there or not, for whoever is not
7
+ let in.
8
+
9
+ A wall for each kind of server:
10
+
11
+ - :mod:`site_paths.asgi` for ASGI: Starlette, FastAPI and others.
12
+ - :mod:`site_paths.wsgi` for WSGI: Flask and others.
13
+ - :mod:`site_paths.django` for Django, where the decision is given
14
+ Django's own request.
15
+
16
+ Whether a deployment keeps its part is checked from outside by the one
17
+ check there is, ``site-paths-check`` of the package of the same name at
18
+ npm, which asks a site written in anything.
19
+ """
20
+
21
+ from ._paths import plain
22
+
23
+ __all__ = ["plain"]
24
+ __version__ = "0.1.0"
site_paths/_paths.py ADDED
@@ -0,0 +1,93 @@
1
+ """How a path is read.
2
+
3
+ A wall compares a request's path with the part it keeps. Servers read a
4
+ path in more than one way, so the path is read as the most forgiving of
5
+ them would: escapes decoded, a backslash or a doubled slash as one
6
+ slash, what follows a semicolon in a segment left out, dots resolved,
7
+ the letters A to Z made small. Some servers take what follows a
8
+ semicolon for parameters of the segment and find the route without
9
+ them.
10
+
11
+ The reading is held to two lists that every implementation of it
12
+ shares, in ``tests/vectors``.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ from typing import NamedTuple
18
+
19
+ #: The most segments a path is read to. No site has a page deeper, and
20
+ #: reading on would cost time that whoever writes a long address decides.
21
+ DEEPEST = 64
22
+
23
+ _SMALL = {ord(letter): ord(letter.lower()) for letter in "ABCDEFGHIJKLMNOPQRSTUVWXYZ"}
24
+ _HEX = frozenset(b"0123456789abcdefABCDEF")
25
+
26
+
27
+ class Reading(NamedTuple):
28
+ """A path as it was read."""
29
+
30
+ #: The path's plain form.
31
+ plain: str
32
+ #: Every place the path stands at on the way there, each the plain
33
+ #: form of a start of it, and its plain form last. A server that
34
+ #: does not resolve dots finds a route by the path as it is written,
35
+ #: so ``/admin/../users`` stands in ``/admin`` to that server though
36
+ #: its plain form is ``/users``.
37
+ stood: tuple[str, ...]
38
+ #: Whether the path has more segments than are read.
39
+ deep: bool
40
+
41
+
42
+ def read(path: str | bytes) -> Reading:
43
+ """Reads a path as it was asked for, escapes and all."""
44
+ asked = path.encode("utf-8", "surrogatepass") if isinstance(path, str) else bytes(path)
45
+ # The path's bytes: an escape is the byte it names.
46
+ decoded = bytearray()
47
+ at = 0
48
+ while at < len(asked):
49
+ if asked[at] == 0x25 and len(asked) - at >= 3 and asked[at + 1] in _HEX and asked[at + 2] in _HEX:
50
+ decoded.append(int(asked[at + 1 : at + 3], 16))
51
+ at += 3
52
+ else:
53
+ decoded.append(asked[at])
54
+ at += 1
55
+ merged = decoded.decode("utf-8", "replace").replace("\\", "/").translate(_SMALL)
56
+ kept: list[str] = []
57
+ stood: list[str] = []
58
+ segments = 0
59
+ ends_in_slash = merged.endswith("/")
60
+ slash = ends_in_slash
61
+ for whole in merged.split("/"):
62
+ piece = whole.split(";", 1)[0]
63
+ if piece == "":
64
+ continue
65
+ segments += 1
66
+ if piece in (".", ".."):
67
+ if piece == ".." and kept:
68
+ kept.pop()
69
+ slash = True
70
+ else:
71
+ kept.append(piece)
72
+ if segments <= DEEPEST:
73
+ stood.append("/" + "/".join(kept))
74
+ slash = ends_in_slash
75
+ plain = "/" + "/".join(kept) + ("/" if kept and slash else "")
76
+ stood.append(plain)
77
+ return Reading(plain, tuple(stood), segments > DEEPEST)
78
+
79
+
80
+ def plain(path: str | bytes) -> str:
81
+ """A path as the most forgiving server would read it."""
82
+ return read(path).plain
83
+
84
+
85
+ def decoded_once(path: str | bytes) -> bytes:
86
+ """A path that a server has decoded already, as one that is read once.
87
+
88
+ A percent sign in it is a percent sign that was asked for, and not
89
+ the start of an escape: reading it as one would decode twice, and a
90
+ path decoded twice may leave a part that the server finds it in.
91
+ """
92
+ asked = path.encode("utf-8", "surrogatepass") if isinstance(path, str) else bytes(path)
93
+ return asked.replace(b"%", b"%25")
site_paths/_wall.py ADDED
@@ -0,0 +1,55 @@
1
+ """What every wall shares: the part it keeps, and its bare answer."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from collections.abc import Iterable
7
+
8
+ from ._paths import Reading, read
9
+
10
+ #: Seconds a decision may take before the caller is kept out.
11
+ PATIENCE = 3.0
12
+
13
+ #: What every answer to a caller who is kept out says of caches,
14
+ #: whoever made the answer: no cache between may keep it. It would be
15
+ #: given to whoever asks next, the staff among them.
16
+ KEPT_BY_NO_CACHE = ("cache-control", "private, no-store")
17
+
18
+ #: A bare answer that nothing is there.
19
+ NOTHING_THERE_STATUS = 404
20
+ NOTHING_THERE_HEADERS = (("content-type", "text/plain; charset=utf-8"), KEPT_BY_NO_CACHE)
21
+ NOTHING_THERE_BODY = b"Not Found\n"
22
+
23
+
24
+ class Part:
25
+ """The part of a site that a wall keeps.
26
+
27
+ ``under`` is the start of the part: the path itself and everything
28
+ below it, however a request spells it. ``match`` is a pattern for
29
+ the paths that are kept, in its place, tried on the plain form.
30
+ """
31
+
32
+ def __init__(self, under: str | None = None, match: str | re.Pattern[str] | None = None) -> None:
33
+ if (under is None) == (match is None):
34
+ raise TypeError("a wall keeps what is under a path, or what fits a pattern")
35
+ self._base = None if under is None else read(under).plain.rstrip("/")
36
+ self._pattern = None if match is None else re.compile(match)
37
+
38
+ def _holds(self, path: str) -> bool:
39
+ if self._pattern is not None:
40
+ return self._pattern.search(path) is not None
41
+ return path == self._base or path.startswith(f"{self._base}/")
42
+
43
+ def covers(self, readings: Iterable[Reading]) -> bool:
44
+ """Whether a request is in the part.
45
+
46
+ Its path stands there at some point, in some reading of it, or
47
+ is deeper than a path is read.
48
+ """
49
+ return any(one.deep or any(self._holds(place) for place in one.stood) for one in readings)
50
+
51
+
52
+ def check_allow(allow: object) -> None:
53
+ """A wall needs the site's own decision of who is let in."""
54
+ if not callable(allow):
55
+ raise TypeError("a wall needs the site's own decision of who is let in")
site_paths/asgi.py ADDED
@@ -0,0 +1,146 @@
1
+ """A wall for ASGI: Starlette, FastAPI and whatever else speaks it.
2
+
3
+ from site_paths.asgi import Wall
4
+
5
+ app.add_middleware(Wall, under="/admin", allow=lambda scope: is_staff(scope))
6
+
7
+ Put it where it runs after whatever says who is signed in and before
8
+ the routes. In Starlette and FastAPI the middleware that is added last
9
+ runs first, so add the wall before the session's or the sign-in's.
10
+
11
+ A wall keeps what a request asks for. It does not keep what the site
12
+ publishes of itself: FastAPI lists every route in `/openapi.json` to
13
+ whoever asks, unless the routes of the part are left out of it.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import asyncio
19
+ import inspect
20
+ import re
21
+ from collections.abc import Awaitable, Callable, MutableMapping
22
+ from typing import Any
23
+
24
+ from ._paths import Reading, decoded_once, read
25
+ from ._wall import KEPT_BY_NO_CACHE, NOTHING_THERE_BODY, NOTHING_THERE_HEADERS, NOTHING_THERE_STATUS, PATIENCE, Part, check_allow
26
+
27
+ Scope = MutableMapping[str, Any]
28
+ Receive = Callable[[], Awaitable[MutableMapping[str, Any]]]
29
+ Send = Callable[[MutableMapping[str, Any]], Awaitable[None]]
30
+ App = Callable[[Scope, Receive, Send], Awaitable[None]]
31
+
32
+
33
+ def _readings(scope: Scope) -> list[Reading]:
34
+ """A request's path as it was sent, and as the server passes it on."""
35
+ found = []
36
+ raw = (scope.get("raw_path") or b"").split(b"?", 1)[0]
37
+ if raw:
38
+ found.append(read(raw))
39
+ path = scope.get("path") or "/"
40
+ found.append(read(decoded_once(path)))
41
+ # An application that is mounted below another is given the rest of
42
+ # the path with the start of it beside, or the whole path with that
43
+ # start beside: which, depends on the server and its age. And its
44
+ # owner may name a part from the top of the site or from where the
45
+ # application is mounted. Each is a reading.
46
+ root = scope.get("root_path") or ""
47
+ if root:
48
+ found.append(read(decoded_once(root + path)))
49
+ if path.startswith(root):
50
+ found.append(read(decoded_once(path[len(root) :] or "/")))
51
+ if raw.startswith(root.encode()):
52
+ found.append(read(raw[len(root.encode()) :] or b"/"))
53
+ return found
54
+
55
+
56
+ class Wall:
57
+ """Keeps a part of an ASGI application from whoever is not let in.
58
+
59
+ ``under``, or ``match`` in its place, says which part.
60
+
61
+ ``allow`` is the site's own decision: given the connection's scope,
62
+ it answers ``True`` for a caller who is let in, at once or when
63
+ awaited. Anything else and an error mean that the caller is not. So
64
+ does a decision that is awaited and does not come in ``patience``
65
+ seconds. One that answers at once is not cut short, and holds every
66
+ other request up while it runs: have it read only what the
67
+ connection carries already, and await whatever asks elsewhere.
68
+
69
+ ``missing`` is what the site answers for a path it does not have. A
70
+ path that the site does not have, such as ``"/nothing-here"``, has
71
+ the application itself answer for that path. An ASGI application
72
+ answers in the site's place. Left out, a bare 404 is answered, which
73
+ may differ from the site's own and so show that something is kept
74
+ here, though not what.
75
+
76
+ Whatever answers, the answer says that no cache may keep it. A
77
+ websocket in the part is closed before it is accepted.
78
+ """
79
+
80
+ def __init__(
81
+ self,
82
+ app: App,
83
+ *,
84
+ under: str | None = None,
85
+ match: str | re.Pattern[str] | None = None,
86
+ allow: Callable[[Scope], object],
87
+ missing: str | App | None = None,
88
+ patience: float = PATIENCE,
89
+ ) -> None:
90
+ check_allow(allow)
91
+ self._app = app
92
+ self._part = Part(under, match)
93
+ self._allow = allow
94
+ self._missing = missing
95
+ self._patience = patience
96
+
97
+ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
98
+ if scope["type"] not in ("http", "websocket") or not self._part.covers(_readings(scope)):
99
+ return await self._app(scope, receive, send)
100
+ if await self._allows(scope):
101
+ return await self._app(scope, receive, send)
102
+ await self._refuse(scope, receive, send)
103
+
104
+ async def _allows(self, scope: Scope) -> bool:
105
+ try:
106
+ answer = self._allow(scope)
107
+ if inspect.isawaitable(answer):
108
+ answer = await asyncio.wait_for(answer, self._patience)
109
+ return answer is True
110
+ except Exception:
111
+ return False
112
+
113
+ async def _refuse(self, scope: Scope, receive: Receive, send: Send) -> None:
114
+ """Answers a caller who is kept out, whatever goes wrong in it."""
115
+ if scope["type"] == "websocket":
116
+ # Closed before it is accepted: the server refuses the
117
+ # upgrade. The site's answer for a missing path is a page,
118
+ # and the site is asked to open nothing for this caller.
119
+ return await send({"type": "websocket.close", "code": 1000})
120
+ started = False
121
+
122
+ async def sending(message: MutableMapping[str, Any]) -> None:
123
+ # Whoever made the answer, no cache between may keep it.
124
+ nonlocal started
125
+ started = True
126
+ if message["type"] == "http.response.start":
127
+ said = [(name, value) for name, value in message.get("headers", []) if name.lower() != b"cache-control"]
128
+ said.append((KEPT_BY_NO_CACHE[0].encode(), KEPT_BY_NO_CACHE[1].encode()))
129
+ message = {**message, "headers": said}
130
+ await send(message)
131
+
132
+ if isinstance(self._missing, str):
133
+ # The application answers as for a path it does not have.
134
+ elsewhere = dict(scope)
135
+ elsewhere.update(path=self._missing, raw_path=self._missing.encode(), query_string=b"")
136
+ return await self._app(elsewhere, receive, sending)
137
+ if self._missing is not None:
138
+ try:
139
+ return await self._missing(scope, receive, sending)
140
+ except Exception:
141
+ if started:
142
+ raise
143
+ headers = [(name.encode(), value.encode()) for name, value in NOTHING_THERE_HEADERS]
144
+ headers.append((b"content-length", str(len(NOTHING_THERE_BODY)).encode()))
145
+ await send({"type": "http.response.start", "status": NOTHING_THERE_STATUS, "headers": headers})
146
+ await send({"type": "http.response.body", "body": b"" if scope.get("method") == "HEAD" else NOTHING_THERE_BODY})
site_paths/django.py ADDED
@@ -0,0 +1,167 @@
1
+ """A wall for Django.
2
+
3
+ # walls.py, in the project
4
+ from site_paths.django import wall
5
+
6
+ staff = wall(under="/admin", allow=lambda request: request.user.is_staff)
7
+
8
+ # settings.py
9
+ MIDDLEWARE = [
10
+ "django.middleware.security.SecurityMiddleware",
11
+ "django.contrib.sessions.middleware.SessionMiddleware",
12
+ "django.contrib.auth.middleware.AuthenticationMiddleware",
13
+ "project.walls.staff",
14
+ "django.middleware.common.CommonMiddleware",
15
+ ...,
16
+ ]
17
+
18
+ Put it after the middleware that says who is signed in, and before
19
+ Django's `CommonMiddleware` and `LocaleMiddleware`. Django looks a route
20
+ up after its middleware has run, so the wall decides before any route
21
+ is found. Those two look at an answer that nothing is there, and
22
+ redirect where the path with a slash, or with a language before it, is
23
+ a route: above the wall they would do so for a route that is there and
24
+ not for a name that is not, which tells the two apart. A wall that
25
+ finds either above itself does not start.
26
+ """
27
+
28
+ from __future__ import annotations
29
+
30
+ import asyncio
31
+ import re
32
+ from collections.abc import Callable
33
+ from typing import Any
34
+
35
+ from asgiref.sync import iscoroutinefunction, sync_to_async
36
+ from django.conf import settings
37
+ from django.core.exceptions import ImproperlyConfigured
38
+ from django.core.handlers.exception import response_for_exception
39
+ from django.http import Http404
40
+ from django.middleware.common import CommonMiddleware
41
+ from django.middleware.locale import LocaleMiddleware
42
+ from django.utils.decorators import sync_and_async_middleware
43
+ from django.utils.module_loading import import_string
44
+
45
+ from ._paths import Reading, decoded_once, read
46
+ from ._wall import KEPT_BY_NO_CACHE, PATIENCE, Part, check_allow
47
+
48
+ #: Where a server keeps the address it was asked for, as it was written.
49
+ _AS_WRITTEN = ("RAW_URI", "REQUEST_URI")
50
+
51
+
52
+ def _readings(request: Any) -> list[Reading]:
53
+ """A request's path as it was sent, and as Django passes it on."""
54
+ found = [read(decoded_once(request.path)), read(decoded_once(request.path_info))]
55
+ scope = getattr(request, "scope", None)
56
+ if scope and scope.get("raw_path"):
57
+ found.append(read(scope["raw_path"].split(b"?", 1)[0]))
58
+ for name in _AS_WRITTEN:
59
+ asked = request.META.get(name)
60
+ if asked:
61
+ target = asked.split("?", 1)[0]
62
+ if "://" in target:
63
+ target = "/" + target.split("://", 1)[1].partition("/")[2]
64
+ found.append(read(target.encode("latin-1", "replace")))
65
+ return found
66
+
67
+
68
+ def _check_order(this: object) -> None:
69
+ """Refuses to start below middleware that would redirect the wall's answer.
70
+
71
+ Where the wall is in the settings by another name than its own,
72
+ nothing can be said of what is above it.
73
+ """
74
+ above = []
75
+ for name in settings.MIDDLEWARE:
76
+ try:
77
+ found = import_string(name)
78
+ except ImportError:
79
+ continue
80
+ if found is this:
81
+ break
82
+ above.append((name, found))
83
+ else:
84
+ return
85
+ for name, found in above:
86
+ if isinstance(found, type) and issubclass(found, (CommonMiddleware, LocaleMiddleware)):
87
+ raise ImproperlyConfigured(
88
+ f"{name} is above a wall in MIDDLEWARE. It redirects an answer that nothing is there "
89
+ "where the path with a slash, or with a language before it, is a route, which would tell "
90
+ "a route that is there from a name that is not. Put the wall above it."
91
+ )
92
+
93
+
94
+ def wall(
95
+ *,
96
+ under: str | None = None,
97
+ match: str | re.Pattern[str] | None = None,
98
+ allow: Callable[[Any], object],
99
+ missing: Callable[[Any], Any] | None = None,
100
+ patience: float = PATIENCE,
101
+ ) -> Callable[[Callable[[Any], Any]], Callable[[Any], Any]]:
102
+ """Makes a middleware that keeps a part of a Django site.
103
+
104
+ ``under``, or ``match`` in its place, says which part.
105
+
106
+ ``allow`` is the site's own decision: given Django's request, it
107
+ answers ``True`` for a caller who is let in. Anything else and an
108
+ error mean that the caller is not. Where Django runs on ASGI, a
109
+ decision that is not a coroutine is made in a thread, as a decision
110
+ that reads the database must be, and one that does not come in
111
+ ``patience`` seconds means that the caller is not let in.
112
+
113
+ ``missing`` is what the site answers for a path it does not have:
114
+ given the request, it returns that answer. Left out, the site's own
115
+ page for a missing path is answered, as Django makes it.
116
+
117
+ Whatever answers, the answer says that no cache may keep it.
118
+ """
119
+ check_allow(allow)
120
+ part = Part(under, match)
121
+
122
+ def refuse(request: Any) -> Any:
123
+ """Answers a caller who is kept out, whatever goes wrong in it."""
124
+ answer = None
125
+ if missing is not None:
126
+ try:
127
+ answer = missing(request)
128
+ except Exception:
129
+ answer = None
130
+ if answer is None:
131
+ # The page Django itself makes where no route is found.
132
+ answer = response_for_exception(request, Http404())
133
+ answer.headers[KEPT_BY_NO_CACHE[0]] = KEPT_BY_NO_CACHE[1]
134
+ return answer
135
+
136
+ @sync_and_async_middleware
137
+ def middleware(get_response: Callable[[Any], Any]) -> Callable[[Any], Any]:
138
+ _check_order(middleware)
139
+ if iscoroutinefunction(get_response):
140
+ decide = allow if iscoroutinefunction(allow) else sync_to_async(allow, thread_sensitive=True)
141
+
142
+ async def kept_awaited(request: Any) -> Any:
143
+ if part.covers(_readings(request)):
144
+ try:
145
+ let_in = (await asyncio.wait_for(decide(request), patience)) is True
146
+ except Exception:
147
+ let_in = False
148
+ if not let_in:
149
+ # Django's page is made as Django makes any, in a thread.
150
+ return await sync_to_async(refuse, thread_sensitive=False)(request)
151
+ return await get_response(request)
152
+
153
+ return kept_awaited
154
+
155
+ def kept(request: Any) -> Any:
156
+ if part.covers(_readings(request)):
157
+ try:
158
+ let_in = allow(request) is True
159
+ except Exception:
160
+ let_in = False
161
+ if not let_in:
162
+ return refuse(request)
163
+ return get_response(request)
164
+
165
+ return kept
166
+
167
+ return middleware
site_paths/py.typed ADDED
File without changes
site_paths/wsgi.py ADDED
@@ -0,0 +1,128 @@
1
+ """A wall for WSGI: Flask and whatever else speaks it.
2
+
3
+ from site_paths.wsgi import Wall
4
+
5
+ app.wsgi_app = Wall(app.wsgi_app, under="/admin", allow=lambda environ: is_staff(environ))
6
+
7
+ It stands before the application, and so before its routes. Its
8
+ decision is given the request's environment, which holds the cookies
9
+ and headers and nothing the application has worked out yet.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import re
15
+ from collections.abc import Callable, Iterable
16
+ from typing import Any
17
+
18
+ from ._paths import Reading, decoded_once, read
19
+ from ._wall import KEPT_BY_NO_CACHE, NOTHING_THERE_BODY, NOTHING_THERE_HEADERS, NOTHING_THERE_STATUS, Part, check_allow
20
+
21
+ Environ = dict[str, Any]
22
+ StartResponse = Callable[..., Any]
23
+ App = Callable[[Environ, StartResponse], Iterable[bytes]]
24
+
25
+ #: Where a server keeps the address it was asked for, as it was written.
26
+ _AS_WRITTEN = ("RAW_URI", "REQUEST_URI")
27
+
28
+
29
+ def _readings(environ: Environ) -> list[Reading]:
30
+ """A request's path as it was sent, and as the server passes it on."""
31
+ found: list[Reading] = []
32
+ written: list[bytes] = []
33
+ for name in _AS_WRITTEN:
34
+ asked = environ.get(name)
35
+ if asked:
36
+ target = asked.split("?", 1)[0]
37
+ # A proxy may be asked with the whole address.
38
+ if "://" in target:
39
+ target = "/" + target.split("://", 1)[1].partition("/")[2]
40
+ written.append(target.encode("latin-1", "replace"))
41
+ found.extend(read(target) for target in written)
42
+ # The server has decoded these once, into bytes kept one to a letter.
43
+ script = environ.get("SCRIPT_NAME", "").encode("latin-1", "replace")
44
+ info = environ.get("PATH_INFO", "").encode("latin-1", "replace")
45
+ found.append(read(decoded_once(script + info)))
46
+ # An application that is mounted below another is given the rest of
47
+ # the path, and its owner may name a part from the top of the site
48
+ # or from where the application is mounted: each is a reading.
49
+ if script:
50
+ found.append(read(decoded_once(info)))
51
+ found.extend(read(target[len(script) :] or b"/") for target in written if target.startswith(script))
52
+ return found
53
+
54
+
55
+ class Wall:
56
+ """Keeps a part of a WSGI application from whoever is not let in.
57
+
58
+ ``under``, or ``match`` in its place, says which part.
59
+
60
+ ``allow`` is the site's own decision: given the request's
61
+ environment, it answers ``True`` for a caller who is let in.
62
+ Anything else and an error mean that the caller is not. It is not
63
+ cut short: give what it asks a time of its own to answer in.
64
+
65
+ ``missing`` is what the site answers for a path it does not have. A
66
+ path that the site does not have, such as ``"/nothing-here"``, has
67
+ the application itself answer for that path. A WSGI application
68
+ answers in the site's place. Left out, a bare 404 is answered, which
69
+ may differ from the site's own and so show that something is kept
70
+ here, though not what.
71
+
72
+ Whatever answers, the answer says that no cache may keep it.
73
+ """
74
+
75
+ def __init__(
76
+ self,
77
+ app: App,
78
+ *,
79
+ under: str | None = None,
80
+ match: str | re.Pattern[str] | None = None,
81
+ allow: Callable[[Environ], object],
82
+ missing: str | App | None = None,
83
+ ) -> None:
84
+ check_allow(allow)
85
+ self._app = app
86
+ self._part = Part(under, match)
87
+ self._allow = allow
88
+ self._missing = missing
89
+
90
+ def __call__(self, environ: Environ, start_response: StartResponse) -> Iterable[bytes]:
91
+ if not self._part.covers(_readings(environ)) or self._allows(environ):
92
+ return self._app(environ, start_response)
93
+ return self._refuse(environ, start_response)
94
+
95
+ def _allows(self, environ: Environ) -> bool:
96
+ try:
97
+ return self._allow(environ) is True
98
+ except Exception:
99
+ return False
100
+
101
+ def _refuse(self, environ: Environ, start_response: StartResponse) -> Iterable[bytes]:
102
+ """Answers a caller who is kept out, whatever goes wrong in it."""
103
+ started = False
104
+
105
+ def starting(status: str, said: list[tuple[str, str]], *more: Any) -> Any:
106
+ # Whoever made the answer, no cache between may keep it.
107
+ nonlocal started
108
+ started = True
109
+ kept = [(name, value) for name, value in said if name.lower() != "cache-control"]
110
+ return start_response(status, [*kept, KEPT_BY_NO_CACHE], *more)
111
+
112
+ if isinstance(self._missing, str):
113
+ # The application answers as for a path it does not have.
114
+ elsewhere = dict(environ)
115
+ elsewhere.update(PATH_INFO=self._missing, QUERY_STRING="")
116
+ for name in _AS_WRITTEN:
117
+ if name in elsewhere:
118
+ elsewhere[name] = self._missing
119
+ return self._app(elsewhere, starting)
120
+ if self._missing is not None:
121
+ try:
122
+ return self._missing(environ, starting)
123
+ except Exception:
124
+ if started:
125
+ raise
126
+ headers = [*NOTHING_THERE_HEADERS, ("content-length", str(len(NOTHING_THERE_BODY)))]
127
+ start_response(f"{NOTHING_THERE_STATUS} Not Found", headers)
128
+ return [b"" if environ.get("REQUEST_METHOD") == "HEAD" else NOTHING_THERE_BODY]
@@ -0,0 +1,226 @@
1
+ Metadata-Version: 2.5
2
+ Name: site-paths
3
+ Version: 0.1.0
4
+ Summary: Stop a site from telling strangers which private routes exist: a wall for ASGI, WSGI and Django.
5
+ Project-URL: Repository, https://github.com/webodik/toller-web
6
+ Project-URL: Issues, https://github.com/webodik/toller-web/issues
7
+ Project-URL: Why, https://github.com/webodik/toller-web/blob/main/docs/why.md
8
+ License-Expression: Apache-2.0
9
+ License-File: LICENSE
10
+ Keywords: access-control,asgi,django,fastapi,flask,middleware,route-enumeration,security,starlette,wsgi
11
+ Classifier: Framework :: Django
12
+ Classifier: Framework :: FastAPI
13
+ Classifier: Framework :: Flask
14
+ Classifier: Programming Language :: Python :: 3.11
15
+ Classifier: Programming Language :: Python :: 3.12
16
+ Classifier: Programming Language :: Python :: 3.13
17
+ Classifier: Programming Language :: Python :: 3.14
18
+ Classifier: Programming Language :: Python :: 3.15
19
+ Classifier: Topic :: Internet :: WWW/HTTP
20
+ Classifier: Topic :: Security
21
+ Classifier: Typing :: Typed
22
+ Requires-Python: >=3.11
23
+ Description-Content-Type: text/markdown
24
+
25
+ # site-paths
26
+
27
+ Stop your site from telling strangers which private routes exist.
28
+
29
+ If `/admin/reports` answers "sign in" and a made-up address answers
30
+ "not found", anybody can tell that your site has a reports page without
31
+ seeing a single report. Asking for a list of names gives the list of
32
+ what you have. Scanners do that in the first minutes of an attack, and
33
+ what they try next is built on it.
34
+ [Why hide whether a route exists?](https://github.com/webodik/toller-web/blob/main/docs/why.md)
35
+
36
+ This is the wall for Python: in your server, it answers every path of a
37
+ private part alike, there or not, for whoever your own code does not
38
+ let in. It is for ASGI (Starlette, FastAPI), WSGI (Flask) and Django.
39
+
40
+ No dependencies. Typed. Apache-2.0.
41
+
42
+ ## Install
43
+
44
+ ```sh
45
+ pip install site-paths
46
+ ```
47
+
48
+ Python 3.11 or later.
49
+
50
+ ## Quick start
51
+
52
+ **1. Ask your deployment what it gives away.** The check is one command
53
+ for a site written in anything, and needs Node.js where it runs, which
54
+ is not on your server. Name the private part and one route in it that
55
+ exists, at the address your visitors use:
56
+
57
+ ```sh
58
+ npx -p site-paths site-paths-check --url https://staging.shop.example --under /admin --has /admin/reports
59
+ ```
60
+
61
+ It asks as a stranger for that route and for made-up names beside it.
62
+ If anything tells them apart, it says what and ends with 1.
63
+ [What the check asks and what it takes](https://github.com/webodik/toller-web/tree/main/js#the-check).
64
+
65
+ **2. If it fails, put a wall before the part,** after whatever says who
66
+ is signed in and before your routes. On FastAPI:
67
+
68
+ ```python
69
+ from site_paths.asgi import Wall
70
+
71
+ app.add_middleware(
72
+ Wall,
73
+ under="/admin",
74
+ allow=lambda scope: scope["session"].get("role") == "staff",
75
+ missing="/nothing-here",
76
+ )
77
+ app.add_middleware(SessionMiddleware, secret_key=...)
78
+ ```
79
+
80
+ `allow` is your own decision about who is let in. `missing` is a path
81
+ your site does not have: whoever is not let in gets your site's own
82
+ answer for it, for every path under `/admin`, so a route that is there
83
+ and one that is not look the same. Staff go on to your routes as before.
84
+
85
+ FastAPI also lists every route in `/openapi.json` to whoever asks. Leave
86
+ the part's routes out of it, with
87
+ `APIRouter(prefix="/admin", include_in_schema=False)`: a wall keeps what
88
+ is asked for, and not what the site publishes of itself.
89
+
90
+ **3. Run the check again, and keep it where your tests run.** It fails
91
+ when a later change lets an answer tell again.
92
+
93
+ ## The wall
94
+
95
+ A wall runs before your site looks a route up, and asks your function
96
+ whether the caller is let in. That order is the point: an answer that
97
+ is made to look the same after the route was found can still be told
98
+ apart by how long it took.
99
+
100
+ ### FastAPI and Starlette
101
+
102
+ See [Quick start](#quick-start).
103
+
104
+ - **Add the wall before the middleware that says who is signed in:**
105
+ the session's, or `AuthenticationMiddleware`. The middleware that is
106
+ added last runs first.
107
+ - **Leave the part's routes out of what FastAPI publishes.** FastAPI
108
+ lists every route in `/openapi.json`, and shows them at `/docs`, to
109
+ whoever asks. A wall keeps what is asked for, and not what the site
110
+ says of itself:
111
+
112
+ ```python
113
+ staff = APIRouter(prefix="/admin", include_in_schema=False)
114
+ ```
115
+
116
+ - **`allow` is given the connection's scope.** A coroutine is awaited,
117
+ and a caller whose answer does not come in three seconds is kept out.
118
+ A plain function is called at once and is not cut short: have it read
119
+ only what the connection carries already, such as the session.
120
+ - **An application mounted below another** keeps its part whether
121
+ `under` names it from the top of the site or from where the
122
+ application is mounted.
123
+
124
+ ### Flask
125
+
126
+ ```python
127
+ from site_paths.wsgi import Wall
128
+
129
+ def is_staff(environ):
130
+ with app.app_context():
131
+ session = app.session_interface.open_session(app, app.request_class(environ))
132
+ return session is not None and session.get("role") == "staff"
133
+
134
+ app.wsgi_app = Wall(app.wsgi_app, under="/admin", allow=is_staff, missing="/nothing-here")
135
+ ```
136
+
137
+ The wall stands before the application, and so before Flask has opened
138
+ the session: `allow` is given the request's environment, and opens the
139
+ session itself as above. A session that is kept on the server needs the
140
+ application's context to open, which is what the `with` is for.
141
+
142
+ ### Django
143
+
144
+ ```python
145
+ # walls.py, in your project
146
+ from site_paths.django import wall
147
+
148
+ staff = wall(under="/admin", allow=lambda request: request.user.is_staff)
149
+ ```
150
+
151
+ ```python
152
+ # settings.py
153
+ MIDDLEWARE = [
154
+ "django.middleware.security.SecurityMiddleware",
155
+ "django.contrib.sessions.middleware.SessionMiddleware",
156
+ "django.contrib.auth.middleware.AuthenticationMiddleware",
157
+ "project.walls.staff",
158
+ "django.middleware.common.CommonMiddleware",
159
+ ...,
160
+ ]
161
+ ```
162
+
163
+ - **After the middleware that says who is signed in, and before
164
+ `CommonMiddleware` and `LocaleMiddleware`.** Those two look at an
165
+ answer that nothing is there and redirect where the path with a
166
+ slash, or with a language before it, is a route. Above the wall they
167
+ would redirect `/admin/reports` when `/admin/reports/` is a route,
168
+ and not a name that is no route, which tells the two apart. A wall
169
+ that finds either above itself does not start, and says why.
170
+ - **Whoever is not let in gets the site's own page for a missing
171
+ path,** as Django makes it.
172
+ - **Where routes carry a language before them** (`i18n_patterns`), the
173
+ part is under each language: keep it with a pattern, such as
174
+ `match=r"^/(en|de)/admin(/|$)"`.
175
+ - **Where Django runs on ASGI,** a decision that is not a coroutine is
176
+ made in a thread.
177
+
178
+ ### Options
179
+
180
+ | Option | |
181
+ | --- | --- |
182
+ | `under` | The start of the part, as a visitor asks for it: the path itself and everything below it |
183
+ | `match` | In place of `under`: a pattern for the paths to keep, such as `r"\.js\.map$"` |
184
+ | `allow` | Your decision. Only `True` lets a caller in: anything else, or an error, keeps the caller out. So does a decision that is awaited and does not come in three seconds |
185
+ | `missing` | What your site answers for a path it does not have. For ASGI and WSGI: a path the site does not have, or an application that answers in its place; left out, a bare `404`. For Django: a function that returns the answer; left out, Django's own page for a missing path |
186
+
187
+ ### What to know
188
+
189
+ - **A path is read as the most forgiving server would read it,** so no
190
+ other spelling of it goes round: `/Admin//reports`, `/%61dmin/reports`
191
+ and `/admin;v=1/reports` are all `/admin/reports`.
192
+ - **A path that enters the part and leaves it again by dots is kept
193
+ too,** such as `/admin/../reports`: these frameworks find a route by
194
+ the path as it is written. So is a path of more than 64 segments,
195
+ wherever it leads.
196
+ - **No cache may keep what a caller who is kept out is answered.** The
197
+ wall says `cache-control: private, no-store` on it, whatever made the
198
+ answer. What your staff are answered is yours to mark the same: a
199
+ cache in between that keeps it gives it to whoever asks next.
200
+ - **A decision that is not awaited is not cut short:** on WSGI, and a
201
+ plain function on ASGI. Give what it asks a time of its own to
202
+ answer in.
203
+ - **A websocket in the part is closed before it is accepted,** for
204
+ whoever is not let in.
205
+ - **A wall does not hide what your site sends every browser.** A script
206
+ that names a route has given it away. The check looks for that.
207
+ - **It does not stand before** anything your platform serves without
208
+ asking your application, such as static files at a CDN.
209
+ - **It is no replacement for authorization.** It keeps the list of
210
+ routes from strangers. What a signed-in caller may do is still your
211
+ code's to decide.
212
+
213
+ ## What it was tried on
214
+
215
+ Python 3.11 to 3.15, on every change. FastAPI on uvicorn, Flask on
216
+ gunicorn, and Django on gunicorn and on uvicorn, each asked by the
217
+ check as a stranger, a customer and the staff: without the wall the
218
+ check fails, with it the check passes. Django with its own
219
+ `CommonMiddleware` and routes that end with a slash; FastAPI with an
220
+ application mounted below it, and with nothing of the part in what it
221
+ publishes. No cache or CDN was put in front. It reads a path by the same two
222
+ lists that the JavaScript package beside it is held to.
223
+
224
+ ## License
225
+
226
+ Apache-2.0: see `LICENSE`.
@@ -0,0 +1,11 @@
1
+ site_paths/__init__.py,sha256=w3fJ4pa5n9C7-pdp0AqURqdcMFvTBKjZYZZm0ztROmg,860
2
+ site_paths/_paths.py,sha256=IlGnmmzk_3Lr82u8bZ0SjoF2rU3ziZIvCosHHv5etGE,3410
3
+ site_paths/_wall.py,sha256=gScljZS_M9NXF0rD7nfhb5xLVX3wf7Py05k3qOD_jys,2123
4
+ site_paths/asgi.py,sha256=pWHIZxiv-DfZcuH4MM-Y_04S4dsLzhrCBXvGPcFwUbg,6428
5
+ site_paths/django.py,sha256=e6600jZDvLYzFTqap0wdnS-BTNOkohHLoGQeYooSgEs,6465
6
+ site_paths/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
7
+ site_paths/wsgi.py,sha256=8KhE3uJ4us02UU9EdwjZEIuQfWai0M-6Jx4OOAhFp-8,5287
8
+ site_paths-0.1.0.dist-info/METADATA,sha256=92ZJ7QcGRX2qbQRWsKf2HxVtaP73ybi8bsoJNHpY5MM,9317
9
+ site_paths-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
10
+ site_paths-0.1.0.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
11
+ site_paths-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.