csrf-shield 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.
@@ -0,0 +1,219 @@
1
+ """Zero-dependency Fetch Metadata (Sec-Fetch-Site) + Origin CSRF protection
2
+ for Python ASGI (FastAPI/Starlette) and WSGI (Flask/Django) apps.
3
+ """
4
+ from __future__ import annotations
5
+
6
+ import json
7
+ import logging
8
+ from dataclasses import dataclass, asdict
9
+ from typing import Callable, Iterable
10
+ from urllib.parse import urlparse
11
+
12
+ logger = logging.getLogger("csrf_shield")
13
+
14
+ SAFE_METHODS = frozenset({"GET", "HEAD", "OPTIONS"})
15
+
16
+
17
+ def _normalize_origin(origin: str) -> str:
18
+ return (origin or "").strip().lower().rstrip("/")
19
+
20
+
21
+ @dataclass
22
+ class Violation:
23
+ method: str
24
+ path: str
25
+ sec_fetch_site: str
26
+ origin: str
27
+ reason: str
28
+ action: str # "reported" or "blocked"
29
+ count: int = 1
30
+
31
+
32
+ class CSRFShield:
33
+ """Core language-standard Fetch Metadata + Origin CSRF guard."""
34
+
35
+ def __init__(
36
+ self,
37
+ *,
38
+ mode: str = "report-only",
39
+ bypass_paths: Iterable[str] = (),
40
+ trusted_origins: Iterable[str] = (),
41
+ auto_patch_cookies: bool = True,
42
+ on_violation: Callable[[Violation], None] | None = None,
43
+ ) -> None:
44
+ if mode not in ("report-only", "enforce"):
45
+ raise ValueError("mode must be 'report-only' or 'enforce'")
46
+ self.mode = mode
47
+ self.bypass_paths = [p.strip() for p in bypass_paths if p and p.strip()]
48
+ self.trusted_origins = {
49
+ _normalize_origin(o) for o in trusted_origins if o and o.strip()
50
+ }
51
+ self.auto_patch_cookies = auto_patch_cookies
52
+ self.on_violation = on_violation or (
53
+ lambda v: logger.warning(
54
+ "[csrf-shield] %s %s %s (%s)", v.action.upper(), v.method, v.path, v.reason
55
+ )
56
+ )
57
+ self._violations: dict[str, Violation] = {}
58
+
59
+ def _is_bypassed(self, path: str) -> bool:
60
+ return any(path == prefix or path.startswith(prefix) for prefix in self.bypass_paths)
61
+
62
+ def check(self, method: str, path: str, headers: dict[str, str]) -> tuple[bool, str]:
63
+ """Return (allowed, reason) for an HTTP request."""
64
+ if method.upper() in SAFE_METHODS:
65
+ return True, ""
66
+
67
+ if self._is_bypassed(path):
68
+ return True, ""
69
+
70
+ lower_headers = {k.lower(): v for k, v in headers.items()}
71
+ origin = _normalize_origin(lower_headers.get("origin", ""))
72
+ if origin and origin in self.trusted_origins:
73
+ return True, ""
74
+
75
+ sec_fetch_site = lower_headers.get("sec-fetch-site", "").lower()
76
+ if sec_fetch_site:
77
+ if sec_fetch_site in ("same-origin", "none"):
78
+ return True, ""
79
+ return False, f"cross-site request blocked via Sec-Fetch-Site: {sec_fetch_site}"
80
+
81
+ if origin:
82
+ parsed = urlparse(origin)
83
+ req_host = lower_headers.get("host", "").lower()
84
+ if not parsed.netloc or parsed.netloc.lower() != req_host:
85
+ return False, f"Origin header ({origin}) does not match Host ({req_host})"
86
+ return True, ""
87
+
88
+ # Non-browser client (curl, server-to-server)
89
+ return True, ""
90
+
91
+ def record(self, method: str, path: str, headers: dict[str, str], reason: str) -> Violation:
92
+ lower_headers = {k.lower(): v for k, v in headers.items()}
93
+ action = "blocked" if self.mode == "enforce" else "reported"
94
+ key = f"{method.upper()} {path} {lower_headers.get('sec-fetch-site', '')}"
95
+ if key in self._violations:
96
+ v = self._violations[key]
97
+ v.count += 1
98
+ v.action = action
99
+ else:
100
+ v = Violation(
101
+ method=method.upper(),
102
+ path=path,
103
+ sec_fetch_site=lower_headers.get("sec-fetch-site", ""),
104
+ origin=lower_headers.get("origin", ""),
105
+ reason=reason,
106
+ action=action,
107
+ )
108
+ self._violations[key] = v
109
+ self.on_violation(v)
110
+ return v
111
+
112
+ def patch_cookie(self, cookie_value: str) -> str:
113
+ if not self.auto_patch_cookies:
114
+ return cookie_value
115
+ if "samesite=" not in cookie_value.lower():
116
+ return f"{cookie_value}; SameSite=Lax"
117
+ return cookie_value
118
+
119
+ def report(self) -> list[dict]:
120
+ return [asdict(v) for v in self._violations.values()]
121
+
122
+
123
+ class ASGIMiddleware:
124
+ """Drop-in ASGI middleware for FastAPI / Starlette:
125
+ app.add_middleware(ASGIMiddleware, mode="enforce")
126
+ """
127
+
128
+ def __init__(self, app, **shield_kwargs) -> None:
129
+ self.app = app
130
+ self.shield = CSRFShield(**shield_kwargs)
131
+
132
+ async def __call__(self, scope, receive, send):
133
+ if scope.get("type") != "http":
134
+ await self.app(scope, receive, send)
135
+ return
136
+
137
+ method = scope.get("method", "GET")
138
+ path = scope.get("path", "/")
139
+ headers = {
140
+ k.decode("latin-1").lower(): v.decode("latin-1")
141
+ for k, v in scope.get("headers", [])
142
+ }
143
+
144
+ allowed, reason = self.shield.check(method, path, headers)
145
+ if not allowed:
146
+ self.shield.record(method, path, headers, reason)
147
+ if self.shield.mode == "enforce":
148
+ body = json.dumps({"error": "csrf_blocked", "reason": reason}).encode("utf-8")
149
+ await send(
150
+ {
151
+ "type": "http.response.start",
152
+ "status": 403,
153
+ "headers": [
154
+ (b"content-type", b"application/json"),
155
+ (b"content-length", str(len(body)).encode("latin-1")),
156
+ ],
157
+ }
158
+ )
159
+ await send({"type": "http.response.body", "body": body})
160
+ return
161
+
162
+ async def patched_send(message):
163
+ if message.get("type") == "http.response.start" and self.shield.auto_patch_cookies:
164
+ new_headers = []
165
+ for k, v in message.get("headers", []):
166
+ if k.lower() == b"set-cookie":
167
+ patched = self.shield.patch_cookie(v.decode("latin-1")).encode("latin-1")
168
+ new_headers.append((k, patched))
169
+ else:
170
+ new_headers.append((k, v))
171
+ message = {**message, "headers": new_headers}
172
+ await send(message)
173
+
174
+ await self.app(scope, receive, patched_send)
175
+
176
+
177
+ class WSGIMiddleware:
178
+ """Drop-in WSGI middleware for Flask / Django:
179
+ app.wsgi_app = WSGIMiddleware(app.wsgi_app, mode="enforce")
180
+ """
181
+
182
+ def __init__(self, app, **shield_kwargs) -> None:
183
+ self.app = app
184
+ self.shield = CSRFShield(**shield_kwargs)
185
+
186
+ def __call__(self, environ, start_response):
187
+ method = environ.get("REQUEST_METHOD", "GET")
188
+ path = environ.get("PATH_INFO", "/")
189
+ headers = {}
190
+ if "HTTP_HOST" in environ:
191
+ headers["host"] = environ["HTTP_HOST"]
192
+ if "HTTP_ORIGIN" in environ:
193
+ headers["origin"] = environ["HTTP_ORIGIN"]
194
+ if "HTTP_SEC_FETCH_SITE" in environ:
195
+ headers["sec-fetch-site"] = environ["HTTP_SEC_FETCH_SITE"]
196
+
197
+ allowed, reason = self.shield.check(method, path, headers)
198
+ if not allowed:
199
+ self.shield.record(method, path, headers, reason)
200
+ if self.shield.mode == "enforce":
201
+ body = json.dumps({"error": "csrf_blocked", "reason": reason}).encode("utf-8")
202
+ start_response(
203
+ "403 Forbidden",
204
+ [("Content-Type", "application/json"), ("Content-Length", str(len(body)))],
205
+ )
206
+ return [body]
207
+
208
+ def patched_start_response(status, response_headers, exc_info=None):
209
+ if self.shield.auto_patch_cookies:
210
+ response_headers = [
211
+ (k, self.shield.patch_cookie(v) if k.lower() == "set-cookie" else v)
212
+ for k, v in response_headers
213
+ ]
214
+ return start_response(status, response_headers, exc_info)
215
+
216
+ return self.app(environ, patched_start_response)
217
+
218
+
219
+ __all__ = ["CSRFShield", "ASGIMiddleware", "WSGIMiddleware", "Violation"]
@@ -0,0 +1,46 @@
1
+ Metadata-Version: 2.4
2
+ Name: csrf-shield
3
+ Version: 0.1.0
4
+ Summary: Zero-dependency Fetch Metadata (Sec-Fetch-Site) + Origin CSRF middleware for FastAPI/ASGI and Flask/WSGI.
5
+ Author: milderbronze
6
+ License: MIT
7
+ Project-URL: Homepage, https://github.com/milderbronze/csrf-shield
8
+ Project-URL: Repository, https://github.com/milderbronze/csrf-shield
9
+ Keywords: csrf,security,fastapi,flask,asgi,wsgi,sec-fetch-site
10
+ Requires-Python: >=3.10
11
+ Description-Content-Type: text/markdown
12
+
13
+ # csrf-shield (Python)
14
+
15
+ Zero-dependency Fetch Metadata (`Sec-Fetch-Site`) + `Origin` CSRF middleware for **FastAPI / Starlette (ASGI)** and **Flask / Django (WSGI)**, with `report-only` rollout mode and automatic `SameSite=Lax` cookie hardening.
16
+
17
+ ## Install
18
+ ```bash
19
+ pip install csrf-shield
20
+ ```
21
+
22
+ ## Usage
23
+
24
+ ### FastAPI / Starlette (ASGI)
25
+ ```python
26
+ from fastapi import FastAPI
27
+ from csrf_shield import ASGIMiddleware
28
+
29
+ app = FastAPI()
30
+ app.add_middleware(
31
+ ASGIMiddleware,
32
+ mode="report-only", # switch to "enforce" after checking logs
33
+ bypass_paths=["/webhooks/"],
34
+ )
35
+ ```
36
+
37
+ ### Flask / Django (WSGI)
38
+ ```python
39
+ from flask import Flask
40
+ from csrf_shield import WSGIMiddleware
41
+
42
+ app = Flask(__name__)
43
+ app.wsgi_app = WSGIMiddleware(app.wsgi_app, mode="enforce")
44
+ ```
45
+
46
+ Full documentation, Go/Docker sidecar, and Node.js package: https://github.com/MilderBronze/csrf-shield
@@ -0,0 +1,5 @@
1
+ csrf_shield/__init__.py,sha256=pHwlYVK9HzaRxYy_iCaOrv8wLyDQ5KGJ3ZKT46q72A0,8124
2
+ csrf_shield-0.1.0.dist-info/METADATA,sha256=LVro4-REUMIbLgMy3t2AoAAk33a9w2ti9vNcOe0CtQE,1336
3
+ csrf_shield-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
4
+ csrf_shield-0.1.0.dist-info/top_level.txt,sha256=RTdJz62RN7b9t6HYfBcB759S0TJqYVBI96jR9ZzWGx4,12
5
+ csrf_shield-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1 @@
1
+ csrf_shield