-
Notifications
You must be signed in to change notification settings - Fork 33
Expand file tree
/
Copy pathpermissions.go
More file actions
1252 lines (1135 loc) · 36.5 KB
/
permissions.go
File metadata and controls
1252 lines (1135 loc) · 36.5 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
// Copyright (c) Mondoo, Inc.
// SPDX-License-Identifier: BUSL-1.1
package main
import (
"encoding/json"
"fmt"
"go/ast"
"go/parser"
"go/token"
"os"
"os/exec"
"path/filepath"
"regexp"
"sort"
"strconv"
"strings"
"time"
)
// PermissionManifest is the JSON output for a provider's permissions.
type PermissionManifest struct {
Provider string `json:"provider"`
Version string `json:"version"`
GeneratedAt string `json:"generated_at"`
Permissions []string `json:"permissions"`
Details []PermissionDetail `json:"details"`
}
// PermissionDetail describes a single extracted API call and its mapped permission.
type PermissionDetail struct {
Permission string `json:"permission"`
Service string `json:"service"`
Action string `json:"action"`
SourceFile string `json:"source_file"`
}
func main() {
if len(os.Args) < 2 {
fmt.Fprintf(os.Stderr, "usage: permissions <provider-path> [--output <path>]\n")
fmt.Fprintf(os.Stderr, " provider-path: path to provider directory (e.g., providers/aws)\n")
os.Exit(1)
}
providerPath := os.Args[1]
outputPath := ""
for i, arg := range os.Args {
if arg == "--output" && i+1 < len(os.Args) {
outputPath = os.Args[i+1]
}
}
providerName := filepath.Base(providerPath)
resourcesDir := filepath.Join(providerPath, "resources")
// Read provider version from config/config.go
version := readProviderVersion(filepath.Join(providerPath, "config", "config.go"))
// Detect provider type and extract permissions
var details []PermissionDetail
switch providerName {
case "aws":
details = extractAWSPermissions(resourcesDir)
case "gcp":
details = extractGCPPermissions(resourcesDir)
case "azure":
details = extractAzurePermissions(resourcesDir)
default:
fmt.Fprintf(os.Stderr, "skipping %s: not a supported cloud provider (aws, gcp, azure)\n", providerName)
os.Exit(0)
}
// Deduplicate and sort permissions
permSet := map[string]bool{}
for _, d := range details {
permSet[d.Permission] = true
}
permissions := make([]string, 0, len(permSet))
for p := range permSet {
permissions = append(permissions, p)
}
sort.Strings(permissions)
// Sort details for stable output
sort.Slice(details, func(i, j int) bool {
if details[i].Permission != details[j].Permission {
return details[i].Permission < details[j].Permission
}
return details[i].SourceFile < details[j].SourceFile
})
// Deduplicate details (same permission + source file)
if len(details) > 0 {
deduped := []PermissionDetail{details[0]}
for i := 1; i < len(details); i++ {
prev := deduped[len(deduped)-1]
if details[i].Permission != prev.Permission || details[i].SourceFile != prev.SourceFile {
deduped = append(deduped, details[i])
}
}
details = deduped
}
manifest := PermissionManifest{
Provider: providerName,
Version: version,
GeneratedAt: deterministicTimestamp(),
Permissions: permissions,
Details: details,
}
if outputPath == "" {
outputPath = filepath.Join(providerPath, "resources", providerName+".permissions.json")
}
// Skip writing if only the timestamp changed.
if existing, err := os.ReadFile(outputPath); err == nil {
var old PermissionManifest
if json.Unmarshal(existing, &old) == nil {
old.GeneratedAt = manifest.GeneratedAt
if manifestsEqual(old, manifest) {
fmt.Printf(" %s: %d permissions (unchanged) → %s\n", providerName, len(permissions), outputPath)
return
}
}
}
data, err := json.MarshalIndent(manifest, "", " ")
if err != nil {
fmt.Fprintf(os.Stderr, "error marshaling JSON: %v\n", err)
os.Exit(1)
}
data = append(data, '\n')
if err := os.MkdirAll(filepath.Dir(outputPath), 0o755); err != nil {
fmt.Fprintf(os.Stderr, "error creating output directory: %v\n", err)
os.Exit(1)
}
if err := os.WriteFile(outputPath, data, 0o644); err != nil {
fmt.Fprintf(os.Stderr, "error writing output: %v\n", err)
os.Exit(1)
}
fmt.Printf(" %s: %d permissions → %s\n", providerName, len(permissions), outputPath)
}
var versionRegex = regexp.MustCompile(`Version:\s*"([^"]+)"`)
func readProviderVersion(configPath string) string {
data, err := os.ReadFile(configPath)
if err != nil {
return "unknown"
}
m := versionRegex.FindSubmatch(data)
if m == nil {
return "unknown"
}
return string(m[1])
}
// deterministicTimestamp returns a reproducible timestamp for the manifest.
// It checks SOURCE_DATE_EPOCH first (standard reproducible-builds env var),
// then falls back to the latest git commit timestamp.
func deterministicTimestamp() string {
// Check SOURCE_DATE_EPOCH (Unix timestamp) and format as RFC 3339
if epoch := os.Getenv("SOURCE_DATE_EPOCH"); epoch != "" {
secs, err := strconv.ParseInt(epoch, 10, 64)
if err == nil {
return time.Unix(secs, 0).UTC().Format(time.RFC3339)
}
}
// Fall back to git commit timestamp
out, err := exec.Command("git", "log", "-1", "--format=%cI").Output()
if err == nil {
ts := strings.TrimSpace(string(out))
if ts != "" {
return ts
}
}
return "unknown"
}
// manifestsEqual reports whether two manifests are identical in all fields.
func manifestsEqual(a, b PermissionManifest) bool {
if a.Provider != b.Provider || a.Version != b.Version || a.GeneratedAt != b.GeneratedAt {
return false
}
if len(a.Permissions) != len(b.Permissions) {
return false
}
for i := range a.Permissions {
if a.Permissions[i] != b.Permissions[i] {
return false
}
}
if len(a.Details) != len(b.Details) {
return false
}
for i := range a.Details {
if a.Details[i] != b.Details[i] {
return false
}
}
return true
}
// listGoFiles returns all non-test, non-generated .go files in a directory tree.
func listGoFiles(dir string) []string {
var files []string
_ = filepath.WalkDir(dir, func(path string, d os.DirEntry, err error) error {
if err != nil {
return nil
}
if d.IsDir() {
return nil
}
name := d.Name()
if !strings.HasSuffix(name, ".go") {
return nil
}
if strings.HasSuffix(name, "_test.go") || strings.HasSuffix(name, ".lr.go") {
return nil
}
files = append(files, path)
return nil
})
return files
}
// =============================================================================
// AWS Permission Extraction
// =============================================================================
// awsServiceNameOverrides maps AWS SDK package names to IAM service prefixes
// where they differ from the Go package name.
var awsServiceNameOverrides = map[string]string{
"cloudwatchlogs": "logs",
"configservice": "config",
"cognitoidentityprovider": "cognito-idp",
"cognitoidentity": "cognito-identity",
"databasemigrationservice": "dms",
"directoryservice": "ds",
"docdb": "rds",
"elasticsearchservice": "es",
"elasticloadbalancing": "elasticloadbalancing",
"elasticloadbalancingv2": "elasticloadbalancing",
"firehose": "firehose",
"inspector2": "inspector2",
"kafka": "kafka",
"lightsail": "lightsail",
"macie2": "macie2",
"memorydb": "memorydb",
"mq": "mq",
"neptune": "rds",
"networkfirewall": "network-firewall",
"opensearch": "es",
"organizations": "organizations",
"pipes": "pipes",
"route53domains": "route53domains",
"s3control": "s3",
"secretsmanager": "secretsmanager",
"securityhub": "securityhub",
"shield": "shield",
"timestreamwrite": "timestream",
"timestreaminfluxdb": "timestream-influxdb",
"workspacesweb": "workspaces-web",
"applicationautoscaling": "application-autoscaling",
"elasticbeanstalk": "elasticbeanstalk",
"elasticache": "elasticache",
"accessanalyzer": "access-analyzer",
}
func extractAWSPermissions(resourcesDir string) []PermissionDetail {
var details []PermissionDetail
files := listGoFiles(resourcesDir)
for _, filePath := range files {
fileName := filepath.Base(filePath)
fset := token.NewFileSet()
f, err := parser.ParseFile(fset, filePath, nil, 0)
if err != nil {
fmt.Fprintf(os.Stderr, "warning: failed to parse %s: %v\n", filePath, err)
continue
}
// Build import map: alias -> package name
// e.g., "sns" -> "sns", "s3control" -> "s3control"
awsImports := extractAWSImports(f)
if len(awsImports) == 0 {
continue
}
// Track variable -> service mappings within each function
// e.g., svc := conn.Sns(region) -> svc maps to "sns"
ast.Inspect(f, func(n ast.Node) bool {
fn, ok := n.(*ast.FuncDecl)
if !ok {
return true
}
// Build variable -> service map for this function
varServices := map[string]string{}
ast.Inspect(fn.Body, func(n ast.Node) bool {
assignStmt, ok := n.(*ast.AssignStmt)
if !ok {
return true
}
// Look for: svc := conn.ServiceMethod(region)
// or: svc, err := conn.ServiceMethod(region)
for i, rhs := range assignStmt.Rhs {
call, ok := rhs.(*ast.CallExpr)
if !ok {
continue
}
sel, ok := call.Fun.(*ast.SelectorExpr)
if !ok {
continue
}
methodName := sel.Sel.Name
// Check if this is a known connection method (e.g., conn.Sns, conn.Ec2)
svcName := awsConnectionMethodToService(methodName)
if svcName == "" {
continue
}
if i < len(assignStmt.Lhs) {
if ident, ok := assignStmt.Lhs[i].(*ast.Ident); ok {
varServices[ident.Name] = svcName
}
}
}
return true
})
// Find API calls: svc.MethodName(ctx, &input)
ast.Inspect(fn.Body, func(n ast.Node) bool {
call, ok := n.(*ast.CallExpr)
if !ok {
return true
}
sel, ok := call.Fun.(*ast.SelectorExpr)
if !ok {
return true
}
methodName := sel.Sel.Name
// Pattern 1: svc.MethodName() where svc is a tracked variable
if ident, ok := sel.X.(*ast.Ident); ok {
if svcName, ok := varServices[ident.Name]; ok {
if isAWSAPIMethod(methodName) {
iamService := awsServiceToIAM(svcName)
details = append(details, PermissionDetail{
Permission: iamService + ":" + methodName,
Service: iamService,
Action: methodName,
SourceFile: fileName,
})
}
}
}
// Pattern 2: pkg.NewMethodPaginator() where pkg is an AWS import
if ident, ok := sel.X.(*ast.Ident); ok {
if _, isAWSPkg := awsImports[ident.Name]; isAWSPkg {
if strings.HasPrefix(methodName, "New") && strings.HasSuffix(methodName, "Paginator") {
action := strings.TrimPrefix(methodName, "New")
action = strings.TrimSuffix(action, "Paginator")
iamService := awsServiceToIAM(awsImports[ident.Name])
details = append(details, PermissionDetail{
Permission: iamService + ":" + action,
Service: iamService,
Action: action,
SourceFile: fileName,
})
}
}
}
return true
})
return false // don't recurse into nested functions again
})
}
return details
}
// extractAWSImports returns a map of import alias -> package name for AWS SDK imports.
func extractAWSImports(f *ast.File) map[string]string {
result := map[string]string{}
for _, imp := range f.Imports {
path := strings.Trim(imp.Path.Value, `"`)
if !strings.Contains(path, "github.com/aws/aws-sdk-go-v2/service/") {
continue
}
pkgName := filepath.Base(path)
alias := pkgName
if imp.Name != nil {
alias = imp.Name.Name
}
result[alias] = pkgName
}
return result
}
// awsConnectionMethodToService maps AwsConnection method names to service names.
// e.g., "Sns" -> "sns", "Ec2" -> "ec2", "S3Control" -> "s3control"
func awsConnectionMethodToService(method string) string {
// The connection methods are PascalCase versions of the service name
// e.g., Ec2, Iam, Sns, S3, S3Control, CloudwatchLogs, etc.
lower := strings.ToLower(method)
// Known connection method names (lowercase -> service package name)
knownMethods := map[string]string{
"organizations": "organizations",
"ec2": "ec2",
"wafv2": "wafv2",
"ecs": "ecs",
"iam": "iam",
"ecr": "ecr",
"ecrpublic": "ecrpublic",
"s3": "s3",
"s3control": "s3control",
"cloudtrail": "cloudtrail",
"cloudwatch": "cloudwatch",
"cloudwatchlogs": "cloudwatchlogs",
"configservice": "configservice",
"rds": "rds",
"lambda": "lambda",
"dynamodb": "dynamodb",
"kms": "kms",
"sns": "sns",
"sqs": "sqs",
"redshift": "redshift",
"cloudfront": "cloudfront",
"cloudformation": "cloudformation",
"ssm": "ssm",
"sts": "sts",
"acm": "acm",
"elb": "elasticloadbalancing",
"elbv2": "elasticloadbalancingv2",
"route53": "route53",
"route53domains": "route53domains",
"eks": "eks",
"efs": "efs",
"apigateway": "apigateway",
"autoscaling": "autoscaling",
"backup": "backup",
"codebuild": "codebuild",
"emr": "emr",
"guardduty": "guardduty",
"kinesis": "kinesis",
"secretsmanager": "secretsmanager",
"securityhub": "securityhub",
"shield": "shield",
"batch": "batch",
"drs": "drs",
"athena": "athena",
"glue": "glue",
"dms": "databasemigrationservice",
"databasemigrationservice": "databasemigrationservice",
"fsx": "fsx",
"neptune": "neptune",
"opensearch": "opensearch",
"docdb": "docdb",
"elasticache": "elasticache",
"elasticbeanstalk": "elasticbeanstalk",
"elasticsearchservice": "elasticsearchservice",
"es": "elasticsearchservice",
"eventbridge": "eventbridge",
"firehose": "firehose",
"inspector2": "inspector2",
"kafka": "kafka",
"lightsail": "lightsail",
"macie2": "macie2",
"memorydb": "memorydb",
"mq": "mq",
"networkfirewall": "networkfirewall",
"appstream": "appstream",
"applicationautoscaling": "applicationautoscaling",
"account": "account",
"sagemaker": "sagemaker",
"cognitoidentity": "cognitoidentity",
"cognitoidentityprovider": "cognitoidentityprovider",
"directoryservice": "directoryservice",
"pipes": "pipes",
"scheduler": "scheduler",
"accessanalyzer": "accessanalyzer",
"timestreamwrite": "timestreamwrite",
"timestreaminfluxdb": "timestreaminfluxdb",
"workdocs": "workdocs",
"workspaces": "workspaces",
"workspacesweb": "workspacesweb",
"codedeploy": "codedeploy",
}
if svc, ok := knownMethods[lower]; ok {
return svc
}
return ""
}
// awsServiceToIAM maps an AWS SDK package name to the IAM service prefix.
func awsServiceToIAM(sdkPkg string) string {
if override, ok := awsServiceNameOverrides[sdkPkg]; ok {
return override
}
return sdkPkg
}
// isAWSAPIMethod returns true if the method name looks like an AWS API call.
func isAWSAPIMethod(name string) bool {
prefixes := []string{
"Describe", "List", "Get", "Put", "Create", "Delete", "Update",
"Batch", "Generate", "Assume", "Decode", "Lookup", "Search",
"Tag", "Untag", "Enable", "Disable", "Start", "Stop",
}
for _, p := range prefixes {
if strings.HasPrefix(name, p) {
return true
}
}
return false
}
// =============================================================================
// GCP Permission Extraction
// =============================================================================
func extractGCPPermissions(resourcesDir string) []PermissionDetail {
var details []PermissionDetail
files := listGoFiles(resourcesDir)
for _, filePath := range files {
fileName := filepath.Base(filePath)
fset := token.NewFileSet()
f, err := parser.ParseFile(fset, filePath, nil, 0)
if err != nil {
fmt.Fprintf(os.Stderr, "warning: failed to parse %s: %v\n", filePath, err)
continue
}
// Build import map
gcpImports := extractGCPImports(f)
if len(gcpImports) == 0 {
continue
}
// Track client/service variables and find API calls
details = append(details, extractGCPgRPCCalls(f, gcpImports, fileName)...)
}
return details
}
// gcpImportInfo holds information about a GCP import.
type gcpImportInfo struct {
alias string // import alias used in code
service string // GCP service name (e.g., "compute", "iam", "kms")
style string // "rest" or "grpc"
path string // full import path
}
func extractGCPImports(f *ast.File) map[string]*gcpImportInfo {
result := map[string]*gcpImportInfo{}
for _, imp := range f.Imports {
path := strings.Trim(imp.Path.Value, `"`)
info := classifyGCPImport(path)
if info == nil {
continue
}
if imp.Name != nil {
info.alias = imp.Name.Name
}
result[info.alias] = info
}
return result
}
// classifyGCPImport determines if an import path is a GCP SDK and returns info.
func classifyGCPImport(path string) *gcpImportInfo {
// REST discovery-based APIs: google.golang.org/api/<service>/v1
// e.g., google.golang.org/api/compute/v1 -> parts: [google.golang.org, api, compute, v1]
if strings.HasPrefix(path, "google.golang.org/api/") {
parts := strings.Split(path, "/")
if len(parts) >= 3 {
svc := parts[2] // "compute", "dns", "sqladmin", etc.
return &gcpImportInfo{
alias: svc,
service: gcpServiceName(svc),
style: "rest",
path: path,
}
}
}
// gRPC client APIs: cloud.google.com/go/<service>/apiv1
// e.g., cloud.google.com/go/kms/apiv1 -> service "kms"
// cloud.google.com/go/spanner/admin/database/apiv1 -> service "spanner"
// cloud.google.com/go/logging/logadmin -> service "logging"
// cloud.google.com/go/pubsub -> service "pubsub"
// cloud.google.com/go/<service>[/<sub>...]/apiv1
// e.g., cloud.google.com/go/kms/apiv1 -> parts: [cloud.google.com, go, kms, apiv1]
// cloud.google.com/go/iam/admin/apiv1 -> parts: [cloud.google.com, go, iam, admin, apiv1]
// cloud.google.com/go/pubsub -> parts: [cloud.google.com, go, pubsub]
if strings.HasPrefix(path, "cloud.google.com/go/") {
parts := strings.Split(path, "/")
if len(parts) >= 3 {
// The primary service name is always parts[2] (first component after "go")
svc := parts[2] // "kms", "iam", "compute", "pubsub", etc.
// Determine the alias: use the last path component unless it's a version
alias := filepath.Base(path)
if strings.HasPrefix(alias, "apiv") || alias == "v2" {
alias = svc
}
// Skip protobuf packages (end in "pb")
if strings.HasSuffix(alias, "pb") {
return nil
}
return &gcpImportInfo{
alias: alias,
service: gcpServiceName(svc),
style: "grpc",
path: path,
}
}
}
return nil
}
// gcpServiceName normalizes GCP service names.
var gcpServiceNameMap = map[string]string{
"compute": "compute",
"cloudresourcemanager": "cloudresourcemanager",
"iam": "iam",
"dns": "dns",
"bigquery": "bigquery",
"logging": "logging",
"monitoring": "monitoring",
"container": "container",
"storage": "storage",
"sqladmin": "sqladmin",
"serviceusage": "serviceusage",
"apikeys": "apikeys",
"kms": "cloudkms",
"functions": "cloudfunctions",
"run": "run",
"artifactregistry": "artifactregistry",
"alloydb": "alloydb",
"aiplatform": "aiplatform",
"privateca": "privateca",
"binaryauthorization": "binaryauthorization",
"spanner": "spanner",
"redis": "redis",
"filestore": "file",
"scheduler": "cloudscheduler",
"deploy": "clouddeploy",
"firestore": "datastore",
"essentialcontacts": "essentialcontacts",
"accessapproval": "accessapproval",
"logadmin": "logging",
"pubsub": "pubsub",
"dataproc": "dataproc",
"notebooks": "notebooks",
"composer": "composer",
"bigtable": "bigtable",
"memcache": "memcache",
"recaptchaenterprise": "recaptchaenterprise",
"cloudbuild": "cloudbuild",
"certificatemanager": "certificatemanager",
"secretmanager": "secretmanager",
"batch": "batch",
"dataplex": "dataplex",
"orgpolicy": "orgpolicy",
}
func gcpServiceName(pkg string) string {
if name, ok := gcpServiceNameMap[pkg]; ok {
return name
}
return pkg
}
// extractGCPgRPCCalls finds gRPC client creation and subsequent method calls.
func extractGCPgRPCCalls(f *ast.File, imports map[string]*gcpImportInfo, fileName string) []PermissionDetail {
var details []PermissionDetail
ast.Inspect(f, func(n ast.Node) bool {
fn, ok := n.(*ast.FuncDecl)
if !ok {
return true
}
if fn.Body == nil {
return true
}
// Track client variables: varName -> service info
clientVars := map[string]*gcpImportInfo{}
// Also track REST service variables
restVars := map[string]*gcpImportInfo{}
ast.Inspect(fn.Body, func(n ast.Node) bool {
assignStmt, ok := n.(*ast.AssignStmt)
if !ok {
return true
}
for i, rhs := range assignStmt.Rhs {
call, ok := rhs.(*ast.CallExpr)
if !ok {
continue
}
sel, ok := call.Fun.(*ast.SelectorExpr)
if !ok {
continue
}
methodName := sel.Sel.Name
pkgIdent, ok := sel.X.(*ast.Ident)
if !ok {
continue
}
pkgName := pkgIdent.Name
imp, isGCPImport := imports[pkgName]
if !isGCPImport {
continue
}
// gRPC client creation: pkg.NewXxxClient(ctx, ...)
if strings.HasPrefix(methodName, "New") && strings.HasSuffix(methodName, "Client") && imp.style == "grpc" {
if i < len(assignStmt.Lhs) {
if ident, ok := assignStmt.Lhs[i].(*ast.Ident); ok {
clientVars[ident.Name] = imp
}
}
}
// REST service creation: pkg.NewService(ctx, ...)
if methodName == "NewService" && imp.style == "rest" {
if i < len(assignStmt.Lhs) {
if ident, ok := assignStmt.Lhs[i].(*ast.Ident); ok {
restVars[ident.Name] = imp
}
}
}
}
return true
})
// Now find calls on client variables: client.ListXxx(ctx, req)
ast.Inspect(fn.Body, func(n ast.Node) bool {
call, ok := n.(*ast.CallExpr)
if !ok {
return true
}
sel, ok := call.Fun.(*ast.SelectorExpr)
if !ok {
return true
}
methodName := sel.Sel.Name
// gRPC client calls
if ident, ok := sel.X.(*ast.Ident); ok {
if imp, ok := clientVars[ident.Name]; ok {
if isGCPAPIMethod(methodName) {
perm := gcpMethodToPermission(imp.service, methodName)
if perm != "" {
details = append(details, PermissionDetail{
Permission: perm,
Service: imp.service,
Action: methodName,
SourceFile: fileName,
})
}
}
}
}
// REST chained calls: restVar.Resource.Method(...)
if innerSel, ok := sel.X.(*ast.SelectorExpr); ok {
resource := innerSel.Sel.Name
if ident, ok := innerSel.X.(*ast.Ident); ok {
if imp, ok := restVars[ident.Name]; ok {
perm := gcpRESTToPermission(imp.service, resource, methodName)
if perm != "" {
details = append(details, PermissionDetail{
Permission: perm,
Service: imp.service,
Action: resource + "." + methodName,
SourceFile: fileName,
})
}
}
}
// Deeper chains: restVar.Projects.Locations.Resource.Method(...)
if innerSel2, ok := innerSel.X.(*ast.SelectorExpr); ok {
_ = innerSel2
// Walk up the chain to find the root variable
rootVar, chain := walkSelectorChain(sel)
if rootVar != "" {
if imp, ok := restVars[rootVar]; ok {
// The last element is the method, the rest form the resource path
if len(chain) >= 2 {
method := chain[len(chain)-1]
// Find the meaningful resource (skip "Projects", "Locations")
resourceName := findMeaningfulResource(chain[:len(chain)-1])
perm := gcpRESTToPermission(imp.service, resourceName, method)
if perm != "" {
details = append(details, PermissionDetail{
Permission: perm,
Service: imp.service,
Action: resourceName + "." + method,
SourceFile: fileName,
})
}
}
}
}
}
}
return true
})
return false
})
return details
}
// walkSelectorChain walks a nested selector expression and returns the root variable
// name and the chain of selected names.
// e.g., svc.Projects.Locations.Keys.List -> ("svc", ["Projects", "Locations", "Keys", "List"])
func walkSelectorChain(sel *ast.SelectorExpr) (string, []string) {
chain := []string{sel.Sel.Name}
current := sel.X
for {
switch x := current.(type) {
case *ast.SelectorExpr:
chain = append([]string{x.Sel.Name}, chain...)
current = x.X
case *ast.Ident:
return x.Name, chain
case *ast.CallExpr:
// Handle cases like svc.Method().Chain
if s, ok := x.Fun.(*ast.SelectorExpr); ok {
chain = append([]string{s.Sel.Name}, chain...)
current = s.X
} else {
return "", chain
}
default:
return "", chain
}
}
}
// findMeaningfulResource finds the meaningful resource name from a chain,
// skipping common parent levels like "Projects", "Locations".
func findMeaningfulResource(chain []string) string {
skip := map[string]bool{
"Projects": true, "Locations": true, "Regions": true,
"Zones": true, "Global": true,
}
for i := len(chain) - 1; i >= 0; i-- {
if !skip[chain[i]] {
return chain[i]
}
}
if len(chain) > 0 {
return chain[len(chain)-1]
}
return ""
}
func isGCPAPIMethod(name string) bool {
prefixes := []string{
"List", "Get", "Create", "Delete", "Update", "Set",
"Aggregated", "Search", "Test",
}
for _, p := range prefixes {
if strings.HasPrefix(name, p) {
return true
}
}
return false
}
// gcpMethodToPermission maps a gRPC method to a GCP IAM permission.
func gcpMethodToPermission(service, method string) string {
// gRPC methods: ListKeyRings -> cloudkms.keyRings.list
// ListServiceAccounts -> iam.serviceAccounts.list
// GetKeyRotationStatus -> cloudkms.cryptoKeys.get
verb := ""
resource := ""
if strings.HasPrefix(method, "AggregatedList") {
verb = "list"
resource = strings.TrimPrefix(method, "AggregatedList")
} else if strings.HasPrefix(method, "List") {
verb = "list"
resource = strings.TrimPrefix(method, "List")
} else if strings.HasPrefix(method, "Get") {
verb = "get"
resource = strings.TrimPrefix(method, "Get")
if resource == "" {
resource = service
}
} else if strings.HasPrefix(method, "Create") {
verb = "create"
resource = strings.TrimPrefix(method, "Create")
} else if strings.HasPrefix(method, "Delete") {
verb = "delete"
resource = strings.TrimPrefix(method, "Delete")
} else if strings.HasPrefix(method, "Update") {
verb = "update"
resource = strings.TrimPrefix(method, "Update")
} else if strings.HasPrefix(method, "Set") {
verb = "update"
resource = strings.TrimPrefix(method, "Set")
} else if strings.HasPrefix(method, "Test") {
verb = "get"
resource = strings.TrimPrefix(method, "Test")
} else if strings.HasPrefix(method, "Search") {
verb = "list"
resource = strings.TrimPrefix(method, "Search")
} else {
return ""
}
if resource == "" {
return ""
}
// Convert PascalCase to camelCase
resource = strings.ToLower(resource[:1]) + resource[1:]
return service + "." + resource + "." + verb
}
// gcpRESTToPermission maps a REST-style call to a GCP IAM permission.
func gcpRESTToPermission(service, resource, method string) string {
if resource == "" {
return ""
}
verb := ""
switch method {
case "List", "AggregatedList", "Pages":
verb = "list"
case "Get", "Do":
verb = "get"
case "Create", "Insert":
verb = "create"
case "Delete":
verb = "delete"
case "Update", "Patch":
verb = "update"
case "GetIamPolicy":
return service + "." + strings.ToLower(resource[:1]) + resource[1:] + ".getIamPolicy"
case "SetIamPolicy":
return service + "." + strings.ToLower(resource[:1]) + resource[1:] + ".setIamPolicy"
default:
verb = strings.ToLower(method)
}
// Convert PascalCase resource to camelCase
res := strings.ToLower(resource[:1]) + resource[1:]
return service + "." + res + "." + verb
}
// =============================================================================
// Azure Permission Extraction
// =============================================================================
func extractAzurePermissions(resourcesDir string) []PermissionDetail {
var details []PermissionDetail
files := listGoFiles(resourcesDir)
for _, filePath := range files {
fileName := filepath.Base(filePath)
fset := token.NewFileSet()
f, err := parser.ParseFile(fset, filePath, nil, 0)
if err != nil {
fmt.Fprintf(os.Stderr, "warning: failed to parse %s: %v\n", filePath, err)
continue
}
// Build import map: alias -> ARM info
azureImports := extractAzureImports(f)
if len(azureImports) == 0 {
continue
}