Repository navigation
Expand file tree
/
Copy pathschema.py
More file actions
488 lines (392 loc) · 20.4 KB
/
Copy pathschema.py
File metadata and controls
488 lines (392 loc) · 20.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
"""Optional per-URN payload schema validation (ADR-0024).
The Python mirror of the Go ``schema`` package and PHP ``BabelQueue\\Schema``. A
:class:`SchemaProvider` supplies a JSON Schema for a message URN — typically read from a
babelqueue-registry ``registry.json`` — and the message's ``data`` is validated against it.
It is opt-in: a URN with no registered schema is never validated.
- **Producer-side (recommended):** call :func:`validate` before publishing so invalid data
never enters the queue, or :func:`check` to branch without raising::
from babelqueue.schema import MapProvider, validate
provider = MapProvider.from_json({"urn:babel:orders:created": ORDERS_SCHEMA_JSON})
validate(provider, "urn:babel:orders:created", {"order_id": 7}) # raises on mismatch
- **Consumer-side (safety net):** wrap a handler with :func:`wrap`. Because a Python handler
receives ``data`` (and ``meta``, ``envelope``) positionally rather than a message object,
the URN is passed explicitly — usually the same URN you register under::
app.register(URN, wrap(provider, URN, on_order_created))
Invalid data raises :class:`~babelqueue.exceptions.InvalidPayloadError`, so the runtime
redelivers (and eventually dead-letters) the poison message; a URN with no schema runs the
handler unchanged.
The validator is a small subset of JSON Schema (draft-07) whose verdicts match the Go and
PHP validators and babelqueue-registry's ``compat`` linter: ``type`` (a name or a union list
such as ``["string", "null"]``), ``required``, ``properties``, ``additionalProperties``,
``items``, ``enum``, ``const``, ``minLength``, ``maxLength``, ``minimum``. ``const`` / ``enum``
compare numbers by mathematical value (``1 == 1.0``; ``True`` is never ``1``), also inside arrays
and objects. A keyword outside the subset never changes the verdict (it is evaluated as absent),
but registering the schema with a :class:`MapProvider` / :class:`DirProvider` reports one
:class:`SchemaWarning` per occurrence through the ``babelqueue.schema`` logger and the provider's
``warnings`` map (conformance ``payload_schema_keywords``). Zero dependencies (stdlib only).
"""
from __future__ import annotations
import functools
import json
import logging
import math
import os
import threading
from decimal import Decimal
from typing import Any, Callable, Dict, List, Mapping, NamedTuple, Optional, Protocol, runtime_checkable
from .exceptions import InvalidPayloadError
Handler = Callable[..., None]
logger = logging.getLogger("babelqueue.schema")
@runtime_checkable
class SchemaProvider(Protocol):
"""A source of per-URN ``data`` schemas, keyed on the message URN."""
def schema_for(self, urn: str) -> Optional[Mapping[str, Any]]:
"""The JSON Schema registered for ``urn``, or None when none is registered."""
class MapProvider:
"""In-memory :class:`SchemaProvider`, for tests and for embedding schemas in code."""
def __init__(self, schemas: Mapping[str, Mapping[str, Any]]) -> None:
self._schemas: dict[str, Mapping[str, Any]] = dict(schemas)
self._warnings: Dict[str, List["SchemaWarning"]] = {}
for urn, schema in self._schemas.items():
found = report_unsupported(urn, schema)
if found:
self._warnings[urn] = found
@property
def warnings(self) -> Dict[str, List["SchemaWarning"]]:
"""urn -> the unsupported-keyword warnings its schema produced at registration (only URNs
that produced at least one). Read-only: a copy; each was also logged on ``babelqueue.schema``."""
return {urn: list(found) for urn, found in self._warnings.items()}
@classmethod
def from_json(cls, raw: Mapping[str, str]) -> "MapProvider":
"""Build a provider from URN -> raw JSON Schema strings, decoding each."""
schemas: dict[str, Mapping[str, Any]] = {}
for urn, body in raw.items():
decoded = json.loads(body)
if not isinstance(decoded, dict):
raise ValueError(f"schema: invalid JSON schema for {urn!r}")
schemas[urn] = decoded
return cls(schemas)
def schema_for(self, urn: str) -> Optional[Mapping[str, Any]]:
return self._schemas.get(urn)
class DirProvider:
"""Reads schemas from a babelqueue-registry manifest (``registry.json``): a list of
``{urn, schema}`` entries mapping each URN to a schema file for its ``data`` block. The
bridge that makes the registry's governed schemas enforceable at runtime. Schema files
are read and decoded lazily and cached (thread-safe). A URN absent from the manifest
returns None (skip); a URN whose schema file is missing raises (config/IO error)."""
def __init__(self, manifest_path: str) -> None:
with open(manifest_path, "r", encoding="utf-8") as fh:
manifest = json.load(fh)
if not isinstance(manifest, dict):
raise ValueError(f"schema: invalid registry manifest {manifest_path!r}")
self._dir = os.path.dirname(manifest_path)
self._files: dict[str, str] = {}
self._cache: dict[str, Mapping[str, Any]] = {}
self._lock = threading.Lock()
self._warnings: Dict[str, List["SchemaWarning"]] = {}
entries = manifest.get("schemas") or []
if isinstance(entries, list):
for entry in entries:
if not isinstance(entry, Mapping):
continue
urn = entry.get("urn")
file = entry.get("schema")
if isinstance(urn, str) and urn and isinstance(file, str) and file:
self._files[urn] = file
@property
def warnings(self) -> Dict[str, List["SchemaWarning"]]:
"""urn -> the unsupported-keyword warnings reported when its schema was first loaded.
Read-only: a copy."""
with self._lock:
return {urn: list(found) for urn, found in self._warnings.items()}
def schema_for(self, urn: str) -> Optional[Mapping[str, Any]]:
with self._lock:
cached = self._cache.get(urn)
if cached is not None:
return cached
file = self._files.get(urn)
if file is None:
return None
path = file if os.path.isabs(file) else os.path.join(self._dir, file)
with open(path, "r", encoding="utf-8") as fh:
decoded = json.load(fh)
if not isinstance(decoded, dict):
raise ValueError(f"schema: invalid schema for {urn!r} ({file})")
self._cache[urn] = decoded
found = report_unsupported(urn, decoded)
if found:
self._warnings[urn] = found
return decoded
def check(provider: SchemaProvider, urn: str, data: Mapping[str, Any]) -> Optional[str]:
"""The first ``data`` violation for ``(urn, data)``, or None when it is valid or when no
schema is registered for the URN (opt-in). Non-raising; for producer-side branching."""
schema = provider.schema_for(urn)
if schema is None:
return None
return validate_schema(schema, dict(data))
def validate(provider: SchemaProvider, urn: str, data: Mapping[str, Any]) -> None:
"""Validate ``(urn, data)`` against its registered schema, raising otherwise. The
producer-side guard; call it before publishing.
:raises InvalidPayloadError: when the data does not match the URN's schema.
"""
violation = check(provider, urn, data)
if violation is not None:
raise InvalidPayloadError(urn, violation)
def wrap(provider: SchemaProvider, urn: str, handler: Handler) -> Handler:
"""Wrap a consume handler so each message's ``data`` is validated against ``urn``'s
schema before the handler runs. The returned callable keeps ``handler``'s signature (via
:func:`functools.wraps`), so the runtime still passes it the right number of positional
args (``data, meta`` or ``data, meta, envelope``)."""
@functools.wraps(handler)
def wrapped(*args: Any) -> None:
data = args[0] if args and isinstance(args[0], Mapping) else {}
validate(provider, urn, data)
handler(*args)
return wrapped
_KNOWN_TYPES = ("object", "array", "string", "integer", "number", "boolean", "null")
def validate_schema(schema: Mapping[str, Any], value: Any, path: str = "") -> Optional[str]:
"""The first violation of ``value`` against a (subset) JSON Schema node, or None."""
if "const" in schema and not _equal(value, schema["const"]):
return _violation(path, "wrong_const")
enum = schema.get("enum")
if isinstance(enum, list) and not any(_equal(value, item) for item in enum):
return _violation(path, "not_in_enum")
typ = schema.get("type")
if isinstance(typ, str):
return _check_type(schema, typ, value, path)
if isinstance(typ, list):
# Union (Draft-07): valid when the value matches ANY listed type, and then the keywords of
# the matched type apply. Names outside the known types can never match; a list with no
# known name constrains nothing, like an unknown single ``type``.
names = [t for t in typ if isinstance(t, str) and t in _KNOWN_TYPES]
if not names:
return None
for name in names:
if _matches_type(name, value):
return _check_type(schema, name, value, path)
return _violation(path, "wrong_type")
return None
def _matches_type(typ: str, value: Any) -> bool:
if typ == "object":
return isinstance(value, Mapping)
if typ == "array":
return isinstance(value, list)
if typ == "string":
return isinstance(value, str)
if typ == "integer":
return _is_integer(value)
if typ == "number":
return _is_number(value)
if typ == "boolean":
return isinstance(value, bool)
return value is None # "null"
def _check_type(schema: Mapping[str, Any], typ: str, value: Any, path: str) -> Optional[str]:
if typ == "object":
return _check_object(schema, value, path)
if typ == "array":
return _check_array(schema, value, path)
if typ == "string":
if not isinstance(value, str):
return _violation(path, "not_a_string")
min_len = _length_bound(schema.get("minLength"))
if min_len is not None and len(value) < min_len:
return _violation(path, "below_min_length")
max_len = _length_bound(schema.get("maxLength"))
if max_len is not None and len(value) > max_len:
return _violation(path, "above_max_length")
return None
if typ == "integer":
if not _is_integer(value):
return _violation(path, "not_an_integer")
return _check_minimum(schema, value, path)
if typ == "number":
if not _is_number(value):
return _violation(path, "not_a_number")
return _check_minimum(schema, value, path)
if typ == "boolean":
return None if isinstance(value, bool) else _violation(path, "not_a_boolean")
if typ == "null":
return None if value is None else _violation(path, "not_null")
return None
def _check_object(schema: Mapping[str, Any], value: Any, path: str) -> Optional[str]:
if not isinstance(value, Mapping):
return _violation(path, "not_an_object")
required = schema.get("required")
if isinstance(required, list):
for key in required:
if isinstance(key, str) and key not in value:
return _violation(_join(path, key), "missing_required")
properties = schema.get("properties")
properties = properties if isinstance(properties, Mapping) else {}
additional_allowed = schema.get("additionalProperties") is not False
for key, item in value.items():
name = str(key)
prop = properties.get(name)
if isinstance(prop, Mapping):
violation = validate_schema(prop, item, _join(path, name))
if violation is not None:
return violation
continue
if not additional_allowed:
return _violation(_join(path, name), "additional_not_allowed")
return None
def _check_array(schema: Mapping[str, Any], value: Any, path: str) -> Optional[str]:
if not isinstance(value, list):
return _violation(path, "not_an_array")
items = schema.get("items")
if not isinstance(items, Mapping):
return None
for i, item in enumerate(value):
violation = validate_schema(items, item, f"{path}[{i}]")
if violation is not None:
return violation
return None
def _length_bound(bound: Any) -> Optional[int]:
"""``minLength`` / ``maxLength`` as an int, truncated toward zero like Go and PHP.
A non-numeric, boolean or non-finite (NaN / +-Infinity) bound is ignored (``None``), as in the
other SDKs; ``int()`` would raise ``ValueError`` / ``OverflowError`` on those.
"""
if isinstance(bound, bool) or not isinstance(bound, (int, float, Decimal)):
return None
if isinstance(bound, float) and not math.isfinite(bound):
return None
if isinstance(bound, Decimal) and not bound.is_finite():
return None
return int(bound)
def _check_minimum(schema: Mapping[str, Any], value: Any, path: str) -> Optional[str]:
minimum = schema.get("minimum")
if isinstance(minimum, (int, float, Decimal)) and not isinstance(minimum, bool) and value < minimum:
return _violation(path, "below_minimum")
return None
def _is_integer(value: Any) -> bool:
"""``integer`` accepts every number whose mathematical value is integral (``1.0`` too)."""
if isinstance(value, bool):
return False
if isinstance(value, int):
return True
if isinstance(value, float):
return value.is_integer()
if isinstance(value, Decimal):
return value.is_finite() and value == value.to_integral_value()
return False
def _is_number(value: Any) -> bool:
# int / float / Decimal (what a ``parse_float=Decimal`` decoder yields); never a bool.
return isinstance(value, (int, float, Decimal)) and not isinstance(value, bool)
def _equal(a: Any, b: Any) -> bool:
"""JSON equality for ``const`` / ``enum``: numbers compare by mathematical value (``1`` ==
``1.0`` == ``Decimal("1")``), recursively inside arrays and objects (object key order is
irrelevant); ``True`` is never ``1``, ``"1"`` is never ``1`` and ``None`` equals only ``None``."""
if isinstance(a, bool) or isinstance(b, bool):
return isinstance(a, bool) and isinstance(b, bool) and a == b
if _is_number(a) and _is_number(b):
return bool(a == b)
if a is None or b is None:
return a is None and b is None
if isinstance(a, str) and isinstance(b, str):
return a == b
if isinstance(a, Mapping) and isinstance(b, Mapping):
return a.keys() == b.keys() and all(_equal(a[k], b[k]) for k in a)
if isinstance(a, (list, tuple)) and isinstance(b, (list, tuple)):
return len(a) == len(b) and all(_equal(x, y) for x, y in zip(a, b))
return False
def _violation(path: str, reason: str) -> str:
return f"{path or '<root>'}: {reason}"
def _join(path: str, key: str) -> str:
return key if path == "" else f"{path}.{key}"
class SchemaWarning(NamedTuple):
"""One keyword outside the supported subset, found while registering a schema. ``pointer`` is
the RFC 6901 JSON Pointer, within the schema document, of the schema object carrying
``keyword`` (``""`` for the root, ``/properties/<name>``, ``/items``,
``/additionalProperties``). The keyword never changes the verdict; this is only a notice."""
pointer: str
keyword: str
_SUPPORTED_KEYWORDS = frozenset(
("type", "required", "properties", "additionalProperties", "items", "enum", "const",
"minLength", "maxLength", "minimum")
)
_ANNOTATION_KEYWORDS = frozenset(("$schema", "$id", "title", "description", "examples", "default", "$comment"))
def unsupported_keywords(schema: Mapping[str, Any]) -> List[SchemaWarning]:
"""Every keyword in ``schema`` outside the supported subset, one entry per occurrence.
Annotation keywords (``$schema``, ``$id``, ``title``, ``description``, ``examples``,
``default``, ``$comment`` and anything starting with ``x-``) never count. The walk descends
only into the values of ``properties``, into ``items`` and into ``additionalProperties`` when
each is an object; it never descends into an unsupported keyword's value, so ``allOf`` or
``definitions`` is one warning and what is inside produces none.
"""
found: List[SchemaWarning] = []
_walk_unsupported(schema, "", found)
return found
def _escape_pointer(token: str) -> str:
return token.replace("~", "~0").replace("/", "~1")
def _walk_unsupported(node: Any, pointer: str, out: List[SchemaWarning]) -> None:
if not isinstance(node, Mapping):
return
for key in node:
name = str(key)
if name in _SUPPORTED_KEYWORDS or name in _ANNOTATION_KEYWORDS or name.startswith("x-"):
continue
out.append(SchemaWarning(pointer, name))
properties = node.get("properties")
if isinstance(properties, Mapping):
for name, sub in properties.items():
_walk_unsupported(sub, f"{pointer}/properties/{_escape_pointer(str(name))}", out)
_walk_unsupported(node.get("items"), f"{pointer}/items", out)
_walk_unsupported(node.get("additionalProperties"), f"{pointer}/additionalProperties", out)
def report_unsupported(urn: str, schema: Mapping[str, Any]) -> List[SchemaWarning]:
"""Find the unsupported keywords of ``schema`` (registered under ``urn``), log one warning each
on the ``babelqueue.schema`` logger and return them."""
found = unsupported_keywords(schema)
for warning in found:
logger.warning(
"Schema for %s uses keyword %r at %r, which the payload validator does not support; "
"it is ignored (the verdict is unchanged).",
urn, warning.keyword, warning.pointer,
)
return found
class SensitivePath(NamedTuple):
"""One property a schema marked ``x-gdpr-sensitive`` (ADR-0030), located by its dotted path
from the schema root. Array elements use the ``field[]`` segment the validator and registry
``compat`` linter use (e.g. ``addresses[].line``). ``category`` is the optional
``"x-gdpr-sensitive": "<category>"`` string, or ``""`` when the keyword was the boolean
``true``. A mark on the root schema itself is reported with ``path == ""``."""
path: str
category: str
def _gdpr_mark(schema: Mapping[str, Any]) -> Optional[str]:
"""Read the ``x-gdpr-sensitive`` extension keyword (ADR-0030) from one schema node.
Returns the category string for a marked node (``""`` when the keyword was the boolean
``true``, a non-empty category when it was a non-empty string), or ``None`` when the node is
not marked. The keyword is **validation-neutral**: it never makes a value valid or invalid, so
annotating a schema is never a breaking change (GR-1). Any other shape — ``false``, ``""``, a
number — leaves the node unmarked. Mirrors the Go ``fromMap`` and the registry's parser.
"""
mark = schema.get("x-gdpr-sensitive")
if mark is True:
return ""
if isinstance(mark, str) and mark != "":
return mark
return None
def sensitive_paths(schema: Mapping[str, Any]) -> List[SensitivePath]:
"""Every property a schema marked ``x-gdpr-sensitive``, in sorted path order (ADR-0030).
Descends nested objects (dotted paths like ``profile.full_name``) and array item schemas
(``addresses[].line``); a mark on the root schema itself is reported with ``path == ""``. It is
the value-level counterpart to the registry's inventory: :mod:`babelqueue.gdpr` uses these paths
to locate the leaves it encrypts on produce and decrypts on consume. The Python mirror of the
Go ``Schema.SensitivePaths``. Non-mapping / malformed nodes are skipped, never raised on.
"""
out: List[SensitivePath] = []
_collect_sensitive(schema, "", out)
out.sort(key=lambda sp: sp.path)
return out
def _collect_sensitive(schema: Any, path: str, out: List[SensitivePath]) -> None:
if not isinstance(schema, Mapping):
return
category = _gdpr_mark(schema)
if category is not None:
out.append(SensitivePath(path, category))
properties = schema.get("properties")
if isinstance(properties, Mapping):
for name, sub in properties.items():
_collect_sensitive(sub, _join(path, str(name)), out)
items = schema.get("items")
if isinstance(items, Mapping):
_collect_sensitive(items, path + "[]", out)