-
Notifications
You must be signed in to change notification settings - Fork 121
/
branch.go
362 lines (317 loc) · 10.8 KB
/
branch.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
// Copyright 2021 Allstar Authors
// 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 branch implements the Branch Protection security policy.
package branch
import (
"context"
"fmt"
"net/http"
"github.com/ossf/allstar/pkg/config"
"github.com/ossf/allstar/pkg/policydef"
"github.com/google/go-github/v39/github"
"github.com/rs/zerolog/log"
)
const configFile = "branch_protection.yaml"
const polName = "Branch Protection"
// OrgConfig is the org-level config definition for Branch Protection.
type OrgConfig struct {
// OptConfig is the standard org-level opt in/out config, RepoOverride applies to all
// BP config.
OptConfig config.OrgOptConfig `yaml:"optConfig"`
// Action defines which action to take, default log, other: issue...
Action string `yaml:"action"`
// EnforceDefault : set to true to enforce policy on default branch, default true.
EnforceDefault bool `yaml:"enforceDefault"`
// EnforceBranches is a map of repos and branches. These are other
// non-default branches to enforce policy on, such as branches which releases
// are made from.
EnforceBranches map[string][]string `yaml:"enforceBranches"`
// RequireApproval : set to true to enforce approval on PRs, default true.
RequireApproval bool `yaml:"requireApproval"`
// ApprovalCount is the number of required PR approvals, default 1.
ApprovalCount int `yaml:"approvalCount"`
// DismissStale : set to true to require PR approvalse be dismissed when a PR is updated, default true.
DismissStale bool `yaml:"dismissStale"`
// BlockForce : set to true to block force pushes, default true.
BlockForce bool `yaml:"blockForce"`
}
// RepoConfig is the repo-level config for Branch Protection
type RepoConfig struct {
// OptConfig is the standard repo-level opt in/out config.
OptConfig config.RepoOptConfig `yaml:"optConfig"`
// Action overrides the same setting in org-level, only if present.
Action *string `yaml:"action"`
// EnforceDefault overrides the same setting in org-level, only if present.
EnforceDefault *bool `yaml:"enforceDefault"`
// EnforceBranches adds more branches to the org-level list. Does not
// override. Always allowed irrespective of DisableRepoOverride setting.
EnforceBranches []string `yaml:"enforceBranches"`
// RequireApproval overrides the same setting in org-level, only if present.
RequireApproval *bool `yaml:"requireAppproval"`
// ApprovalCount overrides the same setting in org-level, only if present.
ApprovalCount *int `yaml:"approvalCount"`
// DismissStale overrides the same setting in org-level, only if present.
DismissStale *bool `yaml:"dismissStale"`
// BlockForce overrides the same setting in org-level, only if present.
BlockForce *bool `yaml:"blockForce"`
}
type mergedConfig struct {
Action string
EnforceDefault bool
EnforceBranches []string
RequireApproval bool
ApprovalCount int
DismissStale bool
BlockForce bool
}
type details struct {
PRReviews bool
NumReviews int
DismissStale bool
BlockForce bool
}
var configFetchConfig func(context.Context, *github.Client, string, string, string, bool, interface{}) error
var configIsEnabled func(ctx context.Context, o config.OrgOptConfig, r config.RepoOptConfig, c *github.Client, owner, repo string) (bool, error)
func init() {
configFetchConfig = config.FetchConfig
configIsEnabled = config.IsEnabled
}
// Branch is the Branch Protection policy object, implements policydef.Policy.
type Branch bool
// NewBranch returns a new BranchProtection polcy.
func NewBranch() policydef.Policy {
var b Branch
return b
}
// Name returns the name of this policy, implementing policydef.Policy.Name()
func (b Branch) Name() string {
return polName
}
type repositories interface {
Get(context.Context, string, string) (*github.Repository,
*github.Response, error)
ListBranches(context.Context, string, string, *github.BranchListOptions) (
[]*github.Branch, *github.Response, error)
GetBranchProtection(context.Context, string, string, string) (
*github.Protection, *github.Response, error)
}
// Check performs the polcy check for Branch Protection based on the
// configuration stored in the org/repo, implementing policydef.Policy.Check()
func (b Branch) Check(ctx context.Context, c *github.Client, owner,
repo string) (*policydef.Result, error) {
return check(ctx, c.Repositories, c, owner, repo)
}
func check(ctx context.Context, rep repositories, c *github.Client, owner,
repo string) (*policydef.Result, error) {
oc, rc := getConfig(ctx, c, owner, repo)
enabled, err := configIsEnabled(ctx, oc.OptConfig, rc.OptConfig, c, owner, repo)
if err != nil {
return nil, err
}
log.Info().
Str("org", owner).
Str("repo", repo).
Str("area", polName).
Bool("enabled", enabled).
Msg("Check repo enabled")
mc := mergeConfig(oc, rc, repo)
r, _, err := rep.Get(ctx, owner, repo)
if err != nil {
return nil, err
}
opt := &github.BranchListOptions{
ListOptions: github.ListOptions{
PerPage: 100,
},
}
var branches []*github.Branch
for {
bs, resp, err := rep.ListBranches(ctx, owner, repo, opt)
if err != nil {
return nil, err
}
branches = append(branches, bs...)
if resp.NextPage == 0 {
break
}
opt.Page = resp.NextPage
}
// Don't really need pagination here, only checking if no branches exist.
if len(branches) == 0 {
return &policydef.Result{
Enabled: enabled,
Pass: true,
NotifyText: "No branches to protect",
Details: nil,
}, nil
}
allBranches := mc.EnforceBranches
if mc.EnforceDefault {
allBranches = append(mc.EnforceBranches, r.GetDefaultBranch())
}
if len(allBranches) == 0 {
return &policydef.Result{
Enabled: enabled,
Pass: true,
NotifyText: "No branches configured for enforcement in policy",
Details: nil,
}, nil
}
pass := true
text := ""
ds := make(map[string]details)
for _, b := range allBranches {
p, rsp, err := rep.GetBranchProtection(ctx, owner, repo, b)
if err != nil {
if rsp != nil && rsp.StatusCode == http.StatusNotFound {
// Branch not protected
pass = false
text = text + fmt.Sprintf("No protection found for branch %v\n", b)
ds[b] = details{}
continue
}
if rsp != nil && rsp.StatusCode == http.StatusForbidden {
// Protection not available
pass = false
text = text + "Branch Protection enforcement is configured in Allstar, however Branch Protection is not available on this repository. Upgrade to GitHub Pro or make this repository public to enable this feature.\n" +
"See: https://docs.github.com/en/repositories/configuring-branches-and-merges-in-your-repository/defining-the-mergeability-of-pull-requests/about-protected-branches for more information.\n" +
"If this is not feasible, then disable Branch Protection policy enforcement for this repository in Allstar configuration."
ds[b] = details{}
break
}
return nil, err
}
var d details
rev := p.GetRequiredPullRequestReviews()
if rev != nil {
d.PRReviews = true
d.DismissStale = rev.DismissStaleReviews
if mc.DismissStale && !rev.DismissStaleReviews {
text = text +
fmt.Sprintf("Dismiss stale reviews not configured for branch %v\n", b)
pass = false
}
d.NumReviews = rev.RequiredApprovingReviewCount
if rev.RequiredApprovingReviewCount < mc.ApprovalCount {
pass = false
text = text +
fmt.Sprintf("PR Approvals below threshold %v : %v for branch %v\n",
rev.RequiredApprovingReviewCount, mc.ApprovalCount, b)
}
} else {
if mc.RequireApproval {
pass = false
text = text +
fmt.Sprintf("PR Approvals not configured for branch %v\n", b)
}
}
afp := p.GetAllowForcePushes()
d.BlockForce = true
if afp != nil {
if mc.BlockForce && afp.Enabled {
text = text +
fmt.Sprintf("Block force push not configured for branch %v\n", b)
pass = false
d.BlockForce = false
}
}
ds[b] = d
}
return &policydef.Result{
Enabled: enabled,
Pass: pass,
NotifyText: text,
Details: ds,
}, nil
}
// Fix implementing policydef.Policy.Fix(). Currently not supported. BP plans
// to support this TODO.
func (b Branch) Fix(ctx context.Context, c *github.Client, owner, repo string) error {
log.Warn().
Str("org", owner).
Str("repo", repo).
Str("area", polName).
Msg("Action fix is configured, but not implemented.")
return nil
}
// GetAction returns the configured action from Branch Protection's
// configuration stored in the org-level repo, default log. Implementing
// policydef.Policy.GetAction()
func (b Branch) GetAction(ctx context.Context, c *github.Client, owner, repo string) string {
oc, rc := getConfig(ctx, c, owner, repo)
mc := mergeConfig(oc, rc, repo)
return mc.Action
}
func getConfig(ctx context.Context, c *github.Client, owner, repo string) (*OrgConfig, *RepoConfig) {
oc := &OrgConfig{ // Fill out non-zero defaults
Action: "log",
EnforceDefault: true,
RequireApproval: true,
ApprovalCount: 1,
DismissStale: true,
BlockForce: true,
}
if err := configFetchConfig(ctx, c, owner, "", configFile, true, oc); err != nil {
log.Error().
Str("org", owner).
Str("repo", repo).
Bool("orgLevel", true).
Str("area", polName).
Str("file", configFile).
Err(err).
Msg("Unexpected config error, using defaults.")
}
rc := &RepoConfig{}
if err := configFetchConfig(ctx, c, owner, repo, configFile, false, rc); err != nil {
log.Error().
Str("org", owner).
Str("repo", repo).
Bool("orgLevel", false).
Str("area", polName).
Str("file", configFile).
Err(err).
Msg("Unexpected config error, using defaults.")
}
return oc, rc
}
func mergeConfig(oc *OrgConfig, rc *RepoConfig, repo string) *mergedConfig {
mc := &mergedConfig{
Action: oc.Action,
EnforceDefault: oc.EnforceDefault,
EnforceBranches: oc.EnforceBranches[repo],
RequireApproval: oc.RequireApproval,
ApprovalCount: oc.ApprovalCount,
DismissStale: oc.DismissStale,
BlockForce: oc.BlockForce,
}
mc.EnforceBranches = append(mc.EnforceBranches, rc.EnforceBranches...)
if !oc.OptConfig.DisableRepoOverride {
if rc.Action != nil {
mc.Action = *rc.Action
}
if rc.EnforceDefault != nil {
mc.EnforceDefault = *rc.EnforceDefault
}
if rc.RequireApproval != nil {
mc.RequireApproval = *rc.RequireApproval
}
if rc.ApprovalCount != nil {
mc.ApprovalCount = *rc.ApprovalCount
}
if rc.DismissStale != nil {
mc.DismissStale = *rc.DismissStale
}
if rc.BlockForce != nil {
mc.BlockForce = *rc.BlockForce
}
}
return mc
}