-
Notifications
You must be signed in to change notification settings - Fork 40
/
pull_request.go
582 lines (506 loc) · 16.4 KB
/
pull_request.go
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
// Copyright 2023 Stacklok, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Package pull_request provides the pull request remediation engine
package pull_request
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
htmltemplate "html/template"
"os"
"strings"
"text/template"
"time"
"github.com/go-git/go-git/v5"
"github.com/go-git/go-git/v5/config"
"github.com/go-git/go-git/v5/plumbing"
"github.com/go-git/go-git/v5/plumbing/object"
"github.com/google/go-github/v61/github"
"github.com/rs/zerolog"
"google.golang.org/protobuf/reflect/protoreflect"
"github.com/stacklok/minder/internal/db"
enginerr "github.com/stacklok/minder/internal/engine/errors"
"github.com/stacklok/minder/internal/engine/interfaces"
"github.com/stacklok/minder/internal/util"
pb "github.com/stacklok/minder/pkg/api/protobuf/go/minder/v1"
provifv1 "github.com/stacklok/minder/pkg/providers/v1"
)
const (
// RemediateType is the type of the REST remediation engine
RemediateType = "pull_request"
)
const (
// if no Mode is specified, create a regular file with 0644 UNIX permissions
ghModeNonExecFile = "100644"
dflBranchBaseName = "minder"
dflBranchTo = "main"
)
const (
prTemplateName = "prBody"
prBodyTmplStr = "{{.PrText}}"
)
type pullRequestMetadata struct {
Number int `json:"pr_number,omitempty"`
}
// Remediator is the remediation engine for the Pull Request remediation type
type Remediator struct {
ghCli provifv1.GitHub
actionType interfaces.ActionType
prCfg *pb.RuleType_Definition_Remediate_PullRequestRemediation
modificationRegistry modificationRegistry
titleTemplate *htmltemplate.Template
bodyTemplate *htmltemplate.Template
}
type paramsPR struct {
ingested *interfaces.Result
repo *pb.Repository
title string
modifier fsModifier
body string
metadata *pullRequestMetadata
prevStatus *db.ListRuleEvaluationsByProfileIdRow
}
// NewPullRequestRemediate creates a new PR remediation engine
func NewPullRequestRemediate(
actionType interfaces.ActionType,
prCfg *pb.RuleType_Definition_Remediate_PullRequestRemediation,
ghCli provifv1.GitHub,
) (*Remediator, error) {
err := prCfg.Validate()
if err != nil {
return nil, fmt.Errorf("pull request remediation config is invalid: %w", err)
}
titleTmpl, err := util.ParseNewHtmlTemplate(&prCfg.Title, "title")
if err != nil {
return nil, fmt.Errorf("cannot parse title template: %w", err)
}
bodyTmpl, err := util.ParseNewHtmlTemplate(&prCfg.Body, "body")
if err != nil {
return nil, fmt.Errorf("cannot parse body template: %w", err)
}
modRegistry := newModificationRegistry()
modRegistry.registerBuiltIn()
return &Remediator{
ghCli: ghCli,
prCfg: prCfg,
actionType: actionType,
modificationRegistry: modRegistry,
titleTemplate: titleTmpl,
bodyTemplate: bodyTmpl,
}, nil
}
// PrTemplateParams is the parameters for the PR templates
type PrTemplateParams struct {
// Entity is the entity to be evaluated
Entity any
// Profile are the parameters to be used in the template
Profile map[string]any
// Params are the rule instance parameters
Params map[string]any
}
// Class returns the action type of the remediation engine
func (r *Remediator) Class() interfaces.ActionType {
return r.actionType
}
// Type returns the action subtype of the remediation engine
func (_ *Remediator) Type() string {
return RemediateType
}
// GetOnOffState returns the alert action state read from the profile
func (_ *Remediator) GetOnOffState(p *pb.Profile) interfaces.ActionOpt {
return interfaces.ActionOptFromString(p.Remediate, interfaces.ActionOptOff)
}
// Do perform the remediation
func (r *Remediator) Do(
ctx context.Context,
cmd interfaces.ActionCmd,
setting interfaces.ActionOpt,
ent protoreflect.ProtoMessage,
params interfaces.ActionsParams,
metadata *json.RawMessage,
) (json.RawMessage, error) {
p, err := r.getParamsForPRRemediation(ctx, ent, params, metadata)
if err != nil {
return nil, fmt.Errorf("cannot get PR remediation params: %w", err)
}
var remErr error
switch setting {
case interfaces.ActionOptOn:
return r.run(ctx, cmd, p)
case interfaces.ActionOptDryRun:
return r.dryRun(ctx, cmd, p)
case interfaces.ActionOptOff, interfaces.ActionOptUnknown:
remErr = errors.New("unexpected action")
}
return nil, remErr
}
func (r *Remediator) getParamsForPRRemediation(
ctx context.Context,
ent protoreflect.ProtoMessage,
params interfaces.ActionsParams,
metadata *json.RawMessage,
) (*paramsPR, error) {
logger := zerolog.Ctx(ctx)
repo, ok := ent.(*pb.Repository)
if !ok {
return nil, fmt.Errorf("expected repository, got %T", ent)
}
tmplParams := &PrTemplateParams{
Entity: ent,
Profile: params.GetRule().Def.AsMap(),
Params: params.GetRule().Params.AsMap(),
}
ingested := params.GetIngestResult()
if ingested == nil || ingested.Fs == nil || ingested.Storer == nil {
return nil, errors.New("ingested filesystem is nil or no git repo was ingested")
}
title := new(bytes.Buffer)
if err := r.titleTemplate.Execute(title, tmplParams); err != nil {
return nil, fmt.Errorf("cannot execute title template: %w", err)
}
modification, err := r.modificationRegistry.getModification(getMethod(r.prCfg), &modificationConstructorParams{
prCfg: r.prCfg,
ghCli: r.ghCli,
bfs: ingested.Fs,
def: params.GetRule().Def.AsMap(),
})
if err != nil {
return nil, fmt.Errorf("cannot get modification: %w", err)
}
err = modification.createFsModEntries(ctx, params)
if err != nil {
return nil, fmt.Errorf("cannot create PR entries: %w", err)
}
prFullBodyText, err := r.getPrBodyText(tmplParams)
if err != nil {
return nil, fmt.Errorf("cannot create PR full body text: %w", err)
}
// Unmarshal the existing remediation metadata, if any
meta := &pullRequestMetadata{}
if metadata != nil {
err := json.Unmarshal(*metadata, meta)
if err != nil {
// There's nothing saved apparently, so no need to fail here, but do log the error
logger.Debug().Msgf("error unmarshalling remediation metadata: %v", err)
}
}
return ¶msPR{
ingested: ingested,
repo: repo,
title: title.String(),
modifier: modification,
body: prFullBodyText,
metadata: meta,
prevStatus: params.GetEvalStatusFromDb(),
}, nil
}
func (r *Remediator) dryRun(
ctx context.Context,
cmd interfaces.ActionCmd,
p *paramsPR,
) (json.RawMessage, error) {
logger := zerolog.Ctx(ctx).Info().Str("repo", p.repo.String())
// Process the command
switch cmd {
case interfaces.ActionCmdOn:
// TODO: jsonize too
logger.Msgf("title:\n%s\n", p.title)
logger.Msgf("body:\n%s\n", p.body)
err := p.modifier.writeSummary(os.Stdout)
if err != nil {
logger.Msgf("cannot write summary: %s\n", err)
}
return nil, nil
case interfaces.ActionCmdOff:
if p.metadata == nil || p.metadata.Number == 0 {
// We cannot do anything without a PR number, so we assume that closing this is a success
return nil, fmt.Errorf("no pull request number provided: %w", enginerr.ErrActionSkipped)
}
endpoint := fmt.Sprintf("repos/%v/%v/pulls/%d", p.repo.GetOwner(), p.repo.GetName(), p.metadata.Number)
body := "{\"state\": \"closed\"}"
curlCmd, err := util.GenerateCurlCommand("PATCH", r.ghCli.GetBaseURL(), endpoint, body)
if err != nil {
return nil, fmt.Errorf("cannot generate curl command to close a pull request: %w", err)
}
logger.Msgf("run the following curl command: \n%s\n", curlCmd)
return nil, nil
case interfaces.ActionCmdDoNothing:
return r.runDoNothing(ctx, p)
}
return nil, nil
}
func (r *Remediator) runOn(
ctx context.Context,
p *paramsPR,
) (json.RawMessage, error) {
logger := zerolog.Ctx(ctx).With().Str("repo", p.repo.String()).Logger()
repo, err := git.Open(p.ingested.Storer, p.ingested.Fs)
if err != nil {
return nil, fmt.Errorf("cannot open git repo: %w", err)
}
wt, err := repo.Worktree()
if err != nil {
return nil, fmt.Errorf("cannot get worktree: %w", err)
}
logger.Debug().Msg("Getting authenticated user details")
email, err := r.ghCli.GetPrimaryEmail(ctx)
if err != nil {
return nil, fmt.Errorf("cannot get primary email: %w", err)
}
currentHeadReference, err := repo.Head()
if err != nil {
return nil, fmt.Errorf("cannot get current HEAD: %w", err)
}
currHeadName := currentHeadReference.Name()
// This resets the worktree so we don't corrupt the ingest cache (at least the main/originally-fetched branch).
// This also makes sure, all new remediations check out from main branch rather than prev remediation branch.
defer checkoutToOriginallyFetchedBranch(&logger, wt, currHeadName)
logger.Debug().Str("branch", branchBaseName(p.title)).Msg("Checking out branch")
err = wt.Checkout(&git.CheckoutOptions{
Branch: plumbing.NewBranchReferenceName(branchBaseName(p.title)),
Create: true,
})
if err != nil {
return nil, fmt.Errorf("cannot checkout branch: %w", err)
}
logger.Debug().Msg("Creating file entries")
changeEntries, err := p.modifier.modifyFs()
if err != nil {
return nil, fmt.Errorf("cannot modifyFs: %w", err)
}
logger.Debug().Msg("Staging changes")
for _, entry := range changeEntries {
if _, err := wt.Add(entry.Path); err != nil {
return nil, fmt.Errorf("cannot add file %s: %w", entry.Path, err)
}
}
logger.Debug().Msg("Committing changes")
_, err = wt.Commit(p.title, &git.CommitOptions{
Author: &object.Signature{
Name: userNameForCommit(ctx, r.ghCli),
Email: email,
When: time.Now(),
},
})
if err != nil {
return nil, fmt.Errorf("cannot commit: %w", err)
}
refspec := refFromBranch(branchBaseName(p.title))
l := logger.With().Str("branchBaseName", branchBaseName(p.title)).Logger()
// Check if a PR already exists for this branch
prNumber := getPRNumberFromBranch(ctx, r.ghCli, p.repo, branchBaseName(p.title))
// If no PR exists, push the branch and create a PR
if prNumber == 0 {
err = pushBranch(ctx, repo, refspec, r.ghCli)
if err != nil {
return nil, fmt.Errorf("cannot push branch: %w", err)
}
pr, err := r.ghCli.CreatePullRequest(
ctx, p.repo.GetOwner(), p.repo.GetName(),
p.title, p.body,
refspec,
dflBranchTo,
)
if err != nil {
return nil, fmt.Errorf("cannot create pull request: %w, %w", err, enginerr.ErrActionFailed)
}
// Return the new PR number
prNumber = pr.GetNumber()
l = l.With().Str("pr_origin", "newly_created").Logger()
} else {
l = l.With().Str("pr_origin", "already_existed").Logger()
}
newMeta, err := json.Marshal(pullRequestMetadata{Number: prNumber})
if err != nil {
return nil, fmt.Errorf("error marshalling pull request remediation metadata json: %w", err)
}
// Success - return the new metadata for storing the pull request number
l.Info().Int("pr_number", prNumber).Msg("pull request remediation completed")
return newMeta, enginerr.ErrActionPending
}
func getPRNumberFromBranch(
ctx context.Context,
cli provifv1.GitHub,
repo *pb.Repository,
branchName string,
) int {
opts := &github.PullRequestListOptions{
// TODO: This is not working as expected, need to fix this
// Head: fmt.Sprintf("%s:%s", repo.GetOwner(), branchName),
State: "open",
}
openPrs, err := cli.ListPullRequests(ctx, repo.GetOwner(), repo.GetName(), opts)
if err != nil {
return 0
}
for _, pr := range openPrs {
if pr.GetHead().GetRef() == branchName {
return pr.GetNumber()
}
}
return 0
}
func (r *Remediator) runOff(
ctx context.Context,
p *paramsPR,
) (json.RawMessage, error) {
logger := zerolog.Ctx(ctx).With().Str("repo", p.repo.String()).Logger()
if p.metadata == nil || p.metadata.Number == 0 {
// We cannot do anything without a PR number, so we assume that closing this is a success
return nil, fmt.Errorf("no pull request number provided: %w", enginerr.ErrActionSkipped)
}
pr, err := r.ghCli.ClosePullRequest(ctx, p.repo.GetOwner(), p.repo.GetName(), p.metadata.Number)
if err != nil {
return nil, fmt.Errorf("error closing pull request %d: %w, %w", p.metadata.Number, err, enginerr.ErrActionFailed)
}
logger.Info().Int("pr_number", pr.GetNumber()).Msg("pull request closed")
return nil, enginerr.ErrActionSkipped
}
func (r *Remediator) run(
ctx context.Context,
cmd interfaces.ActionCmd,
p *paramsPR,
) (json.RawMessage, error) {
// Process the command
switch cmd {
case interfaces.ActionCmdOn:
return r.runOn(ctx, p)
case interfaces.ActionCmdOff:
return r.runOff(ctx, p)
case interfaces.ActionCmdDoNothing:
return r.runDoNothing(ctx, p)
}
return nil, enginerr.ErrActionSkipped
}
func pushBranch(ctx context.Context, repo *git.Repository, refspec string, gh provifv1.GitHub) error {
var b bytes.Buffer
pushOptions := &git.PushOptions{
RemoteName: guessRemote(repo),
Force: true,
RefSpecs: []config.RefSpec{
config.RefSpec(
fmt.Sprintf("+%s:%s", refspec, refspec),
),
},
Progress: &b,
}
err := gh.AddAuthToPushOptions(ctx, pushOptions)
if err != nil {
return fmt.Errorf("cannot add auth to push options: %w", err)
}
err = repo.PushContext(ctx, pushOptions)
if err != nil {
return fmt.Errorf("cannot push: %w", err)
}
zerolog.Ctx(ctx).Debug().Msgf("Push output: %s", b.String())
return nil
}
func guessRemote(gitRepo *git.Repository) string {
remotes, err := gitRepo.Remotes()
if err != nil {
return ""
}
if len(remotes) == 0 {
return ""
}
for _, remote := range remotes {
if remote.Config().Name == "origin" {
return remote.Config().Name
}
}
return remotes[0].Config().Name
}
func refFromBranch(branchFrom string) string {
return fmt.Sprintf("refs/heads/%s", branchFrom)
}
func branchBaseName(prTitle string) string {
baseName := dflBranchBaseName
normalizedPrTitle := strings.ReplaceAll(strings.ToLower(prTitle), " ", "_")
return fmt.Sprintf("%s_%s", baseName, normalizedPrTitle)
}
func userNameForCommit(ctx context.Context, gh provifv1.GitHub) string {
var name string
// we ignore errors here, as we can still create a commit without a name
// and errors are checked when getting the primary email
name, _ = gh.GetName(ctx)
if name == "" {
name, _ = gh.GetLogin(ctx)
}
return name
}
func (r *Remediator) getPrBodyText(tmplParams *PrTemplateParams) (string, error) {
body := new(bytes.Buffer)
if err := r.bodyTemplate.Execute(body, tmplParams); err != nil {
return "", fmt.Errorf("cannot execute body template: %w", err)
}
prFullBodyText, err := createReviewBody(body.String())
if err != nil {
return "", fmt.Errorf("cannot create PR full body text: %w", err)
}
return prFullBodyText, nil
}
func getMethod(prCfg *pb.RuleType_Definition_Remediate_PullRequestRemediation) string {
if prCfg.Method == "" {
return minderContentModification
}
return prCfg.Method
}
func createReviewBody(prText string) (string, error) {
tmpl, err := template.New(prTemplateName).Option("missingkey=error").Parse(prBodyTmplStr)
if err != nil {
return "", err
}
data := struct {
PrText string
}{
PrText: prText,
}
// Execute the template
var buf bytes.Buffer
if err := tmpl.Execute(&buf, data); err != nil {
return "", err
}
return buf.String(), nil
}
func checkoutToOriginallyFetchedBranch(
logger *zerolog.Logger,
wt *git.Worktree,
originallyFetchedBranch plumbing.ReferenceName,
) {
err := wt.Checkout(&git.CheckoutOptions{
Branch: originallyFetchedBranch,
})
if err != nil {
logger.Err(err).Msg(
"unable to checkout to the previous head, this can corrupt the ingest cache, should not happen",
)
} else {
logger.Info().Msg(fmt.Sprintf("checked out back to %s branch", originallyFetchedBranch))
}
}
// runDoNothing returns the previous remediation status
func (_ *Remediator) runDoNothing(ctx context.Context, p *paramsPR) (json.RawMessage, error) {
logger := zerolog.Ctx(ctx).With().Str("repo", p.repo.String()).Logger()
logger.Debug().Msg("Running do nothing")
// Return the previous remediation status.
err := enginerr.RemediationStatusAsError(p.prevStatus.RemStatus)
// If there is a valid remediation metadata, return it too
if p.prevStatus.RemMetadata.Valid {
return p.prevStatus.RemMetadata.RawMessage, err
}
// If there is no remediation metadata, return nil as the metadata and the error
return nil, err
}