-
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmodels.py
More file actions
842 lines (676 loc) · 20.8 KB
/
Copy pathmodels.py
File metadata and controls
842 lines (676 loc) · 20.8 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
#
# Copyright (c) nexB Inc. and others. All rights reserved.
# FederatedCode is a trademark of nexB Inc.
# SPDX-License-Identifier: Apache-2.0
# See http://www.apache.org/licenses/LICENSE-2.0 for the license text.
# See https://github.com/nexB/federatedcode for support or download.
# See https://aboutcode.org for more information about AboutCode.org OSS projects.
#
import uuid
from urllib.parse import urljoin
from django.contrib.auth.models import User
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.fields import GenericRelation
from django.contrib.contenttypes.models import ContentType
from django.db import models
from django.db.models.signals import post_save
from django.dispatch import receiver
from git import Repo
from fedcode.utils import ap_collection
from fedcode.utils import clone_git_repo
from fedcode.utils import full_reverse
from fedcode.utils import generate_webfinger
from federatedcode.settings import FEDERATEDCODE_DOMAIN
from federatedcode.settings import FEDERATEDCODE_WORKSPACE_LOCATION
class ActiveManager(models.Manager):
def get_queryset(self):
return super().get_queryset().filter(is_deleted=False)
class RemoteActor(models.Model):
"""
Represent a remote actor with its username
"""
url = models.URLField(
primary_key=True,
)
username = models.CharField(
max_length=100,
)
created_at = models.DateTimeField(
auto_now_add=True,
help_text="A field to track when remote actor are created",
)
updated_at = models.DateTimeField(
auto_now=True,
help_text="A field to track when remote actor are updated",
)
@property
def safe_url(self):
return f"{self.url.rstrip('/')}/"
class Actor(models.Model):
"""
Represent a local or remote actor
"""
summary = models.CharField(
help_text="profile summary",
max_length=100,
)
public_key = models.TextField(
blank=False,
)
class Meta:
abstract = True
class Reputation(models.Model):
"""
Reputation of a package or vulnerability.
https://www.w3.org/TR/activitystreams-vocabulary/#dfn-like
https://www.w3.org/ns/activitystreams#Dislike
"""
voter = models.CharField(
max_length=100,
help_text="security@vcio",
)
positive = models.BooleanField(
default=True,
) # Like vs Dislike
limit = models.Q(app_label="fedcode", model="review") | models.Q(
app_label="fedcode", model="note"
)
content_type = models.ForeignKey(
ContentType,
limit_choices_to=limit,
on_delete=models.CASCADE,
)
object_id = models.UUIDField(
null=True,
blank=True,
db_index=True,
)
content_object = GenericForeignKey(
"content_type",
"object_id",
)
class Meta:
unique_together = [["voter", "content_type", "object_id"]]
indexes = [
models.Index(fields=["content_type", "object_id"]),
]
@property
def to_ap(self):
return {
"type": "Like" if self.positive else "Dislike",
"actor": self.voter,
"object": self.content_object.to_ap,
}
class Service(models.Model):
"""
A Service is a special user that can manage git repositories ( sync , create )
"""
user = models.OneToOneField(
User,
null=True,
on_delete=models.CASCADE,
)
remote_actor = models.OneToOneField(
RemoteActor,
on_delete=models.CASCADE,
null=True,
blank=True,
)
def __str__(self):
return self.user.username if self.user else self.remote_actor.username
@property
def absolute_url_ap(self):
return full_reverse("user-ap-profile", self.user.username)
@property
def to_ap(self):
return {
"type": "Service", # TODO
"name": self.user.username,
}
class Note(models.Model):
"""
A Note is a message send by a Person or Package.
The content is either a plain text message or structured YAML.
If the author is a Package actor then the content is always YAML
If the author is a Person actor then the content is always plain text
https://www.w3.org/TR/activitystreams-vocabulary/#dfn-note
"""
# https://www.w3.org/TR/activitystreams-vocabulary/#dfn-mediatype
id = models.UUIDField(
primary_key=True,
editable=False,
default=uuid.uuid4,
help_text="The object's unique global identifier",
)
acct = models.CharField(
max_length=200,
help_text="Account that created this note",
)
content = models.TextField(
help_text="Text content for this note",
)
reply_to = models.ForeignKey(
"self",
on_delete=models.SET_NULL,
null=True,
blank=True,
related_name="replies",
help_text="",
)
mediaType = models.CharField(
max_length=20,
default="text/plain",
)
created_at = models.DateTimeField(
auto_now_add=True,
help_text="A field to track when notes are created",
)
updated_at = models.DateTimeField(
auto_now=True,
help_text="A field to track when notes are updated",
)
reputation = GenericRelation(
Reputation,
)
objects = ActiveManager() # Default manager (excludes deleted)
all_objects = models.Manager() # Includes deleted
is_deleted = models.BooleanField(default=False)
def delete(self, *args, **kwargs):
"""Soft delete instead of hard delete."""
self.is_deleted = True
self.save()
class Meta:
ordering = ["-updated_at"]
@property
def username(self):
return self.acct.split("@")[0]
@property
def reputation_value(self):
return (
self.reputation.filter(positive=True).count()
- self.reputation.filter(positive=False).count()
)
@property
def absolute_url(self):
return full_reverse("note-page", self.id)
@property
def acct_avatar(self):
person = Person.objects.get(user__username=self.username)
return person.avatar
@property
def to_ap(self):
return {
"id": self.absolute_url,
"type": "Note",
"author": self.acct,
"content": self.content,
"update_date": str(self.updated_at),
}
class Package(Actor):
"""
A software package is an Actor identified by its package url ( PURL ) ignoring versions
"""
id = models.UUIDField(
primary_key=True,
default=uuid.uuid4,
editable=False,
help_text="The object's unique global identifier",
)
remote_actor = models.OneToOneField(
RemoteActor,
on_delete=models.CASCADE,
null=True,
blank=True,
)
service = models.ForeignKey(
Service,
null=True,
blank=True,
on_delete=models.CASCADE,
)
purl = models.CharField(
max_length=300,
help_text="PURL (no version) ex: @pkg:maven/org.apache.logging",
unique=True,
)
notes = models.ManyToManyField(
Note,
blank=True,
help_text="""the notes created by this package""",
)
objects = ActiveManager() # Default manager (excludes deleted)
all_objects = models.Manager() # Includes deleted
is_deleted = models.BooleanField(default=False)
def delete(self, *args, **kwargs):
"""Soft delete instead of hard delete."""
self.is_deleted = True
self.save()
class Meta:
ordering = ["purl"]
@property
def acct(self):
return generate_webfinger(self.purl)
def __str__(self):
return self.purl
@property
def followers_count(self):
return Follow.objects.filter(package=self).count()
@property
def notes_count(self):
return Note.objects.filter(acct=self.acct).count()
@property
def followers(self):
return Follow.objects.filter(package=self).values("person_id")
@property
def followers_inboxes(self):
"""Return a followers inbox list"""
# TODO Try to avoid for loop
inboxes = []
for person in self.followers:
person_inbox = Person.objects.get(id=person["person_id"]).inbox_url
inboxes.append(person_inbox)
return inboxes
# TODO raise error if the package have a version or qualifiers or subpath
# def save(self, *args, **kwargs):
# if not check_purl_actor(self.string):
# return ValidationError(self.string)
# super(Purl, self).save(*args, **kwargs)
@property
def absolute_url_ap(self):
return full_reverse("purl-ap-profile", self.purl)
@property
def inbox_url(self):
return full_reverse("purl-inbox", self.purl)
@property
def outbox_url(self):
return full_reverse("purl-outbox", self.purl)
@property
def followers_url(self):
return full_reverse("purl-followers", self.purl)
@property
def key_id(self):
return full_reverse("purl-ap-profile", self.purl)
@property
def to_ap(self):
return {
"id": self.absolute_url_ap,
"type": "Package",
"name": self.service.user.username,
"purl": self.purl,
"inbox": self.inbox_url,
"outbox": self.outbox_url,
"followers": self.followers_url,
"publicKey": {
"id": self.absolute_url_ap,
"owner": self.service.absolute_url_ap,
"publicKeyPem": "-----BEGIN PUBLIC KEY-----...-----END PUBLIC KEY-----",
},
}
class Person(Actor):
"""
A person is a user can follow package or just vote or create a notes
"""
user = models.OneToOneField(
User,
null=True,
blank=True,
on_delete=models.CASCADE,
)
remote_actor = models.OneToOneField(
RemoteActor,
on_delete=models.CASCADE,
null=True,
blank=True,
)
notes = models.ManyToManyField(
Note,
blank=True,
help_text="Notes created by this user",
)
class Meta:
constraints = [
models.CheckConstraint(
check=(
models.Q(user__isnull=False, remote_actor__isnull=True)
| models.Q(user__isnull=True, remote_actor__isnull=False)
),
name="either_local_or_remote",
),
]
@property
def avatar(self):
from hashlib import sha256
email = ""
if self.user and (email := self.user.email):
email = email.strip().lower()
gravatar = sha256(email.encode("utf-8")).hexdigest()
return f"https://gravatar.com/avatar/{gravatar}"
@property
def local(self):
return bool(self.user)
@property
def avatar_absolute_url(self):
return self.avatar
# TODO raise error if the user doesn't have a user or remote actor
@property
def reputation_value(self):
"""if someone like your ( review or note ) you will get +1, dislike: -1"""
# user_reputation = Reputation.objects.filter(voter=self.acct)
# return (
# user_reputation.filter(positive=True).count()
# - user_reputation.filter(positive=False).count()
# )
return 0 # FIXME
@property
def acct(self):
return generate_webfinger(self.user.username)
@property
def url(self):
return full_reverse("user-profile", self.user.username)
@property
def absolute_url_ap(self):
return full_reverse("user-ap-profile", self.user.username)
@property
def inbox_url(self):
if not self.local:
return urljoin(self.remote_actor.safe_url, "inbox")
return full_reverse("user-inbox", self.user.username)
@property
def outbox_url(self):
if not self.local:
return urljoin(self.remote_actor.safe_url, "outbox")
return full_reverse("user-outbox", self.user.username)
@property
def following_url(self):
return full_reverse("user-following", self.user.username)
@property
def key_id(self):
if self.user:
return full_reverse("user-ap-profile", self.user.username) + "#main-key"
else:
return self.remote_actor.safe_url + "#main-key"
@property
def to_ap(self):
name = self.user.username if self.local else self.remote_actor.username
return {
"id": self.absolute_url_ap,
"type": "Person",
"name": name,
"summary": self.summary,
"inbox": self.inbox_url,
"outbox": self.outbox_url,
"following": self.following_url,
"image": self.avatar_absolute_url,
"publicKey": {
"id": self.absolute_url_ap,
"owner": self.absolute_url_ap,
"publicKeyPem": "-----BEGIN PUBLIC KEY-----...-----END PUBLIC KEY-----",
},
}
class Follow(models.Model):
"""
A Follow relates a person to a package that "follows" a package.
"""
person = models.ForeignKey(
Person,
on_delete=models.CASCADE,
help_text="Person that follows",
)
package = models.ForeignKey(
Package,
on_delete=models.CASCADE,
help_text="Followed package",
)
created_at = models.DateTimeField(
auto_now_add=True,
help_text="Date created",
)
updated_at = models.DateTimeField(
auto_now=True,
help_text="Date updated",
)
class Meta:
ordering = ["-updated_at"]
def __str__(self):
username = self.person.remote_actor.username
if self.person.local:
username = self.person.user.username
return f"{username} - {self.package.purl}"
class Repository(models.Model):
"""
A git repository used as a backing storage for Package and vulnerability data
"""
id = models.UUIDField(
primary_key=True,
editable=False,
default=uuid.uuid4,
help_text="The object's unique global identifier",
)
url = models.URLField(
help_text="Git Repository url ex: https://github.com/nexB/vulnerablecode-data",
)
path = models.CharField(
max_length=200,
help_text="path of the repository",
)
admin = models.ForeignKey(
Service,
on_delete=models.CASCADE,
help_text="admin user ex: VCIO user",
)
remote_url = models.CharField(
max_length=300,
blank=True,
null=True,
help_text="the url of the repository" " if this repository is remote",
)
last_imported_commit = models.CharField(
max_length=64,
blank=True,
null=True,
)
created_at = models.DateTimeField(
auto_now_add=True,
help_text="A field to track when repository are created",
)
updated_at = models.DateTimeField(
auto_now=True,
help_text="A field to track when repository are updated",
)
class Meta:
unique_together = [["admin", "url"]]
ordering = ["-updated_at"]
def __str__(self):
return self.url
@property
def review_count(self):
return Review.objects.filter(repository=self).count()
@property
def git_repo_obj(self):
return Repo(self.path)
@property
def absolute_url(self):
return full_reverse("repository-page", self.id)
@property
def to_ap(self):
return {
"id": self.absolute_url,
"type": "Repository",
"url": self.url,
}
class Vulnerability(models.Model):
"""
A vulnerability tracked by its VulnerableCode VCID
"""
id = models.CharField(
primary_key=True,
max_length=20,
help_text="Unique vulnerability identifier 'VCID'",
)
repo = models.ForeignKey(
Repository,
on_delete=models.CASCADE,
)
remote_url = models.CharField(
max_length=300,
blank=True,
null=True,
help_text="",
)
class Meta:
unique_together = ("id", "repo")
@property
def absolute_url(self):
return full_reverse("vulnerability-page", self.id)
def __str__(self):
return self.id
@property
def to_ap(self):
return {
"id": self.absolute_url,
"type": "Vulnerability",
"repository": self.repo.absolute_url,
}
class Review(models.Model):
"""
A review tracks the review comments on a Package or Vulnerability.
"""
id = models.UUIDField(
primary_key=True,
editable=False,
default=uuid.uuid4,
help_text="The object's unique global identifier",
)
headline = models.CharField(
max_length=300,
help_text="the review title",
)
author = models.ForeignKey(
Person,
on_delete=models.CASCADE,
)
repository = models.ForeignKey(
Repository,
on_delete=models.CASCADE,
)
filepath = models.CharField(
max_length=300,
help_text="the review path ex: /apache/httpd/VCID-1a68-fd5t-aaam.yml",
)
commit = models.CharField(
max_length=300,
help_text="ex: 104ccd6a7a41329b2953c96e52792a3d6a9ad8e5",
)
data = models.TextField(
help_text="review data ex: vulnerability file",
)
notes = models.ManyToManyField(
Note,
blank=True,
help_text="",
)
created_at = models.DateTimeField(
auto_now_add=True,
help_text="A field to track when review are created",
)
updated_at = models.DateTimeField(
auto_now=True,
help_text="A field to track when review are updated",
)
remote_url = models.CharField(
max_length=300,
blank=True,
null=True,
help_text="the review remote url if " "Remote Review exists",
)
class ReviewStatus(models.IntegerChoices):
OPEN = 0
DRAFT = 1
CLOSED = 2
MERGED = 3
status = models.SmallIntegerField(
choices=ReviewStatus.choices,
null=False,
blank=False,
default=0,
help_text="status of review",
)
reputation = GenericRelation(
Reputation,
)
class Meta:
ordering = ["-updated_at"]
def __str__(self):
return f"{self.headline}"
@property
def reputation_value(self):
return (
self.reputation.filter(positive=True).count()
- self.reputation.filter(positive=False).count()
)
@property
def absolute_url(self):
return full_reverse("review-page", self.id)
@property
def to_ap(self):
return {
"id": self.absolute_url,
"type": "Review",
"author": self.author.absolute_url_ap,
"headline": self.headline,
"repository": str(self.repository.id),
"filepath": self.filepath,
"commit": self.commit,
"content": self.data,
"comments": ap_collection(self.notes),
"published": self.created_at,
"updated": self.updated_at,
}
class FederateRequest(models.Model):
target = models.URLField(
help_text="The request target ex: (inbox of the targeted actor",
blank=False,
null=False,
)
body = models.TextField(
help_text="The request body",
blank=False,
null=False,
)
key_id = models.URLField(
help_text="The key url of the actor ex: https://my-example.com/actor#main-key",
blank=False,
null=False,
)
error_message = models.TextField(
help_text="Error message if a request failed to federate",
)
created_at = models.DateTimeField(
auto_now_add=True,
help_text="A field to track when review are created",
)
done = models.BooleanField(
default=False, help_text="Flag set to true when the request completed"
)
class SyncRequest(models.Model):
repo = models.ForeignKey(
Repository,
on_delete=models.CASCADE,
help_text="The Git repository where the importer will run",
)
error_message = models.TextField(
help_text="Error message if a request failed to sync",
)
created_at = models.DateTimeField(
auto_now_add=True,
help_text="A field to track when review are created",
)
done = models.BooleanField(
default=False, help_text="Flag set to true when the request completed"
)
@receiver(post_save, sender=Repository)
def create_git_repo(sender, instance, created, **kwargs):
if created:
repo = clone_git_repo(FEDERATEDCODE_WORKSPACE_LOCATION, instance.url)
instance.path = repo.working_dir
instance.save()