Skip to content
Merged
20 changes: 15 additions & 5 deletions pkg/cli/add_interactive_git.go
Original file line number Diff line number Diff line change
Expand Up @@ -243,11 +243,8 @@ func (c *AddInteractiveConfig) configureRepositorySecret(secretName, secretValue
return nil
}

// updateLocalBranch fetches and pulls the latest changes from GitHub after PR merge.
// It switches to the default branch before pulling so that the working tree contains
// the merged workflow files, which are required when offering to run the workflow.
func (c *AddInteractiveConfig) updateLocalBranch() error {
addInteractiveLog.Print("Updating local branch with merged changes")
// resolveDefaultBranch queries GitHub and falls back to the local origin, then main on failure.
func (c *AddInteractiveConfig) resolveDefaultBranch() string {
// Get the default branch name using gh
output, err := workflow.RunGHCombined("Getting default branch...", "repo", "view", "--repo", c.RepoOverride, "--json", "defaultBranchRef", "--jq", ".defaultBranchRef.name")
defaultBranch := ""
Expand All @@ -267,6 +264,19 @@ func (c *AddInteractiveConfig) updateLocalBranch() error {
if defaultBranch == "" {
defaultBranch = "main"
}
return defaultBranch
}

// updateLocalBranch fetches and pulls the latest changes from GitHub after PR merge.
// It switches to the default branch before pulling so that the working tree contains
// the merged workflow files, which are required when offering to run the workflow.
func (c *AddInteractiveConfig) updateLocalBranch() error {
addInteractiveLog.Print("Updating local branch with merged changes")

defaultBranch := c.resolveDefaultBranch()
if err := validateGitBranchArg(defaultBranch, "default branch name"); err != nil {
return err
}
addInteractiveLog.Printf("Default branch: %s", defaultBranch)

// Fetch the latest changes from origin
Expand Down
8 changes: 8 additions & 0 deletions pkg/cli/add_interactive_git_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,14 @@ func TestParseDefaultBranchFromLsRemote(t *testing.T) {
}
}

func TestUpdateLocalBranchRejectsUnsafeDefaultBranch(t *testing.T) {
prependFakeGH(t, "echo '--upload-pack=evil'")

err := (&AddInteractiveConfig{}).updateLocalBranch()

assert.ErrorContains(t, err, "invalid default branch name")
}

// TestParseDefaultBranchFromLsRemoteWithRealGit creates real git repositories
// and runs actual `git ls-remote --symref` to verify parsing against real git output.
func TestParseDefaultBranchFromLsRemoteWithRealGit(t *testing.T) {
Expand Down
19 changes: 19 additions & 0 deletions pkg/cli/git.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,16 @@ func isSafeGitRevisionArg(ref string) bool {
return ref != "" && !strings.HasPrefix(ref, "-") && !containsControlCharacters(ref)
}

func validateGitBranchArg(branchName, label string) error {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

pkg/cli/git.go:L30: yagni: validateGitBranchArg wrapper adds a one-off abstraction used only for isSafeGitRevisionArg. Call isSafeGitRevisionArg inline at each callsite with contextual error text until shared semantics diverge.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Keeping the wrapper: validateGitBranchArg is called from 5 sites across 3 files (git.go, pr_command.go, add_interactive_git.go), not a single one-off usage, so the shared helper avoids duplicating the error-message format at each callsite.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[/tdd] validateGitBranchArg is only exercised indirectly through the four call sites (createAndSwitchBranch, switchBranch, pushBranch, checkoutUpdatedDefaultBranch). A direct table-driven unit test for the function itself (covering the exact error message text for each rejection reason: empty, leading dash, control character) would make future refactors of the guarded call sites safer and pin down the wording independent of caller behavior.

💡 Suggested test
func TestValidateGitBranchArg(t *testing.T) {
    t.Parallel()
    err := validateGitBranchArg("--upload-pack=evil", "branch name")
    assert.ErrorContains(t, err, "invalid branch name")

    err = validateGitBranchArg("", "branch name")
    assert.Error(t, err)
}

This complements the existing isSafeGitRevisionArg table test and the per-call-site regression tests already added in this PR.

@copilot please address this.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added TestValidateGitBranchArg as a direct table-driven test covering empty, leading dash, option-like, control character, valid, and custom-label cases.

if branchName == "" {
return fmt.Errorf("invalid %s: must not be empty", label)
}
if !isSafeGitRevisionArg(branchName) {
return fmt.Errorf("invalid %s %q: must not start with '-' or contain control characters", label, branchName)
}
Comment thread
Copilot marked this conversation as resolved.
Resolved
return nil
}

// validateRelPathForGit rejects relative paths that could be misinterpreted as
// a git CLI flag (a leading "-") or that escape the repository root via path
// traversal (a leading ".." path segment after cleaning), before the path is
Expand Down Expand Up @@ -534,6 +544,9 @@ func getCurrentBranchIn(dir string) (string, error) {

// createAndSwitchBranch creates a new branch and switches to it
func createAndSwitchBranch(branchName string, verbose bool) error {
if err := validateGitBranchArg(branchName, "branch name"); err != nil {
return err
}
console.LogVerbose(verbose, "Creating and switching to branch: "+branchName)

cmd := exec.Command("git", "checkout", "-b", branchName)
Expand All @@ -546,6 +559,9 @@ func createAndSwitchBranch(branchName string, verbose bool) error {

// switchBranch switches to the specified branch
func switchBranch(branchName string, verbose bool) error {
if err := validateGitBranchArg(branchName, "branch name"); err != nil {
return err
}
console.LogVerbose(verbose, "Switching to branch: "+branchName)

cmd := exec.Command("git", "checkout", branchName)
Expand All @@ -572,6 +588,9 @@ func commitChanges(message string, verbose bool) error {

// pushBranch pushes the specified branch to origin
func pushBranch(branchName string, verbose bool) error {
if err := validateGitBranchArg(branchName, "branch name"); err != nil {
return err
}
console.LogVerbose(verbose, "Pushing branch: "+branchName)

cmd := exec.Command("git", "push", "-u", "origin", branchName)
Expand Down
46 changes: 46 additions & 0 deletions pkg/cli/git_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,52 @@ func TestIsSafeGitRevisionArg(t *testing.T) {
}
}

func TestValidateGitBranchArg(t *testing.T) {
t.Parallel()
tests := []struct {
name string
branchName string
label string
wantErr bool
errContains string
}{
{"empty", "", "branch name", true, "must not be empty"},
{"leading dash", "-oops", "branch name", true, "must not start with '-' or contain control characters"},
{"option-like", "--upload-pack=evil", "branch name", true, "must not start with '-' or contain control characters"},
{"control character", "origin/main\n--help", "branch name", true, "must not start with '-' or contain control characters"},
{"valid branch", "main", "branch name", false, ""},
{"custom label", "", "default branch name", true, "invalid default branch name"},
{"custom label option-like", "--upload-pack=evil", "default branch name", true, "invalid default branch name \"--upload-pack=evil\": must not start with '-' or contain control characters"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
err := validateGitBranchArg(tt.branchName, tt.label)
if tt.wantErr {
require.Error(t, err)
assert.ErrorContains(t, err, tt.errContains)
} else {
assert.NoError(t, err)
}
})
}
}

func TestBranchOperationsRejectUnsafeRevisionArgs(t *testing.T) {
t.Parallel()

for name, operation := range map[string]func(string, bool) error{
"create and switch": createAndSwitchBranch,
"switch": switchBranch,
"push": pushBranch,
} {
t.Run(name, func(t *testing.T) {
t.Parallel()
assert.ErrorContains(t, operation("--upload-pack=evil", false), "invalid branch name")
})
}
}

func TestValidateRelPathForGit(t *testing.T) {
t.Parallel()
tests := []struct {
Expand Down
3 changes: 3 additions & 0 deletions pkg/cli/pr_command.go
Original file line number Diff line number Diff line change
Expand Up @@ -277,6 +277,9 @@ func checkoutUpdatedDefaultBranch(targetOwner, targetRepo string, verbose bool)
return fmt.Errorf("could not get default branch; ensure required prerequisites are configured, then retry: %w", err)
}
defaultBranch := strings.TrimSpace(string(defaultBranchOutput))
if err := validateGitBranchArg(defaultBranch, "default branch name"); err != nil {
return err
}

// Ensure we're on the latest version of the default branch
if verbose {
Expand Down
10 changes: 10 additions & 0 deletions pkg/cli/pr_command_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,16 @@ func TestCreatePatchFromPRWritesOnlyDiff(t *testing.T) {
}
}

func TestCheckoutUpdatedDefaultBranchRejectsUnsafeDefaultBranch(t *testing.T) {
prependFakeGH(t, "if [ \"$1\" = \"api\" ]; then echo '--upload-pack=evil'; exit 0; fi\nexit 1")

err := checkoutUpdatedDefaultBranch("target-owner", "target-repo", false)

if err == nil || !strings.Contains(err.Error(), "invalid default branch name") {
t.Fatalf("checkoutUpdatedDefaultBranch() error = %v, want invalid default branch rejection", err)
}
}

func TestApplyPatchToRepoScopesCommitToPatchIndex(t *testing.T) {
repoDir := initPRTransferRepo(t)
prependFakeGH(t, "if [ \"$1\" = \"api\" ] && [ \"$2\" = \"/repos/target-owner/target-repo\" ]; then echo main; exit 0; fi\necho unexpected gh \"$@\" >&2\nexit 1\n")
Expand Down
Loading