• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

mindersec / minder / 13311125525

13 Feb 2025 03:26PM UTC coverage: 57.509% (-0.006%) from 57.515%
13311125525

push

github

web-flow
Release PR comment alert type (#5437)

- Remove the feature flag
- Add docs
- Fix bugs

Fix #5432

1 of 3 new or added lines in 1 file covered. (33.33%)

2 existing lines in 1 file now uncovered.

18166 of 31588 relevant lines covered (57.51%)

37.59 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

56.07
/internal/engine/actions/alert/pull_request_comment/pull_request_comment.go
1
// SPDX-FileCopyrightText: Copyright 2024 The Minder Authors
2
// SPDX-License-Identifier: Apache-2.0
3

4
// Package pull_request_comment provides necessary interfaces and implementations for
5
// processing pull request comment alerts.
6
package pull_request_comment
7

8
import (
9
        "context"
10
        "encoding/json"
11
        "errors"
12
        "fmt"
13
        "math"
14
        "strconv"
15
        "time"
16

17
        "github.com/google/go-github/v63/github"
18
        "github.com/rs/zerolog"
19
        "google.golang.org/protobuf/reflect/protoreflect"
20

21
        "github.com/mindersec/minder/internal/db"
22
        enginerr "github.com/mindersec/minder/internal/engine/errors"
23
        "github.com/mindersec/minder/internal/engine/interfaces"
24
        pbinternal "github.com/mindersec/minder/internal/proto"
25
        "github.com/mindersec/minder/internal/util"
26
        pb "github.com/mindersec/minder/pkg/api/protobuf/go/minder/v1"
27
        "github.com/mindersec/minder/pkg/profiles/models"
28
        provifv1 "github.com/mindersec/minder/pkg/providers/v1"
29
)
30

31
const (
32
        // AlertType is the type of the pull request comment alert engine
33
        AlertType = "pull_request_comment"
34
        // PrCommentMaxLength is the maximum length of the pull request comment
35
        // (this was derived from the limit of the GitHub API)
36
        PrCommentMaxLength = 65536
37
)
38

39
// Alert is the structure backing the noop alert
40
type Alert struct {
41
        actionType interfaces.ActionType
42
        gh         provifv1.GitHub
43
        reviewCfg  *pb.RuleType_Definition_Alert_AlertTypePRComment
44
        setting    models.ActionOpt
45
}
46

47
// PrCommentTemplateParams is the parameters for the PR comment templates
48
type PrCommentTemplateParams struct {
49
        // EvalErrorDetails is the details of the error that occurred during evaluation, which may be empty
50
        EvalErrorDetails string
51

52
        // EvalResult is the output of the evaluation, which may be empty
53
        EvalResultOutput any
54
}
55

56
type paramsPR struct {
57
        Owner      string
58
        Repo       string
59
        CommitSha  string
60
        Number     int
61
        Comment    string
62
        Metadata   *alertMetadata
63
        prevStatus *db.ListRuleEvaluationsByProfileIdRow
64
}
65

66
type alertMetadata struct {
67
        ReviewID       string     `json:"review_id,omitempty"`
68
        SubmittedAt    *time.Time `json:"submitted_at,omitempty"`
69
        PullRequestUrl *string    `json:"pull_request_url,omitempty"`
70
}
71

72
// NewPullRequestCommentAlert creates a new pull request comment alert action
73
func NewPullRequestCommentAlert(
74
        actionType interfaces.ActionType,
75
        reviewCfg *pb.RuleType_Definition_Alert_AlertTypePRComment,
76
        gh provifv1.GitHub,
77
        setting models.ActionOpt,
78
) (*Alert, error) {
5✔
79
        if actionType == "" {
5✔
80
                return nil, fmt.Errorf("action type cannot be empty")
×
81
        }
×
82

83
        return &Alert{
5✔
84
                actionType: actionType,
5✔
85
                gh:         gh,
5✔
86
                reviewCfg:  reviewCfg,
5✔
87
                setting:    setting,
5✔
88
        }, nil
5✔
89
}
90

91
// Class returns the action type of the PR comment alert engine
92
func (alert *Alert) Class() interfaces.ActionType {
1✔
93
        return alert.actionType
1✔
94
}
1✔
95

96
// Type returns the action subtype of the PR comment alert engine
97
func (_ *Alert) Type() string {
×
98
        return AlertType
×
99
}
×
100

101
// GetOnOffState returns the alert action state read from the profile
102
func (alert *Alert) GetOnOffState() models.ActionOpt {
×
103
        return models.ActionOptOrDefault(alert.setting, models.ActionOptOff)
×
104
}
×
105

106
// Do comments on a pull request
107
func (alert *Alert) Do(
108
        ctx context.Context,
109
        cmd interfaces.ActionCmd,
110
        entity protoreflect.ProtoMessage,
111
        params interfaces.ActionsParams,
112
        metadata *json.RawMessage,
113
) (json.RawMessage, error) {
5✔
114
        pr, ok := entity.(*pbinternal.PullRequest)
5✔
115
        if !ok {
5✔
116
                return nil, fmt.Errorf("expected pull request, got %T", entity)
×
117
        }
×
118

119
        commentParams, err := alert.getParamsForPRComment(ctx, pr, params, metadata)
5✔
120
        if err != nil {
5✔
121
                return nil, fmt.Errorf("error extracting parameters for PR comment: %w", err)
×
122
        }
×
123

124
        // Process the command based on the action setting
125
        switch alert.setting {
5✔
126
        case models.ActionOptOn:
5✔
127
                return alert.run(ctx, commentParams, cmd)
5✔
128
        case models.ActionOptDryRun:
×
129
                return alert.runDry(ctx, commentParams, cmd)
×
130
        case models.ActionOptOff, models.ActionOptUnknown:
×
131
                return nil, fmt.Errorf("unexpected action setting: %w", enginerr.ErrActionFailed)
×
132
        }
133
        return nil, enginerr.ErrActionSkipped
×
134
}
135

136
func (alert *Alert) run(ctx context.Context, params *paramsPR, cmd interfaces.ActionCmd) (json.RawMessage, error) {
5✔
137
        logger := zerolog.Ctx(ctx)
5✔
138

5✔
139
        // Process the command
5✔
140
        switch cmd {
5✔
141
        // Create a review
142
        case interfaces.ActionCmdOn:
4✔
143
                review := &github.PullRequestReviewRequest{
4✔
144
                        CommitID: github.String(params.CommitSha),
4✔
145
                        Event:    github.String("COMMENT"),
4✔
146
                        Body:     github.String(params.Comment),
4✔
147
                }
4✔
148

4✔
149
                r, err := alert.gh.CreateReview(
4✔
150
                        ctx,
4✔
151
                        params.Owner,
4✔
152
                        params.Repo,
4✔
153
                        params.Number,
4✔
154
                        review,
4✔
155
                )
4✔
156
                if err != nil {
5✔
157
                        return nil, fmt.Errorf("error creating PR review: %w, %w", err, enginerr.ErrActionFailed)
1✔
158
                }
1✔
159

160
                newMeta, err := json.Marshal(alertMetadata{
3✔
161
                        ReviewID:       strconv.FormatInt(r.GetID(), 10),
3✔
162
                        SubmittedAt:    r.SubmittedAt.GetTime(),
3✔
163
                        PullRequestUrl: r.PullRequestURL,
3✔
164
                })
3✔
165
                if err != nil {
3✔
166
                        return nil, fmt.Errorf("error marshalling alert metadata json: %w", err)
×
167
                }
×
168

169
                logger.Info().Int64("review_id", *r.ID).Msg("PR review created")
3✔
170
                return newMeta, nil
3✔
171
        // Dismiss the review
172
        case interfaces.ActionCmdOff:
1✔
173
                if params.Metadata == nil || params.Metadata.ReviewID == "" {
1✔
174
                        // We cannot do anything without the PR review ID, so we assume that turning the alert off is a success
×
175
                        return nil, fmt.Errorf("no PR comment ID provided: %w", enginerr.ErrActionTurnedOff)
×
176
                }
×
177

178
                reviewID, err := strconv.ParseInt(params.Metadata.ReviewID, 10, 64)
1✔
179
                if err != nil {
1✔
180
                        zerolog.Ctx(ctx).Error().Err(err).Str("review_id", params.Metadata.ReviewID).Msg("failed to parse review_id")
×
181
                        return nil, fmt.Errorf("no PR comment ID provided: %w, %w", err, enginerr.ErrActionTurnedOff)
×
182
                }
×
183

184
                _, err = alert.gh.DismissReview(ctx, params.Owner, params.Repo, params.Number, reviewID,
1✔
185
                        &github.PullRequestReviewDismissalRequest{
1✔
186
                                Message: github.String("Dismissed due to alert being turned off"),
1✔
187
                        })
1✔
188
                if err != nil {
1✔
189
                        if errors.Is(err, enginerr.ErrNotFound) {
×
190
                                // There's no PR review with that ID anymore.
×
191
                                // We exit by stating that the action was turned off.
×
192
                                return nil, fmt.Errorf("PR comment already dismissed: %w, %w", err, enginerr.ErrActionTurnedOff)
×
193
                        }
×
194
                        return nil, fmt.Errorf("error dismissing PR comment: %w, %w", err, enginerr.ErrActionFailed)
×
195
                }
196
                logger.Info().Str("review_id", params.Metadata.ReviewID).Msg("PR comment dismissed")
1✔
197
                // Success - return ErrActionTurnedOff to indicate the action was successful
1✔
198
                return nil, fmt.Errorf("%s : %w", alert.Class(), enginerr.ErrActionTurnedOff)
1✔
199
        case interfaces.ActionCmdDoNothing:
×
200
                // Return the previous alert status.
×
201
                return alert.runDoNothing(ctx, params)
×
202
        }
203
        return nil, enginerr.ErrActionSkipped
×
204
}
205

206
// runDry runs the pull request comment action in dry run mode, which logs the comment that would be made
207
func (alert *Alert) runDry(ctx context.Context, params *paramsPR, cmd interfaces.ActionCmd) (json.RawMessage, error) {
×
208
        logger := zerolog.Ctx(ctx)
×
209

×
210
        // Process the command
×
211
        switch cmd {
×
212
        case interfaces.ActionCmdOn:
×
213
                body := github.String(params.Comment)
×
214
                logger.Info().Msgf("dry run: create a PR comment on PR %d in repo %s/%s with the following body: %s",
×
215
                        params.Number, params.Owner, params.Repo, *body)
×
216
                return nil, nil
×
217
        case interfaces.ActionCmdOff:
×
NEW
218
                if params.Metadata == nil || params.Metadata.ReviewID == "" {
×
219
                        // We cannot do anything without the PR review ID, so we assume that turning the alert off is a success
×
220
                        return nil, fmt.Errorf("no PR comment ID provided: %w", enginerr.ErrActionTurnedOff)
×
221
                }
×
NEW
222
                logger.Info().Msgf("dry run: dismiss PR comment %s on PR %d in repo %s/%s", params.Metadata.ReviewID,
×
223
                        params.Number, params.Owner, params.Repo)
×
224
        case interfaces.ActionCmdDoNothing:
×
225
                // Return the previous alert status.
×
226
                return alert.runDoNothing(ctx, params)
×
227

228
        }
229
        return nil, enginerr.ErrActionSkipped
×
230
}
231

232
// runDoNothing returns the previous alert status
233
func (_ *Alert) runDoNothing(ctx context.Context, params *paramsPR) (json.RawMessage, error) {
×
234
        logger := zerolog.Ctx(ctx).With().Str("repo", params.Repo).Logger()
×
235

×
236
        logger.Debug().Msg("Running do nothing")
×
237

×
238
        // Return the previous alert status.
×
239
        err := enginerr.AlertStatusAsError(params.prevStatus)
×
240
        // If there is a valid alert metadata, return it too
×
241
        if params.prevStatus != nil {
×
242
                return params.prevStatus.AlertMetadata, err
×
243
        }
×
244
        // If there is no alert metadata, return nil as the metadata and the error
245
        return nil, err
×
246
}
247

248
// getParamsForSecurityAdvisory extracts the details from the entity
249
func (alert *Alert) getParamsForPRComment(
250
        ctx context.Context,
251
        pr *pbinternal.PullRequest,
252
        params interfaces.ActionsParams,
253
        metadata *json.RawMessage,
254
) (*paramsPR, error) {
5✔
255
        logger := zerolog.Ctx(ctx)
5✔
256
        result := &paramsPR{
5✔
257
                prevStatus: params.GetEvalStatusFromDb(),
5✔
258
                Owner:      pr.GetRepoOwner(),
5✔
259
                Repo:       pr.GetRepoName(),
5✔
260
                CommitSha:  pr.GetCommitSha(),
5✔
261
        }
5✔
262

5✔
263
        // The GitHub Go API takes an int32, but our proto stores an int64; make sure we don't overflow
5✔
264
        // The PR number is an int in GitHub and Gitlab; in practice overflow will never happen.
5✔
265
        if pr.Number > math.MaxInt {
5✔
266
                return nil, fmt.Errorf("pr number is too large")
×
267
        }
×
268
        result.Number = int(pr.Number)
5✔
269

5✔
270
        commentTmpl, err := util.NewSafeHTMLTemplate(&alert.reviewCfg.ReviewMessage, "message")
5✔
271
        if err != nil {
5✔
272
                return nil, fmt.Errorf("cannot parse review message template: %w", err)
×
273
        }
×
274

275
        tmplParams := &PrCommentTemplateParams{
5✔
276
                EvalErrorDetails: enginerr.ErrorAsEvalDetails(params.GetEvalErr()),
5✔
277
        }
5✔
278

5✔
279
        if params.GetEvalResult() != nil {
10✔
280
                tmplParams.EvalResultOutput = params.GetEvalResult().Output
5✔
281
        }
5✔
282

283
        comment, err := commentTmpl.Render(ctx, tmplParams, PrCommentMaxLength)
5✔
284
        if err != nil {
5✔
285
                return nil, fmt.Errorf("cannot execute title template: %w", err)
×
286
        }
×
287

288
        result.Comment = comment
5✔
289

5✔
290
        // Unmarshal the existing alert metadata, if any
5✔
291
        if metadata != nil {
6✔
292
                meta := &alertMetadata{}
1✔
293
                err := json.Unmarshal(*metadata, meta)
1✔
294
                if err != nil {
1✔
295
                        // There's nothing saved apparently, so no need to fail here, but do log the error
×
296
                        logger.Debug().Msgf("error unmarshalling alert metadata: %v", err)
×
297
                } else {
1✔
298
                        result.Metadata = meta
1✔
299
                }
1✔
300
        }
301

302
        return result, nil
5✔
303
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc