File: __init__.py

package info (click to toggle)
cyclonedx-python-lib 9.1.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 10,112 kB
  • sloc: xml: 14,752; python: 11,463; makefile: 21; sh: 16
file content (1298 lines) | stat: -rw-r--r-- 41,095 bytes parent folder | download
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
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
# This file is part of CycloneDX Python Library
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# SPDX-License-Identifier: Apache-2.0
# Copyright (c) OWASP Foundation. All Rights Reserved.

"""
Uniform set of models to represent objects within a CycloneDX software bill-of-materials.

You can either create a `cyclonedx.model.bom.Bom` yourself programmatically, or generate a `cyclonedx.model.bom.Bom`
from a `cyclonedx.parser.BaseParser` implementation.
"""

import re
from datetime import datetime
from enum import Enum
from functools import reduce
from json import loads as json_loads
from typing import Any, Dict, FrozenSet, Generator, Iterable, List, Optional, Tuple, Type, Union
from urllib.parse import quote as url_quote
from uuid import UUID
from warnings import warn
from xml.etree.ElementTree import Element as XmlElement  # nosec B405

import py_serializable as serializable
from sortedcontainers import SortedSet

from .._internal.compare import ComparableTuple as _ComparableTuple
from ..exception.model import InvalidLocaleTypeException, InvalidUriException, UnknownHashTypeException
from ..exception.serialization import CycloneDxDeserializationException, SerializationOfUnexpectedValueException
from ..schema.schema import (
    SchemaVersion1Dot0,
    SchemaVersion1Dot1,
    SchemaVersion1Dot2,
    SchemaVersion1Dot3,
    SchemaVersion1Dot4,
    SchemaVersion1Dot5,
    SchemaVersion1Dot6,
)
from .bom_ref import BomRef

_BOM_LINK_PREFIX = 'urn:cdx:'


@serializable.serializable_enum
class DataFlow(str, Enum):
    """
    This is our internal representation of the dataFlowType simple type within the CycloneDX standard.

    .. note::
        See the CycloneDX Schema: https://cyclonedx.org/docs/1.6/xml/#type_dataFlowType
    """
    INBOUND = 'inbound'
    OUTBOUND = 'outbound'
    BI_DIRECTIONAL = 'bi-directional'
    UNKNOWN = 'unknown'


@serializable.serializable_class
class DataClassification:
    """
    This is our internal representation of the `dataClassificationType` complex type within the CycloneDX standard.

    DataClassification might be deprecated since CycloneDX 1.5, but it is not deprecated in this library.
    In fact, this library will try to provide a compatibility layer if needed.

    .. note::
        See the CycloneDX Schema for dataClassificationType:
        https://cyclonedx.org/docs/1.6/xml/#type_dataClassificationType
    """

    def __init__(
        self, *,
        flow: DataFlow,
        classification: str,
    ) -> None:
        self.flow = flow
        self.classification = classification

    @property
    @serializable.xml_attribute()
    def flow(self) -> DataFlow:
        """
        Specifies the flow direction of the data.

        Valid values are: inbound, outbound, bi-directional, and unknown.

        Direction is relative to the service.

        - Inbound flow states that data enters the service
        - Outbound flow states that data leaves the service
        - Bi-directional states that data flows both ways
        - Unknown states that the direction is not known

        Returns:
            `DataFlow`
        """
        return self._flow

    @flow.setter
    def flow(self, flow: DataFlow) -> None:
        self._flow = flow

    @property
    @serializable.xml_name('.')
    @serializable.xml_string(serializable.XmlStringSerializationType.NORMALIZED_STRING)
    def classification(self) -> str:
        """
        Data classification tags data according to its type, sensitivity, and value if altered, stolen, or destroyed.

        Returns:
            `str`
        """
        return self._classification

    @classification.setter
    def classification(self, classification: str) -> None:
        self._classification = classification

    def __comparable_tuple(self) -> _ComparableTuple:
        return _ComparableTuple((
            self.flow, self.classification
        ))

    def __eq__(self, other: object) -> bool:
        if isinstance(other, DataClassification):
            return self.__comparable_tuple() == other.__comparable_tuple()
        return False

    def __lt__(self, other: object) -> bool:
        if isinstance(other, DataClassification):
            return self.__comparable_tuple() < other.__comparable_tuple()
        return NotImplemented

    def __hash__(self) -> int:
        return hash(self.__comparable_tuple())

    def __repr__(self) -> str:
        return f'<DataClassification flow={self.flow}>'


@serializable.serializable_enum
class Encoding(str, Enum):
    """
    This is our internal representation of the encoding simple type within the CycloneDX standard.

    .. note::
        See the CycloneDX Schema: https://cyclonedx.org/docs/1.6/#type_encoding
    """
    BASE_64 = 'base64'


@serializable.serializable_class
class AttachedText:
    """
    This is our internal representation of the `attachedTextType` complex type within the CycloneDX standard.

    .. note::
        See the CycloneDX Schema for hashType: https://cyclonedx.org/docs/1.6/#type_attachedTextType
    """

    DEFAULT_CONTENT_TYPE = 'text/plain'

    def __init__(
        self, *,
        content: str,
        content_type: str = DEFAULT_CONTENT_TYPE,
        encoding: Optional[Encoding] = None,
    ) -> None:
        self.content_type = content_type
        self.encoding = encoding
        self.content = content

    @property
    @serializable.xml_attribute()
    @serializable.xml_name('content-type')
    @serializable.xml_string(serializable.XmlStringSerializationType.NORMALIZED_STRING)
    def content_type(self) -> str:
        """
        Specifies the content type of the text. Defaults to text/plain if not specified.

        Returns:
            `str`
        """
        return self._content_type

    @content_type.setter
    def content_type(self, content_type: str) -> None:
        self._content_type = content_type

    @property
    @serializable.xml_attribute()
    def encoding(self) -> Optional[Encoding]:
        """
        Specifies the optional encoding the text is represented in.

        Returns:
            `Encoding` if set else `None`
        """
        return self._encoding

    @encoding.setter
    def encoding(self, encoding: Optional[Encoding]) -> None:
        self._encoding = encoding

    @property
    @serializable.xml_name('.')
    def content(self) -> str:
        """
        The attachment data.

        Proactive controls such as input validation and sanitization should be employed to prevent misuse of attachment
        text.

        Returns:
            `str`
        """
        return self._content

    @content.setter
    def content(self, content: str) -> None:
        self._content = content

    def __comparable_tuple(self) -> _ComparableTuple:
        return _ComparableTuple((
            self.content_type, self.encoding, self.content,
        ))

    def __eq__(self, other: object) -> bool:
        if isinstance(other, AttachedText):
            return self.__comparable_tuple() == other.__comparable_tuple()
        return False

    def __lt__(self, other: Any) -> bool:
        if isinstance(other, AttachedText):
            return self.__comparable_tuple() < other.__comparable_tuple()
        return NotImplemented

    def __hash__(self) -> int:
        return hash(self.__comparable_tuple())

    def __repr__(self) -> str:
        return f'<AttachedText content-type={self.content_type}, encoding={self.encoding}>'


@serializable.serializable_enum
class HashAlgorithm(str, Enum):
    """
    This is our internal representation of the hashAlg simple type within the CycloneDX standard.

    .. note::
        See the CycloneDX Schema: https://cyclonedx.org/docs/1.6/#type_hashAlg
    """
    # see `_HashTypeRepositorySerializationHelper.__CASES` for view/case map
    BLAKE2B_256 = 'BLAKE2b-256'  # Only supported in >= 1.2
    BLAKE2B_384 = 'BLAKE2b-384'  # Only supported in >= 1.2
    BLAKE2B_512 = 'BLAKE2b-512'  # Only supported in >= 1.2
    BLAKE3 = 'BLAKE3'  # Only supported in >= 1.2
    MD5 = 'MD5'
    SHA_1 = 'SHA-1'
    SHA_256 = 'SHA-256'
    SHA_384 = 'SHA-384'
    SHA_512 = 'SHA-512'
    SHA3_256 = 'SHA3-256'
    SHA3_384 = 'SHA3-384'  # Only supported in >= 1.2
    SHA3_512 = 'SHA3-512'


class _HashTypeRepositorySerializationHelper(serializable.helpers.BaseHelper):
    """  THIS CLASS IS NON-PUBLIC API  """

    __CASES: Dict[Type[serializable.ViewType], FrozenSet[HashAlgorithm]] = dict()
    __CASES[SchemaVersion1Dot0] = frozenset({
        HashAlgorithm.MD5,
        HashAlgorithm.SHA_1,
        HashAlgorithm.SHA_256,
        HashAlgorithm.SHA_384,
        HashAlgorithm.SHA_512,
        HashAlgorithm.SHA3_256,
        HashAlgorithm.SHA3_512,
    })
    __CASES[SchemaVersion1Dot1] = __CASES[SchemaVersion1Dot0]
    __CASES[SchemaVersion1Dot2] = __CASES[SchemaVersion1Dot1] | {
        HashAlgorithm.BLAKE2B_256,
        HashAlgorithm.BLAKE2B_384,
        HashAlgorithm.BLAKE2B_512,
        HashAlgorithm.BLAKE3,
        HashAlgorithm.SHA3_384,
    }
    __CASES[SchemaVersion1Dot3] = __CASES[SchemaVersion1Dot2]
    __CASES[SchemaVersion1Dot4] = __CASES[SchemaVersion1Dot3]
    __CASES[SchemaVersion1Dot5] = __CASES[SchemaVersion1Dot4]
    __CASES[SchemaVersion1Dot6] = __CASES[SchemaVersion1Dot5]

    @classmethod
    def __prep(cls, hts: Iterable['HashType'], view: Type[serializable.ViewType]) -> Generator['HashType', None, None]:
        cases = cls.__CASES.get(view, ())
        for ht in hts:
            if ht.alg in cases:
                yield ht
            else:
                warn(f'serialization omitted due to unsupported HashAlgorithm: {ht!r}',
                     category=UserWarning, stacklevel=0)

    @classmethod
    def json_normalize(cls, o: Iterable['HashType'], *,
                       view: Optional[Type[serializable.ViewType]],
                       **__: Any) -> List[Any]:
        assert view is not None
        return [
            json_loads(
                ht.as_json(  # type:ignore[attr-defined]
                    view_=view)
            ) for ht in cls.__prep(o, view)
        ]

    @classmethod
    def xml_normalize(cls, o: Iterable['HashType'], *,
                      element_name: str,
                      view: Optional[Type[serializable.ViewType]],
                      xmlns: Optional[str],
                      **__: Any) -> XmlElement:
        assert view is not None
        elem = XmlElement(element_name)
        elem.extend(
            ht.as_xml(  # type:ignore[attr-defined]
                view_=view, as_string=False, element_name='hash', xmlns=xmlns
            ) for ht in cls.__prep(o, view)
        )
        return elem

    @classmethod
    def json_denormalize(cls, o: Any,
                         **__: Any) -> List['HashType']:
        return [
            HashType.from_json(  # type:ignore[attr-defined]
                ht) for ht in o
        ]

    @classmethod
    def xml_denormalize(cls, o: 'XmlElement', *,
                        default_ns: Optional[str],
                        **__: Any) -> List['HashType']:
        return [
            HashType.from_xml(  # type:ignore[attr-defined]
                ht, default_ns) for ht in o
        ]


_MAP_HASHLIB: Dict[str, HashAlgorithm] = {
    # from hashlib.algorithms_guaranteed
    'md5': HashAlgorithm.MD5,
    'sha1': HashAlgorithm.SHA_1,
    # sha224:
    'sha256': HashAlgorithm.SHA_256,
    'sha384': HashAlgorithm.SHA_384,
    'sha512': HashAlgorithm.SHA_512,
    # blake2b:
    # blake2s:
    # sha3_224:
    'sha3_256': HashAlgorithm.SHA3_256,
    'sha3_384': HashAlgorithm.SHA3_384,
    'sha3_512': HashAlgorithm.SHA3_512,
    # shake_128:
    # shake_256:
}


@serializable.serializable_class
class HashType:
    """
    This is our internal representation of the hashType complex type within the CycloneDX standard.

    .. note::
        See the CycloneDX Schema for hashType: https://cyclonedx.org/docs/1.6/#type_hashType
    """

    @staticmethod
    def from_hashlib_alg(hashlib_alg: str, content: str) -> 'HashType':
        """
        Attempts to convert a hashlib-algorithm to our internal model classes.

        Args:
             hashlib_alg:
                Hash algorith - like it is used by `hashlib`.
                Example: `sha256`.

            content:
                Hash value.

        Raises:
            `UnknownHashTypeException` if the algorithm of hash cannot be determined.

        Returns:
            An instance of `HashType`.
        """
        alg = _MAP_HASHLIB.get(hashlib_alg.lower())
        if alg is None:
            raise UnknownHashTypeException(f'Unable to determine hash alg for {hashlib_alg!r}')
        return HashType(alg=alg, content=content)

    @staticmethod
    def from_composite_str(composite_hash: str) -> 'HashType':
        """
        Attempts to convert a string which includes both the Hash Algorithm and Hash Value and represent using our
        internal model classes.

        Args:
             composite_hash:
                Composite Hash string of the format `HASH_ALGORITHM`:`HASH_VALUE`.
                Example: `sha256:806143ae5bfb6a3c6e736a764057db0e6a0e05e338b5630894a5f779cabb4f9b`.

                Valid case insensitive prefixes are:
                `md5`, `sha1`, `sha256`, `sha384`, `sha512`, `blake2b256`, `blake2b384`, `blake2b512`,
                `blake2256`, `blake2384`, `blake2512`, `sha3-256`, `sha3-384`, `sha3-512`,
                `blake3`.

        Raises:
            `UnknownHashTypeException` if the type of hash cannot be determined.

        Returns:
            An instance of `HashType`.
        """
        parts = composite_hash.split(':')

        algorithm_prefix = parts[0].lower()
        if algorithm_prefix == 'md5':
            return HashType(
                alg=HashAlgorithm.MD5,
                content=parts[1].lower()
            )
        elif algorithm_prefix[0:4] == 'sha3':
            return HashType(
                alg=getattr(HashAlgorithm, f'SHA3_{algorithm_prefix[5:]}'),
                content=parts[1].lower()
            )
        elif algorithm_prefix == 'sha1':
            return HashType(
                alg=HashAlgorithm.SHA_1,
                content=parts[1].lower()
            )
        elif algorithm_prefix[0:3] == 'sha':
            # This is actually SHA2...
            return HashType(
                alg=getattr(HashAlgorithm, f'SHA_{algorithm_prefix[3:]}'),
                content=parts[1].lower()
            )
        elif algorithm_prefix[0:7] == 'blake2b':
            return HashType(
                alg=getattr(HashAlgorithm, f'BLAKE2B_{algorithm_prefix[7:]}'),
                content=parts[1].lower()
            )
        elif algorithm_prefix[0:6] == 'blake2':
            return HashType(
                alg=getattr(HashAlgorithm, f'BLAKE2B_{algorithm_prefix[6:]}'),
                content=parts[1].lower()
            )
        elif algorithm_prefix[0:6] == 'blake3':
            return HashType(
                alg=HashAlgorithm.BLAKE3,
                content=parts[1].lower()
            )
        raise UnknownHashTypeException(f'Unable to determine hash type from {composite_hash!r}')

    def __init__(
        self, *,
        alg: HashAlgorithm,
        content: str,
    ) -> None:
        self.alg = alg
        self.content = content

    @property
    @serializable.xml_attribute()
    def alg(self) -> HashAlgorithm:
        """
        Specifies the algorithm used to create the hash.

        Returns:
            `HashAlgorithm`
        """
        return self._alg

    @alg.setter
    def alg(self, alg: HashAlgorithm) -> None:
        self._alg = alg

    @property
    @serializable.xml_name('.')
    @serializable.xml_string(serializable.XmlStringSerializationType.TOKEN)
    def content(self) -> str:
        """
        Hash value content.

        Returns:
            `str`
        """
        return self._content

    @content.setter
    def content(self, content: str) -> None:
        self._content = content

    def __comparable_tuple(self) -> _ComparableTuple:
        return _ComparableTuple((
            self.alg, self.content
        ))

    def __eq__(self, other: object) -> bool:
        if isinstance(other, HashType):
            return self.__comparable_tuple() == other.__comparable_tuple()
        return False

    def __lt__(self, other: Any) -> bool:
        if isinstance(other, HashType):
            return self.__comparable_tuple() < other.__comparable_tuple()
        return NotImplemented

    def __hash__(self) -> int:
        return hash(self.__comparable_tuple())

    def __repr__(self) -> str:
        return f'<HashType {self.alg.name}:{self.content}>'


@serializable.serializable_enum
class ExternalReferenceType(str, Enum):
    """
    Enum object that defines the permissible 'types' for an External Reference according to the CycloneDX schema.

    .. note::
        See the CycloneDX Schema definition: https://cyclonedx.org/docs/1.6/#type_externalReferenceType
    """
    # see `_ExternalReferenceSerializationHelper.__CASES` for view/case map
    ADVERSARY_MODEL = 'adversary-model'  # Only supported in >= 1.5
    ADVISORIES = 'advisories'
    ATTESTATION = 'attestation'  # Only supported in >= 1.5
    BOM = 'bom'
    BUILD_META = 'build-meta'
    BUILD_SYSTEM = 'build-system'
    CERTIFICATION_REPORT = 'certification-report'  # Only supported in >= 1.5
    CHAT = 'chat'
    CODIFIED_INFRASTRUCTURE = 'codified-infrastructure'  # Only supported in >= 1.5
    COMPONENT_ANALYSIS_REPORT = 'component-analysis-report'  # Only supported in >= 1.5
    CONFIGURATION = 'configuration'  # Only supported in >= 1.5
    DIGITAL_SIGNATURE = 'digital-signature'  # Only supported in >= 1.6
    DISTRIBUTION = 'distribution'
    DISTRIBUTION_INTAKE = 'distribution-intake'  # Only supported in >= 1.5
    DOCUMENTATION = 'documentation'
    DYNAMIC_ANALYSIS_REPORT = 'dynamic-analysis-report'  # Only supported in >= 1.5
    ELECTRONIC_SIGNATURE = 'electronic-signature'  # Only supported in >= 1.6
    EVIDENCE = 'evidence'  # Only supported in >= 1.5
    EXPLOITABILITY_STATEMENT = 'exploitability-statement'  # Only supported in >= 1.5
    FORMULATION = 'formulation'  # Only supported in >= 1.5
    ISSUE_TRACKER = 'issue-tracker'
    LICENSE = 'license'
    LOG = 'log'  # Only supported in >= 1.5
    MAILING_LIST = 'mailing-list'
    MATURITY_REPORT = 'maturity-report'  # Only supported in >= 1.5
    MODEL_CARD = 'model-card'  # Only supported in >= 1.5
    PENTEST_REPORT = 'pentest-report'  # Only supported in >= 1.5
    POAM = 'poam'  # Only supported in >= 1.5
    QUALITY_METRICS = 'quality-metrics'  # Only supported in >= 1.5
    RELEASE_NOTES = 'release-notes'  # Only supported in >= 1.4
    RFC_9166 = 'rfc-9116'  # Only supported in >= 1.6
    RISK_ASSESSMENT = 'risk-assessment'  # Only supported in >= 1.5
    RUNTIME_ANALYSIS_REPORT = 'runtime-analysis-report'  # Only supported in >= 1.5
    SECURITY_CONTACT = 'security-contact'  # Only supported in >= 1.5
    STATIC_ANALYSIS_REPORT = 'static-analysis-report'  # Only supported in >= 1.5
    SOCIAL = 'social'
    SOURCE_DISTRIBUTION = 'source-distribution'  # Only supported in >= 1.6
    SCM = 'vcs'
    SUPPORT = 'support'
    THREAT_MODEL = 'threat-model'  # Only supported in >= 1.5
    VCS = 'vcs'
    VULNERABILITY_ASSERTION = 'vulnerability-assertion'  # Only supported in >= 1.5
    WEBSITE = 'website'
    # --
    OTHER = 'other'


class _ExternalReferenceSerializationHelper(serializable.helpers.BaseHelper):
    """  THIS CLASS IS NON-PUBLIC API  """

    __CASES: Dict[Type[serializable.ViewType], FrozenSet[ExternalReferenceType]] = dict()
    __CASES[SchemaVersion1Dot1] = frozenset({
        ExternalReferenceType.VCS,
        ExternalReferenceType.ISSUE_TRACKER,
        ExternalReferenceType.WEBSITE,
        ExternalReferenceType.ADVISORIES,
        ExternalReferenceType.BOM,
        ExternalReferenceType.MAILING_LIST,
        ExternalReferenceType.SOCIAL,
        ExternalReferenceType.CHAT,
        ExternalReferenceType.DOCUMENTATION,
        ExternalReferenceType.SUPPORT,
        ExternalReferenceType.DISTRIBUTION,
        ExternalReferenceType.LICENSE,
        ExternalReferenceType.BUILD_META,
        ExternalReferenceType.BUILD_SYSTEM,
        ExternalReferenceType.OTHER,
    })
    __CASES[SchemaVersion1Dot2] = __CASES[SchemaVersion1Dot1]
    __CASES[SchemaVersion1Dot3] = __CASES[SchemaVersion1Dot2]
    __CASES[SchemaVersion1Dot4] = __CASES[SchemaVersion1Dot3] | {
        ExternalReferenceType.RELEASE_NOTES
    }
    __CASES[SchemaVersion1Dot5] = __CASES[SchemaVersion1Dot4] | {
        ExternalReferenceType.DISTRIBUTION_INTAKE,
        ExternalReferenceType.SECURITY_CONTACT,
        ExternalReferenceType.MODEL_CARD,
        ExternalReferenceType.LOG,
        ExternalReferenceType.CONFIGURATION,
        ExternalReferenceType.EVIDENCE,
        ExternalReferenceType.FORMULATION,
        ExternalReferenceType.ATTESTATION,
        ExternalReferenceType.THREAT_MODEL,
        ExternalReferenceType.ADVERSARY_MODEL,
        ExternalReferenceType.RISK_ASSESSMENT,
        ExternalReferenceType.VULNERABILITY_ASSERTION,
        ExternalReferenceType.EXPLOITABILITY_STATEMENT,
        ExternalReferenceType.PENTEST_REPORT,
        ExternalReferenceType.STATIC_ANALYSIS_REPORT,
        ExternalReferenceType.DYNAMIC_ANALYSIS_REPORT,
        ExternalReferenceType.RUNTIME_ANALYSIS_REPORT,
        ExternalReferenceType.COMPONENT_ANALYSIS_REPORT,
        ExternalReferenceType.MATURITY_REPORT,
        ExternalReferenceType.CERTIFICATION_REPORT,
        ExternalReferenceType.QUALITY_METRICS,
        ExternalReferenceType.CODIFIED_INFRASTRUCTURE,
        ExternalReferenceType.POAM,
    }
    __CASES[SchemaVersion1Dot6] = __CASES[SchemaVersion1Dot5] | {
        ExternalReferenceType.SOURCE_DISTRIBUTION,
        ExternalReferenceType.ELECTRONIC_SIGNATURE,
        ExternalReferenceType.DIGITAL_SIGNATURE,
        ExternalReferenceType.RFC_9166,
    }

    @classmethod
    def __normalize(cls, extref: ExternalReferenceType, view: Type[serializable.ViewType]) -> str:
        return (
            extref
            if extref in cls.__CASES.get(view, ())
            else ExternalReferenceType.OTHER
        ).value

    @classmethod
    def json_normalize(cls, o: Any, *,
                       view: Optional[Type[serializable.ViewType]],
                       **__: Any) -> str:
        assert view is not None
        return cls.__normalize(o, view)

    @classmethod
    def xml_normalize(cls, o: Any, *,
                      view: Optional[Type[serializable.ViewType]],
                      **__: Any) -> str:
        assert view is not None
        return cls.__normalize(o, view)

    @classmethod
    def deserialize(cls, o: Any) -> ExternalReferenceType:
        return ExternalReferenceType(o)


@serializable.serializable_class
class XsUri(serializable.helpers.BaseHelper):
    """
    Helper class that allows us to perform validation on data strings that are defined as xs:anyURI
    in CycloneDX schema.

    Developers can just use this via `str(XsUri('https://www.google.com'))`.

    .. note::
        See XSD definition for xsd:anyURI: http://www.datypic.com/sc/xsd/t-xsd_anyURI.html
        See JSON Schema definition for iri-reference: https://tools.ietf.org/html/rfc3987
    """

    _INVALID_URI_REGEX = re.compile(r'%(?![0-9A-F]{2})|#.*#', re.IGNORECASE + re.MULTILINE)

    __SPEC_REPLACEMENTS = (
        (' ', '%20'),
        ('"', '%22'),
        ("'", '%27'),
        ('[', '%5B'),
        (']', '%5D'),
        ('<', '%3C'),
        ('>', '%3E'),
        ('{', '%7B'),
        ('}', '%7D'),
    )

    @staticmethod
    def __spec_replace(v: str, r: Tuple[str, str]) -> str:
        return v.replace(*r)

    @classmethod
    def _spec_migrate(cls, o: str) -> str:
        """
         Make a string valid to
         - XML::anyURI spec.
         - JSON::iri-reference spec.

         BEST EFFORT IMPLEMENTATION

         @see http://www.w3.org/TR/xmlschema-2/#anyURI
         @see http://www.datypic.com/sc/xsd/t-xsd_anyURI.html
         @see https://datatracker.ietf.org/doc/html/rfc2396
         @see https://datatracker.ietf.org/doc/html/rfc3987
        """
        return reduce(cls.__spec_replace, cls.__SPEC_REPLACEMENTS, o)

    def __init__(self, uri: str) -> None:
        if re.search(XsUri._INVALID_URI_REGEX, uri):
            raise InvalidUriException(
                f"Supplied value '{uri}' does not appear to be a valid URI."
            )
        self._uri = self._spec_migrate(uri)

    def __eq__(self, other: Any) -> bool:
        if isinstance(other, XsUri):
            return self._uri == other._uri
        return False

    def __lt__(self, other: Any) -> bool:
        if isinstance(other, XsUri):
            return self._uri < other._uri
        return NotImplemented

    def __hash__(self) -> int:
        return hash(self._uri)

    def __repr__(self) -> str:
        return f'<XsUri {self._uri}>'

    def __str__(self) -> str:
        return self._uri

    @property
    @serializable.json_name('.')
    @serializable.xml_name('.')
    def uri(self) -> str:
        return self._uri

    @classmethod
    def serialize(cls, o: Any) -> str:
        if isinstance(o, XsUri):
            return str(o)
        raise SerializationOfUnexpectedValueException(
            f'Attempt to serialize a non-XsUri: {o!r}')

    @classmethod
    def deserialize(cls, o: Any) -> 'XsUri':
        try:
            return XsUri(uri=str(o))
        except ValueError as err:
            raise CycloneDxDeserializationException(
                f'XsUri string supplied does not parse: {o!r}'
            ) from err

    @classmethod
    def make_bom_link(
        cls,
        serial_number: Union[UUID, str],
        version: int = 1,
        bom_ref: Optional[Union[str, BomRef]] = None
    ) -> 'XsUri':
        """
        Generate a BOM-Link URI.

        Args:
            serial_number: The unique serial number of the BOM.
            version: The version of the BOM. The default version is 1.
            bom_ref: The unique identifier of the component, service, or vulnerability within the BOM.

        Returns:
            XsUri: Instance of XsUri with the generated BOM-Link URI.
        """
        bom_ref_part = f'#{url_quote(str(bom_ref))}' if bom_ref else ''
        return cls(f'{_BOM_LINK_PREFIX}{serial_number}/{version}{bom_ref_part}')

    def is_bom_link(self) -> bool:
        """
        Check if the URI is a BOM-Link.

        Returns:
            `bool`
        """
        return self._uri.startswith(_BOM_LINK_PREFIX)


@serializable.serializable_class
class ExternalReference:
    """
    This is our internal representation of an ExternalReference complex type that can be used in multiple places within
    a CycloneDX BOM document.

    .. note::
        See the CycloneDX Schema definition: https://cyclonedx.org/docs/1.6/#type_externalReference
    """

    def __init__(
        self, *,
        type: ExternalReferenceType,
        url: XsUri,
        comment: Optional[str] = None,
        hashes: Optional[Iterable[HashType]] = None,
    ) -> None:
        self.url = url
        self.comment = comment
        self.type = type
        self.hashes = hashes or []  # type:ignore[assignment]

    @property
    @serializable.xml_sequence(1)
    def url(self) -> XsUri:
        """
        The URL to the external reference.

        Returns:
            `XsUri`
        """
        return self._url

    @url.setter
    def url(self, url: XsUri) -> None:
        self._url = url

    @property
    def comment(self) -> Optional[str]:
        """
        An optional comment describing the external reference.

        Returns:
            `str` if set else `None`
        """
        return self._comment

    @comment.setter
    def comment(self, comment: Optional[str]) -> None:
        self._comment = comment

    @property
    @serializable.type_mapping(_ExternalReferenceSerializationHelper)
    @serializable.xml_attribute()
    def type(self) -> ExternalReferenceType:
        """
        Specifies the type of external reference.

        There are built-in types to describe common references. If a type does not exist for the reference being
        referred to, use the "other" type.

        Returns:
            `ExternalReferenceType`
        """
        return self._type

    @type.setter
    def type(self, type: ExternalReferenceType) -> None:
        self._type = type

    @property
    @serializable.view(SchemaVersion1Dot3)
    @serializable.view(SchemaVersion1Dot4)
    @serializable.view(SchemaVersion1Dot5)
    @serializable.view(SchemaVersion1Dot6)
    @serializable.type_mapping(_HashTypeRepositorySerializationHelper)
    def hashes(self) -> 'SortedSet[HashType]':
        """
        The hashes of the external reference (if applicable).

        Returns:
            Set of `HashType`
        """
        return self._hashes

    @hashes.setter
    def hashes(self, hashes: Iterable[HashType]) -> None:
        self._hashes = SortedSet(hashes)

    def __comparable_tuple(self) -> _ComparableTuple:
        return _ComparableTuple((
            self._type, self._url, self._comment,
            _ComparableTuple(self._hashes)
        ))

    def __eq__(self, other: object) -> bool:
        if isinstance(other, ExternalReference):
            return self.__comparable_tuple() == other.__comparable_tuple()
        return False

    def __lt__(self, other: Any) -> bool:
        if isinstance(other, ExternalReference):
            return self.__comparable_tuple() < other.__comparable_tuple()
        return NotImplemented

    def __hash__(self) -> int:
        return hash(self.__comparable_tuple())

    def __repr__(self) -> str:
        return f'<ExternalReference {self.type.name}, {self.url}>'


@serializable.serializable_class
class Property:
    """
    This is our internal representation of `propertyType` complex type that can be used in multiple places within
    a CycloneDX BOM document.

    .. note::
        See the CycloneDX Schema definition: https://cyclonedx.org/docs/1.6/xml/#type_propertyType

    Specifies an individual property with a name and value.
    """

    def __init__(
        self, *,
        name: str,
        value: Optional[str] = None,
    ) -> None:
        self.name = name
        self.value = value

    @property
    @serializable.xml_attribute()
    def name(self) -> str:
        """
        The name of the property.

        Duplicate names are allowed, each potentially having a different value.

        Returns:
            `str`
        """
        return self._name

    @name.setter
    def name(self, name: str) -> None:
        self._name = name

    @property
    @serializable.xml_name('.')
    @serializable.xml_string(serializable.XmlStringSerializationType.NORMALIZED_STRING)
    def value(self) -> Optional[str]:
        """
        Value of this Property.

        Returns:
             `str`
        """
        return self._value

    @value.setter
    def value(self, value: Optional[str]) -> None:
        self._value = value

    def __comparable_tuple(self) -> _ComparableTuple:
        return _ComparableTuple((
            self.name, self.value
        ))

    def __eq__(self, other: object) -> bool:
        if isinstance(other, Property):
            return self.__comparable_tuple() == other.__comparable_tuple()
        return False

    def __lt__(self, other: Any) -> bool:
        if isinstance(other, Property):
            return self.__comparable_tuple() < other.__comparable_tuple()
        return NotImplemented

    def __hash__(self) -> int:
        return hash(self.__comparable_tuple())

    def __repr__(self) -> str:
        return f'<Property name={self.name}>'


@serializable.serializable_class
class NoteText:
    """
    This is our internal representation of the Note.text complex type that can be used in multiple places within
    a CycloneDX BOM document.

    .. note::
        See the CycloneDX Schema definition: https://cyclonedx.org/docs/1.6/xml/#type_releaseNotesType
    """

    DEFAULT_CONTENT_TYPE: str = 'text/plain'

    def __init__(
        self, *,
        content: str,
        content_type: Optional[str] = None,
        encoding: Optional[Encoding] = None,
    ) -> None:
        self.content = content
        self.content_type = content_type or NoteText.DEFAULT_CONTENT_TYPE
        self.encoding = encoding

    @property
    @serializable.xml_name('.')
    def content(self) -> str:
        """
        Get the text content of this Note.

        Returns:
            `str` note content
        """
        return self._content

    @content.setter
    def content(self, content: str) -> None:
        self._content = content

    @property
    @serializable.xml_attribute()
    @serializable.xml_name('content-type')
    def content_type(self) -> Optional[str]:
        """
        Get the content-type of this Note.

        Defaults to 'text/plain' if one was not explicitly specified.

        Returns:
            `str` content-type
        """
        return self._content_type

    @content_type.setter
    def content_type(self, content_type: str) -> None:
        self._content_type = content_type

    @property
    @serializable.xml_attribute()
    def encoding(self) -> Optional[Encoding]:
        """
        Get the encoding method used for the note's content.

        Returns:
            `Encoding` if set else `None`
        """
        return self._encoding

    @encoding.setter
    def encoding(self, encoding: Optional[Encoding]) -> None:
        self._encoding = encoding

    def __comparable_tuple(self) -> _ComparableTuple:
        return _ComparableTuple((
            self.content, self.content_type, self.encoding
        ))

    def __eq__(self, other: object) -> bool:
        if isinstance(other, NoteText):
            return self.__comparable_tuple() == other.__comparable_tuple()
        return False

    def __lt__(self, other: Any) -> bool:
        if isinstance(other, NoteText):
            return self.__comparable_tuple() < other.__comparable_tuple()
        return NotImplemented

    def __hash__(self) -> int:
        return hash(self.__comparable_tuple())

    def __repr__(self) -> str:
        return f'<NoteText content_type={self.content_type}, encoding={self.encoding}>'


@serializable.serializable_class
class Note:
    """
    This is our internal representation of the Note complex type that can be used in multiple places within
    a CycloneDX BOM document.

    .. note::
        See the CycloneDX Schema definition: https://cyclonedx.org/docs/1.6/xml/#type_releaseNotesType

    @todo: Replace ``NoteText`` with ``AttachedText``?
    """

    _LOCALE_TYPE_REGEX = re.compile(r'^[a-z]{2}(?:\-[A-Z]{2})?$')

    def __init__(
        self, *,
        text: NoteText,
        locale: Optional[str] = None,
    ) -> None:
        self.text = text
        self.locale = locale

    @property
    def text(self) -> NoteText:
        """
        Specifies the full content of the release note.

        Returns:
            `NoteText`
        """
        return self._text

    @text.setter
    def text(self, text: NoteText) -> None:
        self._text = text

    @property
    @serializable.xml_sequence(1)
    def locale(self) -> Optional[str]:
        """
        Get the ISO locale of this Note.

        The ISO-639 (or higher) language code and optional ISO-3166 (or higher) country code.

        Examples include: "en", "en-US", "fr" and "fr-CA".

        Returns:
            `str` locale if set else `None`
        """
        return self._locale

    @locale.setter
    def locale(self, locale: Optional[str]) -> None:
        self._locale = locale
        if isinstance(locale, str):
            if not re.search(Note._LOCALE_TYPE_REGEX, locale):
                self._locale = None
                raise InvalidLocaleTypeException(
                    f'Supplied locale {locale!r} is not a valid locale.'
                    ' Locale string should be formatted as the ISO-639 (or higher) language code and optional'
                    " ISO-3166 (or higher) country code. according to ISO-639 format. Examples include: 'en', 'en-US'."
                )

    def __comparable_tuple(self) -> _ComparableTuple:
        return _ComparableTuple((
            self.locale, self.text
        ))

    def __eq__(self, other: object) -> bool:
        if isinstance(other, Note):
            return self.__comparable_tuple() == other.__comparable_tuple()
        return False

    def __lt__(self, other: Any) -> bool:
        if isinstance(other, Note):
            return self.__comparable_tuple() < other.__comparable_tuple()
        return NotImplemented

    def __hash__(self) -> int:
        return hash(self.__comparable_tuple())

    def __repr__(self) -> str:
        return f'<Note id={id(self)}, locale={self.locale}>'


@serializable.serializable_class
class IdentifiableAction:
    """
    This is our internal representation of the `identifiableActionType` complex type.

    .. note::
        See the CycloneDX specification: https://cyclonedx.org/docs/1.6/xml/#type_identifiableActionType
    """

    def __init__(
        self, *,
        timestamp: Optional[datetime] = None,
        name: Optional[str] = None,
        email: Optional[str] = None,
    ) -> None:
        self.timestamp = timestamp
        self.name = name
        self.email = email

    @property
    @serializable.type_mapping(serializable.helpers.XsdDateTime)
    def timestamp(self) -> Optional[datetime]:
        """
        The timestamp in which the action occurred.

        Returns:
            `datetime` if set else `None`
        """
        return self._timestamp

    @timestamp.setter
    def timestamp(self, timestamp: Optional[datetime]) -> None:
        self._timestamp = timestamp

    @property
    @serializable.xml_string(serializable.XmlStringSerializationType.NORMALIZED_STRING)
    def name(self) -> Optional[str]:
        """
        The name of the individual who performed the action.

        Returns:
            `str` if set else `None`
        """
        return self._name

    @name.setter
    def name(self, name: Optional[str]) -> None:
        self._name = name

    @property
    @serializable.xml_string(serializable.XmlStringSerializationType.NORMALIZED_STRING)
    def email(self) -> Optional[str]:
        """
        The email address of the individual who performed the action.

        Returns:
            `str` if set else `None`
        """
        return self._email

    @email.setter
    def email(self, email: Optional[str]) -> None:
        self._email = email

    def __comparable_tuple(self) -> _ComparableTuple:
        return _ComparableTuple((
            self.timestamp, self.name, self.email
        ))

    def __eq__(self, other: object) -> bool:
        if isinstance(other, IdentifiableAction):
            return self.__comparable_tuple() == other.__comparable_tuple()
        return False

    def __lt__(self, other: Any) -> bool:
        if isinstance(other, IdentifiableAction):
            return self.__comparable_tuple() < other.__comparable_tuple()
        return NotImplemented

    def __hash__(self) -> int:
        return hash(self.__comparable_tuple())

    def __repr__(self) -> str:
        return f'<IdentifiableAction name={self.name}, email={self.email}>'


@serializable.serializable_class
class Copyright:
    """
    This is our internal representation of the `copyrightsType` complex type.

    .. note::
        See the CycloneDX specification: https://cyclonedx.org/docs/1.6/xml/#type_copyrightsType
    """

    def __init__(
        self, *,
        text: str,
    ) -> None:
        self.text = text

    @property
    @serializable.xml_name('.')
    def text(self) -> str:
        """
        Copyright statement.

        Returns:
            `str` if set else `None`
        """
        return self._text

    @text.setter
    def text(self, text: str) -> None:
        self._text = text

    def __eq__(self, other: object) -> bool:
        if isinstance(other, Copyright):
            return self._text == other._text
        return False

    def __lt__(self, other: Any) -> bool:
        if isinstance(other, Copyright):
            return self._text < other._text
        return NotImplemented

    def __hash__(self) -> int:
        return hash(self._text)

    def __repr__(self) -> str:
        return f'<Copyright text={self.text}>'