velocity-python 0.9.1__py3-none-any.whl → 0.9.3__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.
- velocity/__init__.py +1 -1
- velocity/aws/authz.py +20 -4
- velocity/aws/handlers/base_handler.py +16 -0
- velocity/aws/handlers/exceptions.py +56 -0
- velocity/aws/handlers/mixins/__init__.py +2 -1
- velocity/aws/handlers/mixins/data_service.py +329 -10
- velocity/aws/handlers/response.py +11 -7
- velocity/aws/validation.py +502 -0
- velocity/db/core/table.py +1 -2
- velocity/db/servers/postgres/sql.py +22 -38
- velocity/db/tests/test_sql_builder.py +15 -20
- {velocity_python-0.9.1.dist-info → velocity_python-0.9.3.dist-info}/METADATA +1 -2
- {velocity_python-0.9.1.dist-info → velocity_python-0.9.3.dist-info}/RECORD +17 -16
- {velocity_python-0.9.1.dist-info → velocity_python-0.9.3.dist-info}/WHEEL +0 -0
- {velocity_python-0.9.1.dist-info → velocity_python-0.9.3.dist-info}/entry_points.txt +0 -0
- {velocity_python-0.9.1.dist-info → velocity_python-0.9.3.dist-info}/licenses/LICENSE +0 -0
- {velocity_python-0.9.1.dist-info → velocity_python-0.9.3.dist-info}/top_level.txt +0 -0
velocity/__init__.py
CHANGED
velocity/aws/authz.py
CHANGED
|
@@ -200,10 +200,18 @@ class Rule:
|
|
|
200
200
|
tables: Optional[frozenset] = None
|
|
201
201
|
|
|
202
202
|
def covers(self, action):
|
|
203
|
-
|
|
204
|
-
action == pattern
|
|
205
|
-
|
|
206
|
-
|
|
203
|
+
for pattern in self.actions:
|
|
204
|
+
if action == pattern:
|
|
205
|
+
return True
|
|
206
|
+
if "*" in pattern and fnmatchcase(action, pattern):
|
|
207
|
+
# A provider-only permission is given by name: a wildcard
|
|
208
|
+
# PERMIT never covers it (as a wildcard grant never reaches
|
|
209
|
+
# it, velocity.aws.permissions._expand); a wildcard forbid
|
|
210
|
+
# still does.
|
|
211
|
+
if self.effect == PERMIT and _provider_only_action(action):
|
|
212
|
+
continue
|
|
213
|
+
return True
|
|
214
|
+
return False
|
|
207
215
|
|
|
208
216
|
|
|
209
217
|
@dataclass(frozen=True)
|
|
@@ -482,9 +490,17 @@ def permission(
|
|
|
482
490
|
if known is not None and known != declared:
|
|
483
491
|
raise ValueError(f"A permission named '{name}' is already declared.")
|
|
484
492
|
_PERMISSIONS[name] = declared
|
|
493
|
+
if declared.provider_only and known is None:
|
|
494
|
+
# wildcard rules indexed before this declaration may cover it
|
|
495
|
+
_INDEX.clear()
|
|
485
496
|
return declared
|
|
486
497
|
|
|
487
498
|
|
|
499
|
+
def _provider_only_action(action):
|
|
500
|
+
declared = _PERMISSIONS.get(action)
|
|
501
|
+
return declared is not None and declared.provider_only
|
|
502
|
+
|
|
503
|
+
|
|
488
504
|
def permissions():
|
|
489
505
|
"""Every declared permission, by group and then name."""
|
|
490
506
|
return tuple(sorted(_PERMISSIONS.values(), key=lambda p: (p.group, p.name)))
|
|
@@ -264,10 +264,26 @@ class BaseHandler:
|
|
|
264
264
|
|
|
265
265
|
# Default behavior: raising AlertError surfaces a UI alert.
|
|
266
266
|
# If `toast: true` is present in the payload, show a toast instead.
|
|
267
|
+
# A data-rule refusal (ValidationError) carries the checks it
|
|
268
|
+
# names and whether this caller may override them, on the alert
|
|
269
|
+
# and in the body (velocity.aws.validation).
|
|
270
|
+
validation = None
|
|
271
|
+
block = getattr(exception, "validation_block", None)
|
|
272
|
+
if callable(block):
|
|
273
|
+
try:
|
|
274
|
+
validation = block()
|
|
275
|
+
except Exception:
|
|
276
|
+
validation = None
|
|
267
277
|
if toast:
|
|
268
278
|
local_context.response().toast(message, variant)
|
|
279
|
+
elif validation is not None:
|
|
280
|
+
local_context.response().alert(
|
|
281
|
+
message=message, title=title, extra={"validation": validation}
|
|
282
|
+
)
|
|
269
283
|
else:
|
|
270
284
|
local_context.response().alert(message=message, title=title)
|
|
285
|
+
if validation is not None:
|
|
286
|
+
local_context.response().set_body({"validation": validation})
|
|
271
287
|
return
|
|
272
288
|
|
|
273
289
|
if isinstance(exception, AccessError):
|
|
@@ -93,3 +93,59 @@ class AlertError(AppError):
|
|
|
93
93
|
elif isinstance(data, dict):
|
|
94
94
|
return data
|
|
95
95
|
return {"message": "No message was supplied to AlertError"}
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
class ValidationError(AlertError):
|
|
99
|
+
"""A save refused by one or more **data rules** (required fields,
|
|
100
|
+
formats), each named by a stable dotted id (``admin_users.username_
|
|
101
|
+
required``). The response is the usual alert plus a ``validation`` block
|
|
102
|
+
(``{"checks": [{"id", "message"}], "overridable": bool}``).
|
|
103
|
+
|
|
104
|
+
Only a ValidationError raised through :mod:`velocity.aws.validation`
|
|
105
|
+
(``check`` / ``checks``) can be overridden: only those helpers mark it
|
|
106
|
+
deferrable (a private flag), and on a forced resend they skip the checks
|
|
107
|
+
the caller may skip. One raised directly is refused like any other
|
|
108
|
+
alert. ``overridable`` is decided by the server (``write-object`` sets it
|
|
109
|
+
from the authorization decision); it starts ``False``.
|
|
110
|
+
Security and integrity rules never raise this: they stay AlertError /
|
|
111
|
+
AccessError and are never overridable."""
|
|
112
|
+
|
|
113
|
+
def __init__(
|
|
114
|
+
self,
|
|
115
|
+
checks,
|
|
116
|
+
message=None,
|
|
117
|
+
*,
|
|
118
|
+
title: str | None = None,
|
|
119
|
+
log_to_cloudwatch: bool = False,
|
|
120
|
+
):
|
|
121
|
+
normalized = []
|
|
122
|
+
for item in checks or ():
|
|
123
|
+
if not isinstance(item, dict):
|
|
124
|
+
raise TypeError("each check is a {'id', 'message'} dict")
|
|
125
|
+
check_id = item.get("id")
|
|
126
|
+
if not isinstance(check_id, str) or not check_id.strip():
|
|
127
|
+
raise ValueError("a check needs a non-blank id")
|
|
128
|
+
text = item.get("message")
|
|
129
|
+
normalized.append(
|
|
130
|
+
{"id": check_id.strip(), "message": "" if text is None else str(text)}
|
|
131
|
+
)
|
|
132
|
+
if not normalized:
|
|
133
|
+
raise ValueError("a ValidationError names at least one check")
|
|
134
|
+
if message is None:
|
|
135
|
+
message = "\n".join(c["message"] or c["id"] for c in normalized)
|
|
136
|
+
super().__init__(
|
|
137
|
+
message,
|
|
138
|
+
title=title or "Please check",
|
|
139
|
+
log_to_cloudwatch=log_to_cloudwatch,
|
|
140
|
+
)
|
|
141
|
+
self.checks = normalized
|
|
142
|
+
# set only by velocity.aws.validation's helpers
|
|
143
|
+
self._deferrable = False
|
|
144
|
+
self.overridable = False
|
|
145
|
+
|
|
146
|
+
def validation_block(self):
|
|
147
|
+
"""The ``validation`` block of the error response."""
|
|
148
|
+
return {
|
|
149
|
+
"checks": [dict(c) for c in self.checks],
|
|
150
|
+
"overridable": bool(self.overridable),
|
|
151
|
+
}
|
|
@@ -25,7 +25,7 @@ This package provides mixins for common Lambda handler patterns:
|
|
|
25
25
|
"""
|
|
26
26
|
|
|
27
27
|
from .web_handler import WebHandler, ButtonHandler
|
|
28
|
-
from .data_service import ALL_TABLES, DataServiceMixin
|
|
28
|
+
from .data_service import ALL_TABLES, VALIDATION_ACTIONS, DataServiceMixin
|
|
29
29
|
from .row_scoped import RowScopedDataService
|
|
30
30
|
from .audit_trail import AuditTrailMixin
|
|
31
31
|
from .job_handler import JobHandler
|
|
@@ -45,6 +45,7 @@ from velocity.aws.scheduler import SchedulerMixin
|
|
|
45
45
|
|
|
46
46
|
__all__ = [
|
|
47
47
|
"ALL_TABLES",
|
|
48
|
+
"VALIDATION_ACTIONS",
|
|
48
49
|
"WebHandler",
|
|
49
50
|
"ButtonHandler",
|
|
50
51
|
"DataServiceMixin",
|
|
@@ -8,6 +8,7 @@ that uses velocity.db for database access.
|
|
|
8
8
|
import base64
|
|
9
9
|
import datetime
|
|
10
10
|
import importlib
|
|
11
|
+
import json
|
|
11
12
|
import logging
|
|
12
13
|
import re
|
|
13
14
|
from io import BytesIO
|
|
@@ -17,10 +18,16 @@ from velocity.aws import authz, dirty_pipeline, ssm_config
|
|
|
17
18
|
from velocity.aws import facets
|
|
18
19
|
from velocity.aws import permissions as _grants
|
|
19
20
|
from velocity.aws import tiles as _tiles # noqa: F401 (protects its tables)
|
|
20
|
-
from velocity.aws
|
|
21
|
+
from velocity.aws import validation as _validation
|
|
22
|
+
from velocity.aws.handlers.exceptions import (
|
|
23
|
+
AccessError,
|
|
24
|
+
AlertError,
|
|
25
|
+
BadRequestError,
|
|
26
|
+
ValidationError,
|
|
27
|
+
)
|
|
21
28
|
from velocity.aws.handlers.mixins.client_input import MODES, STRICT, ClientInputGuard
|
|
22
29
|
from velocity.db.exceptions import DbDataIntegrityError
|
|
23
|
-
from velocity.db.fragments import Expr
|
|
30
|
+
from velocity.db.fragments import Expr, Literal
|
|
24
31
|
from velocity.db.servers.tablehelper import TableHelper
|
|
25
32
|
from velocity.misc import export
|
|
26
33
|
|
|
@@ -481,6 +488,10 @@ DIRECT_ACTIONS = frozenset(
|
|
|
481
488
|
|
|
482
489
|
ACTION_NOT_AVAILABLE = "This action is not available."
|
|
483
490
|
|
|
491
|
+
# The validation-override read action (velocity.aws.validation), for a site's
|
|
492
|
+
# ``client_actions`` allow-list: ``client_actions = MINE | VALIDATION_ACTIONS``.
|
|
493
|
+
VALIDATION_ACTIONS = frozenset({"validation-overrides"})
|
|
494
|
+
|
|
484
495
|
|
|
485
496
|
class _AllTables:
|
|
486
497
|
"""``direct_allowed_tables = ALL_TABLES``: an explicit opt-in to every
|
|
@@ -1275,7 +1286,8 @@ class DataServiceMixin:
|
|
|
1275
1286
|
|
|
1276
1287
|
m = self._get_rwx_module(table)
|
|
1277
1288
|
if m is not None and hasattr(m, hook_name):
|
|
1278
|
-
|
|
1289
|
+
# an override of one save reaches only that record's own hooks
|
|
1290
|
+
_validation.run_hook(getattr(m, hook_name), args, kwargs)
|
|
1279
1291
|
|
|
1280
1292
|
def _get_rwx_module(self, table):
|
|
1281
1293
|
"""The app's ``rwx.<table>`` module, or None when there is none.
|
|
@@ -1521,6 +1533,17 @@ class DataServiceMixin:
|
|
|
1521
1533
|
return row
|
|
1522
1534
|
|
|
1523
1535
|
def write_hook(self, tx, table, sys_id, incoming, context, save_as=False):
|
|
1536
|
+
# A validation override (velocity.aws.validation) reaches only the
|
|
1537
|
+
# save write-object granted it: this entry claims it, every other
|
|
1538
|
+
# write (sibling, nested, re-entrant) runs without it.
|
|
1539
|
+
with _validation.claim_write(context, table, sys_id, incoming) as grant:
|
|
1540
|
+
return self._write_row(
|
|
1541
|
+
tx, table, sys_id, incoming, context, save_as=save_as, grant=grant
|
|
1542
|
+
)
|
|
1543
|
+
|
|
1544
|
+
def _write_row(
|
|
1545
|
+
self, tx, table, sys_id, incoming, context, save_as=False, grant=None
|
|
1546
|
+
):
|
|
1524
1547
|
row = {}
|
|
1525
1548
|
incoming.pop("sys_id", None)
|
|
1526
1549
|
# A form posts every field it shows; untouched NULLs come back as ''.
|
|
@@ -1587,6 +1610,7 @@ class DataServiceMixin:
|
|
|
1587
1610
|
# it still wins over any default an after_new hook sets.
|
|
1588
1611
|
row = tx.table(table).new(_new_row_values(incoming))
|
|
1589
1612
|
sys_id = row["sys_id"]
|
|
1613
|
+
_validation.pin_created(grant, sys_id)
|
|
1590
1614
|
self._call_rwx_hook("after_new", "common", tx, table, sys_id, row, context)
|
|
1591
1615
|
self._call_rwx_hook("after_new", table, tx, table, sys_id, row, context)
|
|
1592
1616
|
elif sys_id:
|
|
@@ -2187,6 +2211,12 @@ class DataServiceMixin:
|
|
|
2187
2211
|
self._assert_client_table_for(authz.DATA_WRITE, table_name, "tableName")
|
|
2188
2212
|
self._assert_no_compiled_set(table_name, obj)
|
|
2189
2213
|
self._client_guard().write_data(obj)
|
|
2214
|
+
# A forced save (velocity.aws.validation): refused here, before
|
|
2215
|
+
# anything is written, unless this caller may override, gave a reason
|
|
2216
|
+
# and can be named in the audit row.
|
|
2217
|
+
override = self._validation_override_request(
|
|
2218
|
+
tx, table_name, obj.get("sys_id"), payload, context
|
|
2219
|
+
)
|
|
2190
2220
|
|
|
2191
2221
|
# Ensure the object has at least some data
|
|
2192
2222
|
incoming = obj.copy()
|
|
@@ -2229,13 +2259,8 @@ class DataServiceMixin:
|
|
|
2229
2259
|
)
|
|
2230
2260
|
|
|
2231
2261
|
try:
|
|
2232
|
-
row = self.
|
|
2233
|
-
tx,
|
|
2234
|
-
table_name,
|
|
2235
|
-
incoming.get("sys_id"),
|
|
2236
|
-
incoming,
|
|
2237
|
-
context,
|
|
2238
|
-
save_as=save_as,
|
|
2262
|
+
row, forced = self._write_with_override(
|
|
2263
|
+
tx, table_name, incoming, context, save_as, override
|
|
2239
2264
|
)
|
|
2240
2265
|
|
|
2241
2266
|
if not row:
|
|
@@ -2251,6 +2276,8 @@ class DataServiceMixin:
|
|
|
2251
2276
|
"lastFetch": datetime.datetime.now(),
|
|
2252
2277
|
}
|
|
2253
2278
|
)
|
|
2279
|
+
if forced is not None:
|
|
2280
|
+
context.response().set_body({"validation_override": forced})
|
|
2254
2281
|
logger.debug(
|
|
2255
2282
|
"Successfully wrote to table",
|
|
2256
2283
|
extra={"table_name": table_name},
|
|
@@ -2268,6 +2295,298 @@ class DataServiceMixin:
|
|
|
2268
2295
|
raise
|
|
2269
2296
|
context.response().load_object(row)
|
|
2270
2297
|
|
|
2298
|
+
# ── validation override (velocity.aws.validation) ──────────────────────
|
|
2299
|
+
|
|
2300
|
+
def can_override_validation(self, tx, context, table, sys_id):
|
|
2301
|
+
"""A site's extra condition on a validation override of ``table`` /
|
|
2302
|
+
``sys_id`` (``"@new"`` for a create). It can only NARROW the
|
|
2303
|
+
decision: an override needs the ``validation_override.edit``
|
|
2304
|
+
permission (``authz``; a super user acting as themselves holds it;
|
|
2305
|
+
never under masquerade) AND this returning ``True``. Default
|
|
2306
|
+
``True``. Decide from server-side state, never from the payload."""
|
|
2307
|
+
return True
|
|
2308
|
+
|
|
2309
|
+
def _may_override_validation(self, tx, context, table, sys_id):
|
|
2310
|
+
"""The one decision: not masquerading, ``authz`` permits
|
|
2311
|
+
``validation_override.edit`` on the table, and the site's
|
|
2312
|
+
``can_override_validation`` returns exactly ``True``. Any error is
|
|
2313
|
+
a no."""
|
|
2314
|
+
if _validation.masquerading(context):
|
|
2315
|
+
return False
|
|
2316
|
+
try:
|
|
2317
|
+
decision = authz.decide(
|
|
2318
|
+
self, _validation.EDIT, _validation.resource(table), context
|
|
2319
|
+
)
|
|
2320
|
+
except Exception: # noqa: BLE001 — an error never grants
|
|
2321
|
+
logger.warning("validation override decision failed", exc_info=True)
|
|
2322
|
+
return False
|
|
2323
|
+
# only the declared rule (or being a super user) decides it: a site
|
|
2324
|
+
# rule that happens to permit the action does not
|
|
2325
|
+
if not decision.allowed or decision.rule not in _validation.EDIT_RULES:
|
|
2326
|
+
return False
|
|
2327
|
+
try:
|
|
2328
|
+
return self.can_override_validation(tx, context, table, sys_id) is True
|
|
2329
|
+
except Exception: # noqa: BLE001 — an error never grants
|
|
2330
|
+
logger.warning("can_override_validation failed", exc_info=True)
|
|
2331
|
+
return False
|
|
2332
|
+
|
|
2333
|
+
def validation_override_actor(self, context):
|
|
2334
|
+
"""Who is forcing the save, for ``changed_by``: the audit trail's
|
|
2335
|
+
actor (``resolve_audit_actor``) when the handler has one, else the
|
|
2336
|
+
signed-in email. ``None`` (refused) when no person can be named: an
|
|
2337
|
+
anonymous request or work with no request. (A masquerade session
|
|
2338
|
+
never gets here: it is refused first.)"""
|
|
2339
|
+
actor = None
|
|
2340
|
+
resolver = getattr(self, "resolve_audit_actor", None)
|
|
2341
|
+
try:
|
|
2342
|
+
if callable(resolver):
|
|
2343
|
+
actor = resolver(context)
|
|
2344
|
+
else:
|
|
2345
|
+
getter = getattr(context, "get_logged_in_email", None)
|
|
2346
|
+
actor = getter(default=None) if callable(getter) else None
|
|
2347
|
+
except Exception: # noqa: BLE001 — unknown means "no actor"
|
|
2348
|
+
actor = None
|
|
2349
|
+
if not isinstance(actor, str) or not actor.strip():
|
|
2350
|
+
return None
|
|
2351
|
+
actor = actor.strip()
|
|
2352
|
+
if actor == "anon" or actor.startswith("system:"):
|
|
2353
|
+
return None
|
|
2354
|
+
return actor
|
|
2355
|
+
|
|
2356
|
+
def _validation_override_table(self):
|
|
2357
|
+
from velocity.db.audit import AUDIT_TABLE
|
|
2358
|
+
|
|
2359
|
+
return getattr(self, "audit_table", None) or AUDIT_TABLE
|
|
2360
|
+
|
|
2361
|
+
def _validation_history_exists(self, tx):
|
|
2362
|
+
try:
|
|
2363
|
+
with tx.savepoint():
|
|
2364
|
+
return bool(tx.table(self._validation_override_table()).exists())
|
|
2365
|
+
except Exception: # noqa: BLE001 — unknown means "not there"
|
|
2366
|
+
return False
|
|
2367
|
+
|
|
2368
|
+
def _validation_override_request(self, tx, table, sys_id, payload, context):
|
|
2369
|
+
"""``None`` for an ordinary save; for one carrying ``override``, the
|
|
2370
|
+
authorized ``(check_ids, reason, actor)`` — or a plain AlertError
|
|
2371
|
+
(no ``validation`` block) when the request runs under masquerade,
|
|
2372
|
+
the caller may not override, the reason is blank or too long, no
|
|
2373
|
+
actor can be named, or the history table is missing. Runs before
|
|
2374
|
+
anything is written."""
|
|
2375
|
+
if payload.get("override") is None:
|
|
2376
|
+
return None
|
|
2377
|
+
if _validation.masquerading(context):
|
|
2378
|
+
logger.warning(
|
|
2379
|
+
"validation override refused: masquerade session",
|
|
2380
|
+
extra={"table_name": table},
|
|
2381
|
+
)
|
|
2382
|
+
raise AlertError(
|
|
2383
|
+
"A validation check cannot be overridden while acting as "
|
|
2384
|
+
"another person."
|
|
2385
|
+
)
|
|
2386
|
+
if not self._may_override_validation(tx, context, table, sys_id):
|
|
2387
|
+
logger.warning(
|
|
2388
|
+
"validation override refused: caller may not override",
|
|
2389
|
+
extra={"table_name": table},
|
|
2390
|
+
)
|
|
2391
|
+
raise AlertError("You may not override validation checks.")
|
|
2392
|
+
names, reason = _validation.parse_override(payload.get("override"))
|
|
2393
|
+
actor = self.validation_override_actor(context)
|
|
2394
|
+
if actor is None:
|
|
2395
|
+
raise AlertError(
|
|
2396
|
+
"This override cannot be attributed to a person, so it was refused."
|
|
2397
|
+
)
|
|
2398
|
+
if not self._validation_history_exists(tx):
|
|
2399
|
+
raise AlertError(
|
|
2400
|
+
"Overrides cannot be recorded on this site yet, so this one was "
|
|
2401
|
+
"refused."
|
|
2402
|
+
)
|
|
2403
|
+
return names, reason, actor
|
|
2404
|
+
|
|
2405
|
+
def _write_with_override(self, tx, table, incoming, context, save_as, override):
|
|
2406
|
+
"""``write_hook`` under the authorized override (if any), bound to
|
|
2407
|
+
this record. Returns ``(row, forced)``: ``forced`` is ``{"checks",
|
|
2408
|
+
"reason"}`` when checks were actually skipped (one
|
|
2409
|
+
``validation_override`` audit row is written in the same
|
|
2410
|
+
transaction), else ``None``. A ValidationError leaving the save says
|
|
2411
|
+
whether this caller could override it."""
|
|
2412
|
+
sys_id = incoming.get("sys_id")
|
|
2413
|
+
try:
|
|
2414
|
+
if override is None:
|
|
2415
|
+
row = self.write_hook(
|
|
2416
|
+
tx, table, sys_id, incoming, context, save_as=save_as
|
|
2417
|
+
)
|
|
2418
|
+
return row, None
|
|
2419
|
+
names, reason, actor = override
|
|
2420
|
+
with _validation.override_scope(
|
|
2421
|
+
context, names, reason, table=table, sys_id=sys_id, incoming=incoming
|
|
2422
|
+
) as grant:
|
|
2423
|
+
row = self.write_hook(
|
|
2424
|
+
tx, table, sys_id, incoming, context, save_as=save_as
|
|
2425
|
+
)
|
|
2426
|
+
except ValidationError as exc:
|
|
2427
|
+
exc.overridable = bool(
|
|
2428
|
+
_validation.is_deferrable(exc)
|
|
2429
|
+
and self._may_override_validation(tx, context, table, sys_id)
|
|
2430
|
+
)
|
|
2431
|
+
raise
|
|
2432
|
+
if not grant.skipped:
|
|
2433
|
+
return row, None
|
|
2434
|
+
skipped = list(grant.skipped)
|
|
2435
|
+
if grant.target is None:
|
|
2436
|
+
raise AlertError("The forced save has no record id to record.")
|
|
2437
|
+
self._record_validation_override(
|
|
2438
|
+
tx, table, grant.target, row, skipped, reason, actor
|
|
2439
|
+
)
|
|
2440
|
+
return row, {"checks": skipped, "reason": reason}
|
|
2441
|
+
|
|
2442
|
+
def _record_validation_override(
|
|
2443
|
+
self, tx, table, row_sys_id, row, skipped, reason, actor
|
|
2444
|
+
):
|
|
2445
|
+
"""One ``audit_log`` row for a forced save: check ids (no messages:
|
|
2446
|
+
they may quote the record), reason, values saved (redacted).
|
|
2447
|
+
Fail-closed: when it cannot be written the save fails with it (same
|
|
2448
|
+
transaction, rolled back by the action's error path)."""
|
|
2449
|
+
from velocity.aws.handlers.mixins.audit_trail import json_safe
|
|
2450
|
+
from velocity.db.audit import DEFAULT_REDACT_HINTS, REDACTED
|
|
2451
|
+
|
|
2452
|
+
values = dict(row or {})
|
|
2453
|
+
redact = getattr(self, "audit_redact", None)
|
|
2454
|
+
if callable(redact):
|
|
2455
|
+
values = redact(table, values)
|
|
2456
|
+
else:
|
|
2457
|
+
hints = [str(h).lower() for h in DEFAULT_REDACT_HINTS]
|
|
2458
|
+
values = {
|
|
2459
|
+
str(k): (
|
|
2460
|
+
REDACTED
|
|
2461
|
+
if any(h in str(k).lower() for h in hints)
|
|
2462
|
+
else json_safe(v)
|
|
2463
|
+
)
|
|
2464
|
+
for k, v in values.items()
|
|
2465
|
+
}
|
|
2466
|
+
tx.table(self._validation_override_table()).insert(
|
|
2467
|
+
{
|
|
2468
|
+
"table_name": table,
|
|
2469
|
+
"row_sys_id": int(row_sys_id),
|
|
2470
|
+
"operation": _validation.OPERATION,
|
|
2471
|
+
"changed_by": actor,
|
|
2472
|
+
# the database clock, the one sys_created comes from
|
|
2473
|
+
"changed_at": Literal("CURRENT_TIMESTAMP"),
|
|
2474
|
+
"before": None,
|
|
2475
|
+
"after": {
|
|
2476
|
+
"checks": list(skipped),
|
|
2477
|
+
"reason": reason,
|
|
2478
|
+
"values": values,
|
|
2479
|
+
},
|
|
2480
|
+
"field_diff": {},
|
|
2481
|
+
}
|
|
2482
|
+
)
|
|
2483
|
+
|
|
2484
|
+
def _validation_override_viewer(self, tx, table, context):
|
|
2485
|
+
"""Whether this reader may see who overrode and why: not
|
|
2486
|
+
masquerading and ``authz`` permits ``validation_override.view`` on
|
|
2487
|
+
the table (decided only; the read is recorded when rows are shown)."""
|
|
2488
|
+
if _validation.masquerading(context):
|
|
2489
|
+
return False
|
|
2490
|
+
try:
|
|
2491
|
+
decision = authz.decide(
|
|
2492
|
+
self, _validation.VIEW, _validation.resource(table), context
|
|
2493
|
+
)
|
|
2494
|
+
return decision.allowed and decision.rule in _validation.VIEW_RULES
|
|
2495
|
+
except Exception: # noqa: BLE001 — an error never grants
|
|
2496
|
+
logger.warning("validation override view decision failed", exc_info=True)
|
|
2497
|
+
return False
|
|
2498
|
+
|
|
2499
|
+
def OnActionValidationOverrides(self, tx, context):
|
|
2500
|
+
"""``validation-overrides {table, sys_id}``: the forced saves of one
|
|
2501
|
+
record, newest first (at most 50), for the "Saved with override"
|
|
2502
|
+
chip. Answered only for a record the caller can read — the table
|
|
2503
|
+
gate, the confidential-read record and ``read_hook`` (rwx read
|
|
2504
|
+
hooks, tenant, owner and permission scope), as ``read-object`` —
|
|
2505
|
+
and only for history written since the record was created, so a
|
|
2506
|
+
reused id never shows another record's overrides.
|
|
2507
|
+
|
|
2508
|
+
``{"detail": "full", "validation_overrides": [{"changed_at",
|
|
2509
|
+
"changed_by", "checks", "reason"}]}`` for a reader holding
|
|
2510
|
+
``validation_override.view`` (each such read with rows is recorded
|
|
2511
|
+
as privileged access); otherwise ``{"detail": "limited",
|
|
2512
|
+
"validation_overrides": [{"changed_at", "checks"}]}``. A record the
|
|
2513
|
+
caller cannot read, or a site without the history table, answers an
|
|
2514
|
+
empty list."""
|
|
2515
|
+
payload = context.payload()
|
|
2516
|
+
table = payload.get("table")
|
|
2517
|
+
self._assert_client_table(table, "table")
|
|
2518
|
+
self._audit_confidential_read(tx, table, context)
|
|
2519
|
+
sys_id = ClientInputGuard.integer(payload.get("sys_id"), "sys_id")
|
|
2520
|
+
if sys_id is None or sys_id <= 0:
|
|
2521
|
+
raise BadRequestError("sys_id: expected a record id")
|
|
2522
|
+
entries = []
|
|
2523
|
+
record = self.read_hook(tx, table, sys_id, context)
|
|
2524
|
+
if record and self._validation_history_exists(tx):
|
|
2525
|
+
where = {
|
|
2526
|
+
"table_name": table,
|
|
2527
|
+
"row_sys_id": sys_id,
|
|
2528
|
+
"operation": _validation.OPERATION,
|
|
2529
|
+
}
|
|
2530
|
+
created = record.get("sys_created")
|
|
2531
|
+
if created is not None:
|
|
2532
|
+
where[">=changed_at"] = created
|
|
2533
|
+
rows = (
|
|
2534
|
+
tx.table(self._validation_override_table())
|
|
2535
|
+
.select(
|
|
2536
|
+
columns=["changed_at", "changed_by", "after"],
|
|
2537
|
+
where=where,
|
|
2538
|
+
orderby="changed_at desc",
|
|
2539
|
+
qty=50,
|
|
2540
|
+
)
|
|
2541
|
+
.all()
|
|
2542
|
+
)
|
|
2543
|
+
for entry in rows:
|
|
2544
|
+
after = entry.get("after")
|
|
2545
|
+
if isinstance(after, str):
|
|
2546
|
+
try:
|
|
2547
|
+
after = json.loads(after)
|
|
2548
|
+
except ValueError:
|
|
2549
|
+
after = None
|
|
2550
|
+
after = after if isinstance(after, dict) else {}
|
|
2551
|
+
checks = [
|
|
2552
|
+
c
|
|
2553
|
+
for c in (after.get("checks") or [])
|
|
2554
|
+
if _validation.valid_check_id(c)
|
|
2555
|
+
]
|
|
2556
|
+
entries.append(
|
|
2557
|
+
{
|
|
2558
|
+
"changed_at": entry.get("changed_at"),
|
|
2559
|
+
"changed_by": entry.get("changed_by"),
|
|
2560
|
+
"checks": checks,
|
|
2561
|
+
"reason": after.get("reason"),
|
|
2562
|
+
}
|
|
2563
|
+
)
|
|
2564
|
+
full = self._validation_override_viewer(tx, table, context)
|
|
2565
|
+
if full and entries:
|
|
2566
|
+
# who and why are shown only once the look is on the record
|
|
2567
|
+
# the record names the record: validation_override:<table>:<id>
|
|
2568
|
+
try:
|
|
2569
|
+
decision = authz.require(
|
|
2570
|
+
self,
|
|
2571
|
+
tx,
|
|
2572
|
+
context,
|
|
2573
|
+
_validation.VIEW,
|
|
2574
|
+
_validation.record_resource(table, sys_id),
|
|
2575
|
+
)
|
|
2576
|
+
full = decision.rule in _validation.VIEW_RULES
|
|
2577
|
+
except AccessError:
|
|
2578
|
+
full = False
|
|
2579
|
+
if not full:
|
|
2580
|
+
entries = [
|
|
2581
|
+
{"changed_at": e["changed_at"], "checks": e["checks"]} for e in entries
|
|
2582
|
+
]
|
|
2583
|
+
context.response().set_body(
|
|
2584
|
+
{
|
|
2585
|
+
"detail": "full" if full else "limited",
|
|
2586
|
+
"validation_overrides": entries,
|
|
2587
|
+
}
|
|
2588
|
+
)
|
|
2589
|
+
|
|
2271
2590
|
# Query a table for rows. If the requested result format is excel, then return the
|
|
2272
2591
|
# data as a downloadedable excel file. If the requested result format is raw,
|
|
2273
2592
|
# then return the data as rows for the application front end to handle as it wishes.
|
|
@@ -89,23 +89,27 @@ class Response:
|
|
|
89
89
|
"""
|
|
90
90
|
return self.set_raw_body(to_json(value), "application/json")
|
|
91
91
|
|
|
92
|
-
def alert(
|
|
92
|
+
def alert(
|
|
93
|
+
self,
|
|
94
|
+
message: str,
|
|
95
|
+
title: str = "Notification",
|
|
96
|
+
extra: Optional[Dict[str, Any]] = None,
|
|
97
|
+
) -> "Response":
|
|
93
98
|
"""
|
|
94
99
|
Add an alert action to the response.
|
|
95
100
|
|
|
96
101
|
Args:
|
|
97
102
|
message (str): The alert message.
|
|
98
103
|
title (str): Title for the alert. Defaults to "Notification".
|
|
104
|
+
extra (dict): Further payload keys (e.g. ``validation``); never
|
|
105
|
+
replaces ``title`` or ``message``.
|
|
99
106
|
|
|
100
107
|
Returns:
|
|
101
108
|
Response: The current Response object, allowing method chaining.
|
|
102
109
|
"""
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
"payload": {"title": title, "message": message},
|
|
107
|
-
}
|
|
108
|
-
)
|
|
110
|
+
payload = dict(extra or {})
|
|
111
|
+
payload.update({"title": title, "message": message})
|
|
112
|
+
self.actions.append({"action": "alert", "payload": payload})
|
|
109
113
|
return self
|
|
110
114
|
|
|
111
115
|
def toast(self, message: str, variant: str = "success") -> "Response":
|