Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
test: integration test for feishu approval (#3495)
p0ny6ff04d7219a3
diff --git a/bin/server/cmd/profile.go b/bin/server/cmd/profile.goindex 66d680689a..6b507a7234 100644--- a/bin/server/cmd/profile.go+++ b/bin/server/cmd/profile.go@@ -6,6 +6,7 @@ import ("github.com/bytebase/bytebase/api""github.com/bytebase/bytebase/common"+ "github.com/bytebase/bytebase/plugin/app/feishu""github.com/bytebase/bytebase/server")@@ -40,12 +41,13 @@ func getBaseProfile() server.Profile {BackupRegion: flags.backupRegion,BackupBucket: flags.backupBucket,BackupCredentialFile: flags.backupCredential,+ FeishuAPIURL: feishu.APIPath,}}// GetTestProfile will return a profile for testing.// We require port as an argument of GetTestProfile so that test can run in parallel in different ports.-func GetTestProfile(dataDir string, port int) server.Profile {+func GetTestProfile(dataDir string, port int, feishuAPIURL string) server.Profile {// Using flags.port + 1 as our datastore portdatastorePort := port + 1return server.Profile{@@ -57,13 +59,14 @@ func GetTestProfile(dataDir string, port int) server.Profile {DemoDataDir: fmt.Sprintf("demo/%s", common.ReleaseModeDev),BackupRunnerInterval: 10 * time.Second,BackupStorageBackend: api.BackupStorageBackendLocal,+ FeishuAPIURL: feishuAPIURL,}}// GetTestProfileWithExternalPg will return a profile for testing with external Postgres.// We require port as an argument of GetTestProfile so that test can run in parallel in different ports,// pgURL for connect to Postgres.-func GetTestProfileWithExternalPg(dataDir string, port int, pgUser string, pgURL string) server.Profile {+func GetTestProfileWithExternalPg(dataDir string, port int, pgUser string, pgURL string, feishuAPIURL string) server.Profile {return server.Profile{Mode: common.ReleaseModeDev,ExternalURL: fmt.Sprintf("http://localhost:%d", port),@@ -72,6 +75,7 @@ func GetTestProfileWithExternalPg(dataDir string, port int, pgUser string, pgURLDemoDataDir: fmt.Sprintf("demo/%s", common.ReleaseModeDev),BackupRunnerInterval: 10 * time.Second,BackupStorageBackend: api.BackupStorageBackendLocal,+ FeishuAPIURL: feishuAPIURL,PgURL: pgURL,}}diff --git a/plugin/app/feishu/feishu.go b/plugin/app/feishu/feishu.goindex c6db102d04..0b2b4668d7 100644--- a/plugin/app/feishu/feishu.go+++ b/plugin/app/feishu/feishu.go@@ -22,10 +22,15 @@ const (invalidTokenRespCode = 99991663)-const timeout = 30 * time.Second+const (+ timeout = 30 * time.Second+ // APIPath is the path of the Feishu API server.+ APIPath = "https://open.feishu.cn/open-apis"+)// Provider is the provider for IM Feishu.type Provider struct {+ APIPath string// cache token in memory.// use atomic.Value since it can be accessed concurrently.// we have initialized token so it is either an empty string or a valid but maybe expired token.@@ -36,8 +41,9 @@ type Provider struct {type tokenRefresher func(ctx context.Context, client *http.Client, oldToken *string) error// NewProvider returns a Provider.-func NewProvider() *Provider {+func NewProvider(apiPath string) *Provider {p := Provider{+ APIPath: apiPath,client: &http.Client{Timeout: timeout,},@@ -63,15 +69,15 @@ type ApprovalStatus stringconst (// ApprovalStatusPending is the approval status for pending approvals.- ApprovalStatusPending = ApprovalStatus("PENDING")+ ApprovalStatusPending ApprovalStatus = "PENDING"// ApprovalStatusApproved is the approval status for approved approvals.- ApprovalStatusApproved = ApprovalStatus("APPROVED")+ ApprovalStatusApproved ApprovalStatus = "APPROVED"// ApprovalStatusRejected is the approval status for rejected approvals.- ApprovalStatusRejected = ApprovalStatus("REJECTED")+ ApprovalStatusRejected ApprovalStatus = "REJECTED"// ApprovalStatusCanceled is the approval status for canceled approvals.- ApprovalStatusCanceled = ApprovalStatus("CANCELED")+ ApprovalStatusCanceled ApprovalStatus = "CANCELED"// ApprovalStatusDeleted is the approval status for deleted approvals.- ApprovalStatusDeleted = ApprovalStatus("DELETED")+ ApprovalStatusDeleted ApprovalStatus = "DELETED")// tenantAccessTokenResponse is the response of GetTenantAccessToken.@@ -82,18 +88,17 @@ type tenantAccessTokenResponse struct {Expire int `json:"expire"`}-// approvalDefinitionResponse is the response of CreateApprovalDefinition.-type approvalDefinitionResponse struct {+// ApprovalDefinitionResponse is the response of CreateApprovalDefinition.+type ApprovalDefinitionResponse struct {Code int `json:"code"`Data struct {ApprovalCode string `json:"approval_code"`- ApprovalID string `json:"approval_id"`} `json:"data"`Msg string `json:"msg"`}-// externalApprovalResponse is the response of CreateExternalApproval.-type externalApprovalResponse struct {+// ExternalApprovalResponse is the response of CreateExternalApproval.+type ExternalApprovalResponse struct {Code int `json:"code"`Msg string `json:"msg"`Data struct {@@ -101,8 +106,8 @@ type externalApprovalResponse struct {} `json:"data"`}-// emailsFindResponse is the response of GetIDByEmail.-type emailsFindResponse struct {+// EmailsFindResponse is the response of GetIDByEmail.+type EmailsFindResponse struct {Code int `json:"code"`Msg string `json:"msg"`Data struct {@@ -113,8 +118,8 @@ type emailsFindResponse struct {} `json:"data"`}-// getExternalApprovalResponse is the response of GetExternalApproval.-type getExternalApprovalResponse struct {+// GetExternalApprovalResponse is the response of GetExternalApproval.+type GetExternalApprovalResponse struct {Code int `json:"code"`Msg string `json:"msg"`Data struct {@@ -122,14 +127,14 @@ type getExternalApprovalResponse struct {} `json:"data"`}-// cancelExternalApprovalResponse is the response of CancelExternalApproval.-type cancelExternalApprovalResponse struct {- Code int `json:"code"`- Msg string `json:"msg"`- Data struct{} `json:"data"`+// CancelExternalApprovalResponse is the response of CancelExternalApproval.+type CancelExternalApprovalResponse struct {+ Code int `json:"code"`+ Msg string `json:"msg"`}-type createApprovalInstanceReq struct {+// CreateApprovalInstanceRequest is the request of CreateApprovalInstance.+type CreateApprovalInstanceRequest struct {ApprovalCode string `json:"approval_code"`Form string `json:"form"`NodeApproverOpenIDList []struct {@@ -139,6 +144,18 @@ type createApprovalInstanceReq struct {OpenID string `json:"open_id"`}+// CancelExternalApprovalRequest is the request of CancelExternalApproval.+type CancelExternalApprovalRequest struct {+ ApprovalCode string `json:"approval_code"`+ InstanceCode string `json:"instance_code"`+ UserID string `json:"user_id"`+}++// GetIDByEmailRequest is the request of GetIDByEmail.+type GetIDByEmailRequest struct {+ Emails []string `json:"emails"`+}+// Content is the content of the approval.type Content struct {Issue string@@ -257,17 +274,12 @@ const ("viewer_type": "NONE"}]-}`- cancelExternalApprovalReq = `{- "approval_code": "%s",- "instance_code": "%s",- "user_id": "%s"}`)func (p *Provider) tokenRefresher(tokenCtx TokenCtx) tokenRefresher {return func(ctx context.Context, client *http.Client, oldToken *string) error {- const url = "https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal"+ url := fmt.Sprintf("%s/auth/v3/tenant_access_token/internal", p.APIPath)body := strings.NewReader(fmt.Sprintf(getTenantAccessTokenReq, tokenCtx.AppID, tokenCtx.AppSecret))req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, body)if err != nil {@@ -373,7 +385,7 @@ func retry(ctx context.Context, client *http.Client, token *string, tokenRefresh// https://open.feishu.cn/document/uAjLw4CM/ukTMukTMukTM/reference/approval-v4/approval/createfunc (p *Provider) CreateApprovalDefinition(ctx context.Context, tokenCtx TokenCtx, approvalCode string) (string, error) {body := []byte(fmt.Sprintf(createApprovalDefinitionReq, approvalCode))- const url = "https://open.feishu.cn/open-apis/approval/v4/approvals"+ url := fmt.Sprintf("%s/approval/v4/approvals", p.APIPath)code, _, b, err := p.do(ctx, p.client, http.MethodPost, url, body, p.tokenRefresher(tokenCtx))if err != nil {return "", errors.Wrapf(err, "POST %s", url)@@ -383,7 +395,7 @@ func (p *Provider) CreateApprovalDefinition(ctx context.Context, tokenCtx TokenCreturn "", errors.Errorf("non-200 POST status code %d with body %q", code, b)}- var response approvalDefinitionResponse+ var response ApprovalDefinitionResponseif err := json.Unmarshal([]byte(b), &response); err != nil {return "", err}@@ -401,12 +413,12 @@ func (p *Provider) CreateApprovalDefinition(ctx context.Context, tokenCtx TokenC// example requesterID & approverID: ou_3cda9c969f737aaa05e6915dce306cb9// https://open.feishu.cn/document/uAjLw4CM/ukTMukTMukTM/reference/approval-v4/instance/createfunc (p *Provider) CreateExternalApproval(ctx context.Context, tokenCtx TokenCtx, content Content, approvalCode string, requesterID string, approverID string) (string, error) {- const url = "https://open.feishu.cn/open-apis/approval/v4/instances"+ url := fmt.Sprintf("%s/approval/v4/instances", p.APIPath)formValue, err := formatForm(content)if err != nil {return "", errors.Wrap(err, "failed to compose formValue")}- payload := createApprovalInstanceReq{+ payload := CreateApprovalInstanceRequest{ApprovalCode: approvalCode,Form: formValue,NodeApproverOpenIDList: []struct {@@ -432,7 +444,7 @@ func (p *Provider) CreateExternalApproval(ctx context.Context, tokenCtx TokenCtxreturn "", errors.Errorf("non-200 POST status code %d with body %q", code, b)}- var response externalApprovalResponse+ var response ExternalApprovalResponseif err := json.Unmarshal([]byte(b), &response); err != nil {return "", err}@@ -448,7 +460,7 @@ func (p *Provider) CreateExternalApproval(ctx context.Context, tokenCtx TokenCtx// example instanceCode: 81D31358-93AF-92D6-7425-01A5D67C4E71// https://open.feishu.cn/document/uAjLw4CM/ukTMukTMukTM/reference/approval-v4/instance/getfunc (p *Provider) GetExternalApprovalStatus(ctx context.Context, tokenCtx TokenCtx, instanceCode string) (ApprovalStatus, error) {- url := fmt.Sprintf("https://open.feishu.cn/open-apis/approval/v4/instances/%s", instanceCode)+ url := fmt.Sprintf("%s/approval/v4/instances/%s", p.APIPath, instanceCode)code, _, b, err := p.do(ctx, p.client, http.MethodGet, url, nil, p.tokenRefresher(tokenCtx))if err != nil {return "", errors.Wrapf(err, "GET %s", url)@@ -457,7 +469,7 @@ func (p *Provider) GetExternalApprovalStatus(ctx context.Context, tokenCtx Tokenreturn "", errors.Errorf("non-200 GET status code %d with body %q", code, b)}- var response getExternalApprovalResponse+ var response GetExternalApprovalResponseif err := json.Unmarshal([]byte(b), &response); err != nil {return "", errors.Wrap(err, "failed to unmarshal response to GetExternalApprovalResponse")}@@ -471,8 +483,16 @@ func (p *Provider) GetExternalApprovalStatus(ctx context.Context, tokenCtx Token// CancelExternalApproval cancels an external approval.// https://open.feishu.cn/document/uAjLw4CM/ukTMukTMukTM/reference/approval-v4/instance/cancelfunc (p *Provider) CancelExternalApproval(ctx context.Context, tokenCtx TokenCtx, approvalCode, instanceCode, userID string) error {- const url = "https://open.feishu.cn/open-apis/approval/v4/instances/cancel"- body := []byte(fmt.Sprintf(cancelExternalApprovalReq, approvalCode, instanceCode, userID))+ url := fmt.Sprintf("%s/approval/v4/instances/cancel", p.APIPath)+ req := &CancelExternalApprovalRequest{+ ApprovalCode: approvalCode,+ InstanceCode: instanceCode,+ UserID: userID,+ }+ body, err := json.Marshal(req)+ if err != nil {+ return errors.Wrapf(err, "failed to marshal body %+v", req)+ }code, _, b, err := p.do(ctx, p.client, http.MethodPost, url, body, p.tokenRefresher(tokenCtx))if err != nil {return errors.Wrapf(err, "POST %s", url)@@ -481,7 +501,7 @@ func (p *Provider) CancelExternalApproval(ctx context.Context, tokenCtx TokenCtxreturn errors.Errorf("non-200 POST status code %d with body %q", code, b)}- var response cancelExternalApprovalResponse+ var response CancelExternalApprovalResponseif err := json.Unmarshal([]byte(b), &response); err != nil {return errors.Wrap(err, "failed to unmarshal response to CancelExternalApprovalResponse")}@@ -497,11 +517,8 @@ func (p *Provider) CancelExternalApproval(ctx context.Context, tokenCtx TokenCtx// https://open.feishu.cn/document/uAjLw4CM/ukTMukTMukTM/reference/contact-v3/user/batch_get_id// TODO(p0ny): cache email-id mapping.func (p *Provider) GetIDByEmail(ctx context.Context, tokenCtx TokenCtx, emails []string) (map[string]string, error) {- const url = "https://open.feishu.cn/open-apis/contact/v3/users/batch_get_id"- body, err := json.Marshal(- struct {- Emails []string `json:"emails"`- }{Emails: emails})+ url := fmt.Sprintf("%s/contact/v3/users/batch_get_id", p.APIPath)+ body, err := json.Marshal(&GetIDByEmailRequest{Emails: emails})if err != nil {return nil, err}@@ -515,7 +532,7 @@ func (p *Provider) GetIDByEmail(ctx context.Context, tokenCtx TokenCtx, emails [return nil, errors.Errorf("non-200 POST status code %d with body %q", code, b)}- var response emailsFindResponse+ var response EmailsFindResponseif err := json.Unmarshal([]byte(b), &response); err != nil {return nil, err}diff --git a/plugin/app/feishu/feishu_test.go b/plugin/app/feishu/feishu_test.goindex 1f43e9879d..dfb18cba7a 100644--- a/plugin/app/feishu/feishu_test.go+++ b/plugin/app/feishu/feishu_test.go@@ -14,7 +14,7 @@ import (func TestProvider_CreateApprovalDefinition(t *testing.T) {a := require.New(t)- p := NewProvider()+ p := NewProvider(APIPath)p.client = &http.Client{Transport: &common.MockRoundTripper{MockRoundTrip: func(r *http.Request) (*http.Response, error) {@@ -43,7 +43,7 @@ func TestProvider_CreateApprovalDefinition(t *testing.T) {func TestProvider_CreateExternalApproval(t *testing.T) {a := require.New(t)- p := NewProvider()+ p := NewProvider(APIPath)p.client = &http.Client{Transport: &common.MockRoundTripper{MockRoundTrip: func(r *http.Request) (*http.Response, error) {@@ -71,7 +71,7 @@ func TestProvider_CreateExternalApproval(t *testing.T) {func TestProvider_GetExternalApprovalStatus(t *testing.T) {a := require.New(t)- p := NewProvider()+ p := NewProvider(APIPath)p.client = &http.Client{Transport: &common.MockRoundTripper{MockRoundTrip: func(r *http.Request) (*http.Response, error) {@@ -134,7 +134,7 @@ func TestProvider_GetExternalApprovalStatus(t *testing.T) {func TestProvider_CancelExternalApproval(t *testing.T) {a := require.New(t)- p := NewProvider()+ p := NewProvider(APIPath)p.client = &http.Client{Transport: &common.MockRoundTripper{MockRoundTrip: func(r *http.Request) (*http.Response, error) {@@ -160,7 +160,7 @@ func TestProvider_CancelExternalApproval(t *testing.T) {func TestProvider_GetIDByEmail(t *testing.T) {t.Run("user id not found", func(t *testing.T) {a := require.New(t)- p := NewProvider()+ p := NewProvider(APIPath)p.client = &http.Client{Transport: &common.MockRoundTripper{MockRoundTrip: func(r *http.Request) (*http.Response, error) {@@ -193,7 +193,7 @@ func TestProvider_GetIDByEmail(t *testing.T) {})t.Run("success", func(t *testing.T) {a := require.New(t)- p := NewProvider()+ p := NewProvider(APIPath)p.client = &http.Client{Transport: &common.MockRoundTripper{MockRoundTrip: func(r *http.Request) (*http.Response, error) {diff --git a/server/application_runner.go b/server/application_runner.goindex 2aa0e9e671..17e1cc0608 100644--- a/server/application_runner.go+++ b/server/application_runner.go@@ -19,11 +19,11 @@ import (const applicationRunnerInterval = time.Duration(60) * time.Second// NewApplicationRunner returns a ApplicationRunner.-func NewApplicationRunner(store *store.Store, activityManager *ActivityManager) *ApplicationRunner {+func NewApplicationRunner(store *store.Store, activityManager *ActivityManager, feishuProvider *feishu.Provider) *ApplicationRunner {return &ApplicationRunner{store: store,activityManager: activityManager,- p: feishu.NewProvider(),+ p: feishuProvider,}}diff --git a/server/config.go b/server/config.goindex 3d67ba5090..2382b19612 100644--- a/server/config.go+++ b/server/config.go@@ -55,6 +55,10 @@ type Profile struct {BackupBucket stringBackupCredentialFile string+ // IM integration related fields+ // FeishuAPIURL is the URL of Feishu API server.+ FeishuAPIURL string+// Version is the bytebase's versionVersion string// Git commit hash of the builddiff --git a/server/server.go b/server/server.goindex 4b83890b16..2e1d2bc51e 100644--- a/server/server.go+++ b/server/server.go@@ -32,6 +32,7 @@ import (enterpriseService "github.com/bytebase/bytebase/enterprise/service""github.com/bytebase/bytebase/metric"metricCollector "github.com/bytebase/bytebase/metric/collector"+ "github.com/bytebase/bytebase/plugin/app/feishu"s3bb "github.com/bytebase/bytebase/plugin/storage/s3""github.com/bytebase/bytebase/resources/mysqlutil""github.com/bytebase/bytebase/resources/postgres"@@ -299,7 +300,7 @@ func NewServer(ctx context.Context, prof Profile) (*Server, error) {// Backup runners.BackupRunner = NewBackupRunner(s, prof.BackupRunnerInterval)- s.ApplicationRunner = NewApplicationRunner(s.store, s.ActivityManager)+ s.ApplicationRunner = NewApplicationRunner(s.store, s.ActivityManager, feishu.NewProvider(prof.FeishuAPIURL))// Anomaly scanners.AnomalyScanner = NewAnomalyScanner(s)diff --git a/tests/external_approval_test.go b/tests/external_approval_test.gonew file mode 100644index 0000000000..722a9f13fb--- /dev/null+++ b/tests/external_approval_test.go@@ -0,0 +1,165 @@+package tests++import (+ "context"+ "encoding/json"+ "fmt"+ "testing"+ "time"++ "github.com/stretchr/testify/require"++ "github.com/bytebase/bytebase/api"+ "github.com/bytebase/bytebase/plugin/db"+ "github.com/bytebase/bytebase/tests/fake"+)++func TestExternalApprovalFeishu(t *testing.T) {+ t.Parallel()+ a := require.New(t)+ ctx := context.Background()+ ctl := &controller{}+ dataDir := t.TempDir()+ err := ctl.StartServer(ctx, &config{+ dataDir: dataDir,+ vcsProviderCreator: fake.NewGitLab,+ feishuProverdierCreator: fake.NewFeishu,+ })+ a.NoError(err)+ defer ctl.Close(ctx)+ err = ctl.Login()+ a.NoError(err)++ err = ctl.setLicense()+ a.NoError(err)++ // close existing issues+ issues, err := ctl.getIssues(api.IssueFind{})+ a.NoError(err)+ for _, issue := range issues {+ patchedIssue, err := ctl.patchIssueStatus(api.IssueStatusPatch{+ ID: issue.ID,+ Status: api.IssueCanceled,+ })+ a.NoError(err)+ a.Equal(api.IssueCanceled, patchedIssue.Status)+ }++ err = ctl.patchSetting(api.SettingPatch{+ Name: api.SettingAppIM,+ Value: `{"imType":"im.feishu","appId":"123","appSecret":"123","externalApproval":{"enabled":true}}`,+ })+ a.NoError(err)++ // Create a DBA account.+ dba, err := ctl.createPrincipal(api.PrincipalCreate{+ Type: api.EndUser,+ Name: "DBA",+ Email: "[email protected]",+ })+ a.NoError(err)++ _, err = ctl.createMember(api.MemberCreate{+ Status: api.Active,+ Role: api.DBA,+ PrincipalID: dba.ID,+ })+ a.NoError(err)++ err = ctl.feishuProvider.RegisterEmails("[email protected]", "[email protected]")+ a.NoError(err)++ // Create a project.+ project, err := ctl.createProject(api.ProjectCreate{+ Name: "Test Project",+ Key: "TestExternalApprovalFeishu",+ })+ a.NoError(err)++ // Provision an instance.+ instanceRootDir := t.TempDir()+ instanceName := "testInstance1"+ instanceDir, err := ctl.provisionSQLiteInstance(instanceRootDir, instanceName)+ a.NoError(err)++ environments, err := ctl.getEnvironments()+ a.NoError(err)+ prodEnvironment, err := findEnvironment(environments, "Prod")+ a.NoError(err)++ // Add an instance.+ instance, err := ctl.addInstance(api.InstanceCreate{+ EnvironmentID: prodEnvironment.ID,+ Name: instanceName,+ Engine: db.SQLite,+ Host: instanceDir,+ })+ a.NoError(err)++ // Expecting project to have no database.+ databases, err := ctl.getDatabases(api.DatabaseFind{+ ProjectID: &project.ID,+ })+ a.NoError(err)+ a.Zero(len(databases))+ // Expecting instance to have no database.+ databases, err = ctl.getDatabases(api.DatabaseFind{+ InstanceID: &instance.ID,+ })+ a.NoError(err)+ a.Zero(len(databases))++ // Create an issue that creates a database.+ databaseName := "testSchemaUpdate"+ err = ctl.createDatabase(project, instance, databaseName, "", nil /* labelMap */)+ a.NoError(err)++ // Expecting project to have 1 database.+ databases, err = ctl.getDatabases(api.DatabaseFind{+ ProjectID: &project.ID,+ })+ a.NoError(err)+ a.Equal(1, len(databases))+ database := databases[0]+ a.Equal(instance.ID, database.Instance.ID)++ // Create an issue that updates database schema.+ createContext, err := json.Marshal(&api.MigrationContext{+ DetailList: []*api.MigrationDetail{+ {+ MigrationType: db.Migrate,+ DatabaseID: database.ID,+ Statement: migrationStatement,+ },+ },+ })+ a.NoError(err)+ issue, err := ctl.createIssue(api.IssueCreate{+ ProjectID: project.ID,+ Name: fmt.Sprintf("update schema for database %q", databaseName),+ Type: api.IssueDatabaseSchemaUpdate,+ Description: fmt.Sprintf("This updates the schema of database %q.", databaseName),+ AssigneeID: dba.ID,+ CreateContext: string(createContext),+ })+ a.NoError(err)++ // Sleep for 5 seconds, giving time to ApplicationRunner to create external approvals.+ time.Sleep(5 * time.Second)+ issue, err = ctl.getIssue(issue.ID)+ a.NoError(err)+ taskStatus, err := getNextTaskStatus(issue)+ a.NoError(err)+ // The task is still waiting for approval.+ a.Equal(api.TaskPendingApproval, taskStatus)++ // Should have 1 PENDING approval on the feishu side.+ a.Equal(1, ctl.feishuProvider.PendingApprovalCount())+ // Simulate users approving on the feishu side.+ ctl.feishuProvider.ApprovePendingApprovals()++ // Waiting ApplicationRunner to approves the issue.+ status, err := ctl.waitIssuePipelineWithNoApproval(issue.ID)+ a.NoError(err)+ a.Equal(api.TaskDone, status)+}diff --git a/tests/fake/feishu.go b/tests/fake/feishu.gonew file mode 100644index 0000000000..a114ae61f2--- /dev/null+++ b/tests/fake/feishu.go@@ -0,0 +1,258 @@+package fake++import (+ "encoding/json"+ "fmt"+ "io"+ "net"+ "net/http"+ "sync"++ "github.com/google/uuid"+ "github.com/labstack/echo/v4"+ "github.com/labstack/echo/v4/middleware"+ "github.com/pkg/errors"++ "github.com/bytebase/bytebase/plugin/app/feishu"+)++// Feishu is a fake feishu API server implementation for testing.+type Feishu struct {+ port int+ echo *echo.Echo+ approvalDefinition map[string]bool+ approvalInstance map[string]*approval+ // email to user id mapping+ users map[string]string+ mutex sync.Mutex+}++// FeishuProviderCreator is the function to create a fake feishu provider.+type FeishuProviderCreator func(int) *Feishu++type approval struct {+ approvalCode string+ instanceCode string+ status feishu.ApprovalStatus+}++var _ FeishuProviderCreator = NewFeishu++// NewFeishu creates a new fake feishu provider.+func NewFeishu(port int) *Feishu {+ e := echo.New()++ e.Use(middleware.Logger())+ e.Use(middleware.Recover())++ f := &Feishu{+ port: port,+ echo: e,+ approvalDefinition: map[string]bool{},+ approvalInstance: map[string]*approval{},+ users: map[string]string{},+ mutex: sync.Mutex{},+ }++ // Routes+ g := e.Group("/open-apis")+ g.POST("/approval/v4/approvals", f.createApprovalDefinition)+ g.POST("/approval/v4/instances", f.createApprovalInstance)+ g.GET("/approval/v4/instances/:id", f.getApprovalInstanceStatus)+ g.POST("/approval/v4/instances/cancel", f.cancelApprovalInstance)+ g.POST("/contact/v3/users/batch_get_id", f.getIDByEmail)++ return f+}++// Run starts the fake feishu provider server.+func (f *Feishu) Run() error {+ return f.echo.Start(fmt.Sprintf(":%d", f.port))+}++// Close closes the fake feishu provider server.+func (f *Feishu) Close() error {+ return f.echo.Close()+}++// ListenerAddr returns the fake feishu provider server listener address.+func (f *Feishu) ListenerAddr() net.Addr {+ return f.echo.ListenerAddr()+}++// APIURL returns the API path.+func (*Feishu) APIURL(hostURL string) string {+ return fmt.Sprintf("%s/open-apis", hostURL)+}++// RegisterEmails creates a email-id pair.+func (f *Feishu) RegisterEmails(emails ...string) error {+ f.mutex.Lock()+ defer f.mutex.Unlock()+ for _, email := range emails {+ _, ok := f.users[email]+ if ok {+ return errors.Errorf("register email %s twice", email)+ }+ f.users[email] = uuid.NewString()+ }+ return nil+}++// PendingApprovalCount returns the number of pending approvals.+func (f *Feishu) PendingApprovalCount() int {+ f.mutex.Lock()+ defer f.mutex.Unlock()+ count := 0+ for _, approval := range f.approvalInstance {+ if approval.status == feishu.ApprovalStatusPending {+ count+++ }+ }+ return count+}++// ApprovePendingApprovals approves all pending approvals.+func (f *Feishu) ApprovePendingApprovals() {+ f.mutex.Lock()+ defer f.mutex.Unlock()+ for _, approval := range f.approvalInstance {+ if approval.status == feishu.ApprovalStatusPending {+ approval.status = feishu.ApprovalStatusApproved+ }+ }+}++func (f *Feishu) createApprovalDefinition(c echo.Context) error {+ f.mutex.Lock()+ defer f.mutex.Unlock()+ id := uuid.NewString()+ f.approvalDefinition[id] = true+ return c.JSON(http.StatusOK, &feishu.ApprovalDefinitionResponse{+ Code: 0,+ Data: struct {+ ApprovalCode string `json:"approval_code"`+ }{+ ApprovalCode: id,+ },+ Msg: "success",+ })+}++func (f *Feishu) createApprovalInstance(c echo.Context) error {+ b, err := io.ReadAll(c.Request().Body)+ if err != nil {+ return errors.Wrap(err, "failed to read create approval instance body")+ }+ create := &feishu.CreateApprovalInstanceRequest{}+ if err := json.Unmarshal(b, create); err != nil {+ return errors.Wrap(err, "failed to unmarshal create approval instance body")+ }+ f.mutex.Lock()+ defer f.mutex.Unlock()+ if !f.approvalDefinition[create.ApprovalCode] {+ return errors.Errorf("not found approval code %s", create.ApprovalCode)+ }++ id := uuid.NewString()+ f.approvalInstance[id] = &approval{+ approvalCode: create.ApprovalCode,+ instanceCode: id,+ status: feishu.ApprovalStatusPending,+ }++ return c.JSON(http.StatusOK, &feishu.ExternalApprovalResponse{+ Code: 0,+ Msg: "success",+ Data: struct {+ InstanceCode string `json:"instance_code"`+ }{+ InstanceCode: id,+ },+ })+}++func (f *Feishu) getApprovalInstanceStatus(c echo.Context) error {+ f.mutex.Lock()+ defer f.mutex.Unlock()+ id := c.Param("id")+ approval, ok := f.approvalInstance[id]+ if !ok {+ return errors.Errorf("not found approval instance %s", id)+ }+ return c.JSON(http.StatusOK, &feishu.GetExternalApprovalResponse{+ Code: 0,+ Msg: "success",+ Data: struct {+ Status feishu.ApprovalStatus `json:"status"`+ }{+ Status: approval.status,+ },+ })+}++func (f *Feishu) cancelApprovalInstance(c echo.Context) error {+ b, err := io.ReadAll(c.Request().Body)+ if err != nil {+ return errors.Wrap(err, "failed to read cancel approval instance body")+ }+ req := &feishu.CancelExternalApprovalRequest{}+ if err := json.Unmarshal(b, req); err != nil {+ return errors.Wrap(err, "failed to unmarshal cancel approval instance body")+ }++ f.mutex.Lock()+ defer f.mutex.Unlock()+ approval, ok := f.approvalInstance[req.InstanceCode]+ if !ok {+ return errors.Errorf("not found approval %s", req.InstanceCode)+ }+ if approval.status != feishu.ApprovalStatusPending {+ return errors.Errorf(`expect to cancel a "pending" approval, but get status %q`, approval.status)+ }+ approval.status = feishu.ApprovalStatusCanceled++ return c.JSON(http.StatusOK, &feishu.CancelExternalApprovalResponse{+ Code: 0,+ Msg: "success",+ })+}++func (f *Feishu) getIDByEmail(c echo.Context) error {+ b, err := io.ReadAll(c.Request().Body)+ if err != nil {+ return errors.Wrap(err, "failed to read get id by email body")+ }+ req := &feishu.GetIDByEmailRequest{}+ if err := json.Unmarshal(b, req); err != nil {+ return errors.Wrap(err, "failed to unmarshal get id by email body")+ }+ f.mutex.Lock()+ defer f.mutex.Unlock()+ resp := &feishu.EmailsFindResponse{+ Code: 0,+ Msg: "success",+ }+ for _, email := range req.Emails {+ id, ok := f.users[email]+ if !ok {+ resp.Data.UserList = append(resp.Data.UserList, struct {+ UserID string `json:"user_id"`+ Email string `json:"email"`+ }{+ UserID: "",+ Email: email,+ })+ } else {+ resp.Data.UserList = append(resp.Data.UserList, struct {+ UserID string `json:"user_id"`+ Email string `json:"email"`+ }{+ UserID: id,+ Email: email,+ })+ }+ }++ return c.JSON(http.StatusOK, resp)+}diff --git a/tests/tests.go b/tests/tests.goindex 89f38207d7..0098a69653 100644--- a/tests/tests.go+++ b/tests/tests.go@@ -134,20 +134,23 @@ CREATE TABLE book3 ()type controller struct {- server *server.Server- profile server.Profile- client *http.Client- cookie string- vcsProvider fake.VCSProvider+ server *server.Server+ profile server.Profile+ client *http.Client+ cookie string+ vcsProvider fake.VCSProvider+ feishuProvider *fake.Feishu- rootURL string- apiURL string- vcsURL string+ rootURL string+ apiURL string+ vcsURL string+ feishuURL string}type config struct {- dataDir string- vcsProviderCreator fake.VCSProviderCreator+ dataDir string+ vcsProviderCreator fake.VCSProviderCreator+ feishuProverdierCreator fake.FeishuProviderCreatorpgUser stringpgURL string@@ -179,22 +182,29 @@ func getTestPortForEmbeddedPg() int {// StartServerWithExternalPg starts the main server with external Postgres.func (ctl *controller) StartServerWithExternalPg(ctx context.Context, config *config) error {log.SetLevel(zap.DebugLevel)+ if err := ctl.startMockServers(config.vcsProviderCreator, config.feishuProverdierCreator); err != nil {+ return err+ }serverPort := getTestPort()- profile := cmd.GetTestProfileWithExternalPg(config.dataDir, serverPort, config.pgUser, config.pgURL)+ profile := cmd.GetTestProfileWithExternalPg(config.dataDir, serverPort, config.pgUser, config.pgURL, ctl.feishuProvider.APIURL(ctl.feishuURL))server, err := server.NewServer(ctx, profile)if err != nil {return err}ctl.server = server+ ctl.profile = profile- return ctl.start(ctx, config.vcsProviderCreator, serverPort)+ return ctl.start(ctx, serverPort)}// StartServer starts the main server with embed Postgres.func (ctl *controller) StartServer(ctx context.Context, config *config) error {log.SetLevel(zap.DebugLevel)+ if err := ctl.startMockServers(config.vcsProviderCreator, config.feishuProverdierCreator); err != nil {+ return err+ }serverPort := getTestPortForEmbeddedPg()- profile := cmd.GetTestProfile(config.dataDir, serverPort)+ profile := cmd.GetTestProfile(config.dataDir, serverPort, ctl.feishuProvider.APIURL(ctl.feishuURL))server, err := server.NewServer(ctx, profile)if err != nil {return err@@ -202,39 +212,67 @@ func (ctl *controller) StartServer(ctx context.Context, config *config) error {ctl.server = serverctl.profile = profile- return ctl.start(ctx, config.vcsProviderCreator, serverPort)+ return ctl.start(ctx, serverPort)}-// start only called by StartServer() and StartServerWithExternalPg().-func (ctl *controller) start(ctx context.Context, vcsProviderCreator fake.VCSProviderCreator, port int) error {- ctl.rootURL = fmt.Sprintf("http://localhost:%d", port)- ctl.apiURL = fmt.Sprintf("http://localhost:%d/api", port)-+func (ctl *controller) startMockServers(vcsProviderCreator fake.VCSProviderCreator, feishuProviderCreator fake.FeishuProviderCreator) error {// Set up VCS provider.vcsPort := getTestPort()ctl.vcsProvider = vcsProviderCreator(vcsPort)ctl.vcsURL = fmt.Sprintf("http://localhost:%d", vcsPort)+ // Set up fake feishu server.+ if feishuProviderCreator != nil {+ feishuPort := getTestPort()+ ctl.feishuProvider = feishuProviderCreator(feishuPort)+ ctl.feishuURL = fmt.Sprintf("http://localhost:%d", feishuPort)+ }+errChan := make(chan error, 1)go func() {- if err := ctl.server.Run(ctx, port); err != nil {- errChan <- errors.Wrap(err, "failed to run main server")+ if err := ctl.vcsProvider.Run(); err != nil {+ errChan <- errors.Wrap(err, "failed to run vcsProvider server")}}()+ if feishuProviderCreator != nil {+ go func() {+ if err := ctl.feishuProvider.Run(); err != nil {+ errChan <- errors.Wrap(err, "failed to run feishuProvider server")+ }+ }()+ }++ if err := waitForVCSStart(ctl.vcsProvider, errChan); err != nil {+ return errors.Wrap(err, "failed to wait for vcsProvider to start")+ }++ if feishuProviderCreator != nil {+ if err := waitForFeishuStart(ctl.feishuProvider, errChan); err != nil {+ return errors.Wrap(err, "failed to wait for feishuProvider to start")+ }+ }++ return nil+}++// start only called by StartServer() and StartServerWithExternalPg().+func (ctl *controller) start(ctx context.Context, port int) error {+ ctl.rootURL = fmt.Sprintf("http://localhost:%d", port)+ ctl.apiURL = fmt.Sprintf("http://localhost:%d/api", port)++ errChan := make(chan error, 1)+go func() {- if err := ctl.vcsProvider.Run(); err != nil {- errChan <- errors.Wrap(err, "failed to run vcsProvider server")+ if err := ctl.server.Run(ctx, port); err != nil {+ errChan <- errors.Wrap(err, "failed to run main server")}}()if err := waitForServerStart(ctl.server, errChan); err != nil {return errors.Wrap(err, "failed to wait for server to start")}- if err := waitForVCSStart(ctl.vcsProvider, errChan); err != nil {- return errors.Wrap(err, "failed to wait for vcsProvider to start")- }// initialize controller clients.ctl.client = &http.Client{}@@ -293,6 +331,26 @@ func waitForVCSStart(p fake.VCSProvider, errChan <-chan error) error {}}+func waitForFeishuStart(f *fake.Feishu, errChan <-chan error) error {+ ticker := time.NewTicker(100 * time.Millisecond)+ defer ticker.Stop()++ for {+ select {+ case <-ticker.C:+ addr := f.ListenerAddr()+ if addr != nil && strings.Contains(addr.String(), ":") {+ return nil // was started+ }+ case err := <-errChan:+ if err == http.ErrServerClosed {+ return nil+ }+ return err+ }+ }+}+func (ctl *controller) waitForHealthz() error {begin := time.Now()ticker := time.NewTicker(100 * time.Microsecond)@@ -476,6 +534,42 @@ func (ctl *controller) delete(shortURL string, body io.Reader) (io.ReadCloser, ereturn resp.Body, nil}+func (ctl *controller) createPrincipal(principalCreate api.PrincipalCreate) (*api.Principal, error) {+ buf := new(bytes.Buffer)+ if err := jsonapi.MarshalPayload(buf, &principalCreate); err != nil {+ return nil, errors.Wrap(err, "failed to marshal principal create")+ }++ body, err := ctl.post("/principal", buf)+ if err != nil {+ return nil, err+ }++ principal := new(api.Principal)+ if err = jsonapi.UnmarshalPayload(body, principal); err != nil {+ return nil, errors.Wrap(err, "fail to unmarshal post principal response")+ }+ return principal, nil+}++func (ctl *controller) createMember(memberCreate api.MemberCreate) (*api.Member, error) {+ buf := new(bytes.Buffer)+ if err := jsonapi.MarshalPayload(buf, &memberCreate); err != nil {+ return nil, errors.Wrap(err, "failed to marshal member create")+ }++ body, err := ctl.post("/member", buf)+ if err != nil {+ return nil, err+ }++ member := new(api.Member)+ if err = jsonapi.UnmarshalPayload(body, member); err != nil {+ return nil, errors.Wrap(err, "fail to unmarshal post member response")+ }+ return member, nil+}+// getProjects gets the projects.func (ctl *controller) getProjects() ([]*api.Project, error) {body, err := ctl.get("/project", nil)@@ -937,6 +1031,14 @@ func (ctl *controller) waitIssuePipelineWithStageApproval(id int) (api.TaskStatureturn ctl.waitIssuePipelineTaskImpl(id, ctl.approveIssueTasksWithStageApproval, false)}+// waitIssuePipelineWithNoApproval waits for pipeline to finish and do nothing when approvals are needed.+func (ctl *controller) waitIssuePipelineWithNoApproval(id int) (api.TaskStatus, error) {+ noop := func(*api.Issue) error {+ return nil+ }+ return ctl.waitIssuePipelineTaskImpl(id, noop, false)+}+// waitIssuePipelineImpl waits for the tasks in pipeline to finish and approves tasks when necessary.func (ctl *controller) waitIssuePipelineTaskImpl(id int, approveFunc func(issue *api.Issue) error, approveOnce bool) (api.TaskStatus, error) {// Sleep for 1 second between issues so that we don't get migration version conflict because we are using second-level timestamp for the version string. We choose sleep because it mimics the user's behavior.@@ -1572,6 +1674,24 @@ func (ctl *controller) deleteDataSource(databaseID, dataSourceID int) error {return nil}+func (ctl *controller) patchSetting(settingPatch api.SettingPatch) error {+ buf := new(bytes.Buffer)+ if err := jsonapi.MarshalPayload(buf, &settingPatch); err != nil {+ return errors.Wrap(err, "failed to marshal settingPatch")+ }++ body, err := ctl.patch(fmt.Sprintf("/setting/%s", settingPatch.Name), buf)+ if err != nil {+ return err+ }++ setting := new(api.Setting)+ if err = jsonapi.UnmarshalPayload(body, setting); err != nil {+ return errors.Wrap(err, "fail to unmarshal setting response")+ }+ return nil+}+// upsertPolicy upserts the policy.func (ctl *controller) upsertPolicy(policyUpsert api.PolicyUpsert) error {buf := new(bytes.Buffer)