-
Notifications
You must be signed in to change notification settings - Fork 511
/
valid.py
971 lines (671 loc) · 25.9 KB
/
valid.py
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
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
"""Validators for schema fields."""
import json
import re
from base58 import alphabet
from marshmallow.exceptions import ValidationError
from marshmallow.fields import Field
from marshmallow.validate import OneOf, Range, Regexp, Validator
from ..ledger.endpoint_type import EndpointType as EndpointTypeEnum
from ..revocation.models.revocation_registry import RevocationRegistry
from ..wallet.did_posture import DIDPosture as DIDPostureEnum
from .util import epoch_to_str
B58 = alphabet if isinstance(alphabet, str) else alphabet.decode("ascii")
EXAMPLE_TIMESTAMP = 1640995199 # 2021-12-31 23:59:59Z
class StrOrDictField(Field):
"""URI or Dict field for Marshmallow."""
def _deserialize(self, value, attr, data, **kwargs):
if not isinstance(value, (str, dict)):
raise ValidationError("Field should be str or dict")
return super()._deserialize(value, attr, data, **kwargs)
class StrOrNumberField(Field):
"""String or Number field for Marshmallow."""
def _deserialize(self, value, attr, data, **kwargs):
if not isinstance(value, (str, float, int)):
raise ValidationError("Field should be str or int or float")
return super()._deserialize(value, attr, data, **kwargs)
class DictOrDictListField(Field):
"""Dict or Dict List field for Marshmallow."""
def _deserialize(self, value, attr, data, **kwargs):
if not isinstance(value, dict):
if not isinstance(value, list) or not all(
isinstance(item, dict) for item in value
):
raise ValidationError("Field should be dict or list of dicts")
return super()._deserialize(value, attr, data, **kwargs)
class UriOrDictField(StrOrDictField):
"""URI or Dict field for Marshmallow."""
def _deserialize(self, value, attr, data, **kwargs):
if isinstance(value, str):
# Check regex
Uri()(value)
return super()._deserialize(value, attr, data, **kwargs)
class IntEpoch(Range):
"""Validate value against (integer) epoch format."""
EXAMPLE = EXAMPLE_TIMESTAMP
def __init__(self):
"""Initialize the instance."""
super().__init__( # use u64 for indy-sdk compatibility
min=0,
max=18446744073709551615,
error="Value {input} is not a valid integer epoch time",
)
class WholeNumber(Range):
"""Validate value as non-negative integer."""
EXAMPLE = 0
def __init__(self):
"""Initialize the instance."""
super().__init__(min=0, error="Value {input} is not a non-negative integer")
def __call__(self, value):
"""Validate input value."""
if not isinstance(value, int):
raise ValidationError("Value {input} is not a valid whole number")
super().__call__(value)
class NumericStrWhole(Regexp):
"""Validate value against whole number numeric string."""
EXAMPLE = "0"
PATTERN = r"^[0-9]*$"
def __init__(self):
"""Initialize the instance."""
super().__init__(
NumericStrWhole.PATTERN,
error="Value {input} is not a non-negative numeric string",
)
class NumericStrAny(Regexp):
"""Validate value against any number numeric string."""
EXAMPLE = "-1"
PATTERN = r"^-?[0-9]*$"
def __init__(self):
"""Initialize the instance."""
super().__init__(
NumericStrAny.PATTERN,
error="Value {input} is not a numeric string",
)
class NaturalNumber(Range):
"""Validate value as positive integer."""
EXAMPLE = 10
def __init__(self):
"""Initialize the instance."""
super().__init__(min=1, error="Value {input} is not a positive integer")
def __call__(self, value):
"""Validate input value."""
if not isinstance(value, int):
raise ValidationError("Value {input} is not a valid natural number")
super().__call__(value)
class NumericStrNatural(Regexp):
"""Validate value against natural number numeric string."""
EXAMPLE = "1"
PATTERN = r"^[1-9][0-9]*$"
def __init__(self):
"""Initialize the instance."""
super().__init__(
NumericStrNatural.PATTERN,
error="Value {input} is not a positive numeric string",
)
class IndyRevRegSize(Range):
"""Validate value as indy revocation registry size."""
EXAMPLE = 1000
def __init__(self):
"""Initialize the instance."""
super().__init__(
min=RevocationRegistry.MIN_SIZE,
max=RevocationRegistry.MAX_SIZE,
error=(
"Value {input} must be an integer between "
f"{RevocationRegistry.MIN_SIZE} and "
f"{RevocationRegistry.MAX_SIZE} inclusively"
),
)
def __call__(self, value):
"""Validate input value."""
if not isinstance(value, int):
raise ValidationError(
"Value {input} must be an integer between "
f"{RevocationRegistry.MIN_SIZE} and "
f"{RevocationRegistry.MAX_SIZE} inclusively"
)
super().__call__(value)
class JWSHeaderKid(Regexp):
"""Validate value against JWS header kid."""
EXAMPLE = "did:sov:LjgpST2rjsoxYegQDRm7EL#keys-4"
PATTERN = rf"^did:(?:key:z[{B58}]+|sov:[{B58}]{{21,22}}(;.*)?(\?.*)?#.+)$"
def __init__(self):
"""Initialize the instance."""
super().__init__(
JWSHeaderKid.PATTERN,
error="Value {input} is neither in W3C did:key nor DID URL format",
)
class NonSDList(Regexp):
"""Validate NonSD List."""
EXAMPLE = [
"name",
"address",
"address.street_address",
"nationalities[1:3]",
]
PATTERN = r"[a-z0-9:\[\]_\.@?\(\)]"
def __init__(self):
"""Initialize the instance."""
super().__init__(
NonSDList.PATTERN,
error="Value {input} is not a valid NonSDList",
)
class JSONWebToken(Regexp):
"""Validate JSON Web Token."""
EXAMPLE = (
"eyJhbGciOiJFZERTQSJ9."
"eyJhIjogIjAifQ."
"dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk"
)
PATTERN = r"^[a-zA-Z0-9_-]+\.[a-zA-Z0-9_-]*\.[a-zA-Z0-9_-]+$"
def __init__(self):
"""Initialize the instance."""
super().__init__(
JSONWebToken.PATTERN,
error="Value {input} is not a valid JSON Web token",
)
class SDJSONWebToken(Regexp):
"""Validate SD-JSON Web Token."""
EXAMPLE = (
"eyJhbGciOiJFZERTQSJ9."
"eyJhIjogIjAifQ."
"dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk"
"~WyJEM3BUSFdCYWNRcFdpREc2TWZKLUZnIiwgIkRFIl0"
"~WyJPMTFySVRjRTdHcXExYW9oRkd0aDh3IiwgIlNBIl0"
"~WyJkVmEzX1JlTGNsWTU0R1FHZm5oWlRnIiwgInVwZGF0ZWRfYXQiLCAxNTcwMDAwMDAwXQ"
)
PATTERN = r"^[a-zA-Z0-9_-]+\.[a-zA-Z0-9_-]*\.[a-zA-Z0-9_-]+(?:~[a-zA-Z0-9._-]+)*~?$"
def __init__(self):
"""Initialize the instance."""
super().__init__(
SDJSONWebToken.PATTERN,
error="Value {input} is not a valid SD-JSON Web token",
)
class DIDKey(Regexp):
"""Validate value against DID key specification."""
EXAMPLE = "did:key:z6MkpTHR8VNsBxYAAWHut2Geadd9jSwuBV8xRoAnwWsdvktH"
PATTERN = re.compile(rf"^did:key:z[{B58}]+$")
def __init__(self):
"""Initialize the instance."""
super().__init__(
DIDKey.PATTERN, error="Value {input} is not in W3C did:key format"
)
class DIDKeyOrRef(Regexp):
"""Validate value against DID key specification."""
EXAMPLE = "did:key:z6MkpTHR8VNsBxYAAWHut2Geadd9jSwuBV8xRoAnwWsdvktH"
PATTERN = re.compile(rf"^did:key:z[{B58}]+(?:#z[{B58}]+)?$")
def __init__(self):
"""Initialize the instance."""
super().__init__(
DIDKeyOrRef.PATTERN, error="Value {input} is not a did:key or did:key ref"
)
class DIDKeyRef(Regexp):
"""Validate value as DID key reference."""
EXAMPLE = (
"did:key:z6MkpTHR8VNsBxYAAWHut2Geadd9jSwuBV8xRoAnwWsdvktH"
"#z6MkpTHR8VNsBxYAAWHut2Geadd9jSwuBV8xRoAnwWsdvktH"
)
PATTERN = re.compile(rf"^did:key:z[{B58}]+#z[{B58}]+$")
def __init__(self):
"""Initialize the instance."""
super().__init__(
DIDKeyRef.PATTERN, error="Value {input} is not a did:key reference"
)
class DIDWeb(Regexp):
"""Validate value against did:web specification."""
EXAMPLE = "did:web:example.com"
PATTERN = re.compile(r"^(did:web:)([a-zA-Z0-9%._-]*:)*[a-zA-Z0-9%._-]+$")
def __init__(self):
"""Initialize the instance."""
super().__init__(
DIDWeb.PATTERN, error="Value {input} is not in W3C did:web format"
)
class DIDPosture(OneOf):
"""Validate value against defined DID postures."""
EXAMPLE = DIDPostureEnum.WALLET_ONLY.moniker
def __init__(self):
"""Initialize the instance."""
super().__init__(
choices=[did_posture.moniker for did_posture in DIDPostureEnum],
error="Value {input} must be one of {choices}",
)
class IndyDID(Regexp):
"""Validate value against indy DID."""
EXAMPLE = "WgWxqztrNooG92RXvxSTWv"
PATTERN = re.compile(rf"^(did:sov:)?[{B58}]{{21,22}}$")
def __init__(self):
"""Initialize the instance."""
super().__init__(
IndyDID.PATTERN,
error="Value {input} is not an indy decentralized identifier (DID)",
)
class DIDValidation(Regexp):
"""Validate value against any valid DID spec."""
METHOD = r"([a-zA-Z0-9_]+)"
METHOD_ID = r"([a-zA-Z0-9_.%-]+(:[a-zA-Z0-9_.%-]+)*)"
PARAMS = r"((;[a-zA-Z0-9_.:%-]+=[a-zA-Z0-9_.:%-]*)*)"
PATH = r"(\/[^#?]*)?"
QUERY = r"([?][^#]*)?"
FRAGMENT = r"(\#.*)?$"
EXAMPLE = "did:peer:WgWxqztrNooG92RXvxSTWv"
PATTERN = re.compile(rf"^did:{METHOD}:{METHOD_ID}{PARAMS}{PATH}{QUERY}{FRAGMENT}$")
def __init__(self):
"""Initialize the instance."""
super().__init__(
DIDValidation.PATTERN,
error="Value {input} is not a valid DID",
)
# temporary support for short Indy DIDs in place of qualified DIDs
class MaybeIndyDID(Regexp):
"""Validate value against any valid DID spec or a short Indy DID."""
EXAMPLE = DIDValidation.EXAMPLE
PATTERN = re.compile(IndyDID.PATTERN.pattern + "|" + DIDValidation.PATTERN.pattern)
def __init__(self):
"""Initialize the instance."""
super().__init__(
MaybeIndyDID.PATTERN,
error="Value {input} is not a valid DID",
)
class IndyRawPublicKey(Regexp):
"""Validate value against indy (Ed25519VerificationKey2018) raw public key."""
EXAMPLE = "H3C2AVvLMv6gmMNam3uVAjZpfkcJCwDwnZn6z3wXmqPV"
PATTERN = rf"^[{B58}]{{43,44}}$"
def __init__(self):
"""Initialize the instance."""
super().__init__(
IndyRawPublicKey.PATTERN,
error="Value {input} is not a raw Ed25519VerificationKey2018 key",
)
class RoutingKey(Regexp):
"""Validate between indy or did key.
Validate value against indy (Ed25519VerificationKey2018)
raw public key or DID key specification.
"""
EXAMPLE = DIDKey.EXAMPLE
PATTERN = re.compile(DIDKey.PATTERN.pattern + "|" + IndyRawPublicKey.PATTERN)
def __init__(self):
"""Initialize the instance."""
super().__init__(
RoutingKey.PATTERN,
error=(
"Value {input} is not in W3C did:key"
" or Ed25519VerificationKey2018 key format"
),
)
class IndyCredDefId(Regexp):
"""Validate value against indy credential definition identifier specification."""
EXAMPLE = "WgWxqztrNooG92RXvxSTWv:3:CL:20:tag"
PATTERN = (
rf"^([{B58}]{{21,22}})" # issuer DID
f":3" # cred def id marker
f":CL" # sig alg
rf":(([1-9][0-9]*)|([{B58}]{{21,22}}:2:.+:[0-9.]+))" # schema txn / id
f":(.+)?$" # tag
)
def __init__(self):
"""Initialize the instance."""
super().__init__(
IndyCredDefId.PATTERN,
error="Value {input} is not an indy credential definition identifier",
)
class IndyVersion(Regexp):
"""Validate value against indy version specification."""
EXAMPLE = "1.0"
PATTERN = r"^[0-9.]+$"
def __init__(self):
"""Initialize the instance."""
super().__init__(
IndyVersion.PATTERN,
error="Value {input} is not an indy version (use only digits and '.')",
)
class IndySchemaId(Regexp):
"""Validate value against indy schema identifier specification."""
EXAMPLE = "WgWxqztrNooG92RXvxSTWv:2:schema_name:1.0"
PATTERN = rf"^[{B58}]{{21,22}}:2:.+:[0-9.]+$"
def __init__(self):
"""Initialize the instance."""
super().__init__(
IndySchemaId.PATTERN,
error="Value {input} is not an indy schema identifier",
)
class IndyRevRegId(Regexp):
"""Validate value against indy revocation registry identifier specification."""
EXAMPLE = "WgWxqztrNooG92RXvxSTWv:4:WgWxqztrNooG92RXvxSTWv:3:CL:20:tag:CL_ACCUM:0"
PATTERN = (
rf"^([{B58}]{{21,22}}):4:"
rf"([{B58}]{{21,22}}):3:"
rf"CL:(([1-9][0-9]*)|([{B58}]{{21,22}}:2:.+:[0-9.]+))(:.+)?:"
rf"CL_ACCUM:(.+$)"
)
def __init__(self):
"""Initialize the instance."""
super().__init__(
IndyRevRegId.PATTERN,
error="Value {input} is not an indy revocation registry identifier",
)
class IndyCredRevId(Regexp):
"""Validate value against indy credential revocation identifier specification."""
EXAMPLE = "12345"
PATTERN = r"^[1-9][0-9]*$"
def __init__(self):
"""Initialize the instance."""
super().__init__(
IndyCredRevId.PATTERN,
error="Value {input} is not an indy credential revocation identifier",
)
class IndyPredicate(OneOf):
"""Validate value against indy predicate."""
EXAMPLE = ">="
def __init__(self):
"""Initialize the instance."""
super().__init__(
choices=["<", "<=", ">=", ">"],
error="Value {input} must be one of {choices}",
)
class IndyISO8601DateTime(Regexp):
"""Validate value against ISO 8601 datetime format, indy profile."""
EXAMPLE = epoch_to_str(EXAMPLE_TIMESTAMP)
PATTERN = (
r"^\d{4}-\d\d-\d\d[T ]\d\d:\d\d"
r"(?:\:(?:\d\d(?:\.\d{1,6})?))?(?:[+-]\d\d:?\d\d|Z|)$"
)
def __init__(self):
"""Initialize the instance."""
super().__init__(
IndyISO8601DateTime.PATTERN,
error="Value {input} is not a date in valid format",
)
class RFC3339DateTime(Regexp):
"""Validate value against RFC3339 datetime format."""
EXAMPLE = "2010-01-01T19:23:24Z"
PATTERN = (
r"^([0-9]{4})-([0-9]{2})-([0-9]{2})([Tt ]([0-9]{2}):([0-9]{2}):"
r"([0-9]{2})(\.[0-9]+)?)?(([Zz]|([+-])([0-9]{2}):([0-9]{2})))?$"
)
def __init__(self):
"""Initialize the instance."""
super().__init__(
RFC3339DateTime.PATTERN,
error="Value {input} is not a date in valid format",
)
class IndyWQL(Regexp): # using Regexp brings in nice visual validator cue
"""Validate value as potential WQL query."""
EXAMPLE = json.dumps({"attr::name::value": "Alex"})
PATTERN = r"^{.*}$"
def __init__(self):
"""Initialize the instance."""
super().__init__(
IndyWQL.PATTERN,
error="Value {input} is not a valid WQL query",
)
def __call__(self, value):
"""Validate input value."""
super().__call__(value or "")
message = f"Value {value} is not a valid WQL query"
try:
json.loads(value)
except (json.JSONDecodeError, TypeError):
raise ValidationError(message)
return value
class IndyExtraWQL(Regexp): # using Regexp brings in nice visual validator cue
"""Validate value as potential extra WQL query in cred search for proof req."""
EXAMPLE = json.dumps({"0_drink_uuid": {"attr::drink::value": "martini"}})
PATTERN = r'^{\s*".*?"\s*:\s*{.*?}\s*(,\s*".*?"\s*:\s*{.*?}\s*)*\s*}$'
def __init__(self):
"""Initialize the instance."""
super().__init__(
IndyExtraWQL.PATTERN,
error="Value {input} is not a valid extra WQL query",
)
def __call__(self, value):
"""Validate input value."""
super().__call__(value or "")
message = f"Value {value} is not a valid extra WQL query"
try:
json.loads(value)
except (json.JSONDecodeError, TypeError):
raise ValidationError(message)
return value
class Base64(Regexp):
"""Validate base64 value."""
EXAMPLE = "ey4uLn0="
PATTERN = r"^[a-zA-Z0-9+/]*={0,2}$"
def __init__(self):
"""Initialize the instance."""
super().__init__(
Base64.PATTERN,
error="Value {input} is not a valid base64 encoding",
)
class Base64URL(Regexp):
"""Validate base64 value."""
EXAMPLE = "ey4uLn0="
PATTERN = r"^[-_a-zA-Z0-9]*={0,2}$"
def __init__(self):
"""Initialize the instance."""
super().__init__(
Base64URL.PATTERN,
error="Value {input} is not a valid base64url encoding",
)
class Base64URLNoPad(Regexp):
"""Validate base64 value."""
EXAMPLE = "ey4uLn0"
PATTERN = r"^[-_a-zA-Z0-9]*$"
def __init__(self):
"""Initialize the instance."""
super().__init__(
Base64URLNoPad.PATTERN,
error="Value {input} is not a valid unpadded base64url encoding",
)
class SHA256Hash(Regexp):
"""Validate (binhex-encoded) SHA256 value."""
EXAMPLE = "617a48c7c8afe0521efdc03e5bb0ad9e655893e6b4b51f0e794d70fba132aacb"
PATTERN = r"^[a-fA-F0-9+/]{64}$"
def __init__(self):
"""Initialize the instance."""
super().__init__(
SHA256Hash.PATTERN,
error="Value {input} is not a valid (binhex-encoded) SHA-256 hash",
)
class Base58SHA256Hash(Regexp):
"""Validate value against base58 encoding of SHA-256 hash."""
EXAMPLE = "H3C2AVvLMv6gmMNam3uVAjZpfkcJCwDwnZn6z3wXmqPV"
PATTERN = rf"^[{B58}]{{43,44}}$"
def __init__(self):
"""Initialize the instance."""
super().__init__(
Base58SHA256Hash.PATTERN,
error="Value {input} is not a base58 encoding of a SHA-256 hash",
)
class UUIDFour(Regexp):
"""Validate UUID4: 8-4-4-4-12 hex digits, the 13th of which being 4."""
EXAMPLE = "3fa85f64-5717-4562-b3fc-2c963f66afa6"
PATTERN = (
r"[a-fA-F0-9]{8}-"
r"[a-fA-F0-9]{4}-"
r"4[a-fA-F0-9]{3}-"
r"[a-fA-F0-9]{4}-"
r"[a-fA-F0-9]{12}"
)
def __init__(self):
"""Initialize the instance."""
super().__init__(
UUIDFour.PATTERN,
error="Value {input} is not UUID4 (8-4-4-4-12 hex digits with digit#13=4)",
)
class Uri(Regexp):
"""Validate value against URI on any scheme."""
EXAMPLE = "https://www.w3.org/2018/credentials/v1"
PATTERN = r"\w+:(\/?\/?)[^\s]+"
def __init__(self):
"""Initialize the instance."""
super().__init__(Uri.PATTERN, error="Value {input} is not URI")
class Endpoint(Regexp): # using Regexp brings in nice visual validator cue
"""Validate value against endpoint URL on any scheme."""
EXAMPLE = "https://myhost:8021"
PATTERN = (
r"^[A-Za-z0-9\.\-\+]+:" # scheme
r"//([A-Za-z0-9][.A-Za-z0-9-_]+[A-Za-z0-9])+" # host
r"(:[1-9][0-9]*)?" # port
r"(/[^?&#]+)?$" # path
)
def __init__(self):
"""Initialize the instance."""
super().__init__(
Endpoint.PATTERN,
error="Value {input} is not a valid endpoint",
)
class EndpointType(OneOf):
"""Validate value against allowed endpoint/service types."""
EXAMPLE = EndpointTypeEnum.ENDPOINT.w3c
def __init__(self):
"""Initialize the instance."""
super().__init__(
choices=[e.w3c for e in EndpointTypeEnum],
error="Value {input} must be one of {choices}",
)
class CredentialType(Validator):
"""Credential Type."""
CREDENTIAL_TYPE = "VerifiableCredential"
EXAMPLE = [CREDENTIAL_TYPE, "AlumniCredential"]
def __init__(self) -> None:
"""Initialize the instance."""
super().__init__()
def __call__(self, value):
"""Validate input value."""
length = len(value)
if length < 1 or CredentialType.CREDENTIAL_TYPE not in value:
raise ValidationError(f"type must include {CredentialType.CREDENTIAL_TYPE}")
return value
class CredentialContext(Validator):
"""Credential Context."""
FIRST_CONTEXT = "https://www.w3.org/2018/credentials/v1"
EXAMPLE = [FIRST_CONTEXT, "https://www.w3.org/2018/credentials/examples/v1"]
def __init__(self) -> None:
"""Initialize the instance."""
super().__init__()
def __call__(self, value):
"""Validate input value."""
length = len(value)
if length < 1 or value[0] != CredentialContext.FIRST_CONTEXT:
raise ValidationError(
f"First context must be {CredentialContext.FIRST_CONTEXT}"
)
return value
class CredentialSubject(Validator):
"""Credential subject."""
EXAMPLE = {
"id": "did:example:ebfeb1f712ebc6f1c276e12ec21",
"alumniOf": {"id": "did:example:c276e12ec21ebfeb1f712ebc6f1"},
}
def __init__(self) -> None:
"""Initialize the instance."""
super().__init__()
def __call__(self, value):
"""Validate input value."""
subjects = value if isinstance(value, list) else [value]
for subject in subjects:
if "id" in subject:
uri_validator = Uri()
try:
uri_validator(subject["id"])
except ValidationError:
raise ValidationError(
f'credential subject id {subject["id"]} must be URI'
) from None
return value
class IndyOrKeyDID(Regexp):
"""Indy or Key DID class."""
PATTERN = "|".join(x.pattern for x in [DIDKey.PATTERN, IndyDID.PATTERN])
EXAMPLE = IndyDID.EXAMPLE
def __init__(
self,
):
"""Initialize the instance."""
super().__init__(
IndyOrKeyDID.PATTERN,
error="Value {input} is not in did:key or indy did format",
)
# Instances for marshmallow schema specification
INT_EPOCH_VALIDATE = IntEpoch()
INT_EPOCH_EXAMPLE = IntEpoch.EXAMPLE
WHOLE_NUM_VALIDATE = WholeNumber()
WHOLE_NUM_EXAMPLE = WholeNumber.EXAMPLE
NUM_STR_WHOLE_VALIDATE = NumericStrWhole()
NUM_STR_WHOLE_EXAMPLE = NumericStrWhole.EXAMPLE
NUM_STR_ANY_VALIDATE = NumericStrAny()
NUM_STR_ANY_EXAMPLE = NumericStrAny.EXAMPLE
NATURAL_NUM_VALIDATE = NaturalNumber()
NATURAL_NUM_EXAMPLE = NaturalNumber.EXAMPLE
NUM_STR_NATURAL_VALIDATE = NumericStrNatural()
NUM_STR_NATURAL_EXAMPLE = NumericStrNatural.EXAMPLE
INDY_REV_REG_SIZE_VALIDATE = IndyRevRegSize()
INDY_REV_REG_SIZE_EXAMPLE = IndyRevRegSize.EXAMPLE
JWS_HEADER_KID_VALIDATE = JWSHeaderKid()
JWS_HEADER_KID_EXAMPLE = JWSHeaderKid.EXAMPLE
NON_SD_LIST_VALIDATE = NonSDList()
NON_SD_LIST_EXAMPLE = NonSDList().EXAMPLE
JWT_VALIDATE = JSONWebToken()
JWT_EXAMPLE = JSONWebToken.EXAMPLE
SD_JWT_VALIDATE = SDJSONWebToken()
SD_JWT_EXAMPLE = SDJSONWebToken.EXAMPLE
DID_KEY_VALIDATE = DIDKey()
DID_KEY_EXAMPLE = DIDKey.EXAMPLE
DID_KEY_OR_REF_VALIDATE = DIDKeyOrRef()
DID_KEY_OR_REF_EXAMPLE = DIDKeyOrRef.EXAMPLE
DID_KEY_REF_VALIDATE = DIDKeyRef()
DID_KEY_REF_EXAMPLE = DIDKeyRef.EXAMPLE
DID_POSTURE_VALIDATE = DIDPosture()
DID_POSTURE_EXAMPLE = DIDPosture.EXAMPLE
ROUTING_KEY_VALIDATE = RoutingKey()
ROUTING_KEY_EXAMPLE = RoutingKey.EXAMPLE
INDY_DID_VALIDATE = IndyDID()
INDY_DID_EXAMPLE = IndyDID.EXAMPLE
GENERIC_DID_VALIDATE = MaybeIndyDID()
GENERIC_DID_EXAMPLE = MaybeIndyDID.EXAMPLE
INDY_RAW_PUBLIC_KEY_VALIDATE = IndyRawPublicKey()
INDY_RAW_PUBLIC_KEY_EXAMPLE = IndyRawPublicKey.EXAMPLE
INDY_SCHEMA_ID_VALIDATE = IndySchemaId()
INDY_SCHEMA_ID_EXAMPLE = IndySchemaId.EXAMPLE
INDY_CRED_DEF_ID_VALIDATE = IndyCredDefId()
INDY_CRED_DEF_ID_EXAMPLE = IndyCredDefId.EXAMPLE
INDY_REV_REG_ID_VALIDATE = IndyRevRegId()
INDY_REV_REG_ID_EXAMPLE = IndyRevRegId.EXAMPLE
INDY_CRED_REV_ID_VALIDATE = IndyCredRevId()
INDY_CRED_REV_ID_EXAMPLE = IndyCredRevId.EXAMPLE
INDY_VERSION_VALIDATE = IndyVersion()
INDY_VERSION_EXAMPLE = IndyVersion.EXAMPLE
INDY_PREDICATE_VALIDATE = IndyPredicate()
INDY_PREDICATE_EXAMPLE = IndyPredicate.EXAMPLE
INDY_ISO8601_DATETIME_VALIDATE = IndyISO8601DateTime()
INDY_ISO8601_DATETIME_EXAMPLE = IndyISO8601DateTime.EXAMPLE
RFC3339_DATETIME_VALIDATE = RFC3339DateTime()
RFC3339_DATETIME_EXAMPLE = RFC3339DateTime.EXAMPLE
INDY_WQL_VALIDATE = IndyWQL()
INDY_WQL_EXAMPLE = IndyWQL.EXAMPLE
INDY_EXTRA_WQL_VALIDATE = IndyExtraWQL()
INDY_EXTRA_WQL_EXAMPLE = IndyExtraWQL.EXAMPLE
BASE64_VALIDATE = Base64()
BASE64_EXAMPLE = Base64.EXAMPLE
BASE64URL_VALIDATE = Base64URL()
BASE64URL_EXAMPLE = Base64URL.EXAMPLE
BASE64URL_NO_PAD_VALIDATE = Base64URLNoPad()
BASE64URL_NO_PAD_EXAMPLE = Base64URLNoPad.EXAMPLE
SHA256_VALIDATE = SHA256Hash()
SHA256_EXAMPLE = SHA256Hash.EXAMPLE
BASE58_SHA256_HASH_VALIDATE = Base58SHA256Hash()
BASE58_SHA256_HASH_EXAMPLE = Base58SHA256Hash.EXAMPLE
UUID4_VALIDATE = UUIDFour()
UUID4_EXAMPLE = UUIDFour.EXAMPLE
ENDPOINT_VALIDATE = Endpoint()
ENDPOINT_EXAMPLE = Endpoint.EXAMPLE
ENDPOINT_TYPE_VALIDATE = EndpointType()
ENDPOINT_TYPE_EXAMPLE = EndpointType.EXAMPLE
CREDENTIAL_TYPE_VALIDATE = CredentialType()
CREDENTIAL_TYPE_EXAMPLE = CredentialType.EXAMPLE
CREDENTIAL_CONTEXT_VALIDATE = CredentialContext()
CREDENTIAL_CONTEXT_EXAMPLE = CredentialContext.EXAMPLE
URI_VALIDATE = Uri()
URI_EXAMPLE = Uri.EXAMPLE
CREDENTIAL_SUBJECT_VALIDATE = CredentialSubject()
CREDENTIAL_SUBJECT_EXAMPLE = CredentialSubject.EXAMPLE
INDY_OR_KEY_DID_VALIDATE = IndyOrKeyDID()
INDY_OR_KEY_DID_EXAMPLE = IndyOrKeyDID.EXAMPLE