Skip to content
Open
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
48 changes: 46 additions & 2 deletions pkg/github/repositories.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"context"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
Expand Down Expand Up @@ -1582,10 +1583,12 @@ func CreateBranch(t translations.TranslationHelperFunc) inventory.ServerTool {

// Get the source branch SHA
var ref *github.Reference
var repository *github.Repository

if fromBranch == "" {
// Get default branch if from_branch not specified
repository, resp, err := client.Repositories.Get(ctx, owner, repo)
var resp *github.Response
repository, resp, err = client.Repositories.Get(ctx, owner, repo)
if err != nil {
return ghErrors.NewGitHubAPIErrorResponse(ctx,
"failed to get repository",
Expand Down Expand Up @@ -1618,7 +1621,7 @@ func CreateBranch(t translations.TranslationHelperFunc) inventory.ServerTool {
createdRef, resp, err := client.Git.CreateRef(ctx, owner, repo, newRef)
if err != nil {
return ghErrors.NewGitHubAPIErrorResponse(ctx,
"failed to create branch",
repoWriteAccessErrMsg(ctx, client, repository, "failed to create branch", owner, repo, resp, err),
resp,
err,
), nil, nil
Expand All @@ -1635,6 +1638,47 @@ func CreateBranch(t translations.TranslationHelperFunc) inventory.ServerTool {
)
}

// repoWriteAccessErrMsg disambiguates bare 404/403 responses from write
// endpoints when the caller can read the repository but lacks write access
// (permissions.push is false). Rate limit errors are returned verbatim.
func repoWriteAccessErrMsg(
ctx context.Context,
client *github.Client,
repoObj *github.Repository,
base, owner, repo string,
resp *github.Response,
err error,
) string {
if resp == nil || (resp.StatusCode != http.StatusNotFound && resp.StatusCode != http.StatusForbidden) {
return base
}

var rateLimitErr *github.RateLimitError
var abuseErr *github.AbuseRateLimitError
if errors.As(err, &rateLimitErr) || errors.As(err, &abuseErr) {
return base
}

if repoObj == nil {
fetched, repoResp, repoErr := client.Repositories.Get(ctx, owner, repo)
if repoResp != nil && repoResp.Body != nil {
_ = repoResp.Body.Close()
}
if repoErr != nil {
return base
}
repoObj = fetched
}

if perms := repoObj.GetPermissions(); perms != nil && !perms.GetPush() {
return fmt.Sprintf(
"%s (you have read access to %s/%s, but your credentials lack write access)",
base, owner, repo,
)
}
return base
}

// PushFiles creates a tool to push multiple files in a single commit to a GitHub repository.
func PushFiles(t translations.TranslationHelperFunc) inventory.ServerTool {
tool := NewTool[PushFilesInput, *RepositoryReferenceOutput](
Expand Down
121 changes: 121 additions & 0 deletions pkg/github/repositories_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1533,6 +1533,127 @@ func Test_CreateBranch(t *testing.T) {
expectedErrMsg: "ref name does not match the required pattern 'feature/*'",
unexpectedErrs: []string{"422", "https://docs.github.com"},
},
{
name: "404 on create branch without push permission hints at read-only access",
mockedClient: MockHTTPClientWithHandlers(map[string]http.HandlerFunc{
GetReposGitRefByOwnerByRepoByRef: mockResponse(t, http.StatusOK, mockSourceRef),
"GET /repos/owner/repo/git/ref/heads/main": mockResponse(t, http.StatusOK, mockSourceRef),
PostReposGitRefsByOwnerByRepo: mockResponse(t, http.StatusNotFound, map[string]any{"message": "Not Found"}),
GetReposByOwnerByRepo: mockResponse(t, http.StatusOK, &github.Repository{
DefaultBranch: new("main"),
Permissions: &github.RepositoryPermissions{
Pull: new(true),
Push: new(false),
},
}),
}),
requestArgs: map[string]any{
"owner": "owner",
"repo": "repo",
"branch": "new-feature",
"from_branch": "main",
},
expectError: true,
expectedErrMsg: "credentials lack write access",
},
{
name: "403 on create branch with default branch reuses repo permissions for write hint",
mockedClient: MockHTTPClientWithHandlers(map[string]http.HandlerFunc{
GetReposByOwnerByRepo: mockResponse(t, http.StatusOK, &github.Repository{
DefaultBranch: new("main"),
Permissions: &github.RepositoryPermissions{
Pull: new(true),
Push: new(false),
},
}),
GetReposGitRefByOwnerByRepoByRef: mockResponse(t, http.StatusOK, mockSourceRef),
"GET /repos/owner/repo/git/ref/heads/main": mockResponse(t, http.StatusOK, mockSourceRef),
PostReposGitRefsByOwnerByRepo: mockResponse(t, http.StatusForbidden, map[string]any{"message": "Resource not accessible by integration"}),
}),
requestArgs: map[string]any{
"owner": "owner",
"repo": "repo",
"branch": "new-feature",
},
expectError: true,
expectedErrMsg: "credentials lack write access",
},
{
name: "404 on create branch with push permission omits write-access hint",
mockedClient: MockHTTPClientWithHandlers(map[string]http.HandlerFunc{
GetReposGitRefByOwnerByRepoByRef: mockResponse(t, http.StatusOK, mockSourceRef),
"GET /repos/owner/repo/git/ref/heads/main": mockResponse(t, http.StatusOK, mockSourceRef),
PostReposGitRefsByOwnerByRepo: mockResponse(t, http.StatusNotFound, map[string]any{"message": "Not Found"}),
GetReposByOwnerByRepo: mockResponse(t, http.StatusOK, &github.Repository{
DefaultBranch: new("main"),
Permissions: &github.RepositoryPermissions{
Pull: new(true),
Push: new(true),
},
}),
}),
requestArgs: map[string]any{
"owner": "owner",
"repo": "repo",
"branch": "new-feature",
"from_branch": "main",
},
expectError: true,
expectedErrMsg: "failed to create branch",
unexpectedErrs: []string{"credentials lack write access"},
},
{
name: "rate limit 403 preserves rate limit message without extra hint",
mockedClient: MockHTTPClientWithHandlers(map[string]http.HandlerFunc{
GetReposGitRefByOwnerByRepoByRef: mockResponse(t, http.StatusOK, mockSourceRef),
"GET /repos/owner/repo/git/ref/heads/main": mockResponse(t, http.StatusOK, mockSourceRef),
PostReposGitRefsByOwnerByRepo: func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("X-RateLimit-Remaining", "0")
w.Header().Set("X-RateLimit-Reset", "9999999999")
w.WriteHeader(http.StatusForbidden)
_, _ = w.Write([]byte(`{"message": "API rate limit exceeded"}`))
},
}),
requestArgs: map[string]any{
"owner": "owner",
"repo": "repo",
"branch": "new-feature",
"from_branch": "main",
},
expectError: true,
expectedErrMsg: "rate limit exceeded",
unexpectedErrs: []string{"credentials lack write access"},
},
{
name: "default branch repository without permissions does not repeat lookup",
mockedClient: func() *http.Client {
repoGets := 0
return MockHTTPClientWithHandlers(map[string]http.HandlerFunc{
GetReposByOwnerByRepo: func(w http.ResponseWriter, r *http.Request) {
repoGets++
if repoGets > 1 {
t.Errorf("unexpected duplicate repository lookup (count=%d)", repoGets)
http.Error(w, "unexpected duplicate repository lookup", http.StatusInternalServerError)
return
}
mockResponse(t, http.StatusOK, &github.Repository{
DefaultBranch: new("main"),
})(w, r)
},
GetReposGitRefByOwnerByRepoByRef: mockResponse(t, http.StatusOK, mockSourceRef),
"GET /repos/owner/repo/git/ref/heads/main": mockResponse(t, http.StatusOK, mockSourceRef),
PostReposGitRefsByOwnerByRepo: mockResponse(t, http.StatusNotFound, map[string]any{"message": "Not Found"}),
})
}(),
requestArgs: map[string]any{
"owner": "owner",
"repo": "repo",
"branch": "new-feature",
},
expectError: true,
expectedErrMsg: "failed to create branch",
unexpectedErrs: []string{"credentials lack write access", "unexpected duplicate repository lookup"},
},
}

for _, tc := range tests {
Expand Down
Loading