diff --git a/README.md b/README.md index ee0bb32..d9ccadb 100644 --- a/README.md +++ b/README.md @@ -194,6 +194,8 @@ repo, err := client.FetchRepository(ctx, "https://github.com/octocat/hello-world The `Forge` interface exposes services for repos, issues, pull requests, reviews, releases, CI, branches, labels, milestones, deploy keys, webhooks, secrets, notifications, files, collaborators, commit statuses, commits and artifact attestations. Each backend implements these using its native SDK. +On Bitbucket Cloud, secrets are the repository's Bitbucket Pipelines variables. Listing returns every variable, secured or not, and setting one stores a secured variable, updating and securing any existing variable with that name. Bitbucket deploy keys can only read, so creating one with `ReadOnly` unset (`forge deploy-key add --read-only=false`) returns `forges.ErrNotSupported`. + Under TinyGo, `gitlab.New` retains its signature and returns a backend whose API operations report `forges.ErrNotSupported`. GitLab URL parsing, web link builders and webhook parsing remain available. Native Go retains the full GitLab implementation. ```go diff --git a/bitbucket/branches.go b/bitbucket/branches.go index 4e227bd..9f894f7 100644 --- a/bitbucket/branches.go +++ b/bitbucket/branches.go @@ -9,10 +9,6 @@ import ( forge "github.com/git-pkgs/forge" ) -// maxBranchPageLen is the largest page Bitbucket serves from the refs -// endpoints. -const maxBranchPageLen = 100 - type bitbucketBranchService struct { token string httpClient *http.Client @@ -29,11 +25,6 @@ type bbBranch struct { } `json:"target"` } -type bbBranchesResponse struct { - Values []bbBranch `json:"values"` - Next string `json:"next"` -} - // convertBitbucketBranch maps a Bitbucket branch. Branch objects don't say // whether the branch is the main branch or has restrictions, so Default and // Protected stay false. @@ -50,41 +41,9 @@ func (s *bitbucketBranchService) doJSON(ctx context.Context, method, url string, } func (s *bitbucketBranchService) List(ctx context.Context, owner, repo string, opts forge.ListBranchOpts) ([]forge.Branch, error) { - perPage := opts.PerPage - if perPage <= 0 || perPage > maxBranchPageLen { - perPage = maxBranchPageLen - } - // A start page is counted in pages of perPage, so the page size can only - // shrink to the limit when listing from the first page. - if opts.Limit > 0 && perPage > opts.Limit && opts.Page <= 1 { - perPage = opts.Limit - } - - u := fmt.Sprintf("%s/repositories/%s/%s/refs/branches?pagelen=%d", bitbucketAPI, owner, repo, perPage) - if opts.Page > 1 { - u += fmt.Sprintf("&page=%d", opts.Page) - } - - var all []forge.Branch - for u != "" { - var page bbBranchesResponse - if err := s.doJSON(ctx, http.MethodGet, u, nil, &page); err != nil { - return nil, err - } - for _, bb := range page.Values { - all = append(all, convertBitbucketBranch(bb)) - } - if opts.Limit > 0 && len(all) >= opts.Limit { - break - } - u = page.Next - } - - if opts.Limit > 0 && len(all) > opts.Limit { - all = all[:opts.Limit] - } - - return all, nil + u := fmt.Sprintf("%s/repositories/%s/%s/refs/branches?%s", bitbucketAPI, owner, repo, pageQuery(opts.Page, opts.PerPage, opts.Limit)) + rs := &bitbucketRepoService{token: s.token, httpClient: s.httpClient} + return listPages(ctx, rs, u, opts.Limit, convertBitbucketBranch) } // Create creates branch name at the head of branch from, or at from itself diff --git a/bitbucket/deploy_keys.go b/bitbucket/deploy_keys.go index deaaa30..223972f 100644 --- a/bitbucket/deploy_keys.go +++ b/bitbucket/deploy_keys.go @@ -2,28 +2,88 @@ package bitbucket import ( "context" + "fmt" + "net/http" + "time" forge "github.com/git-pkgs/forge" ) -type bitbucketDeployKeyService struct{} +type bitbucketDeployKeyService struct { + token string + httpClient *http.Client +} func (f *bitbucketForge) DeployKeys() forge.DeployKeyService { - return &bitbucketDeployKeyService{} + return &bitbucketDeployKeyService{token: f.token, httpClient: f.httpClient} +} + +type bbDeployKey struct { + ID int64 `json:"id"` + Key string `json:"key"` + Label string `json:"label"` + CreatedOn string `json:"created_on"` +} + +// convertBitbucketDeployKey maps a Bitbucket deploy key. Bitbucket deploy +// keys can only read, so ReadOnly is always true. +func convertBitbucketDeployKey(bb bbDeployKey) forge.DeployKey { + result := forge.DeployKey{ + ID: bb.ID, + Title: bb.Label, + Key: bb.Key, + ReadOnly: true, + } + if t, err := time.Parse(time.RFC3339, bb.CreatedOn); err == nil { + result.CreatedAt = t + } + return result } -func (s *bitbucketDeployKeyService) List(_ context.Context, _, _ string, _ forge.ListDeployKeyOpts) ([]forge.DeployKey, error) { - return nil, forge.ErrNotSupported +func (s *bitbucketDeployKeyService) repoService() *bitbucketRepoService { + return &bitbucketRepoService{token: s.token, httpClient: s.httpClient} } -func (s *bitbucketDeployKeyService) Get(_ context.Context, _, _ string, _ int64) (*forge.DeployKey, error) { - return nil, forge.ErrNotSupported +func deployKeysURL(owner, repo string) string { + return fmt.Sprintf("%s/repositories/%s/%s/deploy-keys", bitbucketAPI, owner, repo) } -func (s *bitbucketDeployKeyService) Create(_ context.Context, _, _ string, _ forge.CreateDeployKeyOpts) (*forge.DeployKey, error) { - return nil, forge.ErrNotSupported +func (s *bitbucketDeployKeyService) List(ctx context.Context, owner, repo string, opts forge.ListDeployKeyOpts) ([]forge.DeployKey, error) { + u := deployKeysURL(owner, repo) + "?" + pageQuery(opts.Page, opts.PerPage, opts.Limit) + return listPages(ctx, s.repoService(), u, opts.Limit, convertBitbucketDeployKey) +} + +func (s *bitbucketDeployKeyService) Get(ctx context.Context, owner, repo string, id int64) (*forge.DeployKey, error) { + var bb bbDeployKey + u := fmt.Sprintf("%s/%d", deployKeysURL(owner, repo), id) + if err := s.repoService().doJSON(ctx, http.MethodGet, u, nil, &bb); err != nil { + return nil, err + } + result := convertBitbucketDeployKey(bb) + return &result, nil +} + +// Create adds a deploy key. Bitbucket has no deploy keys with write access, +// so asking for one fails with forge.ErrNotSupported instead of silently +// creating a key that can only read. +func (s *bitbucketDeployKeyService) Create(ctx context.Context, owner, repo string, opts forge.CreateDeployKeyOpts) (*forge.DeployKey, error) { + if !opts.ReadOnly { + return nil, fmt.Errorf("creating a deploy key with write access: %w", forge.ErrNotSupported) + } + + body := map[string]string{ + "key": opts.Key, + "label": opts.Title, + } + var bb bbDeployKey + if err := s.repoService().doJSON(ctx, http.MethodPost, deployKeysURL(owner, repo), body, &bb); err != nil { + return nil, err + } + result := convertBitbucketDeployKey(bb) + return &result, nil } -func (s *bitbucketDeployKeyService) Delete(_ context.Context, _, _ string, _ int64) error { - return forge.ErrNotSupported +func (s *bitbucketDeployKeyService) Delete(ctx context.Context, owner, repo string, id int64) error { + u := fmt.Sprintf("%s/%d", deployKeysURL(owner, repo), id) + return s.repoService().doJSON(ctx, http.MethodDelete, u, nil, nil) } diff --git a/bitbucket/deploy_keys_test.go b/bitbucket/deploy_keys_test.go index e8a8526..e292ec0 100644 --- a/bitbucket/deploy_keys_test.go +++ b/bitbucket/deploy_keys_test.go @@ -2,31 +2,173 @@ package bitbucket import ( "context" + "encoding/json" "errors" - forge "github.com/git-pkgs/forge" + "net/http" "testing" + "time" + + forge "github.com/git-pkgs/forge" ) -func TestBitbucketDeployKeyNotSupported(t *testing.T) { - svc := &bitbucketDeployKeyService{} +const deployKeyTestKey = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIKoJlWbTSIfrkeBd3Ti0FbfIEe4kmYVnrIBzMrVAzuhk" - _, err := svc.List(context.Background(), "owner", "repo", forge.ListDeployKeyOpts{}) - if !errors.Is(err, forge.ErrNotSupported) { - t.Errorf("List: expected forge.ErrNotSupported, got %v", err) +func deployKeyJSON(id int64, label string) map[string]any { + return map[string]any{ + "type": "deploy_key", + "id": id, + "key": deployKeyTestKey, + "label": label, + "comment": "ci@example.com", + "created_on": "2024-03-05T10:20:30.123456+00:00", + "last_used": nil, } +} - _, err = svc.Get(context.Background(), "owner", "repo", 1) - if !errors.Is(err, forge.ErrNotSupported) { - t.Errorf("Get: expected forge.ErrNotSupported, got %v", err) +func TestBitbucketListDeployKeys(t *testing.T) { + var srvURL string + mux := http.NewServeMux() + mux.HandleFunc("GET /2.0/repositories/atlassian/stash/deploy-keys", func(w http.ResponseWriter, r *http.Request) { + if got := r.Header.Get("Authorization"); got != "Bearer test-token" { + t.Errorf("Authorization = %q, want bearer token", got) + } + if r.URL.Query().Get("page") == "" { + assertEqual(t, "pagelen", "100", r.URL.Query().Get("pagelen")) + _ = json.NewEncoder(w).Encode(map[string]any{ + "values": []any{deployKeyJSON(11, "ci")}, + "next": srvURL + "/2.0/repositories/atlassian/stash/deploy-keys?pagelen=100&page=2", + }) + return + } + _ = json.NewEncoder(w).Encode(map[string]any{ + "values": []any{deployKeyJSON(12, "mirror")}, + }) + }) + f, u := newTestForge(t, mux) + srvURL = u + + keys, err := f.DeployKeys().List(context.Background(), "atlassian", "stash", forge.ListDeployKeyOpts{}) + if err != nil { + t.Fatalf("unexpected error: %v", err) } - _, err = svc.Create(context.Background(), "owner", "repo", forge.CreateDeployKeyOpts{}) - if !errors.Is(err, forge.ErrNotSupported) { - t.Errorf("Create: expected forge.ErrNotSupported, got %v", err) + created := time.Date(2024, 3, 5, 10, 20, 30, 123456000, time.UTC) + want := []forge.DeployKey{ + {ID: 11, Title: "ci", Key: deployKeyTestKey, ReadOnly: true, CreatedAt: created}, + {ID: 12, Title: "mirror", Key: deployKeyTestKey, ReadOnly: true, CreatedAt: created}, + } + if len(keys) != len(want) { + t.Fatalf("got %d keys, want %d: %+v", len(keys), len(want), keys) + } + for i := range want { + if keys[i].ID != want[i].ID || keys[i].Title != want[i].Title || keys[i].Key != want[i].Key || + keys[i].ReadOnly != want[i].ReadOnly || !keys[i].CreatedAt.Equal(want[i].CreatedAt) { + t.Errorf("keys[%d] = %+v, want %+v", i, keys[i], want[i]) + } + } +} + +func TestBitbucketListDeployKeysLimit(t *testing.T) { + var requests int + mux := http.NewServeMux() + mux.HandleFunc("GET /2.0/repositories/atlassian/stash/deploy-keys", func(w http.ResponseWriter, r *http.Request) { + requests++ + assertEqual(t, "pagelen", "1", r.URL.Query().Get("pagelen")) + _ = json.NewEncoder(w).Encode(map[string]any{ + "values": []any{deployKeyJSON(11, "ci")}, + "next": "http://unused.invalid/next", + }) + }) + f, _ := newTestForge(t, mux) + + keys, err := f.DeployKeys().List(context.Background(), "atlassian", "stash", forge.ListDeployKeyOpts{Limit: 1}) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + assertEqualInt(t, "len", 1, len(keys)) + assertEqualInt(t, "requests", 1, requests) +} + +func TestBitbucketGetDeployKey(t *testing.T) { + mux := http.NewServeMux() + mux.HandleFunc("GET /2.0/repositories/atlassian/stash/deploy-keys/11", func(w http.ResponseWriter, r *http.Request) { + _ = json.NewEncoder(w).Encode(deployKeyJSON(11, "ci")) + }) + f, _ := newTestForge(t, mux) + + key, err := f.DeployKeys().Get(context.Background(), "atlassian", "stash", 11) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + assertEqualInt(t, "ID", 11, int(key.ID)) + assertEqual(t, "Title", "ci", key.Title) + assertEqual(t, "Key", deployKeyTestKey, key.Key) + assertEqualBool(t, "ReadOnly", true, key.ReadOnly) + + if _, err := f.DeployKeys().Get(context.Background(), "atlassian", "stash", 99); !errors.Is(err, forge.ErrNotFound) { + t.Errorf("Get missing key: err = %v, want ErrNotFound", err) + } +} + +func TestBitbucketCreateDeployKey(t *testing.T) { + mux := http.NewServeMux() + mux.HandleFunc("POST /2.0/repositories/atlassian/stash/deploy-keys", func(w http.ResponseWriter, r *http.Request) { + var body map[string]any + if err := json.NewDecoder(r.Body).Decode(&body); err != nil { + t.Errorf("decoding body: %v", err) + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + want := map[string]any{"key": deployKeyTestKey, "label": "ci"} + if len(body) != len(want) || body["key"] != want["key"] || body["label"] != want["label"] { + t.Errorf("body = %v, want %v", body, want) + } + _ = json.NewEncoder(w).Encode(deployKeyJSON(11, "ci")) + }) + f, _ := newTestForge(t, mux) + + key, err := f.DeployKeys().Create(context.Background(), "atlassian", "stash", forge.CreateDeployKeyOpts{ + Title: "ci", + Key: deployKeyTestKey, + ReadOnly: true, + }) + if err != nil { + t.Fatalf("unexpected error: %v", err) } + assertEqualInt(t, "ID", 11, int(key.ID)) + assertEqual(t, "Title", "ci", key.Title) + assertEqualBool(t, "ReadOnly", true, key.ReadOnly) +} + +func TestBitbucketCreateDeployKeyWithWriteAccess(t *testing.T) { + f, _ := newTestForge(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + t.Errorf("unexpected request %s %s", r.Method, r.URL.Path) + })) - err = svc.Delete(context.Background(), "owner", "repo", 1) + _, err := f.DeployKeys().Create(context.Background(), "atlassian", "stash", forge.CreateDeployKeyOpts{ + Title: "ci", + Key: deployKeyTestKey, + }) if !errors.Is(err, forge.ErrNotSupported) { - t.Errorf("Delete: expected forge.ErrNotSupported, got %v", err) + t.Errorf("err = %v, want ErrNotSupported", err) + } +} + +func TestBitbucketDeleteDeployKey(t *testing.T) { + var deleted bool + mux := http.NewServeMux() + mux.HandleFunc("DELETE /2.0/repositories/atlassian/stash/deploy-keys/11", func(w http.ResponseWriter, r *http.Request) { + deleted = true + w.WriteHeader(http.StatusNoContent) + }) + f, _ := newTestForge(t, mux) + + if err := f.DeployKeys().Delete(context.Background(), "atlassian", "stash", 11); err != nil { + t.Fatalf("unexpected error: %v", err) + } + assertEqualBool(t, "deleted", true, deleted) + + if err := f.DeployKeys().Delete(context.Background(), "atlassian", "stash", 99); !errors.Is(err, forge.ErrNotFound) { + t.Errorf("Delete missing key: err = %v, want ErrNotFound", err) } } diff --git a/bitbucket/helpers_test.go b/bitbucket/helpers_test.go index 743e891..6409a0b 100644 --- a/bitbucket/helpers_test.go +++ b/bitbucket/helpers_test.go @@ -1,6 +1,12 @@ package bitbucket -import "testing" +import ( + "net/http" + "net/http/httptest" + "testing" + + forge "github.com/git-pkgs/forge" +) func assertEqual[T ~string](t *testing.T, field, want string, got T) { t.Helper() @@ -22,3 +28,16 @@ func assertEqualInt(t *testing.T, field string, want, got int) { t.Errorf("%s: want %d, got %d", field, want, got) } } + +// newTestForge points the Bitbucket API at a test server running h and +// returns a forge that authenticates with "test-token", along with the +// server's URL. +func newTestForge(t *testing.T, h http.Handler) (forge.Forge, string) { + t.Helper() + srv := httptest.NewServer(h) + t.Cleanup(srv.Close) + origAPI := bitbucketAPI + setBitbucketAPI(srv.URL + "/2.0") + t.Cleanup(func() { setBitbucketAPI(origAPI) }) + return New("test-token", srv.Client()), srv.URL +} diff --git a/bitbucket/paging.go b/bitbucket/paging.go new file mode 100644 index 0000000..5653a9f --- /dev/null +++ b/bitbucket/paging.go @@ -0,0 +1,57 @@ +package bitbucket + +import ( + "context" + "fmt" + "net/http" +) + +// maxPageLen is the largest page Bitbucket serves from most list endpoints. +const maxPageLen = 100 + +// pageQuery returns the pagelen and page query parameters for a list request. +// PerPage defaults to and is capped at maxPageLen. A start page is counted in +// pages of PerPage, so the page size only shrinks to the limit when listing +// from the first page. +func pageQuery(page, perPage, limit int) string { + if perPage <= 0 || perPage > maxPageLen { + perPage = maxPageLen + } + if limit > 0 && perPage > limit && page <= 1 { + perPage = limit + } + q := fmt.Sprintf("pagelen=%d", perPage) + if page > 1 { + q += fmt.Sprintf("&page=%d", page) + } + return q +} + +type bbPage[T any] struct { + Values []T `json:"values"` + Next string `json:"next"` +} + +// listPages fetches u and every page after it by following next links, +// stopping once limit results have been collected when limit is positive. +func listPages[B, T any](ctx context.Context, rs *bitbucketRepoService, u string, limit int, convert func(B) T) ([]T, error) { + var all []T + for u != "" { + var page bbPage[B] + if err := rs.doJSON(ctx, http.MethodGet, u, nil, &page); err != nil { + return nil, err + } + for _, v := range page.Values { + all = append(all, convert(v)) + } + if limit > 0 && len(all) >= limit { + break + } + u = page.Next + } + + if limit > 0 && len(all) > limit { + all = all[:limit] + } + return all, nil +} diff --git a/bitbucket/paging_test.go b/bitbucket/paging_test.go new file mode 100644 index 0000000..ff507b4 --- /dev/null +++ b/bitbucket/paging_test.go @@ -0,0 +1,24 @@ +package bitbucket + +import "testing" + +func TestPageQuery(t *testing.T) { + tests := []struct { + name string + page, perPage, limit int + want string + }{ + {"defaults", 0, 0, 0, "pagelen=100"}, + {"per page", 0, 25, 0, "pagelen=25"}, + {"per page capped", 0, 500, 0, "pagelen=100"}, + {"limit shrinks first page", 0, 0, 10, "pagelen=10"}, + {"limit above per page", 1, 25, 60, "pagelen=25"}, + {"start page", 3, 20, 0, "pagelen=20&page=3"}, + {"start page keeps per page under limit", 2, 50, 10, "pagelen=50&page=2"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + assertEqual(t, "query", tt.want, pageQuery(tt.page, tt.perPage, tt.limit)) + }) + } +} diff --git a/bitbucket/secrets.go b/bitbucket/secrets.go index b50e5f9..0630025 100644 --- a/bitbucket/secrets.go +++ b/bitbucket/secrets.go @@ -2,24 +2,97 @@ package bitbucket import ( "context" + "fmt" + "net/http" + "net/url" forge "github.com/git-pkgs/forge" ) -type bitbucketSecretService struct{} +// bitbucketSecretService manages repository variables for Bitbucket +// Pipelines. Like GitLab's project variables, every variable is listed, +// whether or not it is secured, and Set always stores a secured variable. +type bitbucketSecretService struct { + token string + httpClient *http.Client +} func (f *bitbucketForge) Secrets() forge.SecretService { - return &bitbucketSecretService{} + return &bitbucketSecretService{token: f.token, httpClient: f.httpClient} +} + +type bbPipelineVariable struct { + UUID string `json:"uuid"` + Key string `json:"key"` +} + +// Bitbucket variables carry no timestamps, so only the name is set. +func convertBitbucketVariable(bb bbPipelineVariable) forge.Secret { + return forge.Secret{Name: bb.Key} +} + +func (s *bitbucketSecretService) repoService() *bitbucketRepoService { + return &bitbucketRepoService{token: s.token, httpClient: s.httpClient} } -func (s *bitbucketSecretService) List(_ context.Context, _, _ string, _ forge.ListSecretOpts) ([]forge.Secret, error) { - return nil, forge.ErrNotSupported +func variablesURL(owner, repo string) string { + return fmt.Sprintf("%s/repositories/%s/%s/pipelines_config/variables", bitbucketAPI, owner, repo) } -func (s *bitbucketSecretService) Set(_ context.Context, _, _ string, _ forge.SetSecretOpts) error { - return forge.ErrNotSupported +// variableURL returns the URL of a single variable. Variable UUIDs are +// wrapped in braces, which have to be escaped in the path. +func variableURL(owner, repo, uuid string) string { + return variablesURL(owner, repo) + "/" + url.PathEscape(uuid) +} + +func (s *bitbucketSecretService) List(ctx context.Context, owner, repo string, opts forge.ListSecretOpts) ([]forge.Secret, error) { + u := variablesURL(owner, repo) + "?" + pageQuery(opts.Page, opts.PerPage, opts.Limit) + return listPages(ctx, s.repoService(), u, opts.Limit, convertBitbucketVariable) +} + +// findVariable returns the UUID of the variable called name, or "" when +// there is none. Variables can only be addressed by UUID, so this walks the +// full list. +func (s *bitbucketSecretService) findVariable(ctx context.Context, owner, repo, name string) (string, error) { + u := variablesURL(owner, repo) + "?" + pageQuery(0, 0, 0) + vars, err := listPages(ctx, s.repoService(), u, 0, func(bb bbPipelineVariable) bbPipelineVariable { return bb }) + if err != nil { + return "", err + } + for _, v := range vars { + if v.Key == name { + return v.UUID, nil + } + } + return "", nil +} + +// Set creates a secured variable, or updates the variable with that name and +// marks it secured if it exists. +func (s *bitbucketSecretService) Set(ctx context.Context, owner, repo string, opts forge.SetSecretOpts) error { + uuid, err := s.findVariable(ctx, owner, repo, opts.Name) + if err != nil { + return err + } + + body := map[string]any{ + "key": opts.Name, + "value": opts.Value, + "secured": true, + } + if uuid == "" { + return s.repoService().doJSON(ctx, http.MethodPost, variablesURL(owner, repo), body, nil) + } + return s.repoService().doJSON(ctx, http.MethodPut, variableURL(owner, repo, uuid), body, nil) } -func (s *bitbucketSecretService) Delete(_ context.Context, _, _, _ string) error { - return forge.ErrNotSupported +func (s *bitbucketSecretService) Delete(ctx context.Context, owner, repo, name string) error { + uuid, err := s.findVariable(ctx, owner, repo, name) + if err != nil { + return err + } + if uuid == "" { + return forge.ErrNotFound + } + return s.repoService().doJSON(ctx, http.MethodDelete, variableURL(owner, repo, uuid), nil, nil) } diff --git a/bitbucket/secrets_test.go b/bitbucket/secrets_test.go index 202385c..d20a56e 100644 --- a/bitbucket/secrets_test.go +++ b/bitbucket/secrets_test.go @@ -2,26 +2,205 @@ package bitbucket import ( "context" + "encoding/json" "errors" - forge "github.com/git-pkgs/forge" + "net/http" + "slices" "testing" + + forge "github.com/git-pkgs/forge" +) + +const ( + variablesPath = "/2.0/repositories/atlassian/stash/pipelines_config/variables" + tokenVarUUID = "{8c2a4f1e-0b7d-4e44-9a43-1f5d3c2b6a10}" + tokenVarEscaped = "%7B8c2a4f1e-0b7d-4e44-9a43-1f5d3c2b6a10%7D" ) -func TestBitbucketSecretNotSupported(t *testing.T) { - svc := &bitbucketSecretService{} +func variableJSON(uuid, key string, secured bool) map[string]any { + v := map[string]any{ + "type": "pipeline_variable", + "uuid": uuid, + "key": key, + "secured": secured, + } + if !secured { + v["value"] = "visible" + } + return v +} + +// variablesHandler serves the variable list in two pages, with the +// DEPLOY_TOKEN variable on the second. +func variablesHandler(t *testing.T, srvURL *string) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + if got := r.Header.Get("Authorization"); got != "Bearer test-token" { + t.Errorf("Authorization = %q, want bearer token", got) + } + if r.URL.Query().Get("page") == "" { + _ = json.NewEncoder(w).Encode(map[string]any{ + "values": []any{variableJSON("{11111111-1111-1111-1111-111111111111}", "REGION", false)}, + "next": *srvURL + variablesPath + "?pagelen=100&page=2", + }) + return + } + _ = json.NewEncoder(w).Encode(map[string]any{ + "values": []any{variableJSON(tokenVarUUID, "DEPLOY_TOKEN", true)}, + }) + } +} + +func TestBitbucketListSecrets(t *testing.T) { + var srvURL string + mux := http.NewServeMux() + mux.HandleFunc("GET "+variablesPath, variablesHandler(t, &srvURL)) + f, u := newTestForge(t, mux) + srvURL = u + + secrets, err := f.Secrets().List(context.Background(), "atlassian", "stash", forge.ListSecretOpts{}) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + want := []forge.Secret{{Name: "REGION"}, {Name: "DEPLOY_TOKEN"}} + if !slices.Equal(secrets, want) { + t.Errorf("secrets = %+v, want %+v", secrets, want) + } +} + +func TestBitbucketListSecretsLimit(t *testing.T) { + var srvURL string + var requests int + mux := http.NewServeMux() + list := variablesHandler(t, &srvURL) + mux.HandleFunc("GET "+variablesPath, func(w http.ResponseWriter, r *http.Request) { + requests++ + assertEqual(t, "pagelen", "1", r.URL.Query().Get("pagelen")) + list(w, r) + }) + f, u := newTestForge(t, mux) + srvURL = u - _, err := svc.List(context.Background(), "owner", "repo", forge.ListSecretOpts{}) - if !errors.Is(err, forge.ErrNotSupported) { - t.Errorf("List: expected forge.ErrNotSupported, got %v", err) + secrets, err := f.Secrets().List(context.Background(), "atlassian", "stash", forge.ListSecretOpts{Limit: 1}) + if err != nil { + t.Fatalf("unexpected error: %v", err) } + assertEqualInt(t, "len", 1, len(secrets)) + assertEqualInt(t, "requests", 1, requests) +} - err = svc.Set(context.Background(), "owner", "repo", forge.SetSecretOpts{}) - if !errors.Is(err, forge.ErrNotSupported) { - t.Errorf("Set: expected forge.ErrNotSupported, got %v", err) +func decodeVariableBody(t *testing.T, r *http.Request) map[string]any { + t.Helper() + var body map[string]any + if err := json.NewDecoder(r.Body).Decode(&body); err != nil { + t.Errorf("decoding body: %v", err) } + return body +} + +func assertSecuredVariableBody(t *testing.T, body map[string]any, key, value string) { + t.Helper() + if len(body) != 3 || body["key"] != key || body["value"] != value || body["secured"] != true { + t.Errorf("body = %v, want key %q, value %q, secured", body, key, value) + } +} + +func TestBitbucketSetSecretCreates(t *testing.T) { + var srvURL string + var created bool + mux := http.NewServeMux() + mux.HandleFunc("GET "+variablesPath, variablesHandler(t, &srvURL)) + mux.HandleFunc("POST "+variablesPath, func(w http.ResponseWriter, r *http.Request) { + created = true + assertSecuredVariableBody(t, decodeVariableBody(t, r), "NPM_TOKEN", "s3cret") + w.WriteHeader(http.StatusCreated) + _ = json.NewEncoder(w).Encode(variableJSON("{22222222-2222-2222-2222-222222222222}", "NPM_TOKEN", true)) + }) + mux.HandleFunc("PUT "+variablesPath+"/{uuid}", func(w http.ResponseWriter, r *http.Request) { + t.Errorf("unexpected update of %s", r.PathValue("uuid")) + }) + f, u := newTestForge(t, mux) + srvURL = u + + err := f.Secrets().Set(context.Background(), "atlassian", "stash", forge.SetSecretOpts{Name: "NPM_TOKEN", Value: "s3cret"}) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + assertEqualBool(t, "created", true, created) +} + +func TestBitbucketSetSecretUpdates(t *testing.T) { + var srvURL string + var updated bool + mux := http.NewServeMux() + mux.HandleFunc("GET "+variablesPath, variablesHandler(t, &srvURL)) + mux.HandleFunc("POST "+variablesPath, func(w http.ResponseWriter, r *http.Request) { + t.Error("unexpected create") + }) + mux.HandleFunc("PUT "+variablesPath+"/{uuid}", func(w http.ResponseWriter, r *http.Request) { + updated = true + assertEqual(t, "uuid", tokenVarUUID, r.PathValue("uuid")) + assertEqual(t, "escaped path", variablesPath+"/"+tokenVarEscaped, r.URL.EscapedPath()) + assertSecuredVariableBody(t, decodeVariableBody(t, r), "DEPLOY_TOKEN", "rotated") + _ = json.NewEncoder(w).Encode(variableJSON(tokenVarUUID, "DEPLOY_TOKEN", true)) + }) + f, u := newTestForge(t, mux) + srvURL = u + + err := f.Secrets().Set(context.Background(), "atlassian", "stash", forge.SetSecretOpts{Name: "DEPLOY_TOKEN", Value: "rotated"}) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + assertEqualBool(t, "updated", true, updated) +} + +func TestBitbucketSetSecretListError(t *testing.T) { + mux := http.NewServeMux() + mux.HandleFunc("GET "+variablesPath, func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusForbidden) + }) + mux.HandleFunc("POST "+variablesPath, func(w http.ResponseWriter, r *http.Request) { + t.Error("unexpected create after a failed lookup") + }) + f, _ := newTestForge(t, mux) + + err := f.Secrets().Set(context.Background(), "atlassian", "stash", forge.SetSecretOpts{Name: "NPM_TOKEN", Value: "s3cret"}) + if !errors.Is(err, forge.ErrUnauthorized) { + t.Errorf("err = %v, want ErrUnauthorized", err) + } +} + +func TestBitbucketDeleteSecret(t *testing.T) { + var srvURL string + var deleted bool + mux := http.NewServeMux() + mux.HandleFunc("GET "+variablesPath, variablesHandler(t, &srvURL)) + mux.HandleFunc("DELETE "+variablesPath+"/{uuid}", func(w http.ResponseWriter, r *http.Request) { + deleted = true + assertEqual(t, "uuid", tokenVarUUID, r.PathValue("uuid")) + assertEqual(t, "escaped path", variablesPath+"/"+tokenVarEscaped, r.URL.EscapedPath()) + w.WriteHeader(http.StatusNoContent) + }) + f, u := newTestForge(t, mux) + srvURL = u + + if err := f.Secrets().Delete(context.Background(), "atlassian", "stash", "DEPLOY_TOKEN"); err != nil { + t.Fatalf("unexpected error: %v", err) + } + assertEqualBool(t, "deleted", true, deleted) +} + +func TestBitbucketDeleteSecretNotFound(t *testing.T) { + var srvURL string + mux := http.NewServeMux() + mux.HandleFunc("GET "+variablesPath, variablesHandler(t, &srvURL)) + mux.HandleFunc("DELETE "+variablesPath+"/{uuid}", func(w http.ResponseWriter, r *http.Request) { + t.Errorf("unexpected delete of %s", r.PathValue("uuid")) + }) + f, u := newTestForge(t, mux) + srvURL = u - err = svc.Delete(context.Background(), "owner", "repo", "MY_SECRET") - if !errors.Is(err, forge.ErrNotSupported) { - t.Errorf("Delete: expected forge.ErrNotSupported, got %v", err) + err := f.Secrets().Delete(context.Background(), "atlassian", "stash", "MISSING") + if !errors.Is(err, forge.ErrNotFound) { + t.Errorf("err = %v, want ErrNotFound", err) } } diff --git a/internal/cli/deploy_key.go b/internal/cli/deploy_key.go index 42e2eb9..e0c70b3 100644 --- a/internal/cli/deploy_key.go +++ b/internal/cli/deploy_key.go @@ -104,7 +104,12 @@ func deployKeyAddCmd() *cobra.Command { ReadOnly: flagReadOnly, }) if err != nil { - return notSupported(err, "deploy keys") + feature := "deploy keys" + // A bare ErrNotSupported means the forge has no deploy keys at all. + if !flagReadOnly && err != forges.ErrNotSupported { + feature = "deploy keys with write access" + } + return notSupported(err, feature) } p := printer() diff --git a/internal/cli/deploy_key_test.go b/internal/cli/deploy_key_test.go index f0145e9..34bd881 100644 --- a/internal/cli/deploy_key_test.go +++ b/internal/cli/deploy_key_test.go @@ -1,6 +1,33 @@ package cli -import "testing" +import ( + "context" + "fmt" + "testing" + + "github.com/git-pkgs/forge" + "github.com/git-pkgs/forge/internal/resolve" +) + +type mockDeployKeyService struct { + createErr error +} + +func (m *mockDeployKeyService) List(context.Context, string, string, forges.ListDeployKeyOpts) ([]forges.DeployKey, error) { + return nil, nil +} + +func (m *mockDeployKeyService) Get(context.Context, string, string, int64) (*forges.DeployKey, error) { + return nil, nil +} + +func (m *mockDeployKeyService) Create(context.Context, string, string, forges.CreateDeployKeyOpts) (*forges.DeployKey, error) { + return nil, m.createErr +} + +func (m *mockDeployKeyService) Delete(context.Context, string, string, int64) error { + return nil +} func TestDeployKeySubcommands(t *testing.T) { subs := deployKeyCmd.Commands() @@ -22,3 +49,32 @@ func TestDeployKeySubcommands(t *testing.T) { } } } + +func TestDeployKeyAddNotSupported(t *testing.T) { + wrapped := fmt.Errorf("creating a deploy key: %w", forges.ErrNotSupported) + tests := []struct { + name string + err error + args []string + want string + }{ + {"read-only", wrapped, nil, "deploy keys is not supported by this forge"}, + {"write access", wrapped, []string{"--read-only=false"}, "deploy keys with write access is not supported by this forge"}, + {"no deploy keys at all", forges.ErrNotSupported, []string{"--read-only=false"}, "deploy keys is not supported by this forge"}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + keys := &mockDeployKeyService{createErr: tt.err} + resolve.SetTestForge(&mockForge{deployKeyService: keys}, "owner", "repo", "example.com") + t.Cleanup(resolve.ResetTestForge) + + cmd := deployKeyAddCmd() + cmd.SetArgs(append([]string{"--title", "ci", "--key", "ssh-ed25519 AAAA"}, tt.args...)) + err := cmd.Execute() + if err == nil || err.Error() != tt.want { + t.Fatalf("error = %v, want %q", err, tt.want) + } + }) + } +} diff --git a/internal/cli/pr_checkout_test.go b/internal/cli/pr_checkout_test.go index db1a3ad..ef66216 100644 --- a/internal/cli/pr_checkout_test.go +++ b/internal/cli/pr_checkout_test.go @@ -92,6 +92,7 @@ type mockForge struct { commitStatusService forges.CommitStatusService checkRunService forges.CheckRunService attestationService forges.AttestationService + deployKeyService forges.DeployKeyService } func (m *mockForge) Repos() forges.RepoService { return m.repoService } @@ -102,7 +103,7 @@ func (m *mockForge) Milestones() forges.MilestoneService { return nil } func (m *mockForge) Releases() forges.ReleaseService { return m.releaseService } func (m *mockForge) CI() forges.CIService { return m.ciService } func (m *mockForge) Branches() forges.BranchService { return nil } -func (m *mockForge) DeployKeys() forges.DeployKeyService { return nil } +func (m *mockForge) DeployKeys() forges.DeployKeyService { return m.deployKeyService } func (m *mockForge) Webhooks() forges.WebhookService { return m.webhookService } func (m *mockForge) Secrets() forges.SecretService { return nil } func (m *mockForge) Notifications() forges.NotificationService { return nil }