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.
- flask_deck/__init__.py +184 -0
- flask_deck/adapters/__init__.py +23 -0
- flask_deck/adapters/sqlalchemy.py +272 -0
- flask_deck/audit.py +363 -0
- flask_deck/auth.py +462 -0
- flask_deck/branding.py +217 -0
- flask_deck/charts.py +514 -0
- flask_deck/cli.py +135 -0
- flask_deck/config.py +81 -0
- flask_deck/dashboard.py +416 -0
- flask_deck/deck.py +4153 -0
- flask_deck/demo.py +1066 -0
- flask_deck/events.py +309 -0
- flask_deck/exceptions.py +34 -0
- flask_deck/exporter.py +240 -0
- flask_deck/formatters.py +386 -0
- flask_deck/i18n.py +399 -0
- flask_deck/icons.py +92 -0
- flask_deck/importer.py +612 -0
- flask_deck/introspection.py +376 -0
- flask_deck/jobs.py +382 -0
- flask_deck/mfa.py +670 -0
- flask_deck/model_view.py +1097 -0
- flask_deck/py.typed +0 -0
- flask_deck/query.py +1220 -0
- flask_deck/schema_graph.py +137 -0
- flask_deck/security.py +373 -0
- flask_deck/sql_console.py +391 -0
- flask_deck/sso.py +293 -0
- flask_deck/static/css/deck.css +1333 -0
- flask_deck/static/js/deck.js +1433 -0
- flask_deck/storage.py +669 -0
- flask_deck/templates/flask_deck/audit_list.html +117 -0
- flask_deck/templates/flask_deck/base.html +454 -0
- flask_deck/templates/flask_deck/custom_page.html +12 -0
- flask_deck/templates/flask_deck/dashboard.html +32 -0
- flask_deck/templates/flask_deck/diagnostics.html +80 -0
- flask_deck/templates/flask_deck/error.html +15 -0
- flask_deck/templates/flask_deck/import_wizard.html +143 -0
- flask_deck/templates/flask_deck/jobs_list.html +95 -0
- flask_deck/templates/flask_deck/login.html +93 -0
- flask_deck/templates/flask_deck/login_mfa.html +59 -0
- flask_deck/templates/flask_deck/mfa_setup.html +121 -0
- flask_deck/templates/flask_deck/model_detail.html +124 -0
- flask_deck/templates/flask_deck/model_form.html +389 -0
- flask_deck/templates/flask_deck/model_list.html +489 -0
- flask_deck/templates/flask_deck/partials/drawer_detail.html +93 -0
- flask_deck/templates/flask_deck/partials/widget_grid.html +207 -0
- flask_deck/templates/flask_deck/rbac_matrix.html +59 -0
- flask_deck/templates/flask_deck/record_history.html +102 -0
- flask_deck/templates/flask_deck/schema_inspector.html +83 -0
- flask_deck/templates/flask_deck/sql_console.html +87 -0
- flask_deck-0.3.0.dist-info/METADATA +382 -0
- flask_deck-0.3.0.dist-info/RECORD +57 -0
- flask_deck-0.3.0.dist-info/WHEEL +4 -0
- flask_deck-0.3.0.dist-info/entry_points.txt +5 -0
- flask_deck-0.3.0.dist-info/licenses/LICENSE +21 -0
flask_deck/audit.py
ADDED
|
@@ -0,0 +1,363 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import enum
|
|
4
|
+
import json
|
|
5
|
+
import re
|
|
6
|
+
import threading
|
|
7
|
+
import uuid
|
|
8
|
+
from abc import ABC, abstractmethod
|
|
9
|
+
from collections import deque
|
|
10
|
+
from collections.abc import Iterable, Mapping
|
|
11
|
+
from dataclasses import dataclass, field
|
|
12
|
+
from datetime import date, datetime, time, timezone
|
|
13
|
+
from decimal import Decimal
|
|
14
|
+
from typing import Any
|
|
15
|
+
|
|
16
|
+
import sqlalchemy as sa
|
|
17
|
+
from sqlalchemy.engine import Engine
|
|
18
|
+
|
|
19
|
+
from flask_deck.security import escape_like, is_sensitive_field
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def serialize_audit_value(
|
|
23
|
+
value: Any,
|
|
24
|
+
*,
|
|
25
|
+
extra_sensitive_patterns: Iterable[re.Pattern[str]] = (),
|
|
26
|
+
) -> Any:
|
|
27
|
+
"""Normalize SQLAlchemy/Python values into deterministic JSON-serializable primitives."""
|
|
28
|
+
if value is None or isinstance(value, (bool, int, float, str)):
|
|
29
|
+
return value
|
|
30
|
+
if isinstance(value, enum.Enum):
|
|
31
|
+
return value.value
|
|
32
|
+
if isinstance(value, datetime):
|
|
33
|
+
if value.tzinfo is not None:
|
|
34
|
+
value = value.astimezone(timezone.utc).replace(tzinfo=None)
|
|
35
|
+
return value.isoformat()
|
|
36
|
+
if isinstance(value, (date, time)):
|
|
37
|
+
return value.isoformat()
|
|
38
|
+
if isinstance(value, (Decimal, uuid.UUID)):
|
|
39
|
+
return str(value)
|
|
40
|
+
if isinstance(value, bytes):
|
|
41
|
+
return f"<bytes:{len(value)}>"
|
|
42
|
+
if isinstance(value, Mapping):
|
|
43
|
+
out: dict[str, Any] = {}
|
|
44
|
+
for k, v in value.items():
|
|
45
|
+
ks = str(k)
|
|
46
|
+
if is_sensitive_field(ks, extra_sensitive_patterns):
|
|
47
|
+
out[ks] = "[REDACTED]"
|
|
48
|
+
else:
|
|
49
|
+
out[ks] = serialize_audit_value(
|
|
50
|
+
v, extra_sensitive_patterns=extra_sensitive_patterns
|
|
51
|
+
)
|
|
52
|
+
return out
|
|
53
|
+
if isinstance(value, (list, tuple, set, frozenset)):
|
|
54
|
+
return [
|
|
55
|
+
serialize_audit_value(v, extra_sensitive_patterns=extra_sensitive_patterns)
|
|
56
|
+
for v in value
|
|
57
|
+
]
|
|
58
|
+
return str(value)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def compute_diff(
|
|
62
|
+
old_data: Mapping[str, Any],
|
|
63
|
+
new_data: Mapping[str, Any],
|
|
64
|
+
*,
|
|
65
|
+
sensitive_fields: Iterable[str] = (),
|
|
66
|
+
extra_sensitive_patterns: Iterable[re.Pattern[str]] = (),
|
|
67
|
+
) -> dict[str, dict[str, Any]]:
|
|
68
|
+
"""Compute field-level {field: {'old': ..., 'new': ...}} diff with automatic redaction."""
|
|
69
|
+
sensitive_set = set(sensitive_fields)
|
|
70
|
+
patterns = tuple(extra_sensitive_patterns)
|
|
71
|
+
diff: dict[str, dict[str, Any]] = {}
|
|
72
|
+
all_keys = sorted(set(old_data.keys()) | set(new_data.keys()))
|
|
73
|
+
for key in all_keys:
|
|
74
|
+
old_val = serialize_audit_value(old_data.get(key), extra_sensitive_patterns=patterns)
|
|
75
|
+
new_val = serialize_audit_value(new_data.get(key), extra_sensitive_patterns=patterns)
|
|
76
|
+
if old_val == new_val:
|
|
77
|
+
continue
|
|
78
|
+
if key in sensitive_set or is_sensitive_field(key, patterns):
|
|
79
|
+
diff[key] = {"old": "[REDACTED]", "new": "[REDACTED]"}
|
|
80
|
+
else:
|
|
81
|
+
diff[key] = {"old": old_val, "new": new_val}
|
|
82
|
+
return diff
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
@dataclass(frozen=True, slots=True)
|
|
86
|
+
class AuditEntry:
|
|
87
|
+
"""Immutable audit log record capturing who changed what, when, and how."""
|
|
88
|
+
|
|
89
|
+
id: str
|
|
90
|
+
timestamp: datetime
|
|
91
|
+
actor_id: str
|
|
92
|
+
actor_name: str
|
|
93
|
+
actor_ip: str
|
|
94
|
+
action: str # create | update | delete | bulk_action | import | inline_edit | revert
|
|
95
|
+
model_slug: str
|
|
96
|
+
model_label: str
|
|
97
|
+
record_pk: str
|
|
98
|
+
record_repr: str
|
|
99
|
+
changes: dict[str, dict[str, Any]] = field(default_factory=dict)
|
|
100
|
+
metadata: dict[str, Any] = field(default_factory=dict)
|
|
101
|
+
|
|
102
|
+
@property
|
|
103
|
+
def is_revertible(self) -> bool:
|
|
104
|
+
if self.action not in {"update", "inline_edit"} or not self.changes:
|
|
105
|
+
return False
|
|
106
|
+
# Do not attempt to revert redacted sensitive fields alone if all fields are redacted.
|
|
107
|
+
return any(
|
|
108
|
+
v.get("old") != "[REDACTED]" and v.get("new") != "[REDACTED]"
|
|
109
|
+
for v in self.changes.values()
|
|
110
|
+
)
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
class AuditStore(ABC):
|
|
114
|
+
"""Pluggable audit log persistence interface."""
|
|
115
|
+
|
|
116
|
+
@abstractmethod
|
|
117
|
+
def record(self, entry: AuditEntry) -> AuditEntry:
|
|
118
|
+
"""Persist a new AuditEntry."""
|
|
119
|
+
|
|
120
|
+
@abstractmethod
|
|
121
|
+
def list_entries(
|
|
122
|
+
self,
|
|
123
|
+
*,
|
|
124
|
+
model_slug: str | None = None,
|
|
125
|
+
record_pk: str | None = None,
|
|
126
|
+
action: str | None = None,
|
|
127
|
+
actor: str | None = None,
|
|
128
|
+
search: str | None = None,
|
|
129
|
+
limit: int = 50,
|
|
130
|
+
offset: int = 0,
|
|
131
|
+
) -> tuple[list[AuditEntry], int]:
|
|
132
|
+
"""Return paginated AuditEntry list (newest first) and total count."""
|
|
133
|
+
|
|
134
|
+
@abstractmethod
|
|
135
|
+
def get_entry(self, entry_id: str) -> AuditEntry | None:
|
|
136
|
+
"""Fetch a single AuditEntry by ID."""
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
class InMemoryAuditStore(AuditStore):
|
|
140
|
+
"""Thread-safe bounded ring-buffer audit store for tests and ephemeral demos."""
|
|
141
|
+
|
|
142
|
+
__slots__ = ("_entries", "_lock", "_max_entries")
|
|
143
|
+
|
|
144
|
+
def __init__(self, max_entries: int = 2000) -> None:
|
|
145
|
+
self._max_entries = max(10, max_entries)
|
|
146
|
+
self._entries: deque[AuditEntry] = deque(maxlen=self._max_entries)
|
|
147
|
+
self._lock = threading.Lock()
|
|
148
|
+
|
|
149
|
+
def record(self, entry: AuditEntry) -> AuditEntry:
|
|
150
|
+
with self._lock:
|
|
151
|
+
self._entries.appendleft(entry)
|
|
152
|
+
return entry
|
|
153
|
+
|
|
154
|
+
def list_entries(
|
|
155
|
+
self,
|
|
156
|
+
*,
|
|
157
|
+
model_slug: str | None = None,
|
|
158
|
+
record_pk: str | None = None,
|
|
159
|
+
action: str | None = None,
|
|
160
|
+
actor: str | None = None,
|
|
161
|
+
search: str | None = None,
|
|
162
|
+
limit: int = 50,
|
|
163
|
+
offset: int = 0,
|
|
164
|
+
) -> tuple[list[AuditEntry], int]:
|
|
165
|
+
with self._lock:
|
|
166
|
+
snapshot = list(self._entries)
|
|
167
|
+
|
|
168
|
+
filtered: list[AuditEntry] = []
|
|
169
|
+
q = (search or "").strip().lower()
|
|
170
|
+
actor_q = (actor or "").strip().lower()
|
|
171
|
+
for item in snapshot:
|
|
172
|
+
if model_slug and item.model_slug != model_slug:
|
|
173
|
+
continue
|
|
174
|
+
if record_pk and item.record_pk != record_pk:
|
|
175
|
+
continue
|
|
176
|
+
if action and item.action != action:
|
|
177
|
+
continue
|
|
178
|
+
if actor_q and actor_q not in item.actor_name.lower() and actor_q not in item.actor_id.lower():
|
|
179
|
+
continue
|
|
180
|
+
if q and (
|
|
181
|
+
q not in item.record_repr.lower()
|
|
182
|
+
and q not in item.record_pk.lower()
|
|
183
|
+
and q not in item.model_label.lower()
|
|
184
|
+
and q not in item.actor_name.lower()
|
|
185
|
+
and q not in json.dumps(item.changes).lower()
|
|
186
|
+
):
|
|
187
|
+
continue
|
|
188
|
+
filtered.append(item)
|
|
189
|
+
|
|
190
|
+
total = len(filtered)
|
|
191
|
+
return filtered[offset : offset + limit], total
|
|
192
|
+
|
|
193
|
+
def get_entry(self, entry_id: str) -> AuditEntry | None:
|
|
194
|
+
with self._lock:
|
|
195
|
+
for item in self._entries:
|
|
196
|
+
if item.id == entry_id:
|
|
197
|
+
return item
|
|
198
|
+
return None
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
class SQLAlchemyAuditStore(AuditStore):
|
|
202
|
+
"""Persistent SQLAlchemy Core audit store using an isolated metadata table."""
|
|
203
|
+
|
|
204
|
+
def __init__(
|
|
205
|
+
self,
|
|
206
|
+
engine: Engine,
|
|
207
|
+
*,
|
|
208
|
+
table_name: str = "flask_deck_audit_logs",
|
|
209
|
+
auto_create: bool = True,
|
|
210
|
+
) -> None:
|
|
211
|
+
self._engine = engine
|
|
212
|
+
self._metadata = sa.MetaData()
|
|
213
|
+
self._table = sa.Table(
|
|
214
|
+
table_name,
|
|
215
|
+
self._metadata,
|
|
216
|
+
sa.Column("id", sa.String(36), primary_key=True),
|
|
217
|
+
sa.Column("timestamp", sa.DateTime(timezone=True), nullable=False, index=True),
|
|
218
|
+
sa.Column("actor_id", sa.String(128), nullable=False, index=True),
|
|
219
|
+
sa.Column("actor_name", sa.String(128), nullable=False),
|
|
220
|
+
sa.Column("actor_ip", sa.String(64), nullable=False),
|
|
221
|
+
sa.Column("action", sa.String(32), nullable=False, index=True),
|
|
222
|
+
sa.Column("model_slug", sa.String(128), nullable=False, index=True),
|
|
223
|
+
sa.Column("model_label", sa.String(128), nullable=False),
|
|
224
|
+
sa.Column("record_pk", sa.String(256), nullable=False, index=True),
|
|
225
|
+
sa.Column("record_repr", sa.String(256), nullable=False),
|
|
226
|
+
sa.Column("changes_json", sa.Text, nullable=False),
|
|
227
|
+
sa.Column("metadata_json", sa.Text, nullable=False),
|
|
228
|
+
)
|
|
229
|
+
if auto_create:
|
|
230
|
+
self._metadata.create_all(self._engine, checkfirst=True)
|
|
231
|
+
|
|
232
|
+
def _row_to_entry(self, row: sa.RowMapping) -> AuditEntry:
|
|
233
|
+
ts = row["timestamp"]
|
|
234
|
+
if isinstance(ts, datetime) and ts.tzinfo is None:
|
|
235
|
+
ts = ts.replace(tzinfo=timezone.utc)
|
|
236
|
+
return AuditEntry(
|
|
237
|
+
id=str(row["id"]),
|
|
238
|
+
timestamp=ts,
|
|
239
|
+
actor_id=str(row["actor_id"]),
|
|
240
|
+
actor_name=str(row["actor_name"]),
|
|
241
|
+
actor_ip=str(row["actor_ip"]),
|
|
242
|
+
action=str(row["action"]),
|
|
243
|
+
model_slug=str(row["model_slug"]),
|
|
244
|
+
model_label=str(row["model_label"]),
|
|
245
|
+
record_pk=str(row["record_pk"]),
|
|
246
|
+
record_repr=str(row["record_repr"]),
|
|
247
|
+
changes=json.loads(row["changes_json"] or "{}"),
|
|
248
|
+
metadata=json.loads(row["metadata_json"] or "{}"),
|
|
249
|
+
)
|
|
250
|
+
|
|
251
|
+
def record(self, entry: AuditEntry) -> AuditEntry:
|
|
252
|
+
with self._engine.begin() as conn:
|
|
253
|
+
conn.execute(
|
|
254
|
+
self._table.insert().values(
|
|
255
|
+
id=entry.id,
|
|
256
|
+
timestamp=entry.timestamp,
|
|
257
|
+
actor_id=entry.actor_id[:128],
|
|
258
|
+
actor_name=entry.actor_name[:128],
|
|
259
|
+
actor_ip=entry.actor_ip[:64],
|
|
260
|
+
action=entry.action[:32],
|
|
261
|
+
model_slug=entry.model_slug[:128],
|
|
262
|
+
model_label=entry.model_label[:128],
|
|
263
|
+
record_pk=entry.record_pk[:256],
|
|
264
|
+
record_repr=entry.record_repr[:256],
|
|
265
|
+
changes_json=json.dumps(entry.changes, default=str),
|
|
266
|
+
metadata_json=json.dumps(entry.metadata, default=str),
|
|
267
|
+
)
|
|
268
|
+
)
|
|
269
|
+
return entry
|
|
270
|
+
|
|
271
|
+
def list_entries(
|
|
272
|
+
self,
|
|
273
|
+
*,
|
|
274
|
+
model_slug: str | None = None,
|
|
275
|
+
record_pk: str | None = None,
|
|
276
|
+
action: str | None = None,
|
|
277
|
+
actor: str | None = None,
|
|
278
|
+
search: str | None = None,
|
|
279
|
+
limit: int = 50,
|
|
280
|
+
offset: int = 0,
|
|
281
|
+
) -> tuple[list[AuditEntry], int]:
|
|
282
|
+
t = self._table
|
|
283
|
+
conditions: list[sa.ColumnElement[bool]] = []
|
|
284
|
+
if model_slug:
|
|
285
|
+
conditions.append(t.c.model_slug == model_slug)
|
|
286
|
+
if record_pk:
|
|
287
|
+
conditions.append(t.c.record_pk == record_pk)
|
|
288
|
+
if action:
|
|
289
|
+
conditions.append(t.c.action == action)
|
|
290
|
+
if actor:
|
|
291
|
+
like_actor = f"%{escape_like(actor.strip())}%"
|
|
292
|
+
conditions.append(
|
|
293
|
+
sa.or_(
|
|
294
|
+
t.c.actor_name.ilike(like_actor, escape="\\"),
|
|
295
|
+
t.c.actor_id.ilike(like_actor, escape="\\"),
|
|
296
|
+
)
|
|
297
|
+
)
|
|
298
|
+
if search:
|
|
299
|
+
like_q = f"%{escape_like(search.strip())}%"
|
|
300
|
+
conditions.append(
|
|
301
|
+
sa.or_(
|
|
302
|
+
t.c.record_repr.ilike(like_q, escape="\\"),
|
|
303
|
+
t.c.record_pk.ilike(like_q, escape="\\"),
|
|
304
|
+
t.c.model_label.ilike(like_q, escape="\\"),
|
|
305
|
+
t.c.actor_name.ilike(like_q, escape="\\"),
|
|
306
|
+
t.c.changes_json.ilike(like_q, escape="\\"),
|
|
307
|
+
)
|
|
308
|
+
)
|
|
309
|
+
|
|
310
|
+
count_stmt = sa.select(sa.func.count()).select_from(t)
|
|
311
|
+
rows_stmt = (
|
|
312
|
+
sa.select(t)
|
|
313
|
+
.order_by(t.c.timestamp.desc(), t.c.id.desc())
|
|
314
|
+
.limit(limit)
|
|
315
|
+
.offset(offset)
|
|
316
|
+
)
|
|
317
|
+
if conditions:
|
|
318
|
+
where_clause = sa.and_(*conditions)
|
|
319
|
+
count_stmt = count_stmt.where(where_clause)
|
|
320
|
+
rows_stmt = rows_stmt.where(where_clause)
|
|
321
|
+
|
|
322
|
+
with self._engine.connect() as conn:
|
|
323
|
+
total = int(conn.execute(count_stmt).scalar_one() or 0)
|
|
324
|
+
rows = conn.execute(rows_stmt).mappings().all()
|
|
325
|
+
|
|
326
|
+
return [self._row_to_entry(r) for r in rows], total
|
|
327
|
+
|
|
328
|
+
def get_entry(self, entry_id: str) -> AuditEntry | None:
|
|
329
|
+
stmt = sa.select(self._table).where(self._table.c.id == entry_id).limit(1)
|
|
330
|
+
with self._engine.connect() as conn:
|
|
331
|
+
row = conn.execute(stmt).mappings().first()
|
|
332
|
+
return self._row_to_entry(row) if row is not None else None
|
|
333
|
+
|
|
334
|
+
|
|
335
|
+
def make_audit_entry(
|
|
336
|
+
*,
|
|
337
|
+
actor_id: str,
|
|
338
|
+
actor_name: str,
|
|
339
|
+
actor_ip: str,
|
|
340
|
+
action: str,
|
|
341
|
+
model_slug: str,
|
|
342
|
+
model_label: str,
|
|
343
|
+
record_pk: str,
|
|
344
|
+
record_repr: str,
|
|
345
|
+
changes: dict[str, dict[str, Any]] | None = None,
|
|
346
|
+
metadata: dict[str, Any] | None = None,
|
|
347
|
+
timestamp: datetime | None = None,
|
|
348
|
+
) -> AuditEntry:
|
|
349
|
+
"""Factory creating a UTC-stamped AuditEntry with a fresh UUID."""
|
|
350
|
+
return AuditEntry(
|
|
351
|
+
id=str(uuid.uuid4()),
|
|
352
|
+
timestamp=timestamp or datetime.now(timezone.utc),
|
|
353
|
+
actor_id=actor_id,
|
|
354
|
+
actor_name=actor_name,
|
|
355
|
+
actor_ip=actor_ip,
|
|
356
|
+
action=action,
|
|
357
|
+
model_slug=model_slug,
|
|
358
|
+
model_label=model_label,
|
|
359
|
+
record_pk=record_pk,
|
|
360
|
+
record_repr=record_repr,
|
|
361
|
+
changes=changes or {},
|
|
362
|
+
metadata=metadata or {},
|
|
363
|
+
)
|