-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathghas-audit.sh
More file actions
executable file
·1654 lines (1381 loc) · 65.4 KB
/
ghas-audit.sh
File metadata and controls
executable file
·1654 lines (1381 loc) · 65.4 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
#!/usr/bin/env bash
# ============================================================================
# DISCLAIMER:
# This script is provided "AS IS" without warranty of any kind, either express or implied,
# including but not limited to the implied warranties of merchantability and/or fitness for a
# particular purpose. The entire risk arising out of the use or performance of the sample scripts
# and documentation remains with you. In no event shall Microsoft, its authors, or anyone else
# involved in the creation, production, or delivery of the script be liable for any damages
# whatsoever (including, without limitation, damages for loss of business profits, business
# interruption, loss of business information, or other pecuniary loss) arising out of the use of
# or inability to use the sample scripts or documentation, even if Microsoft has been advised of
# the possibility of such damages.
# ============================================================================
set -e
# ============================================================================
# PARAMETERS
# ============================================================================
ORGANIZATION=""
OUTPUT_PATH="./ghas-reports"
DETAILED_AUDIT=false
# Parse command line arguments
while [[ $# -gt 0 ]]; do
case $1 in
-o|--organization)
ORGANIZATION="$2"
shift 2
;;
-p|--output-path)
OUTPUT_PATH="$2"
shift 2
;;
-d|--detailed-audit)
DETAILED_AUDIT=true
shift
;;
-h|--help)
echo "Usage: $0 -o|--organization <org> [-p|--output-path <path>] [-d|--detailed-audit]"
echo ""
echo "Options:"
echo " -o, --organization GitHub organization name (required)"
echo " -p, --output-path Output directory path (default: ./ghas-reports)"
echo " -d, --detailed-audit Enable detailed audit mode (includes repository details, features, and commit details)"
echo " -h, --help Show this help message"
exit 0
;;
*)
echo "Unknown option: $1"
echo "Use -h or --help for usage information"
exit 1
;;
esac
done
# Prompt for Organization if not provided
if [[ -z "$ORGANIZATION" ]]; then
echo ""
echo -e "${YELLOW}GitHub Organization not specified.${NC}"
echo -e "${CYAN}Please enter the name of the GitHub Organization to audit:${NC}"
read -p "Organization: " ORGANIZATION
if [[ -z "$ORGANIZATION" ]]; then
echo -e "${RED}Error: Organization name is required.${NC}"
exit 1
fi
fi
# Prompt for DetailedAudit mode if not specified via flag
if [[ "$DETAILED_AUDIT" == "false" ]] && [[ ! -t 0 ]]; then
# Non-interactive mode, use default
:
elif [[ "$DETAILED_AUDIT" == "false" ]]; then
echo ""
echo -e "${CYAN}╔════════════════════════════════════════════════════════════════════════════╗${NC}"
echo -e "${CYAN}║ AUDIT MODE SELECTION ║${NC}"
echo -e "${CYAN}╚════════════════════════════════════════════════════════════════════════════╝${NC}"
echo ""
echo -e "${GREEN} [1] BASIC MODE${NC}"
echo -e "${GRAY} • GHAS licensing details (who enabled GHAS, when, and how)${NC}"
echo -e "${GRAY} • Active committers count per repository${NC}"
echo -e "${GRAY} • Summary reports (JSON + CSV)${NC}"
echo -e "${GRAY} • Faster execution, minimal API calls${NC}"
echo ""
echo -e "${YELLOW} [2] DETAILED MODE${NC}"
echo -e "${GRAY} • Everything in BASIC mode, plus:${NC}"
echo -e "${GRAY} • Repository metadata (creation date, size, language, branch)${NC}"
echo -e "${GRAY} • GHAS features status (Secret Scanning, Dependabot, Code Scanning)${NC}"
echo -e "${GRAY} • Detailed commit history for each active committer${NC}"
echo -e "${GRAY} • Longer execution time, more API calls required${NC}"
echo ""
read -p "Select audit mode (1 or 2) [default: 1]: " choice
if [[ -z "$choice" ]]; then
choice="1"
fi
if [[ "$choice" == "2" ]]; then
DETAILED_AUDIT=true
elif [[ "$choice" != "1" ]]; then
echo -e "${YELLOW}Invalid choice. Using BASIC mode.${NC}"
DETAILED_AUDIT=false
fi
fi
# ============================================================================
# COLORS (need to be defined before functions)
# ============================================================================
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
CYAN='\033[0;36m'
WHITE='\033[1;37m'
GRAY='\033[0;37m'
DARKGRAY='\033[1;30m'
NC='\033[0m' # No Color
# ============================================================================
# AUTHENTICATION AND PERMISSIONS CHECK
# ============================================================================
test_github_cli() {
echo ""
echo -e "${CYAN}Checking GitHub CLI installation...${NC}"
if command -v gh >/dev/null 2>&1; then
local gh_version=$(gh --version 2>&1 | head -n 1)
echo -e "${GREEN} ✓ GitHub CLI found: $gh_version${NC}"
return 0
else
echo -e "${RED} ✗ GitHub CLI not found${NC}"
echo ""
echo -e "${YELLOW}Please install GitHub CLI:${NC}"
echo -e "${GRAY} macOS: brew install gh${NC}"
echo -e "${GRAY} Linux: See https://github.com/cli/cli/blob/trunk/docs/install_linux.md${NC}"
echo -e "${GRAY} Or visit: https://cli.github.com/${NC}"
return 1
fi
}
test_github_authentication() {
echo -e "${CYAN}Checking GitHub authentication...${NC}"
if gh auth status >/dev/null 2>&1; then
echo -e "${GREEN} ✓ Authenticated with GitHub${NC}"
return 0
else
echo -e "${RED} ✗ Not authenticated with GitHub${NC}"
echo ""
echo -e "${YELLOW}Please authenticate with GitHub CLI:${NC}"
echo -e "${GRAY} gh auth login${NC}"
return 1
fi
}
test_organization_access() {
local org_name="$1"
echo -e "${CYAN}Verifying access to organization '$org_name'...${NC}"
if gh api "/orgs/$org_name" >/dev/null 2>&1; then
echo -e "${GREEN} ✓ Organization found and accessible${NC}"
return 0
else
echo -e "${RED} ✗ Cannot access organization '$org_name'${NC}"
echo ""
echo -e "${YELLOW}Possible reasons:${NC}"
echo -e "${GRAY} • Organization name is incorrect${NC}"
echo -e "${GRAY} • You don't have access to this organization${NC}"
echo -e "${GRAY} • Organization doesn't exist${NC}"
return 1
fi
}
test_billing_permissions() {
local org_name="$1"
echo -e "${CYAN}Checking billing permissions...${NC}"
if gh api "/orgs/$org_name/settings/billing/advanced-security?advanced_security_product=code_security" >/dev/null 2>&1; then
echo -e "${GREEN} ✓ Billing access confirmed${NC}"
return 0
else
echo -e "${YELLOW} ⚠ No billing access for organization '$org_name'${NC}"
echo -e "${GRAY} → Script will continue, but some billing data may be incomplete${NC}"
return 0 # Non-blocking warning
fi
}
test_prerequisites() {
local org_name="$1"
echo ""
echo -e "${CYAN}╔════════════════════════════════════════════════════════════════════════════╗${NC}"
echo -e "${CYAN}║ PREREQUISITES VERIFICATION ║${NC}"
echo -e "${CYAN}╚════════════════════════════════════════════════════════════════════════════╝${NC}"
local all_passed=true
if ! test_github_cli; then
all_passed=false
fi
if ! test_github_authentication; then
all_passed=false
fi
if ! test_organization_access "$org_name"; then
all_passed=false
fi
if ! test_billing_permissions "$org_name"; then
: # Non-blocking, already returns 0
fi
echo ""
if [[ "$all_passed" == "true" ]]; then
echo -e "${GREEN}✓ All prerequisites met. Starting audit...${NC}"
echo ""
return 0
else
echo -e "${RED}✗ Prerequisites check failed. Please resolve the issues above.${NC}"
echo ""
return 1
fi
}
# ============================================================================
# HELPER FUNCTIONS
# ============================================================================
# Global rate limit tracking
declare -A RATE_LIMIT_INFO=(
[Limit]=0
[Remaining]=0
[Used]=0
[Reset]=0
[Resource]=""
[LastCheck]=0
)
update_rate_limit_info() {
local response_headers="$1"
if [[ -z "$response_headers" ]]; then
return
fi
while IFS=': ' read -r key value; do
case "$key" in
x-ratelimit-limit)
RATE_LIMIT_INFO[Limit]=$value
;;
x-ratelimit-remaining)
RATE_LIMIT_INFO[Remaining]=$value
;;
x-ratelimit-used)
RATE_LIMIT_INFO[Used]=$value
;;
x-ratelimit-reset)
RATE_LIMIT_INFO[Reset]=$value
;;
x-ratelimit-resource)
RATE_LIMIT_INFO[Resource]=$value
;;
esac
done <<< "$response_headers"
RATE_LIMIT_INFO[LastCheck]=$(date +%s)
# Warn if approaching rate limit
if [[ ${RATE_LIMIT_INFO[Remaining]} -lt 100 ]] && [[ ${RATE_LIMIT_INFO[Remaining]} -gt 0 ]]; then
local reset_time=$(date -d "@${RATE_LIMIT_INFO[Reset]}" '+%H:%M:%S' 2>/dev/null || \
date -r "${RATE_LIMIT_INFO[Reset]}" '+%H:%M:%S' 2>/dev/null)
echo -e "${YELLOW} Rate limit low: ${RATE_LIMIT_INFO[Remaining]} requests remaining (resets at $reset_time)${NC}" >&2
fi
}
get_rate_limit_status() {
local response=$(gh api rate_limit --include 2>&1)
if [[ $? -eq 0 ]]; then
# Extract headers (everything before the first {)
local headers=$(echo "$response" | sed '/^{/,$d')
# Extract body (everything from the first {)
local body=$(echo "$response" | sed -n '/^{/,$p')
update_rate_limit_info "$headers"
# Update with more detailed info from API
if [[ -n "$body" ]]; then
RATE_LIMIT_INFO[Limit]=$(echo "$body" | jq -r '.resources.core.limit // 0')
RATE_LIMIT_INFO[Remaining]=$(echo "$body" | jq -r '.resources.core.remaining // 0')
RATE_LIMIT_INFO[Used]=$(echo "$body" | jq -r '.resources.core.used // 0')
RATE_LIMIT_INFO[Reset]=$(echo "$body" | jq -r '.resources.core.reset // 0')
fi
fi
}
wait_for_rate_limit() {
local minimum_remaining=${1:-10}
local force=${2:-false}
get_rate_limit_status
if [[ "$force" == "true" ]] || [[ ${RATE_LIMIT_INFO[Remaining]} -lt $minimum_remaining ]]; then
if [[ ${RATE_LIMIT_INFO[Reset]} -gt 0 ]]; then
local now=$(date +%s)
local wait_seconds=$((RATE_LIMIT_INFO[Reset] - now))
if [[ $wait_seconds -gt 0 ]]; then
local reset_time=$(date -d "@${RATE_LIMIT_INFO[Reset]}" '+%H:%M:%S' 2>/dev/null || \
date -r "${RATE_LIMIT_INFO[Reset]}" '+%H:%M:%S' 2>/dev/null)
echo -e "${YELLOW}Rate limit exceeded. Waiting until $reset_time ($wait_seconds seconds)...${NC}" >&2
sleep $((wait_seconds + 1))
# Verify rate limit has reset
get_rate_limit_status
echo -e "${GREEN} ✓ Rate limit reset. Continuing...${NC}" >&2
fi
fi
fi
}
# Cross-platform timeout wrapper
# Usage: run_with_timeout <seconds> <command>
run_with_timeout() {
local seconds="$1"
shift
# Check if timeout command is available (Linux)
if command -v timeout >/dev/null 2>&1; then
timeout "$seconds" "$@"
return $?
fi
# macOS and other Unix systems - use perl (available by default)
if command -v perl >/dev/null 2>&1; then
perl -e "alarm $seconds; exec @ARGV" "$@"
local exit_code=$?
# Exit code 142 means timeout (SIGALRM)
if [[ $exit_code -eq 142 ]]; then
return 124 # Return same code as timeout command
fi
return $exit_code
fi
# Fallback for systems without timeout or perl
# Run the command without timeout protection
"$@"
return $?
}
invoke_github_api() {
local endpoint="$1"
local paginate="${2:-false}"
local throttle_ms="${3:-0}"
echo -e "${DARKGRAY} [DEBUG] API Call: $endpoint (paginate=$paginate)${NC}" >&2
# Check rate limit before making request
if [[ ${RATE_LIMIT_INFO[Remaining]} -lt 10 ]] && [[ ${RATE_LIMIT_INFO[Remaining]} -gt 0 ]]; then
wait_for_rate_limit 10
fi
# Add throttling if specified
if [[ $throttle_ms -gt 0 ]]; then
sleep $(echo "scale=3; $throttle_ms / 1000" | bc)
fi
# Execute request with timeout protection
if [[ "$paginate" == "true" ]]; then
# For paginated requests, get data without headers first
local response=$(run_with_timeout 300 gh api --paginate "$endpoint" 2>&1)
local exit_code=$?
echo -e "${DARKGRAY} [DEBUG] Paginated request exit code: $exit_code${NC}" >&2
if [[ $exit_code -eq 124 ]]; then
echo -e "${RED} Error: API request timed out after 5 minutes${NC}" >&2
echo -e "${RED} Endpoint: $endpoint${NC}" >&2
return 1
fi
if [[ $exit_code -ne 0 ]]; then
echo -e "${RED} Error: API request failed with exit code $exit_code${NC}" >&2
echo -e "${RED} Endpoint: $endpoint${NC}" >&2
echo -e "${RED} Response: ${response:0:500}${NC}" >&2
return 1
fi
if [[ -n "$response" ]]; then
echo -e "${DARKGRAY} [DEBUG] Response length: ${#response} chars${NC}" >&2
# Update rate limit info with a separate call
local header_response=$(run_with_timeout 30 gh api --include "$endpoint" 2>&1)
if [[ $? -eq 0 ]] && [[ -n "$header_response" ]]; then
local headers=$(echo "$header_response" | sed '/^{/,$d')
update_rate_limit_info "$headers"
fi
echo "$response"
return 0
else
echo -e "${YELLOW} Warning: Empty response from $endpoint${NC}" >&2
return 1
fi
else
# For single requests, get headers and body
local response=$(run_with_timeout 60 gh api --include "$endpoint" 2>&1)
local exit_code=$?
echo -e "${DARKGRAY} [DEBUG] Single request exit code: $exit_code${NC}" >&2
if [[ $exit_code -eq 124 ]]; then
echo -e "${RED} Error: API request timed out${NC}" >&2
echo -e "${RED} Endpoint: $endpoint${NC}" >&2
return 1
fi
if [[ $exit_code -ne 0 ]]; then
echo -e "${RED} Error: API request failed with exit code $exit_code${NC}" >&2
echo -e "${RED} Endpoint: $endpoint${NC}" >&2
echo -e "${RED} Response: ${response:0:500}${NC}" >&2
return 1
fi
if [[ -n "$response" ]]; then
echo -e "${DARKGRAY} [DEBUG] Response length: ${#response} chars${NC}" >&2
# Extract headers (everything before the first { or [)
local headers=$(echo "$response" | sed '/^[{\[]/,$d')
# Extract body (everything from the first { or [)
local body=$(echo "$response" | sed -n '/^[{\[]/,$p')
if [[ -z "$body" ]]; then
echo -e "${YELLOW} Warning: Could not extract body from response${NC}" >&2
echo -e "${DARKGRAY} [DEBUG] Full response: ${response:0:500}${NC}" >&2
return 1
fi
echo -e "${DARKGRAY} [DEBUG] Body length: ${#body} chars${NC}" >&2
update_rate_limit_info "$headers"
echo "$body"
return 0
else
echo -e "${YELLOW} Warning: Empty response for $endpoint${NC}" >&2
return 1
fi
fi
}
get_normalized_repo_name() {
local name="$1"
if [[ "$name" == *"/"* ]]; then
echo "${name##*/}"
else
echo "$name"
fi
}
convert_to_formatted_timestamp() {
local timestamp="$1"
if [[ -z "$timestamp" ]] || [[ "$timestamp" == "0" ]]; then
echo ""
return
fi
# Check if it's a Unix timestamp (milliseconds or seconds)
if [[ "$timestamp" =~ ^[0-9]+$ ]]; then
if [[ ${#timestamp} -gt 10 ]]; then
# Milliseconds
date -d "@$((timestamp / 1000))" '+%Y-%m-%d %H:%M:%S' 2>/dev/null || \
date -r "$((timestamp / 1000))" '+%Y-%m-%d %H:%M:%S' 2>/dev/null || \
echo "$timestamp"
else
# Seconds
date -d "@$timestamp" '+%Y-%m-%d %H:%M:%S' 2>/dev/null || \
date -r "$timestamp" '+%Y-%m-%d %H:%M:%S' 2>/dev/null || \
echo "$timestamp"
fi
else
echo "$timestamp"
fi
}
convert_to_iso8601() {
local date_string="$1"
if [[ -z "$date_string" ]]; then
echo ""
return
fi
date -d "$date_string" '+%Y-%m-%dT%H:%M:%SZ' 2>/dev/null || \
date -j -f "%Y-%m-%dT%H:%M:%SZ" "$date_string" '+%Y-%m-%dT%H:%M:%SZ' 2>/dev/null || \
echo "$date_string"
}
get_first_enable_event() {
local events_json="$1"
if [[ -z "$events_json" ]] || [[ "$events_json" == "[]" ]]; then
echo "null"
return
fi
# Priority patterns for finding the first enable event (note: using capitalized field names)
local priority_patterns=(
'.Action == "repository_security_configuration.applied" and .Actor != "" and .Actor != null'
'(.Action | test("code_security.*enable|advanced_security.*enabled")) and .Actor != "" and .Actor != null'
'(.Action | test("secret_scanning.*enable")) and .Actor != "" and .Actor != null'
'(.Action | test("code_scanning.*enable")) and .Actor != "" and .Actor != null'
'(.Action | test("enable")) and .Actor != "" and .Actor != null'
'.Action == "repo.create" and .Actor != "" and .Actor != null'
)
for pattern in "${priority_patterns[@]}"; do
local result=$(echo "$events_json" | jq -r "sort_by(.Timestamp) | map(select($pattern)) | first // null")
if [[ "$result" != "null" ]]; then
echo "$result"
return
fi
done
echo "null"
}
# ============================================================================
# CORE API FUNCTIONS
# ============================================================================
get_ghas_billing_info() {
local organization="$1"
local code_security_committers=0
local code_security_repos=0
local secret_protection_committers=0
local secret_protection_repos=0
local max_committers=0
local purchased_committers=0
local repositories="[]"
local products=("code_security" "secret_protection")
for product in "${products[@]}"; do
echo -e "${GRAY} → Fetching billing data for $product...${NC}" >&2
local response=$(invoke_github_api "/orgs/$organization/settings/billing/advanced-security?advanced_security_product=$product" false 0)
local api_exit_code=$?
echo -e "${DARKGRAY} [DEBUG] Billing API exit code: $api_exit_code${NC}" >&2
# Debug: show response length and first chars
if [[ -n "$response" ]]; then
echo -e "${DARKGRAY} Response received: ${#response} chars${NC}" >&2
echo -e "${DARKGRAY} First 200 chars: ${response:0:200}${NC}" >&2
else
echo -e "${YELLOW} ⚠ No billing access for $product (this is normal if billing permissions are not granted)${NC}" >&2
echo -e "${DARKGRAY} [DEBUG] API call returned exit code $api_exit_code with empty response${NC}" >&2
continue
fi
# Validate JSON before processing
local jq_validation=$(echo "$response" | jq empty 2>&1)
if [[ $? -eq 0 ]]; then
echo -e "${DARKGRAY} [DEBUG] JSON validation: OK${NC}" >&2
local prod_committers=$(echo "$response" | jq -r '.total_advanced_security_committers // 0')
local prod_count=$(echo "$response" | jq -r '.total_count // 0')
local prod_max=$(echo "$response" | jq -r '.maximum_advanced_security_committers // 0')
local prod_purchased=$(echo "$response" | jq -r '.purchased_advanced_security_committers // 0')
local prod_repos=$(echo "$response" | jq -c '.repositories // []')
# Store product-specific metrics
if [[ "$product" == "code_security" ]]; then
code_security_committers=$prod_committers
code_security_repos=$prod_count
echo -e "${GRAY} ✓ Code Security: $prod_committers committers in $prod_count repos${NC}" >&2
elif [[ "$product" == "secret_protection" ]]; then
secret_protection_committers=$prod_committers
secret_protection_repos=$prod_count
echo -e "${GRAY} ✓ Secret Protection: $prod_committers committers in $prod_count repos${NC}" >&2
fi
if [[ $prod_max -gt $max_committers ]]; then
max_committers=$prod_max
fi
if [[ $prod_purchased -gt $purchased_committers ]]; then
purchased_committers=$prod_purchased
fi
# Merge repositories with product marker
echo -e "${DARKGRAY} [DEBUG] Processing ${prod_count} repos for $product${NC}" >&2
local tagged_repos=$(echo "$prod_repos" | jq --arg pt "$product" '[.[] | . + {product_type: $pt}]' 2>&1)
if [[ $? -ne 0 ]]; then
echo -e "${RED} Error tagging repos: $tagged_repos${NC}" >&2
continue
fi
# Add or merge repositories
repositories=$(echo "$repositories $tagged_repos" | jq -s '
.[0] as $existing | .[1] as $new |
($existing + ($new | map(
. as $item |
($existing | map(select(.name == $item.name)) | length) as $exists |
if $exists > 0 then
. + {product_type_additional: .product_type}
else
.
end
))) | unique_by(.name)
' 2>&1)
if [[ $? -ne 0 ]]; then
echo -e "${RED} Error merging repos: $repositories${NC}" >&2
else
echo -e "${DARKGRAY} [DEBUG] Total unique repos after merge: $(echo "$repositories" | jq 'length')${NC}" >&2
fi
else
echo -e "${RED} Error: Invalid JSON response for $product${NC}" >&2
echo -e "${RED} JQ validation error: $jq_validation${NC}" >&2
echo -e "${DARKGRAY} Response sample: ${response:0:300}${NC}" >&2
fi
done
# Calculate unique repository count
local unique_count=$(echo "$repositories" | jq 'length')
jq -n \
--arg total "$unique_count" \
--arg max "$max_committers" \
--arg purchased "$purchased_committers" \
--arg code_comm "$code_security_committers" \
--arg code_repos "$code_security_repos" \
--arg secret_comm "$secret_protection_committers" \
--arg secret_repos "$secret_protection_repos" \
--argjson repositories "$repositories" \
'{
total_count: ($total | tonumber),
maximum_advanced_security_committers: ($max | tonumber),
purchased_advanced_security_committers: ($purchased | tonumber),
code_security_committers: ($code_comm | tonumber),
code_security_repositories: ($code_repos | tonumber),
secret_protection_committers: ($secret_comm | tonumber),
secret_protection_repositories: ($secret_repos | tonumber),
repositories: $repositories
}'
}
get_repository_details() {
local organization="$1"
shift
local repo_names=("$@")
local details="{}"
local counter=0
local total=${#repo_names[@]}
echo -e "${GRAY} → Fetching details for $total repositories...${NC}" >&2
for repo_name in "${repo_names[@]}"; do
counter=$((counter + 1))
if [[ $((counter % 20)) -eq 0 ]]; then
echo -e "${DARKGRAY} Progress: $counter/$total${NC}" >&2
get_rate_limit_status
if [[ ${RATE_LIMIT_INFO[Remaining]} -lt 30 ]]; then
wait_for_rate_limit 30
fi
fi
local repo_json=$(invoke_github_api "/repos/$organization/$repo_name" false 50)
if [[ -n "$repo_json" ]]; then
local repo_detail=$(echo "$repo_json" | jq -c '{
Repository: .name,
IsPrivate: .private,
CreatedAt: .created_at,
UpdatedAt: .updated_at,
PushedAt: .pushed_at,
Size: .size,
Language: .language,
DefaultBranch: .default_branch
}')
details=$(echo "$details" | jq --arg key "$repo_name" --argjson val "$repo_detail" '. + {($key): $val}')
fi
done
echo "$details"
}
get_repository_features() {
local organization="$1"
shift
local repo_names=("$@")
local features="{}"
local counter=0
local total=${#repo_names[@]}
echo -e "${GRAY} → Fetching GHAS features for $total repositories...${NC}" >&2
for repo_name in "${repo_names[@]}"; do
counter=$((counter + 1))
echo -en "${GRAY} → [$counter/$total] Checking $repo_name...${NC}" >&2
if [[ $((counter % 20)) -eq 0 ]]; then
echo "" >&2
get_rate_limit_status
if [[ ${RATE_LIMIT_INFO[Remaining]} -lt 30 ]]; then
wait_for_rate_limit 30
fi
fi
local repo_json=$(invoke_github_api "/repos/$organization/$repo_name" false 50)
if [[ -z "$repo_json" ]]; then
echo -e " ${RED}✗${NC}" >&2
continue
fi
# Validate JSON before parsing
if ! echo "$repo_json" | jq empty 2>/dev/null; then
echo -e " ${RED}✗ (invalid JSON)${NC}" >&2
continue
fi
local sec=$(echo "$repo_json" | jq -c '.security_and_analysis // {}' 2>/dev/null)
if [[ -z "$sec" ]] || [[ "$sec" == "null" ]]; then
sec="{}"
fi
# Check Code Scanning Default Setup
local code_scanning_state="not-configured"
local code_scanning_langs=""
local code_scanning_schedule=""
local cs_setup=$(invoke_github_api "/repos/$organization/$repo_name/code-scanning/default-setup" false 50 2>/dev/null)
if [[ -n "$cs_setup" ]] && echo "$cs_setup" | jq empty 2>/dev/null; then
code_scanning_state=$(echo "$cs_setup" | jq -r '.state // "not-configured"' 2>/dev/null || echo "not-configured")
if [[ "$code_scanning_state" == "configured" ]]; then
code_scanning_langs=$(echo "$cs_setup" | jq -r '.languages // [] | join(", ")' 2>/dev/null || echo "")
code_scanning_schedule=$(echo "$cs_setup" | jq -r '.schedule // ""' 2>/dev/null || echo "")
fi
fi
# Check Dependabot Alerts
local dependabot_alerts="disabled"
if invoke_github_api "/repos/$organization/$repo_name/vulnerability-alerts" false 50 >/dev/null 2>&1; then
dependabot_alerts="enabled"
fi
local feature_obj=$(echo "$sec" | jq -c \
--arg repo "$repo_name" \
--arg cs_state "$code_scanning_state" \
--arg cs_langs "$code_scanning_langs" \
--arg cs_schedule "$code_scanning_schedule" \
--arg dep_alerts "$dependabot_alerts" \
'{
Repository: $repo,
SecretScanning: .secret_scanning.status,
SecretScanningPushProtection: .secret_scanning_push_protection.status,
DependabotAlerts: $dep_alerts,
DependabotSecurityUpdates: (.dependabot_security_updates.status // "disabled"),
CodeScanningDefaultSetup: $cs_state,
CodeScanningLanguages: $cs_langs,
CodeScanningSchedule: $cs_schedule
}' 2>/dev/null)
if [[ -z "$feature_obj" ]] || [[ "$feature_obj" == "null" ]]; then
echo -e " ${RED}✗ (failed to parse features)${NC}" >&2
continue
fi
features=$(echo "$features" | jq --arg key "$repo_name" --argjson val "$feature_obj" '. + {($key): $val}' 2>/dev/null)
echo -e " ${GREEN}✓${NC}" >&2
done
echo "$features"
}
get_ghas_features_status() {
local organization="$1"
# Use paginate to get all repositories
local repos=$(invoke_github_api "/orgs/$organization/repos?per_page=100&type=all" true 0)
if [[ -z "$repos" ]] || [[ "$repos" == "[]" ]]; then
jq -n \
--arg org "$organization" \
'{
organization: $org,
total_repositories: 0,
ghas_enabled_repositories: 0,
repositories: []
}'
return
fi
local total_repos=$(echo "$repos" | jq 'length')
local ghas_enabled_repos="[]"
echo -e "${GRAY} → Processing $total_repos total repositories...${NC}" >&2
local repo_counter=0
while IFS= read -r repo_name; do
[[ -z "$repo_name" ]] && continue
repo_counter=$((repo_counter + 1))
# Throttle requests to avoid rate limiting (check every 50 repos)
if [[ $((repo_counter % 50)) -eq 0 ]]; then
get_rate_limit_status
echo -e "${GRAY} → Progress: $repo_counter/$total_repos repos | Rate limit: ${RATE_LIMIT_INFO[Remaining]}/${RATE_LIMIT_INFO[Limit]}${NC}" >&2
if [[ ${RATE_LIMIT_INFO[Remaining]} -lt 50 ]]; then
wait_for_rate_limit 50
fi
fi
local repo_details=$(invoke_github_api "/repos/$organization/$repo_name" false 50)
if [[ -z "$repo_details" ]]; then
continue
fi
local sec=$(echo "$repo_details" | jq -c '.security_and_analysis // {}')
local has_advanced=$(echo "$sec" | jq -r '.advanced_security.status // "disabled"')
local has_code_sec=$(echo "$sec" | jq -r '.code_security.status // "disabled"')
local has_secret=$(echo "$sec" | jq -r '.secret_scanning.status // "disabled"')
local has_push_prot=$(echo "$sec" | jq -r '.secret_scanning_push_protection.status // "disabled"')
if [[ "$has_advanced" == "enabled" ]] || [[ "$has_code_sec" == "enabled" ]] || \
[[ "$has_secret" == "enabled" ]] || [[ "$has_push_prot" == "enabled" ]]; then
local adv_sec_status="disabled"
if [[ "$has_code_sec" != "null" ]]; then
adv_sec_status="$has_code_sec"
elif [[ "$has_advanced" != "null" ]]; then
adv_sec_status="$has_advanced"
fi
local dependabot_status=$(echo "$sec" | jq -r '.dependabot_security_updates.status // "N/A"')
local is_private=$(echo "$repo_details" | jq -r '.private')
local created_at=$(echo "$repo_details" | jq -r '.created_at // ""')
local updated_at=$(echo "$repo_details" | jq -r '.updated_at // ""')
local pushed_at=$(echo "$repo_details" | jq -r '.pushed_at // ""')
local repo_obj=$(jq -n \
--arg repo "$repo_name" \
--argjson private "$is_private" \
--arg code_sec "$adv_sec_status" \
--arg secret "$has_secret" \
--arg push_prot "$has_push_prot" \
--arg dependabot "$dependabot_status" \
--arg created "$created_at" \
--arg updated "$updated_at" \
--arg pushed "$pushed_at" \
'{
Repository: $repo,
IsPrivate: $private,
CodeSecurity: $code_sec,
SecretScanning: $secret,
SecretScanningPushProtection: $push_prot,
DependabotSecurityUpdates: $dependabot,
CreatedAt: $created,
UpdatedAt: $updated,
PushedAt: $pushed
}')
ghas_enabled_repos=$(echo "$ghas_enabled_repos" | jq --argjson obj "$repo_obj" '. + [$obj]')
fi
done < <(echo "$repos" | jq -r '.[].name')
local ghas_count=$(echo "$ghas_enabled_repos" | jq 'length')
jq -n \
--arg org "$organization" \
--arg total "$total_repos" \
--arg ghas "$ghas_count" \
--argjson repos "$ghas_enabled_repos" \
'{
organization: $org,
total_repositories: ($total | tonumber),
ghas_enabled_repositories: ($ghas | tonumber),
repositories: $repos
}'
}
get_ghas_audit_events() {
local organization="$1"
local ghas_repos_json="$2"
local all_events="[]"
local ghas_event_actions=(
"repo.advanced_security_enabled" "repo.advanced_security_disabled"
"repository_code_security.enable" "repository_code_security.disable"
"repository_security_configuration.applied" "repository_security_configuration.removed"
"repository_secret_scanning.enable" "repository_secret_scanning.disable"
"repository_secret_scanning_push_protection.enable" "repository_secret_scanning_push_protection.disable"
"repository_secret_scanning_non_provider_patterns.enabled"
"repository_secret_scanning_automatic_validity_checks.enabled"
"repo.secret_scanning_enabled" "repo.secret_scanning_disabled"
"repo.secret_scanning_push_protection_enabled" "repo.secret_scanning_push_protection_disabled"
"repository.code_scanning_enabled" "repository.code_scanning_disabled"
"repo.codeql_enabled" "repo.codeql_disabled"
"repository.dependabot_alerts_enabled" "repository.dependabot_alerts_disabled"
"repository.dependabot_security_updates_enabled" "repository.dependabot_security_updates_disabled"
"repository_vulnerability_alerts.enable" "repository_vulnerability_alerts.disable"
"repository_vulnerability_alerts_auto_dismissal.enable" "repository_vulnerability_alerts_auto_dismissal.disable"
"repository_dependency_graph.enable" "repository_dependency_graph.disable"
)
local actions_filter=$(printf '%s\n' "${ghas_event_actions[@]}" | jq -R . | jq -s .)
local counter=0
local total_repos=$(echo "$ghas_repos_json" | jq 'length')
while IFS= read -r repo_name; do
[[ -z "$repo_name" ]] && continue
counter=$((counter + 1))
# Add progress indicator and rate limit check every 20 repos
if [[ $((counter % 20)) -eq 0 ]]; then
get_rate_limit_status
echo -e "${GRAY} → Audit log progress: $counter/$total_repos repos | Rate limit: ${RATE_LIMIT_INFO[Remaining]}/${RATE_LIMIT_INFO[Limit]}${NC}" >&2
if [[ ${RATE_LIMIT_INFO[Remaining]} -lt 30 ]]; then
wait_for_rate_limit 30
fi
fi
local phrase="repo:$organization/$repo_name"
local response=$(invoke_github_api "/orgs/$organization/audit-log?phrase=$phrase&per_page=100" false 100)
local api_result=$?
# Check if API call succeeded and response is valid JSON
if [[ $api_result -eq 0 ]] && [[ -n "$response" ]] && echo "$response" | jq empty 2>/dev/null; then
if [[ "$response" != "[]" ]]; then
local filtered_events=$(echo "$response" | jq --argjson actions "$actions_filter" \
'[.[] | select(.action as $a | $actions | index($a) != null)]' 2>/dev/null || echo "[]")
if [[ -n "$filtered_events" ]] && [[ "$filtered_events" != "[]" ]]; then
all_events=$(echo "$all_events" | jq --argjson new "$filtered_events" '. + $new' 2>/dev/null || echo "$all_events")
fi
fi
fi
done < <(echo "$ghas_repos_json" | jq -r '.[].Repository // empty')
# Ensure we always return valid JSON
if ! echo "$all_events" | jq empty 2>/dev/null; then
echo "[]"
else
echo "$all_events"
fi
}
get_committer_details() {
local organization="$1"
local repository="$2"
local author="$3"
local ghas_enabled_date="$4"
echo -e "${DARKGRAY} [DEBUG] get_committer_details: repo=$repository, author=$author, date=$ghas_enabled_date${NC}" >&2
local first_push=""
local first_sha=""
# Only query commits if we have a GHAS enabled date
if [[ -z "$ghas_enabled_date" ]]; then
echo -e "${DARKGRAY} [DEBUG] No GHAS enabled date, skipping${NC}" >&2
jq -n '{FirstPushDateAfterGHAS: "", FirstCommitSHA: ""}'
return
fi
local since_param=$(convert_to_iso8601 "$ghas_enabled_date")
echo -e "${DARKGRAY} [DEBUG] Converted date to ISO8601: $since_param${NC}" >&2
if [[ -n "$since_param" ]]; then
local commits=$(invoke_github_api "/repos/$organization/$repository/commits?author=$author&since=$since_param&per_page=100" false 50)
local api_result=$?
echo -e "${DARKGRAY} [DEBUG] Commits API result: $api_result${NC}" >&2
if [[ $api_result -ne 0 ]]; then
echo -e "${YELLOW} ⚠ Could not fetch commits for $author in $repository (exit code: $api_result)${NC}" >&2
jq -n '{FirstPushDateAfterGHAS: "", FirstCommitSHA: ""}'
return
fi
if [[ -n "$commits" ]] && [[ "$commits" != "[]" ]] && echo "$commits" | jq empty 2>/dev/null; then