Skip to content

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

chore: enable linter unhandled-error (#2213)

Yilong Li47d19f00d03f
diff --git a/.golangci.yaml b/.golangci.yaml
index 2ad55ec4c5..596e7112de 100644
--- a/.golangci.yaml
+++ b/.golangci.yaml
@@ -24,6 +24,8 @@ issues:
- Rollback
- logger.Sync
- pgInstance.Stop
+ - fmt.Printf
+ - fmt.Print
run:
timeout: 5m
@@ -67,8 +69,6 @@ linters-settings:
- name: early-return
disabled: true
# TODO(dragonly): Remove the rules below in the following PRs.
- - name: unhandled-error
- disabled: true
- name: if-return
disabled: true
- name: empty-block
diff --git a/bin/bb/cmd/version.go b/bin/bb/cmd/version.go
index b5700c1961..fcadd7764b 100644
--- a/bin/bb/cmd/version.go
+++ b/bin/bb/cmd/version.go
@@ -18,12 +18,11 @@ func newVersionCmd() *cobra.Command {
Use: "version",
Short: "Print the version of bb",
Run: func(cmd *cobra.Command, _ []string) {
- out := cmd.OutOrStdout()
- fmt.Fprintf(out, "bb version: %s\n", version)
- fmt.Fprintf(out, "Golang version: %s\n", goversion)
- fmt.Fprintf(out, "Git commit hash: %s\n", gitcommit)
- fmt.Fprintf(out, "Built on: %s\n", buildtime)
- fmt.Fprintf(out, "Built by: %s\n", builduser)
+ fmt.Printf("bb version: %s\n", version)
+ fmt.Printf("Golang version: %s\n", goversion)
+ fmt.Printf("Git commit hash: %s\n", gitcommit)
+ fmt.Printf("Built on: %s\n", buildtime)
+ fmt.Printf("Built by: %s\n", builduser)
},
}
return versionCmd
diff --git a/bin/bb/cmd/version_test.go b/bin/bb/cmd/version_test.go
deleted file mode 100644
index e104425537..0000000000
--- a/bin/bb/cmd/version_test.go
+++ /dev/null
@@ -1,32 +0,0 @@
-package cmd
-
-import (
- "testing"
-)
-
-func TestVersion(t *testing.T) {
- tt := []testTable{
- {
- args: []string{"version"},
- expected: `bb version: development
-Golang version: unknown
-Git commit hash: unknown
-Built on: unknown
-Built by: unknown
-`,
- },
- {
- args: []string{"version", "--help"},
- expected: `Print the version of bb
-
-Usage:
- bb version [flags]
-
-Flags:
- -h, --help help for version
-`,
- },
- }
-
- tableTest(t, tt)
-}
diff --git a/common/util.go b/common/util.go
index 06e3980b54..b2bdd97385 100644
--- a/common/util.go
+++ b/common/util.go
@@ -24,7 +24,7 @@ func FindString(stringList []string, search string) int {
var letters = []rune("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
// RandomString returns a random string with length n.
-func RandomString(n int) string {
+func RandomString(n int) (string, error) {
var sb strings.Builder
sb.Grow(n)
for i := 0; i < n; i++ {
@@ -33,12 +33,13 @@ func RandomString(n int) string {
// thus has a stronger source of random numbers.
randNum, err := rand.Int(rand.Reader, big.NewInt(int64(len(letters))))
if err != nil {
- // Use 0 as default index when encounter error
- sb.WriteRune(letters[0])
+ return "", err
+ }
+ if _, err := sb.WriteRune(letters[randNum.Uint64()]); err != nil {
+ return "", err
}
- sb.WriteRune(letters[randNum.Uint64()])
}
- return sb.String()
+ return sb.String(), nil
}
// HasPrefixes returns true if the string s has any of the given prefixes.
diff --git a/plugin/db/driver.go b/plugin/db/driver.go
index a6f26a1968..7ae926f552 100644
--- a/plugin/db/driver.go
+++ b/plugin/db/driver.go
@@ -454,7 +454,7 @@ func Open(ctx context.Context, dbType Type, driverConfig DriverConfig, connectio
}
if err := driver.Ping(ctx); err != nil {
- driver.Close(ctx)
+ _ = driver.Close(ctx)
return nil, err
}
diff --git a/resources/mysql/mysql.go b/resources/mysql/mysql.go
index 6acce2b5c5..f59d48c5a9 100644
--- a/resources/mysql/mysql.go
+++ b/resources/mysql/mysql.go
@@ -126,7 +126,7 @@ user=%s
if _, err := fmt.Fprintf(defaultCfgFile, configFmt, basedir, datadir, user); err != nil {
return nil, err
}
- defaultCfgFile.Close()
+ defer defaultCfgFile.Close()
args := []string{
fmt.Sprintf("--defaults-file=%s", defaultCfgFile.Name()),
diff --git a/server/auth.go b/server/auth.go
index d8e30a0f7d..b6c68c2238 100644
--- a/server/auth.go
+++ b/server/auth.go
@@ -152,9 +152,13 @@ func (s *Server) registerAuthRoutes(g *echo.Group) {
// password. The random password is supposed to be not guessable. If user wants
// to login via password, they need to set the new password from the profile
// page.
+ password, err := common.RandomString(20)
+ if err != nil {
+ return echo.NewHTTPError(http.StatusInternalServerError, "Failed to generate random password").SetInternal(err)
+ }
signUp := &api.SignUp{
Email: userInfo.PublicEmail,
- Password: common.RandomString(20),
+ Password: password,
Name: userInfo.Name,
}
var httpError *echo.HTTPError
diff --git a/server/project.go b/server/project.go
index cc2036b640..9b3eee0771 100644
--- a/server/project.go
+++ b/server/project.go
@@ -224,7 +224,11 @@ func (s *Server) registerProjectRoutes(g *echo.Group) {
repositoryCreate.WebhookURLHost = fmt.Sprintf("%s:%d", s.profile.BackendHost, s.profile.BackendPort)
repositoryCreate.WebhookEndpointID = uuid.New().String()
- repositoryCreate.WebhookSecretToken = common.RandomString(gitlab.SecretTokenLength)
+ secretToken, err := common.RandomString(gitlab.SecretTokenLength)
+ if err != nil {
+ return echo.NewHTTPError(http.StatusInternalServerError, "Failed to generate random secret token for GitLab").SetInternal(err)
+ }
+ repositoryCreate.WebhookSecretToken = secretToken
// Create a new webhook and retrieve the created webhook ID
var webhookCreatePayload []byte
diff --git a/server/project_member.go b/server/project_member.go
index f75264fad9..9e88415eab 100644
--- a/server/project_member.go
+++ b/server/project_member.go
@@ -79,6 +79,10 @@ func (s *Server) registerProjectMemberRoutes(g *echo.Group) {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to fetch principal info").SetInternal(err)
}
if principal == nil { // try to create principal
+ password, err := common.RandomString(20)
+ if err != nil {
+ return echo.NewHTTPError(http.StatusInternalServerError, "Failed to generate random password").SetInternal(err)
+ }
signUpInfo := &api.SignUp{
Name: projectMember.Name,
Email: projectMember.Email,
@@ -86,7 +90,7 @@ func (s *Server) registerProjectMemberRoutes(g *echo.Group) {
// To prevent potential security issues, we use random string to set up her password.
// This is another safety measure since we already disallow user login via password
// if the principal uses external auth provider
- Password: common.RandomString(20),
+ Password: password,
}
createdPrincipal, httpErr := trySignUp(ctx, s, signUpInfo, c.Get(getPrincipalIDContextKey()).(int))
if httpErr != nil {
diff --git a/server/server.go b/server/server.go
index 59b9fd42e4..8ce65a7580 100644
--- a/server/server.go
+++ b/server/server.go
@@ -389,10 +389,14 @@ func getInitSetting(ctx context.Context, store *store.Store) (*config, error) {
conf := &config{}
// initial JWT token
+ value, err := common.RandomString(secretLength)
+ if err != nil {
+ return nil, fmt.Errorf("failed to generate random JWT secret, error: %w", err)
+ }
authSetting, err := store.CreateSettingIfNotExist(ctx, &api.SettingCreate{
CreatorID: api.SystemBotID,
Name: api.SettingAuthSecret,
- Value: common.RandomString(secretLength),
+ Value: value,
Description: "Random string used to sign the JWT auth token.",
})
if err != nil {
diff --git a/server/webhook.go b/server/webhook.go
index e0dfaea047..c0e1d2d06c 100644
--- a/server/webhook.go
+++ b/server/webhook.go
@@ -152,7 +152,11 @@ func (s *Server) registerWebhookRoutes(g *echo.Group) {
// Validate the request body first because there is no point in unmarshalling
// the request body if the signature doesn't match.
- if !validateGitHubWebhookSignature256(c.Request().Header.Get("X-Hub-Signature-256"), repo.WebhookSecretToken, body) {
+ validated, err := validateGitHubWebhookSignature256(c.Request().Header.Get("X-Hub-Signature-256"), repo.WebhookSecretToken, body)
+ if err != nil {
+ return echo.NewHTTPError(http.StatusInternalServerError, "Failed to validate GitHub webhook signature").SetInternal(err)
+ }
+ if !validated {
return echo.NewHTTPError(http.StatusBadRequest, "Mismatched payload signature")
}
@@ -227,16 +231,18 @@ func (s *Server) registerWebhookRoutes(g *echo.Group) {
// validateGitHubWebhookSignature256 returns true if the signature matches the
// HMAC hex digested SHA256 hash of the body using the given key.
-func validateGitHubWebhookSignature256(signature, key string, body []byte) bool {
+func validateGitHubWebhookSignature256(signature, key string, body []byte) (bool, error) {
signature = strings.TrimPrefix(signature, "sha256=")
m := hmac.New(sha256.New, []byte(key))
- m.Write(body)
+ if _, err := m.Write(body); err != nil {
+ return false, err
+ }
got := hex.EncodeToString(m.Sum(nil))
// NOTE: Use constant time string comparison helps mitigate certain timing
// attacks against regular equality operators, see
// https://docs.github.com/en/developers/webhooks-and-events/webhooks/securing-your-webhooks#validating-payloads-from-github
- return subtle.ConstantTimeCompare([]byte(signature), []byte(got)) == 1
+ return subtle.ConstantTimeCompare([]byte(signature), []byte(got)) == 1, nil
}
// We are observing the push webhook event so that we will receive the event either when:
diff --git a/server/webhook_test.go b/server/webhook_test.go
index 89081f25b1..95a4394334 100644
--- a/server/webhook_test.go
+++ b/server/webhook_test.go
@@ -291,29 +291,32 @@ func TestValidateGitHubWebhookSignature256(t *testing.T) {
const payload = `{"ref":"refs/heads/main","before":"07da1e122bdbb81da8499b6d82c6b6302581a5a7","after":"5a96148ac5ef11a53b838b8cc0d9c929420657f3","repository":{"id":470746482,"node_id":"R_kgDOHA8Fcg","name":"bytebase-test","full_name":"unknwon/bytebase-test","private":true,"owner":{"name":"unknwon","email":"[email protected]","login":"unknwon","id":2946214,"node_id":"MDQ6VXNlcjI5NDYyMTQ=","avatar_url":"https://avatars.githubusercontent.com/u/2946214?v=4","gravatar_id":"","url":"https://api.github.com/users/unknwon","html_url":"https://github.com/unknwon","followers_url":"https://api.github.com/users/unknwon/followers","following_url":"https://api.github.com/users/unknwon/following{/other_user}","gists_url":"https://api.github.com/users/unknwon/gists{/gist_id}","starred_url":"https://api.github.com/users/unknwon/starred{/owner}{/repo}","subscriptions_url":"https://api.github.com/users/unknwon/subscriptions","organizations_url":"https://api.github.com/users/unknwon/orgs","repos_url":"https://api.github.com/users/unknwon/repos","events_url":"https://api.github.com/users/unknwon/events{/privacy}","received_events_url":"https://api.github.com/users/unknwon/received_events","type":"User","site_admin":false},"html_url":"https://github.com/unknwon/bytebase-test","description":null,"fork":false,"url":"https://github.com/unknwon/bytebase-test","forks_url":"https://api.github.com/repos/unknwon/bytebase-test/forks","keys_url":"https://api.github.com/repos/unknwon/bytebase-test/keys{/key_id}","collaborators_url":"https://api.github.com/repos/unknwon/bytebase-test/collaborators{/collaborator}","teams_url":"https://api.github.com/repos/unknwon/bytebase-test/teams","hooks_url":"https://api.github.com/repos/unknwon/bytebase-test/hooks","issue_events_url":"https://api.github.com/repos/unknwon/bytebase-test/issues/events{/number}","events_url":"https://api.github.com/repos/unknwon/bytebase-test/events","assignees_url":"https://api.github.com/repos/unknwon/bytebase-test/assignees{/user}","branches_url":"https://api.github.com/repos/unknwon/bytebase-test/branches{/branch}","tags_url":"https://api.github.com/repos/unknwon/bytebase-test/tags","blobs_url":"https://api.github.com/repos/unknwon/bytebase-test/git/blobs{/sha}","git_tags_url":"https://api.github.com/repos/unknwon/bytebase-test/git/tags{/sha}","git_refs_url":"https://api.github.com/repos/unknwon/bytebase-test/git/refs{/sha}","trees_url":"https://api.github.com/repos/unknwon/bytebase-test/git/trees{/sha}","statuses_url":"https://api.github.com/repos/unknwon/bytebase-test/statuses/{sha}","languages_url":"https://api.github.com/repos/unknwon/bytebase-test/languages","stargazers_url":"https://api.github.com/repos/unknwon/bytebase-test/stargazers","contributors_url":"https://api.github.com/repos/unknwon/bytebase-test/contributors","subscribers_url":"https://api.github.com/repos/unknwon/bytebase-test/subscribers","subscription_url":"https://api.github.com/repos/unknwon/bytebase-test/subscription","commits_url":"https://api.github.com/repos/unknwon/bytebase-test/commits{/sha}","git_commits_url":"https://api.github.com/repos/unknwon/bytebase-test/git/commits{/sha}","comments_url":"https://api.github.com/repos/unknwon/bytebase-test/comments{/number}","issue_comment_url":"https://api.github.com/repos/unknwon/bytebase-test/issues/comments{/number}","contents_url":"https://api.github.com/repos/unknwon/bytebase-test/contents/{+path}","compare_url":"https://api.github.com/repos/unknwon/bytebase-test/compare/{base}...{head}","merges_url":"https://api.github.com/repos/unknwon/bytebase-test/merges","archive_url":"https://api.github.com/repos/unknwon/bytebase-test/{archive_format}{/ref}","downloads_url":"https://api.github.com/repos/unknwon/bytebase-test/downloads","issues_url":"https://api.github.com/repos/unknwon/bytebase-test/issues{/number}","pulls_url":"https://api.github.com/repos/unknwon/bytebase-test/pulls{/number}","milestones_url":"https://api.github.com/repos/unknwon/bytebase-test/milestones{/number}","notifications_url":"https://api.github.com/repos/unknwon/bytebase-test/notifications{?since,all,participating}","labels_url":"https://api.github.com/repos/unknwon/bytebase-test/labels{/name}","releases_url":"https://api.github.com/repos/unknwon/bytebase-test/releases{/id}","deployments_url":"https://api.github.com/repos/unknwon/bytebase-test/deployments","created_at":1647463607,"updated_at":"2022-03-16T20:46:47Z","pushed_at":1658671596,"git_url":"git://github.com/unknwon/bytebase-test.git","ssh_url":"[email protected]:unknwon/bytebase-test.git","clone_url":"https://github.com/unknwon/bytebase-test.git","svn_url":"https://github.com/unknwon/bytebase-test","homepage":null,"size":20,"stargazers_count":0,"watchers_count":0,"language":null,"has_issues":true,"has_projects":true,"has_downloads":true,"has_wiki":true,"has_pages":false,"forks_count":0,"mirror_url":null,"archived":false,"disabled":false,"open_issues_count":0,"license":{"key":"apache-2.0","name":"Apache License 2.0","spdx_id":"Apache-2.0","url":"https://api.github.com/licenses/apache-2.0","node_id":"MDc6TGljZW5zZTI="},"allow_forking":true,"is_template":false,"web_commit_signoff_required":false,"topics":[],"visibility":"private","forks":0,"open_issues":0,"watchers":0,"default_branch":"main","stargazers":0,"master_branch":"main"},"pusher":{"name":"unknwon","email":"[email protected]"},"sender":{"login":"unknwon","id":2946214,"node_id":"MDQ6VXNlcjI5NDYyMTQ=","avatar_url":"https://avatars.githubusercontent.com/u/2946214?v=4","gravatar_id":"","url":"https://api.github.com/users/unknwon","html_url":"https://github.com/unknwon","followers_url":"https://api.github.com/users/unknwon/followers","following_url":"https://api.github.com/users/unknwon/following{/other_user}","gists_url":"https://api.github.com/users/unknwon/gists{/gist_id}","starred_url":"https://api.github.com/users/unknwon/starred{/owner}{/repo}","subscriptions_url":"https://api.github.com/users/unknwon/subscriptions","organizations_url":"https://api.github.com/users/unknwon/orgs","repos_url":"https://api.github.com/users/unknwon/repos","events_url":"https://api.github.com/users/unknwon/events{/privacy}","received_events_url":"https://api.github.com/users/unknwon/received_events","type":"User","site_admin":false},"created":false,"deleted":false,"forced":false,"base_ref":null,"compare":"https://github.com/unknwon/bytebase-test/compare/07da1e122bdb...5a96148ac5ef","commits":[{"id":"5a96148ac5ef11a53b838b8cc0d9c929420657f3","tree_id":"8a842b23b62886d2ee12c152eda741cf39b1ceef","distinct":true,"message":"Create testdb_dev__202101131000__baseline__create_tablefoo_for_bar.sql","timestamp":"2022-07-24T22:06:36+08:00","url":"https://github.com/unknwon/bytebase-test/commit/5a96148ac5ef11a53b838b8cc0d9c929420657f3","author":{"name":"Joe Chen","email":"[email protected]","username":"unknwon"},"committer":{"name":"GitHub","email":"[email protected]","username":"web-flow"},"added":["Dev/testdb_dev__202101131000__baseline__create_tablefoo_for_bar.sql"],"removed":[],"modified":[]}],"head_commit":{"id":"5a96148ac5ef11a53b838b8cc0d9c929420657f3","tree_id":"8a842b23b62886d2ee12c152eda741cf39b1ceef","distinct":true,"message":"Create testdb_dev__202101131000__baseline__create_tablefoo_for_bar.sql","timestamp":"2022-07-24T22:06:36+08:00","url":"https://github.com/unknwon/bytebase-test/commit/5a96148ac5ef11a53b838b8cc0d9c929420657f3","author":{"name":"Joe Chen","email":"[email protected]","username":"unknwon"},"committer":{"name":"GitHub","email":"[email protected]","username":"web-flow"},"added":["Dev/testdb_dev__202101131000__baseline__create_tablefoo_for_bar.sql"],"removed":[],"modified":[]}}`
t.Run("wrong key", func(t *testing.T) {
- got := validateGitHubWebhookSignature256(
+ got, err := validateGitHubWebhookSignature256(
"sha256=6bf313c917fd04a3c6c85270bab6c2a6ae40b7ab37767107bf80ad5c6a0a0deb",
"abadkey",
[]byte(payload),
)
assert.False(t, got)
+ assert.NoError(t, err)
})
t.Run("wrong signature", func(t *testing.T) {
- got := validateGitHubWebhookSignature256(
+ got, err := validateGitHubWebhookSignature256(
"sha256=8335bc69262e94b20753316d844e155ae4d7826a6c89f12e98083ed0dce8d057",
"bZovosSKsJ8QKCG9",
[]byte(payload),
)
assert.False(t, got)
+ assert.NoError(t, err)
})
t.Run("success", func(t *testing.T) {
- got := validateGitHubWebhookSignature256(
+ got, err := validateGitHubWebhookSignature256(
"sha256=6bf313c917fd04a3c6c85270bab6c2a6ae40b7ab37767107bf80ad5c6a0a0deb",
"bZovosSKsJ8QKCG9",
[]byte(payload),
)
assert.True(t, got)
+ assert.NoError(t, err)
})
}
diff --git a/tests/backup_restore_test.go b/tests/backup_restore_test.go
index 2fcf6b6946..a62824b7d5 100644
--- a/tests/backup_restore_test.go
+++ b/tests/backup_restore_test.go
@@ -472,7 +472,8 @@ func setUpForPITRTest(t *testing.T, ctl *controller, port, envID int, project *a
return mysqlDB, database, func() {
stopInstance()
- mysqlDB.Close()
+ err := mysqlDB.Close()
+ a.NoError(err)
}
}
diff --git a/tests/fake/github.go b/tests/fake/github.go
index eff03c9b6c..3a671a25bc 100644
--- a/tests/fake/github.go
+++ b/tests/fake/github.go
@@ -245,7 +245,9 @@ func (gh *GitHub) SendWebhookPush(repositoryID string, payload []byte) error {
}
m := hmac.New(sha256.New, []byte(webhook.Config.Secret))
- m.Write(payload)
+ if _, err := m.Write(payload); err != nil {
+ return fmt.Errorf("failed to calculate SHA256 of the webhook secret, error: %w", err)
+ }
signature := "sha256=" + hex.EncodeToString(m.Sum(nil))
req.Header.Set("X-Hub-Signature-256", signature)
req.Header.Set("X-GitHub-Event", "push")
diff --git a/tests/mysql_prepare.go b/tests/mysql_prepare.go
index a3a8500ff1..b2f2c6fe1c 100644
--- a/tests/mysql_prepare.go
+++ b/tests/mysql_prepare.go
@@ -50,7 +50,7 @@ func insert(db *sql.DB, insertCount int, batchCount int) error {
for i := 0; i < insertCount; i += batchCount {
buf.Reset()
// We use bytes.Buffer here to concat the strings because strings are too slow.
- buf.WriteString(insertSQL)
+ _, _ = buf.WriteString(insertSQL)
for j := 0; j < batchCount; j++ {
id := i + j
if id >= insertCount {
@@ -61,7 +61,7 @@ func insert(db *sql.DB, insertCount int, batchCount int) error {
delimiter = ", "
}
// append the values after "VALUES ".
- fmt.Fprintf(&buf, "%s(%d, %d, '%s', '%s')", delimiter, id, rand.Intn(insertCount), uuid.New().String(), uuid.New().String())
+ _, _ = buf.WriteString(fmt.Sprintf("%s(%d, %d, '%s', '%s')", delimiter, id, rand.Intn(insertCount), uuid.New().String(), uuid.New().String()))
}
_, err := db.Exec(buf.String())
if err != nil {