Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
81 changes: 61 additions & 20 deletions control/task_github.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,33 @@ var fetchGitHubDefaultBranch = func(host, owner, repo string) (string, error) {
return githubpkg.FetchGitHubDefaultBranch(host, owner, repo)
}

// prefetchGitHubScannedRepo is a test seam over the scanned repository's
// query. The default honors PLUMBER_DISABLE_GITHUB_API (same contract as
// fetchGitHubDefaultBranch above).
var prefetchGitHubScannedRepo = func(host, owner, repo string, branches []string) {
if v := os.Getenv(githubpkg.EnvDisableGitHubAPI); v == "1" || v == "true" {
return
}
githubpkg.PrefetchScannedRepo(host, owner, repo, branches)
}

// prefetchScannedRepo sends the scanned repository's query before its first
// read (the default branch), with the exact branch names
// branchMustBeProtected reads, so that the default branch, the visibility,
// the canonical name, those branches and the default token's releases come
// from one query (plumber#637).
func prefetchScannedRepo(conf *configuration.Configuration, projectPath string) {
owner, repo, ok := gitHubOwnerRepo(projectPath)
if !ok {
return
}
var branches []string
if shouldRunControl(controlBranchMustBeProtected, conf) {
branches, _, _ = branchTargets(collectionBranchProtectionConfig(conf))
}
prefetchGitHubScannedRepo(conf.GithubAPIHost, owner, repo, branches)
}

// scanGitHubWorkflowsRemote is a test seam over the remote workflow fetch,
// which otherwise needs network and auth.
var scanGitHubWorkflowsRemote = githubpkg.ScanGitHubWorkflowsRemote
Expand Down Expand Up @@ -338,16 +365,14 @@ func eligibleDefaultTokenWorkflow(pipeline *ir.NormalizedPipeline, workflowPath
// green (#220). Returns false when the control is disabled/benched/out
// of scope (nothing to fetch) or the fetch succeeded.
func enrichGitHubBranches(l *logrus.Entry, pipeline *ir.NormalizedPipeline, host string, pc *configuration.PlumberConfig, projectPath string, onProgress func(message string)) (fetchFailed bool) {
if pipeline == nil || pc == nil {
if pipeline == nil {
return false
}
if configuration.IsBenched("github", "branchMustBeProtected") {
exact, listing, active := branchTargets(pc)
if !active {
return false
}
cfg := pc.ControlsFor("github").BranchMustBeProtected
if cfg == nil || !cfg.IsEnabled() {
return false
}
owner, repo, addressable := gitHubOwnerRepo(projectPath)
if !addressable {
return false
Expand All @@ -360,21 +385,8 @@ func enrichGitHubBranches(l *logrus.Entry, pipeline *ir.NormalizedPipeline, host
// (FetchGitHubDefaultBranch folds 404/401 into a silent empty success
// by contract), so the zero-branch probe below owns that case.

// Build the targeted-fetch set from non-glob patterns plus the
// default branch (when defaultMustBeProtected is on). Wildcard
// patterns trip the listing fallthrough; on a typical config —
// `main`, `master`, `default` — we never list at all.
exact := make([]string, 0, len(cfg.NamePatterns))
listing := false
for _, p := range cfg.NamePatterns {
if isBranchGlob(p) {
listing = true
continue
}
if p != "" {
exact = append(exact, p)
}
}
// The targeted-fetch set is the non-glob patterns plus the default
// branch (when defaultMustBeProtected is on).
if cfg.DefaultMustBeProtected != nil && *cfg.DefaultMustBeProtected && pipeline.DefaultBranch != "" {
exact = append(exact, pipeline.DefaultBranch)
}
Expand Down Expand Up @@ -437,6 +449,33 @@ func enrichGitHubBranches(l *logrus.Entry, pipeline *ir.NormalizedPipeline, host
return false
}

// branchTargets reads branchMustBeProtected's configuration: the branch
// names it reads one by one (its non-glob patterns, without the default
// branch, which the caller adds), and whether a wildcard pattern needs the
// branch listing. On a typical config (`main`, `master`, `default`) it never
// lists at all. active is false when the control is off, benched, or not
// configured, and nothing is fetched.
func branchTargets(pc *configuration.PlumberConfig) (exact []string, listing, active bool) {
if pc == nil || configuration.IsBenched("github", "branchMustBeProtected") {
return nil, false, false
}
cfg := pc.ControlsFor("github").BranchMustBeProtected
if cfg == nil || !cfg.IsEnabled() {
return nil, false, false
}
exact = make([]string, 0, len(cfg.NamePatterns))
for _, p := range cfg.NamePatterns {
if isBranchGlob(p) {
listing = true
continue
}
if p != "" {
exact = append(exact, p)
}
}
return exact, listing, true
}

// gitHubOwnerRepo splits an owner/repo project path, reporting ok=false for
// anything else (empty, single-segment, or either half empty).
//
Expand Down Expand Up @@ -505,6 +544,7 @@ func RunGitHubAnalysis(conf *configuration.Configuration) (*AnalysisResult, erro
}
logInvalidWorkflows(l, pipeline, conf)

prefetchScannedRepo(conf, conf.ProjectPath)
resolveGitHubDefaultBranch(l, pipeline, conf.GithubAPIHost, conf.ProjectPath)
applyGitHubVisibility(pipeline, conf.GithubAPIHost, conf.ProjectPath)
if owner, repo, addressable := gitHubOwnerRepo(conf.ProjectPath); addressable {
Expand Down Expand Up @@ -661,6 +701,7 @@ func RunGitHubAnalysisRemote(conf *configuration.Configuration, owner, repo, ref
l.WithError(perr).Warn("GitHub workflow read: partial failure (file skipped)")
}
logInvalidWorkflows(l, pipeline, conf)
prefetchScannedRepo(conf, owner+"/"+repo)
applyGitHubVisibility(pipeline, conf.GithubAPIHost, owner+"/"+repo)

resolveGitHubDefaultBranch(l, pipeline, conf.GithubAPIHost, owner+"/"+repo)
Expand Down
58 changes: 58 additions & 0 deletions control/task_github_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"errors"
"os"
"path/filepath"
"reflect"
"testing"

"github.com/getplumber/plumber/configuration"
Expand Down Expand Up @@ -495,3 +496,60 @@ func findControlEntry(t *testing.T, entries []ControlEntry, name string) Control
t.Fatalf("no control entry named %s", name)
return ControlEntry{}
}

// TestRunGitHubAnalysis_PrefetchesTheScannedRepository: the scanned
// repository's query goes out before the default-branch lookup, with the
// exact branch names branchMustBeProtected reads (the wildcard patterns go
// to the listing), so the run sends one query for it. Without the control
// it asks no branch.
func TestRunGitHubAnalysis_PrefetchesTheScannedRepository(t *testing.T) {
enabled := true
withBranches := &configuration.PlumberConfig{
Version: "2.0",
GitHub: &configuration.ProviderConfig{Controls: configuration.ControlsConfig{
BranchMustBeProtected: &configuration.BranchProtectionControlConfig{
Enabled: &enabled,
NamePatterns: []string{"main", "release/*", "dev"},
},
}},
}
for _, tc := range []struct {
name string
pc *configuration.PlumberConfig
want []string
}{
{"branchMustBeProtected on", withBranches, []string{"main", "dev"}},
{"branchMustBeProtected off", &configuration.PlumberConfig{}, nil},
} {
t.Run(tc.name, func(t *testing.T) {
var calls []string
var gotBranches []string
orig := prefetchGitHubScannedRepo
prefetchGitHubScannedRepo = func(host, owner, repo string, branches []string) {
calls = append(calls, "prefetch "+owner+"/"+repo)
gotBranches = branches
}
t.Cleanup(func() { prefetchGitHubScannedRepo = orig })
swapDefaultBranchFetch(t, func(host, owner, repo string) (string, error) {
calls = append(calls, "default branch")
return "main", nil
})

conf := &configuration.Configuration{
ProjectPath: "toptal/chewy",
GitRepoRoot: writeMinimalWorkflow(t),
GithubAPIHost: "127.0.0.1:1",
PlumberConfig: tc.pc,
}
if _, err := RunGitHubAnalysis(conf); err != nil {
t.Fatalf("unexpected error: %v", err)
}
if len(calls) < 2 || calls[0] != "prefetch toptal/chewy" || calls[1] != "default branch" {
t.Errorf("calls = %v, want the prefetch before the default-branch lookup", calls)
}
if !reflect.DeepEqual(gotBranches, tc.want) {
t.Errorf("prefetched branches = %v, want %v", gotBranches, tc.want)
}
})
}
}
8 changes: 7 additions & 1 deletion docs/GITHUB_ISSUES.md
Original file line number Diff line number Diff line change
Expand Up @@ -2319,7 +2319,13 @@ family call the GitHub API **in process** via `github.com/cli/go-gh`,
which reuses the locally stored `gh` token. The action metadata (archived
flag, stars, releases, tags, refs, advisories) is read through the GraphQL
API, many actions per query; on GitHub Enterprise Server the advisories
and the immutable-release flag are read over REST.
and the immutable-release flag are read over REST. On github.com, one
GraphQL query also reads the scanned repository: its default branch,
visibility and full name, the branches `branchMustBeProtected` names with
their protected flag, and the authors of its latest releases. The branch
listing, protection details, rulesets, environments and Actions runs stay
on REST, and so does every read of the scanned repository on GitHub
Enterprise Server.
Plumber never shells out to the `gh` binary (or any other external
binary) during analysis — see getplumber/plumber#310. Without
`gh auth login`, those rules degrade silently (no false positives)
Expand Down
Loading