-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtasks.py
More file actions
3588 lines (2848 loc) · 100 KB
/
Copy pathtasks.py
File metadata and controls
3588 lines (2848 loc) · 100 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
from celery.utils.log import get_task_logger
from celery import shared_task, Task
from cursion import celery
from .utils.crawler import Crawler
from .utils.scanner import Scanner as S
from .utils.tester import Tester as T
from .utils.reporter import Reporter as R
from .utils.wordpress import Wordpress as W
from .utils.alerter import Alerter
from .utils.caser import Caser
from .utils.autocaser import AutoCaser
from .utils.issuer import Issuer
from .utils.exporter import create_and_send_report_export
from .utils.scanner import (
_html_and_logs, _vrt, _lighthouse,
_yellowlab
)
from .utils.alerts import *
from .utils.updater import update_flowrun
from .utils.meter import meter_account
from .utils.manager import record_task
from .models import *
from django.contrib.auth.models import User
from django.utils import timezone
from datetime import datetime, timedelta, timezone
from redis import Redis
from contextlib import contextmanager
from cursion import settings
import asyncio, boto3, time, requests, \
json, stripe, inspect, random, secrets
class BaseTaskWithRetry(Task):
autoretry_for = (Exception, KeyError)
retry_kwargs = {'max_retries': int(settings.MAX_ATTEMPTS - 1)}
retry_backoff = True
# setting logger
logger = get_task_logger(__name__)
# setting redis client
redis_client = Redis.from_url(settings.CELERY_BROKER_URL)
# setting locking manager to prevent duplicate tasks
@contextmanager
def task_lock(lock_name, timeout=300):
lock = redis_client.lock(lock_name, timeout=timeout)
acquired = lock.acquire(blocking=False)
print(f"Lock {'acquired' if acquired else 'not acquired'} for {lock_name}")
try:
yield acquired
finally:
if acquired:
lock.release()
print(f"Lock released for {lock_name}")
# setting s3 instance
def s3():
s3 = boto3.resource('s3',
aws_access_key_id=str(settings.AWS_ACCESS_KEY_ID),
aws_secret_access_key=str(settings.AWS_SECRET_ACCESS_KEY),
region_name=str(settings.AWS_S3_REGION_NAME),
endpoint_url=str(settings.AWS_S3_ENDPOINT_URL)
)
return s3
def check_and_increment_resource(account_id: str, resource: str) -> bool:
"""
Adds 1 to the Account.usage.{resource} if
{resource}_allowed has not been reached or
if account.type is 'cloud'.
Expects: {
'account_id' : <str>,
'resource' : <str> 'scan', 'test', 'caserun', etc
}
Returns: Bool, True if resource was incremented.
"""
# get account
account = Account.objects.get(id=account_id)
# define defaults
success = False
charge_list = ['caseruns', 'flowruns', 'scans', 'tests']
# handle non-paid, cloud accounts
if account.type != 'cloud':
# check allowance
if (int(account.usage[f'{resource}']) + 1) <= int(account.usage[f'{resource}_allowed']):
# increment and update success
account.usage[f'{resource}'] = 1 + int(account.usage[f'{resource}'])
account.save()
success = True
# handle paid, cloud accounts
if account.type == 'cloud':
# increment chargable resources
if resource in charge_list:
# check chargablility
if (int(account.usage[f'{resource}'])) >= int(account.usage[f'{resource}_allowed']):
# meter resource
meter_account(account.id, 1)
# increment and update success
account.usage[f'{resource}'] = 1 + int(account.usage[f'{resource}'])
account.save()
success = True
# increment non-chargable resources
if resource not in charge_list:
# check allowance
if (int(account.usage[f'{resource}']) + 1) <= int(account.usage[f'{resource}_allowed']):
# increment and update success
account.usage[f'{resource}'] = 1 + int(account.usage[f'{resource}'])
account.save()
success = True
# return response
return success
def check_location(location: str) -> bool:
"""
Determines if task should be executed based on
passed location and current system location (settings.LOCATION).
Expects: {
'location': str
}
Returns: bool (True if task should run)
"""
# compare location to system
if location == settings.LOCATION:
return True
if location != settings.LOCATION:
return False
def update_schedule(task_id: str=None) -> None:
"""
Helper function to update Schedule.time_last_run
Expects: {
task_id: str
}
Returns: None
"""
if task_id:
try:
last_run = datetime.now(timezone.utc)
Schedule.objects.filter(periodic_task_id=task_id).update(
time_last_run=last_run
)
except Exception as e:
print(e)
return None
@shared_task()
def redeliver_failed_tasks() -> None:
"""
Check each un-completed resource (Scans & Tests)
for any celery tasks which are no longer executing &
associated resource.component is null. Once found,
re-run those specific tasks with saved kwargs. If
resource appears complete but is not marked as such,
update `.time_completed` with `datetime.now()`
Expects: None
Returns: None
"""
# get uncompleted Scans & Tests
scans = Scan.objects.filter(time_completed=None)
tests = Test.objects.filter(time_completed=None)
# get executing_tasks
i = celery.app.control.inspect()
reserved = i.reserved()
active = i.active()
executing_tasks = []
for replica in reserved:
for task in reserved[replica]:
executing_tasks.append(task['id'])
for replica in active:
for task in active[replica]:
executing_tasks.append(task['id'])
# iterate through each scan and re-run any failed jobs
for scan in scans:
# check for localization
if scan.configs.get('location', 'us') != settings.LOCATION:
continue
# check each task in system['tasks']
task_count = 0
test_id = None
alert_id = None
flowrun_id = None
node_index = None
components = []
for task in scan.system.get('tasks', []):
# get scan.{component} data
if task['component'] == 'yellowlab':
component = scan.yellowlab.get('audits', None)
if task['component'] == 'lighthouse':
component = scan.lighthouse.get('audits', None)
if task['component'] == 'vrt':
component = scan.images
if task['component'] == 'html':
component = scan.html
# record components
components.append(task['component'])
# try to get args
test_id = task['kwargs'].get('test_id')
alert_id = task['kwargs'].get('alert_id')
flowrun_id = task['kwargs'].get('flowrun_id')
node_index = task['kwargs'].get('node_index')
# re-run task if not in executing_tasks &
# scan.{component} is None
if task['task_id'] not in executing_tasks and component is None:
# check for max attempts
if task['attempts'] < settings.MAX_ATTEMPTS:
print(f're-running -> {task["task_method"]}.delay(**{task["kwargs"]})')
eval(f'{task["task_method"]}.delay(**{task["kwargs"]})')
task_count += 1
# try to get test_id
if not test_id and Test.objects.filter(post_scan=scan, time_completed=None).exists():
test_id = Test.objects.filter(post_scan=scan, time_completed=None)[0].id
# check for requested, and not recorded, components:
for comp in scan.type:
if comp not in components and comp != 'logs':
# building args
task = f"run_{comp.replace('html', 'html_and_logs')}_bg"
kwargs = {
"scan_id": str(scan.id),
"test_id": str(test_id),
"alert_id": alert_id,
"flowrun_id": flowrun_id,
"node_index": node_index
}
# run task
print(f'running -> {task}.delay(**{kwargs})')
eval(f'{task}.delay(**{kwargs})')
task_count += 1
# mark scan complete if no tasks were re-run
if task_count == 0 and len(scan.system.get('tasks', [])) > 0:
print(f'marking scan as complete')
scan.time_completed = datetime.now()
scan.save()
# execute `run_test()` if test_id present
if test_id:
print(f'executing run_test() from `post_scan` in `retry_tasks`')
run_test.delay(
test_id=str(test_id),
alert_id=alert_id,
flowrun_id=flowrun_id,
node_index=node_index
)
# iterate through each test and re-run if failed
for test in tests:
# check for localization
if settings.LOCATION != 'us':
continue
# check each task in system['tasks']
task_count = 0
for task in test.system.get('tasks', []):
# re-run task if not in executing_tasks
if task['task_id'] not in executing_tasks:
# check for post_scan completion
if not test.post_scan.time_completed:
print('post_scan not complete skipping test re-run...')
continue
# check for max attempts
if task['attempts'] < settings.MAX_ATTEMPTS:
print(f're-running -> {task["task_method"]}.delay(**{task["kwargs"]})')
eval(f'{task["task_method"]}.delay(**{task["kwargs"]})')
task_count += 1
# mark test complete if no tasks were re-run
if task_count == 0 and len(test.system.get('tasks', [])) > 0:
test.time_completed = datetime.now()
test.save()
return None
@shared_task(bind=True, base=BaseTaskWithRetry)
def create_site_and_pages_bg(self, site_id: str=None, configs: dict=settings.CONFIGS) -> None:
"""
Takes a newly created `Site`, initiates a Crawl and
initial `Scan` for each crawled page
Expects: {
site_id: str,
configs: dict
}
Returns -> None
"""
# getting site and updating for time_crawl_start
site = Site.objects.get(id=site_id)
site.time_crawl_started = datetime.now(timezone.utc)
site.time_crawl_completed = None
site.save()
# get max_urls
max_urls = site.account.usage['pages_allowed']
# crawl site
pages = Crawler(url=site.site_url, max_urls=max_urls).get_links()
# create pages and scans
for url in pages:
# add new page
if not Page.objects.filter(site=site, page_url=url).exists():
page = Page.objects.create(
site=site,
page_url=url,
user=site.user,
account=site.account,
)
# check resouce allowance
if check_and_increment_resource(site.account.id, 'scans'):
# create initial scan
scan = Scan.objects.create(
site=site,
page=page,
type=settings.TYPES,
configs=configs
)
# run each scan component in parallel
run_html_and_logs_bg.delay(scan_id=scan.id)
run_lighthouse_bg.delay(scan_id=scan.id)
run_yellowlab_bg.delay(scan_id=scan.id)
run_vrt_bg.delay(scan_id=scan.id)
# update page info
page.info["latest_scan"]["id"] = str(scan.id)
page.info["latest_scan"]["time_created"] = str(scan.time_created)
page.save()
# updating site status
site.time_crawl_completed = datetime.now(timezone.utc)
site.save()
logger.info('Added site and all pages')
return None
@shared_task(bind=True, base=BaseTaskWithRetry)
def crawl_site_bg(self, site_id: str=None, configs: dict=settings.CONFIGS) -> None:
"""
Takes an existing `Site`, initiates a new Crawl and
initial `Scan` for each newly added page
Expects: {
site_id: str,
configs: dict
}
Returns -> None
"""
# getting site and updating for time_crawl_start
site = Site.objects.get(id=site_id)
site.time_crawl_started = datetime.now(timezone.utc)
site.time_crawl_completed = None
site.save()
# get pages_allowed
pages_allowed = site.account.usage['pages_allowed']
# getting old pages for comparison
old_pages = Page.objects.filter(site=site)
old_urls = []
for p in old_pages:
old_urls.append(p.page_url)
# crawl site
new_urls = Crawler(url=site.site_url, max_urls=pages_allowed).get_links()
add_urls = []
# checking for duplicates
for url in new_urls:
if not url in old_urls:
add_urls.append(url)
# loop thorugh crawled pages
# and add if not present
current_count = len(old_urls)
for url in add_urls:
# add new page if room exists
if current_count < pages_allowed:
page = Page.objects.create(
site=site,
page_url=url,
user=site.user,
account=site.account,
)
# check resouce allowance
if check_and_increment_resource(site.account.id, 'scans'):
# create initial scan
scan = Scan.objects.create(
site=site,
page=page,
type=settings.TYPES,
configs=configs
)
# run each scan component in parallel
run_html_and_logs_bg.delay(scan_id=scan.id)
run_lighthouse_bg.delay(scan_id=scan.id)
run_yellowlab_bg.delay(scan_id=scan.id)
run_vrt_bg.delay(scan_id=scan.id)
page.info["latest_scan"]["id"] = str(scan.id)
page.info["latest_scan"]["time_created"] = str(scan.time_created)
page.save()
# increment
current_count += 1
# updating site status
site.time_crawl_completed = datetime.now(timezone.utc)
site.save()
logger.info('crawled site and added pages')
return None
@shared_task(bind=True, base=BaseTaskWithRetry)
def update_site_and_page_info(
self,
resource: str='all',
site_id: str=None,
page_id: str=None,
) -> None:
"""
Updates the site and or page `latest_scan` & `latest_test` info
depending on scope.
Expects: {
"resource" : str (OPTIONAL),
"site_id" : str (OPTIONAL),
"page_id" : str (OPTIONAL)
}
Returns -> None
"""
# defaults
site = None
page = None
pages = []
scans = []
tests = []
# get associated site
if site_id:
site = Site.objects.get(id=site_id)
pages = Page.objects.filter(site=site)
# get associated page
if page_id:
page = Page.objects.get(id=page_id)
site = page.site
pages = Page.objects.filter(site=site)
# get latest tests & scans of pages
for p in pages:
# set defaults
latest_scan = None
latest_test = None
if Test.objects.filter(page=p).exists() and \
(resource == 'test' or resource == 'all'):
_test = Test.objects.filter(page=p).exclude(
time_completed=None
).order_by('-time_completed')
if len(_test) > 0:
if _test[0].score:
# add to tests[]
tests.append(_test[0].score)
# update latest_test
latest_test = _test[0]
if Scan.objects.filter(page=p).exists() and \
(resource == 'scan' or resource == 'all'):
_scan = Scan.objects.filter(page=p).exclude(
time_completed=None
).order_by('-time_completed')
if len(_scan) > 0:
if _scan[0].score:
# add to scans[]
scans.append(_scan[0].score)
# update latest_scan
latest_scan = _scan[0]
# update single page if passed
if page:
# checking if current p is page
if page.id == p.id:
# latest_scan info
if latest_scan:
page.info['latest_scan']['id'] = str(latest_scan.id)
page.info['latest_scan']['time_created'] = str(latest_scan.time_created)
page.info['latest_scan']['time_completed'] = str(latest_scan.time_completed)
page.info['latest_scan']['score'] = latest_scan.score
page.info['lighthouse'] = latest_scan.lighthouse.get('scores')
page.info['yellowlab'] = latest_scan.yellowlab.get('scores')
print(f'updating {page.page_url} with scan.score -> {latest_scan.score}')
if latest_scan is None and (resource == 'scan' or resource == 'all'):
page.info['latest_scan']['id'] = None
page.info['latest_scan']['time_created'] = None
page.info['latest_scan']['time_completed'] = None
page.info['latest_scan']['score'] = None
page.info['lighthouse'] = None
page.info['yellowlab'] = None
print(f'updating {page.page_url} with scan.score -> {None}')
# latest_test info
if latest_test:
page.info['latest_test']['id'] = str(latest_test.id)
page.info['latest_test']['time_created'] = str(latest_test.time_created)
page.info['latest_test']['time_completed'] = str(latest_test.time_completed)
page.info['latest_test']['score'] = (round(latest_test.score * 100) / 100)
page.info['latest_test']['status'] = latest_test.status
print(f'updating {p.page_url} with test.score -> {latest_test.score}')
if latest_test is None and (resource == 'test' or resource == 'all'):
page.info['latest_test']['id'] = None
page.info['latest_test']['time_created'] = None
page.info['latest_test']['time_completed'] = None
page.info['latest_test']['score'] = None
page.info['latest_test']['status'] = None
print(f'updating {p.page_url} with test.score -> {None}')
# save page
page.save()
# update site with new scan info
if len(scans) > 0:
# calc site average of latest_scan.score
site_avg_scan_score = round((sum(scans)/len(scans)) * 100) / 100
print(f'updating site with new scan score -> {site_avg_scan_score}')
# latest_scan info
if latest_scan:
site.info['latest_scan']['id'] = str(latest_scan.id)
site.info['latest_scan']['time_created'] = str(latest_scan.time_created)
site.info['latest_scan']['time_completed'] = str(latest_scan.time_completed)
site.info['latest_scan']['score'] = latest_scan.score
site.info['lighthouse'] = latest_scan.lighthouse.get('scores')
site.info['yellowlab'] = latest_scan.yellowlab.get('scores')
if latest_scan is None and (resource == 'scan' or resource == 'all'):
site.info['latest_scan']['id'] = None
site.info['latest_scan']['time_created'] = None
site.info['latest_scan']['time_completed'] = None
site.info['latest_scan']['score'] = None
site.info['lighthouse'] = None
site.info['yellowlab'] = None
# update site with new test info
if len(tests) > 0:
# calc site average of latest_test.score
site_avg_test_score = round((sum(tests)/len(tests)) * 100) / 100
print(f'updating site with new test score -> {site_avg_test_score}')
# update site info
if latest_test:
site.info['latest_test']['id'] = str(latest_test.id)
site.info['latest_test']['time_created'] = str(latest_test.time_created)
site.info['latest_test']['time_completed'] = str(latest_test.time_completed)
site.info['latest_test']['score'] = site_avg_test_score
site.info['latest_test']['status'] = latest_test.status
if latest_test is None and (resource == 'test' or resource == 'all'):
site.info['latest_test']['id'] = None
site.info['latest_test']['time_created'] = None
site.info['latest_test']['time_completed'] = None
site.info['latest_test']['score'] = None
site.info['latest_test']['status'] = None
# save info
site.save()
return None
@shared_task(bind=True, base=BaseTaskWithRetry)
def update_scan_score(self, scan_id: str) -> None:
"""
Method to calculate the average health score and update
for the passed scan_id
Expects: {
'scan_id': str
}
Returns -> None
"""
# setting defaults
score = None
scores = []
scan = Scan.objects.get(id=scan_id)
# get latest scan scores
if scan.lighthouse['scores']['average'] is not None:
scans.append(scan.lighthouse['scores']['average'])
if scan.yellowlab['scores']['globalScore'] is not None:
scans.append(scan.yellowlab['scores']['globalScore'])
# calc average score
if len(scores) > 0:
score = sum(scores)/len(scores)
# save to scan
scan.score = score
scan.save()
# returning scan
return None
@shared_task(bind=True, base=BaseTaskWithRetry)
def scan_page_bg(
self,
scan_id : str=None,
test_id : str=None,
alert_id : str=None,
flowrun_id : str=None,
node_index : str=None,
) -> None:
"""
Runs all the requested `Scan` components
of the passed `Scan`.
Expects: {
scan_id : str,
test_id : str,
alert_id : str,
configs : dict,
flowrun_id : str,
node_index : str
}
Returns -> None
"""
# get scan object
scan = Scan.objects.get(id=scan_id)
# run each scan component in parallel
if 'html' in scan.type or 'logs' in scan.type or 'full' in scan.type:
run_html_and_logs_bg.delay(
scan_id=scan.id,
test_id=test_id,
alert_id=alert_id,
flowrun_id=flowrun_id,
node_index=node_index,
)
if 'lighthouse' in scan.type or 'full' in scan.type:
run_lighthouse_bg.delay(
scan_id=scan.id,
test_id=test_id,
alert_id=alert_id,
flowrun_id=flowrun_id,
node_index=node_index,
)
if 'yellowlab' in scan.type or 'full' in scan.type:
run_yellowlab_bg.delay(
scan_id=scan.id,
test_id=test_id,
alert_id=alert_id,
flowrun_id=flowrun_id,
node_index=node_index,
)
if 'vrt' in scan.type or 'full' in scan.type:
run_vrt_bg.delay(
scan_id=scan.id,
test_id=test_id,
alert_id=alert_id,
flowrun_id=flowrun_id,
node_index=node_index,
)
logger.info('started scan component tasks')
return None
@shared_task(bind=True, base=BaseTaskWithRetry)
def create_scan(
self,
scan_id: str=None,
page_id: str=None,
type: list=settings.TYPES,
alert_id: str=None,
configs: str=None,
tags: str=None,
) -> None:
"""
Runs a `Scan` using Scanner.build_scan()
where each component is run in sequence.
Expects: {
scan_id : str,
page_id : str,
type : list,
alert_id : str,
configs : dict,
tags : list,
}
Returns -> None
"""
# get scan if scan_id present
if scan_id is not None:
created_scan = Scan.objects.get(id=scan_id)
# create scan if page_id present
elif page_id is not None:
page = Page.objects.get(id=page_id)
created_scan = Scan.objects.create(
site=page.site,
page=page,
type=type,
configs=configs,
tags=tags,
)
# run scan and alert if necessary
scan = S(scan=created_scan).build_scan()
if alert_id and alert_id != 'None':
print('running alert from `task.create_scan`')
Alerter(alert_id=alert_id, object_id=scan.id).run_alert()
logger.info('Created new scan of site')
return None
@shared_task(bind=True, base=BaseTaskWithRetry)
def create_scan_bg(self, *args, **kwargs) -> None:
"""
Creates 1 or more `Scans` depending on
the scope (page, site or account). Used with `Schedules`
Expects: {
'scope' : str
'resources' : list
'account_id' : strx
'type' : list,
'configs' : dict,
'tags' : list,
'alert_id' : str,
'task_id' : str,
'flowrun_id' : str,
'node_index : str
}
Returns -> None
"""
# get data from kwargs
scope = kwargs.get('scope')
resources = kwargs.get('resources')
account_id = kwargs.get('account_id')
type = kwargs.get('type')
configs = kwargs.get('configs')
tags = kwargs.get('tags')
alert_id = kwargs.get('alert_id')
task_id = kwargs.get('task_id')
flowrun_id = kwargs.get('flowrun_id')
node_index = kwargs.get('node_index')
# check for redis lock
redis_id = task_id if task_id else secrets.token_hex(8)
lock_name = f"lock:create_scan_bg_{redis_id}"
with task_lock(lock_name) as lock_acquired:
# checking if task is already running
if not lock_acquired:
logger.info('task is already running, skipping execution.')
return None
# checking location
if not check_location(configs.get('location', settings.LOCATION)):
logger.info('Not running due to location param')
return None
# setting defaults
pages = []
sites = []
objects = []
# get account if account_id exists
if account_id:
account = Account.objects.get(id=account_id)
# iterating through resources
# and adding to sites or pages
if len(resources) > 0:
for item in resources:
# adding to pages
if item['type'] == 'page':
try:
pages.append(
Page.objects.get(id=item['id'])
)
except Exception as e:
print(e)
# adding to sites
if item['type'] == 'site':
try:
sites.append(
Site.objects.get(id=item['id'])
)
except Exception as e:
print(e)
# grabbing all sites because no
# resources were specified and scope is "account"
if len(resources) == 0 and scope == 'account':
sites = Site.objects.filter(account=account)
# get all pages from existing sites
for site in sites:
pages += Page.objects.filter(site=site)
# creating scans for each page
for page in pages:
# check resource
if check_and_increment_resource(page.account.id, 'scans'):
# create Scan obj
scan = Scan.objects.create(
site=page.site,
page=page,
type=type,
tags=tags,
configs=configs,
)
# updating latest_scan info for page
page.info['latest_scan']['id'] = str(scan.id)
page.info['latest_scan']['time_created'] = str(datetime.now(timezone.utc))
page.info['latest_scan']['time_completed'] = None
page.info['latest_scan']['score'] = None
page.info['latest_scan']['score'] = None
page.save()
# updating latest_scan info for site
page.site.info['latest_scan']['id'] = str(scan.id)
page.site.info['latest_scan']['time_created'] = str(datetime.now(timezone.utc))
page.site.info['latest_scan']['time_completed'] = None
page.site.save()
# adding objects
objects.append({
'parent': str(scan.page.id),
'id': str(scan.id),
'status': 'working'
})
# init scan page in background
scan_page_bg.delay(
scan_id=str(scan.id),
alert_id=alert_id,
flowrun_id=flowrun_id,
node_index=node_index
)
# update flowrun
if flowrun_id and flowrun_id != 'None':
update_flowrun(**{
'flowrun_id': flowrun_id,
'node_index': node_index,
'objects': objects,
'node_status': 'working' if len(objects) > 0 else 'failed',
'message': f'starting {len(objects)} scans for {page.site.site_url} | run_id: {flowrun_id}'
})
# update schedule if task_id is not None
update_schedule(task_id=task_id)
logger.info('created new Scans')
return None
@shared_task(bind=True, base=BaseTaskWithRetry)
def run_html_and_logs_bg(
self,
scan_id: str=None,
test_id: str=None,
alert_id: str=None,
flowrun_id: str=None,
node_index: str=None,
**kwargs
) -> None:
"""
Runs the html & logs components of the passed `Scan`
Expects: {
scan_id : str,
test_id : str,
alert_id : str,
flowrun_id : str,
node_index : str,
**kwargs
}
Returns -> None
"""
# sleeping random for DB
time.sleep(random.uniform(2, 6))