-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathcode_scanning_apply.go
More file actions
276 lines (237 loc) · 8.28 KB
/
code_scanning_apply.go
File metadata and controls
276 lines (237 loc) · 8.28 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
package cmd
import (
"encoding/json"
"fmt"
"os"
"time"
"github.com/spf13/cobra"
gh "github.com/advanced-security/codeql-development-mcp-server/client/internal/github"
)
// ---------------------------------------------------------------------------
// Apply data types
// ---------------------------------------------------------------------------
type applyAction struct {
AlertNumber int `json:"alertNumber"`
RuleID string `json:"ruleId"`
Action string `json:"action"`
DismissReason string `json:"dismissReason,omitempty"`
DismissComment string `json:"dismissComment,omitempty"`
Reason string `json:"reason,omitempty"`
Authorized bool `json:"authorized"`
Applied bool `json:"applied"`
Error string `json:"error,omitempty"`
}
type applySummary struct {
TotalAlerts int `json:"totalAlerts"`
DismissCount int `json:"dismissCount"`
AuthorizedDismissCount int `json:"authorizedDismissCount"`
UnauthorizedDismissCount int `json:"unauthorizedDismissCount"`
NoChangeCount int `json:"noChangeCount"`
AppliedCount int `json:"appliedCount"`
ErrorCount int `json:"errorCount"`
DryRun bool `json:"dryRun"`
}
type applyPlan struct {
Repository string `json:"repository,omitempty"`
GeneratedAt string `json:"generatedAt"`
InputReport string `json:"inputReport,omitempty"`
Actions []applyAction `json:"actions"`
Summary applySummary `json:"summary"`
}
type applyOptions struct {
dryRun bool
acceptAllChanges bool
acceptChangeForRules []string
dismissReason string
dismissComment string
}
// ---------------------------------------------------------------------------
// buildApplyPlan — pure function, no I/O
// ---------------------------------------------------------------------------
func buildApplyPlan(assessed []assessedAlert, opts applyOptions) applyPlan {
acceptRules := make(map[string]bool)
for _, r := range opts.acceptChangeForRules {
acceptRules[r] = true
}
reason := opts.dismissReason
if reason == "" {
reason = "won't fix"
}
var actions []applyAction
noChange := 0
for _, a := range assessed {
switch a.Recommendation {
case "keep", "keep-dismissed", "keep-fixed":
noChange++
continue
case "discard", "review":
action := applyAction{
AlertNumber: a.Number,
RuleID: a.Rule.ID,
Action: "dismiss",
DismissReason: reason,
DismissComment: opts.dismissComment,
Reason: a.RecommendReason,
}
if opts.acceptAllChanges || acceptRules[a.Rule.ID] {
action.Authorized = true
} else if a.Recommendation == "discard" && len(opts.acceptChangeForRules) == 0 {
action.Authorized = true // discard auto-authorized when no rule filter set
}
actions = append(actions, action)
default:
noChange++
}
}
var authorizedCount, unauthorizedCount int
for _, a := range actions {
if a.Authorized {
authorizedCount++
} else {
unauthorizedCount++
}
}
return applyPlan{
GeneratedAt: time.Now().UTC().Format(time.RFC3339),
Actions: actions,
Summary: applySummary{
TotalAlerts: len(assessed),
DismissCount: len(actions),
AuthorizedDismissCount: authorizedCount,
UnauthorizedDismissCount: unauthorizedCount,
NoChangeCount: noChange,
DryRun: opts.dryRun,
},
}
}
// ---------------------------------------------------------------------------
// Cobra command
// ---------------------------------------------------------------------------
var applyCmd = &cobra.Command{
Use: "apply",
Short: "Apply alert lifecycle changes from an assess report",
Long: `Apply the recommended changes from a Phase 2 assess report to
Code Scanning alerts via the GitHub API. Supports dry-run mode to preview
changes without making them, and per-rule or blanket acceptance flags.
This is Phase 3 of the three-phase Code Scanning alert lifecycle workflow.`,
RunE: runApply,
}
var applyFlags struct {
input string
output string
dryRun bool
acceptAllChanges bool
acceptChangeForRules []string
dismissReason string
dismissComment string
repo string
}
func init() {
codeScanningCmd.AddCommand(applyCmd)
f := applyCmd.Flags()
f.StringVar(&applyFlags.input, "input", "", "Path to Phase 2 assess report JSON (required)")
f.StringVar(&applyFlags.output, "output", "", "Output file path (default: <owner>_<repo>.cs-apply.json)")
f.StringVar(&applyFlags.repo, "repo", "", "Repository in owner/repo format (overrides report)")
f.BoolVar(&applyFlags.dryRun, "dry-run", false, "Preview changes without applying them")
f.BoolVar(&applyFlags.acceptAllChanges, "accept-all-changes", false, "Auto-authorize all recommended changes")
f.StringSliceVar(&applyFlags.acceptChangeForRules, "accept-change-for-rule", nil, "Auto-authorize changes for specific rule IDs")
f.StringVar(&applyFlags.dismissReason, "dismiss-reason", "won't fix", "Reason for dismissing alerts (false positive, won't fix, used in tests)")
f.StringVar(&applyFlags.dismissComment, "dismiss-comment", "", "Comment to attach to dismissed alerts")
_ = applyCmd.MarkFlagRequired("input")
}
func runApply(cmd *cobra.Command, _ []string) error {
data, err := os.ReadFile(applyFlags.input)
if err != nil {
return fmt.Errorf("read input: %w", err)
}
var assessReport codeScanningAssessReport
if err := json.Unmarshal(data, &assessReport); err != nil {
return fmt.Errorf("parse assess report: %w", err)
}
repo := applyFlags.repo
if repo == "" {
repo = assessReport.Repository
}
owner, repoName, err := parseRepo(repo)
if err != nil {
return err
}
plan := buildApplyPlan(assessReport.Alerts, applyOptions{
dryRun: applyFlags.dryRun,
acceptAllChanges: applyFlags.acceptAllChanges,
acceptChangeForRules: applyFlags.acceptChangeForRules,
dismissReason: applyFlags.dismissReason,
dismissComment: applyFlags.dismissComment,
})
plan.Repository = repo
plan.InputReport = applyFlags.input
if applyFlags.dryRun {
fmt.Fprintf(cmd.ErrOrStderr(), "DRY RUN — no changes will be made to %s/%s\n", owner, repoName)
}
fmt.Fprintf(cmd.ErrOrStderr(), "Plan: %d alerts, %d to dismiss, %d unchanged\n",
plan.Summary.TotalAlerts, plan.Summary.DismissCount, plan.Summary.NoChangeCount)
// Execute actions (unless dry-run)
if !applyFlags.dryRun && len(plan.Actions) > 0 {
client, err := gh.NewClient()
if err != nil {
return err
}
for i, action := range plan.Actions {
if !action.Authorized {
fmt.Fprintf(cmd.ErrOrStderr(), " Skipping #%d (%s) — not authorized\n",
action.AlertNumber, action.RuleID)
continue
}
fmt.Fprintf(cmd.ErrOrStderr(), " Dismissing #%d (%s)...\n",
action.AlertNumber, action.RuleID)
_, err := client.UpdateAlert(gh.UpdateAlertOptions{
Owner: owner,
Repo: repoName,
AlertNumber: action.AlertNumber,
State: "dismissed",
DismissedReason: action.DismissReason,
DismissedComment: action.DismissComment,
})
if err != nil {
plan.Actions[i].Error = err.Error()
plan.Summary.ErrorCount++
fmt.Fprintf(cmd.ErrOrStderr(), " Error: %v\n", err)
} else {
plan.Actions[i].Applied = true
plan.Summary.AppliedCount++
}
}
}
// Write output
outPath := applyFlags.output
if outPath == "" {
// Derive from repository name: owner_repo.cs-apply.json
if o, r, err := parseRepo(repo); err == nil {
outPath = fmt.Sprintf("%s_%s.cs-apply.json", o, r)
} else {
outPath = "cs-apply.json"
}
}
outData, err := json.MarshalIndent(plan, "", " ")
if err != nil {
return fmt.Errorf("marshal plan: %w", err)
}
if err := os.WriteFile(outPath, outData, 0o600); err != nil {
return fmt.Errorf("write plan: %w", err)
}
mode := "Plan"
if !applyFlags.dryRun {
mode = "Results"
}
fmt.Fprintf(cmd.ErrOrStderr(), "\n%s written to %s\n", mode, outPath)
if plan.Summary.AppliedCount > 0 {
fmt.Fprintf(cmd.ErrOrStderr(), " %d alerts dismissed\n", plan.Summary.AppliedCount)
}
if plan.Summary.ErrorCount > 0 {
fmt.Fprintf(cmd.ErrOrStderr(), " %d errors\n", plan.Summary.ErrorCount)
}
if OutputFormat() == "json" {
fmt.Fprintln(cmd.OutOrStdout(), string(outData))
}
return nil
}