-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgithub_discovery.py
1390 lines (1224 loc) · 48.1 KB
/
github_discovery.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
'''Github discovery - queries the github API for info about hmpps services and stores the results in the service catalogue'''
import os
import http.server
import socketserver
import threading
import logging
import tempfile
from time import sleep
from datetime import datetime
from base64 import b64decode
import re
import json
import yaml
import github
import requests
from dockerfile_parse import DockerfileParser
from slack_sdk import WebClient
from slack_sdk.errors import SlackApiError
import base64
SC_API_ENDPOINT = os.getenv('SERVICE_CATALOGUE_API_ENDPOINT')
SC_API_TOKEN = os.getenv('SERVICE_CATALOGUE_API_KEY')
GITHUB_APP_ID = int(os.getenv('GITHUB_APP_ID'))
GITHUB_APP_INSTALLATION_ID = int(os.getenv('GITHUB_APP_INSTALLATION_ID'))
GITHUB_APP_PRIVATE_KEY = os.getenv('GITHUB_APP_PRIVATE_KEY')
REFRESH_INTERVAL_HOURS = int(os.getenv('REFRESH_INTERVAL_HOURS', '6'))
CIRCLECI_TOKEN = os.getenv('CIRCLECI_TOKEN')
CIRCLECI_API_ENDPOINT = os.getenv(
'CIRCLECI_API_ENDPOINT',
'https://circleci.com/api/v1.1/project/gh/ministryofjustice/',
)
SLACK_BOT_TOKEN = os.getenv('SLACK_BOT_TOKEN')
# Set maximum number of concurrent threads to run, try to avoid secondary github api limits.
MAX_THREADS = 10
LOG_LEVEL = os.environ.get('LOG_LEVEL', 'INFO').upper()
# limit results for testing/dev
# See strapi filter syntax https://docs.strapi.io/dev-docs/api/rest/filters-locale-publication
# Example filter string = '&filters[name][$contains]=example'
SC_FILTER = os.getenv('SC_FILTER', '')
SC_PAGE_SIZE = 10
SC_PAGINATION_PAGE_SIZE = f'&pagination[pageSize]={SC_PAGE_SIZE}'
# Example Sort filter
# SC_SORT='&sort=updatedAt:asc'
SC_SORT = ''
SC_ENDPOINT = f'{SC_API_ENDPOINT}/v1/components?populate=environments{SC_FILTER}{SC_PAGINATION_PAGE_SIZE}{SC_SORT}'
SC_ENDPOINT_TEAMS = f'{SC_API_ENDPOINT}/v1/github-teams'
SC_ENDPOINT_COMPONENTS = f'{SC_API_ENDPOINT}/v1/components'
SC_PRODUCT_FILTER = os.getenv(
'SC_PRODUCT_FILTER',
'&fields[0]=slack_channel_id&fields[1]=slack_channel_name&fields[2]=p_id&fields[3]=name',
)
SC_PRODUCT_ENDPOINT = f'{SC_API_ENDPOINT}/v1/products?populate=environments{SC_PRODUCT_FILTER}{SC_PAGINATION_PAGE_SIZE}{SC_SORT}'
SC_PRODUCT_UPDATE_ENDPOINT = f'{SC_API_ENDPOINT}/v1/products'
ALERTMANAGER_ENDPOINT = os.getenv('ALERTMANAGER_ENDPOINT','http://monitoring-alerts-service.cloud-platform-monitoring-alerts:8080/alertmanager/status')
alertmanager_json_data = ''
class HealthHttpRequestHandler(http.server.SimpleHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.send_header('Content-type', 'text/plain')
self.end_headers()
self.wfile.write(bytes('UP', 'utf8'))
return
def update_sc_component(c_id, data):
try:
log.debug(data)
x = requests.put(
f'{SC_API_ENDPOINT}/v1/components/{c_id}',
headers=sc_api_headers,
json={'data': data},
timeout=10,
)
if x.status_code == 200:
log.info(f'Successfully updated component id {c_id}: {x.status_code}')
else:
log.info(
f'Received non-200 response from service catalogue for component id {c_id}: {x.status_code} {x.content}'
)
except Exception as e:
log.error(f'Error updating component in the SC: {e}')
def update_sc_product(p_id, data):
try:
log.debug(data)
x = requests.put(
f'{SC_PRODUCT_UPDATE_ENDPOINT}/{p_id}',
headers=sc_api_headers,
json={'data': data},
timeout=10,
)
if x.status_code == 200:
log.info(f'Successfully updated product id {p_id}: {x.status_code}')
else:
log.info(
f'Received non-200 response from service catalogue for product id {p_id}: {x.status_code} {x.content}'
)
except Exception as e:
log.error(f'Error updating product in the SC: {e}')
def get_file_yaml(repo, path):
try:
file_contents = repo.get_contents(path)
contents = b64decode(file_contents.content).decode().replace('\t', ' ')
yaml_contents = yaml.safe_load(contents)
return yaml_contents
except github.UnknownObjectException:
log.debug(f'404 File not found {repo.name}:{path}')
except Exception as e:
log.error(f'Error getting yaml file: {e}')
def get_file_json(repo, path):
try:
file_contents = repo.get_contents(path)
json_contents = json.loads(b64decode(file_contents.content))
return json_contents
except github.UnknownObjectException:
log.debug(f'404 File not found {repo.name}:{path}')
except Exception as e:
log.error(f'Error getting json file: {e}')
def get_file_plain(repo, path):
try:
file_contents = repo.get_contents(path)
plain_contents = b64decode(file_contents.content).decode()
return plain_contents
except github.UnknownObjectException:
log.debug(f'404 File not found {repo.name}:{path}')
return False
except Exception as e:
log.error(f'Error getting contents from file: {e}')
def test_endpoint(url, endpoint):
headers = {'User-Agent': 'hmpps-service-discovery'}
try:
r = requests.get(
f'{url}{endpoint}', headers=headers, allow_redirects=False, timeout=10
)
# Test if json is returned
if r.json() and r.status_code != 404:
log.debug(f'Found endpoint: {url}{endpoint} ')
return True
except Exception:
log.debug(f'Could not connect to endpoint: {url}{endpoint} ')
return False
def test_swagger_docs(url):
headers = {'User-Agent': 'hmpps-service-discovery'}
try:
r = requests.get(
f'{url}/swagger-ui.html', headers=headers, allow_redirects=False, timeout=10
)
# Test for 302 redirect)
if r.status_code == 302 and (
'/swagger-ui/index.html' in r.headers['Location']
or 'api-docs/index.html' in r.headers['Location']
):
log.debug(f'Found swagger docs: {url}/swagger-ui.html')
return True
except Exception:
log.debug(f"Couldn't connect: {url}/swagger-ui.html")
return False
def test_subject_access_request_endpoint(url):
headers = {'User-Agent': 'hmpps-service-discovery'}
try:
r = requests.get(
f'{url}/v3/api-docs', headers=headers, allow_redirects=False, timeout=10
)
if r.status_code == 200:
try:
if r.json()['paths']['/subject-access-request']:
log.debug(f'Found SAR endpoint at: {url}/v3/api-docs')
return True
except KeyError:
log.debug('No SAR endpoint found.')
return False
except TimeoutError:
log.debug(f"Timed out connecting to: {url}/v3/api-docs")
return False
except Exception:
log.debug(f"Couldn't connect: {url}/v3/api-docs {r.status_code}")
return False
def get_sc_id(match_type, match_field, match_string):
try:
r = requests.get(
f'{SC_API_ENDPOINT}/v1/{match_type}?filters[{match_field}][$eq]={match_string}',
headers=sc_api_headers,
timeout=10,
)
if r.status_code == 200 and r.json()['data']:
sc_id = r.json()['data'][0]['id']
log.info(
f'Successfully found ID {sc_id}, matching type/field/string: {match_type}/{match_field}/{match_string}'
)
return sc_id
log.info(
f'Could not find ID, matching type/field/string: {match_type}/{match_field}/{match_string}'
)
return False
except Exception as e:
log.error(f'Error getting ID from SC: {e} - {r.status_code} {r.content}')
return False
# This method is to find the values defined for allowlist in values*.yaml files under helm_deploy folder of each project.
# This methods read all the values files under helm_deploy folder and create a dictionary object of allowlist for each environment
# including the default values.
def fetch_values_for_allowlist_key(yaml_data, key):
values = {}
if isinstance(yaml_data, dict):
if key in yaml_data:
if isinstance(yaml_data[key], dict):
values.update(yaml_data[key])
else:
values[key] = yaml_data[key]
for k, v in yaml_data.items():
if isinstance(v, (dict, list)):
child_values = fetch_values_for_allowlist_key(v, key)
if child_values:
values.update({k: child_values})
elif isinstance(yaml_data, list):
for item in yaml_data:
child_values = fetch_values_for_allowlist_key(item, key)
if child_values:
values.update(child_values)
return values
# This method read the value stored in dictionary passed to it checks if the ip allow list is present or not and returns boolean
def is_ipallowList_enabled(yaml_data):
ip_allow_list_enabled = False
if isinstance(yaml_data, dict):
for value in yaml_data.values():
if isinstance(value, dict) and value:
ip_allow_list_enabled = True
return ip_allow_list_enabled
def get_trivy_scan_json_data(project_name):
log.debug(f'Getting trivy scan data for {project_name}')
circleci_headers = {
'Circle-Token': CIRCLECI_TOKEN,
'Content-Type': 'application/json',
'Accept': 'application/json',
}
project_url = f'{CIRCLECI_API_ENDPOINT}{project_name}'
output_json_content = {}
try:
response = requests.get(project_url, headers=circleci_headers, timeout=30)
for build_info in response.json():
workflows = build_info.get('workflows', {})
workflow_name = workflows.get('workflow_name', {})
job_name = build_info.get('workflows', {}).get('job_name')
if workflow_name == 'security' and job_name == 'hmpps/trivy_latest_scan':
latest_build_num = build_info['build_num']
artifacts_url = f'{project_url}/{latest_build_num}/artifacts'
break
log.debug(f'Getting artifact URLs from CircleCI')
response = requests.get(artifacts_url, headers=circleci_headers, timeout=30)
artifact_urls = response.json()
output_json_url = next(
(
artifact['url']
for artifact in artifact_urls
if 'results.json' in artifact['url']
),
None,
)
if output_json_url:
log.debug(f'Fetching artifacts from CircleCI data')
# do not use DEBUG logging for this request
logging.getLogger("urllib3").setLevel(logging.INFO)
response = requests.get(
output_json_url, headers=circleci_headers, timeout=30
)
logging.getLogger("urllib3").setLevel(LOG_LEVEL)
output_json_content = response.json()
return output_json_content
except Exception as e:
log.debug(f'Error: {e}')
def get_slack_channel_name_by_id(slack_channel_id):
log.debug(f'Getting Slack Channel Name for id {slack_channel_id}')
slack_channel_name = None
try:
slack_channel_name = slack_client.conversations_info(channel=slack_channel_id)[
'channel'
]['name']
except SlackApiError as e:
if 'channel_not_found' in str(e):
log.info(
f'Unable to update Slack channel name - {slack_channel_id} not found or private'
)
else:
log.error(f'Slack error: {e}')
log.debug(f'Slack channel name for {slack_channel_id} is {slack_channel_name}')
return slack_channel_name
def get_alertmanager_data():
try:
response = requests.get(ALERTMANAGER_ENDPOINT, verify=False)
if response.status_code == 200:
alertmanager_data = response.json()
config_data = alertmanager_data['config']
formatted_config_data = config_data["original"].replace('\\n', '\n')
yaml_config_data = yaml.safe_load(formatted_config_data)
json_config_data = json.loads(json.dumps(yaml_config_data))
return json_config_data
else:
log.error(f"Error: {response.status_code}")
return None
except requests.exceptions.SSLError as e:
log.error(f"SSL Error: {e}")
return None
except requests.exceptions.RequestException as e:
log.error(f"Request Error: {e}")
return None
except json.JSONDecodeError as e:
log.error(f"JSON Decode Error: {e}")
return None
def find_channel_by_severity_label(alert_severity_label):
# Find the receiver name for the given severity
receiver_name = ''
if alertmanager_json_data is None:
return ''
for route in alertmanager_json_data['route']['routes']:
if route['match'].get('severity') == alert_severity_label:
receiver_name = route['receiver']
break
# Find the channel for the receiver name
if receiver_name:
for receiver in alertmanager_json_data['receivers']:
if receiver['name'] == receiver_name:
slack_configs = receiver.get('slack_configs', [])
if slack_configs:
return slack_configs[0].get('channel')
else :
return ''
def process_repo(**component):
allow_list_key = 'allowlist'
c_name = component['attributes']['name']
c_id = component['id']
github_repo = component['attributes']['github_repo']
part_of_monorepo = component['attributes']['part_of_monorepo']
project_dir = (
(component['attributes']['path_to_project'] or c_name)
if part_of_monorepo
else '.'
)
helm_dir = (
component['attributes']['path_to_helm_dir'] or f'{project_dir}/helm_deploy'
)
log.info(f'Processing component: {c_name}')
try:
repo = gh.get_repo(f'ministryofjustice/{github_repo}')
default_branch = repo.get_branch(repo.default_branch)
branch_protection = default_branch.get_protection()
except Exception as e:
log.error(
f'Error with ministryofjustice/{c_name}, check github app has permissions to see it. {e}'
)
return False
# Empty data dict gets populated along the way, and finally used in PUT request to service catalogue
data = {}
# Add standard github repo properties
data.update({'language': repo.language})
data.update({'description': repo.description})
data.update({'github_project_visibility': repo.visibility})
data.update({'github_repo': repo.name})
data.update({'latest_commit': {
'sha': default_branch.commit.sha,
'date_time': default_branch.commit.commit.committer.date.isoformat(),
}})
# GitHub teams access, branch protection etc.
branch_protection_restricted_teams = []
teams_write = []
teams_admin = []
teams_maintain = []
# variables used for implemenmtation of findind IP allowlist in helm values files
ip_allow_list_data = {}
ip_allow_list = {}
ip_allow_list_default = {}
versions_data = {}
trivy_scan_summary = {}
modsecurity_enabled_default = None
modsecurity_audit_enabled_default = None
modsecurity_snippet_default = None
try:
branch_protection = default_branch.get_protection()
branch_protection_teams = branch_protection.get_team_push_restrictions() or []
for team in branch_protection_teams:
branch_protection_restricted_teams.append(team.slug)
except Exception as e:
log.error(f'Unable to get branch protection {repo.name}: {e}')
teams = repo.get_teams()
for team in teams:
team_permissions = team.get_repo_permission(repo)
if team_permissions.admin:
teams_admin.append(team.slug)
elif team_permissions.maintain:
teams_maintain.append(team.slug)
elif team_permissions.push:
teams_write.append(team.slug)
data.update({'github_project_teams_admin': teams_admin})
log.debug(f'teams_admin: {teams_admin}')
data.update({'github_project_teams_maintain': teams_maintain})
log.debug(f'teams_maintain: {teams_maintain}')
data.update({'github_project_teams_write': teams_write})
log.debug(f'teams_write: {teams_write}')
data.update(
{
'github_project_branch_protection_restricted_teams': branch_protection_restricted_teams
}
)
log.debug(
f'branch_protection_restricted_teams: {branch_protection_restricted_teams}'
)
# Get enforce_admin details from branch protection
enforce_admins = branch_protection.enforce_admins
data.update({'github_enforce_admins_enabled': enforce_admins})
log.debug(f'github_enforce_admins_enabled: {enforce_admins}')
# Github topics
topics = repo.get_topics()
data.update({'github_topics': topics})
# Try to detect frontends or UIs
if re.search(
r'([fF]rontend)|(-ui)|(UI)|([uU]ser\s[iI]nterface)',
f'{c_name} {repo.description}',
):
log.debug("Detected 'frontend|-ui' keyword, setting frontend flag.")
data.update({'frontend': True})
# CircleCI config
cirlcleci_config = get_file_yaml(repo, '.circleci/config.yml')
if cirlcleci_config:
try:
trivy_scan_json = get_trivy_scan_json_data(c_name)
trivy_scan_date = trivy_scan_json.get('CreatedAt')
trivy_scan_summary.update(
{'trivy_scan_json': trivy_scan_json, 'trivy_scan_date': trivy_scan_date}
)
# Add trivy scan result to final data dict.
data.update(
{'trivy_scan_summary': trivy_scan_summary.get('trivy_scan_json')}
)
data.update(
{
'trivy_last_completed_scan_date': trivy_scan_summary.get(
'trivy_scan_date'
)
}
)
except Exception:
log.debug('Unable to get trivy scan results')
try:
cirleci_orbs = cirlcleci_config['orbs']
for key, value in cirleci_orbs.items():
if 'ministryofjustice/hmpps' in value:
hmpps_orb_version = value.split('@')[1]
versions_data.update({'circleci': {'hmpps_orb': hmpps_orb_version}})
log.debug(f'hmpps orb version: {hmpps_orb_version}')
except Exception:
log.debug('No hmpps orb version found')
# Helm charts
helm_chart = (
get_file_yaml(repo, f'{helm_dir}/{c_name}/Chart.yaml')
or get_file_yaml(repo, f'{helm_dir}/Chart.yaml')
or {}
)
if 'dependencies' in helm_chart:
helm_dep_versions = {}
for item in helm_chart['dependencies']:
helm_dep_versions.update({item['name']: item['version']})
versions_data.update({'helm_dependencies': helm_dep_versions})
helm_environments = []
try:
helm_deploy = repo.get_contents(helm_dir, default_branch.commit.sha)
except Exception as e:
helm_deploy = False
log.debug(f'helm_deploy folder: {e}')
if helm_deploy:
for file in helm_deploy:
if file.name.startswith('values-'):
env = re.match('values-([a-z0-9-]+)\\.y[a]?ml', file.name)[1]
helm_environments.append(env)
# HEAT-223 Start : Read and collate data for IPallowlist from all environment specific values.yaml files.
ip_allow_list[file] = fetch_values_for_allowlist_key(
get_file_yaml(repo, f'{helm_dir}/{file.name}'), allow_list_key
)
ip_allow_list_data.update({file.name: ip_allow_list[file]})
# HEAT-223 End : Read and collate data for IPallowlist from all environment specific values.yaml files.
helm_default_values = (
get_file_yaml(repo, f'{helm_dir}/{c_name}/values.yaml')
or get_file_yaml(repo, f'{helm_dir}/values.yaml')
or {}
)
if helm_default_values:
ip_allow_list_default = fetch_values_for_allowlist_key(
helm_default_values, allow_list_key
)
# Try to get the container image
try:
container_image = helm_default_values['image']['repository']
data.update({'container_image': container_image})
except KeyError:
pass
try:
container_image = helm_default_values['generic-service']['image'][
'repository'
]
data.update({'container_image': container_image})
except KeyError:
pass
# Try to get the productID
try:
product_id = helm_default_values['generic-service']['productId']
sc_product_id = get_sc_id('products', 'p_id', product_id)
if sc_product_id:
data.update({'product': sc_product_id})
except KeyError:
pass
# Get modsecurity data, if enabled.
modsecurity_enabled_default = None
modsecurity_audit_enabled_default = None
modsecurity_snippet_default = None
try:
modsecurity_enabled_default = helm_default_values['generic-service'][
'ingress'
]['modsecurity_enabled']
except KeyError:
pass
try:
modsecurity_audit_enabled_default = helm_default_values[
'generic-service'
]['ingress']['modsecurity_audit_enabled']
except KeyError:
pass
try:
modsecurity_snippet_default = helm_default_values['generic-service'][
'ingress'
]['modsecurity_snippet']
except KeyError:
pass
# helm env values files, extract useful values
helm_envs = {}
alert_severity_label_envs = {}
for env in helm_environments:
values = get_file_yaml(repo, f'{helm_dir}/values-{env}.yaml')
if values:
# Ingress hostname
try:
host = values['generic-service']['ingress']['host']
helm_envs.update({env: {'host': host}})
log.debug(f'{env} ingress host: {host}')
except KeyError:
pass
# Ingress alternative location
try:
host = values['generic-service']['ingress']['hosts'][-1]
helm_envs.update({env: {'host': host}})
log.debug(f'{env} ingress host: {host}')
except KeyError:
pass
# Ingress alternative location
try:
host = values['ingress']['host']
helm_envs.update({env: {'host': host}})
log.debug(f'{env} ingress host: {host}')
except KeyError:
pass
# Ingress alternative location
try:
host = values['ingress']['hosts'][-1]['host']
helm_envs.update({env: {'host': host}})
log.debug(f'{env} ingress host: {host}')
except KeyError:
pass
# Container image alternative location
try:
container_image = values['image']['repository']
data.update({'container_image': container_image})
except KeyError:
pass
try:
container_image = values['generic-service']['image']['repository']
data.update({'container_image': container_image})
except KeyError:
pass
# Get modsecurity data
modsecurity_enabled_env = None
modsecurity_audit_enabled_env = None
modsecurity_snippet_env = None
try:
modsecurity_enabled_env = values['generic-service']['ingress'][
'modsecurity_enabled'
]
except KeyError:
pass
try:
modsecurity_audit_enabled_env = values['generic-service']['ingress'][
'modsecurity_audit_enabled'
]
except KeyError:
pass
try:
modsecurity_snippet_env = values['generic-service']['ingress'][
'modsecurity_snippet'
]
except KeyError:
pass
# Alert severity label
alert_severity_label = None
try:
alert_severity_label = values['generic-prometheus-alerts']['alertSeverity']
alert_severity_label_envs.update({env: {'alert_severity_label': alert_severity_label}})
except KeyError:
pass
environments = []
if repo.name in bootstrap_projects:
p = bootstrap_projects[repo.name]
# Get dev namespace data
if 'circleci_project_k8s_namespace' in p:
dev_namespace = p['circleci_project_k8s_namespace']
e = {'namespace': dev_namespace, 'type': 'dev'}
ns_id = get_sc_id('namespaces', 'name', dev_namespace)
if ns_id:
e.update({'ns': ns_id})
if modsecurity_enabled_env is None and modsecurity_enabled_default:
e.update({'modsecurity_enabled': True})
elif modsecurity_enabled_env:
e.update({'modsecurity_enabled': True})
else:
e.update({'modsecurity_enabled': False})
if (
modsecurity_audit_enabled_env is None
and modsecurity_audit_enabled_default
):
e.update({'modsecurity_audit_enabled': True})
elif modsecurity_enabled_env:
e.update({'modsecurity_audit_enabled': True})
else:
e.update({'modsecurity_audit_enabled': False})
if modsecurity_snippet_env is None and modsecurity_snippet_default:
e.update({'modsecurity_snippet': modsecurity_snippet_default})
elif modsecurity_snippet_env:
e.update({'modsecurity_snippet': modsecurity_snippet_env})
else:
e.update({'modsecurity_snippet': None})
allow_list_values_for_prj_ns = {}
if 'dev' in helm_envs:
dev_url = f'https://{helm_envs["dev"]["host"]}'
e.update({'name': 'dev', 'type': 'dev', 'url': dev_url})
if 'dev' in alert_severity_label_envs:
label = alert_severity_label_envs["dev"]["alert_severity_label"]
else:
try:
label = helm_default_values['generic-prometheus-alerts']['alertSeverity']
print(f'Alert severity label not found for dev environment in {c_name}, getting default value {label}')
except KeyError:
pass
if label:
e.update({'alert_severity_label': label})
channel = find_channel_by_severity_label(label)
log.info(f'{c_name} Alerts channel for dev {label}: {channel}')
if channel != '':
e.update({'alerts_slack_channel': channel})
try:
ip_allow_list_env = ip_allow_list_data['values-dev.yaml']
allow_list_values_for_prj_ns.update(
{
'values-dev.yaml': ip_allow_list_env,
'values.yaml': ip_allow_list_default,
}
)
e.update(
{
'ip_allow_list': allow_list_values_for_prj_ns,
'ip_allow_list_enabled': is_ipallowList_enabled(
allow_list_values_for_prj_ns
),
}
)
except KeyError:
pass
elif 'development' in helm_envs:
dev_url = f'https://{helm_envs["development"]["host"]}'
e.update({'name': 'development', 'type': 'dev', 'url': dev_url})
if 'development' in alert_severity_label_envs:
label = alert_severity_label_envs["developement"]["alert_severity_label"]
else:
try:
label = helm_default_values['generic-prometheus-alerts']['alertSeverity']
print(f'Alert severity label not found for development environment in {c_name}, getting default value {label}')
except KeyError:
pass
if label:
e.update({'alert_severity_label': label})
channel = find_channel_by_severity_label(label)
log.info(f'{c_name} Alerts channel for developement {label}: {channel}')
if channel != '':
e.update({'alerts_slack_channel': channel})
try:
ip_allow_list_env = ip_allow_list_data['values-development.yaml']
allow_list_values_for_prj_ns.update(
{
'values-development.yaml': ip_allow_list_env,
'values.yaml': ip_allow_list_default,
}
)
e.update(
{
'ip_allow_list': allow_list_values_for_prj_ns,
'ip_allow_list_enabled': is_ipallowList_enabled(
allow_list_values_for_prj_ns
),
}
)
except KeyError:
pass
else:
dev_url = False
if dev_url:
health_path = '/health'
info_path = '/info'
# Hack for hmpps-auth non standard endpoints
if 'sign-in' in dev_url:
health_path = '/auth/health'
info_path = '/auth/info'
if test_endpoint(dev_url, health_path):
e.update({'health_path': health_path})
if test_endpoint(dev_url, info_path):
e.update({'info_path': info_path})
if test_swagger_docs(dev_url):
e.update({'swagger_docs': '/swagger-ui.html'})
data.update({'api': True, 'frontend': False})
if test_subject_access_request_endpoint(dev_url):
e.update({'include_in_subject_access_requests': True})
# Try to add the existing env ID so we dont overwrite existing env entries
existing_envs = component['attributes']['environments']
for item in existing_envs:
if item['name'] == 'dev' or item['name'] == 'development':
env_id = item['id']
e.update({'id': env_id})
break
environments.append(e)
# Get other env namespaces based on circleci context data
if 'circleci_context_k8s_namespaces' in p:
for c in p['circleci_context_k8s_namespaces']:
e = {}
allow_list_values = {}
env_name = c['env_name']
if 'env_type' in c:
env_type = c['env_type']
else:
env_type = env_name
e.update({'type': env_type, 'name': env_name})
if env_name in helm_envs:
env_url = f'https://{helm_envs[env_name]["host"]}'
e.update({'url': env_url})
try:
ip_allow_list_env = ip_allow_list_data[
f'values-{env_name}.yaml'
]
allow_list_values.update(
{
f'values-{env_name}.yaml': ip_allow_list_env,
'values.yaml': ip_allow_list_default,
}
)
e.update(
{
'ip_allow_list': allow_list_values,
'ip_allow_list_enabled': is_ipallowList_enabled(
allow_list_values
),
}
)
except KeyError:
pass
else:
env_url = False
if env_name in alert_severity_label_envs:
label = alert_severity_label_envs[env_name]["alert_severity_label"]
else:
try:
label = helm_default_values['generic-prometheus-alerts']['alertSeverity']
print(f'Alert severity label not found for {env_name} environment in {c_name}, getting default value {label}')
except KeyError:
pass
if label:
e.update({'alert_severity_label': label})
channel = find_channel_by_severity_label(label)
log.info(f'{c_name} Alerts channel for {env_name} {label}: {channel}')
if channel != '':
e.update({'alerts_slack_channel': channel})
if 'namespace' in c:
env_namespace = c['namespace']
e.update({'namespace': env_namespace})
ns_id = get_sc_id('namespaces', 'name', env_namespace)
if ns_id:
e.update({'ns': ns_id})
if modsecurity_enabled_env is None and modsecurity_enabled_default:
e.update({'modsecurity_enabled': True})
elif modsecurity_enabled_env:
e.update({'modsecurity_enabled': True})
else:
e.update({'modsecurity_enabled': False})
if (
modsecurity_audit_enabled_env is None
and modsecurity_audit_enabled_default
):
e.update({'modsecurity_audit_enabled': True})
elif modsecurity_enabled_env:
e.update({'modsecurity_audit_enabled': True})
else:
e.update({'modsecurity_audit_enabled': False})
if modsecurity_snippet_env is None and modsecurity_snippet_default:
e.update({'modsecurity_snippet': modsecurity_snippet_default})
elif modsecurity_snippet_env:
e.update({'modsecurity_snippet': modsecurity_snippet_env})
else:
e.update({'modsecurity_snippet': None})
if env_url:
health_path = '/health'
info_path = '/info'
# Hack for hmpps-auth non standard endpoints
if 'sign-in' in env_url:
health_path = '/auth/health'
info_path = '/auth/info'
if test_endpoint(env_url, health_path):
e.update({'health_path': health_path})
if test_endpoint(env_url, info_path):
e.update({'info_path': info_path})
# Test for API docs - and if found also test for SAR endpoint.
if test_swagger_docs(env_url):
e.update({'swagger_docs': '/swagger-ui.html'})
data.update({'api': True, 'frontend': False})
if test_subject_access_request_endpoint(env_url):
e.update({'include_in_subject_access_requests': True})
# Try to add the existing env ID so we dont overwrite existing env entries
existing_envs = component['attributes']['environments']
for item in existing_envs:
if item['name'] == env_name:
env_id = item['id']
e.update({'id': env_id})
break
environments.append(e)
# If no environment data is discovered above, and if environment data has been
# manually added to the SC, ensure we just pass the existing data to the SC update.
if not environments:
environments = component['attributes']['environments']
# App insights cloud_RoleName
if repo.language == 'Kotlin' or repo.language == 'Java':
app_insights_config = get_file_json(
repo, f'{project_dir}/applicationinsights.json'
)
if app_insights_config:
app_insights_cloud_role_name = app_insights_config['role']['name']
data.update({'app_insights_cloud_role_name': app_insights_cloud_role_name})
if repo.language == 'JavaScript' or repo.language == 'TypeScript':
package_json = get_file_json(repo, f'{project_dir}/package.json')
if package_json:
app_insights_cloud_role_name = package_json['name']
if re.match(r'^[a-zA-Z0-9-_]+$', app_insights_cloud_role_name):
data.update(
{'app_insights_cloud_role_name': app_insights_cloud_role_name}
)
# Gradle config
build_gradle_config_content = False
if repo.language == 'Kotlin' or repo.language == 'Java':
build_gradle_kts_config = get_file_plain(repo, 'build.gradle.kts')
build_gradle_config_content = build_gradle_kts_config
# Try alternative location for java projects
if not build_gradle_config_content:
build_gradle_java_config = get_file_plain(repo, 'build.gradle')
build_gradle_config_content = build_gradle_java_config
if build_gradle_config_content:
try:
regex = "id\\(\\'uk.gov.justice.hmpps.gradle-spring-boot\\'\\) version \\'(.*)\\'( apply false)?$"
hmpps_gradle_spring_boot_version = re.search(
regex, build_gradle_config_content, re.MULTILINE
)[1]
log.debug(
f'Found hmpps gradle-spring-boot version: {hmpps_gradle_spring_boot_version}'
)
versions_data.update(
{
'gradle': {
'hmpps_gradle_spring_boot': hmpps_gradle_spring_boot_version
}
}
)
except TypeError:
pass
# Parse Dockerfile
try:
file_contents = repo.get_contents(f'{project_dir}/Dockerfile')
dockerfile = DockerfileParser(fileobj=tempfile.NamedTemporaryFile())
dockerfile.content = b64decode(file_contents.content)
docker_data = {}
if re.search(r'rds-ca-2019-root\.pem', dockerfile.content, re.MULTILINE):
docker_data.update({'rds_ca_cert': 'rds-ca-2019-root.pem'})
if re.search(r'global-bundle\.pem', dockerfile.content, re.MULTILINE):
docker_data.update({'rds_ca_cert': 'global-bundle.pem'})
try: