velocity-python 0.9.0__py3-none-any.whl → 0.9.2__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 +342 -11
- velocity/aws/handlers/response.py +11 -7
- velocity/aws/validation.py +502 -0
- {velocity_python-0.9.0.dist-info → velocity_python-0.9.2.dist-info}/METADATA +1 -1
- {velocity_python-0.9.0.dist-info → velocity_python-0.9.2.dist-info}/RECORD +14 -13
- {velocity_python-0.9.0.dist-info → velocity_python-0.9.2.dist-info}/WHEEL +0 -0
- {velocity_python-0.9.0.dist-info → velocity_python-0.9.2.dist-info}/entry_points.txt +0 -0
- {velocity_python-0.9.0.dist-info → velocity_python-0.9.2.dist-info}/licenses/LICENSE +0 -0
- {velocity_python-0.9.0.dist-info → velocity_python-0.9.2.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
|
|
|
@@ -112,6 +119,14 @@ def _column_types(tx, table):
|
|
|
112
119
|
return {}
|
|
113
120
|
|
|
114
121
|
|
|
122
|
+
def _new_row_values(incoming):
|
|
123
|
+
"""The values a ``@new`` row is inserted with: ``incoming`` without
|
|
124
|
+
``sys_id`` (the database assigns it), or None (``Table.new``'s bare
|
|
125
|
+
insert) when nothing else was sent."""
|
|
126
|
+
values = {k: v for k, v in (incoming or {}).items() if k != "sys_id"}
|
|
127
|
+
return values or None
|
|
128
|
+
|
|
129
|
+
|
|
115
130
|
def _bump_sys_id_sequence(tx, table):
|
|
116
131
|
"""Keep the table's serial/identity sequence ahead of MAX(sys_id) so a
|
|
117
132
|
future auto-generated id can never collide with an explicitly chosen one
|
|
@@ -473,6 +488,10 @@ DIRECT_ACTIONS = frozenset(
|
|
|
473
488
|
|
|
474
489
|
ACTION_NOT_AVAILABLE = "This action is not available."
|
|
475
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
|
+
|
|
476
495
|
|
|
477
496
|
class _AllTables:
|
|
478
497
|
"""``direct_allowed_tables = ALL_TABLES``: an explicit opt-in to every
|
|
@@ -1267,7 +1286,8 @@ class DataServiceMixin:
|
|
|
1267
1286
|
|
|
1268
1287
|
m = self._get_rwx_module(table)
|
|
1269
1288
|
if m is not None and hasattr(m, hook_name):
|
|
1270
|
-
|
|
1289
|
+
# an override of one save reaches only that record's own hooks
|
|
1290
|
+
_validation.run_hook(getattr(m, hook_name), args, kwargs)
|
|
1271
1291
|
|
|
1272
1292
|
def _get_rwx_module(self, table):
|
|
1273
1293
|
"""The app's ``rwx.<table>`` module, or None when there is none.
|
|
@@ -1513,6 +1533,17 @@ class DataServiceMixin:
|
|
|
1513
1533
|
return row
|
|
1514
1534
|
|
|
1515
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
|
+
):
|
|
1516
1547
|
row = {}
|
|
1517
1548
|
incoming.pop("sys_id", None)
|
|
1518
1549
|
# A form posts every field it shows; untouched NULLs come back as ''.
|
|
@@ -1573,8 +1604,13 @@ class DataServiceMixin:
|
|
|
1573
1604
|
self._call_rwx_hook(
|
|
1574
1605
|
"before_write", table, tx, table, NEW_ROW, incoming, context
|
|
1575
1606
|
)
|
|
1576
|
-
|
|
1607
|
+
# Insert WITH the validated values: an empty INSERT fails a NOT NULL
|
|
1608
|
+
# column (or a check/trigger) before the values are ever written
|
|
1609
|
+
# (w933). ``incoming`` is applied again after after_new below, so
|
|
1610
|
+
# it still wins over any default an after_new hook sets.
|
|
1611
|
+
row = tx.table(table).new(_new_row_values(incoming))
|
|
1577
1612
|
sys_id = row["sys_id"]
|
|
1613
|
+
_validation.pin_created(grant, sys_id)
|
|
1578
1614
|
self._call_rwx_hook("after_new", "common", tx, table, sys_id, row, context)
|
|
1579
1615
|
self._call_rwx_hook("after_new", table, tx, table, sys_id, row, context)
|
|
1580
1616
|
elif sys_id:
|
|
@@ -2175,6 +2211,12 @@ class DataServiceMixin:
|
|
|
2175
2211
|
self._assert_client_table_for(authz.DATA_WRITE, table_name, "tableName")
|
|
2176
2212
|
self._assert_no_compiled_set(table_name, obj)
|
|
2177
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
|
+
)
|
|
2178
2220
|
|
|
2179
2221
|
# Ensure the object has at least some data
|
|
2180
2222
|
incoming = obj.copy()
|
|
@@ -2217,13 +2259,8 @@ class DataServiceMixin:
|
|
|
2217
2259
|
)
|
|
2218
2260
|
|
|
2219
2261
|
try:
|
|
2220
|
-
row = self.
|
|
2221
|
-
tx,
|
|
2222
|
-
table_name,
|
|
2223
|
-
incoming.get("sys_id"),
|
|
2224
|
-
incoming,
|
|
2225
|
-
context,
|
|
2226
|
-
save_as=save_as,
|
|
2262
|
+
row, forced = self._write_with_override(
|
|
2263
|
+
tx, table_name, incoming, context, save_as, override
|
|
2227
2264
|
)
|
|
2228
2265
|
|
|
2229
2266
|
if not row:
|
|
@@ -2239,6 +2276,8 @@ class DataServiceMixin:
|
|
|
2239
2276
|
"lastFetch": datetime.datetime.now(),
|
|
2240
2277
|
}
|
|
2241
2278
|
)
|
|
2279
|
+
if forced is not None:
|
|
2280
|
+
context.response().set_body({"validation_override": forced})
|
|
2242
2281
|
logger.debug(
|
|
2243
2282
|
"Successfully wrote to table",
|
|
2244
2283
|
extra={"table_name": table_name},
|
|
@@ -2256,6 +2295,298 @@ class DataServiceMixin:
|
|
|
2256
2295
|
raise
|
|
2257
2296
|
context.response().load_object(row)
|
|
2258
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
|
+
|
|
2259
2590
|
# Query a table for rows. If the requested result format is excel, then return the
|
|
2260
2591
|
# data as a downloadedable excel file. If the requested result format is raw,
|
|
2261
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":
|
|
@@ -0,0 +1,502 @@
|
|
|
1
|
+
"""Data-rule checks a permitted person may override, with a reason, audited.
|
|
2
|
+
|
|
3
|
+
A table hook declares each **data rule** (a required field, a format) through
|
|
4
|
+
this module instead of raising a plain ``AlertError``::
|
|
5
|
+
|
|
6
|
+
from velocity.aws import validation
|
|
7
|
+
|
|
8
|
+
def before_write(tx, table, sys_id, incoming, context):
|
|
9
|
+
with validation.checks(context) as v:
|
|
10
|
+
v.check("admin_users.email_required", incoming.get("email"),
|
|
11
|
+
"Email is required.")
|
|
12
|
+
v.check("admin_users.username_required", incoming.get("username"),
|
|
13
|
+
"Username is required.")
|
|
14
|
+
# ... or one at a time (raises at the first failure):
|
|
15
|
+
validation.check(context, "admin_users.phone_format",
|
|
16
|
+
looks_like_phone(incoming.get("phone")),
|
|
17
|
+
"Phone must look like 555-555-0100.")
|
|
18
|
+
|
|
19
|
+
A failed check raises :class:`~velocity.aws.handlers.exceptions.
|
|
20
|
+
ValidationError` naming it; ``checks`` gathers every failure of the block and
|
|
21
|
+
raises ONE ValidationError listing them. Only checks raised this way can be
|
|
22
|
+
overridden (opt-in): security and integrity rules (permissions, identity,
|
|
23
|
+
duplicates, database constraints) keep raising ``AlertError`` /
|
|
24
|
+
``AccessError`` and are never overridable.
|
|
25
|
+
|
|
26
|
+
**Who.** One authorization decision: :data:`EDIT`
|
|
27
|
+
(``validation_override.edit``) on the table, through
|
|
28
|
+
:func:`velocity.aws.authz.decide` — deny by default, a super user acting as
|
|
29
|
+
themselves allowed, never while masquerading. The site grants the permission
|
|
30
|
+
(``principal_permissions`` or the grant tables); a handler's
|
|
31
|
+
``can_override_validation`` can only narrow it. :data:`VIEW`
|
|
32
|
+
(``validation_override.view``, implied by ``edit``) shows who overrode and
|
|
33
|
+
why; each such read is recorded as privileged access.
|
|
34
|
+
|
|
35
|
+
**Forcing a save.** ``DataServiceMixin.OnActionWriteObject`` reads
|
|
36
|
+
``override: {"reason", "checks": [ids]}`` from the payload, decides, and only
|
|
37
|
+
then opens an :func:`override_scope` for that one save. The save's own
|
|
38
|
+
``DataServiceMixin.write_hook`` entry claims it (:func:`claim_write`: same
|
|
39
|
+
context, table, id and the very payload dict); every other write — a
|
|
40
|
+
sibling record, a nested or re-entrant write — runs without it. While the
|
|
41
|
+
claimed write runs, a failed check is skipped (and remembered) only when the
|
|
42
|
+
request named it, its id belongs to the saved table (``<table>.<rule>``),
|
|
43
|
+
and it is made in that record's own rwx hooks (:func:`run_hook`) or in
|
|
44
|
+
``write_hook`` itself — never in a hook running inside another hook. A
|
|
45
|
+
create's hooks are covered by ``"@new"`` until its row exists and by the new
|
|
46
|
+
id after (:func:`pin_created`). Every other check is enforced. Code a
|
|
47
|
+
handler runs before or after ``super().write_hook`` gets no override. The
|
|
48
|
+
handler records one ``validation_override`` row in ``audit_log``: check ids,
|
|
49
|
+
reason, values saved. A hook validating another row of its own table
|
|
50
|
+
passes ``record=<its sys_id>`` to :func:`check` / :func:`checks`; such a
|
|
51
|
+
check is never skipped. (Check messages are not stored: they may quote the
|
|
52
|
+
record's data, and the ids name the rules).
|
|
53
|
+
"""
|
|
54
|
+
|
|
55
|
+
from __future__ import annotations
|
|
56
|
+
|
|
57
|
+
import contextlib
|
|
58
|
+
import contextvars
|
|
59
|
+
import re
|
|
60
|
+
from dataclasses import dataclass, field
|
|
61
|
+
from typing import Iterable, List, Optional
|
|
62
|
+
|
|
63
|
+
from velocity.aws import authz
|
|
64
|
+
from velocity.aws.handlers.exceptions import AlertError, ValidationError
|
|
65
|
+
|
|
66
|
+
OPERATION = "validation_override"
|
|
67
|
+
REASON_MAX = 500
|
|
68
|
+
CHECK_ID_MAX = 120
|
|
69
|
+
CHECKS_MAX = 50
|
|
70
|
+
|
|
71
|
+
NEW_ROW = "@new" # DataService's new-row sentinel (kept here: no import cycle)
|
|
72
|
+
|
|
73
|
+
# ── the permissions and the one decision ─────────────────────────────────────
|
|
74
|
+
|
|
75
|
+
EDIT = "validation_override.edit"
|
|
76
|
+
VIEW = "validation_override.view"
|
|
77
|
+
|
|
78
|
+
authz.permission(
|
|
79
|
+
VIEW,
|
|
80
|
+
label="See validation override details",
|
|
81
|
+
description="See who saved a record past a data rule, and why. Each look "
|
|
82
|
+
"is recorded.",
|
|
83
|
+
group="Validation",
|
|
84
|
+
privileged=True,
|
|
85
|
+
# given by name only: no wildcard grant ("*.view", "*") reaches it
|
|
86
|
+
provider_only=True,
|
|
87
|
+
)
|
|
88
|
+
authz.permission(
|
|
89
|
+
EDIT,
|
|
90
|
+
label="Override validation checks",
|
|
91
|
+
description="Save a record that fails a data rule, after giving a reason. "
|
|
92
|
+
"Each override is recorded.",
|
|
93
|
+
group="Validation",
|
|
94
|
+
privileged=True,
|
|
95
|
+
# given by name only: no wildcard grant ("*.edit", "*") reaches it
|
|
96
|
+
provider_only=True,
|
|
97
|
+
requires=(VIEW,),
|
|
98
|
+
)
|
|
99
|
+
MASQUERADE_RULE = "validation_override.masquerade"
|
|
100
|
+
RULES = (
|
|
101
|
+
authz.permit(EDIT, EDIT, when=authz.holds_for(EDIT)),
|
|
102
|
+
authz.permit(VIEW, VIEW, when=authz.holds_for(VIEW), audit=True),
|
|
103
|
+
# nobody overrides, or reads who did, while acting as someone else
|
|
104
|
+
authz.forbid(MASQUERADE_RULE, {EDIT, VIEW}, when=authz.masquerading),
|
|
105
|
+
)
|
|
106
|
+
authz.register(*RULES)
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def masquerading(context) -> bool:
|
|
110
|
+
"""Whether the request runs under a masquerade grant (an administrator
|
|
111
|
+
acting as someone). A session that cannot be read counts as one."""
|
|
112
|
+
getter = getattr(context, "session", None)
|
|
113
|
+
if not callable(getter):
|
|
114
|
+
return False
|
|
115
|
+
try:
|
|
116
|
+
session = getter() or {}
|
|
117
|
+
except Exception: # noqa: BLE001 — unknown is "yes" (fail closed)
|
|
118
|
+
return True
|
|
119
|
+
if not isinstance(session, dict):
|
|
120
|
+
return True
|
|
121
|
+
return bool(session.get("masquerade") or session.get("real_user"))
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
# The rules that may decide an override or a detail read: the declared ones
|
|
125
|
+
# and being a super user. A decision any other rule made is not accepted.
|
|
126
|
+
EDIT_RULES = frozenset({EDIT, authz.SUPERUSER_RULE})
|
|
127
|
+
VIEW_RULES = frozenset({VIEW, authz.SUPERUSER_RULE})
|
|
128
|
+
RECORD = "validation_override"
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def resource(table):
|
|
132
|
+
"""The table, for the decision."""
|
|
133
|
+
return authz.Resource(authz.TABLE, table)
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def record_resource(table, sys_id):
|
|
137
|
+
"""One record, for the privileged-access record of a detail read
|
|
138
|
+
(``validation_override:<table>:<sys_id>``)."""
|
|
139
|
+
return authz.Resource(RECORD, f"{table}:{int(sys_id)}")
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
# ── check ids ───────────────────────────────────────────────────────────────
|
|
143
|
+
|
|
144
|
+
# lower-case dotted segments: ``admin_users.username_required``
|
|
145
|
+
CHECK_ID = re.compile(r"[a-z][a-z0-9_]*(?:\.[a-z0-9_]+)*\Z")
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def valid_check_id(check_id) -> bool:
|
|
149
|
+
return (
|
|
150
|
+
isinstance(check_id, str)
|
|
151
|
+
and len(check_id) <= CHECK_ID_MAX
|
|
152
|
+
and bool(CHECK_ID.match(check_id))
|
|
153
|
+
)
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def _require_id(check_id):
|
|
157
|
+
if not valid_check_id(check_id):
|
|
158
|
+
raise ValueError(
|
|
159
|
+
f"check id {check_id!r} must be lower-case dotted segments "
|
|
160
|
+
"(e.g. 'admin_users.username_required')"
|
|
161
|
+
)
|
|
162
|
+
return check_id
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
# ── the grant ───────────────────────────────────────────────────────────────
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def _record_id(sys_id):
|
|
169
|
+
"""An existing record's id as an int, ``NEW_ROW`` for a create, else
|
|
170
|
+
``None`` (a where dict, garbage)."""
|
|
171
|
+
if isinstance(sys_id, str) and sys_id.strip() in ("", NEW_ROW):
|
|
172
|
+
return NEW_ROW
|
|
173
|
+
if isinstance(sys_id, bool):
|
|
174
|
+
return None
|
|
175
|
+
try:
|
|
176
|
+
return int(sys_id)
|
|
177
|
+
except (TypeError, ValueError):
|
|
178
|
+
return None
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
@dataclass
|
|
182
|
+
class OverrideGrant:
|
|
183
|
+
"""An authorized override for ONE save: the request's context, the
|
|
184
|
+
record (``table``; ``sys_id`` as requested; ``target``: its id, ``None``
|
|
185
|
+
until a create's row exists), the payload dict ``write-object`` passes to
|
|
186
|
+
``write_hook`` (``incoming``: the save is told apart from any other
|
|
187
|
+
write by that object), the check ids that may be skipped, why, and
|
|
188
|
+
which were (``skipped``, in order).
|
|
189
|
+
|
|
190
|
+
``claimed``: the save's ``DataServiceMixin.write_hook`` entry took it
|
|
191
|
+
(once); ``active``: that entry is running."""
|
|
192
|
+
|
|
193
|
+
context: object
|
|
194
|
+
checks: frozenset
|
|
195
|
+
reason: str
|
|
196
|
+
table: str
|
|
197
|
+
sys_id: object
|
|
198
|
+
incoming: object
|
|
199
|
+
target: Optional[int] = None
|
|
200
|
+
skipped: List[str] = field(default_factory=list)
|
|
201
|
+
claimed: bool = False
|
|
202
|
+
active: bool = False
|
|
203
|
+
depth: int = 0
|
|
204
|
+
|
|
205
|
+
def skips(self, check_id) -> bool:
|
|
206
|
+
"""A named check of this save's own table (``<table>.<rule>``)."""
|
|
207
|
+
return check_id in self.checks and check_id.startswith(f"{self.table}.")
|
|
208
|
+
|
|
209
|
+
def covers(self, args) -> bool:
|
|
210
|
+
"""Whether a hook called with ``args`` (``tx, table, sys_id, ...``)
|
|
211
|
+
belongs to this save's record. Never pins: the target is set by the
|
|
212
|
+
claimed ``write_hook`` once the row exists, and until then no hook
|
|
213
|
+
for a real id is covered."""
|
|
214
|
+
if not self.active or len(args) < 3 or args[1] != self.table:
|
|
215
|
+
return False
|
|
216
|
+
record = _record_id(args[2])
|
|
217
|
+
if record is None:
|
|
218
|
+
return False
|
|
219
|
+
if record == NEW_ROW:
|
|
220
|
+
return self.target is None
|
|
221
|
+
return self.target is not None and record == self.target
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
_ACTIVE: contextvars.ContextVar[Optional[OverrideGrant]] = contextvars.ContextVar(
|
|
225
|
+
"velocity_validation_override", default=None
|
|
226
|
+
)
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
def active_grant(context) -> Optional[OverrideGrant]:
|
|
230
|
+
"""The override in force for ``context`` here, if any: only while the
|
|
231
|
+
granted save's own ``write_hook`` runs."""
|
|
232
|
+
grant = _ACTIVE.get()
|
|
233
|
+
if (
|
|
234
|
+
grant is not None
|
|
235
|
+
and grant.active
|
|
236
|
+
and context is not None
|
|
237
|
+
and grant.context is context
|
|
238
|
+
):
|
|
239
|
+
return grant
|
|
240
|
+
return None
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
@contextlib.contextmanager
|
|
244
|
+
def override_scope(
|
|
245
|
+
context, checks: Iterable[str], reason: str, *, table, sys_id, incoming
|
|
246
|
+
):
|
|
247
|
+
"""Make an override of ONE save available: ``table`` / ``sys_id``
|
|
248
|
+
(``"@new"`` for a create), whose payload dict is ``incoming``.
|
|
249
|
+
|
|
250
|
+
Server code only: the caller has already decided the actor may override
|
|
251
|
+
(``DataServiceMixin`` does this for ``write-object``). Nothing is skipped
|
|
252
|
+
until :func:`claim_write` — ``DataServiceMixin.write_hook`` — claims it
|
|
253
|
+
for that very save. Yields the :class:`OverrideGrant`, whose ``skipped``
|
|
254
|
+
says what was actually skipped. Cleared when the block ends, however it
|
|
255
|
+
ends."""
|
|
256
|
+
names = frozenset(_require_id(c) for c in checks)
|
|
257
|
+
if not isinstance(reason, str) or not reason.strip():
|
|
258
|
+
raise ValueError("an override needs a reason")
|
|
259
|
+
if not isinstance(table, str) or not table:
|
|
260
|
+
raise ValueError("an override is for one table")
|
|
261
|
+
record = _record_id(sys_id)
|
|
262
|
+
if record is None:
|
|
263
|
+
raise ValueError("an override is for one record")
|
|
264
|
+
if not isinstance(incoming, dict):
|
|
265
|
+
raise ValueError("an override is for one save's payload")
|
|
266
|
+
grant = OverrideGrant(
|
|
267
|
+
context=context,
|
|
268
|
+
checks=names,
|
|
269
|
+
reason=reason.strip(),
|
|
270
|
+
table=table,
|
|
271
|
+
sys_id=record,
|
|
272
|
+
incoming=incoming,
|
|
273
|
+
)
|
|
274
|
+
token = _ACTIVE.set(grant)
|
|
275
|
+
try:
|
|
276
|
+
yield grant
|
|
277
|
+
finally:
|
|
278
|
+
_ACTIVE.reset(token)
|
|
279
|
+
|
|
280
|
+
|
|
281
|
+
@contextlib.contextmanager
|
|
282
|
+
def claim_write(context, table, sys_id, incoming):
|
|
283
|
+
"""Around ``DataServiceMixin.write_hook``. The FIRST entry for the
|
|
284
|
+
granted save — same context, table, requested id and the very payload
|
|
285
|
+
dict ``write-object`` passed — claims the grant and runs with it. Every
|
|
286
|
+
other entry (a sibling record, a re-entrant or nested write, a second
|
|
287
|
+
write of the same record) runs with no grant at all. Yields the grant
|
|
288
|
+
for the claiming entry, else ``None``."""
|
|
289
|
+
grant = _ACTIVE.get()
|
|
290
|
+
if grant is None:
|
|
291
|
+
yield None
|
|
292
|
+
return
|
|
293
|
+
if (
|
|
294
|
+
not grant.claimed
|
|
295
|
+
and grant.context is context
|
|
296
|
+
and grant.incoming is incoming
|
|
297
|
+
and table == grant.table
|
|
298
|
+
and _record_id(sys_id) == grant.sys_id
|
|
299
|
+
):
|
|
300
|
+
grant.claimed = True
|
|
301
|
+
grant.active = True
|
|
302
|
+
if grant.sys_id != NEW_ROW:
|
|
303
|
+
grant.target = grant.sys_id
|
|
304
|
+
try:
|
|
305
|
+
yield grant
|
|
306
|
+
finally:
|
|
307
|
+
grant.active = False
|
|
308
|
+
return
|
|
309
|
+
token = _ACTIVE.set(None)
|
|
310
|
+
try:
|
|
311
|
+
yield None
|
|
312
|
+
finally:
|
|
313
|
+
_ACTIVE.reset(token)
|
|
314
|
+
|
|
315
|
+
|
|
316
|
+
def pin_created(grant, row_sys_id):
|
|
317
|
+
"""The claimed create's row now exists: its hooks are covered from here
|
|
318
|
+
by that id (and no longer by ``"@new"``)."""
|
|
319
|
+
if grant is None or not grant.active or grant.target is not None:
|
|
320
|
+
return
|
|
321
|
+
record = _record_id(row_sys_id)
|
|
322
|
+
if isinstance(record, int):
|
|
323
|
+
grant.target = record
|
|
324
|
+
|
|
325
|
+
|
|
326
|
+
def run_hook(fn, args, kwargs):
|
|
327
|
+
"""Call an rwx hook ``fn(*args, **kwargs)`` under the override rules:
|
|
328
|
+
the grant reaches a hook only when the claimed save calls it directly
|
|
329
|
+
for its own record. A hook running inside another hook (a nested write,
|
|
330
|
+
read or find) or for another record runs with no grant: its checks are
|
|
331
|
+
enforced."""
|
|
332
|
+
grant = _ACTIVE.get()
|
|
333
|
+
if grant is None:
|
|
334
|
+
return fn(*args, **kwargs)
|
|
335
|
+
if grant.depth == 0 and grant.covers(args):
|
|
336
|
+
grant.depth += 1
|
|
337
|
+
try:
|
|
338
|
+
return fn(*args, **kwargs)
|
|
339
|
+
finally:
|
|
340
|
+
grant.depth -= 1
|
|
341
|
+
token = _ACTIVE.set(None)
|
|
342
|
+
try:
|
|
343
|
+
return fn(*args, **kwargs)
|
|
344
|
+
finally:
|
|
345
|
+
_ACTIVE.reset(token)
|
|
346
|
+
|
|
347
|
+
|
|
348
|
+
# ── declaring checks ────────────────────────────────────────────────────────
|
|
349
|
+
|
|
350
|
+
|
|
351
|
+
def _raise(failures):
|
|
352
|
+
exc = ValidationError(failures)
|
|
353
|
+
exc._deferrable = True
|
|
354
|
+
raise exc
|
|
355
|
+
|
|
356
|
+
|
|
357
|
+
_THIS_RECORD = object()
|
|
358
|
+
|
|
359
|
+
|
|
360
|
+
def _about_target(grant, record) -> bool:
|
|
361
|
+
"""Whether a check is about the claimed record: ``record`` omitted
|
|
362
|
+
means yes; given, it must be the claimed record's id (never while a
|
|
363
|
+
create has no id yet, unless it is ``"@new"`` then)."""
|
|
364
|
+
if record is _THIS_RECORD:
|
|
365
|
+
return True
|
|
366
|
+
wanted = _record_id(record)
|
|
367
|
+
if wanted is None:
|
|
368
|
+
return False
|
|
369
|
+
if grant.target is None:
|
|
370
|
+
return wanted == NEW_ROW
|
|
371
|
+
return wanted == grant.target
|
|
372
|
+
|
|
373
|
+
|
|
374
|
+
def _fails(context, check_id, ok, message, record=_THIS_RECORD) -> Optional[dict]:
|
|
375
|
+
"""``None`` when the check passes or is skipped by the override in
|
|
376
|
+
force; else the failure ``{"id", "message"}``."""
|
|
377
|
+
_require_id(check_id)
|
|
378
|
+
if ok:
|
|
379
|
+
return None
|
|
380
|
+
grant = active_grant(context)
|
|
381
|
+
if grant is not None and grant.skips(check_id) and _about_target(grant, record):
|
|
382
|
+
if check_id not in grant.skipped:
|
|
383
|
+
grant.skipped.append(check_id)
|
|
384
|
+
return None
|
|
385
|
+
return {"id": check_id, "message": "" if message is None else str(message)}
|
|
386
|
+
|
|
387
|
+
|
|
388
|
+
def check(context, check_id: str, ok, message: str, *, record=_THIS_RECORD) -> bool:
|
|
389
|
+
"""One data rule: ``ok`` truthy passes (returns ``True``). A failure
|
|
390
|
+
raises :class:`ValidationError` naming ``check_id``, unless an authorized
|
|
391
|
+
override of this save names it (then it is recorded as skipped and
|
|
392
|
+
``False`` is returned, so the hook can carry on).
|
|
393
|
+
|
|
394
|
+
``record``: the ``sys_id`` of the row being validated. Omitted, the
|
|
395
|
+
check is about the record being saved. A hook that validates ANOTHER
|
|
396
|
+
row of its own table must pass it: a check about any row but the saved
|
|
397
|
+
one is never skipped."""
|
|
398
|
+
failure = _fails(context, check_id, ok, message, record)
|
|
399
|
+
if failure is None:
|
|
400
|
+
return bool(ok)
|
|
401
|
+
_raise([failure])
|
|
402
|
+
|
|
403
|
+
|
|
404
|
+
class Checks:
|
|
405
|
+
"""Collects the data rules of one save; raises ONE
|
|
406
|
+
:class:`ValidationError` listing every failure (not skipped by an
|
|
407
|
+
override) when the block ends or :meth:`raise_if_failed` is called."""
|
|
408
|
+
|
|
409
|
+
def __init__(self, context, record=_THIS_RECORD):
|
|
410
|
+
self.context = context
|
|
411
|
+
self.record = record
|
|
412
|
+
self.failures: List[dict] = []
|
|
413
|
+
|
|
414
|
+
def check(self, check_id: str, ok, message: str) -> bool:
|
|
415
|
+
failure = _fails(self.context, check_id, ok, message, self.record)
|
|
416
|
+
if failure is None:
|
|
417
|
+
return bool(ok)
|
|
418
|
+
if not any(f["id"] == check_id for f in self.failures):
|
|
419
|
+
self.failures.append(failure)
|
|
420
|
+
return False
|
|
421
|
+
|
|
422
|
+
def raise_if_failed(self):
|
|
423
|
+
if self.failures:
|
|
424
|
+
failures, self.failures = self.failures, []
|
|
425
|
+
_raise(failures)
|
|
426
|
+
|
|
427
|
+
def __enter__(self):
|
|
428
|
+
return self
|
|
429
|
+
|
|
430
|
+
def __exit__(self, exc_type, exc, tb):
|
|
431
|
+
if exc_type is None:
|
|
432
|
+
self.raise_if_failed()
|
|
433
|
+
return False
|
|
434
|
+
|
|
435
|
+
|
|
436
|
+
def checks(context, *, record=_THIS_RECORD) -> Checks:
|
|
437
|
+
"""``with validation.checks(context) as v: v.check(...)``. ``record``
|
|
438
|
+
as for :func:`check`: pass the ``sys_id`` when the rules are about a
|
|
439
|
+
row other than the one being saved."""
|
|
440
|
+
return Checks(context, record)
|
|
441
|
+
|
|
442
|
+
|
|
443
|
+
def is_deferrable(exc) -> bool:
|
|
444
|
+
"""Whether ``exc`` came from this module's helpers (only those can be
|
|
445
|
+
skipped by an override)."""
|
|
446
|
+
return isinstance(exc, ValidationError) and exc._deferrable is True
|
|
447
|
+
|
|
448
|
+
|
|
449
|
+
def parse_override(value):
|
|
450
|
+
"""The client's ``override`` object as ``(check_ids, reason)``; refuses
|
|
451
|
+
(``AlertError``) a malformed one, a blank reason, or one over
|
|
452
|
+
``REASON_MAX`` characters."""
|
|
453
|
+
if not isinstance(value, dict):
|
|
454
|
+
raise AlertError("The override request is malformed.")
|
|
455
|
+
reason = value.get("reason")
|
|
456
|
+
reason = reason.strip() if isinstance(reason, str) else ""
|
|
457
|
+
if not reason:
|
|
458
|
+
raise AlertError("A reason is required to save past a validation check.")
|
|
459
|
+
if len(reason) > REASON_MAX:
|
|
460
|
+
raise AlertError(
|
|
461
|
+
f"The override reason must be {REASON_MAX} characters or fewer."
|
|
462
|
+
)
|
|
463
|
+
names = value.get("checks")
|
|
464
|
+
if (
|
|
465
|
+
not isinstance(names, list)
|
|
466
|
+
or not names
|
|
467
|
+
or len(names) > CHECKS_MAX
|
|
468
|
+
or not all(valid_check_id(n) for n in names)
|
|
469
|
+
):
|
|
470
|
+
raise AlertError("The override must name the checks it skips.")
|
|
471
|
+
return list(dict.fromkeys(names)), reason
|
|
472
|
+
|
|
473
|
+
|
|
474
|
+
__all__ = [
|
|
475
|
+
"CHECK_ID",
|
|
476
|
+
"CHECKS_MAX",
|
|
477
|
+
"Checks",
|
|
478
|
+
"EDIT",
|
|
479
|
+
"EDIT_RULES",
|
|
480
|
+
"RECORD",
|
|
481
|
+
"MASQUERADE_RULE",
|
|
482
|
+
"OPERATION",
|
|
483
|
+
"OverrideGrant",
|
|
484
|
+
"REASON_MAX",
|
|
485
|
+
"RULES",
|
|
486
|
+
"VIEW",
|
|
487
|
+
"VIEW_RULES",
|
|
488
|
+
"ValidationError",
|
|
489
|
+
"active_grant",
|
|
490
|
+
"claim_write",
|
|
491
|
+
"pin_created",
|
|
492
|
+
"check",
|
|
493
|
+
"checks",
|
|
494
|
+
"is_deferrable",
|
|
495
|
+
"masquerading",
|
|
496
|
+
"override_scope",
|
|
497
|
+
"parse_override",
|
|
498
|
+
"record_resource",
|
|
499
|
+
"resource",
|
|
500
|
+
"run_hook",
|
|
501
|
+
"valid_check_id",
|
|
502
|
+
]
|
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
velocity/__init__.py,sha256=
|
|
1
|
+
velocity/__init__.py,sha256=BDYGUKdmW1-ueOFU12jKkAOLI-NKLgFHNN0A3BvmeSo,362
|
|
2
2
|
velocity/cache.py,sha256=pthvw7gDVEXRzkTcQtA5YVf4Q1IxAamWsba4UReT0RE,8933
|
|
3
3
|
velocity/hooks.py,sha256=jY_qtAapNHvptmryFSD-Zc7RvLhV6e5nJEH3x2xTgCw,20575
|
|
4
4
|
velocity/logging.py,sha256=MAsZap1cDSdOBNRc_9ezQxup5dHOS0ARxU9NI_-UK3E,4037
|
|
5
5
|
velocity/aws/__init__.py,sha256=XJJ79gnPlhg3aJij713PB8-vjQOt-BkqxYeGCBOxAu8,3460
|
|
6
6
|
velocity/aws/amplify.py,sha256=N_763LiraJfuLYSllGKG6jfP2oyCJgtrK_wI2UZKv1E,8852
|
|
7
|
-
velocity/aws/authz.py,sha256=
|
|
7
|
+
velocity/aws/authz.py,sha256=v_hMZVZR3j_RrjUNwfnWau3NhIlzzRuAH-laVHMC4tM,54593
|
|
8
8
|
velocity/aws/blobs.py,sha256=2TlTZ3KPxBdXDJ99aVSgDLR11wPQ8O3BbtNbY8mFQ28,9691
|
|
9
9
|
velocity/aws/dirty_pipeline.py,sha256=yxAm-JWK-_epDjYolJxyGO2xsdefziZfsvIkcEAsk40,22411
|
|
10
10
|
velocity/aws/email.py,sha256=CAvXTAUxJqMaT8ylpRwRcVEA4YLFMUuHCrwYLVE4G1E,6243
|
|
@@ -26,6 +26,7 @@ velocity/aws/sms.py,sha256=2CdcLlIEy_V5K5Qx_pZ2vrakvEK7IhP7y1JUttBgyG4,16253
|
|
|
26
26
|
velocity/aws/ssm_config.py,sha256=xkcBxPuCcdjpeArxdcGnSBiuyG2txlUraSqtCtb_kIo,7987
|
|
27
27
|
velocity/aws/tiles.py,sha256=_38EH9ngxQxLeiZnTHBta-TXg1VkO2hPvaoPHWEKAlc,28011
|
|
28
28
|
velocity/aws/user_data.py,sha256=qLdmzUpkapUToEWaQ_jSeJa6hHgTHIqz0p0Cp2JuFx4,15564
|
|
29
|
+
velocity/aws/validation.py,sha256=rj1bDYULxR2Wu512vbIhEcmU4Uv_IcwgFX2yS1ZBLf8,18115
|
|
29
30
|
velocity/aws/assets/__init__.py,sha256=2R9LUShtaqkyRbMhxj8IL1JMP80H4iBfqaQflK38KXI,1709
|
|
30
31
|
velocity/aws/assets/backfill.py,sha256=ybbD5vqpmr6vTIue8HDRkNVJwfCdTFHzBeq91nmwtTg,4679
|
|
31
32
|
velocity/aws/assets/indexing.py,sha256=6sihNC6cPfhdNpPcNppucs9kSaV-HjCH1QsgSK7XFEA,8799
|
|
@@ -51,21 +52,21 @@ velocity/aws/deploy/policies.py,sha256=aO92HJOCN8L6SE0_BlnTaN6QGywVIPD6FeifvhfdQ
|
|
|
51
52
|
velocity/aws/deploy/reconcile.py,sha256=3xZXXiiVeCw4nUV8lKyk1XCgRbpNCLVYXIXbOLXes9I,20130
|
|
52
53
|
velocity/aws/deploy/targets.py,sha256=vmZzGbLDKNtWkwd2ado_ZhT8AT6nXYbJD5nIgDiBzRc,6632
|
|
53
54
|
velocity/aws/handlers/__init__.py,sha256=0yvVADxMHK8JOhgGRxMIz1XkNGlUk08AOmdR4qhNP2U,906
|
|
54
|
-
velocity/aws/handlers/base_handler.py,sha256=
|
|
55
|
+
velocity/aws/handlers/base_handler.py,sha256=1A_EO_71clM3-h-hAIUJxs_2LL7w3kkwj9Nz33loJMw,19918
|
|
55
56
|
velocity/aws/handlers/context.py,sha256=Yrq-vtl2-0WeoTaFVMuKOQRM2Cnyq21rNvVtUvGjxx0,61416
|
|
56
57
|
velocity/aws/handlers/context_factory.py,sha256=8rhYKrylzwQxBFqBckmF7jgWGZhfomLOT_Yu404CtJQ,784
|
|
57
|
-
velocity/aws/handlers/exceptions.py,sha256=
|
|
58
|
+
velocity/aws/handlers/exceptions.py,sha256=J-4VkiKASE-z2X-sr5EUq7FWv3x7fzR7Yl536G5VeZc,5026
|
|
58
59
|
velocity/aws/handlers/lambda_handler.py,sha256=CR9PrFHPpXlvIXPf_GrTXFaF5Ih0Es2DTU_qlYj1Zkk,21842
|
|
59
60
|
velocity/aws/handlers/masquerade.py,sha256=ZMXGGB-w7pXRV8Fq0qBmJOL1Eq55hXP3Rq3dWjJk6Ck,5157
|
|
60
61
|
velocity/aws/handlers/perf.py,sha256=zLAcr_IrvpnZS1zzzXi-YhopRgCv3OeetQgOx_S43Xw,1421
|
|
61
|
-
velocity/aws/handlers/response.py,sha256=
|
|
62
|
+
velocity/aws/handlers/response.py,sha256=Xi5mzBPiYC-VVS3qFyCgfuV3YyuGuhS1O54QGI7jGHs,17201
|
|
62
63
|
velocity/aws/handlers/sqs_handler.py,sha256=1A7pHnZ-gl6AGcdK5hWvNUg-s8IjRhrBeiQLacHHhHk,9669
|
|
63
|
-
velocity/aws/handlers/mixins/__init__.py,sha256=
|
|
64
|
+
velocity/aws/handlers/mixins/__init__.py,sha256=AJ2mDI53I7DhGqBj-Y3J2bSVR85n7uR3riY-aASi0_s,2757
|
|
64
65
|
velocity/aws/handlers/mixins/action_names.py,sha256=6RYAdromGcDD9Fv6tYKAtgzLhKx8gf5oG-7K67roWqI,1112
|
|
65
66
|
velocity/aws/handlers/mixins/audit_trail.py,sha256=CxZ_3IgbxZ3Ev2pSvwLeVPxlsVqUjazr87QsBqOuHHs,27421
|
|
66
67
|
velocity/aws/handlers/mixins/client_errors.py,sha256=0LqIRm1gZRwzHH32ravGHAgcQqJzjh5p6M_ptuL2Tto,20105
|
|
67
68
|
velocity/aws/handlers/mixins/client_input.py,sha256=UhfwsRiztOYDrJnQPZhQ6J71NAmCyrXjMgxbko2rnfQ,24225
|
|
68
|
-
velocity/aws/handlers/mixins/data_service.py,sha256=
|
|
69
|
+
velocity/aws/handlers/mixins/data_service.py,sha256=5pJ2gZG_pqZ9UR2kCI6Qa5Nut2n3MluLRnUrphJ3mGo,125538
|
|
69
70
|
velocity/aws/handlers/mixins/job_handler.py,sha256=RvMtoMiZiivoxSVp-egQUQSpr6xZCDfeaYxzonIPLyw,7509
|
|
70
71
|
velocity/aws/handlers/mixins/permissions_actions.py,sha256=KjWKu4in0OvczEqO4JpVkmBPL_C0I1qOAraBeW21XvI,32409
|
|
71
72
|
velocity/aws/handlers/mixins/row_scoped.py,sha256=f7N70RjzlHIVyjDsEI1oImCdjyFsgoP9aIvYXUXD5-Q,12967
|
|
@@ -253,9 +254,9 @@ velocity/workflow/points.py,sha256=g_vQ3cdHdx_JloVCS5dVjo_jJoSolO92K5p3suDzxlE,1
|
|
|
253
254
|
velocity/workflow/schema.py,sha256=1ZAkGZ_4YrTAfY6TIPCviWQJGLhhmAJmkxisfLyy2og,21597
|
|
254
255
|
velocity/workflow/traveler.py,sha256=Ik1InoEo69sZB1wVV-UinVo4P0P5QlcV_hh858p3OWE,20562
|
|
255
256
|
velocity/workflow/views.py,sha256=oTPjpuheND8y4VbcTY8c-4fMdSHKb0jgGzXMuT_G7_s,32175
|
|
256
|
-
velocity_python-0.9.
|
|
257
|
-
velocity_python-0.9.
|
|
258
|
-
velocity_python-0.9.
|
|
259
|
-
velocity_python-0.9.
|
|
260
|
-
velocity_python-0.9.
|
|
261
|
-
velocity_python-0.9.
|
|
257
|
+
velocity_python-0.9.2.dist-info/licenses/LICENSE,sha256=aoN245GG8s9oRUU89KNiGTU4_4OtnNmVi4hQeChg6rM,1076
|
|
258
|
+
velocity_python-0.9.2.dist-info/METADATA,sha256=0uVUIRUtgV1_klFlzqRrHz4z-aiVm2yTbQSrevFabvU,17820
|
|
259
|
+
velocity_python-0.9.2.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
260
|
+
velocity_python-0.9.2.dist-info/entry_points.txt,sha256=nXUKJHkOGQCSPoagdmMNd_qycrle1LVU-GhYknLGM1M,56
|
|
261
|
+
velocity_python-0.9.2.dist-info/top_level.txt,sha256=JW2vJPmodgdgSz7H6yoZvnxF8S3fTMIv-YJWCT1sNW0,9
|
|
262
|
+
velocity_python-0.9.2.dist-info/RECORD,,
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|