-
-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathmodels.py
More file actions
2557 lines (2179 loc) · 88.1 KB
/
models.py
File metadata and controls
2557 lines (2179 loc) · 88.1 KB
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
#
# Copyright (c) nexB Inc. and others. All rights reserved.
# DejaCode is a trademark of nexB Inc.
# SPDX-License-Identifier: AGPL-3.0-only
# See https://github.com/aboutcode-org/dejacode for support or download.
# See https://aboutcode.org for more information about AboutCode FOSS projects.
#
import logging
import re
from contextlib import suppress
from urllib.parse import quote_plus
from django.contrib.postgres.fields import ArrayField
from django.core import validators
from django.core.exceptions import MultipleObjectsReturned
from django.core.exceptions import ObjectDoesNotExist
from django.core.exceptions import ValidationError
from django.core.validators import EMPTY_VALUES
from django.db import models
from django.db.models import CharField
from django.db.models import Count
from django.db.models import Exists
from django.db.models import OuterRef
from django.db.models.functions import Concat
from django.dispatch import receiver
from django.template.defaultfilters import filesizeformat
from django.utils.functional import cached_property
from django.utils.html import format_html
from django.utils.text import format_lazy
from django.utils.text import get_valid_filename
from django.utils.text import normalize_newlines
from django.utils.translation import gettext_lazy as _
from attributecode.model import About
from cyclonedx import model as cyclonedx_model
from cyclonedx.model import component as cyclonedx_component
from cyclonedx.model import contact as cyclonedx_contact
from cyclonedx.model import license as cyclonedx_license
from license_expression import ExpressionError
from packageurl import PackageURL
from packageurl.contrib import purl2url
from packageurl.contrib import url2purl
from packageurl.contrib.django.models import PackageURLMixin
from packageurl.contrib.django.models import PackageURLQuerySetMixin
from packageurl.contrib.django.utils import without_empty_values
from component_catalog.license_expression_dje import build_licensing
from component_catalog.license_expression_dje import get_expression_as_spdx
from component_catalog.license_expression_dje import get_license_objects
from component_catalog.license_expression_dje import parse_expression
from component_catalog.license_expression_dje import render_expression_as_html
from dejacode_toolkit import spdx
from dejacode_toolkit.download import DataCollectionException
from dejacode_toolkit.download import collect_package_data
from dejacode_toolkit.purldb import PurlDB
from dejacode_toolkit.purldb import pick_purldb_entry
from dje import urn
from dje.copier import post_copy
from dje.copier import post_update
from dje.fields import JSONListField
from dje.fields import NoStripTextField
from dje.models import DataspacedManager
from dje.models import DataspacedModel
from dje.models import DataspacedQuerySet
from dje.models import ExternalReferenceMixin
from dje.models import History
from dje.models import HistoryFieldsMixin
from dje.models import ParentChildModelMixin
from dje.models import ParentChildRelationshipModel
from dje.models import ReferenceNotesMixin
from dje.tasks import logger as tasks_logger
from dje.utils import is_purl_str
from dje.utils import set_fields_from_object
from dje.validators import generic_uri_validator
from dje.validators import validate_url_segment
from dje.validators import validate_version
from license_library.models import License
from license_library.models import LicenseChoice
from policy.models import SetPolicyFromLicenseMixin
from policy.models import UsagePolicyMixin
from vulnerabilities.models import AffectedByVulnerabilityMixin
from vulnerabilities.models import AffectedByVulnerabilityRelationship
from workflow.models import RequestMixin
logger = logging.getLogger("dje")
COMPONENT_PACKAGE_COMMON_FIELDS = [
"copyright",
"dependencies",
"description",
"holder",
"homepage_url",
"license_expression",
"name",
"notice_text",
"primary_language",
"release_date",
"version",
]
LICENSE_EXPRESSION_HELP_TEXT = _(
"The License Expression assigned to a DejaCode Package or Component is an editable "
'value equivalent to a "concluded license" as determined by a curator who has '
"performed analysis to clarify or correct the declared license expression, which "
"may have been assigned automatically (from a scan or an associated package "
"definition) when the Package or Component was originally created. "
"A license expression defines the relationship of one or more licenses to a "
"software object. More than one applicable license can be expressed as "
'"license-key-a AND license-key-b". A choice of applicable licenses can be '
'expressed as "license-key-a OR license-key-b", and you can indicate the primary '
"(preferred) license by placing it first, on the left-hand side of the OR "
"relationship. The relationship words (OR, AND) can be combined as needed, "
"and the use of parentheses can be applied to clarify the meaning; "
'for example "((license-key-a AND license-key-b) OR (license-key-c))". '
"An exception to a license can be expressed as "
'"license-key WITH license-exception-key".'
)
class PackageAlreadyExistsWarning(Exception):
def __init__(self, message):
self.message = message
def validate_filename(value):
invalid_chars = ["/", "\\", ":"]
if any(char in value for char in invalid_chars):
raise ValidationError(
_("Enter a valid filename: slash, backslash, or colon are not allowed.")
)
class VulnerabilityQuerySetMixin:
def with_vulnerability_count(self):
"""Annotate the QuerySet with the vulnerability_count."""
return self.annotate(
vulnerability_count=Count("affected_by_vulnerabilities", distinct=True)
)
def vulnerable(self):
"""Return vulnerable Packages."""
return self.with_vulnerability_count().filter(vulnerability_count__gt=0)
class LicenseExpressionMixin:
"""Model mixin for models that store license expressions."""
def _get_licensing(self):
"""Return a Licensing object built from the assigned licenses."""
# WARNING: Do not apply select/prefect_related here but on the main QuerySet instead
# For example: prefetch_related('component_set__licenses__dataspace')
return build_licensing(self.licenses.all())
licensing = cached_property(_get_licensing)
def _get_normalized_expression(self):
"""
Return this object ``license_expression`` field value as a normalized parsed
expression object.
"""
if self.license_expression:
return parse_expression(
self.license_expression,
licenses=self.licensing,
validate_known=False,
validate_strict=False,
)
normalized_expression = cached_property(_get_normalized_expression)
def get_license_expression(self, template="{symbol.key}", as_link=False, show_policy=False):
"""
Validate and Return the license_expression value set on this instance.
The license expression is NOT validated for known symbols.
Use the `template` format string to render each license in the expression.
if `as_link` is True, render the expression as a link.
"""
if self.license_expression:
rendered = self.normalized_expression.render_as_readable(
template,
as_link=as_link,
show_policy=show_policy,
)
return format_html(rendered)
def get_license_expression_attribution(self):
# note: the fields use in the template must be available as attributes or
# properties on a License.
template = '<a href="#license_{symbol.key}">{symbol.short_name}</a>'
return self.get_license_expression(template)
license_expression_attribution = cached_property(get_license_expression_attribution)
def get_license_expression_linked(self):
return self.get_license_expression(as_link=True)
license_expression_linked = cached_property(get_license_expression_linked)
def get_license_expression_linked_with_policy(self):
license_expression = self.get_license_expression(as_link=True, show_policy=True)
if license_expression:
return format_html('<span class="license-expression">{}</span>', license_expression)
def _get_primary_license(self):
"""
Return the primary license key of this instance or None. The primary license is
the left most license of the expression. It can be the combination of a
license WITH an exception and therefore may contain more than one key.
WARNING: This does not support exception as primary_license.
"""
if self.license_expression:
licensing = build_licensing()
return licensing.primary_license_key(self.license_expression)
primary_license = cached_property(_get_primary_license)
def get_expression_as_spdx(self, expression):
"""
Return the license_expression formatted for SPDX compatibility.
This includes a workaround for a SPDX spec limitation, where license exceptions
that do not exist in the SPDX list cannot be provided as "LicenseRef-" in the
"hasExtractedLicensingInfos".
The current fix is to use AND rather than WITH for any exception that is a
"LicenseRef-".
See discussion at https://github.com/spdx/tools-java/issues/73
"""
if not expression:
return
try:
expression_as_spdx = get_expression_as_spdx(expression, self.dataspace)
except ExpressionError as e:
return str(e)
if expression_as_spdx:
return expression_as_spdx.replace("WITH LicenseRef-", "AND LicenseRef-")
@property
def concluded_license_expression_spdx(self):
return self.get_expression_as_spdx(self.license_expression)
@property
def license_expression_html(self):
if self.license_expression:
return render_expression_as_html(self.license_expression, self.dataspace)
def save(self, *args, **kwargs):
"""
Call the handle_assigned_licenses method on save, except during copy.
During copy, as some Licenses referenced by the license_expression may not exists in the
target Dataspace yet, the handle_assigned_licenses() would not be able to create the
proper assignments and the UUID of those assignments would not be shared with
reference Dataspace.
Thus, the handle_assigned_licenses() is skipped during the copy process and the
License assignments are handled by the m2m copy.
"""
super().save(*args, **kwargs)
self.handle_assigned_licenses(copy=kwargs.get("copy"))
def handle_assigned_licenses(self, copy=False):
"""
Create missing AssignedLicense instances and deletes the ones non-referenced
in the license_expression.
In `copy` mode, all the license assignments are deleted to avoid any conflicts
during the copy/update process where all the assignments are properly created.
"""
licenses_field = self._meta.get_field("licenses")
AssignedLicense = licenses_field.remote_field.through
# Looking for the FK field name, on the AssignedLicense, that points to this Model
fk_field_name = [
field
for field in AssignedLicense._meta.get_fields()
if field.many_to_one and field.concrete and field.related_model == self.__class__
]
if len(fk_field_name) != 1:
return
fk_field_name = fk_field_name[0].name
assigned_license_qs = AssignedLicense.objects.filter(
**{"dataspace": self.dataspace, fk_field_name: self}
)
if copy:
# Deletes all existing license assignments to ensure UUID integrity
# as the licenses will be properly assigned during the copy/update process
assigned_license_qs.delete()
return
# Get the full list of licenses is required here for proper
# validation. We cannot rely on the assigned licenses since we
# are modifying those assignments.
all_licenses = License.objects.scope(self.dataspace).for_expression()
licenses = get_license_objects(self.license_expression, all_licenses)
for license_instance in licenses:
AssignedLicense.objects.get_or_create(
**{
"dataspace": self.dataspace,
fk_field_name: self,
"license": license_instance,
}
)
assigned_license_qs.exclude(license__in=licenses).delete()
@cached_property
def license_choices_expression(self):
"""Return the license choices as an expression."""
return LicenseChoice.objects.get_choices_expression(self.license_expression, self.dataspace)
@cached_property
def has_license_choices(self):
"""Return `True` if applying the LicenseChoice results in a new expression."""
return self.license_expression != self.license_choices_expression
@property
def attribution_required(self):
return any(license.attribution_required for license in self.licenses.all())
@property
def redistribution_required(self):
return any(license.redistribution_required for license in self.licenses.all())
@property
def change_tracking_required(self):
return any(license.change_tracking_required for license in self.licenses.all())
@cached_property
def compliance_alerts(self):
"""
Return the list of all existing `compliance_alert` through this license
`usage_policy`.
"""
return [
license.usage_policy.compliance_alert
for license in self.licenses.all()
if license.usage_policy_id and license.usage_policy.compliance_alert
]
def compliance_table_class(self):
"""Return a CSS class for a table row based on the licenses `compliance_alerts`."""
if "error" in self.compliance_alerts:
return "table-danger"
elif "warning" in self.compliance_alerts:
return "table-warning"
class LicenseFieldsMixin(models.Model):
declared_license_expression = models.TextField(
blank=True,
help_text=_(
"A license expression derived from statements in the manifests or key "
"files of a software project, such as the NOTICE, COPYING, README, and "
"LICENSE files."
),
)
other_license_expression = models.TextField(
blank=True,
help_text=_(
"A license expression derived from detected licenses in the non-key files "
"of a software project, which are often third-party software used by the "
"project, or test, sample and documentation files."
),
)
class Meta:
abstract = True
@property
def declared_license_expression_spdx(self):
return self.get_expression_as_spdx(self.declared_license_expression)
@property
def other_license_expression_spdx(self):
return self.get_expression_as_spdx(self.other_license_expression)
def get_cyclonedx_properties(instance):
"""
Return fields not supported natively by CycloneDX as properties.
Those fields are required to load the BOM without major data loss.
See https://github.com/nexB/aboutcode-cyclonedx-taxonomy
"""
property_prefix = "aboutcode"
property_fields = [
"filename", # package-only
"download_url", # package-only
"primary_language",
"homepage_url",
"notice_text",
]
properties = [
cyclonedx_model.Property(name=f"{property_prefix}:{field_name}", value=value)
for field_name in property_fields
if (value := getattr(instance, field_name, None)) not in EMPTY_VALUES
]
return properties
class HolderMixin(models.Model):
"""Add the `holder` field."""
holder = models.TextField(
blank=True,
help_text=_(
"The name(s) of the copyright holder(s) of a software package as documented in the "
"code. This field is intended to record the copyright holder independently of "
"copyright statement dates and formats, and generally corresponds to the owner of "
"the associated software project."
),
)
class Meta:
abstract = True
class KeywordsMixin(models.Model):
"""Add the `keywords` field."""
keywords = JSONListField(
blank=True,
help_text=_(
"A keyword is a category or label that helps you to find items "
"for particular requirements."
),
)
class Meta:
abstract = True
class CPEMixin(models.Model):
"""Add the `cpe` field."""
cpe = models.CharField(
_("CPE"),
blank=True,
max_length=1024,
help_text=_(
"Common Platform Enumeration (CPE) is a standardized method of describing and "
"identifying a computing asset. CPE does not necessarily identify a unique instance "
"or version of a computing asset. For example, a CPE could identify a component name "
"with a version range."
),
)
class Meta:
abstract = True
def get_spdx_cpe_external_ref(self):
if self.cpe:
return spdx.ExternalRef(
category="SECURITY",
type="cpe23Type",
locator=self.cpe,
)
class URLFieldsMixin(models.Model):
homepage_url = models.URLField(
_("Homepage URL"),
max_length=1024,
blank=True,
help_text=_("Homepage URL."),
)
# The URLField validation is too strict to support values like git://
vcs_url = models.CharField(
_("VCS URL"),
max_length=1024,
validators=[generic_uri_validator],
blank=True,
help_text=_("URL to the Version Control System (VCS)."),
)
code_view_url = models.URLField(
_("Code view URL"),
max_length=1024,
blank=True,
help_text=_("A URL that allows you to browse and view the source code online."),
)
bug_tracking_url = models.URLField(
_("Bug tracking URL"),
max_length=1024,
blank=True,
help_text=_("A URL to the bug reporting system."),
)
class Meta:
abstract = True
class HashFieldsMixin(models.Model):
"""
The hash fields are not indexed by default, use the `indexes` in Meta as needed:
class Meta:
indexes = [
models.Index(fields=['md5']),
models.Index(fields=['sha1']),
models.Index(fields=['sha256']),
models.Index(fields=['sha512']),
]
"""
md5 = models.CharField(
_("MD5"),
max_length=32,
blank=True,
help_text=_("MD5 checksum hex-encoded, as in md5sum."),
)
sha1 = models.CharField(
_("SHA1"),
max_length=40,
blank=True,
help_text=_("SHA1 checksum hex-encoded, as in sha1sum."),
)
sha256 = models.CharField(
_("SHA256"),
max_length=64,
blank=True,
help_text=_("SHA256 checksum hex-encoded, as in sha256sum."),
)
sha512 = models.CharField(
_("SHA512"),
max_length=128,
blank=True,
help_text=_("SHA512 checksum hex-encoded, as in sha512sum."),
)
class Meta:
abstract = True
class ComponentType(DataspacedModel):
label = models.CharField(
max_length=50,
help_text=_(
"Label that indicates the scope, function, and complexity of a component. "
"Every dataspace has its own list of component types. Examples include: "
"product, package, project, assembly, module, platform, directory, file, snippet."
),
)
notes = models.TextField(
blank=True,
help_text=_("Optional descriptive text."),
)
class Meta:
unique_together = (("dataspace", "label"), ("dataspace", "uuid"))
ordering = ["label"]
def __str__(self):
return self.label
CONFIGURATION_STATUS_HELP = _(
"The configuration status can be used to communicate the current stage of the review process "
"and whether additional review is required."
)
class DefaultOnAdditionManager(DataspacedManager):
def get_default_on_addition_qs(self, dataspace):
"""
Return the QuerySet with default_on_addition=True scoped to the given `dataspace`.
The QS count should be 0 or 1 max.
"""
return self.scope(dataspace).filter(default_on_addition=True)
class DefaultOnAdditionFieldMixin(models.Model):
default_on_addition = models.BooleanField(
_("Default on addition"),
default=False,
help_text=_(
"Indicates this instance is automatically assigned by the "
"application to an object when it is initially created."
),
)
objects = DefaultOnAdditionManager()
class Meta:
abstract = True
def save(self, *args, **kwargs):
"""
Make sure only one default_on_addition is set to True per Dataspace by forcing False
for default_on_addition on any other instance.
Note that this cannot be done in clean() as the dataspace will not have
been set on the instance yet.
"""
if self.default_on_addition:
qs = self.__class__.objects.get_default_on_addition_qs(self.dataspace)
qs.update(default_on_addition=False)
super().save(*args, **kwargs)
class BaseStatusMixin(DefaultOnAdditionFieldMixin, models.Model):
label = models.CharField(
max_length=50,
help_text=_("Concise name to identify the status."),
)
text = models.TextField(
help_text=_("Descriptive text to define the status purpose precisely."),
)
class Meta:
abstract = True
unique_together = (("dataspace", "label"), ("dataspace", "uuid"))
ordering = ["label"]
def __str__(self):
return self.label
class DefaultOnAdditionMixin:
def save(self, *args, **kwargs):
"""
Set the default Status on ADDITION, if a Status instance was set as default.
Note that this cannot be done in clean() as the dataspace will not be
set on the instance yet.
"""
is_addition = not self.pk
if is_addition:
default_on_addition_fields = [
field
for field in self._meta.get_fields()
if field.is_relation
and issubclass(field.related_model, DefaultOnAdditionFieldMixin)
]
for on_addition_field in default_on_addition_fields:
if not getattr(self, on_addition_field.name):
related_model = on_addition_field.related_model
default = related_model.objects.get_default_on_addition_qs(
self.dataspace
).first()
setattr(self, on_addition_field.name, default)
super().save(*args, **kwargs)
class ComponentStatus(BaseStatusMixin, DataspacedModel):
class Meta(BaseStatusMixin.Meta):
verbose_name_plural = _("component status")
def component_mixin_factory(verbose_name):
"""
Return a BaseComponentMixin class suitable for Component and Product.
This factory logic is required to inject a variable verbose name in the help_text.
"""
class BaseComponentMixin(
DefaultOnAdditionMixin,
LicenseExpressionMixin,
URLFieldsMixin,
RequestMixin,
HistoryFieldsMixin,
models.Model,
):
"""Component and Product common Model fields."""
name = models.CharField(
db_index=True,
max_length=100,
help_text=format_lazy(
"Name by which the {verbose_name} is commonly referenced.",
verbose_name=_(verbose_name),
),
validators=[validate_url_segment],
)
version = models.CharField(
db_index=True,
max_length=100,
blank=True,
help_text=format_lazy(
"Identifies a specific version of a {verbose_name}. The combination of "
"name + version uniquely identifies a {verbose_name}. If the version is "
"(nv) or blank, it signifies an unstated/unknown version (or it indicates "
"that version does not apply to the {verbose_name}), and it does not imply "
"that the information in this {verbose_name} definition applies to any "
"or all possible versions of the {verbose_name}.",
verbose_name=_(verbose_name),
),
validators=[validate_version],
)
owner = models.ForeignKey(
to="organization.Owner",
null=True,
blank=True,
on_delete=models.PROTECT,
help_text=format_lazy(
"Owner is an optional field selected by the user to identify the original "
"creator (copyright holder) of the {verbose_name}. "
"If this {verbose_name} is in its original, unmodified state, the {verbose_name}"
" owner is associated with the original author/publisher. "
"If this {verbose_name} has been copied and modified, "
"the {verbose_name} owner should be the owner that has copied and "
"modified it.",
verbose_name=_(verbose_name),
),
)
release_date = models.DateField(
null=True,
blank=True,
help_text=format_lazy(
"The date that the {verbose_name} was released by its owner.",
verbose_name=_(verbose_name),
),
)
description = models.TextField(
blank=True,
help_text=_("Free form description, preferably as provided by the author(s)."),
)
copyright = models.TextField(
blank=True,
help_text=format_lazy(
"The copyright statement(s) that pertain to this {verbose_name}, as "
"contained in the source or as specified in an associated file.",
verbose_name=_(verbose_name),
),
)
homepage_url = models.URLField(
_("Homepage URL"),
max_length=1024,
blank=True,
help_text=format_lazy(
"Homepage URL for the {verbose_name}.",
verbose_name=_(verbose_name),
),
)
primary_language = models.CharField(
db_index=True,
max_length=50,
blank=True,
help_text=format_lazy(
"The primary programming language associated with the {verbose_name}.",
verbose_name=_(verbose_name),
),
)
admin_notes = models.TextField(
blank=True,
help_text=format_lazy(
"Comments about the {verbose_name}, provided by administrators, "
"intended for viewing and maintenance by administrators only.",
verbose_name=_(verbose_name),
),
)
notice_text = NoStripTextField(
blank=True,
help_text=format_lazy(
"The notice text provided by the authors of a {verbose_name} to identify "
"the copyright statement(s), contributors, and/or license obligations that apply"
" to a {verbose_name}.",
verbose_name=_(verbose_name),
),
)
class Meta:
abstract = True
unique_together = (("dataspace", "name", "version"), ("dataspace", "uuid"))
ordering = ("name", "version")
def __str__(self):
if self.version:
return f"{self.name} {self.version}"
return self.name
def get_url(self, name, params=None):
if not params:
params = [self.dataspace.name, quote_plus(self.name)]
if self.version:
params.append(quote_plus(self.version))
return super().get_url(name, params)
def get_absolute_url(self):
return self.get_url("details")
def get_change_url(self):
return self.get_url("change")
def get_delete_url(self):
return self.get_url("delete")
def get_about_files_url(self):
return self.get_url("about_files")
def get_export_spdx_url(self):
return self.get_url("export_spdx")
def get_export_cyclonedx_url(self):
return self.get_url("export_cyclonedx")
def get_about_files(self):
"""
Return the list of all AboutCode files from all the Packages
related to this instance.
"""
return [
about_file
for package in self.all_packages
for about_file in package.get_about_files()
]
def as_cyclonedx(self, license_expression_spdx=None):
"""Return this Component/Product as an CycloneDX Component entry."""
supplier = None
if self.owner:
supplier = cyclonedx_contact.OrganizationalEntity(
name=self.owner.name,
urls=[self.owner.homepage_url],
)
expression_spdx = license_expression_spdx or self.concluded_license_expression_spdx
licenses = []
if expression_spdx:
# Using the LicenseExpression directly as the make_with_expression method
# does not support the "LicenseRef-" keys.
licenses = [cyclonedx_license.LicenseExpression(value=expression_spdx)]
if self.__class__.__name__ == "Product":
component_type = cyclonedx_component.ComponentType.APPLICATION
else:
component_type = cyclonedx_component.ComponentType.LIBRARY
return cyclonedx_component.Component(
name=self.name,
type=component_type,
version=self.version,
bom_ref=self.cyclonedx_bom_ref,
supplier=supplier,
licenses=licenses,
copyright=self.copyright,
description=self.description,
cpe=getattr(self, "cpe", None),
properties=get_cyclonedx_properties(self),
)
return BaseComponentMixin
BaseComponentMixin = component_mixin_factory("component")
class ComponentQuerySet(VulnerabilityQuerySetMixin, DataspacedQuerySet):
def with_has_hierarchy(self):
subcomponents = Subcomponent.objects.filter(
models.Q(child_id=OuterRef("pk")) | models.Q(parent_id=OuterRef("pk"))
)
return self.annotate(has_hierarchy=Exists(subcomponents))
PROJECT_FIELD_HELP = _(
"Project is a free-form label that you can use to group and find packages and components "
"that interest you; for example, you may be starting a new development project, "
"evaluating them for use in a product or you may want to get approval to use them."
)
class Component(
ReferenceNotesMixin,
UsagePolicyMixin,
SetPolicyFromLicenseMixin,
ExternalReferenceMixin,
HolderMixin,
KeywordsMixin,
CPEMixin,
AffectedByVulnerabilityMixin,
LicenseFieldsMixin,
ParentChildModelMixin,
BaseComponentMixin,
DataspacedModel,
):
license_expression = models.CharField(
_("Concluded license expression"),
max_length=1024,
blank=True,
db_index=True,
help_text=LICENSE_EXPRESSION_HELP_TEXT,
)
configuration_status = models.ForeignKey(
to="component_catalog.ComponentStatus",
on_delete=models.PROTECT,
null=True,
blank=True,
help_text=CONFIGURATION_STATUS_HELP,
)
type = models.ForeignKey(
to="component_catalog.ComponentType",
on_delete=models.PROTECT,
null=True,
blank=True,
help_text=_("A component type provides a label to filter and sort components."),
)
approval_reference = models.CharField(
max_length=200,
blank=True,
help_text=_(
"The name or number of a document (e.g. approval document, contract, etc.) "
"that indicates that the component is approved for use in your organization."
),
)
guidance = models.TextField(
verbose_name=_("Component usage guidance"),
blank=True,
help_text=_(
"Component usage guidance is provided by your organization to specify "
"recommendations, requirements and restrictions regarding your usage of this "
"component.",
),
)
is_active = models.BooleanField(
verbose_name=_("Is active"),
null=True,
db_index=True,
default=True,
help_text=_(
"When set to True (Yes), this field indicates that a component definition in the "
"catalog is currently in use (active). When set to False (No), this field indicates "
"that a component is deprecated (inactive) and should not be used, and the component "
"will not appear in the user views. When the field value is Unknown, the component "
"will not appear in the user views, usually suggesting that the component has not "
"yet been evaluated."
),
)
curation_level = models.PositiveSmallIntegerField(
db_index=True,
default=0,
validators=[validators.MaxValueValidator(100)],
help_text=_(
"A numeric value, from 0 to 100, that indicates the level of completeness of "
"all the pertinent component data, as well as the state of that data being "
'reviewed by a senior administrator. General guidelines: "10" indicates basic '
'data present. "20" indicates copyright and notice data are provided. '
'assigned. "30" indicates all license data are provided. "40" indicates all '
"available technical details (including URLs and primary language) are provided. "
'"50" indicates that relevant parent and child are provided. '
"Any other values are at the discretion of a senior administrative reviewer."
),
)
COMPONENT_FIELDS_WEIGHT = (
("notice_text", 10),
("copyright", 5),
("description", 5),
("packages", 5),
("homepage_url", 5),
("keywords", 5),
("licenses", 5),
("notice_filename", 5),
("notice_url", 5),
("bug_tracking_url", 3),
("code_view_url", 3),
("primary_language", 3),
("release_date", 3),
("vcs_url", 3),
("owner", 2),
("type", 2),
("version", 2),
)
completion_level = models.PositiveSmallIntegerField(
default=0,
db_index=True,
help_text=_(
"Completion level is a number automatically calculated by the application to "
"indicate the completeness of the data for a specific component. Fields that "
"influence the calculation include: Notice Text, Copyright, Description, Package, "
"Homepage URL, Keyword, License, Notice Filename, Notice URL, Bug Tracking URL, "