-
-
Notifications
You must be signed in to change notification settings - Fork 41
/
__init__.py
1440 lines (1139 loc) · 42.3 KB
/
__init__.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
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
# encoding: utf-8
# 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.
import hashlib
import re
import sys
import warnings
from datetime import datetime, timezone
from enum import Enum
from typing import Any, Iterable, Optional, Tuple, TypeVar
import serializable
from sortedcontainers import SortedSet
from ..exception.model import (
InvalidLocaleTypeException,
InvalidUriException,
MutuallyExclusivePropertiesException,
NoPropertiesProvidedException,
UnknownHashTypeException,
)
from ..schema.schema import SchemaVersion1Dot3, SchemaVersion1Dot4
"""
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.
"""
def get_now_utc() -> datetime:
return datetime.now(tz=timezone.utc)
def sha1sum(filename: str) -> str:
"""
Generate a SHA1 hash of the provided file.
Args:
filename:
Absolute path to file to hash as `str`
Returns:
SHA-1 hash
"""
h = hashlib.sha1()
with open(filename, 'rb') as f:
for byte_block in iter(lambda: f.read(4096), b""):
h.update(byte_block)
return h.hexdigest()
_T = TypeVar('_T')
class ComparableTuple(Tuple[Optional[_T], ...]):
"""
Allows comparison of tuples, allowing for None values.
"""
def __lt__(self, other: Any) -> bool:
for s, o in zip(self, other):
if s == o:
continue
if s is None:
return False
if o is None:
return True
if s < o:
return True
if s > o:
return False
return False
def __gt__(self, other: Any) -> bool:
for s, o in zip(self, other):
if s == o:
continue
if s is None:
return True
if o is None:
return False
if s < o:
return False
if s > o:
return True
return False
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.4/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.
.. note::
See the CycloneDX Schema for dataClassificationType:
https://cyclonedx.org/docs/1.4/xml/#type_dataClassificationType
"""
def __init__(self, *, flow: DataFlow, classification: str) -> None:
self.flow = flow
self.classification = classification
@property # type: ignore[misc]
@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 # type: ignore[misc]
@serializable.xml_name('.')
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 __eq__(self, other: object) -> bool:
if isinstance(other, DataClassification):
return hash(other) == hash(self)
return False
def __hash__(self) -> int:
return hash((self.flow, self.classification))
def __repr__(self) -> str:
return f'<DataClassification flow={self.flow}>'
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.4/#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.3/#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 # type: ignore[misc]
@serializable.xml_attribute()
@serializable.xml_name('content-type')
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 # type: ignore[misc]
@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 # type: ignore[misc]
@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 __eq__(self, other: object) -> bool:
if isinstance(other, AttachedText):
return hash(other) == hash(self)
return False
def __lt__(self, other: Any) -> bool:
if isinstance(other, AttachedText):
return ComparableTuple((self.content_type, self.content, self.encoding)) < \
ComparableTuple((other.content_type, other.content, other.encoding))
return NotImplemented
def __hash__(self) -> int:
return hash((self.content, self.content_type, self.encoding))
def __repr__(self) -> str:
return f'<AttachedText content-type={self.content_type}, encoding={self.encoding}>'
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.3/#type_hashAlg
"""
BLAKE2B_256 = 'BLAKE2b-256'
BLAKE2B_384 = 'BLAKE2b-384'
BLAKE2B_512 = 'BLAKE2b-512'
BLAKE3 = 'BLAKE3'
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'
SHA3_512 = 'SHA3-512'
@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.3/#type_hashType
"""
@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`.
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:3] == 'sha':
return HashType(
alg=getattr(HashAlgorithm, 'SHA_{}'.format(algorithm_prefix[3:])),
content=parts[1].lower()
)
elif algorithm_prefix[0:6] == 'blake2':
return HashType(
alg=getattr(HashAlgorithm, 'BLAKE2b_{}'.format(algorithm_prefix[6:])),
content=parts[1].lower()
)
raise UnknownHashTypeException(f"Unable to determine hash type from '{composite_hash}'")
def __init__(self, *, alg: HashAlgorithm, content: str) -> None:
self.alg = alg
self.content = content
@property # type: ignore[misc]
@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 # type: ignore[misc]
@serializable.xml_name('.')
def content(self) -> str:
"""
Hash value content.
Returns:
`str`
"""
return self._content
@content.setter
def content(self, content: str) -> None:
self._content = content
def __eq__(self, other: object) -> bool:
if isinstance(other, HashType):
return hash(other) == hash(self)
return False
def __lt__(self, other: Any) -> bool:
if isinstance(other, HashType):
return ComparableTuple((self.alg, self.content)) < ComparableTuple((other.alg, other.content))
return NotImplemented
def __hash__(self) -> int:
return hash((self.alg, self.content))
def __repr__(self) -> str:
return f'<HashType {self.alg.name}:{self.content}>'
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.3/#type_externalReferenceType
"""
ADVISORIES = 'advisories'
BOM = 'bom'
BUILD_META = 'build-meta'
BUILD_SYSTEM = 'build-system'
CHAT = 'chat'
DISTRIBUTION = 'distribution'
DOCUMENTATION = 'documentation'
ISSUE_TRACKER = 'issue-tracker'
LICENSE = 'license'
MAILING_LIST = 'mailing-list'
OTHER = 'other'
RELEASE_NOTES = 'release-notes' # Only supported in >= 1.4
SOCIAL = 'social'
SCM = 'vcs'
SUPPORT = 'support'
VCS = 'vcs'
WEBSITE = 'website'
@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
"""
_INVALID_URI_REGEX = re.compile(r'%(?![0-9A-F]{2})|#.*#', re.IGNORECASE + re.MULTILINE)
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 = uri
@property # type: ignore[misc]
@serializable.json_name('.')
@serializable.xml_name('.')
def uri(self) -> str:
return self._uri
@classmethod
def serialize(cls, o: object) -> str:
if isinstance(o, XsUri):
return str(o)
raise ValueError(f'Attempt to serialize a non-XsUri: {o.__class__}')
@classmethod
def deserialize(cls, o: object) -> 'XsUri':
try:
return XsUri(uri=str(o))
except ValueError:
raise ValueError(f'XsUri string supplied ({o}) does not parse!')
def __eq__(self, other: object) -> bool:
if isinstance(other, XsUri):
return hash(other) == hash(self)
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
@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.3/#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
@property # type: ignore[misc]
@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 # type: ignore[misc]
@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 # type: ignore[misc]
@serializable.view(SchemaVersion1Dot3)
@serializable.view(SchemaVersion1Dot4)
@serializable.xml_array(serializable.XmlArraySerializationType.NESTED, 'hash')
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 __eq__(self, other: object) -> bool:
if isinstance(other, ExternalReference):
return hash(other) == hash(self)
return False
def __lt__(self, other: Any) -> bool:
if isinstance(other, ExternalReference):
return ComparableTuple((self._type, self._url, self._comment)) < \
ComparableTuple((other._type, other._url, other._comment))
return NotImplemented
def __hash__(self) -> int:
return hash((
self._type, self._url, self._comment,
tuple(sorted(self._hashes, key=hash))
))
def __repr__(self) -> str:
return f'<ExternalReference {self.type.name}, {self.url}>'
@serializable.serializable_class
class License:
"""
This is our internal representation of `licenseType` 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.4/xml/#type_licenseType
"""
def __init__(self, *, id: Optional[str] = None, name: Optional[str] = None,
text: Optional[AttachedText] = None, url: Optional[XsUri] = None) -> None:
if not id and not name:
raise MutuallyExclusivePropertiesException('Either `id` or `name` MUST be supplied')
if id and name:
warnings.warn(
'Both `id` and `name` have been supplied - `name` will be ignored!',
RuntimeWarning
)
self.id = id
if not id:
self.name = name
else:
self.name = None
self.text = text
self.url = url
@property
def id(self) -> Optional[str]:
"""
A valid SPDX license ID
Returns:
`str` or `None`
"""
return self._id
@id.setter
def id(self, id: Optional[str]) -> None:
self._id = id
@property
def name(self) -> Optional[str]:
"""
If SPDX does not define the license used, this field may be used to provide the license name.
Returns:
`str` or `None`
"""
return self._name
@name.setter
def name(self, name: Optional[str]) -> None:
self._name = name
@property
def text(self) -> Optional[AttachedText]:
"""
Specifies the optional full text of the attachment
Returns:
`AttachedText` else `None`
"""
return self._text
@text.setter
def text(self, text: Optional[AttachedText]) -> None:
self._text = text
@property
def url(self) -> Optional[XsUri]:
"""
The URL to the attachment file. If the attachment is a license or BOM, an externalReference should also be
specified for completeness.
Returns:
`XsUri` or `None`
"""
return self._url
@url.setter
def url(self, url: Optional[XsUri]) -> None:
self._url = url
def __eq__(self, other: object) -> bool:
if isinstance(other, License):
return hash(other) == hash(self)
return False
def __lt__(self, other: Any) -> bool:
if isinstance(other, License):
return ComparableTuple((self.id, self.name)) < ComparableTuple((other.id, other.name))
return NotImplemented
def __hash__(self) -> int:
return hash((self.id, self.name, self.text, self.url))
def __repr__(self) -> str:
return f'<License id={self.id}, name={self.name}>'
@serializable.serializable_class
class LicenseChoice:
"""
This is our internal representation of `licenseChoiceType` 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.4/xml/#type_licenseChoiceType
"""
def __init__(self, *, license: Optional[License] = None, expression: Optional[str] = None) -> None:
if not license and not expression:
raise NoPropertiesProvidedException(
'One of `license` or `expression` must be supplied - neither supplied'
)
if license and expression:
warnings.warn(
'Both `license` and `expression` have been supplied - `license` will take precedence',
RuntimeWarning
)
self.license = license
if not license:
self.expression = expression
else:
self.expression = None
@property
def license(self) -> Optional[License]:
"""
License definition
Returns:
`License` or `None`
"""
return self._license
@license.setter
def license(self, license: Optional[License]) -> None:
self._license = license
@property
def expression(self) -> Optional[str]:
"""
A valid SPDX license expression (not enforced).
Refer to https://spdx.org/specifications for syntax requirements.
Returns:
`str` or `None`
"""
return self._expression
@expression.setter
def expression(self, expression: Optional[str]) -> None:
self._expression = expression
def __eq__(self, other: object) -> bool:
if isinstance(other, LicenseChoice):
return hash(other) == hash(self)
return False
def __lt__(self, other: Any) -> bool:
if isinstance(other, LicenseChoice):
return ComparableTuple((self.license, self.expression)) < ComparableTuple(
(other.license, other.expression))
return NotImplemented
def __hash__(self) -> int:
return hash((self.license, self.expression))
def __repr__(self) -> str:
return f'<LicenseChoice license={self.license}, expression={self.expression}>'
@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.4/xml/#type_propertyType
Specifies an individual property with a name and value.
"""
def __init__(self, *, name: str, value: str) -> None:
self.name = name
self.value = value
@property # type: ignore[misc]
@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 # type: ignore[misc]
@serializable.xml_name('.')
def value(self) -> str:
"""
Value of this Property.
Returns:
`str`
"""
return self._value
@value.setter
def value(self, value: str) -> None:
self._value = value
def __eq__(self, other: object) -> bool:
if isinstance(other, Property):
return hash(other) == hash(self)
return False
def __lt__(self, other: Any) -> bool:
if isinstance(other, Property):
return ComparableTuple((self.name, self.value)) < ComparableTuple((other.name, other.value))
return NotImplemented
def __hash__(self) -> int:
return hash((self.name, self.value))
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.4/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 # type: ignore[misc]
@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 # type: ignore[misc]
@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 # type: ignore[misc]
@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 __eq__(self, other: object) -> bool:
if isinstance(other, NoteText):
return hash(other) == hash(self)
return False
def __lt__(self, other: Any) -> bool:
if isinstance(other, NoteText):
return ComparableTuple((self.content, self.content_type, self.encoding)) < \
ComparableTuple((other.content, other.content_type, other.encoding))
return NotImplemented
def __hash__(self) -> int:
return hash((self.content, self.content_type, self.encoding))
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.4/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 # type: ignore[misc]
@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}' is not a valid locale. "
f"Locale string should be formatted as the ISO-639 (or higher) language code and optional "
f"ISO-3166 (or higher) country code. according to ISO-639 format. Examples include: 'en', 'en-US'."
)
def __eq__(self, other: object) -> bool:
if isinstance(other, Note):
return hash(other) == hash(self)
return False
def __lt__(self, other: Any) -> bool:
if isinstance(other, Note):
return ComparableTuple((self.locale, self.text)) < ComparableTuple((other.locale, other.text))
return NotImplemented
def __hash__(self) -> int:
return hash((self.text, self.locale))
def __repr__(self) -> str:
return f'<Note id={id(self)}, locale={self.locale}>'
@serializable.serializable_class
class OrganizationalContact:
"""
This is our internal representation of the `organizationalContact` 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.4/xml/#type_organizationalContact
"""
def __init__(self, *, name: Optional[str] = None, phone: Optional[str] = None, email: Optional[str] = None) -> None:
if not name and not phone and not email:
raise NoPropertiesProvidedException(
'One of name, email or phone must be supplied for an OrganizationalContact - none supplied.'