flask-deck 0.3.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.
Files changed (57) hide show
  1. flask_deck/__init__.py +184 -0
  2. flask_deck/adapters/__init__.py +23 -0
  3. flask_deck/adapters/sqlalchemy.py +272 -0
  4. flask_deck/audit.py +363 -0
  5. flask_deck/auth.py +462 -0
  6. flask_deck/branding.py +217 -0
  7. flask_deck/charts.py +514 -0
  8. flask_deck/cli.py +135 -0
  9. flask_deck/config.py +81 -0
  10. flask_deck/dashboard.py +416 -0
  11. flask_deck/deck.py +4153 -0
  12. flask_deck/demo.py +1066 -0
  13. flask_deck/events.py +309 -0
  14. flask_deck/exceptions.py +34 -0
  15. flask_deck/exporter.py +240 -0
  16. flask_deck/formatters.py +386 -0
  17. flask_deck/i18n.py +399 -0
  18. flask_deck/icons.py +92 -0
  19. flask_deck/importer.py +612 -0
  20. flask_deck/introspection.py +376 -0
  21. flask_deck/jobs.py +382 -0
  22. flask_deck/mfa.py +670 -0
  23. flask_deck/model_view.py +1097 -0
  24. flask_deck/py.typed +0 -0
  25. flask_deck/query.py +1220 -0
  26. flask_deck/schema_graph.py +137 -0
  27. flask_deck/security.py +373 -0
  28. flask_deck/sql_console.py +391 -0
  29. flask_deck/sso.py +293 -0
  30. flask_deck/static/css/deck.css +1333 -0
  31. flask_deck/static/js/deck.js +1433 -0
  32. flask_deck/storage.py +669 -0
  33. flask_deck/templates/flask_deck/audit_list.html +117 -0
  34. flask_deck/templates/flask_deck/base.html +454 -0
  35. flask_deck/templates/flask_deck/custom_page.html +12 -0
  36. flask_deck/templates/flask_deck/dashboard.html +32 -0
  37. flask_deck/templates/flask_deck/diagnostics.html +80 -0
  38. flask_deck/templates/flask_deck/error.html +15 -0
  39. flask_deck/templates/flask_deck/import_wizard.html +143 -0
  40. flask_deck/templates/flask_deck/jobs_list.html +95 -0
  41. flask_deck/templates/flask_deck/login.html +93 -0
  42. flask_deck/templates/flask_deck/login_mfa.html +59 -0
  43. flask_deck/templates/flask_deck/mfa_setup.html +121 -0
  44. flask_deck/templates/flask_deck/model_detail.html +124 -0
  45. flask_deck/templates/flask_deck/model_form.html +389 -0
  46. flask_deck/templates/flask_deck/model_list.html +489 -0
  47. flask_deck/templates/flask_deck/partials/drawer_detail.html +93 -0
  48. flask_deck/templates/flask_deck/partials/widget_grid.html +207 -0
  49. flask_deck/templates/flask_deck/rbac_matrix.html +59 -0
  50. flask_deck/templates/flask_deck/record_history.html +102 -0
  51. flask_deck/templates/flask_deck/schema_inspector.html +83 -0
  52. flask_deck/templates/flask_deck/sql_console.html +87 -0
  53. flask_deck-0.3.0.dist-info/METADATA +382 -0
  54. flask_deck-0.3.0.dist-info/RECORD +57 -0
  55. flask_deck-0.3.0.dist-info/WHEEL +4 -0
  56. flask_deck-0.3.0.dist-info/entry_points.txt +5 -0
  57. flask_deck-0.3.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,137 @@
1
+ from __future__ import annotations
2
+
3
+ import math
4
+ from collections.abc import Mapping, Sequence
5
+
6
+ from markupsafe import Markup, escape
7
+
8
+ from flask_deck.introspection import ModelMeta
9
+
10
+
11
+ def render_schema_erd_svg(
12
+ metas: Sequence[ModelMeta],
13
+ row_counts: Mapping[str, int],
14
+ ) -> Markup:
15
+ """Render a crisp, strict-CSP pure SVG Entity-Relationship Diagram from frozen ModelMeta."""
16
+ if not metas:
17
+ return Markup('<div class="dk-chart-empty">No models registered</div>')
18
+
19
+ cols_per_row = min(3, max(1, len(metas)))
20
+ card_w = 240.0
21
+ header_h = 30.0
22
+ row_h = 19.0
23
+ pad_x = 56.0
24
+ pad_y = 44.0
25
+ margin = 24.0
26
+ max_fields_shown = 7
27
+
28
+ # Precompute node geometry
29
+ positions: dict[type, tuple[float, float, float, float]] = {}
30
+ node_data: list[tuple[ModelMeta, float, float, float, float]] = []
31
+
32
+ row_heights: dict[int, float] = {}
33
+ for idx, meta in enumerate(metas):
34
+ r = idx // cols_per_row
35
+ shown = min(max_fields_shown, len(meta.fields)) + (1 if len(meta.fields) > max_fields_shown else 0)
36
+ h = header_h + shown * row_h + 10.0
37
+ row_heights[r] = max(row_heights.get(r, 0.0), h)
38
+
39
+ total_rows = math.ceil(len(metas) / cols_per_row)
40
+ row_y: dict[int, float] = {}
41
+ cur_y = margin
42
+ for r in range(total_rows):
43
+ row_y[r] = cur_y
44
+ cur_y += row_heights[r] + pad_y
45
+
46
+ svg_w = margin * 2 + cols_per_row * card_w + max(0, cols_per_row - 1) * pad_x
47
+ svg_h = max(180.0, cur_y - pad_y + margin)
48
+
49
+ for idx, meta in enumerate(metas):
50
+ r = idx // cols_per_row
51
+ c = idx % cols_per_row
52
+ x = margin + c * (card_w + pad_x)
53
+ y = row_y[r]
54
+ shown = min(max_fields_shown, len(meta.fields)) + (1 if len(meta.fields) > max_fields_shown else 0)
55
+ h = header_h + shown * row_h + 10.0
56
+ positions[meta.model] = (x, y, card_w, h)
57
+ node_data.append((meta, x, y, card_w, h))
58
+
59
+ parts: list[str] = [
60
+ '<div class="dk-erd-wrap">',
61
+ f'<svg class="dk-erd-svg" viewBox="0 0 {int(svg_w)} {int(svg_h)}" role="img" aria-label="SQLAlchemy schema relationship diagram">',
62
+ '<defs>'
63
+ '<marker id="dk-erd-arrow" viewBox="0 0 10 10" refX="8" refY="5" markerWidth="6" markerHeight="6" orient="auto-start-reverse">'
64
+ '<path d="M 1 1 L 9 5 L 1 9 z" class="dk-erd-arrow-head"/>'
65
+ '</marker>'
66
+ '</defs>',
67
+ ]
68
+
69
+ # Draw FK relationship connectors underneath model nodes (including overflow fields beyond max_fields_shown)
70
+ for meta, x, y, w, _h in node_data:
71
+ for f_idx, field in enumerate(meta.fields):
72
+ if field.fk_target_model is None or field.fk_target_model not in positions:
73
+ continue
74
+ if field.fk_target_model is meta.model:
75
+ continue
76
+ tx, ty, tw, _th = positions[field.fk_target_model]
77
+ anchor_idx = min(f_idx, max_fields_shown)
78
+ fy = y + header_h + anchor_idx * row_h + row_h * 0.55
79
+ target_y = ty + header_h * 0.5
80
+
81
+ if tx >= x + w:
82
+ sx, ex = x + w, tx
83
+ mid_x = (sx + ex) / 2.0
84
+ d = f"M{sx:.1f},{fy:.1f} C{mid_x:.1f},{fy:.1f} {mid_x:.1f},{target_y:.1f} {ex:.1f},{target_y:.1f}"
85
+ elif x >= tx + tw:
86
+ sx, ex = x, tx + tw
87
+ mid_x = (sx + ex) / 2.0
88
+ d = f"M{sx:.1f},{fy:.1f} C{mid_x:.1f},{fy:.1f} {mid_x:.1f},{target_y:.1f} {ex:.1f},{target_y:.1f}"
89
+ else:
90
+ sx = x + w
91
+ ex = tx + tw
92
+ bend = min(svg_w - 4.0, max(sx, ex) + 20.0)
93
+ d = f"M{sx:.1f},{fy:.1f} C{bend:.1f},{fy:.1f} {bend:.1f},{target_y:.1f} {ex:.1f},{target_y:.1f}"
94
+
95
+ parts.append(
96
+ f'<path class="dk-erd-edge" d="{d}" marker-end="url(#dk-erd-arrow)">'
97
+ f"<title>{escape(meta.name)}.{escape(field.name)} → {escape(field.fk_target_table or '')}</title>"
98
+ "</path>"
99
+ )
100
+
101
+ # Draw model table nodes
102
+ for meta, x, y, w, h in node_data:
103
+ count = row_counts.get(meta.slug, 0)
104
+ parts.append(
105
+ f'<g class="dk-erd-node">'
106
+ f'<rect class="dk-erd-card" x="{x:.1f}" y="{y:.1f}" width="{w:.1f}" height="{h:.1f}" rx="5"/>'
107
+ f'<rect class="dk-erd-head" x="{x:.1f}" y="{y:.1f}" width="{w:.1f}" height="{header_h:.1f}" rx="5"/>'
108
+ f'<line class="dk-erd-div" x1="{x:.1f}" y1="{y + header_h:.1f}" x2="{x + w:.1f}" y2="{y + header_h:.1f}"/>'
109
+ f'<text class="dk-erd-title" x="{x + 10:.1f}" y="{y + 19:.1f}">{escape(meta.name)}</text>'
110
+ f'<text class="dk-erd-count" x="{x + w - 10:.1f}" y="{y + 19:.1f}" text-anchor="end">{count:,} rows</text>'
111
+ )
112
+ for f_idx, f in enumerate(meta.fields[:max_fields_shown]):
113
+ fy = y + header_h + (f_idx + 1) * row_h - 3.0
114
+ tag = "PK" if f.primary_key else ("FK" if f.fk_target_table else ("SEC" if f.is_sensitive else ""))
115
+ tag_cls = (
116
+ "dk-erd-tag-pk"
117
+ if f.primary_key
118
+ else ("dk-erd-tag-fk" if f.fk_target_table else "dk-erd-tag-sec")
119
+ )
120
+ name_x = x + (34.0 if tag else 10.0)
121
+ if tag:
122
+ parts.append(f'<text class="{tag_cls}" x="{x + 10:.1f}" y="{fy:.1f}">{tag}</text>')
123
+ short_name = f.name if len(f.name) <= 18 else f"{f.name[:17]}…"
124
+ parts.append(
125
+ f'<text class="dk-erd-col" x="{name_x:.1f}" y="{fy:.1f}">{escape(short_name)}</text>'
126
+ f'<text class="dk-erd-type" x="{x + w - 10:.1f}" y="{fy:.1f}" text-anchor="end">{escape(f.field_type)}</text>'
127
+ )
128
+ if len(meta.fields) > max_fields_shown:
129
+ extra = len(meta.fields) - max_fields_shown
130
+ ey = y + header_h + (max_fields_shown + 1) * row_h - 3.0
131
+ parts.append(
132
+ f'<text class="dk-erd-type" x="{x + 10:.1f}" y="{ey:.1f}">+{extra} more column(s)</text>'
133
+ )
134
+ parts.append("</g>")
135
+
136
+ parts.append("</svg></div>")
137
+ return Markup("".join(parts))
flask_deck/security.py ADDED
@@ -0,0 +1,373 @@
1
+ from __future__ import annotations
2
+
3
+ import hmac
4
+ import re
5
+ import secrets
6
+ import threading
7
+ import time
8
+ from collections import OrderedDict
9
+ from collections.abc import Iterable, Mapping
10
+ from decimal import Decimal
11
+ from typing import Any
12
+ from urllib.parse import urlsplit
13
+
14
+ from flask import Request, Response, session
15
+ from werkzeug.security import check_password_hash, generate_password_hash
16
+
17
+ CSRF_SESSION_KEY = "_deck_csrf_token"
18
+ CSRF_HEADER_NAME = "X-Deck-CSRFToken"
19
+ CSRF_FORM_FIELD = "_csrf_token"
20
+
21
+ DEFAULT_PASSWORD_HASH_METHOD = "pbkdf2:sha256:600000"
22
+
23
+ # Precomputed dummy hash for constant-time authentication when username does not exist.
24
+ _DUMMY_PASSWORD_HASH: str = generate_password_hash(
25
+ "deck-constant-time-dummy-secret-value",
26
+ method=DEFAULT_PASSWORD_HASH_METHOD,
27
+ )
28
+
29
+ DEFAULT_SENSITIVE_PATTERN: re.Pattern[str] = re.compile(
30
+ r"(?:^|_)(?:password|passwd|pwd|secret|token|api_?key|private_?key|access_?key|"
31
+ r"auth_?key|signing_?key|salt|hash(?:es)?|ssn|tckn|iban|cvv|credit_?card|card_?number|"
32
+ r"pin|passphrase|otp|mfa_?secret|recovery_?codes)(?:$|_)",
33
+ re.IGNORECASE,
34
+ )
35
+
36
+ _CSV_FORMULA_PREFIXES: tuple[str, ...] = ("=", "+", "-", "@", "\t", "\r", "\n")
37
+ _CSP_NONCE_RE: re.Pattern[str] = re.compile(r"^[A-Za-z0-9+/=_-]{8,128}$")
38
+ _CSP_IMG_SOURCE_RE: re.Pattern[str] = re.compile(
39
+ r"^https?://[A-Za-z0-9.-]+(?::\d{1,5})?(?:/[A-Za-z0-9._~:/?#\[\]@!$&()*+,;=%-]*)?$"
40
+ )
41
+
42
+
43
+ def is_valid_csp_img_source(token: str) -> bool:
44
+ """Validate an extra CSP img-src origin token (no wildcards, bare schemes, or control chars)."""
45
+ if not isinstance(token, str) or any(ord(c) <= 32 or ord(c) == 127 for c in token):
46
+ return False
47
+ clean = token.strip()
48
+ if not clean or "*" in clean or ";" in clean or "," in clean or "'" in clean or '"' in clean:
49
+ return False
50
+ if clean in {"blob:", "mediastream:"}:
51
+ return True
52
+ parsed = urlsplit(clean)
53
+ if parsed.scheme.lower() not in {"http", "https"} or not parsed.netloc:
54
+ return False
55
+ return bool(_CSP_IMG_SOURCE_RE.fullmatch(clean))
56
+
57
+
58
+ def generate_nonce() -> str:
59
+ """Return a fresh per-request cryptographic CSP nonce."""
60
+ return secrets.token_urlsafe(16)
61
+
62
+
63
+ def build_csp_header(nonce: str, *, extra_img_sources: Iterable[str] = ()) -> str:
64
+ """Build a strict Content-Security-Policy with zero unsafe-inline directives."""
65
+ safe_nonce = nonce if isinstance(nonce, str) and _CSP_NONCE_RE.fullmatch(nonce) else generate_nonce()
66
+ img_parts = ["'self'", "data:"]
67
+ for src in extra_img_sources:
68
+ clean = src.strip()
69
+ if is_valid_csp_img_source(clean):
70
+ img_parts.append(clean)
71
+ return (
72
+ "default-src 'none'; "
73
+ f"script-src 'self' 'nonce-{safe_nonce}'; "
74
+ "style-src 'self'; "
75
+ f"img-src {' '.join(img_parts)}; "
76
+ "font-src 'self'; "
77
+ "connect-src 'self'; "
78
+ "frame-ancestors 'none'; "
79
+ "base-uri 'none'; "
80
+ "form-action 'self'"
81
+ )
82
+
83
+
84
+ def apply_security_headers(
85
+ response: Response,
86
+ *,
87
+ nonce: str,
88
+ is_static: bool = False,
89
+ has_version_hash: bool = False,
90
+ extra_img_sources: Iterable[str] = (),
91
+ ) -> Response:
92
+ """Attach defense-in-depth HTTP security and caching headers to Deck responses."""
93
+ response.headers.setdefault(
94
+ "Content-Security-Policy",
95
+ build_csp_header(nonce, extra_img_sources=extra_img_sources),
96
+ )
97
+ response.headers.setdefault("X-Content-Type-Options", "nosniff")
98
+ response.headers.setdefault("X-Frame-Options", "DENY")
99
+ response.headers.setdefault("Referrer-Policy", "same-origin")
100
+ response.headers.setdefault("Permissions-Policy", "camera=(), microphone=(), geolocation=()")
101
+
102
+ if is_static:
103
+ if has_version_hash:
104
+ response.headers["Cache-Control"] = "public, max-age=31536000, immutable"
105
+ else:
106
+ response.headers.setdefault("Cache-Control", "public, max-age=3600")
107
+ else:
108
+ if "Cache-Control" not in response.headers:
109
+ response.headers["Cache-Control"] = "no-store, max-age=0"
110
+ response.headers["Pragma"] = "no-cache"
111
+
112
+ return response
113
+
114
+
115
+ def get_csrf_token() -> str:
116
+ """Fetch or create a per-session cryptographic CSRF token."""
117
+ token = session.get(CSRF_SESSION_KEY)
118
+ if not isinstance(token, str) or len(token) < 32:
119
+ token = secrets.token_urlsafe(32)
120
+ session[CSRF_SESSION_KEY] = token
121
+ return token
122
+
123
+
124
+ def rotate_csrf_token() -> str:
125
+ """Generate and persist a new CSRF token (used after authentication changes)."""
126
+ token = secrets.token_urlsafe(32)
127
+ session[CSRF_SESSION_KEY] = token
128
+ return token
129
+
130
+
131
+ def _check_origin_headers(req: Request) -> bool:
132
+ """Secondary same-origin verification using Sec-Fetch-Site and Origin headers."""
133
+ sec_fetch_site = req.headers.get("Sec-Fetch-Site", "").strip().lower()
134
+ if sec_fetch_site and sec_fetch_site not in {"same-origin", "none"}:
135
+ return False
136
+
137
+ origin = req.headers.get("Origin", "").strip()
138
+ if origin:
139
+ if origin.lower() == "null":
140
+ # Chromium may emit Origin: null on same-origin form posts under strict referrer policies.
141
+ # Allow ONLY when browser explicitly confirms Sec-Fetch-Site: same-origin.
142
+ return sec_fetch_site == "same-origin"
143
+ parsed_origin = urlsplit(origin)
144
+ parsed_host = urlsplit(req.host_url)
145
+ if (
146
+ parsed_origin.scheme.lower() != parsed_host.scheme.lower()
147
+ or parsed_origin.netloc.lower() != parsed_host.netloc.lower()
148
+ ):
149
+ return False
150
+
151
+ return True
152
+
153
+
154
+ def validate_csrf(req: Request) -> bool:
155
+ """Validate CSRF token and same-origin headers for any mutating request."""
156
+ if not _check_origin_headers(req):
157
+ return False
158
+
159
+ expected = session.get(CSRF_SESSION_KEY)
160
+ if not isinstance(expected, str) or len(expected) < 32:
161
+ return False
162
+
163
+ provided = req.headers.get(CSRF_HEADER_NAME)
164
+ if not provided:
165
+ provided = req.form.get(CSRF_FORM_FIELD)
166
+ if not provided and req.is_json:
167
+ payload = req.get_json(silent=True)
168
+ if isinstance(payload, Mapping):
169
+ raw = payload.get(CSRF_FORM_FIELD)
170
+ if isinstance(raw, str):
171
+ provided = raw
172
+
173
+ if not isinstance(provided, str) or not provided:
174
+ return False
175
+
176
+ return hmac.compare_digest(expected, provided)
177
+
178
+
179
+ def verify_password_constant_time(password_hash: str | None, candidate: str) -> bool:
180
+ """Verify a password hash without leaking username existence via timing."""
181
+ if not password_hash:
182
+ check_password_hash(_DUMMY_PASSWORD_HASH, candidate)
183
+ return False
184
+ return check_password_hash(password_hash, candidate)
185
+
186
+
187
+ def is_safe_redirect_url(target: str | None) -> bool:
188
+ """Allow only strict relative same-origin redirect targets."""
189
+ if not target or not isinstance(target, str):
190
+ return False
191
+ if "\\" in target or any(ord(ch) < 32 or ord(ch) == 127 for ch in target):
192
+ return False
193
+ if not target.startswith("/") or target.startswith("//"):
194
+ return False
195
+ parsed = urlsplit(target)
196
+ return parsed.scheme == "" and parsed.netloc == ""
197
+
198
+
199
+ def is_safe_display_url(url: str | None) -> bool:
200
+ """Allow only http://, https://, or relative / links to block javascript:/data: XSS."""
201
+ if not url or not isinstance(url, str):
202
+ return False
203
+ if "\\" in url or any(ord(ch) < 32 or ord(ch) == 127 for ch in url):
204
+ return False
205
+ stripped = url.strip()
206
+ if not stripped:
207
+ return False
208
+ if stripped.startswith("/") and not stripped.startswith("//"):
209
+ return True
210
+ parsed = urlsplit(stripped)
211
+ return parsed.scheme.lower() in {"http", "https"} and bool(parsed.netloc)
212
+
213
+
214
+ def sanitize_csv_cell(value: Any, *, enabled: bool = True) -> str:
215
+ """Neutralize spreadsheet formula injection (=, +, -, @, tab, CR, LF) in exported CSV cells."""
216
+ if value is None:
217
+ return ""
218
+ if isinstance(value, bool):
219
+ return "true" if value else "false"
220
+ if isinstance(value, (int, float, Decimal)):
221
+ return str(value)
222
+
223
+ text = str(value)
224
+ if not enabled or not text:
225
+ return text
226
+
227
+ stripped = text.lstrip(" \t\r\n")
228
+ if text.startswith(("\t", "\r", "\n")) or (stripped and stripped[0] in _CSV_FORMULA_PREFIXES):
229
+ return f"'{text}"
230
+ return text
231
+
232
+
233
+ def is_sensitive_field(
234
+ field_name: str,
235
+ extra_patterns: Iterable[re.Pattern[str]] = (),
236
+ ) -> bool:
237
+ """Return True if a column name matches built-in or custom sensitive field patterns."""
238
+ if DEFAULT_SENSITIVE_PATTERN.search(field_name):
239
+ return True
240
+ return any(pattern.search(field_name) for pattern in extra_patterns)
241
+
242
+
243
+ def mask_value(value: Any) -> Any:
244
+ """Deterministically mask a field value while preserving minimal operational utility."""
245
+ if value is None:
246
+ return None
247
+ text = str(value)
248
+ if not text:
249
+ return ""
250
+ if "@" in text and "." in text.split("@", 1)[1]:
251
+ local, domain = text.split("@", 1)
252
+ prefix = local[0] if local else "*"
253
+ return f"{prefix}***@{domain}"
254
+ if len(text) <= 4:
255
+ return "••••"
256
+ return f"••••{text[-4:]}"
257
+
258
+
259
+ def redact_mapping(
260
+ data: Mapping[str, Any],
261
+ sensitive_fields: Iterable[str],
262
+ extra_patterns: Iterable[re.Pattern[str]] = (),
263
+ ) -> dict[str, Any]:
264
+ """Return a copy of mapping with sensitive keys replaced by '[REDACTED]'."""
265
+ sensitive_set = set(sensitive_fields)
266
+ redacted: dict[str, Any] = {}
267
+ for key, val in data.items():
268
+ if key in sensitive_set or is_sensitive_field(key, extra_patterns):
269
+ redacted[key] = "[REDACTED]"
270
+ else:
271
+ redacted[key] = val
272
+ return redacted
273
+
274
+
275
+ def escape_like(term: str) -> str:
276
+ """Escape SQL LIKE wildcards (\\, %, _) for safe substring searches."""
277
+ return term.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")
278
+
279
+
280
+ def check_json_depth(value: Any, max_depth: int, _current: int = 0) -> bool:
281
+ """Return False if a parsed JSON structure exceeds max_depth."""
282
+ if _current > max_depth:
283
+ return False
284
+ if isinstance(value, dict):
285
+ return all(check_json_depth(v, max_depth, _current + 1) for v in value.values())
286
+ if isinstance(value, list):
287
+ return all(check_json_depth(v, max_depth, _current + 1) for v in value)
288
+ return True
289
+
290
+
291
+ class LoginRateLimiter:
292
+ """Thread-safe bounded sliding-window login brute-force throttler."""
293
+
294
+ __slots__ = (
295
+ "_attempts",
296
+ "_lock",
297
+ "_lockout_seconds",
298
+ "_lockouts",
299
+ "_max_attempts",
300
+ "_max_keys",
301
+ "_window_seconds",
302
+ )
303
+
304
+ def __init__(
305
+ self,
306
+ *,
307
+ max_attempts: int = 5,
308
+ window_seconds: int = 300,
309
+ lockout_seconds: int = 300,
310
+ max_keys: int = 10000,
311
+ ) -> None:
312
+ self._max_attempts = max_attempts
313
+ self._window_seconds = window_seconds
314
+ self._lockout_seconds = lockout_seconds
315
+ self._max_keys = max_keys
316
+ self._attempts: OrderedDict[str, list[float]] = OrderedDict()
317
+ self._lockouts: OrderedDict[str, float] = OrderedDict()
318
+ self._lock = threading.Lock()
319
+
320
+ def _evict_if_needed(self, store: OrderedDict[str, Any]) -> None:
321
+ while len(store) > self._max_keys:
322
+ store.popitem(last=False)
323
+
324
+ def _keys(self, ip: str, username: str) -> tuple[str, ...]:
325
+ clean_ip = (ip or "unknown").strip()[:64]
326
+ clean_user = (username or "").strip().lower()[:128]
327
+ if clean_user:
328
+ return (f"ip:{clean_ip}", f"pair:{clean_ip}:{clean_user}", f"user:{clean_user}")
329
+ return (f"ip:{clean_ip}", f"pair:{clean_ip}:")
330
+
331
+ def is_locked(self, ip: str, username: str = "") -> tuple[bool, int]:
332
+ """Return (locked, retry_after_seconds)."""
333
+ now = time.monotonic()
334
+ with self._lock:
335
+ for key in self._keys(ip, username):
336
+ until = self._lockouts.get(key)
337
+ if until is not None:
338
+ if until > now:
339
+ return True, max(1, int(until - now))
340
+ self._lockouts.pop(key, None)
341
+ return False, 0
342
+
343
+ def record_failure(self, ip: str, username: str = "") -> None:
344
+ """Record a failed authentication attempt and engage lockout if threshold is reached."""
345
+ now = time.monotonic()
346
+ cutoff = now - self._window_seconds
347
+ with self._lock:
348
+ for key in self._keys(ip, username):
349
+ # IP-only bucket allows 3x threshold (shared NATs); per-user bucket allows 2x
350
+ # to defeat distributed IP-rotation brute force without trivial single-typo lockouts.
351
+ if key.startswith("ip:"):
352
+ limit = self._max_attempts * 3
353
+ elif key.startswith("user:"):
354
+ limit = self._max_attempts * 2
355
+ else:
356
+ limit = self._max_attempts
357
+ timestamps = [t for t in self._attempts.get(key, []) if t >= cutoff]
358
+ timestamps.append(now)
359
+ self._attempts[key] = timestamps
360
+ self._attempts.move_to_end(key)
361
+ self._evict_if_needed(self._attempts)
362
+ if len(timestamps) >= limit:
363
+ self._lockouts[key] = now + self._lockout_seconds
364
+ self._lockouts.move_to_end(key)
365
+ self._evict_if_needed(self._lockouts)
366
+
367
+ def record_success(self, ip: str, username: str = "") -> None:
368
+ """Clear pair and per-user failure history after a successful authentication."""
369
+ keys = self._keys(ip, username)
370
+ with self._lock:
371
+ for key in keys[1:]:
372
+ self._attempts.pop(key, None)
373
+ self._lockouts.pop(key, None)