-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
832 lines (767 loc) · 28.8 KB
/
Copy pathmain.go
File metadata and controls
832 lines (767 loc) · 28.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"slices"
"strings"
policyManager "github.com/compliance-framework/agent/policy-manager"
"github.com/compliance-framework/agent/runner"
"github.com/compliance-framework/agent/runner/proto"
"github.com/google/go-github/v71/github"
"github.com/hashicorp/go-hclog"
goplugin "github.com/hashicorp/go-plugin"
"github.com/mitchellh/mapstructure"
)
type OperationalMode string
const (
OperationalModeBundled OperationalMode = "Bundled" // default: one evidence per repo
OperationalModeGranular OperationalMode = "Granular" // one evidence per alert/CVE
)
type PluginConfig struct {
Token string `mapstructure:"token"`
Organization *string `mapstructure:"organization"`
IncludedRepositories *string `mapstructure:"included-repositories"`
User *string `mapstructure:"user"`
SecurityTeamName *string `mapstructure:"security-team-name"`
OperationalMode OperationalMode `mapstructure:"operational-mode"`
}
type ParsedConfig struct {
Token string `mapstructure:"token"`
Organization *string `mapstructure:"organization"`
IncludedRepositories []string `mapstructure:"included-repositories"`
User *string `mapstructure:"user"`
SecurityTeamName *string `mapstructure:"security-team-name"`
OperationalMode OperationalMode `mapstructure:"operational-mode"`
}
type DependabotPlugin struct {
logger hclog.Logger
config *PluginConfig
parsedConfig *ParsedConfig
githubClient *github.Client
}
type DependabotData struct {
Alerts []*github.DependabotAlert `json:"alerts"`
// Pointer-to-slice allows distinguishing: nil (not configured/fetched) vs &[] (empty team) vs &[members] (has members).
// omitempty omits nil, but emits empty or non-empty slices.
SecurityTeamMembers *[]*github.User `json:"security_team_members,omitempty"`
}
var errDependabotAlertsPermissionDenied = errors.New("insufficient permissions to fetch dependabot alerts")
var dependabotAlertStates = []string{"auto_dismissed", "dismissed", "fixed", "open"}
var (
granularActivities = []*proto.Activity{
{Title: "Collect Individual Dependabot Alert"},
}
granularActors = []*proto.OriginActor{
{
Title: "The Continuous Compliance Framework",
Type: "assessment-platform",
Links: []*proto.Link{
{
Href: "https://compliance-framework.github.io/docs/",
Rel: policyManager.Pointer("reference"),
Text: policyManager.Pointer("The Continuous Compliance Framework"),
},
},
},
{
Title: "Continuous Compliance Framework - Dependabot Plugin",
Type: "tool",
Links: []*proto.Link{
{
Href: "https://github.com/compliance-framework/plugin-dependabot",
Rel: policyManager.Pointer("reference"),
Text: policyManager.Pointer("The Continuous Compliance Framework Dependabot Plugin"),
},
},
},
}
granularComponents = []*proto.Component{
{
Identifier: "common-components/github-repository",
Type: "service",
Title: "GitHub Repository",
Description: "A GitHub repository is a discrete codebase or project workspace hosted within a GitHub Organization or user account.",
Purpose: "To serve as the authoritative and version-controlled location for a specific software project.",
},
}
)
type granularPolicyContext struct {
labelsBase map[string]string
inventory []*proto.InventoryItem
subjects []*proto.Subject
}
func (l *DependabotPlugin) ParseConfig() {
l.parsedConfig = &ParsedConfig{}
if l.config.IncludedRepositories != nil {
l.parsedConfig.IncludedRepositories = strings.Split(*l.config.IncludedRepositories, ",")
}
l.parsedConfig.Token = l.config.Token
l.parsedConfig.Organization = l.config.Organization
l.parsedConfig.User = l.config.User
l.parsedConfig.SecurityTeamName = l.config.SecurityTeamName
switch strings.ToLower(string(l.config.OperationalMode)) {
case strings.ToLower(string(OperationalModeGranular)):
l.parsedConfig.OperationalMode = OperationalModeGranular
case strings.ToLower(string(OperationalModeBundled)):
l.parsedConfig.OperationalMode = OperationalModeBundled
default:
l.logger.Debug("ParseConfig: operational-mode not set or unrecognised, defaulting to Bundled", "raw_value", l.config.OperationalMode)
l.parsedConfig.OperationalMode = OperationalModeBundled
}
l.logger.Debug("ParseConfig: resolved operational mode",
"raw_value", l.config.OperationalMode,
"resolved_value", l.parsedConfig.OperationalMode,
"included_repositories", l.parsedConfig.IncludedRepositories,
)
}
func (l *DependabotPlugin) Configure(req *proto.ConfigureRequest) (*proto.ConfigureResponse, error) {
config := &PluginConfig{}
if err := mapstructure.Decode(req.GetConfig(), config); err != nil {
l.logger.Error("Configure: failed to decode config", "error", err)
return nil, err
}
l.config = config
l.logger.Debug("Configure: received raw config",
"operational_mode", l.config.OperationalMode,
"organization", l.config.Organization,
"included_repositories", l.config.IncludedRepositories,
"security_team_name", l.config.SecurityTeamName,
)
l.ParseConfig()
l.githubClient = github.NewClient(nil).WithAuthToken(l.parsedConfig.Token)
return &proto.ConfigureResponse{}, nil
}
func (l *DependabotPlugin) Init(req *proto.InitRequest, apiHelper runner.ApiHelper) (*proto.InitResponse, error) {
ctx := context.Background()
l.logger.Debug("Init: starting with operational mode", "operational_mode", l.parsedConfig.OperationalMode)
subjectTemplates := []*proto.SubjectTemplate{
{
Name: "dependabot-repository",
Type: proto.SubjectType_SUBJECT_TYPE_COMPONENT,
TitleTemplate: "Dependabot for repository: {{ .repository }}",
DescriptionTemplate: "Dependabot alerts for GitHub repository {{ .repository }} in organization {{ .organization }}",
PurposeTemplate: "Represents Dependabot monitoring for a GitHub repository being evaluated for compliance",
IdentityLabelKeys: []string{"repository", "organization"},
SelectorLabels: []*proto.SubjectLabelSelector{},
LabelSchema: []*proto.SubjectLabelSchema{
{Key: "repository", Description: "The name of the GitHub repository"},
{Key: "organization", Description: "The GitHub organization owning the repository"},
},
},
}
return runner.InitWithSubjectsAndRisksFromPolicies(ctx, l.logger, req, apiHelper, subjectTemplates)
}
func (l *DependabotPlugin) Eval(req *proto.EvalRequest, apiHelper runner.ApiHelper) (*proto.EvalResponse, error) {
ctx := context.Background()
l.logger.Debug("Eval: starting", "operational_mode", l.parsedConfig.OperationalMode, "policy_paths", req.GetPolicyPaths())
repochan, errchan := l.FetchRepositories(ctx)
l.logger.Debug("Fetching repositories from Github API")
var securityTeamMembers []*github.User
if l.parsedConfig.SecurityTeamName != nil && *l.parsedConfig.SecurityTeamName != "" {
var err error
securityTeamMembers, err = l.FetchSecurityTeamMembers(ctx)
if err != nil {
l.logger.Error("Failed to fetch security team members from Github API", "error", err)
return &proto.EvalResponse{
Status: proto.ExecutionStatus_FAILURE,
}, err
}
}
done := false
// Track permission issues during alert collection
reposAlertsPermissionDenied := make([]string, 0)
for !done {
select {
case err, ok := <-errchan:
if !ok {
done = true
continue
}
l.logger.Debug("Error fetching repositories from Github API", "error", err)
return &proto.EvalResponse{
Status: proto.ExecutionStatus_FAILURE,
}, err
case repo, ok := <-repochan:
if !ok {
done = true
continue
}
l.logger.Debug("Fetching repository dependabot alerts from Github API", "repo", repo.GetFullName())
alerts, err := l.FetchRepositoryDependabotAlerts(ctx, repo)
if err != nil {
if errors.Is(err, errDependabotAlertsPermissionDenied) {
l.logger.Warn("Skipping repository due to insufficient permissions for alerts fetch", "repo", repo.GetFullName(), "error", err)
reposAlertsPermissionDenied = append(reposAlertsPermissionDenied, repo.GetFullName())
continue
}
l.logger.Error("Failed to fetch repository dependabot alerts from Github API", "repo", repo.GetFullName(), "error", err)
return &proto.EvalResponse{
Status: proto.ExecutionStatus_FAILURE,
}, err
}
l.logger.Debug("Eval: dispatching repo",
"repo", repo.GetFullName(),
"operational_mode", l.parsedConfig.OperationalMode,
"operational_mode_bytes", fmt.Sprintf("%q", string(l.parsedConfig.OperationalMode)),
"is_granular", l.parsedConfig.OperationalMode == OperationalModeGranular,
)
switch l.parsedConfig.OperationalMode {
case OperationalModeGranular:
l.logger.Debug("Eval: using granular path", "repo", repo.GetFullName())
if err := l.evalForGranular(ctx, repo, alerts, req, apiHelper); err != nil {
return &proto.EvalResponse{Status: proto.ExecutionStatus_FAILURE}, err
}
default:
l.logger.Debug("Eval: using bundle path", "repo", repo.GetFullName())
if err := l.evalForBundle(ctx, repo, alerts, securityTeamMembers, req, apiHelper); err != nil {
return &proto.EvalResponse{Status: proto.ExecutionStatus_FAILURE}, err
}
}
}
}
if len(reposAlertsPermissionDenied) > 0 {
l.logger.Info("Repositories skipped due to insufficient permissions (alerts)", "count", len(reposAlertsPermissionDenied), "repos", reposAlertsPermissionDenied)
}
return &proto.EvalResponse{
Status: proto.ExecutionStatus_SUCCESS,
}, nil
}
func (l *DependabotPlugin) evalForGranular(ctx context.Context, repo *github.Repository, alerts []*github.DependabotAlert, req *proto.EvalRequest, apiHelper runner.ApiHelper) error {
l.logger.Debug("evalForGranular: starting", "repo", repo.GetFullName(), "alert_count", len(alerts), "policy_paths", req.GetPolicyPaths())
if len(req.GetPolicyPaths()) == 0 {
l.logger.Debug("evalForGranular: skipping repo because no policy paths were configured", "repo", repo.GetFullName())
return nil
}
policyContext := newGranularPolicyContext(repo)
totalEvidence := 0
for i, alert := range alerts {
cveID := granularAlertIdentifier(alert)
l.logger.Debug("evalForGranular: evaluating alert", "index", i, "cve_id", cveID, "state", alert.GetState())
alertEvidences, err := l.EvaluateGranularPolicies(ctx, repo, alert, req, policyContext)
if err != nil {
l.logger.Error("Failed to evaluate granular policies", "repo", repo.GetFullName(), "cve_id", cveID, "error", err)
return err
}
l.logger.Debug("evalForGranular: evidence produced", "cve_id", cveID, "count", len(alertEvidences))
totalEvidence += len(alertEvidences)
if len(alertEvidences) == 0 {
l.logger.Debug("evalForGranular: skipping evidence submission because policy evaluation produced no evidence", "cve_id", cveID, "repo", repo.GetFullName())
continue
}
if err = apiHelper.CreateEvidence(ctx, alertEvidences); err != nil {
l.logger.Error("Failed to send granular evidence", "repo", repo.GetFullName(), "cve_id", cveID, "error", err)
return err
}
l.logger.Debug("evalForGranular: evidence sent", "cve_id", cveID)
}
l.logger.Info("Granular evaluation summary", "repo", repo.GetFullName(), "alert_count", len(alerts), "evidence_count", totalEvidence)
return nil
}
func (l *DependabotPlugin) evalForBundle(ctx context.Context, repo *github.Repository, alerts []*github.DependabotAlert, securityTeamMembers []*github.User, req *proto.EvalRequest, apiHelper runner.ApiHelper) error {
l.logger.Debug("evalForBundle: starting", "repo", repo.GetFullName(), "alert_count", len(alerts), "policy_paths", req.GetPolicyPaths())
data := &DependabotData{
Alerts: alerts,
}
if securityTeamMembers != nil {
data.SecurityTeamMembers = &securityTeamMembers
}
evidences, err := l.EvaluatePolicies(ctx, repo, data, req)
if err != nil {
l.logger.Error("Failed to evaluate policies", "repo", repo.GetFullName(), "error", err)
return err
}
l.logger.Debug("evalForBundle: evidence produced", "repo", repo.GetFullName(), "count", len(evidences))
if err = apiHelper.CreateEvidence(ctx, evidences); err != nil {
l.logger.Error("Failed to send evidence", "repo", repo.GetFullName(), "error", err)
return err
}
l.logger.Debug("evalForBundle: evidence sent", "repo", repo.GetFullName())
return nil
}
func (l *DependabotPlugin) FetchSecurityTeamMembers(ctx context.Context) ([]*github.User, error) {
members, _, err := l.githubClient.Teams.ListTeamMembersBySlug(ctx, *l.parsedConfig.Organization, *l.parsedConfig.SecurityTeamName, nil)
if err != nil {
if isPermissionError(err) {
return nil, nil
}
return nil, err
}
return members, nil
}
func (l *DependabotPlugin) FetchRepositoryDependabotAlerts(ctx context.Context, repo *github.Repository) ([]*github.DependabotAlert, error) {
stateFilter := dependabotAlertStateFilter()
opts := &github.ListAlertsOptions{
State: &stateFilter,
ListCursorOptions: github.ListCursorOptions{
PerPage: 100,
},
}
allAlerts := make([]*github.DependabotAlert, 0)
for {
alerts, resp, err := l.githubClient.Dependabot.ListRepoAlerts(ctx, repo.GetOwner().GetLogin(), repo.GetName(), opts)
if isPermissionError(err) {
return nil, fmt.Errorf("%w: %s: %v", errDependabotAlertsPermissionDenied, repo.GetFullName(), err)
}
if err != nil {
return nil, err
}
allAlerts = append(allAlerts, alerts...)
if !advanceDependabotAlertsPage(opts, resp) {
break
}
}
l.logger.Debug("Fetched repository dependabot alerts from GitHub API", "repo", repo.GetFullName(), "state", stateFilter, "count", len(allAlerts))
return allAlerts, nil
}
func dependabotAlertStateFilter() string {
return strings.Join(dependabotAlertStates, ",")
}
func advanceDependabotAlertsPage(opts *github.ListAlertsOptions, resp *github.Response) bool {
if resp == nil {
return false
}
if resp.Cursor != "" {
opts.ListCursorOptions.Cursor = resp.Cursor
opts.ListCursorOptions.Page = ""
opts.ListOptions.Page = 0
return true
}
if resp.NextPageToken != "" {
opts.ListCursorOptions.Page = resp.NextPageToken
opts.ListCursorOptions.Cursor = ""
opts.ListOptions.Page = 0
return true
}
if resp.NextPage != 0 {
opts.ListOptions.Page = resp.NextPage
opts.ListCursorOptions.Page = ""
opts.ListCursorOptions.Cursor = ""
return true
}
return false
}
func (l *DependabotPlugin) FetchRepositories(ctx context.Context) (<-chan *github.Repository, <-chan error) {
repositories := make(chan *github.Repository)
errs := make(chan error)
go func() {
defer close(repositories)
defer close(errs)
page := 1
done := false
// Tracking for logging visibility
emittedRepos := make([]string, 0)
noPermissionRepos := make([]string, 0)
archivedSkipped := 0
for !done {
l.logger.Trace("Fetching repositories from Github API")
repos, _, err := l.githubClient.Repositories.ListByOrg(ctx, *l.parsedConfig.Organization, &github.RepositoryListByOrgOptions{
ListOptions: github.ListOptions{
Page: page,
},
})
if err != nil {
l.logger.Error("Failed while fetching repositories from Github API", "error", err)
errs <- err
done = true
break
}
for _, repo := range repos {
if repo.GetArchived() {
l.logger.Debug("Skipping archived repository", "repo", repo.GetFullName())
archivedSkipped++
continue
}
alertsEnabled, _, err := l.githubClient.Repositories.GetVulnerabilityAlerts(ctx, repo.GetOwner().GetLogin(), repo.GetName())
if err != nil {
if isPermissionError(err) {
l.logger.Warn("Skipping repository due to insufficient permissions for vulnerability alerts check", "repo", repo.GetFullName(), "error", err)
noPermissionRepos = append(noPermissionRepos, repo.GetFullName())
continue
}
l.logger.Error("Failed while fetching vulnerability alerts from Github API", "repo", repo.GetFullName(), "error", err)
errs <- err
done = true
break
}
if alertsEnabled {
if l.parsedConfig.IncludedRepositories != nil {
if !slices.Contains(l.parsedConfig.IncludedRepositories, repo.GetFullName()) {
l.logger.Debug("Skipping repository due to not being explicitly included in config", "repo", repo.GetFullName())
continue
}
}
repositories <- repo
emittedRepos = append(emittedRepos, repo.GetFullName())
}
}
page++
if len(repos) == 0 {
done = true
break
}
}
// Emit a summary for engineers to understand visibility
l.logger.Info("Repository enumeration summary", "emitted", len(emittedRepos), "skipped_permissions", len(noPermissionRepos), "skipped_archived", archivedSkipped)
if len(emittedRepos) > 0 {
l.logger.Debug("Repositories with sufficient permissions (and alerts enabled)", "repos", emittedRepos)
}
if len(noPermissionRepos) > 0 {
l.logger.Info("Repositories without sufficient permissions", "repos", noPermissionRepos)
}
}()
return repositories, errs
}
func (l *DependabotPlugin) EvaluatePolicies(ctx context.Context, repo *github.Repository, data *DependabotData, req *proto.EvalRequest) ([]*proto.Evidence, error) {
var accumulatedErrors error
activities := make([]*proto.Activity, 0)
evidences := make([]*proto.Evidence, 0)
activities = append(activities, &proto.Activity{
Title: "Collect Repository Dependabot Alerts",
})
actors := []*proto.OriginActor{
{
Title: "The Continuous Compliance Framework",
Type: "assessment-platform",
Links: []*proto.Link{
{
Href: "https://compliance-framework.github.io/docs/",
Rel: policyManager.Pointer("reference"),
Text: policyManager.Pointer("The Continuous Compliance Framework"),
},
},
Props: nil,
},
{
Title: "Continuous Compliance Framework - Dependabot Plugin",
Type: "tool",
Links: []*proto.Link{
{
Href: "https://github.com/compliance-framework/plugin-dependabot",
Rel: policyManager.Pointer("reference"),
Text: policyManager.Pointer("The Continuous Compliance Framework Dependabot Plugin"),
},
},
Props: nil,
},
}
components := []*proto.Component{
{
Identifier: "common-components/github-repository",
Type: "service",
Title: "GitHub Repository",
Description: "A GitHub repository is a discrete codebase or project workspace hosted within a GitHub Organization or user account. It contains source code, documentation, configuration files, workflows, and version history managed through Git. Repositories support access control, issues, pull requests, branch protection, and automated CI/CD pipelines.",
Purpose: "To serve as the authoritative and version-controlled location for a specific software project, enabling secure collaboration, code review, automation, and traceability of changes throughout the development lifecycle.",
},
{
Identifier: "common-components/version-control",
Type: "service",
Title: "Version Control",
Description: "Version control systems track and manage changes to source code and configuration files over time. They provide collaboration, traceability, and the ability to audit or revert code to previous states. Version control enables parallel development workflows and structured release management across software projects.",
Purpose: "To maintain a complete and auditable history of code and configuration changes, enable collaboration across distributed teams, and support secure and traceable software development lifecycle (SDLC) practices.",
},
}
inventory := []*proto.InventoryItem{
{
Identifier: fmt.Sprintf("github-repository/%s", repo.GetFullName()),
Type: "github-repository",
Title: fmt.Sprintf("GitHub Repository [%s]", repo.GetName()),
Props: []*proto.Property{
{
Name: "name",
Value: repo.GetName(),
},
{
Name: "path",
Value: repo.GetFullName(),
},
{
Name: "organization",
Value: repo.GetOwner().GetLogin(),
},
},
Links: []*proto.Link{
{
Href: repo.GetURL(),
Text: policyManager.Pointer("Repository URL"),
},
},
ImplementedComponents: []*proto.InventoryItemImplementedComponent{
{
Identifier: "common-components/github-repository",
},
{
Identifier: "common-components/version-control",
},
},
},
}
subjects := []*proto.Subject{
{
Type: proto.SubjectType_SUBJECT_TYPE_INVENTORY_ITEM,
Identifier: fmt.Sprintf("github-repository/%s", repo.GetFullName()),
},
{
Type: proto.SubjectType_SUBJECT_TYPE_INVENTORY_ITEM,
Identifier: fmt.Sprintf("github-organization/%s", repo.GetOwner().GetLogin()),
},
{
Type: proto.SubjectType_SUBJECT_TYPE_COMPONENT,
Identifier: "common-components/github-repository",
},
{
Type: proto.SubjectType_SUBJECT_TYPE_COMPONENT,
Identifier: "common-components/version-control",
},
}
for _, policyPath := range req.GetPolicyPaths() {
l.logger.Debug("EvaluatePolicies: running policy", "repo", repo.GetFullName(), "policy_path", policyPath)
// Explicitly reset steps to make things readable
processor := policyManager.NewPolicyProcessor(
l.logger,
map[string]string{
"provider": "github",
"type": "repository",
"repository": repo.GetName(),
"organization": repo.GetOwner().GetLogin(),
},
subjects,
components,
inventory,
actors,
activities,
)
if l.logger.IsTrace() {
if inputJSON, jsonErr := json.Marshal(data); jsonErr == nil {
l.logger.Trace("EvaluatePolicies: policy input", "policy_path", policyPath, "input", string(inputJSON))
} else {
l.logger.Trace("EvaluatePolicies: failed to marshal policy input", "policy_path", policyPath, "error", jsonErr)
}
}
evidence, err := processor.GenerateResults(ctx, policyPath, data)
l.logger.Debug("EvaluatePolicies: policy result", "policy_path", policyPath, "evidence_count", len(evidence), "error", err)
evidences = slices.Concat(evidences, evidence)
if err != nil {
accumulatedErrors = errors.Join(accumulatedErrors, err)
}
}
appendEvidenceLink(evidences, repositorySecurityLink(repo))
l.logger.Info("collected evidence", "count", len(evidences))
return evidences, accumulatedErrors
}
func (l *DependabotPlugin) EvaluateGranularPolicies(ctx context.Context, repo *github.Repository, alert *github.DependabotAlert, req *proto.EvalRequest, policyContext *granularPolicyContext) ([]*proto.Evidence, error) {
var accumulatedErrors error
labels := buildGranularPolicyLabels(policyContext.labelsBase, alert)
cveID := labels["cve_id"]
evidences := make([]*proto.Evidence, 0)
for _, policyPath := range req.GetPolicyPaths() {
l.logger.Debug("EvaluateGranularPolicies: running policy", "cve_id", cveID, "repo", repo.GetFullName(), "policy_path", policyPath)
processor := policyManager.NewPolicyProcessor(
l.logger,
labels,
policyContext.subjects,
granularComponents,
policyContext.inventory,
granularActors,
granularActivities,
)
policyInput := granularPolicyInput(alert)
if l.logger.IsTrace() {
if inputJSON, jsonErr := json.Marshal(policyInput); jsonErr == nil {
l.logger.Trace("EvaluateGranularPolicies: policy input", "cve_id", cveID, "policy_path", policyPath, "input", string(inputJSON))
} else {
l.logger.Trace("EvaluateGranularPolicies: failed to marshal policy input", "cve_id", cveID, "policy_path", policyPath, "error", jsonErr)
}
}
evidence, err := processor.GenerateResults(ctx, policyPath, policyInput)
l.logger.Debug("EvaluateGranularPolicies: policy result", "cve_id", cveID, "policy_path", policyPath, "evidence_count", len(evidence), "error", err)
evidences = slices.Concat(evidences, evidence)
if err != nil {
accumulatedErrors = errors.Join(accumulatedErrors, err)
}
}
appendEvidenceLink(evidences, dependabotAlertLink(repo, alert))
l.logger.Debug("collected granular evidence", "cve_id", cveID, "repo", repo.GetFullName(), "count", len(evidences))
return evidences, accumulatedErrors
}
func appendEvidenceLink(evidences []*proto.Evidence, link *proto.Link) {
if link == nil || link.GetHref() == "" {
return
}
for _, evidence := range evidences {
if evidence == nil {
continue
}
evidence.Links = append(evidence.Links, &proto.Link{
Href: link.GetHref(),
Rel: policyManager.Pointer(link.GetRel()),
Text: policyManager.Pointer(link.GetText()),
})
}
}
func repositorySecurityLink(repo *github.Repository) *proto.Link {
repositoryURL := repositoryWebURL(repo)
if repositoryURL == "" {
return nil
}
return &proto.Link{
Href: fmt.Sprintf("%s/security", repositoryURL),
Rel: policyManager.Pointer("reference"),
Text: policyManager.Pointer("Repository security page"),
}
}
func dependabotAlertLink(repo *github.Repository, alert *github.DependabotAlert) *proto.Link {
if alert == nil {
return nil
}
if alert.GetHTMLURL() != "" {
return &proto.Link{
Href: alert.GetHTMLURL(),
Rel: policyManager.Pointer("reference"),
Text: policyManager.Pointer("Dependabot alert"),
}
}
if alert.GetNumber() == 0 {
return nil
}
repositoryURL := repositoryWebURL(repo)
if repositoryURL == "" {
return nil
}
return &proto.Link{
Href: fmt.Sprintf("%s/security/dependabot/%d", repositoryURL, alert.GetNumber()),
Rel: policyManager.Pointer("reference"),
Text: policyManager.Pointer("Dependabot alert"),
}
}
func repositoryWebURL(repo *github.Repository) string {
if repo == nil {
return ""
}
if repo.GetHTMLURL() != "" {
return strings.TrimRight(repo.GetHTMLURL(), "/")
}
if repo.GetFullName() != "" {
return fmt.Sprintf("https://github.com/%s", repo.GetFullName())
}
if repo.GetOwner().GetLogin() != "" && repo.GetName() != "" {
return fmt.Sprintf("https://github.com/%s/%s", repo.GetOwner().GetLogin(), repo.GetName())
}
return ""
}
func newGranularPolicyContext(repo *github.Repository) *granularPolicyContext {
repositoryIdentifier := fmt.Sprintf("github-repository/%s", repo.GetFullName())
return &granularPolicyContext{
labelsBase: map[string]string{
"provider": "github",
"type": "dependabot",
"repository": repo.GetName(),
"organization": repo.GetOwner().GetLogin(),
},
inventory: []*proto.InventoryItem{
{
Identifier: repositoryIdentifier,
Type: "github-repository",
Title: fmt.Sprintf("GitHub Repository [%s]", repo.GetName()),
Props: []*proto.Property{
{Name: "name", Value: repo.GetName()},
{Name: "path", Value: repo.GetFullName()},
{Name: "organization", Value: repo.GetOwner().GetLogin()},
},
Links: []*proto.Link{
{
Href: repo.GetURL(),
Text: policyManager.Pointer("Repository URL"),
},
},
ImplementedComponents: []*proto.InventoryItemImplementedComponent{
{Identifier: "common-components/github-repository"},
},
},
},
subjects: []*proto.Subject{
{
Type: proto.SubjectType_SUBJECT_TYPE_INVENTORY_ITEM,
Identifier: repositoryIdentifier,
},
{
Type: proto.SubjectType_SUBJECT_TYPE_INVENTORY_ITEM,
Identifier: fmt.Sprintf("github-organization/%s", repo.GetOwner().GetLogin()),
},
{
Type: proto.SubjectType_SUBJECT_TYPE_COMPONENT,
Identifier: "common-components/github-repository",
},
},
}
}
func buildGranularPolicyLabels(baseLabels map[string]string, alert *github.DependabotAlert) map[string]string {
severity := alert.GetSecurityVulnerability().GetSeverity()
impact := severity
if severity == "medium" {
impact = "moderate"
}
var cvssScoreVal float64
if score := alert.GetSecurityAdvisory().GetCVSS().GetScore(); score != nil {
cvssScoreVal = *score
}
labels := make(map[string]string, len(baseLabels)+6)
for key, value := range baseLabels {
labels[key] = value
}
labels["cve_id"] = granularAlertIdentifier(alert)
labels["package_name"] = alert.GetDependency().GetPackage().GetName()
labels["ecosystem"] = alert.GetDependency().GetPackage().GetEcosystem()
labels["severity"] = severity
labels["impact"] = impact
labels["cvss_score"] = fmt.Sprintf("%.1f", cvssScoreVal)
return labels
}
func granularAlertIdentifier(alert *github.DependabotAlert) string {
cveID := alert.GetSecurityAdvisory().GetCVEID()
if cveID == "" {
cveID = alert.GetSecurityAdvisory().GetGHSAID()
}
return cveID
}
func granularPolicyInput(alert *github.DependabotAlert) []*github.DependabotAlert {
return []*github.DependabotAlert{alert}
}
// isPermissionError returns true if the error from the GitHub client indicates
// a permissions or visibility issue (e.g., 401/403/404).
func isPermissionError(err error) bool {
if err == nil {
return false
}
var ger *github.ErrorResponse
if errors.As(err, &ger) {
if ger.Response != nil {
switch ger.Response.StatusCode {
case 401, 403, 404:
return true
}
}
}
return false
}
func main() {
logger := hclog.New(&hclog.LoggerOptions{
Level: hclog.Debug,
JSONFormat: true,
})
dependabot := &DependabotPlugin{
logger: logger,
}
// pluginMap is the map of plugins we can dispense.
logger.Debug("initiating dependabot plugin")
goplugin.Serve(&goplugin.ServeConfig{
HandshakeConfig: runner.HandshakeConfig,
Plugins: map[string]goplugin.Plugin{
"runner": &runner.RunnerV2GRPCPlugin{
Impl: dependabot,
},
},
GRPCServer: goplugin.DefaultGRPCServer,
})
}