data-mask-policy 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,923 @@
1
+ """Offline policy-driven masking for JSON-compatible Python data."""
2
+ from __future__ import annotations
3
+
4
+ import inspect
5
+ import ipaddress
6
+ import math
7
+ import re
8
+ from collections.abc import Callable
9
+ from dataclasses import dataclass, field
10
+ from functools import partial
11
+ from types import CoroutineType
12
+ from typing import Literal, TypeAlias, TypedDict, cast
13
+
14
+ __all__ = [
15
+ "CompiledPolicy",
16
+ "CustomStrategy",
17
+ "JsonScalar",
18
+ "JsonValue",
19
+ "Limits",
20
+ "MaskCondition",
21
+ "MaskContext",
22
+ "MaskError",
23
+ "MaskErrorCode",
24
+ "MaskPolicy",
25
+ "MaskReport",
26
+ "MaskResult",
27
+ "MaskRule",
28
+ "MaskStrategy",
29
+ "MaskStrategyOptions",
30
+ "Masker",
31
+ "PolicyValidation",
32
+ "compile_policy",
33
+ "create_masker",
34
+ "explain_policy",
35
+ "mask_account",
36
+ "mask_card",
37
+ "mask_email",
38
+ "mask_identifier",
39
+ "mask_ip",
40
+ "mask_name",
41
+ "mask_object",
42
+ "mask_phone",
43
+ "mask_string",
44
+ "redact",
45
+ "validate_policy",
46
+ ]
47
+
48
+ JsonScalar: TypeAlias = "None | str | int | float | bool"
49
+ JsonValue: TypeAlias = "JsonScalar | list[JsonValue] | dict[str, JsonValue]"
50
+ MaskContext: TypeAlias = "dict[str, JsonScalar]"
51
+ CustomStrategy: TypeAlias = "Callable[[JsonValue, dict[str, JsonValue]], JsonValue]"
52
+ MaskErrorCode: TypeAlias = Literal[
53
+ "INVALID_POLICY", "INVALID_RULE", "INVALID_PATH", "UNKNOWN_STRATEGY", "INVALID_STRATEGY_OPTIONS",
54
+ "UNSUPPORTED_SCHEMA_VERSION", "POLICY_CONFLICT", "INVALID_CONTEXT", "MISSING_REQUIRED_FIELD",
55
+ "INVALID_VALUE", "UNSUPPORTED_INPUT", "CIRCULAR_REFERENCE", "DEPTH_LIMIT_EXCEEDED",
56
+ "NODE_LIMIT_EXCEEDED", "ARRAY_LIMIT_EXCEEDED", "STRING_LIMIT_EXCEEDED", "WILDCARD_LIMIT_EXCEEDED",
57
+ "WORK_LIMIT_EXCEEDED", "TEXT_LIMIT_EXCEEDED", "POLICY_LIMIT_EXCEEDED", "CUSTOM_STRATEGY_FAILED",
58
+ "INVALID_STRATEGY_RESULT",
59
+ ]
60
+
61
+
62
+ class Limits(TypedDict, total=False):
63
+ maxRules: int
64
+ maxPathLength: int
65
+ maxPathSegments: int
66
+ maxConditionDepth: int
67
+ maxDepth: int
68
+ maxNodes: int
69
+ maxArrayLength: int
70
+ maxStringLength: int
71
+ maxWildcardMatches: int
72
+ maxWork: int
73
+ maxTextSize: int
74
+
75
+
76
+ class MaskStrategyOptions(TypedDict, total=False):
77
+ maskChar: str
78
+ visiblePrefix: int
79
+ visibleSuffix: int
80
+ maskLength: int
81
+ preserveLength: bool
82
+ replacement: JsonValue
83
+ invalidInput: Literal["redact", "error"]
84
+
85
+
86
+ MaskStrategy: TypeAlias = Literal[
87
+ "redact", "remove", "replace", "partial", "prefix", "suffix", "full", "email", "phone", "card",
88
+ "name", "identifier", "account", "ip", "aadhaar", "pan", "ssn", "sin", "passport", "iban",
89
+ ]
90
+
91
+
92
+ class _All(TypedDict):
93
+ all: list[MaskCondition]
94
+
95
+
96
+ class _Any(TypedDict):
97
+ any: list[MaskCondition]
98
+
99
+
100
+ class _Exists(TypedDict):
101
+ field: str
102
+ operator: Literal["exists"]
103
+
104
+
105
+ class _Equality(TypedDict):
106
+ field: str
107
+ operator: Literal["equals", "notEquals"]
108
+ value: JsonScalar
109
+
110
+
111
+ class _Membership(TypedDict):
112
+ field: str
113
+ operator: Literal["in", "notIn"]
114
+ value: list[JsonScalar]
115
+
116
+
117
+ MaskCondition: TypeAlias = "_All | _Any | _Exists | _Equality | _Membership"
118
+
119
+
120
+ class _RuleRequired(TypedDict):
121
+ id: str
122
+ path: str
123
+ strategy: str
124
+
125
+
126
+ class MaskRule(_RuleRequired, total=False):
127
+ description: str
128
+ options: MaskStrategyOptions | dict[str, JsonValue]
129
+ priority: int
130
+ required: bool
131
+ when: MaskCondition
132
+
133
+
134
+ class _PolicyRequired(TypedDict):
135
+ schemaVersion: Literal[1]
136
+ rules: list[MaskRule]
137
+
138
+
139
+ class MaskPolicy(_PolicyRequired, total=False):
140
+ id: str
141
+ version: str
142
+ defaultAction: Literal["preserve", "remove"]
143
+ allowPaths: list[str]
144
+
145
+
146
+ class _RuleReport(TypedDict):
147
+ id: str
148
+ strategy: str
149
+ matched: int
150
+ selected: int
151
+ status: Literal["matched", "unmatched", "skipped"]
152
+
153
+
154
+ class MaskReport(TypedDict):
155
+ policyId: str | None
156
+ policyVersion: str | None
157
+ defaultAction: Literal["preserve", "remove"]
158
+ matchedRules: int
159
+ maskedFields: int
160
+ removedFields: int
161
+ projectedFields: int
162
+ unmatchedRules: int
163
+ skippedRules: int
164
+ rules: list[_RuleReport]
165
+
166
+
167
+ class MaskResult(TypedDict):
168
+ data: JsonValue
169
+ report: MaskReport
170
+
171
+
172
+ class _ValidationErrorRequired(TypedDict):
173
+ code: MaskErrorCode
174
+
175
+
176
+ class _ValidationError(_ValidationErrorRequired, total=False):
177
+ ruleIndex: int
178
+ otherRuleIndex: int
179
+
180
+
181
+ class PolicyValidation(TypedDict):
182
+ valid: bool
183
+ errors: list[_ValidationError]
184
+
185
+
186
+ class MaskError(Exception):
187
+ """Stable error code and optional zero-based configuration indices."""
188
+
189
+ def __init__(
190
+ self, code: MaskErrorCode, rule_index: int | None = None, other_rule_index: int | None = None
191
+ ) -> None:
192
+ super().__init__(code)
193
+ self.code = code
194
+ self.rule_index = rule_index
195
+ self.other_rule_index = other_rule_index
196
+
197
+
198
+ @dataclass(frozen=True, slots=True)
199
+ class _Bounds:
200
+ maxRules: int = 512
201
+ maxPathLength: int = 1024
202
+ maxPathSegments: int = 32
203
+ maxConditionDepth: int = 8
204
+ maxDepth: int = 64
205
+ maxNodes: int = 250_000
206
+ maxArrayLength: int = 50_000
207
+ maxStringLength: int = 65_536
208
+ maxWildcardMatches: int = 100_000
209
+ maxWork: int = 1_000_000
210
+ maxTextSize: int = 4_000_000
211
+
212
+
213
+ _DEFAULTS = _Bounds()
214
+ _FORBIDDEN = frozenset({"__proto__", "prototype", "constructor"})
215
+ _SAFE_INT = (1 << 53) - 1
216
+ _ID = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]{0,95}")
217
+ _INDEX = re.compile(r"0|[1-9][0-9]*")
218
+ _CONTROL = re.compile(r"[\x00-\x20\x7f]")
219
+ _SURROGATE = re.compile(r"[\ud800-\udfff]")
220
+ Dict: TypeAlias = "dict[str, JsonValue]"
221
+
222
+
223
+ @dataclass(slots=True)
224
+ class _Budget:
225
+ limits: _Bounds
226
+ nodes: int = 0
227
+ text: int = 0
228
+
229
+ def count(self, depth: int) -> None:
230
+ if depth > self.limits.maxDepth:
231
+ raise MaskError("DEPTH_LIMIT_EXCEEDED")
232
+ self.nodes += 1
233
+ if self.nodes > self.limits.maxNodes:
234
+ raise MaskError("NODE_LIMIT_EXCEEDED")
235
+
236
+ def string(self, value: str, code: MaskErrorCode) -> None:
237
+ if len(value) > self.limits.maxStringLength:
238
+ raise MaskError("STRING_LIMIT_EXCEEDED")
239
+ if _SURROGATE.search(value):
240
+ raise MaskError(code)
241
+ self.text += len(value)
242
+ if self.text > self.limits.maxTextSize:
243
+ raise MaskError("TEXT_LIMIT_EXCEEDED")
244
+
245
+
246
+ def _copy(
247
+ value: object, budget: _Budget, code: MaskErrorCode, depth: int = 0, ancestors: set[int] | None = None
248
+ ) -> JsonValue:
249
+ budget.count(depth)
250
+ if value is None or type(value) is bool:
251
+ return value
252
+ if type(value) is str:
253
+ budget.string(value, code)
254
+ return value
255
+ if type(value) is int:
256
+ if -_SAFE_INT <= value <= _SAFE_INT:
257
+ return value
258
+ raise MaskError(code)
259
+ if type(value) is float:
260
+ if math.isfinite(value) and (not value.is_integer() or abs(value) <= _SAFE_INT):
261
+ return int(value) if value.is_integer() else value
262
+ raise MaskError(code)
263
+ if type(value) is not list and type(value) is not dict:
264
+ raise MaskError(code)
265
+ if ancestors is None:
266
+ ancestors = set()
267
+ identity = id(value)
268
+ if identity in ancestors:
269
+ raise MaskError("CIRCULAR_REFERENCE")
270
+ ancestors.add(identity)
271
+ try:
272
+ if type(value) is list:
273
+ if len(value) > budget.limits.maxArrayLength:
274
+ raise MaskError("ARRAY_LIMIT_EXCEEDED")
275
+ return [_copy(item, budget, code, depth + 1, ancestors) for item in value]
276
+ output: Dict = {}
277
+ for key, item in cast(dict[object, object], value).items():
278
+ if type(key) is not str or key in _FORBIDDEN:
279
+ raise MaskError(code)
280
+ budget.string(key, code)
281
+ output[key] = _copy(item, budget, code, depth + 1, ancestors)
282
+ return output
283
+ finally:
284
+ ancestors.remove(identity)
285
+
286
+
287
+ def _record(value: object, code: MaskErrorCode) -> Dict:
288
+ if type(value) is not dict:
289
+ raise MaskError(code)
290
+ return cast(Dict, value)
291
+
292
+
293
+ def _keys(value: Dict, allowed: tuple[str, ...], code: MaskErrorCode) -> None:
294
+ if any(key not in allowed for key in value):
295
+ raise MaskError(code)
296
+
297
+
298
+ class _Wildcard:
299
+ __slots__ = ()
300
+
301
+
302
+ _WILDCARD = _Wildcard()
303
+ _Segment: TypeAlias = "str | int | _Wildcard"
304
+ _Path: TypeAlias = "tuple[_Segment, ...]"
305
+
306
+
307
+ def _path(value: JsonValue, limits: _Bounds) -> _Path:
308
+ code: MaskErrorCode = "INVALID_PATH"
309
+ if not isinstance(value, str) or not value or len(value) > limits.maxPathLength:
310
+ raise MaskError(code)
311
+ path = value
312
+ segments: list[_Segment] = []
313
+ cursor = 0
314
+
315
+ def push(segment: _Segment) -> None:
316
+ if isinstance(segment, str) and (not segment or segment in _FORBIDDEN):
317
+ raise MaskError(code)
318
+ segments.append(segment)
319
+ if len(segments) > limits.maxPathSegments:
320
+ raise MaskError(code)
321
+
322
+ def name() -> None:
323
+ nonlocal cursor
324
+ characters: list[str] = []
325
+ while cursor < len(path) and path[cursor] not in ".[]":
326
+ character = path[cursor]
327
+ cursor += 1
328
+ if character == "\\":
329
+ if cursor == len(path) or path[cursor] not in ".[]\\":
330
+ raise MaskError(code)
331
+ character = path[cursor]
332
+ cursor += 1
333
+ characters.append(character)
334
+ push("".join(characters))
335
+
336
+ if path[0] != "[":
337
+ name()
338
+ while cursor < len(path):
339
+ if path[cursor] == ".":
340
+ cursor += 1
341
+ name()
342
+ elif path[cursor] == "[":
343
+ end = path.find("]", cursor + 1)
344
+ if end == -1:
345
+ raise MaskError(code)
346
+ token = path[cursor + 1:end]
347
+ if token == "*":
348
+ push(_WILDCARD)
349
+ elif len(token) <= 16 and _INDEX.fullmatch(token) and int(token) <= _SAFE_INT:
350
+ push(int(token))
351
+ else:
352
+ raise MaskError(code)
353
+ cursor = end + 1
354
+ else:
355
+ raise MaskError(code)
356
+ return tuple(segments)
357
+
358
+
359
+ def _overlap(left: _Path, right: _Path) -> bool:
360
+ return all(
361
+ a == b or (a is _WILDCARD and isinstance(b, int)) or (b is _WILDCARD and isinstance(a, int))
362
+ for a, b in zip(left, right)
363
+ )
364
+
365
+
366
+ def _is_scalar(value: JsonValue) -> bool:
367
+ return not isinstance(value, (list, dict))
368
+
369
+
370
+ def _scalar_key(value: JsonScalar) -> tuple[str, JsonScalar]:
371
+ if isinstance(value, bool):
372
+ return ("boolean", value)
373
+ if isinstance(value, (int, float)):
374
+ return ("number", value)
375
+ return ("null" if value is None else "string", value)
376
+
377
+
378
+ _Check: TypeAlias = "Callable[[MaskContext], bool]"
379
+
380
+
381
+ def _condition(value: JsonValue, limits: _Bounds, depth: int = 1) -> _Check:
382
+ code: MaskErrorCode = "INVALID_CONTEXT"
383
+ if depth > limits.maxConditionDepth:
384
+ raise MaskError("POLICY_LIMIT_EXCEEDED")
385
+ item = _record(value, code)
386
+ group_key = "all" if "all" in item else "any" if "any" in item else None
387
+ if group_key:
388
+ _keys(item, (group_key,), code)
389
+ group = item[group_key]
390
+ if not isinstance(group, list) or not group:
391
+ raise MaskError(code)
392
+ checks = [_condition(child, limits, depth + 1) for child in group]
393
+
394
+ def group_check(context: MaskContext) -> bool:
395
+ results = [check(context) for check in checks]
396
+ return all(results) if group_key == "all" else any(results)
397
+
398
+ return group_check
399
+ key, operator = item.get("field"), item.get("operator")
400
+ if not isinstance(key, str) or not _ID.fullmatch(key) or key in _FORBIDDEN:
401
+ raise MaskError(code)
402
+ if operator == "exists":
403
+ _keys(item, ("field", "operator"), code)
404
+ return lambda context: key in context
405
+ _keys(item, ("field", "operator", "value"), code)
406
+ if "value" not in item:
407
+ raise MaskError(code)
408
+ operand = item["value"]
409
+ if operator in ("equals", "notEquals"):
410
+ if not _is_scalar(operand):
411
+ raise MaskError(code)
412
+ choices = {_scalar_key(cast(JsonScalar, operand))}
413
+ elif operator in ("in", "notIn"):
414
+ if not isinstance(operand, list) or not operand or not all(_is_scalar(member) for member in operand):
415
+ raise MaskError(code)
416
+ choices = {_scalar_key(cast(JsonScalar, member)) for member in operand}
417
+ else:
418
+ raise MaskError(code)
419
+
420
+ def compare(context: MaskContext) -> bool:
421
+ if key not in context:
422
+ raise MaskError(code)
423
+ return (_scalar_key(context[key]) in choices) == (operator in ("equals", "in"))
424
+
425
+ return compare
426
+
427
+ _VISIBLE = {
428
+ "partial": (0, 4), "prefix": (0, 4), "suffix": (4, 0), "full": (0, 0),
429
+ "phone": (0, 4), "card": (0, 4), "name": (1, 0), "identifier": (0, 4), "account": (0, 4),
430
+ "aadhaar": (0, 4), "pan": (0, 2), "ssn": (0, 4), "sin": (0, 3), "passport": (0, 3), "iban": (0, 4),
431
+ }
432
+ _SPECIALIZED = frozenset({"email", "ip", "redact", "remove", "replace"})
433
+ _REDACTED = "[REDACTED]"
434
+
435
+
436
+ class _Removed:
437
+ __slots__ = ()
438
+
439
+
440
+ _REMOVED = _Removed()
441
+
442
+
443
+ def _builtin(name: str) -> bool:
444
+ return name in _VISIBLE or name in _SPECIALIZED
445
+
446
+
447
+ def _strategy_options(name: str, value: JsonValue, limits: _Bounds) -> MaskStrategyOptions:
448
+ code: MaskErrorCode = "INVALID_STRATEGY_OPTIONS"
449
+ opts = _record(value, code)
450
+ if name == "remove":
451
+ _keys(opts, (), code)
452
+ elif name in ("replace", "redact"):
453
+ _keys(opts, ("replacement",), code)
454
+ if name == "replace" and "replacement" not in opts:
455
+ raise MaskError(code)
456
+ if name == "redact" and "replacement" in opts and not isinstance(opts["replacement"], str):
457
+ raise MaskError(code)
458
+ else:
459
+ allowed = ["maskChar", "maskLength", "preserveLength", "invalidInput"]
460
+ if name not in ("full", "email", "ip", "prefix"):
461
+ allowed.append("visiblePrefix")
462
+ if name not in ("full", "email", "ip", "suffix"):
463
+ allowed.append("visibleSuffix")
464
+ _keys(opts, tuple(allowed), code)
465
+ for key in ("maskLength", "visiblePrefix", "visibleSuffix"):
466
+ if key in opts:
467
+ count = opts[key]
468
+ if type(count) is not int or not (int(key == "maskLength") <= count <= limits.maxStringLength):
469
+ raise MaskError(code)
470
+ if "maskChar" in opts and (not isinstance(opts["maskChar"], str) or len(opts["maskChar"]) != 1):
471
+ raise MaskError(code)
472
+ if "preserveLength" in opts and type(opts["preserveLength"]) is not bool:
473
+ raise MaskError(code)
474
+ if "maskLength" in opts and opts.get("preserveLength") is True:
475
+ raise MaskError(code)
476
+ if "invalidInput" in opts and opts["invalidInput"] not in ("redact", "error"):
477
+ raise MaskError(code)
478
+ return cast(MaskStrategyOptions, opts)
479
+
480
+
481
+ def _transform(name: str, value: JsonValue, opts: MaskStrategyOptions) -> JsonValue | _Removed:
482
+ if name == "remove":
483
+ return _REMOVED
484
+ if name == "replace":
485
+ return opts["replacement"]
486
+ if name == "redact":
487
+ return opts.get("replacement", _REDACTED)
488
+
489
+ def invalid() -> str:
490
+ if opts.get("invalidInput") == "error":
491
+ raise MaskError("INVALID_VALUE")
492
+ return _REDACTED
493
+
494
+ if not isinstance(value, str) or not value:
495
+ return invalid()
496
+
497
+ def mask(count: int) -> str:
498
+ return opts.get("maskChar", "*") * opts.get("maskLength", count if opts.get("preserveLength") else 3)
499
+
500
+ def protect(output: str) -> str:
501
+ return _REDACTED if output == value else output
502
+
503
+ if name == "email":
504
+ parts = value.split("@")
505
+ if len(parts) != 2 or not all(parts) or _CONTROL.search(value):
506
+ return invalid()
507
+ local, domain = parts
508
+ if len(local) < 2:
509
+ return _REDACTED
510
+ return protect(local[0] + mask(len(local) - 1) + "@" + domain)
511
+ if name == "ip":
512
+ if "%" in value:
513
+ return invalid()
514
+ try:
515
+ ipaddress.ip_address(value)
516
+ except ValueError:
517
+ return invalid()
518
+ return protect(mask(len(value)))
519
+ if name in ("card", "phone"):
520
+ digits = len(re.sub(r"[^0-9]", "", value))
521
+ if name == "card":
522
+ valid = re.search(r"[^0-9 -]", value) is None and 12 <= digits <= 19
523
+ else:
524
+ valid = (re.search(r"[^0-9 ()+-]", value) is None and 7 <= digits <= 15
525
+ and ("+" not in value or (value.startswith("+") and value.find("+", 1) == -1)))
526
+ if not valid:
527
+ return invalid()
528
+ prefix, suffix = _VISIBLE[name]
529
+ start, end = opts.get("visiblePrefix", prefix), opts.get("visibleSuffix", suffix)
530
+ if start + end >= len(value):
531
+ return _REDACTED
532
+ return protect(value[:start] + mask(len(value) - start - end) + value[len(value) - end:])
533
+
534
+
535
+ def _individual(name: str, value: object, options: MaskStrategyOptions | None) -> str:
536
+ config = {} if options is None else options
537
+ opts = _strategy_options(name, _copy(config, _Budget(_DEFAULTS), "INVALID_STRATEGY_OPTIONS"), _DEFAULTS)
538
+ text = value if type(value) is str else None
539
+ if name != "redact" and text is not None:
540
+ _Budget(_DEFAULTS).string(text, "INVALID_VALUE")
541
+ result = cast(str, _transform(name, text, opts))
542
+ _Budget(_DEFAULTS).string(result, "INVALID_VALUE")
543
+ return result
544
+
545
+
546
+ def mask_string(value: object, options: MaskStrategyOptions | None = None) -> str:
547
+ return _individual("partial", value, options)
548
+
549
+
550
+ def mask_email(value: object, options: MaskStrategyOptions | None = None) -> str:
551
+ return _individual("email", value, options)
552
+
553
+
554
+ def mask_phone(value: object, options: MaskStrategyOptions | None = None) -> str:
555
+ return _individual("phone", value, options)
556
+
557
+
558
+ def mask_card(value: object, options: MaskStrategyOptions | None = None) -> str:
559
+ return _individual("card", value, options)
560
+
561
+
562
+ def mask_name(value: object, options: MaskStrategyOptions | None = None) -> str:
563
+ return _individual("name", value, options)
564
+
565
+
566
+ def mask_identifier(value: object, options: MaskStrategyOptions | None = None) -> str:
567
+ return _individual("identifier", value, options)
568
+
569
+
570
+ def mask_account(value: object, options: MaskStrategyOptions | None = None) -> str:
571
+ return _individual("account", value, options)
572
+
573
+
574
+ def mask_ip(value: object, options: MaskStrategyOptions | None = None) -> str:
575
+ return _individual("ip", value, options)
576
+
577
+
578
+ def redact(value: object, options: MaskStrategyOptions | None = None) -> str:
579
+ return _individual("redact", value, options)
580
+
581
+
582
+ _Transform: TypeAlias = "Callable[[JsonValue, _Budget], JsonValue | _Removed]"
583
+
584
+
585
+ @dataclass(frozen=True, slots=True)
586
+ class _Rule:
587
+ index: int
588
+ id: str
589
+ path: _Path
590
+ name: str
591
+ priority: int
592
+ required: bool
593
+ check: _Check | None
594
+ apply: _Transform
595
+
596
+
597
+ @dataclass(frozen=True, slots=True)
598
+ class _Configuration:
599
+ limits: _Bounds
600
+ strict: bool
601
+ id: str | None
602
+ version: str | None
603
+ rules: tuple[_Rule, ...]
604
+ allowed: tuple[_Path, ...]
605
+
606
+
607
+ def _settings(
608
+ limits: Limits | None, strategies: dict[str, CustomStrategy] | None
609
+ ) -> tuple[_Bounds, dict[str, CustomStrategy]]:
610
+ code: MaskErrorCode = "INVALID_POLICY"
611
+ result: dict[str, int] = {}
612
+ if limits is not None:
613
+ if type(limits) is not dict:
614
+ raise MaskError(code)
615
+ defaults = _Bounds.__dataclass_fields__
616
+ caps = {"maxRules": 1024, "maxDepth": 128, "maxPathSegments": 64}
617
+ for name, maximum in limits.items():
618
+ if type(name) is not str or name not in defaults or type(maximum) is not int:
619
+ raise MaskError(code)
620
+ cap = caps.get(name, cast(int, getattr(_DEFAULTS, name)) * 4)
621
+ if not 1 <= maximum <= cap:
622
+ raise MaskError(code)
623
+ result[name] = maximum
624
+ custom: dict[str, CustomStrategy] = {}
625
+ if strategies is not None:
626
+ if type(strategies) is not dict:
627
+ raise MaskError(code)
628
+ for name, strategy in strategies.items():
629
+ if (type(name) is not str or not _ID.fullmatch(name) or name in _FORBIDDEN or _builtin(name)
630
+ or not callable(strategy) or inspect.iscoroutinefunction(strategy)
631
+ or inspect.isasyncgenfunction(strategy) or inspect.isgeneratorfunction(strategy)):
632
+ raise MaskError(code)
633
+ custom[name] = strategy
634
+ return _Bounds(**result), custom
635
+
636
+
637
+ def _rule(value: JsonValue, index: int, limits: _Bounds, custom: dict[str, CustomStrategy]) -> _Rule:
638
+ code: MaskErrorCode = "INVALID_RULE"
639
+ rule = _record(value, code)
640
+ _keys(rule, ("id", "path", "strategy", "description", "options", "priority", "required", "when"), code)
641
+ identifier, name = rule.get("id"), rule.get("strategy")
642
+ priority, required = rule.get("priority", 0), rule.get("required", False)
643
+ if (not isinstance(identifier, str) or not _ID.fullmatch(identifier)
644
+ or type(priority) is not int or type(required) is not bool
645
+ or ("description" in rule and not isinstance(rule["description"], str))):
646
+ raise MaskError(code)
647
+ path = _path(rule.get("path"), limits)
648
+ if not isinstance(name, str):
649
+ raise MaskError("UNKNOWN_STRATEGY")
650
+ options = rule.get("options", {})
651
+ apply: _Transform
652
+ if _builtin(name):
653
+ opts = _strategy_options(name, options, limits)
654
+ apply = lambda value, budget: _transform(name, value, opts)
655
+ else:
656
+ callback = custom.get(name)
657
+ if callback is None:
658
+ raise MaskError("UNKNOWN_STRATEGY")
659
+ custom_options = _record(options, "INVALID_STRATEGY_OPTIONS")
660
+
661
+ def invoke(value: JsonValue, budget: _Budget) -> JsonValue:
662
+ input_value = _copy(value, budget, "UNSUPPORTED_INPUT")
663
+ config = cast(Dict, _copy(custom_options, budget, "INVALID_STRATEGY_OPTIONS"))
664
+ try:
665
+ result: object = callback(input_value, config)
666
+ except Exception: # noqa: BLE001, S110 Deliberately discard the original exception and its payload.
667
+ pass
668
+ else:
669
+ if type(result) is CoroutineType:
670
+ result.close()
671
+ raise MaskError("INVALID_STRATEGY_RESULT")
672
+ return cast(JsonValue, result)
673
+ raise MaskError("CUSTOM_STRATEGY_FAILED")
674
+
675
+ apply = invoke
676
+ check = _condition(rule["when"], limits) if "when" in rule else None
677
+ return _Rule(index, identifier, path, name, priority, required, check, apply)
678
+
679
+
680
+ def _compile(
681
+ policy: object, limits: Limits | None, strategies: dict[str, CustomStrategy] | None
682
+ ) -> _Configuration:
683
+ bounds, custom = _settings(limits, strategies)
684
+ code: MaskErrorCode = "INVALID_POLICY"
685
+ config = _record(_copy(policy, _Budget(bounds), code), code)
686
+ _keys(config, ("schemaVersion", "id", "version", "defaultAction", "allowPaths", "rules"), code)
687
+ schema_version = config.get("schemaVersion")
688
+ if type(schema_version) is not int or schema_version != 1:
689
+ raise MaskError("UNSUPPORTED_SCHEMA_VERSION")
690
+ for key in ("id", "version"):
691
+ if key in config:
692
+ item = config[key]
693
+ if not isinstance(item, str) or not _ID.fullmatch(item):
694
+ raise MaskError(code)
695
+ default_action, rules, allow_paths = config.get("defaultAction", "preserve"), config.get("rules"), config.get(
696
+ "allowPaths", []
697
+ )
698
+ if default_action not in ("preserve", "remove") or not isinstance(rules, list) or not isinstance(allow_paths, list):
699
+ raise MaskError(code)
700
+ if "allowPaths" in config and default_action != "remove":
701
+ raise MaskError(code)
702
+ if len(rules) > bounds.maxRules or len(allow_paths) > bounds.maxRules:
703
+ raise MaskError("POLICY_LIMIT_EXCEEDED")
704
+ identifiers: set[str] = set()
705
+ compiled: list[_Rule] = []
706
+ for index, value in enumerate(rules):
707
+ try:
708
+ rule = _rule(value, index, bounds, custom)
709
+ if rule.id in identifiers:
710
+ raise MaskError("INVALID_RULE")
711
+ except MaskError as error:
712
+ raise MaskError(error.code, index) from None
713
+ identifiers.add(rule.id)
714
+ compiled.append(rule)
715
+ for index, left in enumerate(compiled):
716
+ for other_index, right in enumerate(compiled[:index]):
717
+ if _overlap(left.path, right.path) and (len(left.path) != len(right.path) or left.priority == right.priority):
718
+ raise MaskError("POLICY_CONFLICT", index, other_index)
719
+ allowed = tuple(_path(path, bounds) for path in allow_paths)
720
+ for rule in compiled:
721
+ if any(len(rule.path) < len(path) and _overlap(rule.path, path) for path in allowed):
722
+ raise MaskError("POLICY_CONFLICT", rule.index)
723
+ return _Configuration(
724
+ bounds, default_action == "remove", cast("str | None", config.get("id")),
725
+ cast("str | None", config.get("version")), tuple(compiled), allowed,
726
+ )
727
+
728
+ @dataclass(slots=True)
729
+ class _Plan:
730
+ allowed: bool = False
731
+ children: dict[str | int, _Plan] = field(default_factory=dict)
732
+ rule: _Rule | None = None
733
+
734
+
735
+ @dataclass(slots=True)
736
+ class _Counters:
737
+ work: int = 0
738
+ wildcards: int = 0
739
+
740
+
741
+ def _locate(
742
+ value: JsonValue, node: _Plan, path: _Path, at: int, limits: _Bounds, counters: _Counters,
743
+ match: Callable[[_Plan], None],
744
+ ) -> int:
745
+ counters.work += 1
746
+ if counters.work > limits.maxWork:
747
+ raise MaskError("WORK_LIMIT_EXCEEDED")
748
+ if at == len(path):
749
+ match(node)
750
+ return 1
751
+ step = path[at]
752
+
753
+ def descend(key: str | int, item: JsonValue) -> int:
754
+ child = node.children.get(key)
755
+ if child is None:
756
+ child = _Plan()
757
+ node.children[key] = child
758
+ return _locate(item, child, path, at + 1, limits, counters, match)
759
+
760
+ if isinstance(value, list):
761
+ if step is _WILDCARD:
762
+ counters.wildcards += len(value)
763
+ if counters.wildcards > limits.maxWildcardMatches:
764
+ raise MaskError("WILDCARD_LIMIT_EXCEEDED")
765
+ return sum(descend(index, item) for index, item in enumerate(value))
766
+ if isinstance(step, int) and step < len(value):
767
+ return descend(step, value[step])
768
+ elif isinstance(value, dict) and isinstance(step, str) and step in value:
769
+ return descend(step, value[step])
770
+ return 0
771
+
772
+
773
+ def _render(
774
+ value: JsonValue, node: _Plan | None, strict: bool, root: bool, budget: _Budget, report: MaskReport | None
775
+ ) -> JsonValue | _Removed:
776
+ allowed = node is not None and node.allowed
777
+ rule = node.rule if node is not None and not root and (allowed or not strict) else None
778
+ if rule is not None:
779
+ try:
780
+ result = rule.apply(value, budget)
781
+ if report is not None:
782
+ report["rules"][rule.index]["selected"] += 1
783
+ if result is _REMOVED:
784
+ if report is not None:
785
+ report["removedFields"] += 1
786
+ return _REMOVED
787
+ # Test the exact type without consulting attributes on an unsupported object.
788
+ if strict and (type(result) is list or type(result) is dict):
789
+ raise MaskError("INVALID_STRATEGY_RESULT")
790
+ output = _copy(result, budget, "INVALID_STRATEGY_RESULT")
791
+ if report is not None:
792
+ report["maskedFields"] += 1
793
+ return output
794
+ except MaskError as error:
795
+ raise MaskError(error.code, rule.index) from None
796
+ structural = node is not None and bool(node.children)
797
+ if strict and not root and not allowed and not structural:
798
+ return _REMOVED
799
+ if not strict and not structural:
800
+ return value
801
+ if not isinstance(value, (list, dict)):
802
+ return None if strict and root else value
803
+ container: Dict | list[JsonValue] = [] if isinstance(value, list) else {}
804
+ entries = enumerate(value) if isinstance(value, list) else value.items()
805
+ for key, item in entries:
806
+ child = node.children.get(key) if node is not None else None
807
+ member = _render(item, child, strict, False, budget, report)
808
+ if isinstance(member, _Removed):
809
+ explicit = child and child.rule and child.rule.name == "remove" and (not strict or child.allowed)
810
+ if report is not None and not explicit:
811
+ report["projectedFields"] += 1
812
+ elif isinstance(container, list):
813
+ container.append(member)
814
+ else:
815
+ container[cast(str, key)] = member
816
+ if strict and not root and not allowed and not container:
817
+ return _REMOVED
818
+ return container
819
+
820
+
821
+ def _allow(node: _Plan) -> None:
822
+ node.allowed = True
823
+
824
+
825
+ def _resolve(rule: _Rule, node: _Plan) -> None:
826
+ if node.rule is None or node.rule.priority < rule.priority:
827
+ node.rule = rule
828
+
829
+
830
+ def _run(config: _Configuration, data: JsonValue, context: MaskContext | None, report: MaskReport | None) -> JsonValue:
831
+ limits = config.limits
832
+ attributes = _record(_copy({} if context is None else context, _Budget(limits), "INVALID_CONTEXT"), "INVALID_CONTEXT")
833
+ if not all(_is_scalar(value) for value in attributes.values()):
834
+ raise MaskError("INVALID_CONTEXT")
835
+ value = _copy(data, _Budget(limits), "UNSUPPORTED_INPUT")
836
+ root, counters = _Plan(), _Counters()
837
+ for allowed in config.allowed:
838
+ _locate(value, root, allowed, 0, limits, counters, _allow)
839
+ for rule in config.rules:
840
+ try:
841
+ if rule.check and not rule.check(cast(MaskContext, attributes)):
842
+ if report is not None:
843
+ report["skippedRules"] += 1
844
+ continue
845
+ matched = _locate(
846
+ value, root, rule.path, 0, limits, counters, partial(_resolve, rule)
847
+ )
848
+ if not matched and rule.required:
849
+ raise MaskError("MISSING_REQUIRED_FIELD")
850
+ except MaskError as error:
851
+ raise MaskError(error.code, rule.index) from None
852
+ if report is not None:
853
+ report["rules"][rule.index]["matched"] = matched
854
+ report["rules"][rule.index]["status"] = "matched" if matched else "unmatched"
855
+ count_key: Literal["matchedRules", "unmatchedRules"] = "matchedRules" if matched else "unmatchedRules"
856
+ report[count_key] += 1
857
+ result = _render(value, root, config.strict, True, _Budget(limits), report)
858
+ return _copy(result, _Budget(limits), "INVALID_STRATEGY_RESULT")
859
+
860
+
861
+ @dataclass(frozen=True, slots=True)
862
+ class CompiledPolicy:
863
+ """Reusable policy snapshot. Build one with compile_policy or create_masker."""
864
+
865
+ _config: _Configuration = field(repr=False)
866
+
867
+ def apply(self, data: JsonValue, *, context: MaskContext | None = None) -> JsonValue:
868
+ return _run(self._config, data, context, None)
869
+
870
+ def apply_with_report(self, data: JsonValue, *, context: MaskContext | None = None) -> MaskResult:
871
+ config = self._config
872
+ report: MaskReport = {
873
+ "policyId": config.id, "policyVersion": config.version,
874
+ "defaultAction": "remove" if config.strict else "preserve",
875
+ "matchedRules": 0, "maskedFields": 0, "removedFields": 0, "projectedFields": 0,
876
+ "unmatchedRules": 0, "skippedRules": 0,
877
+ "rules": [
878
+ {"id": rule.id, "strategy": rule.name, "matched": 0, "selected": 0, "status": "skipped"}
879
+ for rule in config.rules
880
+ ],
881
+ }
882
+ return {"data": _run(config, data, context, report), "report": report}
883
+
884
+
885
+ def validate_policy(
886
+ policy: object, *, limits: Limits | None = None, strategies: dict[str, CustomStrategy] | None = None
887
+ ) -> PolicyValidation:
888
+ try:
889
+ _compile(policy, limits, strategies)
890
+ except MaskError as error:
891
+ detail: _ValidationError = {"code": error.code}
892
+ if error.rule_index is not None:
893
+ detail["ruleIndex"] = error.rule_index
894
+ if error.other_rule_index is not None:
895
+ detail["otherRuleIndex"] = error.other_rule_index
896
+ return {"valid": False, "errors": [detail]}
897
+ return {"valid": True, "errors": []}
898
+
899
+
900
+ def compile_policy(
901
+ policy: MaskPolicy, *, limits: Limits | None = None, strategies: dict[str, CustomStrategy] | None = None
902
+ ) -> CompiledPolicy:
903
+ return CompiledPolicy(_compile(policy, limits, strategies))
904
+
905
+
906
+ Masker = CompiledPolicy
907
+ create_masker = compile_policy
908
+
909
+
910
+ def mask_object(
911
+ data: JsonValue, policy: MaskPolicy, *, context: MaskContext | None = None,
912
+ limits: Limits | None = None, strategies: dict[str, CustomStrategy] | None = None,
913
+ ) -> JsonValue:
914
+ return compile_policy(policy, limits=limits, strategies=strategies).apply(data, context=context)
915
+
916
+
917
+ def explain_policy(
918
+ policy: MaskPolicy, synthetic_data: JsonValue, *, context: MaskContext | None = None,
919
+ limits: Limits | None = None, strategies: dict[str, CustomStrategy] | None = None,
920
+ ) -> MaskReport:
921
+ return compile_policy(policy, limits=limits, strategies=strategies).apply_with_report(
922
+ synthetic_data, context=context
923
+ )["report"]