Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add support for bitbucket workspace token authentication #508

Merged
merged 4 commits into from
Nov 20, 2024
Merged
Show file tree
Hide file tree
Changes from 2 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
4 changes: 3 additions & 1 deletion cmd/other.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,11 +35,13 @@ func getToken(flag *flag.FlagSet) (string, error) {
token = ght
} else if ght := os.Getenv("BITBUCKET_CLOUD_APP_PASSWORD"); ght != "" {
token = ght
} else if ght := os.Getenv("BITBUCKET_CLOUD_WORKSPACE_TOKEN"); ght != "" {
token = ght
}
}

if token == "" {
return "", errors.New("either the --token flag or the GITHUB_TOKEN/GITLAB_TOKEN/GITEA_TOKEN/BITBUCKET_SERVER_TOKEN/BITBUCKET_CLOUD_APP_PASSWORD environment variable has to be set")
return "", errors.New("either the --token flag or the GITHUB_TOKEN/GITLAB_TOKEN/GITEA_TOKEN/BITBUCKET_SERVER_TOKEN/BITBUCKET_CLOUD_APP_PASSWORD/BITBUCKET_CLOUD_WORKSPACE_TOKEN environment variable has to be set")
}

return token, nil
Expand Down
18 changes: 16 additions & 2 deletions cmd/platform.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,15 @@ func configurePlatform(cmd *cobra.Command) {
flags.StringP("base-url", "g", "", "Base URL of the target platform, needs to be changed for GitHub enterprise, a self-hosted GitLab instance, Gitea or BitBucket.")
flags.BoolP("insecure", "", false, "Insecure controls whether a client verifies the server certificate chain and host name. Used only for Bitbucket server.")
flags.StringP("username", "u", "", "The Bitbucket server username.")
flags.StringP("token", "T", "", "The personal access token for the targeting platform. Can also be set using the GITHUB_TOKEN/GITLAB_TOKEN/GITEA_TOKEN/BITBUCKET_SERVER_TOKEN/BITBUCKET_CLOUD_APP_PASSWORD environment variable.")
flags.StringP("token", "T", "", "The personal access token for the targeting platform. Can also be set using the GITHUB_TOKEN/GITLAB_TOKEN/GITEA_TOKEN/BITBUCKET_SERVER_TOKEN/BITBUCKET_CLOUD_APP_PASSWORD/BITBUCKET_CLOUD_WORKSPACE_TOKEN environment variable.")
flags.StringP("auth-type", "", "app-password", `The authentication type. Used only for Bitbucket cloud.
Available values:
app-password: authenticate using an app password
workspace-token: authenticate using a workspace token
Copy link
Owner

Choose a reason for hiding this comment

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

If the descriptions are not providing any additional value, please just have then listed on the same line.

`)
_ = cmd.RegisterFlagCompletionFunc("auth-type", func(cmd *cobra.Command, _ []string, _ string) ([]string, cobra.ShellCompDirective) {
return []string{"app-password", "workspace-token"}, cobra.ShellCompDirectiveNoFileComp
})

flags.StringSliceP("org", "O", nil, "The name of a GitHub organization. All repositories in that organization will be used.")
flags.StringSliceP("group", "G", nil, "The name of a GitLab organization. All repositories in that group will be used.")
Expand Down Expand Up @@ -294,6 +302,7 @@ func createBitbucketCloudClient(flag *flag.FlagSet, verifyFlags bool) (multigitt
sshAuth, _ := flag.GetBool("ssh-auth")
fork, _ := flag.GetBool("fork")
newOwner, _ := flag.GetString("fork-owner")
authTypeStr, _ := flag.GetString("auth-type")

if verifyFlags && len(workspaces) == 0 && len(users) == 0 && len(repos) == 0 {
return nil, errors.New("no workspace, user or repository set")
Expand All @@ -308,7 +317,12 @@ func createBitbucketCloudClient(flag *flag.FlagSet, verifyFlags bool) (multigitt
return nil, err
}

vc, err := bitbucketcloud.New(username, token, repos, workspaces, users, fork, sshAuth, newOwner)
authType, err := bitbucketcloud.ParseAuthType(authTypeStr)
if err != nil {
return nil, err
}

vc, err := bitbucketcloud.New(username, token, repos, workspaces, users, fork, sshAuth, newOwner, authType)
if err != nil {
return nil, err
}
Expand Down
16 changes: 11 additions & 5 deletions docs/README.template.md
Original file line number Diff line number Diff line change
Expand Up @@ -141,15 +141,21 @@ Do you have a nice script that might be useful to others? Please create a PR tha

_note: bitbucket cloud support is currently in Beta_

In order to use bitbucket cloud you will need to create and use an [App Password](https://support.atlassian.com/bitbucket-cloud/docs/app-passwords/). The app password you create needs sufficient permissions so ensure you grant it Read and Write access to projects, repositories and pull requests and at least Read access to your account and workspace membership.
In order to use bitbucket cloud you will need to create and use an [App Password](https://support.atlassian.com/bitbucket-cloud/docs/app-passwords/) or [Workspace Token](https://support.atlassian.com/bitbucket-cloud/docs/access-tokens/). The app password or workspace token you create needs sufficient permissions so ensure you grant it Read and Write access to projects, repositories and pull requests and at least Read access to your account and workspace membership.

You will need to configure the bitbucket workspace using the `org` option for multi-gitter for the repositories you want to make changes to e.g. `multi-gitter run examples/go/upgrade-go-version.sh -u your_username --org "your_workspace"`
You will need to configure the bitbucket workspace using the `org` option for multi-gitter for the repositories you want to make changes to. You will also need to configure the authentication method using the `auth-type` flag e.g. `multi-gitter run examples/go/upgrade-go-version.sh -u your_username --org "your_workspace" --auth-type app-password`

### Example
Here is an example of using the command line options to run a script from the `examples/` directory and make pull-requests for a few repositories in a specified workspace.
Here is an example of using the command line options to run a script from the `examples/` directory and make pull-requests for a few repositories in a specified workspace, using app password authentication.
```shell
export BITBUCKET_CLOUD_APP_PASSWORD="your_app_password"
multi-gitter run examples/go/upgrade-go-version.sh -u your_username --org "your_workspace" --repo "your_first_repository,your_second_repository" --platform bitbucket_cloud -m "your_commit_message" -B your_branch_name
multi-gitter run examples/go/upgrade-go-version.sh -u your_username --org "your_workspace" --repo "your_first_repository,your_second_repository" --platform bitbucket_cloud -m "your_commit_message" -B your_branch_name --auth-type app-password
```

Here is an example of running the script using workspace token authentication.
```shell
export BITBUCKET_CLOUD_WORKSPACE_TOKEN="your_workspace_token"
multi-gitter run examples/go/upgrade-go-version.sh -u your_username --org "your_workspace" --repo "your_first_repository,your_second_repository" --platform bitbucket_cloud -m "your_commit_message" -B your_branch_name --auth-type workspace-token
```

### Bitbucket Cloud Limitations
Expand All @@ -165,4 +171,4 @@ We also only support modifying a single workspace, any additional workspaces pas

We also have noticed the performance is slower with larger workspaces and we expect to resolve this when we add support for projects to make filtering repositories by project faster.

</details>
</details>
55 changes: 48 additions & 7 deletions internal/scm/bitbucketcloud/bitbucket_cloud.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,12 +25,13 @@ type BitbucketCloud struct {
token string
sshAuth bool
newOwner string
authType AuthType
httpClient *http.Client
bbClient *bitbucket.Client
}

func New(username string, token string, repositories []string, workspaces []string, users []string, fork bool, sshAuth bool,
newOwner string) (*BitbucketCloud, error) {
newOwner string, authType AuthType) (*BitbucketCloud, error) {
if strings.TrimSpace(token) == "" {
return nil, errors.New("bearer token is empty")
}
Expand All @@ -44,10 +45,18 @@ func New(username string, token string, repositories []string, workspaces []stri
bitbucketCloud.token = token
bitbucketCloud.sshAuth = sshAuth
bitbucketCloud.newOwner = newOwner
bitbucketCloud.authType = authType
bitbucketCloud.httpClient = &http.Client{
Transport: internalHTTP.LoggingRoundTripper{},
}
bitbucketCloud.bbClient = bitbucket.NewBasicAuth(username, token)

if authType == AuthTypeAppPassword {
// Authenticate using app password
bitbucketCloud.bbClient = bitbucket.NewBasicAuth(username, token)
} else if authType == AuthTypeWorkspaceToken {
// Authenticate using workspace token
bitbucketCloud.bbClient = bitbucket.NewOAuthbearerToken(token)
}

return bitbucketCloud, nil
}
Expand All @@ -59,16 +68,21 @@ func (bbc *BitbucketCloud) CreatePullRequest(_ context.Context, _ scm.Repository
Owner: bbc.workspaces[0],
RepoSlug: bbcRepo.name,
}
currentUser, err := bbc.bbClient.User.Profile()
if err != nil {
return nil, err
var currentUserUUID string
if bbc.authType == AuthTypeAppPassword {
currentUser, err := bbc.bbClient.User.Profile()
if err != nil {
return nil, err
}
currentUserUUID = currentUser.Uuid
}

defaultReviewers, err := bbc.bbClient.Repositories.Repository.ListEffectiveDefaultReviewers(repoOptions)
if err != nil {
return nil, err
}
for _, reviewer := range defaultReviewers.EffectiveDefaultReviewers {
if currentUser.Uuid != reviewer.User.Uuid {
if currentUserUUID != reviewer.User.Uuid {
newPR.Reviewers = append(newPR.Reviewers, reviewer.User.Uuid)
}
}
Expand Down Expand Up @@ -351,7 +365,12 @@ func (bbc *BitbucketCloud) convertRepository(repo bitbucket.Repository) (*reposi
return nil, err
}

parsedURL.User = url.UserPassword(bbc.username, bbc.token)
if bbc.authType == AuthTypeAppPassword {
parsedURL.User = url.UserPassword(bbc.username, bbc.token)
} else if bbc.authType == AuthTypeWorkspaceToken {
parsedURL.User = url.UserPassword("x-token-auth", bbc.token)
}

cloneURL = parsedURL.String()
}

Expand All @@ -372,3 +391,25 @@ func findLinkType(cloneLinks []hrefLink, cloneType string, repoName string) (str

return "", errors.Errorf("unable to find clone url for repository %s using clone type %s", repoName, cloneType)
}

// AuthType defines the authentication method for Bitbucket Cloud
type AuthType int

const (
// AuthTypeAppPassword will use app password authentication
AuthTypeAppPassword AuthType = iota + 1
// AuthTypeWorkspaceToken will use workspace token authentication
AuthTypeWorkspaceToken
)

// ParseAuthType parses an auth type from a string
func ParseAuthType(str string) (AuthType, error) {
switch str {
default:
return AuthType(0), fmt.Errorf("could not parse \"%s\" as auth type", str)
case "app-password":
return AuthTypeAppPassword, nil
case "workspace-token":
return AuthTypeWorkspaceToken, nil
}
}
Loading