Skip to content

Database governance built for humans and agents — controlling changes and access across every major database.

chore: VCS SQL review for GitHub (#2860)

ecmadaob1a5afb07978
diff --git a/frontend/src/types/oauth.ts b/frontend/src/types/oauth.ts
index 0d7ebd0969..7b5be725f2 100644
--- a/frontend/src/types/oauth.ts
+++ b/frontend/src/types/oauth.ts
@@ -45,15 +45,18 @@ export function openWindowForOAuth(
sessionStorage.setItem(OAuthStateSessionKey, stateQueryParameter);
if (vcsType == "GITHUB_COM") {
+ // GitHub OAuth App scopes: https://docs.github.com/en/developers/apps/building-oauth-apps/scopes-for-oauth-apps
+ // We need the workflow scope to update GitHub action files.
return window.open(
`${endpoint}?client_id=${applicationId}&redirect_uri=${encodeURIComponent(
redirectUrl()
- )}&state=${stateQueryParameter}&response_type=code&scope=api,repo`,
+ )}&state=${stateQueryParameter}&response_type=code&scope=api,repo,workflow`,
"oauth",
"location=yes,left=200,top=200,height=640,width=480,scrollbars=yes,status=yes"
);
}
// GITLAB_SELF_HOST
+ // GitLab OAuth App scopes: https://docs.gitlab.com/ee/integration/oauth_provider.html#authorized-applications
return window.open(
`${endpoint}?client_id=${applicationId}&redirect_uri=${encodeURIComponent(
redirectUrl()
diff --git a/go.mod b/go.mod
index 8bfd14ef19..e4a660d08d 100644
--- a/go.mod
+++ b/go.mod
@@ -37,7 +37,7 @@ require (
github.com/xi2/xz v0.0.0-20171230120015-48954b6210f8
github.com/xo/dburl v0.12.4
go.uber.org/zap v1.23.0
- golang.org/x/crypto v0.0.0-20220926161630-eccd6366d1be
+ golang.org/x/crypto v0.0.0-20221005025214-4161e89ecf1b
golang.org/x/sys v0.0.0-20220928140112-f11e5e49a4ec
golang.org/x/text v0.3.7
gopkg.in/yaml.v3 v3.0.1
diff --git a/go.sum b/go.sum
index f0e75154a0..e4b6a0b35d 100644
--- a/go.sum
+++ b/go.sum
@@ -796,8 +796,8 @@ golang.org/x/crypto v0.0.0-20210817164053-32db794688a5/go.mod h1:GvvjBRRGRdwPK5y
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
golang.org/x/crypto v0.0.0-20220411220226-7b82a4e95df4/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4=
golang.org/x/crypto v0.0.0-20220722155217-630584e8d5aa/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4=
-golang.org/x/crypto v0.0.0-20220926161630-eccd6366d1be h1:fmw3UbQh+nxngCAHrDCCztao/kbYFnWjoqop8dHx05A=
-golang.org/x/crypto v0.0.0-20220926161630-eccd6366d1be/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4=
+golang.org/x/crypto v0.0.0-20221005025214-4161e89ecf1b h1:huxqepDufQpLLIRXiVkTvnxrzJlpwmIWAObmcCcUFr0=
+golang.org/x/crypto v0.0.0-20221005025214-4161e89ecf1b/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4=
golang.org/x/exp v0.0.0-20180321215751-8460e604b9de/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
golang.org/x/exp v0.0.0-20180807140117-3d87b88a115f/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
golang.org/x/exp v0.0.0-20181106170214-d68db9428509/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
diff --git a/plugin/vcs/github/github.go b/plugin/vcs/github/github.go
index 244f0e66fe..d842fe5ba2 100644
--- a/plugin/vcs/github/github.go
+++ b/plugin/vcs/github/github.go
@@ -4,6 +4,7 @@ package github
import (
"bytes"
"context"
+ "crypto/rand"
"encoding/base64"
"encoding/json"
"fmt"
@@ -14,6 +15,9 @@ import (
"strings"
"time"
+ "golang.org/x/crypto/blake2b"
+ "golang.org/x/crypto/nacl/box"
+
"github.com/pkg/errors"
"github.com/bytebase/bytebase/common"
@@ -658,7 +662,7 @@ func (p *Provider) CreateFile(ctx context.Context, oauthCtx common.OauthContext,
}
url := fmt.Sprintf("%s/repos/%s/contents/%s", p.APIURL(instanceURL), repositoryID, url.QueryEscape(filePath))
- code, _, _, err := oauth.Put(
+ code, _, resp, err := oauth.Put(
ctx,
p.client,
url,
@@ -684,7 +688,7 @@ func (p *Provider) CreateFile(ctx context.Context, oauthCtx common.OauthContext,
return errors.Errorf("failed to create/update file through URL %s, status code: %d, body: %s",
url,
code,
- body,
+ resp,
)
}
return nil
@@ -779,33 +783,318 @@ func (p *Provider) readFile(ctx context.Context, oauthCtx common.OauthContext, i
return &file, nil
}
+type githubBranchCreate struct {
+ Ref string `json:"ref"`
+ SHA string `json:"sha"`
+}
+
+type githubBranch struct {
+ Ref string `json:"ref"`
+ Object referenceObject `json:"object"`
+}
+
+type referenceObject struct {
+ SHA string `json:"sha"`
+}
+
// GetBranch gets the given branch in the repository.
//
-// Docs: https://docs.github.com/en/rest/git/refs#create-a-reference
-func (*Provider) GetBranch(_ context.Context, _ common.OauthContext, _, _, _ string) (*vcs.BranchInfo, error) {
- return nil, errors.Errorf("GetBranch for GitHub is not implemented yet")
+// Docs: https://docs.github.com/en/rest/git/refs#get-a-reference
+func (p *Provider) GetBranch(ctx context.Context, oauthCtx common.OauthContext, instanceURL, repositoryID, branchName string) (*vcs.BranchInfo, error) {
+ url := fmt.Sprintf("%s/repos/%s/git/ref/heads/%s", p.APIURL(instanceURL), repositoryID, branchName)
+ 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.Wrapf(err, "GET %s", url)
+ }
+
+ if code == http.StatusNotFound {
+ return nil, common.Errorf(common.NotFound, "failed to create branch from URL %s", url)
+ } else if code >= 300 {
+ return nil, errors.Errorf("failed to create branch from URL %s, status code: %d, body: %s",
+ url,
+ code,
+ body,
+ )
+ }
+
+ res := new(githubBranch)
+ if err := json.Unmarshal([]byte(body), res); err != nil {
+ return nil, err
+ }
+
+ name, err := vcs.Branch(res.Ref)
+ if err != nil {
+ return nil, err
+ }
+
+ return &vcs.BranchInfo{
+ Name: name,
+ LastCommitID: res.Object.SHA,
+ }, nil
}
// CreateBranch creates the branch in the repository.
//
// Docs: https://docs.github.com/en/rest/git/refs#create-a-reference
-func (*Provider) CreateBranch(_ context.Context, _ common.OauthContext, _, _ string, _ *vcs.BranchInfo) error {
- return errors.Errorf("CreateBranch for GitHub is not implemented yet")
+func (p *Provider) CreateBranch(ctx context.Context, oauthCtx common.OauthContext, instanceURL, repositoryID string, branch *vcs.BranchInfo) error {
+ body, err := json.Marshal(
+ githubBranchCreate{
+ Ref: fmt.Sprintf("refs/heads/%s", branch.Name),
+ SHA: branch.LastCommitID,
+ },
+ )
+ if err != nil {
+ return errors.Wrap(err, "marshal branch create")
+ }
+
+ url := fmt.Sprintf("%s/repos/%s/git/refs", p.APIURL(instanceURL), repositoryID)
+ code, _, resp, err := oauth.Post(
+ ctx,
+ p.client,
+ url,
+ &oauthCtx.AccessToken,
+ bytes.NewReader(body),
+ tokenRefresher(
+ instanceURL,
+ oauthContext{
+ ClientID: oauthCtx.ClientID,
+ ClientSecret: oauthCtx.ClientSecret,
+ RefreshToken: oauthCtx.RefreshToken,
+ },
+ oauthCtx.Refresher,
+ ),
+ )
+ if err != nil {
+ return errors.Wrapf(err, "GET %s", url)
+ }
+
+ if code == http.StatusNotFound {
+ return common.Errorf(common.NotFound, "failed to create branch from URL %s", url)
+ } else if code >= 300 {
+ return errors.Errorf("failed to create branch from URL %s, status code: %d, body: %s",
+ url,
+ code,
+ resp,
+ )
+ }
+
+ return nil
}
// CreatePullRequest creates the pull request in the repository.
//
// Docs: https://docs.github.com/en/rest/pulls/pulls#create-a-pull-request
-func (*Provider) CreatePullRequest(_ context.Context, _ common.OauthContext, _, _ string, _ *vcs.PullRequestCreate) error {
- return errors.Errorf("CreatePullRequest for GitHub is not implemented yet")
+func (p *Provider) CreatePullRequest(ctx context.Context, oauthCtx common.OauthContext, instanceURL, repositoryID string, pullRequestCreate *vcs.PullRequestCreate) error {
+ body, err := json.Marshal(pullRequestCreate)
+ if err != nil {
+ return errors.Wrap(err, "marshal pull request create")
+ }
+
+ url := fmt.Sprintf("%s/repos/%s/pulls", p.APIURL(instanceURL), repositoryID)
+ code, _, resp, err := oauth.Post(
+ ctx,
+ p.client,
+ url,
+ &oauthCtx.AccessToken,
+ bytes.NewReader(body),
+ tokenRefresher(
+ instanceURL,
+ oauthContext{
+ ClientID: oauthCtx.ClientID,
+ ClientSecret: oauthCtx.ClientSecret,
+ RefreshToken: oauthCtx.RefreshToken,
+ },
+ oauthCtx.Refresher,
+ ),
+ )
+ if err != nil {
+ return errors.Wrapf(err, "GET %s", url)
+ }
+
+ if code == http.StatusNotFound {
+ return common.Errorf(common.NotFound, "failed to create pull request from URL %s", url)
+ } else if code >= 300 {
+ return errors.Errorf("failed to create pull request from URL %s, status code: %d, body: %s",
+ url,
+ code,
+ resp,
+ )
+ }
+
+ return nil
+}
+
+type environmentVariable struct {
+ EncryptedValue string `json:"encrypted_value"`
+ KeyID string `json:"key_id"`
}
// UpsertEnvironmentVariable creates or updates the environment variable in the repository.
//
+// https://docs.github.com/en/rest/actions/secrets#create-or-update-a-repository-secret
+func (p *Provider) UpsertEnvironmentVariable(ctx context.Context, oauthCtx common.OauthContext, instanceURL, repositoryID, key, value string) error {
+ // We have to encrypt the secret value using the public key in the repository.
+ // Docs: https://docs.github.com/en/rest/actions/secrets#example-encrypting-a-secret-using-nodejs
+ publicKey, err := p.getRepositoryPublicKey(ctx, oauthCtx, instanceURL, repositoryID)
+ if err != nil {
+ return errors.Wrapf(err, "Failed to get public key")
+ }
+ encryptValue, err := encryptEnvironmentVariable(publicKey.Key, value)
+ if err != nil {
+ return errors.Wrapf(err, "Failed to encrypt environment variable")
+ }
+
+ body, err := json.Marshal(
+ environmentVariable{
+ KeyID: publicKey.KeyID,
+ EncryptedValue: encryptValue,
+ },
+ )
+ if err != nil {
+ return errors.Wrap(err, "marshal environment variable")
+ }
+
+ url := fmt.Sprintf("%s/repos/%s/actions/secrets/%s", p.APIURL(instanceURL), repositoryID, key)
+ code, _, resp, err := oauth.Put(
+ ctx,
+ p.client,
+ url,
+ &oauthCtx.AccessToken,
+ bytes.NewReader(body),
+ tokenRefresher(
+ instanceURL,
+ oauthContext{
+ ClientID: oauthCtx.ClientID,
+ ClientSecret: oauthCtx.ClientSecret,
+ RefreshToken: oauthCtx.RefreshToken,
+ },
+ oauthCtx.Refresher,
+ ),
+ )
+ if err != nil {
+ return errors.Wrapf(err, "PUT %s", url)
+ }
+
+ if code == http.StatusNotFound {
+ return common.Errorf(common.NotFound, "failed to upsert environment variable from URL %s", url)
+ } else if code >= 300 {
+ return errors.Errorf("failed to upsert environment variable from URL %s, status code: %d, body: %s",
+ url,
+ code,
+ resp,
+ )
+ }
+
+ return nil
+}
+
+// encryptEnvironmentVariable encrypt the value with public key
+//
+// https://github.com/jefflinse/githubsecret
+func encryptEnvironmentVariable(publicKey, value string) (string, error) {
+ const keySize = 32
+ const nonceSize = 24
+
+ // decode the provided public key from base64
+ recipientKey := new([keySize]byte)
+ b, err := base64.StdEncoding.DecodeString(publicKey)
+ if err != nil {
+ return "", err
+ } else if size := len(b); size != keySize {
+ return "", errors.Errorf("Public key has invalid length, expect %d bytes but found %d", keySize, size)
+ }
+
+ copy(recipientKey[:], b)
+
+ // create an ephemeral key pair
+ pubKey, privKey, err := box.GenerateKey(rand.Reader)
+ if err != nil {
+ return "", err
+ }
+
+ // create the nonce by hashing together the two public keys
+ nonce := new([nonceSize]byte)
+ nonceHash, err := blake2b.New(nonceSize, nil)
+ if err != nil {
+ return "", err
+ }
+
+ if _, err := nonceHash.Write(pubKey[:]); err != nil {
+ return "", err
+ }
+
+ if _, err := nonceHash.Write(recipientKey[:]); err != nil {
+ return "", err
+ }
+
+ copy(nonce[:], nonceHash.Sum(nil))
+
+ // begin the output with the ephemeral public key and append the encrypted content
+ out := box.Seal(pubKey[:], []byte(value), nonce, recipientKey, privKey)
+
+ // base64-encode the final output
+ return base64.StdEncoding.EncodeToString(out), nil
+}
+
+type repositoryPublicKey struct {
+ KeyID string `json:"key_id"`
+ Key string `json:"key"`
+}
+
+// getRepositoryPublicKey returns the public key in the GitHub repository.
+//
// https://docs.github.com/en/rest/actions/secrets#get-a-repository-public-key
-// https://docs.github.com/en/rest/actions/secrets#get-a-repository-secret
-func (*Provider) UpsertEnvironmentVariable(_ context.Context, _ common.OauthContext, _, _, _, _ string) error {
- return errors.Errorf("UpsertEnvironmentVariable for GitHub is not implemented yet")
+func (p *Provider) getRepositoryPublicKey(ctx context.Context, oauthCtx common.OauthContext, instanceURL, repositoryID string) (*repositoryPublicKey, error) {
+ url := fmt.Sprintf("%s/repos/%s/actions/secrets/public-key", p.APIURL(instanceURL), repositoryID)
+ 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.Wrapf(err, "GET %s", url)
+ }
+
+ if code == http.StatusNotFound {
+ return nil, common.Errorf(common.NotFound, "failed to get repo public key from URL %s", url)
+ } else if code >= 300 {
+ return nil, errors.Errorf("failed to get repo public key from URL %s, status code: %d, body: %s",
+ url,
+ code,
+ body,
+ )
+ }
+
+ res := new(repositoryPublicKey)
+ if err := json.Unmarshal([]byte(body), res); err != nil {
+ return nil, err
+ }
+
+ return res, nil
}
// CreateWebhook creates a webhook in the repository with given payload.
diff --git a/plugin/vcs/github/sql-review.yml b/plugin/vcs/github/sql-review.yml
new file mode 100644
index 0000000000..0077687eba
--- /dev/null
+++ b/plugin/vcs/github/sql-review.yml
@@ -0,0 +1,22 @@
+on: [pull_request]
+jobs:
+ sql-review:
+ runs-on: ubuntu-latest
+ name: SQL Review
+ steps:
+ - name: SQL advise
+ run: |
+ pull_number=$(jq --raw-output .pull_request.number "$GITHUB_EVENT_PATH")
+ API="%s/pull/$pull_number"
+ echo "Start request $API"
+
+ response=$(curl -s --show-error -X GET "$API" -H "Content-type: application/json" -H "X-SQL-Review-Token: ${{ secrets.%s }}")
+ echo $response
+ status=$(echo $response | jq -r '.status')
+ content=$(echo $response | jq -r '.content')
+
+ while read message; do
+ echo $message
+ done <<< "$(echo $content | jq -r '.[]')"
+
+ if [ "$status" == "ERROR" ]; then exit 1; fi
diff --git a/plugin/vcs/github/sql_review.go b/plugin/vcs/github/sql_review.go
new file mode 100644
index 0000000000..fe6952fa3c
--- /dev/null
+++ b/plugin/vcs/github/sql_review.go
@@ -0,0 +1,23 @@
+package github
+
+import (
+ _ "embed"
+ "fmt"
+
+ "github.com/bytebase/bytebase/plugin/vcs"
+)
+
+// sqlReviewAction is the GitHub action for SQL review in VCS workflow.
+//
+//go:embed sql-review.yml
+var sqlReviewAction string
+
+const (
+ // SQLReviewActionFilePath is the SQL review action file path.
+ SQLReviewActionFilePath = ".github/workflows/sql-review.yml"
+)
+
+// SetupSQLReviewCI will setup the SQL review CI content with SQL review endpoint.
+func SetupSQLReviewCI(endpoint string) string {
+ return fmt.Sprintf(sqlReviewAction, endpoint, vcs.SQLReviewAPISecretName)
+}
diff --git a/server/project.go b/server/project.go
index 905e5779ea..0fd917a24b 100644
--- a/server/project.go
+++ b/server/project.go
@@ -590,7 +590,6 @@ func (s *Server) registerProjectRoutes(g *echo.Group) {
})
}
-// nolint:unused
func (s *Server) setupVCSSQLReviewCI(ctx context.Context, repository *api.Repository) error {
branch, err := s.setupVCSSQLReviewBranch(ctx, repository)
if err != nil {
@@ -616,7 +615,9 @@ func (s *Server) setupVCSSQLReviewCI(ctx context.Context, repository *api.Reposi
switch repository.VCS.Type {
case vcsPlugin.GitHubCom:
- return nil
+ if err := s.setupVCSSQLReviewCIForGitHub(ctx, repository, branch); err != nil {
+ return err
+ }
case vcsPlugin.GitLabSelfHost:
if err := s.setupVCSSQLReviewCIForGitLab(ctx, repository, branch); err != nil {
return err
@@ -644,7 +645,6 @@ func (s *Server) setupVCSSQLReviewCI(ctx context.Context, repository *api.Reposi
}
// setupVCSSQLReviewBranch will create a new branch to setup SQL review CI.
-// nolint:unused
func (s *Server) setupVCSSQLReviewBranch(ctx context.Context, repository *api.Repository) (*vcsPlugin.BranchInfo, error) {
branch, err := vcsPlugin.Get(repository.VCS.Type, vcsPlugin.ProviderConfig{}).GetBranch(
ctx,
@@ -687,8 +687,60 @@ func (s *Server) setupVCSSQLReviewBranch(ctx context.Context, repository *api.Re
return branchCreate, nil
}
+// setupVCSSQLReviewCIForGitHub will create the pull request in GitHub to setup SQL review action.
+func (s *Server) setupVCSSQLReviewCIForGitHub(ctx context.Context, repository *api.Repository, branch *vcsPlugin.BranchInfo) error {
+ sqlReviewEndpoint := fmt.Sprintf("%s/hook/sql-review/%d", s.profile.ExternalURL, repository.ProjectID)
+ sqlReviewConfig := github.SetupSQLReviewCI(sqlReviewEndpoint)
+ fileLastCommitID := ""
+
+ fileMeta, err := vcsPlugin.Get(repository.VCS.Type, vcsPlugin.ProviderConfig{}).ReadFileMeta(
+ ctx,
+ common.OauthContext{
+ ClientID: repository.VCS.ApplicationID,
+ ClientSecret: repository.VCS.Secret,
+ AccessToken: repository.AccessToken,
+ RefreshToken: repository.RefreshToken,
+ Refresher: s.refreshToken(ctx, repository.WebURL),
+ },
+ repository.VCS.InstanceURL,
+ repository.ExternalID,
+ github.SQLReviewActionFilePath,
+ branch.Name,
+ )
+ if err != nil {
+ log.Debug(
+ "Failed to get file meta",
+ zap.String("file", github.SQLReviewActionFilePath),
+ zap.String("last_commit", branch.LastCommitID),
+ zap.Int("code", common.ErrorCode(err).Int()),
+ zap.Error(err),
+ )
+ } else if fileMeta != nil {
+ fileLastCommitID = fileMeta.LastCommitID
+ }
+
+ return vcsPlugin.Get(repository.VCS.Type, vcsPlugin.ProviderConfig{}).CreateFile(
+ ctx,
+ common.OauthContext{
+ ClientID: repository.VCS.ApplicationID,
+ ClientSecret: repository.VCS.Secret,
+ AccessToken: repository.AccessToken,
+ RefreshToken: repository.RefreshToken,
+ Refresher: s.refreshToken(ctx, repository.WebURL),
+ },
+ repository.VCS.InstanceURL,
+ repository.ExternalID,
+ github.SQLReviewActionFilePath,
+ vcsPlugin.FileCommitCreate{
+ Branch: branch.Name,
+ CommitMessage: sqlReviewInVCSPRTitle,
+ Content: sqlReviewConfig,
+ LastCommitID: fileLastCommitID,
+ },
+ )
+}
+
// setupVCSSQLReviewCIForGitLab will create or update SQL review related files in GitLab to setup SQL review CI.
-// nolint:unused
func (s *Server) setupVCSSQLReviewCIForGitLab(ctx context.Context, repository *api.Repository, branch *vcsPlugin.BranchInfo) error {
// create or update the .gitlab-ci.yml
if err := s.createOrUpdateVCSSQLReviewFileForGitLab(ctx, repository, branch, gitlab.CIFilePath, func(fileMeta *vcsPlugin.FileMeta) (string, error) {
@@ -735,7 +787,6 @@ func (s *Server) setupVCSSQLReviewCIForGitLab(ctx context.Context, repository *a
}
// createOrUpdateVCSSQLReviewFileForGitLab will create or update SQL review file for GitLab CI.
-// nolint:unused
func (s *Server) createOrUpdateVCSSQLReviewFileForGitLab(
ctx context.Context,
repository *api.Repository,