json-structure 0.8.2__tar.gz → 0.8.3__tar.gz

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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: json-structure
3
- Version: 0.8.2
3
+ Version: 0.8.3
4
4
  Summary: Validators for JSON Structure schemas and instances
5
5
  Project-URL: Homepage, https://json-structure.org
6
6
  Project-URL: Documentation, https://github.com/json-structure/sdk
@@ -18,7 +18,7 @@ version_tuple: tuple[int | str, ...]
18
18
  commit_id: str | None
19
19
  __commit_id__: str | None
20
20
 
21
- __version__ = version = '0.8.2'
22
- __version_tuple__ = version_tuple = (0, 8, 2)
21
+ __version__ = version = '0.8.3'
22
+ __version_tuple__ = version_tuple = (0, 8, 3)
23
23
 
24
24
  __commit_id__ = commit_id = None
@@ -34,13 +34,19 @@ import json
34
34
  import re
35
35
  import copy
36
36
  import datetime
37
+ import base64
38
+ import binascii
39
+ import calendar
40
+ from fractions import Fraction
37
41
  import uuid
38
42
  from urllib.parse import urlparse
39
43
 
40
44
  # Regular expressions for date, datetime, time, duration and JSON pointer.
41
45
  _DATE_REGEX = re.compile(r'^\d{4}-\d{2}-\d{2}$')
42
46
  _DATETIME_REGEX = re.compile(
43
- r'^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+\-]\d{2}:\d{2})$'
47
+ r'([0-9]{4})-([0-9]{2})-([0-9]{2})[Tt]'
48
+ r'([0-9]{2}):([0-9]{2}):([0-9]{2})(?:\.[0-9]+)?'
49
+ r'([Zz]|[+\-][0-9]{2}:[0-9]{2})'
44
50
  )
45
51
  _TIME_REGEX = re.compile(r'^\d{2}:\d{2}:\d{2}(?:\.\d+)?$')
46
52
  # ISO 8601 duration pattern: P[n]Y[n]M[n]DT[n]H[n]M[n]S or P[n]W
@@ -50,6 +56,84 @@ _DURATION_REGEX = re.compile(
50
56
  _JSONPOINTER_REGEX = re.compile(r'^#(\/[^\/]+)*$')
51
57
 
52
58
 
59
+ def _is_rfc3339_datetime(value):
60
+ """Validate fields without converting or truncating the lexical timestamp.
61
+
62
+ Leap seconds must occupy UTC month-end 23:59; this does not maintain an
63
+ external IERS announcement table (which would also constrain future dates).
64
+ """
65
+ match = _DATETIME_REGEX.fullmatch(value)
66
+ if match is None:
67
+ return False
68
+ year, month, day, hour, minute, second = map(int, match.groups()[:6])
69
+ if not 1 <= month <= 12 or not 1 <= day <= calendar.monthrange(year, month)[1]:
70
+ return False
71
+ if hour > 23 or minute > 59 or second > 60:
72
+ return False
73
+ zone = match.group(7)
74
+ offset = 0
75
+ if zone not in ("Z", "z"):
76
+ offset_hour, offset_minute = int(zone[1:3]), int(zone[4:6])
77
+ if offset_hour > 23 or offset_minute > 59:
78
+ return False
79
+ offset = (offset_hour * 60 + offset_minute) * (1 if zone[0] == "+" else -1)
80
+ if second < 60:
81
+ return True
82
+ day_shift, utc_minute = divmod(hour * 60 + minute - offset, 24 * 60)
83
+ if utc_minute != 23 * 60 + 59:
84
+ return False
85
+ day += day_shift
86
+ if day < 1:
87
+ month -= 1
88
+ if month == 0:
89
+ year, month = year - 1, 12
90
+ day = calendar.monthrange(year, month)[1]
91
+ elif day > calendar.monthrange(year, month)[1]:
92
+ day, month = 1, month + 1
93
+ if month == 13:
94
+ year, month = year + 1, 1
95
+ return day == calendar.monthrange(year, month)[1]
96
+
97
+
98
+ def _is_encoded_binary(value, encoding):
99
+ """Check RFC 4648 text without altering, inspecting or transcoding its bytes."""
100
+ try:
101
+ if encoding in ("base64", "base64url"):
102
+ alphabet = r"[A-Za-z0-9+/]" if encoding == "base64" else r"[A-Za-z0-9_-]"
103
+ pattern = rf"(?:{alphabet}{{4}})*(?:{alphabet}{{2}}==|{alphabet}{{3}}=)?"
104
+ if re.fullmatch(pattern, value) is None:
105
+ return False
106
+ base64.b64decode(value, altchars=b"-_" if encoding == "base64url" else None, validate=True)
107
+ elif encoding == "base16":
108
+ base64.b16decode(value)
109
+ elif encoding == "base32":
110
+ base64.b32decode(value)
111
+ elif encoding == "base32hex":
112
+ # b32hexdecode was added in Python 3.10; keep the Python 3.8 floor.
113
+ if re.fullmatch(r"[0-9A-V]*={0,6}", value) is None:
114
+ return False
115
+ alphabet = str.maketrans("0123456789ABCDEFGHIJKLMNOPQRSTUV", "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567")
116
+ base64.b32decode(value.translate(alphabet))
117
+ else:
118
+ return False
119
+ except (binascii.Error, ValueError):
120
+ return False
121
+ return True
122
+
123
+
124
+ def _is_multiple_of(value, divisor):
125
+ """Use exact decimal-value arithmetic, not binary remainders or tolerances."""
126
+ if isinstance(value, bool) or isinstance(divisor, bool):
127
+ return False
128
+ try:
129
+ # Interpret decimal text (including str(float)); Fraction avoids both
130
+ # binary division artefacts and Decimal context precision/rounding.
131
+ step = Fraction(str(divisor))
132
+ return step > 0 and (Fraction(str(value)) / step).denominator == 1
133
+ except (ValueError, TypeError, ZeroDivisionError, OverflowError):
134
+ return False
135
+
136
+
53
137
  class JSONStructureInstanceValidator:
54
138
  """
55
139
  Validator for JSON document instances against full JSON Structure Core schemas.
@@ -246,7 +330,9 @@ class JSONStructureInstanceValidator:
246
330
  for t in schema_type:
247
331
  backup = list(self.errors)
248
332
  self.errors = []
249
- self.validate_instance(instance, {"type": t}, path)
333
+ branch_schema = dict(schema)
334
+ branch_schema["type"] = t
335
+ self.validate_instance(instance, branch_schema, path, meta)
250
336
  branch_errors = self.errors
251
337
  self.errors = backup
252
338
  if not branch_errors:
@@ -341,32 +427,32 @@ class JSONStructureInstanceValidator:
341
427
  if instance is not None:
342
428
  self.errors.append(f"Expected null at {path}, got {type(instance).__name__}")
343
429
  elif schema_type == "int8":
344
- if not isinstance(instance, int):
430
+ if isinstance(instance, bool) or not isinstance(instance, int):
345
431
  self.errors.append(f"Expected int8 at {path}, got {type(instance).__name__}")
346
432
  elif not (-2**7 <= instance <= 2**7 - 1):
347
433
  self.errors.append(f"int8 value at {path} out of range")
348
434
  elif schema_type == "uint8":
349
- if not isinstance(instance, int):
435
+ if isinstance(instance, bool) or not isinstance(instance, int):
350
436
  self.errors.append(f"Expected uint8 at {path}, got {type(instance).__name__}")
351
437
  elif not (0 <= instance <= 2**8 - 1):
352
438
  self.errors.append(f"uint8 value at {path} out of range")
353
439
  elif schema_type == "int16":
354
- if not isinstance(instance, int):
440
+ if isinstance(instance, bool) or not isinstance(instance, int):
355
441
  self.errors.append(f"Expected int16 at {path}, got {type(instance).__name__}")
356
442
  elif not (-2**15 <= instance <= 2**15 - 1):
357
443
  self.errors.append(f"int16 value at {path} out of range")
358
444
  elif schema_type == "uint16":
359
- if not isinstance(instance, int):
445
+ if isinstance(instance, bool) or not isinstance(instance, int):
360
446
  self.errors.append(f"Expected uint16 at {path}, got {type(instance).__name__}")
361
447
  elif not (0 <= instance <= 2**16 - 1):
362
448
  self.errors.append(f"uint16 value at {path} out of range")
363
449
  elif schema_type == "int32" or schema_type == "integer":
364
- if not isinstance(instance, int):
450
+ if isinstance(instance, bool) or not isinstance(instance, int):
365
451
  self.errors.append(f"Expected {schema_type} at {path}, got {type(instance).__name__}")
366
452
  elif not (-2**31 <= instance <= 2**31 - 1):
367
453
  self.errors.append(f"{schema_type} value at {path} out of range")
368
454
  elif schema_type == "uint32":
369
- if not isinstance(instance, int):
455
+ if isinstance(instance, bool) or not isinstance(instance, int):
370
456
  self.errors.append(f"Expected uint32 at {path}, got {type(instance).__name__}")
371
457
  elif not (0 <= instance <= 2**32 - 1):
372
458
  self.errors.append(f"uint32 value at {path} out of range")
@@ -411,10 +497,10 @@ class JSONStructureInstanceValidator:
411
497
  except ValueError:
412
498
  self.errors.append(f"Invalid uint128 format at {path}")
413
499
  elif schema_type == "float8":
414
- if not isinstance(instance, (int, float)):
500
+ if isinstance(instance, bool) or not isinstance(instance, (int, float)):
415
501
  self.errors.append(f"Expected float8 at {path}, got {type(instance).__name__}")
416
502
  elif schema_type in ("float", "double"):
417
- if not isinstance(instance, (int, float)):
503
+ if isinstance(instance, bool) or not isinstance(instance, (int, float)):
418
504
  self.errors.append(f"Expected {schema_type} at {path}, got {type(instance).__name__}")
419
505
  elif schema_type == "decimal":
420
506
  if not isinstance(instance, str):
@@ -428,7 +514,7 @@ class JSONStructureInstanceValidator:
428
514
  if not isinstance(instance, str) or not _DATE_REGEX.match(instance):
429
515
  self.errors.append(f"Expected date (YYYY-MM-DD) at {path}")
430
516
  elif schema_type == "datetime":
431
- if not isinstance(instance, str) or not _DATETIME_REGEX.match(instance):
517
+ if not isinstance(instance, str) or not _is_rfc3339_datetime(instance):
432
518
  self.errors.append(f"Expected datetime (RFC3339) at {path}")
433
519
  elif schema_type == "time":
434
520
  if not isinstance(instance, str) or not _TIME_REGEX.match(instance):
@@ -456,6 +542,8 @@ class JSONStructureInstanceValidator:
456
542
  elif schema_type == "binary":
457
543
  if not isinstance(instance, str):
458
544
  self.errors.append(f"Expected binary (base64 string) at {path}")
545
+ elif not _is_encoded_binary(instance, schema.get("contentEncoding", "base64")):
546
+ self.errors.append(f"Invalid binary encoding at {path}")
459
547
  elif schema_type == "jsonpointer":
460
548
  if not isinstance(instance, str) or not _JSONPOINTER_REGEX.match(instance):
461
549
  self.errors.append(f"Expected JSON pointer format at {path}")
@@ -701,7 +789,7 @@ class JSONStructureInstanceValidator:
701
789
  errors.append(f"String shorter than minLength {schema['minLength']}")
702
790
  if "pattern" in schema and isinstance(instance, str):
703
791
  import re
704
- if not re.match(schema["pattern"], instance):
792
+ if not re.fullmatch(schema["pattern"], instance):
705
793
  errors.append(f"String does not match pattern {schema['pattern']}")
706
794
  if t in ("number", "integer", "float", "double", "float8", "decimal",
707
795
  "int8", "uint8", "int16", "uint16", "int32", "uint32",
@@ -710,7 +798,7 @@ class JSONStructureInstanceValidator:
710
798
  errors.append(f"Number less than minimum {schema['minimum']}")
711
799
  if "maximum" in schema and instance > schema["maximum"]:
712
800
  errors.append(f"Number greater than maximum {schema['maximum']}")
713
- if "multipleOf" in schema and instance % schema["multipleOf"] != 0:
801
+ if "multipleOf" in schema and not _is_multiple_of(instance, schema["multipleOf"]):
714
802
  errors.append(f"Number not a multiple of {schema['multipleOf']}")
715
803
  if t == "array":
716
804
  if "minItems" in schema and len(instance) < schema["minItems"]:
@@ -877,16 +965,8 @@ class JSONStructureInstanceValidator:
877
965
  f"Value at {path} is not less than exclusive maximum {excl_max}")
878
966
  except Exception:
879
967
  self.errors.append(f"Cannot evaluate exclusiveMaximum constraint at {path}")
880
- if "multipleOf" in schema:
881
- try:
882
- # Handle floating point precision issues
883
- multiple_of = schema["multipleOf"]
884
- quotient = instance / multiple_of
885
- # Check if the quotient is close to an integer within a small tolerance
886
- if abs(quotient - round(quotient)) > 1e-10:
887
- self.errors.append(f"Value at {path} is not a multiple of {schema['multipleOf']}")
888
- except Exception:
889
- self.errors.append(f"Cannot evaluate multipleOf constraint at {path}")
968
+ if "multipleOf" in schema and not _is_multiple_of(instance, schema["multipleOf"]):
969
+ self.errors.append(f"Value at {path} is not a multiple of {schema['multipleOf']}")
890
970
 
891
971
  # String constraints.
892
972
  if schema.get("type") == "string":
@@ -905,7 +985,7 @@ class JSONStructureInstanceValidator:
905
985
  if "pattern" in schema:
906
986
  try:
907
987
  pattern = re.compile(schema["pattern"])
908
- if not pattern.search(instance):
988
+ if not pattern.fullmatch(instance):
909
989
  self.errors.append(f"String at {path} does not match pattern {schema['pattern']}")
910
990
  except (re.error, TypeError):
911
991
  self.errors.append(f"Invalid pattern constraint at {path}")
@@ -61,6 +61,11 @@ class JSONStructureSchemaCoreValidator:
61
61
  COMPOSITION_KEYWORDS = {"allOf", "anyOf", "oneOf", "not", "if", "then", "else"}
62
62
 
63
63
  # Extended keywords for validation
64
+ NUMERIC_TYPES = {
65
+ "number", "integer", "float8", "float", "double", "decimal",
66
+ "int8", "uint8", "int16", "uint16", "int32", "uint32",
67
+ "int64", "uint64", "int128", "uint128",
68
+ }
64
69
  NUMERIC_VALIDATION_KEYWORDS = {"minimum", "maximum", "exclusiveMinimum", "exclusiveMaximum", "multipleOf"}
65
70
  STRING_VALIDATION_KEYWORDS = {"minLength", "maxLength", "pattern", "format", "contentEncoding", "contentMediaType"}
66
71
  ARRAY_VALIDATION_KEYWORDS = {"minItems", "maxItems", "uniqueItems", "contains", "minContains", "maxContains"}
@@ -789,6 +794,16 @@ class JSONStructureSchemaCoreValidator:
789
794
  if not validation_enabled:
790
795
  self._add_extension_keyword_warning("default", path)
791
796
 
797
+ @classmethod
798
+ def _is_numeric_schema_type(cls, type_name):
799
+ """Units apply to numeric values, including explicit-null numeric unions."""
800
+ members = type_name if isinstance(type_name, list) else [type_name]
801
+ numeric_members = [member for member in members if member != "null"]
802
+ return bool(numeric_members) and all(
803
+ isinstance(member, str) and member in cls.NUMERIC_TYPES
804
+ for member in numeric_members
805
+ )
806
+
792
807
  def _check_ucum_unit_keyword(self, obj, path):
793
808
  """
794
809
  Check the ucumUnit keyword from the JSONStructureUnits extension.
@@ -803,22 +818,14 @@ class JSONStructureSchemaCoreValidator:
803
818
  if not isinstance(ucum_unit, str):
804
819
  self._err("'ucumUnit' must be a string.", f"{path}/ucumUnit", ErrorCodes.SCHEMA_KEYWORD_INVALID_TYPE)
805
820
 
806
- numeric_types = {
807
- "number", "integer", "float", "double", "decimal",
808
- "int32", "uint32", "int64", "uint64", "int128", "uint128"
809
- }
810
821
  type_name = obj.get("type")
811
- if not isinstance(type_name, str) or type_name not in numeric_types:
822
+ if not self._is_numeric_schema_type(type_name):
812
823
  self._err("'ucumUnit' can only appear in numeric schemas.", f"{path}/ucumUnit", ErrorCodes.SCHEMA_CONSTRAINT_TYPE_MISMATCH)
813
824
 
814
825
  def _check_units_keywords(self, obj, path):
815
826
  """
816
827
  Check the unit, currency, and symbols keywords from the JSONStructureUnits extension.
817
828
  """
818
- numeric_types = {
819
- "number", "integer", "float", "double", "decimal",
820
- "int32", "uint32", "int64", "uint64", "int128", "uint128"
821
- }
822
829
  units_enabled = "JSONStructureUnits" in self.enabled_extensions
823
830
 
824
831
  for keyword in ("unit", "currency", "symbols"):
@@ -838,7 +845,7 @@ class JSONStructureSchemaCoreValidator:
838
845
  self._err("'unit' must be a string.", f"{path}/unit", ErrorCodes.SCHEMA_KEYWORD_INVALID_TYPE)
839
846
 
840
847
  type_name = obj.get("type")
841
- if not isinstance(type_name, str) or type_name not in numeric_types:
848
+ if not self._is_numeric_schema_type(type_name):
842
849
  self._err("'unit' can only appear in numeric schemas.", f"{path}/unit", ErrorCodes.SCHEMA_CONSTRAINT_TYPE_MISMATCH)
843
850
 
844
851
  def _check_relations_keywords(self, obj, path):
File without changes