Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
fix(github): unable to load big files (#6444)
Joe Chen9aed1ec4a331
diff --git a/backend/plugin/vcs/github/github.go b/backend/plugin/vcs/github/github.goindex a6e5c6fbc8..290017ed55 100644--- a/backend/plugin/vcs/github/github.go+++ b/backend/plugin/vcs/github/github.go@@ -653,9 +653,47 @@ func (p *Provider) ReadFileMeta(ctx context.Context, oauthCtx common.OauthContexif err != nil {return nil, errors.Wrap(err, "get last commit ID")}- file, err := p.readFile(ctx, oauthCtx, instanceURL, repositoryID, filePath, lastCommitID)++ url := fmt.Sprintf("%s/repos/%s/contents/%s?ref=%s", p.APIURL(instanceURL), repositoryID, url.QueryEscape(filePath), lastCommitID)+ code, _, body, err := oauth.Get(+ ctx,+ p.client,+ url,+ &oauthCtx.AccessToken,+ tokenRefresher(+ instanceURL,+ oauthContext{+ ClientID: oauthCtx.ClientID,+ ClientSecret: oauthCtx.ClientSecret,+ RefreshToken: oauthCtx.RefreshToken,+ },+ oauthCtx.Refresher,+ ),+ )if err != nil {- return nil, errors.Wrap(err, "read file")+ return nil, errors.Wrapf(err, "GET %s", url)+ }++ if code == http.StatusNotFound {+ return nil, common.Errorf(common.NotFound, "failed to read file meta from URL %s", url)+ } else if code >= 300 {+ return nil,+ errors.Errorf("failed to read file meta from URL %s, status code: %d, body: %s",+ url,+ code,+ body,+ )+ }++ // This API endpoint returns a JSON array if the path is a directory, and we do+ // not want that.+ if body != "" && body[0] == '[' {+ return nil, errors.Errorf("%q is a directory not a file", filePath)+ }++ var file File+ if err = json.Unmarshal([]byte(body), &file); err != nil {+ return nil, errors.Wrap(err, "unmarshal body")}return &vcs.FileMeta{@@ -715,17 +753,8 @@ func (p *Provider) getLastCommitID(ctx context.Context, oauthCtx common.OauthCon//// Docs: https://docs.github.com/en/rest/repos/contents#get-repository-contentfunc (p *Provider) ReadFileContent(ctx context.Context, oauthCtx common.OauthContext, instanceURL, repositoryID, filePath, ref string) (string, error) {- file, err := p.readFile(ctx, oauthCtx, instanceURL, repositoryID, filePath, ref)- if err != nil {- return "", errors.Wrap(err, "read file")- }- return file.Content, nil-}--// readFile reads the given file in the repository.-func (p *Provider) readFile(ctx context.Context, oauthCtx common.OauthContext, instanceURL, repositoryID, filePath, ref string) (*File, error) {url := fmt.Sprintf("%s/repos/%s/contents/%s?ref=%s", p.APIURL(instanceURL), repositoryID, url.QueryEscape(filePath), ref)- code, _, body, err := oauth.Get(+ code, _, body, err := oauth.GetWithHeader(ctx,p.client,url,@@ -739,41 +768,25 @@ func (p *Provider) readFile(ctx context.Context, oauthCtx common.OauthContext, i},oauthCtx.Refresher,),+ map[string]string{+ "Accept": "application/vnd.github.raw",+ },)if err != nil {- return nil, errors.Wrapf(err, "GET %s", url)+ return "", errors.Wrapf(err, "GET %s", url)}if code == http.StatusNotFound {- return nil, common.Errorf(common.NotFound, "failed to read file from URL %s", url)+ return "", common.Errorf(common.NotFound, "failed to read file content from URL %s", url)} else if code >= 300 {- return nil,- errors.Errorf("failed to read file from URL %s, status code: %d, body: %s",+ return "",+ errors.Errorf("failed to read file content from URL %s, status code: %d, body: %s",url,code,body,)}-- // This API endpoint returns a JSON array if the path is a directory, and we do- // not want that.- if body != "" && body[0] == '[' {- return nil, errors.Errorf("%q is a directory not a file", filePath)- }-- var file File- if err = json.Unmarshal([]byte(body), &file); err != nil {- return nil, errors.Wrap(err, "unmarshal body")- }-- if file.Encoding == "base64" {- decodedContent, err := base64.StdEncoding.DecodeString(file.Content)- if err != nil {- return nil, errors.Wrap(err, "decode file content")- }- file.Content = string(decodedContent)- }- return &file, nil+ return body, nil}// PullRequestFile is the API message for files in GitHub pull request.diff --git a/backend/plugin/vcs/github/github_test.go b/backend/plugin/vcs/github/github_test.goindex a43324c138..4c0a3fed8d 100644--- a/backend/plugin/vcs/github/github_test.go+++ b/backend/plugin/vcs/github/github_test.go@@ -603,31 +603,23 @@ func TestProvider_ReadFileMeta(t *testing.T) {}func TestProvider_ReadFileContent(t *testing.T) {+ const want = `# Sample GitLab Project++This sample project shows how a project in GitLab looks for demonstration purposes. It contains issues, merge requests and Markdown files in many branches,+named and filled with lorem ipsum.++You can look around to get an idea how to structure your project and, when done, you can safely delete this project.++[Learn more about creating GitLab projects.](https://docs.gitlab.com/ee/gitlab-basics/create-project.html)+`+p := newMockProvider(func(r *http.Request) (*http.Response, error) {assert.Equal(t, "/repos/octocat/Hello-World/contents/README.md", r.URL.Path)+ assert.Equal(t, "application/vnd.github.raw", r.Header.Get("Accept"))return &http.Response{StatusCode: http.StatusOK,// Example response derived from https://docs.github.com/en/rest/repos/contents#get-repository-content- Body: io.NopCloser(strings.NewReader(`-{- "type": "file",- "encoding": "base64",- "size": 442,- "name": "README.md",- "path": "README.md",- "content": "IyBTYW1wbGUgR2l0TGFiIFByb2plY3QKClRoaXMgc2FtcGxlIHByb2plY3Qgc2hvd3MgaG93IGEgcHJvamVjdCBpbiBHaXRMYWIgbG9va3MgZm9yIGRlbW9uc3RyYXRpb24gcHVycG9zZXMuIEl0IGNvbnRhaW5zIGlzc3VlcywgbWVyZ2UgcmVxdWVzdHMgYW5kIE1hcmtkb3duIGZpbGVzIGluIG1hbnkgYnJhbmNoZXMsCm5hbWVkIGFuZCBmaWxsZWQgd2l0aCBsb3JlbSBpcHN1bS4KCllvdSBjYW4gbG9vayBhcm91bmQgdG8gZ2V0IGFuIGlkZWEgaG93IHRvIHN0cnVjdHVyZSB5b3VyIHByb2plY3QgYW5kLCB3aGVuIGRvbmUsIHlvdSBjYW4gc2FmZWx5IGRlbGV0ZSB0aGlzIHByb2plY3QuCgpbTGVhcm4gbW9yZSBhYm91dCBjcmVhdGluZyBHaXRMYWIgcHJvamVjdHMuXShodHRwczovL2RvY3MuZ2l0bGFiLmNvbS9lZS9naXRsYWItYmFzaWNzL2NyZWF0ZS1wcm9qZWN0Lmh0bWwpCg==",- "sha": "3d21ec53a331a6f037a91c368710b99387d012c1",- "url": "https://api.github.com/repos/octocat/Hello-World/contents/README.md",- "git_url": "https://api.github.com/repos/octocat/Hello-World/git/blobs/3d21ec53a331a6f037a91c368710b99387d012c1",- "html_url": "https://github.com/octocat/Hello-World/blob/master/README.md",- "download_url": "https://raw.githubusercontent.com/octocat/Hello-World/master/README.md",- "_links": {- "git": "https://api.github.com/repos/octocat/Hello-World/git/blobs/3d21ec53a331a6f037a91c368710b99387d012c1",- "self": "https://api.github.com/repos/octocat/Hello-World/contents/README.md",- "html": "https://github.com/octocat/Hello-World/blob/master/README.md"- }-}-`)),+ Body: io.NopCloser(strings.NewReader(want)),}, nil},)@@ -636,15 +628,6 @@ func TestProvider_ReadFileContent(t *testing.T) {got, err := p.ReadFileContent(ctx, common.OauthContext{}, githubComURL, "octocat/Hello-World", "README.md", "master")require.NoError(t, err)- want := `# Sample GitLab Project--This sample project shows how a project in GitLab looks for demonstration purposes. It contains issues, merge requests and Markdown files in many branches,-named and filled with lorem ipsum.--You can look around to get an idea how to structure your project and, when done, you can safely delete this project.--[Learn more about creating GitLab projects.](https://docs.gitlab.com/ee/gitlab-basics/create-project.html)-`assert.Equal(t, want, got)}diff --git a/backend/plugin/vcs/internal/oauth/oauth.go b/backend/plugin/vcs/internal/oauth/oauth.goindex 908d35e6b4..d08f6e9379 100644--- a/backend/plugin/vcs/internal/oauth/oauth.go+++ b/backend/plugin/vcs/internal/oauth/oauth.go@@ -73,6 +73,13 @@ func Get(ctx context.Context, client *http.Client, url string, token *string, toreturn retry(ctx, client, token, tokenRefresher, requester(ctx, client, http.MethodGet, url, token, nil))}+// GetWithHeader makes a HTTP GET request to the given URL using the token and+// additional header. It refreshes token and retries the request in the case of+// the token has expired.+func GetWithHeader(ctx context.Context, client *http.Client, url string, token *string, tokenRefresher TokenRefresher, header map[string]string) (code int, _ http.Header, respBody string, err error) {+ return retry(ctx, client, token, tokenRefresher, requesterWithHeader(ctx, client, http.MethodGet, url, token, nil, header))+}+// Put makes a HTTP PUT request to the given URL using the token. It refreshes// token and retries the request in the case of the token has expired.func Put(ctx context.Context, client *http.Client, url string, token *string, body io.Reader, tokenRefresher TokenRefresher) (code int, header http.Header, respBody string, err error) {diff --git a/backend/tests/fake/github.go b/backend/tests/fake/github.goindex 31917b3e0b..18f2176db3 100644--- a/backend/tests/fake/github.go+++ b/backend/tests/fake/github.go@@ -176,6 +176,10 @@ func (gh *GitHub) readRepositoryFile(c echo.Context) error {return c.String(http.StatusNotFound, fmt.Sprintf("file %q not found", filePath))}+ if c.Request().Header.Get("Accept") == "application/vnd.github.raw" {+ return c.String(http.StatusOK, content)+ }+buf, err := json.Marshal(github.File{Encoding: "base64",