reguard 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.
- reguard/__init__.py +99 -0
- reguard/_asgi.py +212 -0
- reguard/_engine.py +1279 -0
- reguard/_shared.py +895 -0
- reguard/_wsgi.py +247 -0
- reguard/py.typed +0 -0
- reguard-0.1.0.dist-info/METADATA +107 -0
- reguard-0.1.0.dist-info/RECORD +10 -0
- reguard-0.1.0.dist-info/WHEEL +4 -0
- reguard-0.1.0.dist-info/licenses/LICENSE +21 -0
reguard/__init__.py
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
"""
|
|
2
|
+
reguard: Reguard for your Python server. One middleware, WSGI or ASGI:
|
|
3
|
+
|
|
4
|
+
import reguard
|
|
5
|
+
|
|
6
|
+
app.wsgi_app = reguard.wsgi(app.wsgi_app) # Flask
|
|
7
|
+
application = reguard.wsgi(get_wsgi_application()) # Django (wsgi.py)
|
|
8
|
+
app.add_middleware(reguard.ASGIMiddleware) # FastAPI / Starlette
|
|
9
|
+
application = reguard.asgi(get_asgi_application()) # Django (asgi.py)
|
|
10
|
+
|
|
11
|
+
It reads REGUARD_KEY from the environment, and then:
|
|
12
|
+
1. Serves /_s/* (the browser script and its reports) by passing it to Reguard, so the script is
|
|
13
|
+
first-party on your domain. Only Reguard's own `_s` cookie is passed on, never yours.
|
|
14
|
+
2. Adds the script tag to your HTML pages (right after <head>), unless a page already has it.
|
|
15
|
+
3. Verifies the visitor's verdict: ``reguard.verdict(request)`` (None when there is none). With
|
|
16
|
+
``block=True`` it also answers flagged visitors with 429 for you.
|
|
17
|
+
4. Sends Reguard short summaries of the requests you serve: keyed hashes and coarse shapes, never
|
|
18
|
+
values, so it can see scraping and probing across a visit.
|
|
19
|
+
|
|
20
|
+
It never raises into your request handling and never delays a response: summaries are queued and
|
|
21
|
+
sent from a background thread. With no key configured it passes everything through.
|
|
22
|
+
|
|
23
|
+
Options (all optional): key, collector, inject, block, forward, source_maps, ignore, collect,
|
|
24
|
+
watch_sessionless, on_error, flush_interval. See https://reguard.site/docs/.
|
|
25
|
+
"""
|
|
26
|
+
from __future__ import annotations
|
|
27
|
+
|
|
28
|
+
from typing import Any, Callable, Iterable, Mapping, Optional
|
|
29
|
+
|
|
30
|
+
from ._asgi import ASGIMiddleware
|
|
31
|
+
from ._engine import Claim, Verdict
|
|
32
|
+
from ._shared import format_site_key, parse_site_key
|
|
33
|
+
from ._wsgi import ENVIRON_KEY, WSGIMiddleware
|
|
34
|
+
|
|
35
|
+
__version__ = "0.1.0"
|
|
36
|
+
__all__ = ["wsgi", "asgi", "WSGIMiddleware", "ASGIMiddleware", "verdict", "Verdict", "Claim", "parse_site_key", "format_site_key", "__version__"]
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def wsgi(app: Callable[..., Iterable[bytes]], **options: Any) -> WSGIMiddleware:
|
|
40
|
+
"""
|
|
41
|
+
Wrap a WSGI app. Options:
|
|
42
|
+
|
|
43
|
+
- key: your site key (``rgk.…``, from the dashboard). Default: the REGUARD_KEY environment variable.
|
|
44
|
+
- collector: where Reguard answers. Default: REGUARD_COLLECTOR or https://api.reguard.site.
|
|
45
|
+
- inject: add the script tag to HTML pages (default True).
|
|
46
|
+
- block: answer flagged visitors for you. True blocks a visitor with any claim; a dict narrows
|
|
47
|
+
it: labels, status (default 429), min_stage, require (routes that need a live Reguard script,
|
|
48
|
+
e.g. ["/api/*"]), require_max_age (s, default 60), require_grace (s, 15),
|
|
49
|
+
require_grace_requests (30), require_grace_pages (3), require_refresh_requests (30),
|
|
50
|
+
require_refresh (s, 10), pace (False, or limits {"documents" | "api" | "not_found":
|
|
51
|
+
{"burst": n, "per_second": r}}).
|
|
52
|
+
- forward: send request summaries (default True).
|
|
53
|
+
- source_maps: "deny" answers 404 for *.map and drops SourceMap headers (default when block
|
|
54
|
+
is set) or "allow".
|
|
55
|
+
- ignore: ``ignore(path) -> bool`` for paths never summarized (e.g. health checks).
|
|
56
|
+
- collect: what Reguard receives: pages ("masked" | "hashed" | "off"), addresses ("hashed" |
|
|
57
|
+
"off"), behavior (bool), requests (bool), skip (paths Reguard never runs on, e.g. ["/account/*"]).
|
|
58
|
+
- watch_sessionless: summarize cookieless requests worth watching (default True).
|
|
59
|
+
- on_error: called with errors Reguard swallowed (it never raises into your app).
|
|
60
|
+
- flush_interval: seconds between summary batches (default 2).
|
|
61
|
+
"""
|
|
62
|
+
return WSGIMiddleware(app, **options)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def asgi(app: Any, **options: Any) -> ASGIMiddleware:
|
|
66
|
+
"""Wrap an ASGI app. Same options as :func:`wsgi`."""
|
|
67
|
+
return ASGIMiddleware(app, **options)
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def verdict(obj: Any) -> Optional[Verdict]:
|
|
71
|
+
"""
|
|
72
|
+
The visitor's verified verdict, or None: from a Flask/Werkzeug request, a Django HttpRequest, a
|
|
73
|
+
Starlette/FastAPI Request, a WSGI environ or an ASGI scope.
|
|
74
|
+
"""
|
|
75
|
+
if obj is None:
|
|
76
|
+
return None
|
|
77
|
+
if isinstance(obj, Mapping):
|
|
78
|
+
if ENVIRON_KEY in obj:
|
|
79
|
+
return obj[ENVIRON_KEY]
|
|
80
|
+
if "reguard" in obj:
|
|
81
|
+
v = obj["reguard"]
|
|
82
|
+
return v if isinstance(v, Verdict) or v is None else None
|
|
83
|
+
state = obj.get("state")
|
|
84
|
+
if isinstance(state, Mapping):
|
|
85
|
+
v = state.get("reguard")
|
|
86
|
+
return v if isinstance(v, Verdict) else None
|
|
87
|
+
return None
|
|
88
|
+
for attr in ("environ", "META", "scope"):
|
|
89
|
+
try:
|
|
90
|
+
d = getattr(obj, attr, None)
|
|
91
|
+
except Exception:
|
|
92
|
+
d = None
|
|
93
|
+
if isinstance(d, Mapping):
|
|
94
|
+
v = verdict(d)
|
|
95
|
+
if v is not None:
|
|
96
|
+
return v
|
|
97
|
+
state = getattr(obj, "state", None)
|
|
98
|
+
v = getattr(state, "reguard", None) if state is not None else None
|
|
99
|
+
return v if isinstance(v, Verdict) else None
|
reguard/_asgi.py
ADDED
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
"""
|
|
2
|
+
ASGI: FastAPI, Starlette, Django (asgi.py), Quart, Litestar and any other ASGI app.
|
|
3
|
+
|
|
4
|
+
app.add_middleware(reguard.ASGIMiddleware) # FastAPI / Starlette
|
|
5
|
+
application = reguard.asgi(get_asgi_application()) # Django (asgi.py)
|
|
6
|
+
|
|
7
|
+
The verdict is at ``scope["reguard"]`` and ``scope["state"]["reguard"]`` (Starlette:
|
|
8
|
+
``request.state.reguard``), or use ``reguard.verdict(request)``. Only HTTP requests are handled;
|
|
9
|
+
lifespan and websocket connections pass straight through.
|
|
10
|
+
"""
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import asyncio
|
|
14
|
+
from typing import Any, Awaitable, Callable, Dict, List, MutableMapping, Optional, Tuple
|
|
15
|
+
from urllib.parse import quote
|
|
16
|
+
|
|
17
|
+
from ._engine import PROXY_BODY_LIMIT, Engine, Request, RequestContext, Verdict, http_version_of, is_reguard_path
|
|
18
|
+
|
|
19
|
+
Scope = MutableMapping[str, Any]
|
|
20
|
+
Message = MutableMapping[str, Any]
|
|
21
|
+
Receive = Callable[[], Awaitable[Message]]
|
|
22
|
+
Send = Callable[[Message], Awaitable[None]]
|
|
23
|
+
ASGIApp = Callable[[Scope, Receive, Send], Awaitable[None]]
|
|
24
|
+
|
|
25
|
+
_SAFE = "/;=,:@!$&'()*+~-._"
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def request_from_scope(scope: Scope) -> Request:
|
|
29
|
+
headers: Dict[str, str] = {}
|
|
30
|
+
order: List[str] = []
|
|
31
|
+
for raw_name, raw_value in scope.get("headers") or []:
|
|
32
|
+
name = raw_name.decode("latin-1").lower() if isinstance(raw_name, (bytes, bytearray)) else str(raw_name).lower()
|
|
33
|
+
value = raw_value.decode("latin-1") if isinstance(raw_value, (bytes, bytearray)) else str(raw_value)
|
|
34
|
+
order.append(name)
|
|
35
|
+
if name in headers:
|
|
36
|
+
headers[name] = headers[name] + ("; " if name == "cookie" else ", ") + value
|
|
37
|
+
else:
|
|
38
|
+
headers[name] = value
|
|
39
|
+
raw_path = scope.get("raw_path")
|
|
40
|
+
if raw_path:
|
|
41
|
+
path = raw_path.decode("latin-1") if isinstance(raw_path, (bytes, bytearray)) else str(raw_path)
|
|
42
|
+
else:
|
|
43
|
+
path = quote(str(scope.get("path") or "/").encode("utf-8"), safe=_SAFE)
|
|
44
|
+
if "?" in path:
|
|
45
|
+
url = path # a server that left the query on raw_path
|
|
46
|
+
else:
|
|
47
|
+
qs = scope.get("query_string") or b""
|
|
48
|
+
qs_text = qs.decode("latin-1") if isinstance(qs, (bytes, bytearray)) else str(qs)
|
|
49
|
+
url = path + ("?" + qs_text if qs_text else "")
|
|
50
|
+
client = scope.get("client")
|
|
51
|
+
peer = str(client[0]) if client else ""
|
|
52
|
+
return Request(
|
|
53
|
+
method=str(scope.get("method") or "GET").upper(),
|
|
54
|
+
url=url or "/",
|
|
55
|
+
headers=headers,
|
|
56
|
+
order=order,
|
|
57
|
+
http_version=http_version_of(str(scope.get("http_version") or "1.1")),
|
|
58
|
+
peer=peer,
|
|
59
|
+
scheme=str(scope.get("scheme") or "http"),
|
|
60
|
+
)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _set_verdict(scope: Scope, v: Optional[Verdict]) -> None:
|
|
64
|
+
scope["reguard"] = v
|
|
65
|
+
state = scope.get("state")
|
|
66
|
+
if state is None:
|
|
67
|
+
state = scope["state"] = {}
|
|
68
|
+
if isinstance(state, MutableMapping):
|
|
69
|
+
state["reguard"] = v
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _encode(headers: List[Tuple[str, str]]) -> List[Tuple[bytes, bytes]]:
|
|
73
|
+
return [(n.lower().encode("latin-1"), v.encode("latin-1")) for n, v in headers]
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def _decode(headers: Any) -> List[Tuple[str, str]]:
|
|
77
|
+
out: List[Tuple[str, str]] = []
|
|
78
|
+
for n, v in headers or []:
|
|
79
|
+
out.append((n.decode("latin-1") if isinstance(n, (bytes, bytearray)) else str(n), v.decode("latin-1") if isinstance(v, (bytes, bytearray)) else str(v)))
|
|
80
|
+
return out
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
class ASGIMiddleware:
|
|
84
|
+
"""
|
|
85
|
+
Reguard for an ASGI app: serves /_s/*, adds the script tag to HTML pages, verifies the visitor's
|
|
86
|
+
verdict (``scope["reguard"]``, ``request.state.reguard``), optionally blocks, and sends request
|
|
87
|
+
summaries. Options as in ``reguard.wsgi()``.
|
|
88
|
+
"""
|
|
89
|
+
|
|
90
|
+
def __init__(self, app: ASGIApp, **options: Any) -> None:
|
|
91
|
+
self.app = app
|
|
92
|
+
self._engine = Engine(**options)
|
|
93
|
+
|
|
94
|
+
@property
|
|
95
|
+
def site(self) -> Optional[str]:
|
|
96
|
+
"""The site id read from the key (None when no key is configured)."""
|
|
97
|
+
return self._engine.site
|
|
98
|
+
|
|
99
|
+
@property
|
|
100
|
+
def engine(self) -> Engine:
|
|
101
|
+
return self._engine
|
|
102
|
+
|
|
103
|
+
def flush(self) -> None:
|
|
104
|
+
"""Send queued summaries now (blocking: call it from a thread in async code)."""
|
|
105
|
+
self._engine.flush()
|
|
106
|
+
|
|
107
|
+
def close(self) -> None:
|
|
108
|
+
"""Stop the summary thread and send what's queued (e.g. on shutdown)."""
|
|
109
|
+
self._engine.close()
|
|
110
|
+
|
|
111
|
+
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
|
|
112
|
+
eng = self._engine
|
|
113
|
+
if scope.get("type") != "http" or not eng.enabled:
|
|
114
|
+
await self.app(scope, receive, send)
|
|
115
|
+
return
|
|
116
|
+
try:
|
|
117
|
+
req = request_from_scope(scope)
|
|
118
|
+
except Exception as e:
|
|
119
|
+
eng.error(e)
|
|
120
|
+
await self.app(scope, receive, send)
|
|
121
|
+
return
|
|
122
|
+
if is_reguard_path(req.path):
|
|
123
|
+
await self._serve_reguard(req, receive, send)
|
|
124
|
+
return
|
|
125
|
+
try:
|
|
126
|
+
ctx, answer, verdict = eng.handle(req)
|
|
127
|
+
except Exception as e:
|
|
128
|
+
eng.error(e)
|
|
129
|
+
_set_verdict(scope, None)
|
|
130
|
+
await self.app(scope, receive, send)
|
|
131
|
+
return
|
|
132
|
+
_set_verdict(scope, verdict)
|
|
133
|
+
if answer is not None:
|
|
134
|
+
status, headers, body = answer
|
|
135
|
+
try:
|
|
136
|
+
await send({"type": "http.response.start", "status": status, "headers": _encode(ctx.start(status, headers))})
|
|
137
|
+
out = b"" if req.method == "HEAD" else ctx.body(body) + ctx.end()
|
|
138
|
+
await send({"type": "http.response.body", "body": out, "more_body": False})
|
|
139
|
+
finally:
|
|
140
|
+
ctx.finish()
|
|
141
|
+
return
|
|
142
|
+
await self._run_app(scope, receive, send, ctx)
|
|
143
|
+
|
|
144
|
+
async def _run_app(self, scope: Scope, receive: Receive, send: Send, ctx: RequestContext) -> None:
|
|
145
|
+
async def receive_wrapper() -> Message:
|
|
146
|
+
message = await receive()
|
|
147
|
+
if message.get("type") == "http.request":
|
|
148
|
+
ctx.capture(message.get("body") or b"")
|
|
149
|
+
return message
|
|
150
|
+
|
|
151
|
+
async def send_wrapper(message: Message) -> None:
|
|
152
|
+
kind = message.get("type")
|
|
153
|
+
if kind == "http.response.start":
|
|
154
|
+
status = int(message.get("status", 200))
|
|
155
|
+
headers = ctx.start(status, _decode(message.get("headers")))
|
|
156
|
+
await send({**message, "headers": _encode(headers)})
|
|
157
|
+
elif kind == "http.response.body":
|
|
158
|
+
more = bool(message.get("more_body", False))
|
|
159
|
+
out = ctx.body(bytes(message.get("body") or b""))
|
|
160
|
+
if not more:
|
|
161
|
+
out += ctx.end()
|
|
162
|
+
if out or not more:
|
|
163
|
+
await send({**message, "body": out, "more_body": more})
|
|
164
|
+
if not more:
|
|
165
|
+
ctx.finish()
|
|
166
|
+
else:
|
|
167
|
+
if kind in ("http.response.pathsend", "http.response.zerocopysend"):
|
|
168
|
+
if ctx.injector is not None:
|
|
169
|
+
ctx.injector.mode = "pass"
|
|
170
|
+
await send(message)
|
|
171
|
+
if kind == "http.response.pathsend" or (kind == "http.response.zerocopysend" and not message.get("more_body", False)):
|
|
172
|
+
ctx.finish()
|
|
173
|
+
|
|
174
|
+
try:
|
|
175
|
+
await self.app(scope, receive_wrapper if ctx.body_capture is not None else receive, send_wrapper)
|
|
176
|
+
except BaseException:
|
|
177
|
+
if not ctx.started_response:
|
|
178
|
+
ctx.status = 500 # the server answers 500 for an app that raised
|
|
179
|
+
ctx.finish()
|
|
180
|
+
raise
|
|
181
|
+
ctx.finish()
|
|
182
|
+
|
|
183
|
+
async def _serve_reguard(self, req: Request, receive: Receive, send: Send) -> None:
|
|
184
|
+
eng = self._engine
|
|
185
|
+
try:
|
|
186
|
+
body: Optional[bytes] = None
|
|
187
|
+
if req.method not in ("GET", "HEAD"):
|
|
188
|
+
chunks: List[bytes] = []
|
|
189
|
+
size = 0
|
|
190
|
+
while True:
|
|
191
|
+
message = await receive()
|
|
192
|
+
if message.get("type") == "http.disconnect":
|
|
193
|
+
return
|
|
194
|
+
if message.get("type") != "http.request":
|
|
195
|
+
continue
|
|
196
|
+
chunk = bytes(message.get("body") or b"")
|
|
197
|
+
size += len(chunk)
|
|
198
|
+
if size > PROXY_BODY_LIMIT:
|
|
199
|
+
raise ValueError("request body over 1 MiB")
|
|
200
|
+
chunks.append(chunk)
|
|
201
|
+
if not message.get("more_body", False):
|
|
202
|
+
break
|
|
203
|
+
body = b"".join(chunks)
|
|
204
|
+
loop = asyncio.get_running_loop()
|
|
205
|
+
status, headers, data = await loop.run_in_executor(None, eng.proxy, req, body)
|
|
206
|
+
except Exception as e:
|
|
207
|
+
eng.error(e)
|
|
208
|
+
await send({"type": "http.response.start", "status": 502, "headers": [(b"content-length", b"0")]})
|
|
209
|
+
await send({"type": "http.response.body", "body": b"", "more_body": False})
|
|
210
|
+
return
|
|
211
|
+
await send({"type": "http.response.start", "status": status, "headers": _encode(headers)})
|
|
212
|
+
await send({"type": "http.response.body", "body": data, "more_body": False})
|