-
Notifications
You must be signed in to change notification settings - Fork 711
Expand file tree
/
Copy pathmodels.py
More file actions
9670 lines (8598 loc) · 347 KB
/
models.py
File metadata and controls
9670 lines (8598 loc) · 347 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
import json
import os
import re
import hashlib
from datetime import date, datetime
from pathlib import Path
from typing import Self, Union, List, Optional, Literal, Tuple, Final
import statistics
from django.contrib.contenttypes.models import ContentType
from django.utils import timezone
from icecream import ic
from auditlog.registry import auditlog
from django.utils.functional import cached_property
import yaml
from django.apps import apps
from django.core import serializers
from django.core.exceptions import ValidationError
from django.core.validators import (
FileExtensionValidator,
MaxValueValidator,
RegexValidator,
MinValueValidator,
)
from django.core.files.storage import default_storage
from django.db import models, transaction
from django.db.models import F, Q, OuterRef, Subquery, Prefetch, Count
from django.db.models.query import QuerySet
from django.forms.models import model_to_dict
from django.urls import reverse
from django.utils.html import format_html
from django.utils.translation import get_language
from django.utils.translation import gettext_lazy as _
from structlog import get_logger
from django.utils.timezone import now
from iam.models import Folder, FolderMixin, PublishInRootFolderMixin, User
from library.helpers import (
get_referential_translation,
update_translations,
update_translations_as_string,
update_translations_in_object,
)
from core.utils import format_currency as _fmt_currency
from global_settings.models import GlobalSettings
from .base_models import (
AbstractBaseModel,
ActorSyncManager,
ActorSyncMixin,
EditableMixin,
ETADueDateMixin,
NameDescriptionMixin,
)
from .utils import (
camel_case,
is_compute_result_truthy,
sha256,
update_selected_implementation_groups,
_is_question_visible,
_build_answer_context,
)
from .validators import (
validate_file_name,
validate_file_size,
JSONSchemaInstanceValidator,
)
from . import dora
from collections import defaultdict, deque
logger = get_logger(__name__)
def _defer_once(conn_attr: str, key, callback):
"""Schedule *callback* via on_commit, deduplicating by *key* per transaction.
Attaches a pending-set to the DB connection under *conn_attr* so that only
the first call per *key* in a given transaction actually registers the
on_commit hook.
"""
conn = transaction.get_connection()
pending = getattr(conn, conn_attr, None)
if pending is None:
pending = set()
setattr(conn, conn_attr, pending)
if key not in pending:
pending.add(key)
def _on_commit(k=key, p=pending, cb=callback):
p.discard(k)
cb()
transaction.on_commit(_on_commit)
URN_REGEX = r"^urn:([a-zA-Z0-9_-]+):([a-zA-Z0-9_-]+):([a-zA-Z0-9_-]+)(?::([a-zA-Z0-9_-]+))?:([0-9A-Za-z\[\]\(\)\-\._:]+)$"
def match_urn(urn_string):
match = re.match(URN_REGEX, urn_string)
if match:
return match.groups() # Returns all captured groups from the regex match
else:
return None
def _create_questions_from_data(requirement_node, questions_data):
"""Create Question and QuestionChoice objects from the old JSON questions format.
Args:
requirement_node: RequirementNode instance
questions_data: dict keyed by question URN with type, text, choices, etc.
"""
from core.models import Question, QuestionChoice
questions_to_create = []
choices_data_per_question = [] # parallel list: choices data for each question
for order, (q_urn, q_data) in enumerate(questions_data.items()):
raw_type = q_data.get("type", "text")
q_type = "unique_choice" if raw_type == "single_choice" else raw_type
parts = q_urn.split(":")
q_ref_id = parts[-1] if parts else q_urn
question_text = q_data.get("text", "")
questions_to_create.append(
Question(
requirement_node=requirement_node,
urn=q_urn,
ref_id=q_ref_id,
text=question_text,
annotation=q_data.get("annotation", question_text),
type=q_type,
config=q_data.get("config"),
depends_on=q_data.get("depends_on"),
order=order,
weight=q_data.get("weight", 1),
folder=requirement_node.folder,
is_published=True,
translations=q_data.get("translations"),
)
)
choices_data_per_question.append(q_data.get("choices", []))
created_questions = Question.objects.bulk_create(questions_to_create)
choices_to_create = []
for question, choices_data in zip(created_questions, choices_data_per_question):
for c_order, choice in enumerate(choices_data):
c_urn = choice.get("urn") or None
c_parts = c_urn.split(":") if c_urn else []
c_ref_id = c_parts[-1] if c_parts else None
compute_result = choice.get("compute_result")
if compute_result is not None:
compute_result = str(compute_result).lower()
choice_value = choice.get("value", "")
choices_to_create.append(
QuestionChoice(
question=question,
urn=c_urn,
ref_id=c_ref_id,
value=choice_value,
annotation=choice.get("annotation", choice_value),
add_score=choice.get("add_score"),
compute_result=compute_result,
order=c_order,
description=choice.get("description"),
color=choice.get("color"),
select_implementation_groups=choice.get(
"select_implementation_groups"
),
folder=requirement_node.folder,
is_published=True,
translations=choice.get("translations"),
)
)
if choices_to_create:
QuestionChoice.objects.bulk_create(choices_to_create)
def _sync_questions_from_data(requirement_node, questions_data):
"""Sync Question and QuestionChoice objects for a RequirementNode.
For new nodes this behaves like a pure create. For existing nodes it
upserts questions by URN and choices by ref_id, then prunes stale rows.
"""
from core.models import Question, QuestionChoice
existing_questions = {
q.urn: q for q in requirement_node.questions.prefetch_related("choices").all()
}
incoming_urns = set()
for order, (q_urn, q_data) in enumerate(questions_data.items()):
incoming_urns.add(q_urn)
raw_type = q_data.get("type", "text")
q_type = "unique_choice" if raw_type == "single_choice" else raw_type
parts = q_urn.split(":")
q_ref_id = parts[-1] if parts else q_urn
question_text = q_data.get("text", "")
question_fields = {
"ref_id": q_ref_id,
"text": question_text,
"annotation": q_data.get("annotation", question_text),
"type": q_type,
"config": q_data.get("config"),
"depends_on": q_data.get("depends_on"),
"order": order,
"weight": q_data.get("weight", 1),
"translations": q_data.get("translations"),
}
if q_urn in existing_questions:
question = existing_questions[q_urn]
for attr, value in question_fields.items():
setattr(question, attr, value)
question.save()
else:
question = Question.objects.create(
requirement_node=requirement_node,
urn=q_urn,
folder=requirement_node.folder,
is_published=True,
**question_fields,
)
# --- sync choices ---
existing_choices_by_urn = {}
existing_null_choices = []
for c in question.choices.all():
if c.urn is not None:
existing_choices_by_urn[c.urn] = c
else:
existing_null_choices.append(c)
incoming_urns_choices = set()
incoming_null_count = 0
incoming_choices = q_data.get("choices", [])
# 1. Collect incoming URNs
for choice in incoming_choices:
c_urn = choice.get("urn") or None
if c_urn:
incoming_urns_choices.add(c_urn)
# 2. Delete choices with URNs no longer in incoming data
stale_urns_choices = set(existing_choices_by_urn.keys()) - incoming_urns_choices
if stale_urns_choices:
question.choices.filter(urn__in=stale_urns_choices).delete()
# 3. Replace null-ref_id choices: delete old ones BEFORE creating new ones
if existing_null_choices:
question.choices.filter(
pk__in=[c.pk for c in existing_null_choices]
).delete()
# 4. Create/Update choices
for c_order, choice in enumerate(incoming_choices):
c_urn = choice.get("urn") or None
c_parts = c_urn.split(":") if c_urn else []
c_ref_id = c_parts[-1] if c_parts else None
compute_result = choice.get("compute_result")
if compute_result is not None:
compute_result = str(compute_result).lower()
choice_value = choice.get("value", "")
choice_fields = {
"value": choice_value,
"annotation": choice.get("annotation", choice_value),
"add_score": choice.get("add_score"),
"compute_result": compute_result,
"order": c_order,
"description": choice.get("description"),
"color": choice.get("color"),
"select_implementation_groups": choice.get(
"select_implementation_groups"
),
"translations": choice.get("translations"),
"ref_id": c_ref_id,
}
if c_urn is not None:
if c_urn in existing_choices_by_urn:
existing_choice = existing_choices_by_urn[c_urn]
for attr, value in choice_fields.items():
setattr(existing_choice, attr, value)
existing_choice.save()
else:
QuestionChoice.objects.create(
question=question,
urn=c_urn,
folder=requirement_node.folder,
is_published=True,
**choice_fields,
)
else:
incoming_null_count += 1
QuestionChoice.objects.create(
question=question,
urn=None,
folder=requirement_node.folder,
is_published=True,
**choice_fields,
)
# Delete questions whose URNs are no longer in the incoming data
stale_urns = set(existing_questions.keys()) - incoming_urns
if stale_urns:
Question.objects.filter(
requirement_node=requirement_node, urn__in=stale_urns
).delete()
########################### Referential objects #########################
class ReferentialObjectMixin(AbstractBaseModel, FolderMixin):
"""
Mixin for referential objects.
"""
urn = models.CharField(
max_length=255, null=True, blank=True, unique=True, verbose_name=_("URN")
)
ref_id = models.CharField( # Should this field be nullable ?
max_length=100, blank=True, null=True, verbose_name=_("Reference ID")
)
provider = models.CharField(
max_length=200, blank=True, null=True, verbose_name=_("Provider")
)
name = models.CharField(
null=True, max_length=200, verbose_name=_("Name"), unique=False
)
description = models.TextField(null=True, blank=True, verbose_name=_("Description"))
annotation = models.TextField(null=True, blank=True, verbose_name=_("Annotation"))
translations = models.JSONField(
null=True, blank=True, verbose_name=_("Translations")
)
class Meta:
abstract = True
@property
def node_id(self) -> str | None:
from core.utils import extract_node_id
return extract_node_id(self.urn)
@property
def get_name_translated(self) -> str:
translations = self.translations if self.translations else {}
locale_translations = translations.get(get_language(), {})
return locale_translations.get("name", self.name)
@property
def get_description_translated(self) -> str:
translations = self.translations if self.translations else {}
locale_translations = translations.get(get_language(), {})
return locale_translations.get("description", self.description)
@property
def get_annotation_translated(self) -> str:
translations = self.translations if self.translations else {}
locale_translations = translations.get(get_language(), {})
return locale_translations.get("annotation", self.annotation)
@property
def display_short(self) -> str:
_name = (
self.ref_id
if not self.get_name_translated
else self.get_name_translated
if not self.ref_id
else f"{self.ref_id} - {self.get_name_translated}"
)
_name = "" if not _name else _name
return _name
@property
def display_long(self) -> str:
_name = self.display_short
_display = (
_name
if not self.get_description_translated
else self.get_description_translated
if _name == ""
else f"{_name}: {self.get_description_translated}"
)
return _display
def __str__(self) -> str:
return self.display_short
class I18nObjectMixin(models.Model):
locale = models.CharField(
max_length=100, null=False, blank=False, default="en", verbose_name=_("Locale")
)
default_locale = models.BooleanField(default=True, verbose_name=_("Default locale"))
class Meta:
abstract = True
class FilteringLabel(FolderMixin, AbstractBaseModel, PublishInRootFolderMixin):
label = models.CharField(
max_length=100,
verbose_name=_("Label"),
validators=[
RegexValidator(
regex=r"^[\w-]{1,36}$",
message="invalidLabel",
code="invalid_label",
)
],
)
def __str__(self) -> str:
return self.label
fields_to_check = ["label"]
class FilteringLabelMixin(models.Model):
filtering_labels = models.ManyToManyField(
FilteringLabel, blank=True, verbose_name=_("Labels")
)
class Meta:
abstract = True
class LibraryFilteringLabel(FolderMixin, AbstractBaseModel, PublishInRootFolderMixin):
@property
def reference_count(self) -> int:
return self.stored_libraries.count()
def garbage_collect(self) -> bool:
"""Delete the object if it's not being used (self.reference_count == 0).
Return True if the object was deleted, otherwise return false."""
if self.reference_count > 0:
return False
self.delete()
return True
label = models.CharField(
max_length=100,
verbose_name=_("Label"),
validators=[
RegexValidator(
regex=r"^[\w-]{1,36}$",
message="invalidLabel",
code="invalid_label",
)
],
)
def __str__(self) -> str:
return self.label
fields_to_check = ["label"]
class LibraryMixin(ReferentialObjectMixin, I18nObjectMixin):
class Meta:
abstract = True
unique_together = [["urn", "locale", "version"]]
urn = models.CharField(max_length=255, null=True, blank=True, verbose_name=_("URN"))
copyright = models.CharField(
max_length=4096, null=True, blank=True, verbose_name=_("Copyright")
)
version = models.IntegerField(null=False, verbose_name=_("Version"))
packager = models.CharField(
max_length=100,
blank=True,
null=True,
help_text=_("Packager of the library"),
verbose_name=_("Packager"),
)
publication_date = models.DateField(null=True)
builtin = models.BooleanField(default=False)
objects_meta = models.JSONField(default=dict)
dependencies = models.JSONField(
null=True
) # models.CharField(blank=False,null=True,max_length=16384)
@property
def get_locales(self):
return (
[self.locale] + list(self.translations.keys())
if self.translations
else [self.locale]
)
class Severity(models.IntegerChoices):
UNDEFINED = -1, "undefined"
INFO = 0, "info"
LOW = 1, "low"
MEDIUM = 2, "medium"
HIGH = 3, "high"
CRITICAL = 4, "critical"
class StoredLibrary(LibraryMixin):
filtering_labels = models.ManyToManyField(
LibraryFilteringLabel,
blank=True,
verbose_name=_("Labels"),
related_name="stored_libraries",
)
is_loaded = models.BooleanField(default=False)
hash_checksum = models.CharField(max_length=64)
content = models.JSONField()
autoload = models.BooleanField(
default=False,
help_text="If set to true, the library will be automatically loaded on migrate.",
)
REQUIRED_FIELDS = {"urn", "name", "version", "objects"}
FIELDS_VERIFIERS = {}
# For now a library isn't updated if its SHA256 checksum has already been registered in the database.
HASH_CHECKSUM_SET = set()
@classmethod
def __init_class__(cls):
cls.HASH_CHECKSUM_SET = set(
value["hash_checksum"] for value in cls.objects.values("hash_checksum")
)
@classmethod
def store_library_content(
cls, library_content: bytes, builtin: bool = False, dry_run: bool = False
) -> Tuple[Optional[Union["StoredLibrary", dict]], Optional[str]]:
hash_checksum = sha256(library_content)
if not dry_run and hash_checksum in StoredLibrary.HASH_CHECKSUM_SET:
# We do not store the library if its hash checksum is in the database.
return None, "libraryAlreadyLoadedError"
try:
library_data = yaml.safe_load(library_content)
if not isinstance(library_data, dict):
raise yaml.YAMLError(
f"The YAML content must be a dictionary but it's been interpreted as a {type(library_data).__name__} !"
)
except yaml.YAMLError as e:
logger.error("Error while loading library content", error=e)
raise e
missing_fields = StoredLibrary.REQUIRED_FIELDS - set(library_data.keys())
if missing_fields:
err = "The following fields are missing : {}".format(
", ".join(repr(field) for field in missing_fields)
)
logger.error("Error while loading library content", error=err)
raise ValueError(err)
urn = library_data["urn"].lower()
if not match_urn(urn):
logger.error("Library URN is badly formatted", urn=urn)
raise ValueError("Library URN is badly formatted")
locale = library_data.get("locale", "en")
version = int(library_data["version"])
is_loaded = LoadedLibrary.objects.filter( # We consider the library as loaded even if the loaded version is different
urn=urn, locale=locale
).exists()
if dry_run:
objects_meta = {
key: (1 if key in ("framework", "preset") else len(value))
for key, value in library_data["objects"].items()
}
return (
{
"name": library_data["name"],
"urn": urn,
"locale": locale,
"version": version,
"ref_id": library_data.get("ref_id"),
"description": library_data.get("description"),
"provider": library_data.get("provider"),
"packager": library_data.get("packager"),
"publication_date": library_data.get("publication_date"),
"objects_meta": objects_meta,
"is_loaded": is_loaded,
"builtin": builtin,
"copyright": library_data.get("copyright"),
},
None,
)
same_version_lib = StoredLibrary.objects.filter(
urn=urn, locale=locale, version=version
).first()
if same_version_lib:
# update hash following cosmetic change (e.g. when we added publication date)
logger.info("update hash", urn=urn)
same_version_lib.hash_checksum = hash_checksum
same_version_lib.save()
return None, "libraryAlreadyLoadedError"
if StoredLibrary.objects.filter(urn=urn, locale=locale, version__gte=version):
return (
None,
"libraryOutdatedError",
) # We do not accept to store outdated libraries
with transaction.atomic():
# This code allows adding outdated libraries in the library store but they will be erased if a greater version of this library is stored.
for outdated_library in StoredLibrary.objects.filter(
urn=urn, locale=locale, version__lt=version
):
outdated_library.delete()
objects_meta = {
key: (1 if key in ("framework", "preset") else len(value))
for key, value in library_data["objects"].items()
}
dependencies = library_data.get(
"dependencies", []
) # I don't want whitespaces in URN anymore nontheless
library_objects = library_data["objects"]
label_names = library_data.get("labels", [])
filtering_labels = [
LibraryFilteringLabel.objects.get_or_create(label=label_name)[0]
for label_name in label_names
]
new_library = StoredLibrary.objects.create(
name=library_data["name"],
is_published=True,
urn=urn,
locale=locale,
version=version,
ref_id=library_data["ref_id"],
default_locale=False, # We don't care about this value yet.
description=library_data.get("description"),
annotation=library_data.get("annotation"),
copyright=library_data.get("copyright"),
provider=library_data.get("provider"),
packager=library_data.get("packager"),
publication_date=library_data.get("publication_date"),
translations=library_data.get("translations", {}),
objects_meta=objects_meta,
dependencies=dependencies,
is_loaded=is_loaded,
# We have to add a "builtin: true" line to every builtin library file.
builtin=builtin,
hash_checksum=hash_checksum,
content=library_objects,
autoload=bool(
library_objects.get(
"requirement_mapping_set",
library_objects.get("requirement_mapping_sets"),
)
), # autoload is true if the library contains requirement mapping sets
)
new_library.filtering_labels.set(filtering_labels)
return new_library, None
@classmethod
def store_library_file(
cls, fname: Path, builtin: bool = False
) -> Tuple[Optional["StoredLibrary"], Optional[str]]:
with open(fname, "rb") as f:
library_content = f.read()
return StoredLibrary.store_library_content(library_content, builtin=builtin)
def get_loaded_library(self) -> Optional["LoadedLibrary"]:
if not self.is_loaded:
return
return LoadedLibrary.objects.filter(urn=self.urn).first()
@property
def is_update(self) -> bool:
loaded_library = self.get_loaded_library()
return loaded_library is not None and loaded_library.has_update
@property
def reference_count(self) -> int:
loaded_library = self.get_loaded_library()
return loaded_library.reference_count if loaded_library is not None else 0
def load(self) -> Union[str, None]:
from library.utils import LibraryImporter
if LoadedLibrary.objects.filter(urn=self.urn, locale=self.locale).exists():
return "This library has already been loaded."
library_importer = LibraryImporter(self)
error_msg = library_importer.import_library()
if error_msg is None:
self.is_loaded = True
self.save()
return error_msg
@property
def is_preset(self) -> bool:
return bool(self.content and "preset" in self.content)
def delete(self, *args, **kwargs):
library_filtering_labels = list(self.filtering_labels.all())
super().delete(*args, **kwargs)
for library_label in library_filtering_labels:
library_label.garbage_collect()
class LibraryUpdater:
class ScoreChangeDetected(Exception):
"""Exception raised when score boundaries change, requiring user decision"""
def __init__(
self, framework_urn, prev_scores, new_scores, affected_assessments
):
self.framework_urn = framework_urn
self.prev_scores = prev_scores
self.new_scores = new_scores
self.affected_assessments = affected_assessments
self.strategies = [
{"name": "clamp", "description": "clampDescription", "action": "clamp"},
{"name": "reset", "description": "resetDescription", "action": "reset"},
{
"name": "ruleOfThree",
"description": "ruleOfThreeDescription",
"action": "rule_of_three",
},
]
super().__init__("Score boundaries changed, user decision required")
def __init__(
self,
old_library: "LoadedLibrary",
new_library: StoredLibrary,
strategy: Optional[str] = None,
):
self.old_library = old_library
self.new_library = new_library
self.strategy = strategy
new_library_content = self.new_library.content
self.dependencies: List[str] = self.new_library.dependencies or []
self.i18n_object_dict = {
"locale": self.old_library.locale,
"default_locale": self.old_library.default_locale,
}
self.referential_object_dict = {
"provider": self.new_library.provider,
"is_published": True,
}
# The "framework" field will be ignored if the "frameworks" field is defined.
self.new_frameworks = new_library_content.get(
"frameworks"
) or new_library_content.get("framework")
if isinstance(self.new_frameworks, dict):
self.new_frameworks = [self.new_frameworks]
# The "risk_matrix" field will be ignored if the "risk_matrices" field is defined.
self.new_matrices = new_library_content.get(
"risk_matrices"
) or new_library_content.get("risk_matrix")
if isinstance(self.new_matrices, dict):
self.new_matrices = [self.new_matrices]
# The "requirement_mapping_sets" field will be ignored if the "requirement_mapping_set" field is defined.
self.new_requirement_mapping_sets = new_library_content.get(
"requirement_mapping_sets"
) or new_library_content.get("requirement_mapping_set")
if isinstance(self.new_requirement_mapping_sets, dict):
self.new_requirement_mapping_sets = [self.new_requirement_mapping_sets]
self.threats = new_library_content.get("threats", [])
self.reference_controls = new_library_content.get("reference_controls", [])
self.metric_definitions = new_library_content.get("metric_definitions", [])
def update_dependencies(self) -> Union[str, None]:
for dependency_urn in self.dependencies:
possible_dependencies = [*LoadedLibrary.objects.filter(urn=dependency_urn)]
if (
not possible_dependencies
): # This part of the code hasn't been tested yet
stored_dependencies = [
*StoredLibrary.objects.filter(urn=dependency_urn)
]
if not stored_dependencies:
return "dependencyNotFound"
dependency = stored_dependencies[0]
for i in range(1, len(stored_dependencies)):
stored_dependency = stored_dependencies[i]
if stored_dependency.locale == self.old_library.locale:
dependency = stored_dependency
if error_msg := dependency.load():
return error_msg
continue
dependency = possible_dependencies[0]
for i in range(1, len(possible_dependencies)):
possible_dependency = possible_dependencies[i]
if possible_dependency.locale == self.old_library.locale:
dependency = possible_dependency
if (error_msg := dependency.update(self.strategy)) not in [
None,
"libraryHasNoUpdate",
]:
return error_msg
def update_threats(self):
for threat in self.threats:
normalized_urn = threat["urn"].lower()
Threat.objects.update_or_create(
urn=normalized_urn,
defaults=threat,
create_defaults={
**self.referential_object_dict,
**self.i18n_object_dict,
**threat,
"library": self.old_library,
},
)
def update_reference_controls(self):
for reference_control in self.reference_controls:
normalized_urn = reference_control["urn"].lower()
ReferenceControl.objects.update_or_create(
urn=normalized_urn,
defaults=reference_control,
create_defaults={
**self.referential_object_dict,
**self.i18n_object_dict,
**reference_control,
"library": self.old_library,
},
)
def update_metric_definitions(self):
from metrology.models import MetricDefinition
for metric_definition in self.metric_definitions:
normalized_urn = metric_definition["urn"].lower()
# Handle unit lookup by name
unit = None
if unit_name := metric_definition.get("unit"):
unit = Terminology.objects.filter(
name=unit_name,
field_path=Terminology.FieldPath.METRIC_UNIT,
).first()
metric_definition = {**metric_definition, "unit": unit}
else:
metric_definition = {**metric_definition}
metric_definition.pop("unit", None)
MetricDefinition.objects.update_or_create(
urn=normalized_urn,
defaults=metric_definition,
create_defaults={
**self.referential_object_dict,
**self.i18n_object_dict,
**metric_definition,
"library": self.old_library,
},
)
def update_frameworks(self):
"""
Update frameworks with score change handling.
Behavior (score-boundary updates only)
self.strategy: One of:
- None: Check for changes and raise exception if detected
- 'clamp': Clamp existing scores to new boundaries (default behavior)
- 'reset': Reset all scores to None
- 'rule_of_three': Apply proportional scaling from old to new range
"""
for new_framework in self.new_frameworks:
with transaction.atomic():
requirement_nodes = new_framework["requirement_nodes"]
framework_dict = {**new_framework}
del framework_dict["requirement_nodes"]
framework_dict["urn"] = framework_dict["urn"].lower()
if "outcomes_definition" not in framework_dict:
framework_dict["outcomes_definition"] = []
prev_fw = Framework.objects.filter(urn=framework_dict["urn"]).first()
prev_min = getattr(prev_fw, "min_score", None)
prev_max = getattr(prev_fw, "max_score", None)
prev_def = getattr(prev_fw, "scores_definition", None)
new_framework, _ = Framework.objects.update_or_create(
urn=framework_dict["urn"],
defaults=framework_dict,
create_defaults={
**self.referential_object_dict,
**self.i18n_object_dict,
**framework_dict,
"library": self.old_library,
},
)
# update requirement_nodes
requirement_node_urns = set(
rc.urn.lower()
for rc in RequirementNode.objects.filter(framework=new_framework)
)
new_requirement_node_urns = set(
rc["urn"].lower() for rc in requirement_nodes
)
deleted_requirement_node_urns = (
requirement_node_urns - new_requirement_node_urns
)
for requirement_node_urn in deleted_requirement_node_urns:
requirement_node = RequirementNode.objects.filter(
urn=requirement_node_urn
).first()
if requirement_node is not None:
requirement_node.delete()
involved_library_urns = [*self.dependencies, self.old_library.urn]
involved_libraries = LoadedLibrary.objects.filter(
urn__in=involved_library_urns
)
objects_tracked = {}
for threat in Threat.objects.filter(library__in=involved_libraries):
objects_tracked[threat.urn.lower()] = threat
for rc in ReferenceControl.objects.filter(
library__in=involved_libraries
):
objects_tracked[rc.urn.lower()] = rc
compliance_assessments = [
*ComplianceAssessment.objects.filter(
framework=new_framework
).select_related("folder", "perimeter")
]
existing_requirement_node_objects = {
rn.urn.lower(): rn
for rn in RequirementNode.objects.filter(framework=new_framework)
}
existing_requirement_assessment_objects = defaultdict(list)
for ra in RequirementAssessment.objects.filter(
requirement__framework=new_framework
).select_related("compliance_assessment"):
existing_requirement_assessment_objects[
ra.requirement.urn.lower()
].append(ra)
requirement_assessment_objects_to_create = []
requirement_assessment_objects_to_update = []
answers_changed_ca_ids = set()
requirement_node_objects_to_update = []
order_id = 0
all_fields_to_update = set()
# Check if score boundaries changed
score_boundaries_changed = (
prev_min != new_framework.min_score
or prev_max != new_framework.max_score
or prev_def != new_framework.scores_definition
)
# If scores changed and no strategy provided, raise exception for frontend to handle
if (
score_boundaries_changed
and self.strategy is None
and compliance_assessments
):
# Check which assessments would be affected
affected_cas = [
ca
for ca in compliance_assessments
if (
ca.min_score == prev_min
and ca.max_score == prev_max
and ca.scores_definition == prev_def
)
]
if affected_cas:
raise self.ScoreChangeDetected(
framework_urn=new_framework.urn,
prev_scores={
"min_score": prev_min,
"max_score": prev_max,
"scores_definition": prev_def,
},
new_scores={
"min_score": new_framework.min_score,
"max_score": new_framework.max_score,
"scores_definition": new_framework.scores_definition,