From cd9904ae95a0a6175559be13c679f10cb1082457 Mon Sep 17 00:00:00 2001 From: NopeCharon <115794254+NopeCharon@users.noreply.github.com> Date: Thu, 19 Nov 2026 19:02:47 +0000 Subject: [PATCH 1/3] Add file access and commit resolution to the Bitbucket backend The Bitbucket Cloud backend returned ErrNotSupported for Files().Get, Files().List and Commits().ResolveCommit, so `forge file cat`/`file ls`, Client.ResolveCommit and funding.Discover didn't work on bitbucket.org even though its API covers all three. ResolveCommit uses the single-commit endpoint, which resolves branches, tags and abbreviated SHAs. That endpoint, like /src, takes the ref as a path segment and 404s on any ref containing a slash, escaped or not, so "feature/login" can't be resolved there. Slashed refs are looked up on the refs endpoints instead, which accept them escaped into one segment: first as a branch, then as a tag. Full SHAs are normalized without a request, as on the other backends. Files are read from /src. That endpoint answers a directory with a JSON listing and a file with its raw bytes (JSON files included, served as text/plain), so: - Get asks for ?format=meta first, rejects directories and files over 32 MB, then reads the content at the commit the metadata came from so a branch moving in between can't mix two versions. Bitbucket doesn't expose blob SHAs, so FileContent.SHA stays empty. - List requests the directory with the trailing slash Bitbucket needs (the root 404s without one), follows `next` links, and reports a path that turns out to be a file as "not a directory" instead of failing to decode its content. Entries map to dir, file, symlink (the "link" attribute) and submodule ("subrepository"). An empty ref reads the main branch through HEAD, and a slashed ref is resolved to its commit first. Paths are cleaned against the repository root, so "." and ".." segments can't leave the /src endpoint. doJSON's request handling moves into a send helper that returns the response, so the raw reads share its auth header and error mapping. Tests cover both services against httptest servers, the error classification table, and replay recordings of real api.bitbucket.org responses, including a slashed branch. --- README.md | 2 +- bitbucket/bitbucket.go | 34 ++- bitbucket/commits.go | 72 ++++- bitbucket/commits_test.go | 184 ++++++++++++ bitbucket/errors_test.go | 8 + bitbucket/files.go | 191 +++++++++++- bitbucket/files_test.go | 277 +++++++++++++++++- bitbucket/replay_test.go | 45 +++ .../testdata/replay/TestReplayGetFile.json | 32 ++ .../testdata/replay/TestReplayListFiles.json | 17 ++ .../replay/TestReplayResolveCommit.json | 17 ++ .../TestReplayResolveCommitSlashedBranch.json | 17 ++ 12 files changed, 867 insertions(+), 29 deletions(-) create mode 100644 bitbucket/commits_test.go create mode 100644 bitbucket/testdata/replay/TestReplayGetFile.json create mode 100644 bitbucket/testdata/replay/TestReplayListFiles.json create mode 100644 bitbucket/testdata/replay/TestReplayResolveCommit.json create mode 100644 bitbucket/testdata/replay/TestReplayResolveCommitSlashedBranch.json diff --git a/README.md b/README.md index ee0bb32..1709f50 100644 --- a/README.md +++ b/README.md @@ -358,7 +358,7 @@ p, _ := purl.Parse("pkg:npm/lodash?repository_url=https://github.com/lodash/loda repo, err := client.FetchRepositoryFromPURL(ctx, p) ``` -Branches, tags and abbreviated commit refs can be resolved to full commit SHAs without listing every tag. GitHub, GitLab and Gitea/Forgejo implement this; the remaining backends return `forges.ErrNotSupported`. +Branches, tags and abbreviated commit refs can be resolved to full commit SHAs without listing every tag. GitHub, GitLab, Gitea/Forgejo and Bitbucket Cloud implement this; the remaining backends return `forges.ErrNotSupported`. ```go f, _ := client.ForgeFor("gitlab.com") diff --git a/bitbucket/bitbucket.go b/bitbucket/bitbucket.go index 68a96d6..7b0b715 100644 --- a/bitbucket/bitbucket.go +++ b/bitbucket/bitbucket.go @@ -113,19 +113,22 @@ type bbReposResponse struct { Next string `json:"next"` } -func (s *bitbucketRepoService) doJSON(ctx context.Context, method, url string, body any, v any) error { +// send makes a request and returns the response when its status is below +// 400. A 404 becomes forge.ErrNotFound and any other error status a +// forge.HTTPError. The caller closes the response body. +func (s *bitbucketRepoService) send(ctx context.Context, method, url string, body any) (*http.Response, error) { var bodyReader io.Reader if body != nil { b, err := json.Marshal(body) if err != nil { - return err + return nil, err } bodyReader = bytes.NewReader(b) } req, err := http.NewRequestWithContext(ctx, method, url, bodyReader) if err != nil { - return err + return nil, err } if s.token != "" { req.Header.Set("Authorization", "Bearer "+s.token) @@ -136,19 +139,30 @@ func (s *bitbucketRepoService) doJSON(ctx context.Context, method, url string, b resp, err := s.httpClient.Do(req) if err != nil { - return err + return nil, err } - defer func() { _ = resp.Body.Close() }() if resp.StatusCode == http.StatusNotFound { - return forge.ErrNotFound - } - if resp.StatusCode == http.StatusNoContent { - return nil + _ = resp.Body.Close() + return nil, forge.ErrNotFound } if resp.StatusCode >= http.StatusBadRequest { respBody, _ := io.ReadAll(resp.Body) - return &forge.HTTPError{StatusCode: resp.StatusCode, URL: url, Body: string(respBody)} + _ = resp.Body.Close() + return nil, &forge.HTTPError{StatusCode: resp.StatusCode, URL: url, Body: string(respBody)} + } + return resp, nil +} + +func (s *bitbucketRepoService) doJSON(ctx context.Context, method, url string, body any, v any) error { + resp, err := s.send(ctx, method, url, body) + if err != nil { + return err + } + defer func() { _ = resp.Body.Close() }() + + if resp.StatusCode == http.StatusNoContent { + return nil } if v != nil { diff --git a/bitbucket/commits.go b/bitbucket/commits.go index 92ae34f..239b1af 100644 --- a/bitbucket/commits.go +++ b/bitbucket/commits.go @@ -2,16 +2,80 @@ package bitbucket import ( "context" + "errors" + "fmt" + "net/http" + "net/url" + "strings" forge "github.com/git-pkgs/forge" ) -type bitbucketCommitService struct{} +type bitbucketCommitService struct { + token string + httpClient *http.Client +} func (f *bitbucketForge) Commits() forge.CommitService { - return &bitbucketCommitService{} + return &bitbucketCommitService{token: f.token, httpClient: f.httpClient} +} + +type bbRef struct { + Target struct { + Hash string `json:"hash"` + } `json:"target"` +} + +// ResolveCommit returns the full commit SHA for ref in owner/repo. The +// single-commit endpoint resolves branches, tags and abbreviated SHAs, but it +// takes the ref as a path segment and can't route one that contains a slash, +// such as "feature/login". Those are looked up as a branch and then as a tag. +func (s *bitbucketCommitService) ResolveCommit(ctx context.Context, owner, repo, ref string) (string, error) { + if err := forge.ValidateCommitRef(owner, repo, ref); err != nil { + return "", err + } + if forge.IsFullCommitSHA(ref) { + return strings.ToLower(ref), nil + } + + rs := &bitbucketRepoService{token: s.token, httpClient: s.httpClient} + var sha string + if strings.Contains(ref, "/") { + hash, err := resolveSlashedRef(ctx, rs, owner, repo, ref) + if err != nil { + return "", forge.CommitRefError(owner, repo, ref, err) + } + sha = hash + } else { + u := fmt.Sprintf("%s/repositories/%s/%s/commit/%s", bitbucketAPI, owner, repo, url.PathEscape(ref)) + var commit struct { + Hash string `json:"hash"` + } + if err := rs.getJSON(ctx, u, &commit); err != nil { + return "", forge.CommitRefError(owner, repo, ref, err) + } + sha = commit.Hash + } + return forge.ResolvedCommitSHA(owner, repo, ref, sha) } -func (s *bitbucketCommitService) ResolveCommit(_ context.Context, _, _, _ string) (string, error) { - return "", forge.ErrNotSupported +// resolveSlashedRef returns the commit hash of the branch or tag named ref. +// Bitbucket only accepts a ref containing a slash on its refs endpoints, where +// it is escaped into one path segment. Branches are tried first because that +// is where slashed names are common. It returns forge.ErrNotFound when +// neither exists. +func resolveSlashedRef(ctx context.Context, rs *bitbucketRepoService, owner, repo, ref string) (string, error) { + for _, kind := range []string{"branches", "tags"} { + u := fmt.Sprintf("%s/repositories/%s/%s/refs/%s/%s", bitbucketAPI, owner, repo, kind, url.PathEscape(ref)) + var r bbRef + err := rs.getJSON(ctx, u, &r) + if errors.Is(err, forge.ErrNotFound) { + continue + } + if err != nil { + return "", err + } + return r.Target.Hash, nil + } + return "", forge.ErrNotFound } diff --git a/bitbucket/commits_test.go b/bitbucket/commits_test.go new file mode 100644 index 0000000..6cd1b55 --- /dev/null +++ b/bitbucket/commits_test.go @@ -0,0 +1,184 @@ +package bitbucket + +import ( + "context" + "encoding/json" + "errors" + "net/http" + "net/http/httptest" + "slices" + "sync/atomic" + "testing" + + forge "github.com/git-pkgs/forge" +) + +const ( + bitbucketCommitSHA = "8e8c483db84b4bee98b60c0593521ed34d9990e8" + bitbucketCommitSHAUpper = "8E8C483DB84B4BEE98B60C0593521ED34D9990E8" +) + +// newCommitTestForge points the Bitbucket API at a test server running h. +func newCommitTestForge(t *testing.T, h http.Handler) forge.Forge { + 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()) +} + +func writeRefTarget(w http.ResponseWriter, hash string) { + _ = json.NewEncoder(w).Encode(map[string]any{ + "target": map[string]any{"hash": hash}, + }) +} + +func TestBitbucketResolveCommit(t *testing.T) { + mux := http.NewServeMux() + mux.HandleFunc("GET /2.0/repositories/atlassian/stash/commit/v1.0.0", 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) + } + _ = json.NewEncoder(w).Encode(map[string]any{"hash": bitbucketCommitSHAUpper}) + }) + + f := newCommitTestForge(t, mux) + sha, err := f.Commits().ResolveCommit(context.Background(), "atlassian", "stash", "v1.0.0") + if err != nil { + t.Fatalf("ResolveCommit() error = %v", err) + } + if sha != bitbucketCommitSHA { + t.Errorf("ResolveCommit() = %q, want %q", sha, bitbucketCommitSHA) + } +} + +func TestBitbucketResolveCommitSkipsRequestForFullSHA(t *testing.T) { + var requests atomic.Int32 + f := newCommitTestForge(t, http.HandlerFunc(func(http.ResponseWriter, *http.Request) { + requests.Add(1) + })) + + sha, err := f.Commits().ResolveCommit(context.Background(), "atlassian", "stash", bitbucketCommitSHAUpper) + if err != nil { + t.Fatalf("ResolveCommit() error = %v", err) + } + if sha != bitbucketCommitSHA { + t.Errorf("ResolveCommit() = %q, want normalized %q", sha, bitbucketCommitSHA) + } + if got := requests.Load(); got != 0 { + t.Errorf("ResolveCommit() made %d requests for a full SHA, want 0", got) + } +} + +func TestBitbucketResolveCommitNotFound(t *testing.T) { + f := newCommitTestForge(t, http.NotFoundHandler()) + _, err := f.Commits().ResolveCommit(context.Background(), "atlassian", "stash", "missing") + if !errors.Is(err, forge.ErrNotFound) { + t.Errorf("ResolveCommit() error = %v, want ErrNotFound", err) + } +} + +func TestBitbucketResolveCommitRejectsShortSHAInResponse(t *testing.T) { + mux := http.NewServeMux() + mux.HandleFunc("GET /2.0/repositories/atlassian/stash/commit/v1.0.0", func(w http.ResponseWriter, _ *http.Request) { + _ = json.NewEncoder(w).Encode(map[string]any{"hash": "8e8c483"}) + }) + + f := newCommitTestForge(t, mux) + if _, err := f.Commits().ResolveCommit(context.Background(), "atlassian", "stash", "v1.0.0"); err == nil { + t.Fatal("ResolveCommit() error = nil, want invalid SHA error") + } +} + +func TestBitbucketResolveCommitRequiresArguments(t *testing.T) { + f := New("", nil) + if _, err := f.Commits().ResolveCommit(context.Background(), "", "stash", "v1.0.0"); !errors.Is(err, forge.ErrCommitRefRequired) { + t.Errorf("ResolveCommit() error = %v, want ErrCommitRefRequired", err) + } +} + +func TestBitbucketResolveCommitSlashedRef(t *testing.T) { + tests := []struct { + name string + branches bool // whether the ref exists as a branch + tags bool // whether the ref exists as a tag + wantSHA string + wantErr error + wantURLs []string + }{ + { + name: "branch", + branches: true, + tags: true, + wantSHA: bitbucketCommitSHA, + wantURLs: []string{"/2.0/repositories/atlassian/stash/refs/branches/feature%2Flogin"}, + }, + { + name: "tag", + tags: true, + wantSHA: bitbucketCommitSHA, + wantURLs: []string{ + "/2.0/repositories/atlassian/stash/refs/branches/feature%2Flogin", + "/2.0/repositories/atlassian/stash/refs/tags/feature%2Flogin", + }, + }, + { + name: "missing", + wantErr: forge.ErrNotFound, + wantURLs: []string{ + "/2.0/repositories/atlassian/stash/refs/branches/feature%2Flogin", + "/2.0/repositories/atlassian/stash/refs/tags/feature%2Flogin", + }, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + var got []string + f := newCommitTestForge(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + got = append(got, r.URL.EscapedPath()) + switch r.URL.EscapedPath() { + case "/2.0/repositories/atlassian/stash/refs/branches/feature%2Flogin": + if tt.branches { + writeRefTarget(w, bitbucketCommitSHA) + return + } + case "/2.0/repositories/atlassian/stash/refs/tags/feature%2Flogin": + if tt.tags { + writeRefTarget(w, bitbucketCommitSHA) + return + } + } + http.NotFound(w, r) + })) + + sha, err := f.Commits().ResolveCommit(context.Background(), "atlassian", "stash", "feature/login") + if tt.wantErr != nil { + if !errors.Is(err, tt.wantErr) { + t.Fatalf("ResolveCommit() error = %v, want %v", err, tt.wantErr) + } + } else if err != nil { + t.Fatalf("ResolveCommit() error = %v", err) + } + if sha != tt.wantSHA { + t.Errorf("ResolveCommit() = %q, want %q", sha, tt.wantSHA) + } + if !slices.Equal(got, tt.wantURLs) { + t.Errorf("requested %v, want %v", got, tt.wantURLs) + } + }) + } +} + +func TestBitbucketResolveCommitSlashedRefServerError(t *testing.T) { + f := newCommitTestForge(t, http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(http.StatusInternalServerError) + })) + + _, err := f.Commits().ResolveCommit(context.Background(), "atlassian", "stash", "feature/login") + if !errors.Is(err, forge.ErrServerError) { + t.Errorf("ResolveCommit() error = %v, want ErrServerError", err) + } +} diff --git a/bitbucket/errors_test.go b/bitbucket/errors_test.go index 4a3ceaf..764ca95 100644 --- a/bitbucket/errors_test.go +++ b/bitbucket/errors_test.go @@ -30,6 +30,14 @@ func TestBitbucketErrorsAreClassified(t *testing.T) { _, err := f.PullRequests().Diff(ctx, "owner", "repo", 1) return err }, + "file content": func(f forge.Forge) error { + _, err := f.Files().Get(ctx, "owner", "repo", "README.md", "main") + return err + }, + "resolve commit": func(f forge.Forge) error { + _, err := f.Commits().ResolveCommit(ctx, "owner", "repo", "main") + return err + }, } for _, tt := range tests { diff --git a/bitbucket/files.go b/bitbucket/files.go index ab25346..7b5a585 100644 --- a/bitbucket/files.go +++ b/bitbucket/files.go @@ -2,20 +2,199 @@ package bitbucket import ( "context" + "encoding/json" + "errors" + "fmt" + "io" + "mime" + "net/http" + "net/url" + "path" + "slices" + "strings" forge "github.com/git-pkgs/forge" ) -type bitbucketFileService struct{} +const maxFileSize = 32 << 20 // 32 MB + +type bitbucketFileService struct { + token string + httpClient *http.Client +} func (f *bitbucketForge) Files() forge.FileService { - return &bitbucketFileService{} + return &bitbucketFileService{token: f.token, httpClient: f.httpClient} +} + +// bbSrcEntry is a file or directory from the /src endpoint, either on its own +// (with ?format=meta) or as an entry in a directory listing. +type bbSrcEntry struct { + Path string `json:"path"` + Type string `json:"type"` // commit_file or commit_directory + Size int64 `json:"size"` + Attributes []string `json:"attributes"` // link, executable, subrepository, binary, lfs + Commit struct { + Hash string `json:"hash"` + } `json:"commit"` +} + +type bbSrcResponse struct { + Values []bbSrcEntry `json:"values"` + Next string `json:"next"` +} + +func (s *bitbucketFileService) repoService() *bitbucketRepoService { + return &bitbucketRepoService{token: s.token, httpClient: s.httpClient} +} + +// pathSegments splits a repository file path into its segments. The path is +// cleaned against the repository root first, so empty, "." and ".." segments +// are resolved and can never climb out of the /src endpoint. +func pathSegments(filePath string) []string { + clean := path.Clean("/" + filePath) + if clean == "/" { + return nil + } + return strings.Split(clean[1:], "/") +} + +// srcURL returns the /src URL for the path segments at revision rev. +func srcURL(owner, repo, rev string, segments []string) string { + parts := make([]string, 0, len(segments)+1) + parts = append(parts, url.PathEscape(rev)) + for _, seg := range segments { + parts = append(parts, url.PathEscape(seg)) + } + return fmt.Sprintf("%s/repositories/%s/%s/src/%s", bitbucketAPI, owner, repo, strings.Join(parts, "/")) } -func (s *bitbucketFileService) Get(_ context.Context, _, _, _, _ string) (*forge.FileContent, error) { - return nil, forge.ErrNotSupported +// srcRevision returns the revision to put in a /src URL for ref. An empty ref +// means the main branch, which Bitbucket serves as HEAD. The /src endpoint +// takes the revision as a single path segment, so a branch or tag containing +// a slash is resolved to its commit first. +func (s *bitbucketFileService) srcRevision(ctx context.Context, owner, repo, ref string) (string, error) { + switch { + case ref == "": + return "HEAD", nil + case strings.Contains(ref, "/"): + return resolveSlashedRef(ctx, s.repoService(), owner, repo, ref) + default: + return ref, nil + } +} + +func (s *bitbucketFileService) Get(ctx context.Context, owner, repo, filePath, ref string) (*forge.FileContent, error) { + segments := pathSegments(filePath) + if len(segments) == 0 { + return nil, errors.New("file path is required") + } + rev, err := s.srcRevision(ctx, owner, repo, ref) + if err != nil { + return nil, err + } + + // The /src endpoint answers a directory with a JSON listing and a file + // with its raw content, so ask for the metadata first to tell them apart. + rs := s.repoService() + var meta bbSrcEntry + if err := rs.getJSON(ctx, srcURL(owner, repo, rev, segments)+"?format=meta", &meta); err != nil { + return nil, err + } + p := strings.Join(segments, "/") + if meta.Type == "commit_directory" { + return nil, fmt.Errorf("%s is a directory", p) + } + if meta.Size > maxFileSize { + return nil, fmt.Errorf("%s is %d bytes, larger than the %d byte limit", p, meta.Size, maxFileSize) + } + // Read the content from the commit the metadata came from, so a branch + // that moves in between can't mix up two versions of the file. + if meta.Commit.Hash != "" { + rev = meta.Commit.Hash + } + + u := srcURL(owner, repo, rev, segments) + resp, err := rs.send(ctx, http.MethodGet, u, nil) + if err != nil { + return nil, err + } + defer func() { _ = resp.Body.Close() }() + content, err := io.ReadAll(io.LimitReader(resp.Body, maxFileSize+1)) + if err != nil { + return nil, err + } + if len(content) > maxFileSize { + return nil, fmt.Errorf("%s is larger than the %d byte limit", p, maxFileSize) + } + + return &forge.FileContent{ + Name: path.Base(p), + Path: p, + Content: content, + }, nil +} + +func (s *bitbucketFileService) List(ctx context.Context, owner, repo, filePath, ref string) ([]forge.FileEntry, error) { + rev, err := s.srcRevision(ctx, owner, repo, ref) + if err != nil { + return nil, err + } + + rs := s.repoService() + segments := pathSegments(filePath) + dir := strings.Join(segments, "/") + // Directories, the root included, are only listed with a trailing slash. + u := srcURL(owner, repo, rev, segments) + "/?pagelen=100" + var entries []forge.FileEntry + for u != "" { + page, err := listPage(ctx, rs, u, dir) + if err != nil { + return nil, err + } + for _, e := range page.Values { + entries = append(entries, forge.FileEntry{ + Name: path.Base(e.Path), + Path: e.Path, + Type: srcEntryType(e), + Size: e.Size, + }) + } + u = page.Next + } + return entries, nil +} + +// listPage fetches one page of the listing of dir. The /src endpoint serves a +// file's raw content rather than an error when dir names a file, which shows +// up as a response that isn't JSON. +func listPage(ctx context.Context, rs *bitbucketRepoService, u, dir string) (*bbSrcResponse, error) { + resp, err := rs.send(ctx, http.MethodGet, u, nil) + if err != nil { + return nil, err + } + defer func() { _ = resp.Body.Close() }() + + mediaType, _, _ := mime.ParseMediaType(resp.Header.Get("Content-Type")) + if mediaType != "application/json" { + return nil, fmt.Errorf("%s is not a directory", dir) + } + var page bbSrcResponse + if err := json.NewDecoder(resp.Body).Decode(&page); err != nil { + return nil, err + } + return &page, nil } -func (s *bitbucketFileService) List(_ context.Context, _, _, _, _ string) ([]forge.FileEntry, error) { - return nil, forge.ErrNotSupported +func srcEntryType(e bbSrcEntry) string { + switch { + case e.Type == "commit_directory": + return "dir" + case slices.Contains(e.Attributes, "link"): + return "symlink" + case slices.Contains(e.Attributes, "subrepository"): + return "submodule" + default: + return "file" + } } diff --git a/bitbucket/files_test.go b/bitbucket/files_test.go index d402715..76387d5 100644 --- a/bitbucket/files_test.go +++ b/bitbucket/files_test.go @@ -2,22 +2,283 @@ package bitbucket import ( "context" + "encoding/json" + "errors" + "net/http" + "net/http/httptest" + "slices" + "strings" "testing" forge "github.com/git-pkgs/forge" ) -func TestBitbucketFilesNotSupported(t *testing.T) { - f := New("token", nil) +const fileTestCommit = "5b6c39df3196eeeb8a36684beb9a3df854a0b5f3" + +// newFileTestForge points the Bitbucket API at a test server running h. +func newFileTestForge(t *testing.T, h http.Handler) forge.Forge { + 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()) +} + +func writeSrcMeta(w http.ResponseWriter, path, typ string, size int64) { + _ = json.NewEncoder(w).Encode(map[string]any{ + "path": path, + "type": typ, + "size": size, + "commit": map[string]any{"hash": fileTestCommit}, + }) +} + +func TestBitbucketGetFile(t *testing.T) { + mux := http.NewServeMux() + mux.HandleFunc("GET /2.0/repositories/atlassian/stash/src/main/docs/README.md", func(w http.ResponseWriter, r *http.Request) { + if r.URL.Query().Get("format") != "meta" { + t.Errorf("content requested at the ref instead of the resolved commit") + } + writeSrcMeta(w, "docs/README.md", "commit_file", 5) + }) + mux.HandleFunc("GET /2.0/repositories/atlassian/stash/src/"+fileTestCommit+"/docs/README.md", 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) + } + w.Header().Set("Content-Type", "text/plain") + _, _ = w.Write([]byte("hello")) + }) + + f := newFileTestForge(t, mux) + file, err := f.Files().Get(context.Background(), "atlassian", "stash", "docs/README.md", "main") + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + + assertEqual(t, "Name", "README.md", file.Name) + assertEqual(t, "Path", "docs/README.md", file.Path) + assertEqual(t, "Content", "hello", string(file.Content)) +} + +func TestBitbucketGetFileDefaultsToHEAD(t *testing.T) { + mux := http.NewServeMux() + mux.HandleFunc("GET /2.0/repositories/atlassian/stash/src/HEAD/FUNDING.yml", func(w http.ResponseWriter, _ *http.Request) { + writeSrcMeta(w, "FUNDING.yml", "commit_file", 4) + }) + mux.HandleFunc("GET /2.0/repositories/atlassian/stash/src/"+fileTestCommit+"/FUNDING.yml", func(w http.ResponseWriter, _ *http.Request) { + _, _ = w.Write([]byte("x: y")) + }) + + f := newFileTestForge(t, mux) + file, err := f.Files().Get(context.Background(), "atlassian", "stash", "FUNDING.yml", "") + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + assertEqual(t, "Content", "x: y", string(file.Content)) +} + +func TestBitbucketGetFileSlashedRef(t *testing.T) { + f := newFileTestForge(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.URL.EscapedPath() { + case "/2.0/repositories/atlassian/stash/refs/branches/feature%2Flogin": + _ = json.NewEncoder(w).Encode(map[string]any{ + "target": map[string]any{"hash": fileTestCommit}, + }) + case "/2.0/repositories/atlassian/stash/src/" + fileTestCommit + "/a.txt": + if r.URL.Query().Get("format") == "meta" { + writeSrcMeta(w, "a.txt", "commit_file", 1) + return + } + _, _ = w.Write([]byte("a")) + default: + t.Errorf("unexpected request %s", r.URL.EscapedPath()) + http.NotFound(w, r) + } + })) + + file, err := f.Files().Get(context.Background(), "atlassian", "stash", "a.txt", "feature/login") + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + assertEqual(t, "Content", "a", string(file.Content)) +} + +func TestBitbucketGetFileDirectory(t *testing.T) { + mux := http.NewServeMux() + mux.HandleFunc("GET /2.0/repositories/atlassian/stash/src/main/docs", func(w http.ResponseWriter, _ *http.Request) { + writeSrcMeta(w, "docs", "commit_directory", 0) + }) + + f := newFileTestForge(t, mux) + _, err := f.Files().Get(context.Background(), "atlassian", "stash", "docs", "main") + if err == nil || !strings.Contains(err.Error(), "docs is a directory") { + t.Fatalf("error = %v, want directory error", err) + } +} + +func TestBitbucketGetFileTooLarge(t *testing.T) { + mux := http.NewServeMux() + mux.HandleFunc("GET /2.0/repositories/atlassian/stash/src/main/big.bin", func(w http.ResponseWriter, _ *http.Request) { + writeSrcMeta(w, "big.bin", "commit_file", maxFileSize+1) + }) + + f := newFileTestForge(t, mux) + _, err := f.Files().Get(context.Background(), "atlassian", "stash", "big.bin", "main") + if err == nil || !strings.Contains(err.Error(), "limit") { + t.Fatalf("error = %v, want size limit error", err) + } +} + +func TestBitbucketGetFileNotFound(t *testing.T) { + f := newFileTestForge(t, http.NotFoundHandler()) + _, err := f.Files().Get(context.Background(), "atlassian", "stash", "missing.txt", "main") + if !errors.Is(err, forge.ErrNotFound) { + t.Fatalf("error = %v, want ErrNotFound", err) + } +} + +func TestBitbucketGetFileRequiresPath(t *testing.T) { + f := New("", nil) + for _, p := range []string{"", "/", ".", "a/.."} { + if _, err := f.Files().Get(context.Background(), "atlassian", "stash", p, "main"); err == nil { + t.Errorf("Get(%q): expected an error", p) + } + } +} + +func TestBitbucketFilePathsStayInsideSrc(t *testing.T) { + var paths []string + f := newFileTestForge(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + paths = append(paths, r.URL.EscapedPath()) + http.NotFound(w, r) + })) + ctx := context.Background() + _, _ = f.Files().Get(ctx, "atlassian", "stash", "../../../pullrequests/1", "main") + _, _ = f.Files().List(ctx, "atlassian", "stash", "docs/../../..", "main") + + want := []string{ + "/2.0/repositories/atlassian/stash/src/main/pullrequests/1", + "/2.0/repositories/atlassian/stash/src/main/", + } + if !slices.Equal(paths, want) { + t.Errorf("requested %v, want %v", paths, want) + } +} + +func TestSrcURLEscapesSegments(t *testing.T) { + got := srcURL("o", "r", "v1.0", []string{"a b", "c#d?.txt"}) + want := bitbucketAPI + "/repositories/o/r/src/v1.0/a%20b/c%23d%3F.txt" + if got != want { + t.Errorf("srcURL = %q, want %q", got, want) + } +} + +func TestBitbucketListFiles(t *testing.T) { + var srvURL string + mux := http.NewServeMux() + mux.HandleFunc("GET /2.0/repositories/atlassian/stash/src/main/", func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json; charset=utf-8") + if r.URL.Query().Get("page") == "" { + if got := r.URL.Query().Get("pagelen"); got != "100" { + t.Errorf("pagelen = %q, want 100", got) + } + _ = json.NewEncoder(w).Encode(map[string]any{ + "values": []map[string]any{ + {"path": "docs", "type": "commit_directory"}, + {"path": "README.md", "type": "commit_file", "size": 120, "attributes": []string{}}, + }, + "next": srvURL + "/2.0/repositories/atlassian/stash/src/main/?pagelen=100&page=2", + }) + return + } + _ = json.NewEncoder(w).Encode(map[string]any{ + "values": []map[string]any{ + {"path": "current", "type": "commit_file", "size": 7, "attributes": []string{"link"}}, + {"path": "vendor/lib", "type": "commit_file", "attributes": []string{"subrepository"}}, + {"path": "run.sh", "type": "commit_file", "size": 30, "attributes": []string{"executable"}}, + }, + }) + }) + srv := httptest.NewServer(mux) + defer srv.Close() + srvURL = srv.URL + origAPI := bitbucketAPI + setBitbucketAPI(srv.URL + "/2.0") + defer setBitbucketAPI(origAPI) + + entries, err := New("", srv.Client()).Files().List(context.Background(), "atlassian", "stash", "", "main") + if err != nil { + t.Fatalf("unexpected error: %v", err) + } - _, err := f.Files().Get(ctx, "owner", "repo", "path", "main") - if err != forge.ErrNotSupported { - t.Errorf("Get: expected forge.ErrNotSupported, got %v", err) + want := []forge.FileEntry{ + {Name: "docs", Path: "docs", Type: "dir"}, + {Name: "README.md", Path: "README.md", Type: "file", Size: 120}, + {Name: "current", Path: "current", Type: "symlink", Size: 7}, + {Name: "lib", Path: "vendor/lib", Type: "submodule"}, + {Name: "run.sh", Path: "run.sh", Type: "file", Size: 30}, } + if !slices.Equal(entries, want) { + t.Errorf("entries = %+v, want %+v", entries, want) + } +} + +func TestBitbucketListFilesSubdirectory(t *testing.T) { + mux := http.NewServeMux() + mux.HandleFunc("GET /2.0/repositories/atlassian/stash/src/HEAD/docs/guides/", func(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(map[string]any{ + "values": []map[string]any{ + {"path": "docs/guides/setup.md", "type": "commit_file", "size": 10}, + }, + }) + }) + + f := newFileTestForge(t, mux) + entries, err := f.Files().List(context.Background(), "atlassian", "stash", "/docs/guides/", "") + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + want := []forge.FileEntry{{Name: "setup.md", Path: "docs/guides/setup.md", Type: "file", Size: 10}} + if !slices.Equal(entries, want) { + t.Errorf("entries = %+v, want %+v", entries, want) + } +} - _, err = f.Files().List(ctx, "owner", "repo", "path", "main") - if err != forge.ErrNotSupported { - t.Errorf("List: expected forge.ErrNotSupported, got %v", err) +func TestBitbucketListFilesOnFile(t *testing.T) { + mux := http.NewServeMux() + mux.HandleFunc("GET /2.0/repositories/atlassian/stash/src/main/package.json/", func(w http.ResponseWriter, _ *http.Request) { + // Bitbucket serves the file itself, even for JSON files. + w.Header().Set("Content-Type", "text/plain") + _, _ = w.Write([]byte(`{"values": []}`)) + }) + + f := newFileTestForge(t, mux) + _, err := f.Files().List(context.Background(), "atlassian", "stash", "package.json", "main") + if err == nil || !strings.Contains(err.Error(), "package.json is not a directory") { + t.Fatalf("error = %v, want not a directory error", err) + } +} + +func TestBitbucketListFilesSlashedRefNotFound(t *testing.T) { + var paths []string + f := newFileTestForge(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + paths = append(paths, r.URL.EscapedPath()) + http.NotFound(w, r) + })) + + _, err := f.Files().List(context.Background(), "atlassian", "stash", "", "release/1.x") + if !errors.Is(err, forge.ErrNotFound) { + t.Fatalf("error = %v, want ErrNotFound", err) + } + want := []string{ + "/2.0/repositories/atlassian/stash/refs/branches/release%2F1.x", + "/2.0/repositories/atlassian/stash/refs/tags/release%2F1.x", + } + if !slices.Equal(paths, want) { + t.Errorf("requested %v, want %v", paths, want) } } diff --git a/bitbucket/replay_test.go b/bitbucket/replay_test.go index c9edbd1..c0a56f7 100644 --- a/bitbucket/replay_test.go +++ b/bitbucket/replay_test.go @@ -37,3 +37,48 @@ func TestReplayGetRepoNotFound(t *testing.T) { t.Fatalf("expected ErrNotFound, got %v", err) } } + +func TestReplayGetFile(t *testing.T) { + f := New("", httpreplay.Client(t)) + file, err := f.Files().Get(context.Background(), "atlassian", "atlassian-connect-express", ".nvmrc", "v12.2.3") + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + + assertEqual(t, "Name", ".nvmrc", file.Name) + assertEqual(t, "Path", ".nvmrc", file.Path) + assertEqual(t, "Content", "18.20.7", string(file.Content)) +} + +func TestReplayListFiles(t *testing.T) { + f := New("", httpreplay.Client(t)) + entries, err := f.Files().List(context.Background(), "atlassian", "atlassian-connect-express", "lib", "v12.2.3") + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + + types := map[string]string{} + for _, e := range entries { + types[e.Path] = e.Type + } + assertEqual(t, "lib/internal", "dir", types["lib/internal"]) + assertEqual(t, "lib/index.js", "file", types["lib/index.js"]) +} + +func TestReplayResolveCommit(t *testing.T) { + f := New("", httpreplay.Client(t)) + sha, err := f.Commits().ResolveCommit(context.Background(), "atlassian", "atlassian-connect-express", "v12.2.3") + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + assertEqual(t, "SHA", "fd61ca641c0db3ab42ad10bc1b2b7190033aee77", sha) +} + +func TestReplayResolveCommitSlashedBranch(t *testing.T) { + f := New("", httpreplay.Client(t)) + sha, err := f.Commits().ResolveCommit(context.Background(), "atlassian", "atlassian-connect-express", "inno/forge-remote-support") + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + assertEqual(t, "SHA", "cd987445da673a61046669f8d42e05b50255007d", sha) +} diff --git a/bitbucket/testdata/replay/TestReplayGetFile.json b/bitbucket/testdata/replay/TestReplayGetFile.json new file mode 100644 index 0000000..0150a04 --- /dev/null +++ b/bitbucket/testdata/replay/TestReplayGetFile.json @@ -0,0 +1,32 @@ +[ + { + "request": { + "method": "GET", + "url": "https://api.bitbucket.org/2.0/repositories/atlassian/atlassian-connect-express/src/v12.2.3/.nvmrc?format=meta" + }, + "response": { + "status_code": 200, + "header": { + "Content-Type": [ + "application/json; charset=utf-8" + ] + }, + "body": "{\"path\":\".nvmrc\",\"commit\":{\"hash\":\"fd61ca641c0db3ab42ad10bc1b2b7190033aee77\",\"links\":{\"self\":{\"href\":\"https://api.bitbucket.org/2.0/repositories/atlassian/atlassian-connect-express/commit/fd61ca641c0db3ab42ad10bc1b2b7190033aee77\"},\"html\":{\"href\":\"https://bitbucket.org/atlassian/atlassian-connect-express/commits/fd61ca641c0db3ab42ad10bc1b2b7190033aee77\"}},\"type\":\"commit\"},\"type\":\"commit_file\",\"attributes\":[],\"escaped_path\":\".nvmrc\",\"size\":7,\"mimetype\":null,\"links\":{\"self\":{\"href\":\"https://api.bitbucket.org/2.0/repositories/atlassian/atlassian-connect-express/src/fd61ca641c0db3ab42ad10bc1b2b7190033aee77/.nvmrc\"},\"meta\":{\"href\":\"https://api.bitbucket.org/2.0/repositories/atlassian/atlassian-connect-express/src/fd61ca641c0db3ab42ad10bc1b2b7190033aee77/.nvmrc?format=meta\"},\"history\":{\"href\":\"https://api.bitbucket.org/2.0/repositories/atlassian/atlassian-connect-express/filehistory/fd61ca641c0db3ab42ad10bc1b2b7190033aee77/.nvmrc\"}},\"has_malware_warning\":false}" + } + }, + { + "request": { + "method": "GET", + "url": "https://api.bitbucket.org/2.0/repositories/atlassian/atlassian-connect-express/src/fd61ca641c0db3ab42ad10bc1b2b7190033aee77/.nvmrc" + }, + "response": { + "status_code": 200, + "header": { + "Content-Type": [ + "text/plain" + ] + }, + "body": "18.20.7" + } + } +] diff --git a/bitbucket/testdata/replay/TestReplayListFiles.json b/bitbucket/testdata/replay/TestReplayListFiles.json new file mode 100644 index 0000000..bea0fec --- /dev/null +++ b/bitbucket/testdata/replay/TestReplayListFiles.json @@ -0,0 +1,17 @@ +[ + { + "request": { + "method": "GET", + "url": "https://api.bitbucket.org/2.0/repositories/atlassian/atlassian-connect-express/src/v12.2.3/lib/?pagelen=100" + }, + "response": { + "status_code": 200, + "header": { + "Content-Type": [ + "application/json; charset=utf-8" + ] + }, + "body": "{\"values\":[{\"path\":\"lib/internal\",\"commit\":{\"hash\":\"fd61ca641c0db3ab42ad10bc1b2b7190033aee77\",\"links\":{\"self\":{\"href\":\"https://api.bitbucket.org/2.0/repositories/atlassian/atlassian-connect-express/commit/fd61ca641c0db3ab42ad10bc1b2b7190033aee77\"},\"html\":{\"href\":\"https://bitbucket.org/atlassian/atlassian-connect-express/commits/fd61ca641c0db3ab42ad10bc1b2b7190033aee77\"}},\"type\":\"commit\"},\"type\":\"commit_directory\",\"links\":{\"self\":{\"href\":\"https://api.bitbucket.org/2.0/repositories/atlassian/atlassian-connect-express/src/fd61ca641c0db3ab42ad10bc1b2b7190033aee77/lib/internal/\"},\"meta\":{\"href\":\"https://api.bitbucket.org/2.0/repositories/atlassian/atlassian-connect-express/src/fd61ca641c0db3ab42ad10bc1b2b7190033aee77/lib/internal/?format=meta\"}}},{\"path\":\"lib/middleware\",\"commit\":{\"hash\":\"fd61ca641c0db3ab42ad10bc1b2b7190033aee77\",\"links\":{\"self\":{\"href\":\"https://api.bitbucket.org/2.0/repositories/atlassian/atlassian-connect-express/commit/fd61ca641c0db3ab42ad10bc1b2b7190033aee77\"},\"html\":{\"href\":\"https://bitbucket.org/atlassian/atlassian-connect-express/commits/fd61ca641c0db3ab42ad10bc1b2b7190033aee77\"}},\"type\":\"commit\"},\"type\":\"commit_directory\",\"links\":{\"self\":{\"href\":\"https://api.bitbucket.org/2.0/repositories/atlassian/atlassian-connect-express/src/fd61ca641c0db3ab42ad10bc1b2b7190033aee77/lib/middleware/\"},\"meta\":{\"href\":\"https://api.bitbucket.org/2.0/repositories/atlassian/atlassian-connect-express/src/fd61ca641c0db3ab42ad10bc1b2b7190033aee77/lib/middleware/?format=meta\"}}},{\"path\":\"lib/store\",\"commit\":{\"hash\":\"fd61ca641c0db3ab42ad10bc1b2b7190033aee77\",\"links\":{\"self\":{\"href\":\"https://api.bitbucket.org/2.0/repositories/atlassian/atlassian-connect-express/commit/fd61ca641c0db3ab42ad10bc1b2b7190033aee77\"},\"html\":{\"href\":\"https://bitbucket.org/atlassian/atlassian-connect-express/commits/fd61ca641c0db3ab42ad10bc1b2b7190033aee77\"}},\"type\":\"commit\"},\"type\":\"commit_directory\",\"links\":{\"self\":{\"href\":\"https://api.bitbucket.org/2.0/repositories/atlassian/atlassian-connect-express/src/fd61ca641c0db3ab42ad10bc1b2b7190033aee77/lib/store/\"},\"meta\":{\"href\":\"https://api.bitbucket.org/2.0/repositories/atlassian/atlassian-connect-express/src/fd61ca641c0db3ab42ad10bc1b2b7190033aee77/lib/store/?format=meta\"}}},{\"path\":\"lib/index.js\",\"commit\":{\"hash\":\"fd61ca641c0db3ab42ad10bc1b2b7190033aee77\",\"links\":{\"self\":{\"href\":\"https://api.bitbucket.org/2.0/repositories/atlassian/atlassian-connect-express/commit/fd61ca641c0db3ab42ad10bc1b2b7190033aee77\"},\"html\":{\"href\":\"https://bitbucket.org/atlassian/atlassian-connect-express/commits/fd61ca641c0db3ab42ad10bc1b2b7190033aee77\"}},\"type\":\"commit\"},\"type\":\"commit_file\",\"attributes\":[],\"escaped_path\":\"lib/index.js\",\"size\":10881,\"mimetype\":\"application/javascript\",\"links\":{\"self\":{\"href\":\"https://api.bitbucket.org/2.0/repositories/atlassian/atlassian-connect-express/src/fd61ca641c0db3ab42ad10bc1b2b7190033aee77/lib/index.js\"},\"meta\":{\"href\":\"https://api.bitbucket.org/2.0/repositories/atlassian/atlassian-connect-express/src/fd61ca641c0db3ab42ad10bc1b2b7190033aee77/lib/index.js?format=meta\"},\"history\":{\"href\":\"https://api.bitbucket.org/2.0/repositories/atlassian/atlassian-connect-express/filehistory/fd61ca641c0db3ab42ad10bc1b2b7190033aee77/lib/index.js\"}}}],\"pagelen\":100,\"page\":1}" + } + } +] diff --git a/bitbucket/testdata/replay/TestReplayResolveCommit.json b/bitbucket/testdata/replay/TestReplayResolveCommit.json new file mode 100644 index 0000000..f39b227 --- /dev/null +++ b/bitbucket/testdata/replay/TestReplayResolveCommit.json @@ -0,0 +1,17 @@ +[ + { + "request": { + "method": "GET", + "url": "https://api.bitbucket.org/2.0/repositories/atlassian/atlassian-connect-express/commit/v12.2.3" + }, + "response": { + "status_code": 200, + "header": { + "Content-Type": [ + "application/json; charset=utf-8" + ] + }, + "body": "{\"type\": \"commit\", \"hash\": \"fd61ca641c0db3ab42ad10bc1b2b7190033aee77\", \"date\": \"2026-04-30T04:37:34+00:00\", \"author\": {\"type\": \"author\", \"raw\": \"Vincent \", \"user\": {\"display_name\": \"Vincent Nguyen\", \"links\": {\"self\": {\"href\": \"https://api.bitbucket.org/2.0/users/%7B8921678d-cc20-474a-b7e3-8c6ff3b1a140%7D\"}, \"avatar\": {\"href\": \"https://avatar-management--avatars.us-west-2.prod.public.atl-paas.net/initials/VN-3.png\"}, \"html\": {\"href\": \"https://bitbucket.org/%7B8921678d-cc20-474a-b7e3-8c6ff3b1a140%7D/\"}}, \"type\": \"user\", \"uuid\": \"{8921678d-cc20-474a-b7e3-8c6ff3b1a140}\", \"account_id\": \"712020:cf50c3cb-714f-4214-be27-f5bace22a1f9\", \"nickname\": \"Vincent Nguyen\"}}, \"message\": \"12.2.3\\n\", \"summary\": {\"type\": \"rendered\", \"raw\": \"12.2.3\\n\", \"markup\": \"markdown\", \"html\": \"

12.2.3

\"}, \"links\": {\"self\": {\"href\": \"https://api.bitbucket.org/2.0/repositories/atlassian/atlassian-connect-express/commit/fd61ca641c0db3ab42ad10bc1b2b7190033aee77\"}, \"html\": {\"href\": \"https://bitbucket.org/atlassian/atlassian-connect-express/commits/fd61ca641c0db3ab42ad10bc1b2b7190033aee77\"}, \"diff\": {\"href\": \"https://api.bitbucket.org/2.0/repositories/atlassian/atlassian-connect-express/diff/fd61ca641c0db3ab42ad10bc1b2b7190033aee77\"}, \"approve\": {\"href\": \"https://api.bitbucket.org/2.0/repositories/atlassian/atlassian-connect-express/commit/fd61ca641c0db3ab42ad10bc1b2b7190033aee77/approve\"}, \"comments\": {\"href\": \"https://api.bitbucket.org/2.0/repositories/atlassian/atlassian-connect-express/commit/fd61ca641c0db3ab42ad10bc1b2b7190033aee77/comments\"}, \"statuses\": {\"href\": \"https://api.bitbucket.org/2.0/repositories/atlassian/atlassian-connect-express/commit/fd61ca641c0db3ab42ad10bc1b2b7190033aee77/statuses\"}, \"patch\": {\"href\": \"https://api.bitbucket.org/2.0/repositories/atlassian/atlassian-connect-express/patch/fd61ca641c0db3ab42ad10bc1b2b7190033aee77\"}}, \"parents\": [{\"hash\": \"eea819926de1835d07a9508c0459b00de6bb50d6\", \"links\": {\"self\": {\"href\": \"https://api.bitbucket.org/2.0/repositories/atlassian/atlassian-connect-express/commit/eea819926de1835d07a9508c0459b00de6bb50d6\"}, \"html\": {\"href\": \"https://bitbucket.org/atlassian/atlassian-connect-express/commits/eea819926de1835d07a9508c0459b00de6bb50d6\"}}, \"type\": \"commit\"}], \"rendered\": {\"message\": {\"type\": \"rendered\", \"raw\": \"12.2.3\\n\", \"markup\": \"markdown\", \"html\": \"

12.2.3

\"}}, \"repository\": {\"type\": \"repository\", \"full_name\": \"atlassian/atlassian-connect-express\", \"links\": {\"self\": {\"href\": \"https://api.bitbucket.org/2.0/repositories/atlassian/atlassian-connect-express\"}, \"html\": {\"href\": \"https://bitbucket.org/atlassian/atlassian-connect-express\"}, \"avatar\": {\"href\": \"https://bytebucket.org/ravatar/%7B47b154f6-a82d-4e03-99ce-44fb75b4827c%7D?ts=138914\"}}, \"name\": \"atlassian-connect-express\", \"uuid\": \"{47b154f6-a82d-4e03-99ce-44fb75b4827c}\"}, \"participants\": []}" + } + } +] diff --git a/bitbucket/testdata/replay/TestReplayResolveCommitSlashedBranch.json b/bitbucket/testdata/replay/TestReplayResolveCommitSlashedBranch.json new file mode 100644 index 0000000..494b813 --- /dev/null +++ b/bitbucket/testdata/replay/TestReplayResolveCommitSlashedBranch.json @@ -0,0 +1,17 @@ +[ + { + "request": { + "method": "GET", + "url": "https://api.bitbucket.org/2.0/repositories/atlassian/atlassian-connect-express/refs/branches/inno%2Fforge-remote-support" + }, + "response": { + "status_code": 200, + "header": { + "Content-Type": [ + "application/json; charset=utf-8" + ] + }, + "body": "{\"name\": \"inno/forge-remote-support\", \"target\": {\"type\": \"commit\", \"hash\": \"cd987445da673a61046669f8d42e05b50255007d\", \"date\": \"2023-05-02T03:00:43+00:00\", \"author\": {\"type\": \"author\", \"raw\": \"James Dahms \", \"user\": {\"display_name\": \"James Dahms\", \"links\": {\"self\": {\"href\": \"https://api.bitbucket.org/2.0/users/%7B9cda637f-9edd-460a-abd8-2da493a330ac%7D\"}, \"avatar\": {\"href\": \"https://avatar-management--avatars.us-west-2.prod.public.atl-paas.net/initials/JD-2.png\"}, \"html\": {\"href\": \"https://bitbucket.org/%7B9cda637f-9edd-460a-abd8-2da493a330ac%7D/\"}}, \"type\": \"user\", \"uuid\": \"{9cda637f-9edd-460a-abd8-2da493a330ac}\", \"account_id\": \"63be705d0a1b5442166a943c\", \"nickname\": \"James Dahms\"}}, \"message\": \"Merged in release/8.0.0 (pull request #382)\\n\\nRelease/8.0.0\\n\\nApproved-by: Anthony Nguyen\\nApproved-by: Min Su\", \"links\": {\"self\": {\"href\": \"https://api.bitbucket.org/2.0/repositories/atlassian/atlassian-connect-express/commit/cd987445da673a61046669f8d42e05b50255007d\"}, \"html\": {\"href\": \"https://bitbucket.org/atlassian/atlassian-connect-express/commits/cd987445da673a61046669f8d42e05b50255007d\"}, \"diff\": {\"href\": \"https://api.bitbucket.org/2.0/repositories/atlassian/atlassian-connect-express/diff/cd987445da673a61046669f8d42e05b50255007d\"}, \"approve\": {\"href\": \"https://api.bitbucket.org/2.0/repositories/atlassian/atlassian-connect-express/commit/cd987445da673a61046669f8d42e05b50255007d/approve\"}, \"comments\": {\"href\": \"https://api.bitbucket.org/2.0/repositories/atlassian/atlassian-connect-express/commit/cd987445da673a61046669f8d42e05b50255007d/comments\"}, \"statuses\": {\"href\": \"https://api.bitbucket.org/2.0/repositories/atlassian/atlassian-connect-express/commit/cd987445da673a61046669f8d42e05b50255007d/statuses\"}}, \"parents\": [{\"hash\": \"a70e9d821d8d5a2fdc85ce1c1e888204276ac73f\", \"links\": {\"self\": {\"href\": \"https://api.bitbucket.org/2.0/repositories/atlassian/atlassian-connect-express/commit/a70e9d821d8d5a2fdc85ce1c1e888204276ac73f\"}, \"html\": {\"href\": \"https://bitbucket.org/atlassian/atlassian-connect-express/commits/a70e9d821d8d5a2fdc85ce1c1e888204276ac73f\"}}, \"type\": \"commit\"}, {\"hash\": \"df02206ca6057e4475fe4a47189eb024bae168b3\", \"links\": {\"self\": {\"href\": \"https://api.bitbucket.org/2.0/repositories/atlassian/atlassian-connect-express/commit/df02206ca6057e4475fe4a47189eb024bae168b3\"}, \"html\": {\"href\": \"https://bitbucket.org/atlassian/atlassian-connect-express/commits/df02206ca6057e4475fe4a47189eb024bae168b3\"}}, \"type\": \"commit\"}], \"repository\": {\"type\": \"repository\", \"full_name\": \"atlassian/atlassian-connect-express\", \"links\": {\"self\": {\"href\": \"https://api.bitbucket.org/2.0/repositories/atlassian/atlassian-connect-express\"}, \"html\": {\"href\": \"https://bitbucket.org/atlassian/atlassian-connect-express\"}, \"avatar\": {\"href\": \"https://bytebucket.org/ravatar/%7B47b154f6-a82d-4e03-99ce-44fb75b4827c%7D?ts=138914\"}}, \"name\": \"atlassian-connect-express\", \"uuid\": \"{47b154f6-a82d-4e03-99ce-44fb75b4827c}\"}}, \"links\": {\"self\": {\"href\": \"https://api.bitbucket.org/2.0/repositories/atlassian/atlassian-connect-express/refs/branches/inno/forge-remote-support\"}, \"commits\": {\"href\": \"https://api.bitbucket.org/2.0/repositories/atlassian/atlassian-connect-express/commits/inno/forge-remote-support\"}, \"html\": {\"href\": \"https://bitbucket.org/atlassian/atlassian-connect-express/branch/inno/forge-remote-support\"}, \"pullrequest_create\": {\"href\": \"https://bitbucket.org/atlassian/atlassian-connect-express/pull-requests/new?source=inno/forge-remote-support&t=1\"}}, \"type\": \"branch\", \"merge_strategies\": [\"merge_commit\", \"squash\", \"fast_forward\", \"squash_fast_forward\", \"rebase_fast_forward\", \"rebase_merge\"], \"sync_strategies\": [\"merge_commit\", \"rebase\"], \"default_merge_strategy\": \"merge_commit\"}" + } + } +] From 8c41daa4f4405d13ce7e21a37f2ed6dbf46babe2 Mon Sep 17 00:00:00 2001 From: NopeCharon <115794254+NopeCharon@users.noreply.github.com> Date: Fri, 20 Nov 2026 14:41:17 +0530 Subject: [PATCH 2/3] Only follow Bitbucket listing pagination links on the API origin A file whose content is JSON is served with an application/json content type, so List could decode it as a listing and follow its next link with the bearer token attached. Refuse next links to any other scheme or host. --- bitbucket/files.go | 18 ++++++++++++++++++ bitbucket/files_test.go | 14 ++++++++++++++ 2 files changed, 32 insertions(+) diff --git a/bitbucket/files.go b/bitbucket/files.go index 7b5a585..4a83940 100644 --- a/bitbucket/files.go +++ b/bitbucket/files.go @@ -161,10 +161,28 @@ func (s *bitbucketFileService) List(ctx context.Context, owner, repo, filePath, }) } u = page.Next + if u != "" && !sameOrigin(u, bitbucketAPI) { + return nil, fmt.Errorf("refusing to follow pagination link to %s", u) + } } return entries, nil } +// sameOrigin reports whether u has the same scheme and host as base. Listing +// pages come from file content when dir turns out to be a file, so a next link +// is only followed if it stays on the API, where the bearer token is sent. +func sameOrigin(u, base string) bool { + a, err := url.Parse(u) + if err != nil { + return false + } + b, err := url.Parse(base) + if err != nil { + return false + } + return a.Scheme == b.Scheme && a.Host == b.Host +} + // listPage fetches one page of the listing of dir. The /src endpoint serves a // file's raw content rather than an error when dir names a file, which shows // up as a response that isn't JSON. diff --git a/bitbucket/files_test.go b/bitbucket/files_test.go index 76387d5..1a4b535 100644 --- a/bitbucket/files_test.go +++ b/bitbucket/files_test.go @@ -282,3 +282,17 @@ func TestBitbucketListFilesSlashedRefNotFound(t *testing.T) { t.Errorf("requested %v, want %v", paths, want) } } + +func TestBitbucketListFilesRejectsForeignNextLink(t *testing.T) { + mux := http.NewServeMux() + mux.HandleFunc("GET /2.0/repositories/atlassian/stash/src/main/", func(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"values": [], "next": "https://collector.example/capture"}`)) + }) + + f := newFileTestForge(t, mux) + _, err := f.Files().List(context.Background(), "atlassian", "stash", "", "main") + if err == nil || !strings.Contains(err.Error(), "pagination link") { + t.Errorf("error = %v, want a refused pagination link", err) + } +} From bd9312b310d873a6018256b366f464153e2005f6 Mon Sep 17 00:00:00 2001 From: NopeCharon <115794254+NopeCharon@users.noreply.github.com> Date: Sun, 22 Nov 2026 00:48:29 +0530 Subject: [PATCH 3/3] bitbucket: reject . and .. as file refs, trim comments, share test helper Signed-off-by: NopeCharon <115794254+NopeCharon@users.noreply.github.com> --- bitbucket/commits.go | 12 ++++-------- bitbucket/files.go | 18 +++++++++--------- bitbucket/files_test.go | 41 +++++++++++++++++++---------------------- 3 files changed, 32 insertions(+), 39 deletions(-) diff --git a/bitbucket/commits.go b/bitbucket/commits.go index 239b1af..6a650b9 100644 --- a/bitbucket/commits.go +++ b/bitbucket/commits.go @@ -26,10 +26,7 @@ type bbRef struct { } `json:"target"` } -// ResolveCommit returns the full commit SHA for ref in owner/repo. The -// single-commit endpoint resolves branches, tags and abbreviated SHAs, but it -// takes the ref as a path segment and can't route one that contains a slash, -// such as "feature/login". Those are looked up as a branch and then as a tag. +// ResolveCommit returns the full commit SHA for ref in owner/repo. func (s *bitbucketCommitService) ResolveCommit(ctx context.Context, owner, repo, ref string) (string, error) { if err := forge.ValidateCommitRef(owner, repo, ref); err != nil { return "", err @@ -60,10 +57,9 @@ func (s *bitbucketCommitService) ResolveCommit(ctx context.Context, owner, repo, } // resolveSlashedRef returns the commit hash of the branch or tag named ref. -// Bitbucket only accepts a ref containing a slash on its refs endpoints, where -// it is escaped into one path segment. Branches are tried first because that -// is where slashed names are common. It returns forge.ErrNotFound when -// neither exists. +// Bitbucket only routes a ref containing a slash on its refs endpoints, where +// it is escaped into one segment. Branches are tried first, then tags, and +// forge.ErrNotFound is returned if neither exists. func resolveSlashedRef(ctx context.Context, rs *bitbucketRepoService, owner, repo, ref string) (string, error) { for _, kind := range []string{"branches", "tags"} { u := fmt.Sprintf("%s/repositories/%s/%s/refs/%s/%s", bitbucketAPI, owner, repo, kind, url.PathEscape(ref)) diff --git a/bitbucket/files.go b/bitbucket/files.go index 4a83940..d6d7f40 100644 --- a/bitbucket/files.go +++ b/bitbucket/files.go @@ -70,13 +70,15 @@ func srcURL(owner, repo, rev string, segments []string) string { } // srcRevision returns the revision to put in a /src URL for ref. An empty ref -// means the main branch, which Bitbucket serves as HEAD. The /src endpoint -// takes the revision as a single path segment, so a branch or tag containing -// a slash is resolved to its commit first. +// means the main branch, which Bitbucket serves as HEAD. func (s *bitbucketFileService) srcRevision(ctx context.Context, owner, repo, ref string) (string, error) { switch { case ref == "": return "HEAD", nil + case ref == "." || ref == "..": + // Not valid ref names, and Bitbucket would resolve them as path + // segments and read other API resources. + return "", fmt.Errorf("invalid ref %q", ref) case strings.Contains(ref, "/"): return resolveSlashedRef(ctx, s.repoService(), owner, repo, ref) default: @@ -168,9 +170,8 @@ func (s *bitbucketFileService) List(ctx context.Context, owner, repo, filePath, return entries, nil } -// sameOrigin reports whether u has the same scheme and host as base. Listing -// pages come from file content when dir turns out to be a file, so a next link -// is only followed if it stays on the API, where the bearer token is sent. +// sameOrigin reports whether u has the same scheme and host as base. Next links +// are fetched with the bearer token, so they must stay on the API origin. func sameOrigin(u, base string) bool { a, err := url.Parse(u) if err != nil { @@ -183,9 +184,8 @@ func sameOrigin(u, base string) bool { return a.Scheme == b.Scheme && a.Host == b.Host } -// listPage fetches one page of the listing of dir. The /src endpoint serves a -// file's raw content rather than an error when dir names a file, which shows -// up as a response that isn't JSON. +// listPage fetches one page of the listing of dir. When dir names a file, /src +// serves its content instead of an error, so a non-JSON response means a file. func listPage(ctx context.Context, rs *bitbucketRepoService, u, dir string) (*bbSrcResponse, error) { resp, err := rs.send(ctx, http.MethodGet, u, nil) if err != nil { diff --git a/bitbucket/files_test.go b/bitbucket/files_test.go index 1a4b535..4d8c945 100644 --- a/bitbucket/files_test.go +++ b/bitbucket/files_test.go @@ -15,17 +15,6 @@ import ( const fileTestCommit = "5b6c39df3196eeeb8a36684beb9a3df854a0b5f3" -// newFileTestForge points the Bitbucket API at a test server running h. -func newFileTestForge(t *testing.T, h http.Handler) forge.Forge { - 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()) -} - func writeSrcMeta(w http.ResponseWriter, path, typ string, size int64) { _ = json.NewEncoder(w).Encode(map[string]any{ "path": path, @@ -51,7 +40,7 @@ func TestBitbucketGetFile(t *testing.T) { _, _ = w.Write([]byte("hello")) }) - f := newFileTestForge(t, mux) + f := newCommitTestForge(t, mux) file, err := f.Files().Get(context.Background(), "atlassian", "stash", "docs/README.md", "main") if err != nil { t.Fatalf("unexpected error: %v", err) @@ -71,7 +60,7 @@ func TestBitbucketGetFileDefaultsToHEAD(t *testing.T) { _, _ = w.Write([]byte("x: y")) }) - f := newFileTestForge(t, mux) + f := newCommitTestForge(t, mux) file, err := f.Files().Get(context.Background(), "atlassian", "stash", "FUNDING.yml", "") if err != nil { t.Fatalf("unexpected error: %v", err) @@ -80,7 +69,7 @@ func TestBitbucketGetFileDefaultsToHEAD(t *testing.T) { } func TestBitbucketGetFileSlashedRef(t *testing.T) { - f := newFileTestForge(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + f := newCommitTestForge(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { switch r.URL.EscapedPath() { case "/2.0/repositories/atlassian/stash/refs/branches/feature%2Flogin": _ = json.NewEncoder(w).Encode(map[string]any{ @@ -111,7 +100,7 @@ func TestBitbucketGetFileDirectory(t *testing.T) { writeSrcMeta(w, "docs", "commit_directory", 0) }) - f := newFileTestForge(t, mux) + f := newCommitTestForge(t, mux) _, err := f.Files().Get(context.Background(), "atlassian", "stash", "docs", "main") if err == nil || !strings.Contains(err.Error(), "docs is a directory") { t.Fatalf("error = %v, want directory error", err) @@ -124,7 +113,7 @@ func TestBitbucketGetFileTooLarge(t *testing.T) { writeSrcMeta(w, "big.bin", "commit_file", maxFileSize+1) }) - f := newFileTestForge(t, mux) + f := newCommitTestForge(t, mux) _, err := f.Files().Get(context.Background(), "atlassian", "stash", "big.bin", "main") if err == nil || !strings.Contains(err.Error(), "limit") { t.Fatalf("error = %v, want size limit error", err) @@ -132,7 +121,7 @@ func TestBitbucketGetFileTooLarge(t *testing.T) { } func TestBitbucketGetFileNotFound(t *testing.T) { - f := newFileTestForge(t, http.NotFoundHandler()) + f := newCommitTestForge(t, http.NotFoundHandler()) _, err := f.Files().Get(context.Background(), "atlassian", "stash", "missing.txt", "main") if !errors.Is(err, forge.ErrNotFound) { t.Fatalf("error = %v, want ErrNotFound", err) @@ -150,13 +139,21 @@ func TestBitbucketGetFileRequiresPath(t *testing.T) { func TestBitbucketFilePathsStayInsideSrc(t *testing.T) { var paths []string - f := newFileTestForge(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + f := newCommitTestForge(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { paths = append(paths, r.URL.EscapedPath()) http.NotFound(w, r) })) ctx := context.Background() _, _ = f.Files().Get(ctx, "atlassian", "stash", "../../../pullrequests/1", "main") + for _, ref := range []string{".", ".."} { + if _, err := f.Files().Get(ctx, "atlassian", "stash", "pullrequests/1", ref); err == nil { + t.Errorf("Get with ref %q succeeded, want an error", ref) + } + if _, err := f.Files().List(ctx, "atlassian", "stash", "docs", ref); err == nil { + t.Errorf("List with ref %q succeeded, want an error", ref) + } + } _, _ = f.Files().List(ctx, "atlassian", "stash", "docs/../../..", "main") want := []string{ @@ -237,7 +234,7 @@ func TestBitbucketListFilesSubdirectory(t *testing.T) { }) }) - f := newFileTestForge(t, mux) + f := newCommitTestForge(t, mux) entries, err := f.Files().List(context.Background(), "atlassian", "stash", "/docs/guides/", "") if err != nil { t.Fatalf("unexpected error: %v", err) @@ -256,7 +253,7 @@ func TestBitbucketListFilesOnFile(t *testing.T) { _, _ = w.Write([]byte(`{"values": []}`)) }) - f := newFileTestForge(t, mux) + f := newCommitTestForge(t, mux) _, err := f.Files().List(context.Background(), "atlassian", "stash", "package.json", "main") if err == nil || !strings.Contains(err.Error(), "package.json is not a directory") { t.Fatalf("error = %v, want not a directory error", err) @@ -265,7 +262,7 @@ func TestBitbucketListFilesOnFile(t *testing.T) { func TestBitbucketListFilesSlashedRefNotFound(t *testing.T) { var paths []string - f := newFileTestForge(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + f := newCommitTestForge(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { paths = append(paths, r.URL.EscapedPath()) http.NotFound(w, r) })) @@ -290,7 +287,7 @@ func TestBitbucketListFilesRejectsForeignNextLink(t *testing.T) { _, _ = w.Write([]byte(`{"values": [], "next": "https://collector.example/capture"}`)) }) - f := newFileTestForge(t, mux) + f := newCommitTestForge(t, mux) _, err := f.Files().List(context.Background(), "atlassian", "stash", "", "main") if err == nil || !strings.Contains(err.Error(), "pagination link") { t.Errorf("error = %v, want a refused pagination link", err)