From a868f763ca931bf63ec2344a571df32f438c3a65 Mon Sep 17 00:00:00 2001 From: cbcwestwolf <1004626265@qq.com> Date: Wed, 10 Aug 2022 18:26:46 +0800 Subject: [PATCH 01/17] 1st commit. Modify parser --- errno/errcode.go | 1 + errno/errname.go | 1 + parser/parser.go | 13 +++++++++---- parser/parser.y | 13 +++++++++---- 4 files changed, 20 insertions(+), 8 deletions(-) diff --git a/errno/errcode.go b/errno/errcode.go index c9b1f085ddf2a..8ec0bb8b6c98d 100644 --- a/errno/errcode.go +++ b/errno/errcode.go @@ -840,6 +840,7 @@ const ( ErrGeneratedColumnNonPrior = 3107 ErrDependentByGeneratedColumn = 3108 ErrGeneratedColumnRefAutoInc = 3109 + ErrAccountHasBeenLocked = 3118 ErrWarnConflictingHint = 3126 ErrUnresolvedHintName = 3128 ErrInvalidJSONText = 3140 diff --git a/errno/errname.go b/errno/errname.go index 9b27b44c09da7..ecc5582633d92 100644 --- a/errno/errname.go +++ b/errno/errname.go @@ -835,6 +835,7 @@ var MySQLErrName = map[uint16]*mysql.ErrMessage{ ErrGeneratedColumnNonPrior: mysql.Message("Generated column can refer only to generated columns defined prior to it.", nil), ErrDependentByGeneratedColumn: mysql.Message("Column '%s' has a generated column dependency.", nil), ErrGeneratedColumnRefAutoInc: mysql.Message("Generated column '%s' cannot refer to auto-increment column.", nil), + ErrAccountHasBeenLocked: mysql.Message("Access denied for user '%s'@'%s'. Account is locked.", nil), ErrWarnConflictingHint: mysql.Message("Hint %s is ignored as conflicting/duplicated.", nil), ErrUnresolvedHintName: mysql.Message("Unresolved name '%s' for %s hint", nil), ErrInvalidFieldSize: mysql.Message("Invalid size for column '%s'.", nil), diff --git a/parser/parser.go b/parser/parser.go index 24fac516e07e6..e9a2fd8660081 100644 --- a/parser/parser.go +++ b/parser/parser.go @@ -20737,14 +20737,11 @@ yynewstate: } case 2317: { - l := []*ast.PasswordOrLockOption{} - parser.yyVAL.item = l + parser.yyVAL.item = []*ast.PasswordOrLockOption{} } case 2318: { parser.yyVAL.item = yyS[yypt-0].item - yylex.AppendError(yylex.Errorf("TiDB does not support PASSWORD EXPIRE and ACCOUNT LOCK now, they would be parsed but ignored.")) - parser.lastErrorAsWarn() } case 2319: { @@ -20773,6 +20770,8 @@ yynewstate: parser.yyVAL.item = &ast.PasswordOrLockOption{ Type: ast.PasswordExpire, } + yylex.AppendError(yylex.Errorf("TiDB does not support PASSWORD EXPIRE, they would be parsed but ignored.")) + parser.lastErrorAsWarn() } case 2324: { @@ -20780,18 +20779,24 @@ yynewstate: Type: ast.PasswordExpireInterval, Count: yyS[yypt-1].item.(int64), } + yylex.AppendError(yylex.Errorf("TiDB does not support PASSWORD EXPIRE, they would be parsed but ignored.")) + parser.lastErrorAsWarn() } case 2325: { parser.yyVAL.item = &ast.PasswordOrLockOption{ Type: ast.PasswordExpireNever, } + yylex.AppendError(yylex.Errorf("TiDB does not support PASSWORD EXPIRE, they would be parsed but ignored.")) + parser.lastErrorAsWarn() } case 2326: { parser.yyVAL.item = &ast.PasswordOrLockOption{ Type: ast.PasswordExpireDefault, } + yylex.AppendError(yylex.Errorf("TiDB does not support PASSWORD EXPIRE, they would be parsed but ignored.")) + parser.lastErrorAsWarn() } case 2327: { diff --git a/parser/parser.y b/parser/parser.y index 286317eb987a4..c609d666f5d66 100644 --- a/parser/parser.y +++ b/parser/parser.y @@ -12769,14 +12769,11 @@ RequireListElement: PasswordOrLockOptions: { - l := []*ast.PasswordOrLockOption{} - $$ = l + $$ = []*ast.PasswordOrLockOption{} } | PasswordOrLockOptionList { $$ = $1 - yylex.AppendError(yylex.Errorf("TiDB does not support PASSWORD EXPIRE and ACCOUNT LOCK now, they would be parsed but ignored.")) - parser.lastErrorAsWarn() } PasswordOrLockOptionList: @@ -12809,6 +12806,8 @@ PasswordOrLockOption: $$ = &ast.PasswordOrLockOption{ Type: ast.PasswordExpire, } + yylex.AppendError(yylex.Errorf("TiDB does not support PASSWORD EXPIRE, they would be parsed but ignored.")) + parser.lastErrorAsWarn() } | PasswordExpire "INTERVAL" Int64Num "DAY" { @@ -12816,18 +12815,24 @@ PasswordOrLockOption: Type: ast.PasswordExpireInterval, Count: $3.(int64), } + yylex.AppendError(yylex.Errorf("TiDB does not support PASSWORD EXPIRE, they would be parsed but ignored.")) + parser.lastErrorAsWarn() } | PasswordExpire "NEVER" { $$ = &ast.PasswordOrLockOption{ Type: ast.PasswordExpireNever, } + yylex.AppendError(yylex.Errorf("TiDB does not support PASSWORD EXPIRE, they would be parsed but ignored.")) + parser.lastErrorAsWarn() } | PasswordExpire "DEFAULT" { $$ = &ast.PasswordOrLockOption{ Type: ast.PasswordExpireDefault, } + yylex.AppendError(yylex.Errorf("TiDB does not support PASSWORD EXPIRE, they would be parsed but ignored.")) + parser.lastErrorAsWarn() } PasswordExpire: From 63b5b4bc091efc673d4a26f3ce5f5a3da51c60cc Mon Sep 17 00:00:00 2001 From: cbcwestwolf <1004626265@qq.com> Date: Thu, 11 Aug 2022 16:38:34 +0800 Subject: [PATCH 02/17] change account_locked in mysql.user --- executor/simple.go | 42 ++++++++++++++++++++++++++++++++++++++++-- util/sqlexec/utils.go | 9 +++------ 2 files changed, 43 insertions(+), 8 deletions(-) diff --git a/executor/simple.go b/executor/simple.go index df0fb6608acb9..20e9787e5ba8d 100644 --- a/executor/simple.go +++ b/executor/simple.go @@ -793,8 +793,22 @@ func (e *SimpleExec) executeCreateUser(ctx context.Context, s *ast.CreateUserStm return err } + lockAccount := false + if len(s.PasswordOrLockOptions) > 0 { + // If "ACCOUNT LOCK" or "ACCOUNT UNLOCK" appears many times, + // the last declaration takes effect. + for i := len(s.PasswordOrLockOptions) - 1; i >= 0; i-- { + if s.PasswordOrLockOptions[i].Type == ast.Lock { + lockAccount = true + break + } else if s.PasswordOrLockOptions[i].Type == ast.Unlock { + break + } + } + } + sql := new(strings.Builder) - if s.IsCreateRole { + if s.IsCreateRole || lockAccount { sqlexec.MustFormatSQL(sql, `INSERT INTO %n.%n (Host, User, authentication_string, plugin, Account_locked) VALUES `, mysql.SystemDB, mysql.UserTable) } else { sqlexec.MustFormatSQL(sql, `INSERT INTO %n.%n (Host, User, authentication_string, plugin) VALUES `, mysql.SystemDB, mysql.UserTable) @@ -844,7 +858,7 @@ func (e *SimpleExec) executeCreateUser(ctx context.Context, s *ast.CreateUserStm } hostName := strings.ToLower(spec.User.Hostname) - if s.IsCreateRole { + if s.IsCreateRole || lockAccount { sqlexec.MustFormatSQL(sql, `(%?, %?, %?, %?, %?)`, hostName, spec.User.Username, pwd, authPlugin, "Y") } else { sqlexec.MustFormatSQL(sql, `(%?, %?, %?, %?)`, hostName, spec.User.Username, pwd, authPlugin) @@ -912,6 +926,21 @@ func (e *SimpleExec) executeAlterUser(ctx context.Context, s *ast.AlterUserStmt) s.Specs = []*ast.UserSpec{spec} } + lockAccount := "" + if len(s.PasswordOrLockOptions) > 0 { + // If "ACCOUNT LOCK" or "ACCOUNT UNLOCK" appears many times, + // the last declaration takes effect. + for i := len(s.PasswordOrLockOptions) - 1; i >= 0; i-- { + if s.PasswordOrLockOptions[i].Type == ast.Lock { + lockAccount = "Y" + break + } else if s.PasswordOrLockOptions[i].Type == ast.Unlock { + lockAccount = "N" + break + } + } + } + privData, err := tlsOption2GlobalPriv(s.TLSOptions) if err != nil { return err @@ -998,6 +1027,15 @@ func (e *SimpleExec) executeAlterUser(ctx context.Context, s *ast.AlterUserStmt) } } + if len(lockAccount) != 0 { + _, _, err := exec.ExecRestrictedSQL(ctx, nil, + `UPDATE %n.%n SET account_locked=%? WHERE Host=%? and User=%?;`, + mysql.SystemDB, mysql.UserTable, lockAccount, strings.ToLower(spec.User.Hostname), spec.User.Username) + if err != nil { + failedUsers = append(failedUsers, spec.User.String()) + } + } + if len(privData) > 0 { _, _, err := exec.ExecRestrictedSQL(ctx, nil, "INSERT INTO %n.%n (Host, User, Priv) VALUES (%?,%?,%?) ON DUPLICATE KEY UPDATE Priv = values(Priv)", mysql.SystemDB, mysql.GlobalPrivTable, spec.User.Hostname, spec.User.Username, string(hack.String(privData))) if err != nil { diff --git a/util/sqlexec/utils.go b/util/sqlexec/utils.go index d61e5375378e1..2448f778a0646 100644 --- a/util/sqlexec/utils.go +++ b/util/sqlexec/utils.go @@ -233,17 +233,14 @@ func escapeSQL(sql string, args ...interface{}) ([]byte, error) { // 1. %?: automatic conversion by the type of arguments. E.g. []string -> ('s1','s2'..) // 2. %%: output % // 3. %n: for identifiers, for example ("use %n", db) -// But it does not prevent you from doing: -/* - EscapeSQL("select '%?", ";SQL injection!;") => "select '';SQL injection!;'". -*/ +// But it does not prevent you from doing EscapeSQL("select '%?", ";SQL injection!;") => "select ”;SQL injection!;'". // It is still your responsibility to write safe SQL. func EscapeSQL(sql string, args ...interface{}) (string, error) { str, err := escapeSQL(sql, args...) return string(str), err } -// MustEscapeSQL is an helper around EscapeSQL. The error returned from escapeSQL can be avoided statically if you do not pass interface{}. +// MustEscapeSQL is a helper around EscapeSQL. The error returned from escapeSQL can be avoided statically if you do not pass interface{}. func MustEscapeSQL(sql string, args ...interface{}) string { r, err := EscapeSQL(sql, args...) if err != nil { @@ -262,7 +259,7 @@ func FormatSQL(w io.Writer, sql string, args ...interface{}) error { return err } -// MustFormatSQL is an helper around FormatSQL, like MustEscapeSQL. But it asks that the writer must be strings.Builder, +// MustFormatSQL is a helper around FormatSQL, like MustEscapeSQL. But it asks that the writer must be strings.Builder, // which will not return error when w.Write(...). func MustFormatSQL(w *strings.Builder, sql string, args ...interface{}) { err := FormatSQL(w, sql, args...) From a4894c20c4018a8d0f266c7c811ba16be7826ddd Mon Sep 17 00:00:00 2001 From: cbcwestwolf <1004626265@qq.com> Date: Thu, 11 Aug 2022 16:59:43 +0800 Subject: [PATCH 03/17] Fix --- util/sqlexec/utils.go | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/util/sqlexec/utils.go b/util/sqlexec/utils.go index 2448f778a0646..05d87ce5bbd37 100644 --- a/util/sqlexec/utils.go +++ b/util/sqlexec/utils.go @@ -233,7 +233,10 @@ func escapeSQL(sql string, args ...interface{}) ([]byte, error) { // 1. %?: automatic conversion by the type of arguments. E.g. []string -> ('s1','s2'..) // 2. %%: output % // 3. %n: for identifiers, for example ("use %n", db) -// But it does not prevent you from doing EscapeSQL("select '%?", ";SQL injection!;") => "select ”;SQL injection!;'". +// But it does not prevent you from doing: +/* + EscapeSQL("select '%?", ";SQL injection!;") => "select '';SQL injection!;'". +*/ // It is still your responsibility to write safe SQL. func EscapeSQL(sql string, args ...interface{}) (string, error) { str, err := escapeSQL(sql, args...) From 44f7a37cdf8383910cf8a656734074a62c27ee52 Mon Sep 17 00:00:00 2001 From: cbcwestwolf <1004626265@qq.com> Date: Thu, 11 Aug 2022 19:47:27 +0800 Subject: [PATCH 04/17] Check account_locked when logining --- bindinfo/bind_test.go | 4 +- bindinfo/capture_test.go | 38 +-- bindinfo/session_handle_test.go | 4 +- ddl/db_cache_test.go | 2 +- ddl/sequence_test.go | 10 +- executor/cluster_table_test.go | 14 +- executor/executor_issue_test.go | 2 +- executor/executor_test.go | 2 +- executor/explain_test.go | 4 +- executor/grant_test.go | 2 +- executor/infoschema_cluster_table_test.go | 6 +- executor/infoschema_reader_test.go | 18 +- executor/show_placement_test.go | 6 +- executor/showtest/show_test.go | 31 +- executor/simpletest/simple_test.go | 22 +- infoschema/cluster_tables_test.go | 16 +- infoschema/tables_test.go | 12 +- parser/auth/caching_sha2.go | 2 +- planner/core/binary_plan_test.go | 10 +- planner/core/integration_partition_test.go | 4 +- planner/core/integration_test.go | 4 +- planner/core/prepare_test.go | 4 +- privilege/privilege.go | 2 +- privilege/privileges/errors.go | 2 + privilege/privileges/privileges.go | 40 ++- privilege/privileges/privileges_test.go | 272 +++++++++--------- server/conn.go | 4 +- server/server.go | 1 + session/session.go | 24 +- session/session_test/session_test.go | 18 +- .../sessionstates/session_states_test.go | 4 +- table/tables/cache_test.go | 2 +- table/tables/tables_test.go | 4 +- .../pessimistictest/pessimistic_test.go | 4 +- 34 files changed, 299 insertions(+), 295 deletions(-) diff --git a/bindinfo/bind_test.go b/bindinfo/bind_test.go index 45cc0b9d2c879..ee8a1959bab2a 100644 --- a/bindinfo/bind_test.go +++ b/bindinfo/bind_test.go @@ -736,11 +736,11 @@ func TestPrivileges(t *testing.T) { tk.MustExec("drop table if exists t") tk.MustExec("create table t(a int, b int, index idx(a))") tk.MustExec("create global binding for select * from t using select * from t use index(idx)") - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "root", Hostname: "%"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "root", Hostname: "%"}, nil, nil)) rows := tk.MustQuery("show global bindings").Rows() require.Len(t, rows, 1) tk.MustExec("create user test@'%'") - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "test", Hostname: "%"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "test", Hostname: "%"}, nil, nil)) rows = tk.MustQuery("show global bindings").Rows() require.Len(t, rows, 0) } diff --git a/bindinfo/capture_test.go b/bindinfo/capture_test.go index c92bc31316404..03116db6f6c4d 100644 --- a/bindinfo/capture_test.go +++ b/bindinfo/capture_test.go @@ -61,7 +61,7 @@ func TestDMLCapturePlanBaseline(t *testing.T) { rows := tk.MustQuery("show global bindings").Rows() require.Len(t, rows, 0) - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "root", Hostname: "%"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "root", Hostname: "%"}, nil, nil)) tk.MustExec("delete from t where b = 1 and c > 1") tk.MustExec("delete from t where b = 1 and c > 1") tk.MustExec("update t set a = 1 where b = 1 and c > 1") @@ -108,7 +108,7 @@ func TestCapturePlanBaseline(t *testing.T) { rows := tk.MustQuery("show global bindings").Rows() require.Len(t, rows, 0) - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "root", Hostname: "%"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "root", Hostname: "%"}, nil, nil)) tk.MustExec("select * from t where a > 10") tk.MustExec("select * from t where a > 10") tk.MustExec("admin capture bindings") @@ -140,7 +140,7 @@ func TestCapturePlanBaseline4DisabledStatus(t *testing.T) { rows := tk.MustQuery("show global bindings").Rows() require.Len(t, rows, 0) - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "root", Hostname: "%"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "root", Hostname: "%"}, nil, nil)) tk.MustExec("select * from t where a > 10") tk.MustExec("select * from t where a > 10") tk.MustExec("admin capture bindings") @@ -188,7 +188,7 @@ func TestCaptureDBCaseSensitivity(t *testing.T) { tk.MustExec("use SPM") tk.MustExec("create table t(a int, b int, key(b))") tk.MustExec("create global binding for select * from t using select /*+ use_index(t) */ * from t") - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "root", Hostname: "%"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "root", Hostname: "%"}, nil, nil)) tk.MustExec("select /*+ use_index(t,b) */ * from t") tk.MustExec("select /*+ use_index(t,b) */ * from t") tk.MustExec("admin capture bindings") @@ -214,7 +214,7 @@ func TestCaptureBaselinesDefaultDB(t *testing.T) { tk.MustExec("drop database if exists spm") tk.MustExec("create database spm") tk.MustExec("create table spm.t(a int, index idx_a(a))") - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "root", Hostname: "%"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "root", Hostname: "%"}, nil, nil)) tk.MustExec("select * from spm.t ignore index(idx_a) where a > 10") tk.MustExec("select * from spm.t ignore index(idx_a) where a > 10") tk.MustExec("admin capture bindings") @@ -241,7 +241,7 @@ func TestCapturePreparedStmt(t *testing.T) { tk := testkit.NewTestKit(t, store) stmtsummary.StmtSummaryByDigestMap.Clear() - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "root", Hostname: "%"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "root", Hostname: "%"}, nil, nil)) tk.MustExec("use test") tk.MustExec("drop table if exists t") tk.MustExec("create table t(a int, b int, c int, key idx_b(b), key idx_c(c))") @@ -276,7 +276,7 @@ func TestCapturePlanBaselineIgnoreTiFlash(t *testing.T) { tk.MustExec("use test") tk.MustExec("drop table if exists t") tk.MustExec("create table t(a int, b int, key(a), key(b))") - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "root", Hostname: "%"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "root", Hostname: "%"}, nil, nil)) tk.MustExec("select * from t") tk.MustExec("select * from t") // Create virtual tiflash replica info. @@ -351,7 +351,7 @@ func TestBindingSource(t *testing.T) { tk.MustExec("SET GLOBAL tidb_capture_plan_baselines = off") }() tk.MustExec("use test") - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "root", Hostname: "%"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "root", Hostname: "%"}, nil, nil)) tk.MustExec("select * from t ignore index(idx_a) where a < 10") tk.MustExec("select * from t ignore index(idx_a) where a < 10") tk.MustExec("admin capture bindings") @@ -371,7 +371,7 @@ func TestCapturedBindingCharset(t *testing.T) { tk := testkit.NewTestKit(t, store) stmtsummary.StmtSummaryByDigestMap.Clear() - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "root", Hostname: "%"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "root", Hostname: "%"}, nil, nil)) tk.MustExec("use test") tk.MustExec("create table t(name varchar(25), index idx(name))") @@ -404,7 +404,7 @@ func TestConcurrentCapture(t *testing.T) { tk.MustExec("use test") tk.MustExec("drop table if exists t") tk.MustExec("create table t(a int, b int)") - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "root", Hostname: "%"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "root", Hostname: "%"}, nil, nil)) tk.MustExec("select * from t") tk.MustExec("select * from t") tk.MustExec("admin capture bindings") @@ -424,7 +424,7 @@ func TestUpdateSubqueryCapture(t *testing.T) { tk.MustExec("create table t1(a int, b int, c int, key idx_b(b))") tk.MustExec("create table t2(a int, b int)") stmtsummary.StmtSummaryByDigestMap.Clear() - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "root", Hostname: "%"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "root", Hostname: "%"}, nil, nil)) tk.MustExec("update t1 set b = 1 where b = 2 and (a in (select a from t2 where b = 1) or c in (select a from t2 where b = 1))") tk.MustExec("update t1 set b = 1 where b = 2 and (a in (select a from t2 where b = 1) or c in (select a from t2 where b = 1))") tk.MustExec("admin capture bindings") @@ -477,7 +477,7 @@ func TestIssue20417(t *testing.T) { stmtsummary.StmtSummaryByDigestMap.Clear() tk.MustExec("SET GLOBAL tidb_capture_plan_baselines = on") dom.BindHandle().CaptureBaselines() - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "root", Hostname: "%"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "root", Hostname: "%"}, nil, nil)) tk.MustExec("select * from t where b=2 and c=213124") tk.MustExec("select * from t where b=2 and c=213124") tk.MustExec("admin capture bindings") @@ -522,7 +522,7 @@ func TestCaptureWithZeroSlowLogThreshold(t *testing.T) { tk.MustExec("drop table if exists t") tk.MustExec("create table t(a int)") stmtsummary.StmtSummaryByDigestMap.Clear() - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "root", Hostname: "%"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "root", Hostname: "%"}, nil, nil)) tk.MustExec("set tidb_slow_log_threshold = 0") tk.MustExec("select * from t") tk.MustExec("select * from t") @@ -548,7 +548,7 @@ func TestIssue25505(t *testing.T) { tk.MustExec("create table t (a int(11) default null,b int(11) default null,key b (b),key ba (b))") tk.MustExec("create table t1 (a int(11) default null,b int(11) default null,key idx_ab (a,b),key idx_a (a),key idx_b (b))") tk.MustExec("create table t2 (a int(11) default null,b int(11) default null,key idx_ab (a,b),key idx_a (a),key idx_b (b))") - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "root", Hostname: "%"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "root", Hostname: "%"}, nil, nil)) spmMap := map[string]string{} spmMap["with recursive `cte` ( `a` ) as ( select ? union select `a` + ? from `test` . `t1` where `a` < ? ) select * from `cte`"] = @@ -615,7 +615,7 @@ func TestCaptureUserFilter(t *testing.T) { tk.MustExec("drop table if exists t") tk.MustExec("create table t(a int)") - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "root", Hostname: "%"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "root", Hostname: "%"}, nil, nil)) tk.MustExec("select * from t where a > 10") tk.MustExec("select * from t where a > 10") tk.MustExec("admin capture bindings") @@ -638,7 +638,7 @@ func TestCaptureUserFilter(t *testing.T) { tk.MustExec(`grant all on *.* to usr1 with grant option`) tk2 := testkit.NewTestKit(t, store) tk2.MustExec("use test") - require.True(t, tk2.Session().Auth(&auth.UserIdentity{Username: "usr1", Hostname: "%"}, nil, nil)) + require.NoError(t, tk2.Session().Auth(&auth.UserIdentity{Username: "usr1", Hostname: "%"}, nil, nil)) tk2.MustExec("select * from t where a > 10") tk2.MustExec("select * from t where a > 10") tk2.MustExec("admin capture bindings") @@ -702,7 +702,7 @@ func TestCaptureWildcardFilter(t *testing.T) { tk.MustExec("SET GLOBAL tidb_capture_plan_baselines = off") }() - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "root", Hostname: "%"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "root", Hostname: "%"}, nil, nil)) dbs := []string{"db11", "db12", "db2"} tbls := []string{"t11", "t12", "t2"} for _, db := range dbs { @@ -808,7 +808,7 @@ func TestCaptureFilter(t *testing.T) { tk.MustExec("drop table if exists t") tk.MustExec("create table t(a int)") - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "root", Hostname: "%"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "root", Hostname: "%"}, nil, nil)) tk.MustExec("select * from t where a > 10") tk.MustExec("select * from t where a > 10") tk.MustExec("admin capture bindings") @@ -960,7 +960,7 @@ func TestCaptureHints(t *testing.T) { tk.MustExec("use test") tk.MustExec("drop table if exists t") tk.MustExec("create table t(pk int primary key, a int, b int, key(a), key(b))") - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "root", Hostname: "%"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "root", Hostname: "%"}, nil, nil)) captureCases := []struct { query string diff --git a/bindinfo/session_handle_test.go b/bindinfo/session_handle_test.go index 18dd99f6a3246..73bb271c2106f 100644 --- a/bindinfo/session_handle_test.go +++ b/bindinfo/session_handle_test.go @@ -181,7 +181,7 @@ func TestBaselineDBLowerCase(t *testing.T) { tk.MustExec("create database SPM") tk.MustExec("use SPM") tk.MustExec("create table t(a int, b int)") - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "root", Hostname: "%"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "root", Hostname: "%"}, nil, nil)) tk.MustExec("update t set a = a + 1") tk.MustExec("update t set a = a + 1") tk.MustExec("admin capture bindings") @@ -271,7 +271,7 @@ func TestShowGlobalBindings(t *testing.T) { tk.MustExec("use SPM") tk.MustExec("create table t(a int, b int, key(a))") tk.MustExec("create table t0(a int, b int, key(a))") - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "root", Hostname: "%"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "root", Hostname: "%"}, nil, nil)) rows := tk.MustQuery("show global bindings").Rows() require.Len(t, rows, 0) // Simulate existing bindings in the mysql.bind_info. diff --git a/ddl/db_cache_test.go b/ddl/db_cache_test.go index b6ecc2468effa..fb3cabd224c93 100644 --- a/ddl/db_cache_test.go +++ b/ddl/db_cache_test.go @@ -268,7 +268,7 @@ func TestIssue34069(t *testing.T) { defer sem.Disable() tk := testkit.NewTestKit(t, store) - tk.Session().Auth(&auth.UserIdentity{Username: "root", Hostname: "%"}, nil, nil) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "root", Hostname: "%"}, nil, nil)) tk.MustExec("use test;") tk.MustExec("create table t_34069 (t int);") // No error when SEM is enabled. diff --git a/ddl/sequence_test.go b/ddl/sequence_test.go index 45983f9b3511e..df58df12b0ebd 100644 --- a/ddl/sequence_test.go +++ b/ddl/sequence_test.go @@ -83,7 +83,7 @@ func TestCreateSequence(t *testing.T) { tk1 := testkit.NewTestKit(t, store) se, err := session.CreateSession4Test(store) require.NoError(t, err) - require.True(t, se.Auth(&auth.UserIdentity{Username: "myuser", Hostname: "localhost"}, nil, nil)) + require.NoError(t, se.Auth(&auth.UserIdentity{Username: "myuser", Hostname: "localhost"}, nil, nil)) tk1.SetSession(se) // grant the myuser the access to database test. @@ -163,7 +163,7 @@ func TestDropSequence(t *testing.T) { tk1 := testkit.NewTestKit(t, store) se, err := session.CreateSession4Test(store) require.NoError(t, err) - require.True(t, se.Auth(&auth.UserIdentity{Username: "myuser", Hostname: "localhost"}, nil, nil)) + require.NoError(t, se.Auth(&auth.UserIdentity{Username: "myuser", Hostname: "localhost"}, nil, nil)) tk1.SetSession(se) // grant the myuser the access to database test. @@ -197,7 +197,7 @@ func TestShowCreateSequence(t *testing.T) { tk1 := testkit.NewTestKit(t, store) se, err := session.CreateSession4Test(store) require.NoError(t, err) - require.True(t, se.Auth(&auth.UserIdentity{Username: "myuser", Hostname: "localhost"}, nil, nil)) + require.NoError(t, se.Auth(&auth.UserIdentity{Username: "myuser", Hostname: "localhost"}, nil, nil)) tk1.SetSession(se) // Grant the myuser the access to table t in database test, but sequence seq. @@ -910,7 +910,7 @@ func TestSequenceFunctionPrivilege(t *testing.T) { tk1 := testkit.NewTestKit(t, store) se, err := session.CreateSession4Test(store) require.NoError(t, err) - require.True(t, se.Auth(&auth.UserIdentity{Username: "myuser", Hostname: "localhost"}, nil, nil)) + require.NoError(t, se.Auth(&auth.UserIdentity{Username: "myuser", Hostname: "localhost"}, nil, nil)) tk1.SetSession(se) // grant the myuser the create access to the sequence. @@ -1103,7 +1103,7 @@ func TestAlterSequencePrivilege(t *testing.T) { tk1 := testkit.NewTestKit(t, store) se, err := session.CreateSession4Test(store) require.NoError(t, err) - require.True(t, se.Auth(&auth.UserIdentity{Username: "myuser", Hostname: "localhost"}, nil, nil)) + require.NoError(t, se.Auth(&auth.UserIdentity{Username: "myuser", Hostname: "localhost"}, nil, nil)) tk1.SetSession(se) // grant the myuser the access to database test. diff --git a/executor/cluster_table_test.go b/executor/cluster_table_test.go index e2eaa733e06de..c2970474a1ca5 100644 --- a/executor/cluster_table_test.go +++ b/executor/cluster_table_test.go @@ -283,7 +283,7 @@ func TestSQLDigestTextRetriever(t *testing.T) { tk := testkit.NewTestKit(t, store) tk.MustExec("use test") - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "root", Hostname: "%"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "root", Hostname: "%"}, nil, nil)) tk.MustExec("insert into test_sql_digest_text_retriever values (1, 1)") insertNormalized, insertDigest := parser.NormalizeDigest("insert into test_sql_digest_text_retriever values (1, 1)") @@ -307,7 +307,7 @@ func TestFunctionDecodeSQLDigests(t *testing.T) { tk := testkit.NewTestKit(t, store) tk.MustExec("use test") - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "root", Hostname: "%"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "root", Hostname: "%"}, nil, nil)) tk.MustExec("set global tidb_enable_stmt_summary = 1") tk.MustQuery("select @@global.tidb_enable_stmt_summary").Check(testkit.Rows("1")) tk.MustExec("drop table if exists test_func_decode_sql_digests") @@ -366,21 +366,21 @@ func TestFunctionDecodeSQLDigestsPrivilege(t *testing.T) { defer srv.Stop() dropUserTk := testkit.NewTestKit(t, store) - require.True(t, dropUserTk.Session().Auth(&auth.UserIdentity{Username: "root", Hostname: "%"}, nil, nil)) + require.NoError(t, dropUserTk.Session().Auth(&auth.UserIdentity{Username: "root", Hostname: "%"}, nil, nil)) tk := testkit.NewTestKit(t, store) - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "root", Hostname: "%"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "root", Hostname: "%"}, nil, nil)) tk.MustExec("create user 'testuser'@'localhost'") defer dropUserTk.MustExec("drop user 'testuser'@'localhost'") - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "testuser", Hostname: "localhost"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "testuser", Hostname: "localhost"}, nil, nil)) tk.MustGetErrMsg("select tidb_decode_sql_digests('[\"aa\"]')", "[expression:1227]Access denied; you need (at least one of) the PROCESS privilege(s) for this operation") tk = testkit.NewTestKit(t, store) - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "root", Hostname: "%"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "root", Hostname: "%"}, nil, nil)) tk.MustExec("create user 'testuser2'@'localhost'") defer dropUserTk.MustExec("drop user 'testuser2'@'localhost'") tk.MustExec("grant process on *.* to 'testuser2'@'localhost'") - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "testuser2", Hostname: "localhost"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "testuser2", Hostname: "localhost"}, nil, nil)) tk.MustExec("select tidb_decode_sql_digests('[\"aa\"]')") } diff --git a/executor/executor_issue_test.go b/executor/executor_issue_test.go index 5eb08c6789f0e..e0f3775b9286d 100644 --- a/executor/executor_issue_test.go +++ b/executor/executor_issue_test.go @@ -417,7 +417,7 @@ func TestIndexJoin31494(t *testing.T) { dom.ExpensiveQueryHandle().SetSessionManager(sm) defer tk.MustExec("SET GLOBAL tidb_mem_oom_action = DEFAULT") tk.MustExec("SET GLOBAL tidb_mem_oom_action='CANCEL'") - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "root", Hostname: "%"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "root", Hostname: "%"}, nil, nil)) tk.MustExec("set @@tidb_mem_quota_query=2097152;") // This bug will be reproduced in 10 times. for i := 0; i < 10; i++ { diff --git a/executor/executor_test.go b/executor/executor_test.go index 0fe57783a9f4c..7d9b189c52178 100644 --- a/executor/executor_test.go +++ b/executor/executor_test.go @@ -5925,7 +5925,7 @@ func TestSummaryFailedUpdate(t *testing.T) { dom.ExpensiveQueryHandle().SetSessionManager(sm) defer tk.MustExec("SET GLOBAL tidb_mem_oom_action = DEFAULT") tk.MustExec("SET GLOBAL tidb_mem_oom_action='CANCEL'") - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "root", Hostname: "%"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "root", Hostname: "%"}, nil, nil)) tk.MustExec("set @@tidb_mem_quota_query=1") tk.MustMatchErrMsg("update t set t.a = t.a - 1 where t.a in (select a from t where a < 4)", "Out Of Memory Quota!.*") tk.MustExec("set @@tidb_mem_quota_query=1000000000") diff --git a/executor/explain_test.go b/executor/explain_test.go index 0b569fd958f5c..a05c0e044249c 100644 --- a/executor/explain_test.go +++ b/executor/explain_test.go @@ -35,7 +35,7 @@ func TestExplainPrivileges(t *testing.T) { store := testkit.CreateMockStore(t) se, err := session.CreateSession4Test(store) require.NoError(t, err) - require.True(t, se.Auth(&auth.UserIdentity{Username: "root", Hostname: "%"}, nil, nil)) + require.NoError(t, se.Auth(&auth.UserIdentity{Username: "root", Hostname: "%"}, nil, nil)) tk := testkit.NewTestKit(t, store) tk.SetSession(se) @@ -48,7 +48,7 @@ func TestExplainPrivileges(t *testing.T) { tk1 := testkit.NewTestKit(t, store) se, err = session.CreateSession4Test(store) require.NoError(t, err) - require.True(t, se.Auth(&auth.UserIdentity{Username: "explain", Hostname: "%"}, nil, nil)) + require.NoError(t, se.Auth(&auth.UserIdentity{Username: "explain", Hostname: "%"}, nil, nil)) tk1.SetSession(se) tk.MustExec(`grant select on explaindatabase.v to 'explain'@'%'`) diff --git a/executor/grant_test.go b/executor/grant_test.go index 2c06b2fbb9b5c..843cff3b7afd4 100644 --- a/executor/grant_test.go +++ b/executor/grant_test.go @@ -511,7 +511,7 @@ func TestPerformanceSchemaPrivGrant(t *testing.T) { defer func() { tk.MustExec("drop user issue27867;") }() - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "root", Hostname: "localhost"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "root", Hostname: "localhost"}, nil, nil)) tk.MustGetErrCode("grant all on performance_schema.* to issue27867;", errno.ErrDBaccessDenied) // Check case insensitivity tk.MustGetErrCode("grant all on PERFormanCE_scHemA.* to issue27867;", errno.ErrDBaccessDenied) diff --git a/executor/infoschema_cluster_table_test.go b/executor/infoschema_cluster_table_test.go index 7128d65afdc7c..3af92f2654dd3 100644 --- a/executor/infoschema_cluster_table_test.go +++ b/executor/infoschema_cluster_table_test.go @@ -347,7 +347,7 @@ func TestTableStorageStats(t *testing.T) { tk.MustExec("grant all privileges on *.* to 'testuser2'@'localhost'") tk.MustExec("grant select on *.* to 'testuser3'@'localhost'") - require.True(t, tk.Session().Auth(&auth.UserIdentity{ + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{ Username: "testuser", Hostname: "localhost", }, nil, nil)) @@ -355,14 +355,14 @@ func TestTableStorageStats(t *testing.T) { // User has no access to this schema, so the result set is empty. tk.MustQuery("select count(1) from information_schema.TABLE_STORAGE_STATS where TABLE_SCHEMA = 'mysql'").Check(testkit.Rows("0")) - require.True(t, tk.Session().Auth(&auth.UserIdentity{ + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{ Username: "testuser2", Hostname: "localhost", }, nil, nil)) tk.MustQuery("select count(1) from information_schema.TABLE_STORAGE_STATS where TABLE_SCHEMA = 'mysql'").Check(testkit.Rows(strconv.Itoa(result))) - require.True(t, tk.Session().Auth(&auth.UserIdentity{ + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{ Username: "testuser3", Hostname: "localhost", }, nil, nil)) diff --git a/executor/infoschema_reader_test.go b/executor/infoschema_reader_test.go index b19e8cefbc1ac..ba413298a7deb 100644 --- a/executor/infoschema_reader_test.go +++ b/executor/infoschema_reader_test.go @@ -95,7 +95,7 @@ func TestSchemataTables(t *testing.T) { tk.MustExec("create user schemata_tester") schemataTester := testkit.NewTestKit(t, store) schemataTester.MustExec("use information_schema") - require.True(t, schemataTester.Session().Auth(&auth.UserIdentity{ + require.NoError(t, schemataTester.Session().Auth(&auth.UserIdentity{ Username: "schemata_tester", Hostname: "127.0.0.1", }, nil, nil)) @@ -231,7 +231,7 @@ func TestDDLJobs(t *testing.T) { tk.MustExec("create user DDL_JOBS_tester") DDLJobsTester := testkit.NewTestKit(t, store) DDLJobsTester.MustExec("use information_schema") - require.True(t, DDLJobsTester.Session().Auth(&auth.UserIdentity{ + require.NoError(t, DDLJobsTester.Session().Auth(&auth.UserIdentity{ Username: "DDL_JOBS_tester", Hostname: "127.0.0.1", }, nil, nil)) @@ -263,7 +263,7 @@ func TestKeyColumnUsage(t *testing.T) { tk.MustExec("create user key_column_tester") keyColumnTester := testkit.NewTestKit(t, store) keyColumnTester.MustExec("use information_schema") - require.True(t, keyColumnTester.Session().Auth(&auth.UserIdentity{ + require.NoError(t, keyColumnTester.Session().Auth(&auth.UserIdentity{ Username: "key_column_tester", Hostname: "127.0.0.1", }, nil, nil)) @@ -285,7 +285,7 @@ func TestUserPrivileges(t *testing.T) { tk.MustExec("create user constraints_tester") constraintsTester := testkit.NewTestKit(t, store) constraintsTester.MustExec("use information_schema") - require.True(t, constraintsTester.Session().Auth(&auth.UserIdentity{ + require.NoError(t, constraintsTester.Session().Auth(&auth.UserIdentity{ Username: "constraints_tester", Hostname: "127.0.0.1", }, nil, nil)) @@ -304,7 +304,7 @@ func TestUserPrivileges(t *testing.T) { tk.MustExec("create user tester1") tk1 := testkit.NewTestKit(t, store) tk1.MustExec("use information_schema") - require.True(t, tk1.Session().Auth(&auth.UserIdentity{ + require.NoError(t, tk1.Session().Auth(&auth.UserIdentity{ Username: "tester1", Hostname: "127.0.0.1", }, nil, nil)) @@ -317,7 +317,7 @@ func TestUserPrivileges(t *testing.T) { tk.MustExec("GRANT r_columns_priv TO tester2;") tk2 := testkit.NewTestKit(t, store) tk2.MustExec("use information_schema") - require.True(t, tk2.Session().Auth(&auth.UserIdentity{ + require.NoError(t, tk2.Session().Auth(&auth.UserIdentity{ Username: "tester2", Hostname: "127.0.0.1", }, nil, nil)) @@ -334,7 +334,7 @@ func TestUserPrivileges(t *testing.T) { tk.MustExec("GRANT r_all_priv TO tester3;") tk3 := testkit.NewTestKit(t, store) tk3.MustExec("use information_schema") - require.True(t, tk3.Session().Auth(&auth.UserIdentity{ + require.NoError(t, tk3.Session().Auth(&auth.UserIdentity{ Username: "tester3", Hostname: "127.0.0.1", }, nil, nil)) @@ -352,7 +352,7 @@ func TestUserPrivilegesTable(t *testing.T) { // test the privilege of new user for information_schema.user_privileges tk.MustExec("create user usageuser") - require.True(t, tk.Session().Auth(&auth.UserIdentity{ + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{ Username: "usageuser", Hostname: "127.0.0.1", }, nil, nil)) @@ -563,7 +563,7 @@ func TestForAnalyzeStatus(t *testing.T) { tk.MustExec("create user analyze_tester") analyzeTester := testkit.NewTestKit(t, store) analyzeTester.MustExec("use information_schema") - require.True(t, analyzeTester.Session().Auth(&auth.UserIdentity{ + require.NoError(t, analyzeTester.Session().Auth(&auth.UserIdentity{ Username: "analyze_tester", Hostname: "127.0.0.1", }, nil, nil)) diff --git a/executor/show_placement_test.go b/executor/show_placement_test.go index 4d6b4ff1692d7..0b47c1721dd17 100644 --- a/executor/show_placement_test.go +++ b/executor/show_placement_test.go @@ -151,7 +151,7 @@ func TestShowPlacementPrivilege(t *testing.T) { defer tk.MustExec("drop table if exists db2.t3") tk1 := testkit.NewTestKit(t, store) - require.True(t, tk1.Session().Auth(&auth.UserIdentity{Username: "user1", Hostname: "%"}, nil, nil)) + require.NoError(t, tk1.Session().Auth(&auth.UserIdentity{Username: "user1", Hostname: "%"}, nil, nil)) // before grant tk1.MustQuery("show placement").Check(testkit.Rows( @@ -308,7 +308,7 @@ func TestShowPlacementForDBPrivilege(t *testing.T) { defer tk.MustExec("drop table db2.t1") tk1 := testkit.NewTestKit(t, store) - require.True(t, tk1.Session().Auth(&auth.UserIdentity{Username: "user1", Hostname: "%"}, nil, nil)) + require.NoError(t, tk1.Session().Auth(&auth.UserIdentity{Username: "user1", Hostname: "%"}, nil, nil)) privs := []string{ "all privileges on db2.*", @@ -400,7 +400,7 @@ func TestShowPlacementForTableAndPartitionPrivilege(t *testing.T) { defer tk.MustExec("drop table if exists db2.t1") tk1 := testkit.NewTestKit(t, store) - require.True(t, tk1.Session().Auth(&auth.UserIdentity{Username: "user1", Hostname: "%"}, nil, nil)) + require.NoError(t, tk1.Session().Auth(&auth.UserIdentity{Username: "user1", Hostname: "%"}, nil, nil)) // before grant err := tk1.ExecToErr("show placement for table test.t1") diff --git a/executor/showtest/show_test.go b/executor/showtest/show_test.go index 1a20a02868a5d..ad877375364ad 100644 --- a/executor/showtest/show_test.go +++ b/executor/showtest/show_test.go @@ -57,7 +57,7 @@ func TestShowOpenTables(t *testing.T) { func TestShowCreateViewDefiner(t *testing.T) { store := testkit.CreateMockStore(t) tk := testkit.NewTestKit(t, store) - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "root", Hostname: "%", AuthUsername: "root", AuthHostname: "%"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "root", Hostname: "%", AuthUsername: "root", AuthHostname: "%"}, nil, nil)) tk.MustExec("use test") tk.MustExec("create or replace view v1 as select 1") @@ -644,7 +644,7 @@ func TestShowVisibility(t *testing.T) { tk.MustExec(`create user 'show'@'%'`) tk1 := testkit.NewTestKit(t, store) - require.True(t, tk1.Session().Auth(&auth.UserIdentity{Username: "show", Hostname: "%"}, nil, nil)) + require.NoError(t, tk1.Session().Auth(&auth.UserIdentity{Username: "show", Hostname: "%"}, nil, nil)) // No ShowDatabases privilege, this user would see nothing except INFORMATION_SCHEMA. tk.MustQuery("show databases").Check(testkit.Rows("INFORMATION_SCHEMA")) @@ -682,7 +682,7 @@ func TestShowDatabasesInfoSchemaFirst(t *testing.T) { tk.MustExec(`grant select on BBBB.* to 'show'@'%'`) tk1 := testkit.NewTestKit(t, store) - require.True(t, tk1.Session().Auth(&auth.UserIdentity{Username: "show", Hostname: "%"}, nil, nil)) + require.NoError(t, tk1.Session().Auth(&auth.UserIdentity{Username: "show", Hostname: "%"}, nil, nil)) tk1.MustQuery("show databases").Check(testkit.Rows("INFORMATION_SCHEMA", "AAAA", "BBBB")) tk.MustExec(`drop user 'show'@'%'`) @@ -785,12 +785,12 @@ func TestShowGrantsPrivilege(t *testing.T) { tk.MustExec("create user show_grants") tk.MustExec("show grants for show_grants") tk1 := testkit.NewTestKit(t, store) - require.True(t, tk1.Session().Auth(&auth.UserIdentity{Username: "show_grants", Hostname: "%"}, nil, nil)) + require.NoError(t, tk1.Session().Auth(&auth.UserIdentity{Username: "show_grants", Hostname: "%"}, nil, nil)) err := tk1.QueryToErr("show grants for root") require.EqualError(t, executor.ErrDBaccessDenied.GenWithStackByArgs("show_grants", "%", mysql.SystemDB), err.Error()) // Test show grants for user with auth host name `%`. tk2 := testkit.NewTestKit(t, store) - require.True(t, tk2.Session().Auth(&auth.UserIdentity{Username: "show_grants", Hostname: "127.0.0.1", AuthUsername: "show_grants", AuthHostname: "%"}, nil, nil)) + require.NoError(t, tk2.Session().Auth(&auth.UserIdentity{Username: "show_grants", Hostname: "127.0.0.1", AuthUsername: "show_grants", AuthHostname: "%"}, nil, nil)) tk2.MustQuery("show grants") } @@ -800,7 +800,7 @@ func TestShowStatsPrivilege(t *testing.T) { tk.MustExec("create user show_stats") tk1 := testkit.NewTestKit(t, store) - require.True(t, tk1.Session().Auth(&auth.UserIdentity{Username: "show_stats", Hostname: "%"}, nil, nil)) + require.NoError(t, tk1.Session().Auth(&auth.UserIdentity{Username: "show_stats", Hostname: "%"}, nil, nil)) e := "[planner:1142]SHOW command denied to user 'show_stats'@'%' for table" err := tk1.ExecToErr("show stats_meta") require.ErrorContains(t, err, e) @@ -819,7 +819,7 @@ func TestShowStatsPrivilege(t *testing.T) { tk1.MustExec("SHOW STATS_HISTOGRAMS") tk.MustExec("create user a@'%' identified by '';") - require.True(t, tk1.Session().Auth(&auth.UserIdentity{Username: "a", Hostname: "%"}, nil, nil)) + require.NoError(t, tk1.Session().Auth(&auth.UserIdentity{Username: "a", Hostname: "%"}, nil, nil)) tk.MustExec("grant select on mysql.stats_meta to a@'%';") tk.MustExec("grant select on mysql.stats_buckets to a@'%';") tk.MustExec("grant select on mysql.stats_histograms to a@'%';") @@ -831,7 +831,7 @@ func TestShowStatsPrivilege(t *testing.T) { func TestIssue18878(t *testing.T) { store := testkit.CreateMockStore(t) tk := testkit.NewTestKit(t, store) - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "root", Hostname: "127.0.0.1", AuthHostname: "%"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "root", Hostname: "127.0.0.1", AuthHostname: "%"}, nil, nil)) tk.MustQuery("select user()").Check(testkit.Rows("root@127.0.0.1")) tk.MustQuery("show grants") tk.MustQuery("select user()").Check(testkit.Rows("root@127.0.0.1")) @@ -851,10 +851,10 @@ func TestIssue17794(t *testing.T) { store := testkit.CreateMockStore(t) tk := testkit.NewTestKit(t, store) tk.MustExec("CREATE USER 'root'@'8.8.%'") - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "root", Hostname: "9.9.9.9", AuthHostname: "%"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "root", Hostname: "9.9.9.9", AuthHostname: "%"}, nil, nil)) tk1 := testkit.NewTestKit(t, store) - require.True(t, tk1.Session().Auth(&auth.UserIdentity{Username: "root", Hostname: "8.8.8.8", AuthHostname: "8.8.%"}, nil, nil)) + require.NoError(t, tk1.Session().Auth(&auth.UserIdentity{Username: "root", Hostname: "8.8.8.8", AuthHostname: "8.8.%"}, nil, nil)) tk.MustQuery("show grants").Check(testkit.Rows("GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' WITH GRANT OPTION")) tk1.MustQuery("show grants").Check(testkit.Rows("GRANT USAGE ON *.* TO 'root'@'8.8.%'")) } @@ -878,7 +878,7 @@ func TestIssue10549(t *testing.T) { tk.MustExec("GRANT 'app_developer' TO 'dev';") tk.MustExec("SET DEFAULT ROLE app_developer TO 'dev';") - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "dev", Hostname: "%", AuthUsername: "dev", AuthHostname: "%"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "dev", Hostname: "%", AuthUsername: "dev", AuthHostname: "%"}, nil, nil)) tk.MustQuery("SHOW DATABASES;").Check(testkit.Rows("INFORMATION_SCHEMA", "newdb")) tk.MustQuery("SHOW GRANTS;").Check(testkit.Rows("GRANT USAGE ON *.* TO 'dev'@'%'", "GRANT ALL PRIVILEGES ON newdb.* TO 'dev'@'%'", "GRANT 'app_developer'@'%' TO 'dev'@'%'")) tk.MustQuery("SHOW GRANTS FOR CURRENT_USER").Check(testkit.Rows("GRANT USAGE ON *.* TO 'dev'@'%'", "GRANT ALL PRIVILEGES ON newdb.* TO 'dev'@'%'", "GRANT 'app_developer'@'%' TO 'dev'@'%'")) @@ -892,7 +892,7 @@ func TestIssue11165(t *testing.T) { tk.MustExec("CREATE USER 'manager'@'localhost';") tk.MustExec("GRANT 'r_manager' TO 'manager'@'localhost';") - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "manager", Hostname: "localhost", AuthUsername: "manager", AuthHostname: "localhost"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "manager", Hostname: "localhost", AuthUsername: "manager", AuthHostname: "localhost"}, nil, nil)) tk.MustExec("SET DEFAULT ROLE ALL TO 'manager'@'localhost';") tk.MustExec("SET DEFAULT ROLE NONE TO 'manager'@'localhost';") tk.MustExec("SET DEFAULT ROLE 'r_manager' TO 'manager'@'localhost';") @@ -1055,8 +1055,7 @@ func TestShowCreateUser(t *testing.T) { // "show create user" for other user requires the SELECT privilege on mysql database. tk1 := testkit.NewTestKit(t, store) tk1.MustExec("use mysql") - succ := tk1.Session().Auth(&auth.UserIdentity{Username: "check_priv", Hostname: "127.0.0.1", AuthUsername: "test_show", AuthHostname: "asdf"}, nil, nil) - require.True(t, succ) + require.NoError(t, tk1.Session().Auth(&auth.UserIdentity{Username: "check_priv", Hostname: "127.0.0.1", AuthUsername: "test_show", AuthHostname: "asdf"}, nil, nil)) err = tk1.QueryToErr("show create user 'root'@'%'") require.Error(t, err) @@ -1828,7 +1827,7 @@ func TestShowDatabasesLike(t *testing.T) { store := testkit.CreateMockStore(t) tk := testkit.NewTestKit(t, store) - require.True(t, tk.Session().Auth(&auth.UserIdentity{ + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{ Username: "root", Hostname: "%"}, nil, nil)) tk.MustExec("DROP DATABASE IF EXISTS `TEST_$1`") @@ -1865,7 +1864,7 @@ func TestShowCollationsLike(t *testing.T) { store := testkit.CreateMockStore(t) tk := testkit.NewTestKit(t, store) - require.True(t, tk.Session().Auth(&auth.UserIdentity{ + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{ Username: "root", Hostname: "%"}, nil, nil)) tk.MustQuery("SHOW COLLATION LIKE 'UTF8MB4_BI%'").Check(testkit.Rows("utf8mb4_bin utf8mb4 46 Yes Yes 1")) tk.MustQuery("SHOW COLLATION LIKE 'utf8mb4_bi%'").Check(testkit.Rows("utf8mb4_bin utf8mb4 46 Yes Yes 1")) diff --git a/executor/simpletest/simple_test.go b/executor/simpletest/simple_test.go index f11d6efc0a4be..694cfcb7e7d88 100644 --- a/executor/simpletest/simple_test.go +++ b/executor/simpletest/simple_test.go @@ -94,7 +94,7 @@ func TestIssue9111(t *testing.T) { se, err := session.CreateSession4Test(store) require.NoError(t, err) defer se.Close() - require.True(t, se.Auth(&auth.UserIdentity{Username: "user_admin", Hostname: "localhost"}, nil, nil)) + require.NoError(t, se.Auth(&auth.UserIdentity{Username: "user_admin", Hostname: "localhost"}, nil, nil)) ctx := context.Background() _, err = se.Execute(ctx, `create user test_create_user`) @@ -146,7 +146,7 @@ func TestExtendedStatsPrivileges(t *testing.T) { se, err := session.CreateSession4Test(store) require.NoError(t, err) defer se.Close() - require.True(t, se.Auth(&auth.UserIdentity{Username: "u1", Hostname: "%"}, nil, nil)) + require.NoError(t, se.Auth(&auth.UserIdentity{Username: "u1", Hostname: "%"}, nil, nil)) ctx := context.Background() _, err = se.Execute(ctx, "set session tidb_enable_extended_stats = on") require.NoError(t, err) @@ -184,7 +184,7 @@ func TestIssue17247(t *testing.T) { tk1 := testkit.NewTestKit(t, store) tk1.MustExec("use test") - require.True(t, tk1.Session().Auth(&auth.UserIdentity{Username: "issue17247", Hostname: "%"}, nil, nil)) + require.NoError(t, tk1.Session().Auth(&auth.UserIdentity{Username: "issue17247", Hostname: "%"}, nil, nil)) tk1.MustExec("ALTER USER USER() IDENTIFIED BY 'xxx'") tk1.MustExec("ALTER USER CURRENT_USER() IDENTIFIED BY 'yyy'") tk1.MustExec("ALTER USER CURRENT_USER IDENTIFIED BY 'zzz'") @@ -216,10 +216,10 @@ func TestSetCurrentUserPwd(t *testing.T) { tk.MustExec("DROP USER IF EXISTS issue28534;") }() - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "issue28534", Hostname: "localhost", CurrentUser: true, AuthUsername: "issue28534", AuthHostname: "%"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "issue28534", Hostname: "localhost", CurrentUser: true, AuthUsername: "issue28534", AuthHostname: "%"}, nil, nil)) tk.MustExec(`SET PASSWORD FOR CURRENT_USER() = "43582eussi"`) - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "root", Hostname: "%"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "root", Hostname: "%"}, nil, nil)) result := tk.MustQuery(`SELECT authentication_string FROM mysql.User WHERE User="issue28534"`) result.Check(testkit.Rows(auth.EncodePassword("43582eussi"))) } @@ -374,7 +374,7 @@ func TestSetRoleAllCorner(t *testing.T) { se, err := session.CreateSession4Test(store) require.NoError(t, err) defer se.Close() - require.True(t, se.Auth(&auth.UserIdentity{Username: "set_role_all", Hostname: "localhost"}, nil, nil)) + require.NoError(t, se.Auth(&auth.UserIdentity{Username: "set_role_all", Hostname: "localhost"}, nil, nil)) ctx := context.Background() _, err = se.Execute(ctx, `set role all`) require.NoError(t, err) @@ -390,7 +390,7 @@ func TestCreateRole(t *testing.T) { se, err := session.CreateSession4Test(store) require.NoError(t, err) defer se.Close() - require.True(t, se.Auth(&auth.UserIdentity{Username: "testCreateRole", Hostname: "localhost"}, nil, nil)) + require.NoError(t, se.Auth(&auth.UserIdentity{Username: "testCreateRole", Hostname: "localhost"}, nil, nil)) ctx := context.Background() _, err = se.Execute(ctx, `create role test_create_role;`) @@ -415,7 +415,7 @@ func TestDropRole(t *testing.T) { se, err := session.CreateSession4Test(store) require.NoError(t, err) defer se.Close() - require.True(t, se.Auth(&auth.UserIdentity{Username: "testCreateRole", Hostname: "localhost"}, nil, nil)) + require.NoError(t, se.Auth(&auth.UserIdentity{Username: "testCreateRole", Hostname: "localhost"}, nil, nil)) ctx := context.Background() _, err = se.Execute(ctx, `drop role test_create_role;`) @@ -573,7 +573,7 @@ func TestRoleAdmin(t *testing.T) { se, err := session.CreateSession4Test(store) require.NoError(t, err) defer se.Close() - require.True(t, se.Auth(&auth.UserIdentity{Username: "testRoleAdmin", Hostname: "localhost"}, nil, nil)) + require.NoError(t, se.Auth(&auth.UserIdentity{Username: "testRoleAdmin", Hostname: "localhost"}, nil, nil)) ctx := context.Background() _, err = se.Execute(ctx, "GRANT `targetRole` TO `testRoleAdmin`;") @@ -647,7 +647,7 @@ func TestSetDefaultRoleAll(t *testing.T) { se, err := session.CreateSession4Test(store) require.NoError(t, err) defer se.Close() - require.True(t, se.Auth(&auth.UserIdentity{Username: "test_all", Hostname: "localhost"}, nil, nil)) + require.NoError(t, se.Auth(&auth.UserIdentity{Username: "test_all", Hostname: "localhost"}, nil, nil)) ctx := context.Background() _, err = se.Execute(ctx, "set default role all to test_all;") @@ -882,7 +882,7 @@ func TestFlushPrivileges(t *testing.T) { se, err := session.CreateSession4Test(store) require.NoError(t, err) defer se.Close() - require.True(t, se.Auth(&auth.UserIdentity{Username: "testflush", Hostname: "localhost"}, nil, nil)) + require.NoError(t, se.Auth(&auth.UserIdentity{Username: "testflush", Hostname: "localhost"}, nil, nil)) ctx := context.Background() // Before flush. diff --git a/infoschema/cluster_tables_test.go b/infoschema/cluster_tables_test.go index dbb7345d79169..b416157e702cb 100644 --- a/infoschema/cluster_tables_test.go +++ b/infoschema/cluster_tables_test.go @@ -192,7 +192,7 @@ func SubTestDataLockWaitsPrivilege(t *testing.T) { tk.MustExec("create user 'testuser'@'localhost'") defer dropUserTk.MustExec("drop user 'testuser'@'localhost'") - require.True(t, tk.Session().Auth(&auth.UserIdentity{ + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{ Username: "testuser", Hostname: "localhost", }, nil, nil)) @@ -203,7 +203,7 @@ func SubTestDataLockWaitsPrivilege(t *testing.T) { tk.MustExec("create user 'testuser2'@'localhost'") defer dropUserTk.MustExec("drop user 'testuser2'@'localhost'") tk.MustExec("grant process on *.* to 'testuser2'@'localhost'") - require.True(t, tk.Session().Auth(&auth.UserIdentity{ + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{ Username: "testuser2", Hostname: "localhost", }, nil, nil)) @@ -305,7 +305,7 @@ select * from t3; tk.MustExec("create user user2") user1 := testkit.NewTestKit(t, s.store) user1.MustExec("use information_schema") - require.True(t, user1.Session().Auth(&auth.UserIdentity{ + require.NoError(t, user1.Session().Auth(&auth.UserIdentity{ Username: "user1", Hostname: "127.0.0.1", }, nil, nil)) @@ -315,7 +315,7 @@ select * from t3; user2 := testkit.NewTestKit(t, s.store) user2.MustExec("use information_schema") - require.True(t, user2.Session().Auth(&auth.UserIdentity{ + require.NoError(t, user2.Session().Auth(&auth.UserIdentity{ Username: "user2", Hostname: "127.0.0.1", }, nil, nil)) @@ -369,7 +369,7 @@ func TestStmtSummaryEvictedCountTable(t *testing.T) { defer tk1.MustExec("drop user 'testuser'@'localhost'") defer tk1.MustExec("drop user 'testuser2'@'localhost'") - require.True(t, tk.Session().Auth(&auth.UserIdentity{ + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{ Username: "testuser", Hostname: "localhost", }, nil, nil)) @@ -378,7 +378,7 @@ func TestStmtSummaryEvictedCountTable(t *testing.T) { // This error is come from cop(TiDB) fetch from rpc server. require.EqualError(t, err, "other error: [planner:1227]Access denied; you need (at least one of) the PROCESS privilege(s) for this operation") - require.True(t, tk.Session().Auth(&auth.UserIdentity{ + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{ Username: "testuser2", Hostname: "localhost", }, nil, nil)) @@ -405,7 +405,7 @@ func TestStmtSummaryIssue35340(t *testing.T) { tk := s.newTestKitWithRoot(t) for j := 0; j < 100; j++ { user := "user" + strconv.Itoa(j) - require.True(t, tk.Session().Auth(&auth.UserIdentity{ + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{ Username: user, Hostname: "localhost", }, nil, nil)) @@ -803,6 +803,6 @@ func (s *clusterTablesSuite) setUpMockPDHTTPServer() (*httptest.Server, string) func (s *clusterTablesSuite) newTestKitWithRoot(t *testing.T) *testkit.TestKit { tk := testkit.NewTestKit(t, s.store) tk.MustExec("use test") - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "root", Hostname: "%"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "root", Hostname: "%"}, nil, nil)) return tk } diff --git a/infoschema/tables_test.go b/infoschema/tables_test.go index b742c868f0f77..c31cc42f6afb7 100644 --- a/infoschema/tables_test.go +++ b/infoschema/tables_test.go @@ -47,7 +47,7 @@ import ( func newTestKitWithRoot(t *testing.T, store kv.Storage) *testkit.TestKit { tk := testkit.NewTestKit(t, store) tk.MustExec("use test") - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "root", Hostname: "%"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "root", Hostname: "%"}, nil, nil)) return tk } @@ -57,7 +57,7 @@ func newTestKitWithPlanCache(t *testing.T, store kv.Storage) *testkit.TestKit { require.NoError(t, err) tk.SetSession(se) tk.RefreshConnectionID() - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "root", Hostname: "%"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "root", Hostname: "%"}, nil, nil)) return tk } @@ -120,7 +120,7 @@ func TestInfoSchemaFieldValue(t *testing.T) { tk1 := testkit.NewTestKit(t, store) tk1.MustExec("use test") - require.True(t, tk1.Session().Auth(&auth.UserIdentity{ + require.NoError(t, tk1.Session().Auth(&auth.UserIdentity{ Username: "xxx", Hostname: "127.0.0.1", }, nil, nil)) @@ -1388,7 +1388,7 @@ func TestInfoSchemaClientErrors(t *testing.T) { errno.IncrementError(1365, "root", "localhost") tk.MustExec("CREATE USER 'infoschematest'@'localhost'") - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "infoschematest", Hostname: "localhost"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "infoschematest", Hostname: "localhost"}, nil, nil)) err := tk.QueryToErr("SELECT * FROM information_schema.client_errors_summary_global") require.Equal(t, "[planner:1227]Access denied; you need (at least one of) the PROCESS privilege(s) for this operation", err.Error()) @@ -1486,7 +1486,7 @@ func TestInfoSchemaDeadlockPrivilege(t *testing.T) { tk := newTestKitWithRoot(t, store) tk.MustExec("create user 'testuser'@'localhost'") - require.True(t, tk.Session().Auth(&auth.UserIdentity{ + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{ Username: "testuser", Hostname: "localhost", }, nil, nil)) @@ -1497,7 +1497,7 @@ func TestInfoSchemaDeadlockPrivilege(t *testing.T) { tk = newTestKitWithRoot(t, store) tk.MustExec("create user 'testuser2'@'localhost'") tk.MustExec("grant process on *.* to 'testuser2'@'localhost'") - require.True(t, tk.Session().Auth(&auth.UserIdentity{ + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{ Username: "testuser2", Hostname: "localhost", }, nil, nil)) diff --git a/parser/auth/caching_sha2.go b/parser/auth/caching_sha2.go index ff405b5dde14a..b7166d201ea08 100644 --- a/parser/auth/caching_sha2.go +++ b/parser/auth/caching_sha2.go @@ -180,7 +180,7 @@ func sha256crypt(plaintext string, salt []byte, iterations int) string { return buf.String() } -// CheckShaPassword is to checks if a MySQL style caching_sha2 authentication string matches a password +// CheckShaPassword is to check if a MySQL style caching_sha2 authentication string matches a password func CheckShaPassword(pwhash []byte, password string) (bool, error) { pwhashParts := bytes.Split(pwhash, []byte("$")) if len(pwhashParts) != 4 { diff --git a/planner/core/binary_plan_test.go b/planner/core/binary_plan_test.go index 2377235ecab16..b7c047253c6db 100644 --- a/planner/core/binary_plan_test.go +++ b/planner/core/binary_plan_test.go @@ -150,7 +150,7 @@ func TestBinaryPlanInExplainAndSlowLog(t *testing.T) { func TestBinaryPlanSwitch(t *testing.T) { store := testkit.CreateMockStore(t) tk := testkit.NewTestKit(t, store) - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "root", Hostname: "%"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "root", Hostname: "%"}, nil, nil)) originCfg := config.GetGlobalConfig() newCfg := *originCfg @@ -220,7 +220,7 @@ func TestBinaryPlanSwitch(t *testing.T) { func TestTooLongBinaryPlan(t *testing.T) { store := testkit.CreateMockStore(t) tk := testkit.NewTestKit(t, store) - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "root", Hostname: "%"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "root", Hostname: "%"}, nil, nil)) originCfg := config.GetGlobalConfig() newCfg := *originCfg @@ -282,7 +282,7 @@ func TestTooLongBinaryPlan(t *testing.T) { func TestLongBinaryPlan(t *testing.T) { store := testkit.CreateMockStore(t) tk := testkit.NewTestKit(t, store) - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "root", Hostname: "%"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "root", Hostname: "%"}, nil, nil)) originCfg := config.GetGlobalConfig() newCfg := *originCfg @@ -337,7 +337,7 @@ func TestLongBinaryPlan(t *testing.T) { func TestBinaryPlanOfPreparedStmt(t *testing.T) { store := testkit.CreateMockStore(t) tk := testkit.NewTestKit(t, store) - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "root", Hostname: "%"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "root", Hostname: "%"}, nil, nil)) originCfg := config.GetGlobalConfig() newCfg := *originCfg @@ -500,7 +500,7 @@ func TestInvalidDecodeBinaryPlan(t *testing.T) { func TestUnnecessaryBinaryPlanInSlowLog(t *testing.T) { store := testkit.CreateMockStore(t) tk := testkit.NewTestKit(t, store) - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "root", Hostname: "%"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "root", Hostname: "%"}, nil, nil)) originCfg := config.GetGlobalConfig() newCfg := *originCfg diff --git a/planner/core/integration_partition_test.go b/planner/core/integration_partition_test.go index 0bed9f1eb7709..e8c53739d2819 100644 --- a/planner/core/integration_partition_test.go +++ b/planner/core/integration_partition_test.go @@ -560,7 +560,7 @@ func TestListPartitionPrivilege(t *testing.T) { se, err := session.CreateSession4Test(store) require.NoError(t, err) - require.True(t, se.Auth(&auth.UserIdentity{Username: "root", Hostname: "%"}, nil, nil)) + require.NoError(t, se.Auth(&auth.UserIdentity{Username: "root", Hostname: "%"}, nil, nil)) tk.SetSession(se) tk.MustExec("create database list_partition_pri") tk.MustExec("use list_partition_pri") @@ -574,7 +574,7 @@ func TestListPartitionPrivilege(t *testing.T) { tk1 := testkit.NewTestKit(t, store) se, err = session.CreateSession4Test(store) require.NoError(t, err) - require.True(t, se.Auth(&auth.UserIdentity{Username: "priv_test", Hostname: "%"}, nil, nil)) + require.NoError(t, se.Auth(&auth.UserIdentity{Username: "priv_test", Hostname: "%"}, nil, nil)) tk1.SetSession(se) tk1.MustExec(`use list_partition_pri`) err = tk1.ExecToErr(`alter table tlist truncate partition p0`) diff --git a/planner/core/integration_test.go b/planner/core/integration_test.go index c122e592136bc..9372533fb87ed 100644 --- a/planner/core/integration_test.go +++ b/planner/core/integration_test.go @@ -4097,7 +4097,7 @@ func TestCreateViewIsolationRead(t *testing.T) { store := testkit.CreateMockStore(t) se, err := session.CreateSession4Test(store) require.NoError(t, err) - require.True(t, se.Auth(&auth.UserIdentity{Username: "root", Hostname: "%"}, nil, nil)) + require.NoError(t, se.Auth(&auth.UserIdentity{Username: "root", Hostname: "%"}, nil, nil)) tk := testkit.NewTestKit(t, store) tk.SetSession(se) @@ -7015,7 +7015,7 @@ func TestLeftShiftPushDownToTiFlash(t *testing.T) { func TestIssue36609(t *testing.T) { store := testkit.CreateMockStore(t) tk := testkit.NewTestKit(t, store) - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "root", Hostname: "%"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "root", Hostname: "%"}, nil, nil)) tk.MustExec("use test") tk.MustExec("create table t1(a int, b int, c int, d int, index ia(a), index ib(b), index ic(c), index id(d))") tk.MustExec("create table t2(a int, b int, c int, d int, index ia(a), index ib(b), index ic(c), index id(d))") diff --git a/planner/core/prepare_test.go b/planner/core/prepare_test.go index 10d5dd454a8ed..3fb9c09f31a0d 100644 --- a/planner/core/prepare_test.go +++ b/planner/core/prepare_test.go @@ -436,7 +436,7 @@ func TestPrepareCache(t *testing.T) { // user u_tp userSess := newSession(t, store, "test") - require.True(t, userSess.Auth(&auth.UserIdentity{Username: "u_tp", Hostname: "localhost"}, nil, nil)) + require.NoError(t, userSess.Auth(&auth.UserIdentity{Username: "u_tp", Hostname: "localhost"}, nil, nil)) mustExec(t, userSess, `prepare ps_stp_r from 'select * from tp where c1 > ?'`) mustExec(t, userSess, `set @p2 = 2`) tk.SetSession(userSess) @@ -1799,7 +1799,7 @@ func TestIssue18066(t *testing.T) { tk := testkit.NewTestKit(t, store) tk.MustExec(`set tidb_enable_prepared_plan_cache=1`) tk.RefreshConnectionID() - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "root", Hostname: "%"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "root", Hostname: "%"}, nil, nil)) tk.MustExec("use test") tk.MustExec("drop table if exists t") diff --git a/privilege/privilege.go b/privilege/privilege.go index af5ff9924ffe9..013329b655972 100644 --- a/privilege/privilege.go +++ b/privilege/privilege.go @@ -60,7 +60,7 @@ type Manager interface { // ConnectionVerification verifies user privilege for connection. // Requires exact match on user name and host name. - ConnectionVerification(user, host string, auth, salt []byte, tlsState *tls.ConnectionState) bool + ConnectionVerification(user, host string, auth, salt []byte, tlsState *tls.ConnectionState) error // GetAuthWithoutVerification uses to get auth name without verification. // Requires exact match on user name and host name. diff --git a/privilege/privileges/errors.go b/privilege/privileges/errors.go index e1f995840771f..e7a60842a9987 100644 --- a/privilege/privileges/errors.go +++ b/privilege/privileges/errors.go @@ -24,4 +24,6 @@ var ( errInvalidPrivilegeType = dbterror.ClassPrivilege.NewStd(mysql.ErrInvalidPrivilegeType) ErrNonexistingGrant = dbterror.ClassPrivilege.NewStd(mysql.ErrNonexistingGrant) errLoadPrivilege = dbterror.ClassPrivilege.NewStd(mysql.ErrLoadPrivilege) + errAccessDenied = dbterror.ClassPrivilege.NewStd(mysql.ErrAccessDenied) + errAccountHasBeenLocked = dbterror.ClassPrivilege.NewStd(mysql.ErrAccountHasBeenLocked) ) diff --git a/privilege/privileges/privileges.go b/privilege/privileges/privileges.go index e6633b03f1d5d..4388affaa0a0f 100644 --- a/privilege/privileges/privileges.go +++ b/privilege/privileges/privileges.go @@ -281,12 +281,15 @@ func (p *UserPrivileges) GetAuthWithoutVerification(user, host string) (success } // ConnectionVerification implements the Manager interface. -func (p *UserPrivileges) ConnectionVerification(user, host string, authentication, salt []byte, tlsState *tls.ConnectionState) (success bool) { +func (p *UserPrivileges) ConnectionVerification(user, host string, authentication, salt []byte, tlsState *tls.ConnectionState) error { + hasPassword := "YES" + if len(authentication) == 0 { + hasPassword = "NO" + } if SkipWithGrant { p.user = user p.host = host - success = true - return + return nil } mysqlPriv := p.Handle.Get() @@ -294,7 +297,7 @@ func (p *UserPrivileges) ConnectionVerification(user, host string, authenticatio if record == nil { logutil.BgLogger().Error("get user privilege record fail", zap.String("user", user), zap.String("host", host)) - return + return errAccessDenied.FastGenByArgs(user, host, hasPassword) } globalPriv := mysqlPriv.matchGlobalPriv(user, host) @@ -302,36 +305,32 @@ func (p *UserPrivileges) ConnectionVerification(user, host string, authenticatio if !p.checkSSL(globalPriv, tlsState) { logutil.BgLogger().Error("global priv check ssl fail", zap.String("user", user), zap.String("host", host)) - success = false - return + return errAccessDenied.FastGenByArgs(user, host, hasPassword) } } // Login a locked account is not allowed. locked := record.AccountLocked if locked { - logutil.BgLogger().Error("try to login a locked account", - zap.String("user", user), zap.String("host", host)) - success = false - return + logutil.BgLogger().Error(fmt.Sprintf("Access denied for user '%s'@'%s'. Account is locked.", user, host)) + return errAccountHasBeenLocked.FastGenByArgs(user, host) } pwd := record.AuthenticationString if !p.isValidHash(record) { - return + return errAccessDenied.FastGenByArgs(user, host, hasPassword) } // empty password if len(pwd) == 0 && len(authentication) == 0 { p.user = user p.host = record.Host - success = true - return + return errAccessDenied.FastGenByArgs(user, host, hasPassword) } if len(pwd) == 0 || len(authentication) == 0 { if record.AuthPlugin != mysql.AuthSocket { - return + return errAccessDenied.FastGenByArgs(user, host, hasPassword) } } @@ -339,11 +338,11 @@ func (p *UserPrivileges) ConnectionVerification(user, host string, authenticatio hpwd, err := auth.DecodePassword(pwd) if err != nil { logutil.BgLogger().Error("decode password string failed", zap.Error(err)) - return + return errAccessDenied.FastGenByArgs(user, host, hasPassword) } if !auth.CheckScrambledPassword(salt, hpwd, authentication) { - return + return errAccessDenied.FastGenByArgs(user, host, hasPassword) } } else if record.AuthPlugin == mysql.AuthCachingSha2Password { authok, err := auth.CheckShaPassword([]byte(pwd), string(authentication)) @@ -352,24 +351,23 @@ func (p *UserPrivileges) ConnectionVerification(user, host string, authenticatio } if !authok { - return + return errAccessDenied.FastGenByArgs(user, host, hasPassword) } } else if record.AuthPlugin == mysql.AuthSocket { if string(authentication) != user && string(authentication) != pwd { logutil.BgLogger().Error("Failed socket auth", zap.String("user", user), zap.String("socket_user", string(authentication)), zap.String("authentication_string", pwd)) - return + return errAccessDenied.FastGenByArgs(user, host, hasPassword) } } else { logutil.BgLogger().Error("unknown authentication plugin", zap.String("user", user), zap.String("plugin", record.AuthPlugin)) - return + return errAccessDenied.FastGenByArgs(user, host, hasPassword) } p.user = user p.host = record.Host - success = true - return + return nil } type checkResult int diff --git a/privilege/privileges/privileges_test.go b/privilege/privileges/privileges_test.go index df4b4d273f1e6..3f65d5a501746 100644 --- a/privilege/privileges/privileges_test.go +++ b/privilege/privileges/privileges_test.go @@ -55,7 +55,7 @@ func TestCheckDBPrivilege(t *testing.T) { tk := testkit.NewTestKit(t, store) activeRoles := make([]*auth.RoleIdentity, 0) - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "testcheck", Hostname: "localhost"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "testcheck", Hostname: "localhost"}, nil, nil)) pc := privilege.GetPrivilegeManager(tk.Session()) require.False(t, pc.RequestVerification(activeRoles, "test", "", "", mysql.SelectPriv)) @@ -69,7 +69,7 @@ func TestCheckDBPrivilege(t *testing.T) { activeRoles = append(activeRoles, &auth.RoleIdentity{Username: "testcheck", Hostname: "localhost"}) rootTk.MustExec(`GRANT 'testcheck'@'localhost' TO 'testcheck_tmp'@'localhost';`) tk2 := testkit.NewTestKit(t, store) - require.True(t, tk2.Session().Auth(&auth.UserIdentity{Username: "testcheck_tmp", Hostname: "localhost"}, nil, nil)) + require.NoError(t, tk2.Session().Auth(&auth.UserIdentity{Username: "testcheck_tmp", Hostname: "localhost"}, nil, nil)) pc = privilege.GetPrivilegeManager(tk2.Session()) require.True(t, pc.RequestVerification(activeRoles, "test", "", "", mysql.SelectPriv)) require.True(t, pc.RequestVerification(activeRoles, "test", "", "", mysql.UpdatePriv)) @@ -85,7 +85,7 @@ func TestCheckPointGetDBPrivilege(t *testing.T) { rootTk.MustExec(`insert into test2.t(id, v) values(1, 1)`) tk := testkit.NewTestKit(t, store) - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "tester", Hostname: "localhost"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "tester", Hostname: "localhost"}, nil, nil)) tk.MustExec(`use test;`) err := tk.ExecToErr(`select * from test2.t where id = 1`) require.True(t, terror.ErrorEqual(err, core.ErrTableaccessDenied)) @@ -107,7 +107,7 @@ func TestCheckExchangePartitionDBPrivilege(t *testing.T) { rootTk.MustExec(`create table nt (a varchar(3));`) tk := testkit.NewTestKit(t, store) - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "tester", Hostname: "localhost"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "tester", Hostname: "localhost"}, nil, nil)) tk.MustExec("use test") rootTk.MustExec(`GRANT CREATE ON test.* TO 'tester'@'localhost';`) @@ -140,7 +140,7 @@ func TestIssue22946(t *testing.T) { rootTk.MustExec("grant select on test.* to delTest@'localhost';") tk := testkit.NewTestKit(t, store) - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "delTest", Hostname: "localhost"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "delTest", Hostname: "localhost"}, nil, nil)) tk.MustExec(`delete from db1.a as A where exists(select 1 from db2.b as B where A.id = B.id);`) rootTk.MustExec("use db1;") err := tk.ExecToErr("delete from test.a as A;") @@ -156,7 +156,7 @@ func TestCheckTablePrivilege(t *testing.T) { tk := testkit.NewTestKit(t, store) activeRoles := make([]*auth.RoleIdentity, 0) - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "test1", Hostname: "localhost"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "test1", Hostname: "localhost"}, nil, nil)) pc := privilege.GetPrivilegeManager(tk.Session()) require.False(t, pc.RequestVerification(activeRoles, "test", "test", "", mysql.SelectPriv)) @@ -171,7 +171,7 @@ func TestCheckTablePrivilege(t *testing.T) { activeRoles = append(activeRoles, &auth.RoleIdentity{Username: "test1", Hostname: "localhost"}) tk2 := testkit.NewTestKit(t, store) rootTk.MustExec(`GRANT 'test1'@'localhost' TO 'test1_tmp'@'localhost';`) - require.True(t, tk2.Session().Auth(&auth.UserIdentity{Username: "test1_tmp", Hostname: "localhost"}, nil, nil)) + require.NoError(t, tk2.Session().Auth(&auth.UserIdentity{Username: "test1_tmp", Hostname: "localhost"}, nil, nil)) pc2 := privilege.GetPrivilegeManager(tk2.Session()) require.True(t, pc2.RequestVerification(activeRoles, "test", "test", "", mysql.SelectPriv)) require.True(t, pc2.RequestVerification(activeRoles, "test", "test", "", mysql.UpdatePriv)) @@ -191,7 +191,7 @@ func TestCheckViewPrivilege(t *testing.T) { tk := testkit.NewTestKit(t, store) activeRoles := make([]*auth.RoleIdentity, 0) - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "vuser", Hostname: "localhost"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "vuser", Hostname: "localhost"}, nil, nil)) pc := privilege.GetPrivilegeManager(tk.Session()) require.False(t, pc.RequestVerification(activeRoles, "test", "v", "", mysql.SelectPriv)) @@ -212,7 +212,7 @@ func TestCheckPrivilegeWithRoles(t *testing.T) { rootTk.MustExec(`GRANT r_1, r_2, r_3 TO 'test_role'@'localhost';`) tk := testkit.NewTestKit(t, store) - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "test_role", Hostname: "localhost"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "test_role", Hostname: "localhost"}, nil, nil)) tk.MustExec(`SET ROLE r_1, r_2;`) rootTk.MustExec(`SET DEFAULT ROLE r_1 TO 'test_role'@'localhost';`) // test bogus role for current user. @@ -432,11 +432,11 @@ func TestErrorMessage(t *testing.T) { // The session.Auth() func will populate the AuthUsername and AuthHostname fields. // We don't have to explicitly specify them. - require.True(t, wildTk.Session().Auth(&auth.UserIdentity{Username: "wildcard", Hostname: "192.168.1.1"}, nil, nil)) + require.NoError(t, wildTk.Session().Auth(&auth.UserIdentity{Username: "wildcard", Hostname: "192.168.1.1"}, nil, nil)) require.EqualError(t, wildTk.ExecToErr("use mysql;"), "[executor:1044]Access denied for user 'wildcard'@'%' to database 'mysql'") specificTk := testkit.NewTestKit(t, store) - require.True(t, specificTk.Session().Auth(&auth.UserIdentity{Username: "specifichost", Hostname: "192.168.1.1"}, nil, nil)) + require.NoError(t, specificTk.Session().Auth(&auth.UserIdentity{Username: "specifichost", Hostname: "192.168.1.1"}, nil, nil)) require.EqualError(t, specificTk.ExecToErr("use mysql;"), "[executor:1044]Access denied for user 'specifichost'@'192.168.1.1' to database 'mysql'") } @@ -462,12 +462,12 @@ func TestDropTablePrivileges(t *testing.T) { ctx, _ := tk.Session().(sessionctx.Context) tk.MustExec(`CREATE TABLE todrop(c int);`) // ctx.GetSessionVars().User = "root@localhost" - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "root", Hostname: "localhost"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "root", Hostname: "localhost"}, nil, nil)) tk.MustExec(`CREATE USER 'drop'@'localhost';`) tk.MustExec(`GRANT Select ON test.todrop TO 'drop'@'localhost';`) // ctx.GetSessionVars().User = "drop@localhost" - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "drop", Hostname: "localhost"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "drop", Hostname: "localhost"}, nil, nil)) tk.MustExec(`SELECT * FROM todrop;`) require.Error(t, tk.ExecToErr("DROP TABLE todrop;")) @@ -490,12 +490,12 @@ func TestSetPasswdStmt(t *testing.T) { tk.MustExec("CREATE USER 'nobodyuser'") tk.MustExec("GRANT ALL ON *.* TO 'superuser'") - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "superuser", Hostname: "localhost", AuthUsername: "superuser", AuthHostname: "%"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "superuser", Hostname: "localhost", AuthUsername: "superuser", AuthHostname: "%"}, nil, nil)) tk.MustExec("SET PASSWORD for 'nobodyuser' = 'newpassword'") tk.MustExec("SET PASSWORD for 'nobodyuser' = ''") // low privileged user trying to set password for other user (fails) - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "nobodyuser", Hostname: "localhost", AuthUsername: "nobodyuser", AuthHostname: "%"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "nobodyuser", Hostname: "localhost", AuthUsername: "nobodyuser", AuthHostname: "%"}, nil, nil)) err := tk.ExecToErr("SET PASSWORD for 'superuser' = 'newpassword'") require.Error(t, err) } @@ -514,7 +514,7 @@ func TestAlterUserStmt(t *testing.T) { tk.MustExec("GRANT RESTRICTED_USER_ADMIN ON *.* TO semuser1, semuser2, semuser3") tk.MustExec("GRANT SYSTEM_USER ON *.* to semuser3") // user is both restricted + has SYSTEM_USER (or super) - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "superuser2", Hostname: "localhost"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "superuser2", Hostname: "localhost"}, nil, nil)) tk.MustExec("ALTER USER 'nobodyuser2' IDENTIFIED BY 'newpassword'") tk.MustExec("ALTER USER 'nobodyuser2' IDENTIFIED BY ''") @@ -523,7 +523,7 @@ func TestAlterUserStmt(t *testing.T) { // nobodyuser4 = FAIL (has SYSTEM_USER) // superuser2 = FAIL (has SYSTEM_USER privilege implied by SUPER) - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "nobodyuser2", Hostname: "localhost"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "nobodyuser2", Hostname: "localhost"}, nil, nil)) tk.MustExec("ALTER USER 'nobodyuser2' IDENTIFIED BY 'newpassword'") tk.MustExec("ALTER USER 'nobodyuser2' IDENTIFIED BY ''") tk.MustExec("ALTER USER 'nobodyuser3' IDENTIFIED BY ''") @@ -534,7 +534,7 @@ func TestAlterUserStmt(t *testing.T) { // Nobody3 has no privileges at all, but they can still alter their own password. // Any other user fails. - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "nobodyuser3", Hostname: "localhost"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "nobodyuser3", Hostname: "localhost"}, nil, nil)) tk.MustExec("ALTER USER 'nobodyuser3' IDENTIFIED BY ''") err = tk.ExecToErr("ALTER USER 'nobodyuser4' IDENTIFIED BY 'newpassword'") require.EqualError(t, err, "[planner:1227]Access denied; you need (at least one of) the CREATE USER privilege(s) for this operation") @@ -544,13 +544,13 @@ func TestAlterUserStmt(t *testing.T) { // Nobody5 doesn't explicitly have CREATE USER, but mysql also accepts UDPATE on mysql.user // as a substitute so it can modify nobody2 and nobody3 but not nobody4 - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "nobodyuser5", Hostname: "localhost"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "nobodyuser5", Hostname: "localhost"}, nil, nil)) tk.MustExec("ALTER USER 'nobodyuser2' IDENTIFIED BY ''") tk.MustExec("ALTER USER 'nobodyuser3' IDENTIFIED BY ''") err = tk.ExecToErr("ALTER USER 'nobodyuser4' IDENTIFIED BY 'newpassword'") require.EqualError(t, err, "[planner:1227]Access denied; you need (at least one of) the SYSTEM_USER or SUPER privilege(s) for this operation") - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "semuser1", Hostname: "localhost"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "semuser1", Hostname: "localhost"}, nil, nil)) tk.MustExec("ALTER USER 'semuser1' IDENTIFIED BY ''") tk.MustExec("ALTER USER 'semuser2' IDENTIFIED BY ''") tk.MustExec("ALTER USER 'semuser3' IDENTIFIED BY ''") @@ -565,17 +565,17 @@ func TestAlterUserStmt(t *testing.T) { // any request for UpdatePriv on mysql.user even if the privilege exists in the internal mysql.user table. // UpdatePriv on mysql.user - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "nobodyuser5", Hostname: "localhost"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "nobodyuser5", Hostname: "localhost"}, nil, nil)) err = tk.ExecToErr("ALTER USER 'nobodyuser2' IDENTIFIED BY 'newpassword'") require.EqualError(t, err, "[planner:1227]Access denied; you need (at least one of) the CREATE USER privilege(s) for this operation") // actual CreateUserPriv - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "nobodyuser2", Hostname: "localhost"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "nobodyuser2", Hostname: "localhost"}, nil, nil)) tk.MustExec("ALTER USER 'nobodyuser2' IDENTIFIED BY ''") tk.MustExec("ALTER USER 'nobodyuser3' IDENTIFIED BY ''") // UpdatePriv on mysql.user but also has RESTRICTED_TABLES_ADMIN - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "semuser1", Hostname: "localhost"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "semuser1", Hostname: "localhost"}, nil, nil)) tk.MustExec("ALTER USER 'nobodyuser2' IDENTIFIED BY ''") tk.MustExec("ALTER USER 'nobodyuser3' IDENTIFIED BY ''") @@ -585,10 +585,10 @@ func TestAlterUserStmt(t *testing.T) { tk.MustExec("ALTER USER 'semuser2' IDENTIFIED BY ''") tk.MustExec("ALTER USER 'semuser3' IDENTIFIED BY ''") - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "superuser2", Hostname: "localhost"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "superuser2", Hostname: "localhost"}, nil, nil)) err = tk.ExecToErr("ALTER USER 'semuser1' IDENTIFIED BY 'newpassword'") require.EqualError(t, err, "[planner:1227]Access denied; you need (at least one of) the RESTRICTED_USER_ADMIN privilege(s) for this operation") - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "semuser4", Hostname: "localhost"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "semuser4", Hostname: "localhost"}, nil, nil)) // has restricted_user_admin but not CREATE USER or (update on mysql.user + RESTRICTED_TABLES_ADMIN) tk.MustExec("ALTER USER 'semuser4' IDENTIFIED BY ''") // can modify self err = tk.ExecToErr("ALTER USER 'nobodyuser3' IDENTIFIED BY 'newpassword'") @@ -607,13 +607,13 @@ func TestSelectViewSecurity(t *testing.T) { ctx, _ := tk.Session().(sessionctx.Context) tk.MustExec(`CREATE TABLE viewsecurity(c int);`) // ctx.GetSessionVars().User = "root@localhost" - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "root", Hostname: "localhost"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "root", Hostname: "localhost"}, nil, nil)) tk.MustExec(`CREATE USER 'selectusr'@'localhost';`) tk.MustExec(`GRANT CREATE VIEW ON test.* TO 'selectusr'@'localhost';`) tk.MustExec(`GRANT SELECT ON test.viewsecurity TO 'selectusr'@'localhost';`) // ctx.GetSessionVars().User = "selectusr@localhost" - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "selectusr", Hostname: "localhost"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "selectusr", Hostname: "localhost"}, nil, nil)) tk.MustExec(`SELECT * FROM test.viewsecurity;`) tk.MustExec(`CREATE ALGORITHM = UNDEFINED SQL SECURITY DEFINER VIEW test.selectviewsecurity as select * FROM test.viewsecurity;`) @@ -728,15 +728,15 @@ func TestRoleAdminSecurity(t *testing.T) { tk.MustExec(`CREATE USER 'ar2'@'localhost';`) tk.MustExec(`GRANT ALL ON *.* to ar1@localhost`) defer func() { - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "root", Hostname: "%"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "root", Hostname: "%"}, nil, nil)) tk.MustExec("drop user 'ar1'@'localhost'") tk.MustExec("drop user 'ar2'@'localhost'") }() - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "ar1", Hostname: "localhost"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "ar1", Hostname: "localhost"}, nil, nil)) tk.MustExec(`create role r_test1@localhost`) - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "ar2", Hostname: "localhost"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "ar2", Hostname: "localhost"}, nil, nil)) err := tk.ExecToErr(`create role r_test2@localhost`) require.True(t, terror.ErrorEqual(err, core.ErrSpecificAccessDenied)) } @@ -767,7 +767,7 @@ func TestCheckCertBasedAuth(t *testing.T) { tk.MustExec(`CREATE USER 'r15_san_only_fail'@'localhost' require san 'URI:spiffe://mesh.pingcap.com/ns/timesh/sa/me2'`) defer func() { - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "root", Hostname: "%"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "root", Hostname: "%"}, nil, nil)) tk.MustExec("drop user 'r1'@'localhost'") tk.MustExec("drop user 'r2'@'localhost'") tk.MustExec("drop user 'r3'@'localhost'") @@ -786,27 +786,27 @@ func TestCheckCertBasedAuth(t *testing.T) { }() // test without ssl or ca - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "r1", Hostname: "localhost"}, nil, nil)) - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "r2", Hostname: "localhost"}, nil, nil)) - require.False(t, tk.Session().Auth(&auth.UserIdentity{Username: "r3", Hostname: "localhost"}, nil, nil)) - require.False(t, tk.Session().Auth(&auth.UserIdentity{Username: "r4", Hostname: "localhost"}, nil, nil)) - require.False(t, tk.Session().Auth(&auth.UserIdentity{Username: "r5", Hostname: "localhost"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "r1", Hostname: "localhost"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "r2", Hostname: "localhost"}, nil, nil)) + require.Error(t, tk.Session().Auth(&auth.UserIdentity{Username: "r3", Hostname: "localhost"}, nil, nil)) + require.Error(t, tk.Session().Auth(&auth.UserIdentity{Username: "r4", Hostname: "localhost"}, nil, nil)) + require.Error(t, tk.Session().Auth(&auth.UserIdentity{Username: "r5", Hostname: "localhost"}, nil, nil)) // test use ssl without ca tk.Session().GetSessionVars().TLSConnectionState = &tls.ConnectionState{VerifiedChains: nil} - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "r1", Hostname: "localhost"}, nil, nil)) - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "r2", Hostname: "localhost"}, nil, nil)) - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "r3", Hostname: "localhost"}, nil, nil)) - require.False(t, tk.Session().Auth(&auth.UserIdentity{Username: "r4", Hostname: "localhost"}, nil, nil)) - require.False(t, tk.Session().Auth(&auth.UserIdentity{Username: "r5", Hostname: "localhost"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "r1", Hostname: "localhost"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "r2", Hostname: "localhost"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "r3", Hostname: "localhost"}, nil, nil)) + require.Error(t, tk.Session().Auth(&auth.UserIdentity{Username: "r4", Hostname: "localhost"}, nil, nil)) + require.Error(t, tk.Session().Auth(&auth.UserIdentity{Username: "r5", Hostname: "localhost"}, nil, nil)) // test use ssl with signed but info wrong ca. tk.Session().GetSessionVars().TLSConnectionState = &tls.ConnectionState{VerifiedChains: [][]*x509.Certificate{{{}}}} - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "r1", Hostname: "localhost"}, nil, nil)) - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "r2", Hostname: "localhost"}, nil, nil)) - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "r3", Hostname: "localhost"}, nil, nil)) - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "r4", Hostname: "localhost"}, nil, nil)) - require.False(t, tk.Session().Auth(&auth.UserIdentity{Username: "r5", Hostname: "localhost"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "r1", Hostname: "localhost"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "r2", Hostname: "localhost"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "r3", Hostname: "localhost"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "r4", Hostname: "localhost"}, nil, nil)) + require.Error(t, tk.Session().Auth(&auth.UserIdentity{Username: "r5", Hostname: "localhost"}, nil, nil)) // test a all pass case tk.Session().GetSessionVars().TLSConnectionState = connectionState( @@ -836,16 +836,16 @@ func TestCheckCertBasedAuth(t *testing.T) { require.NoError(t, err) cert.URIs = append(cert.URIs, &url) }) - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "r1", Hostname: "localhost"}, nil, nil)) - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "r2", Hostname: "localhost"}, nil, nil)) - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "r3", Hostname: "localhost"}, nil, nil)) - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "r4", Hostname: "localhost"}, nil, nil)) - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "r5", Hostname: "localhost"}, nil, nil)) - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "r14_san_only_pass", Hostname: "localhost"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "r1", Hostname: "localhost"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "r2", Hostname: "localhost"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "r3", Hostname: "localhost"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "r4", Hostname: "localhost"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "r5", Hostname: "localhost"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "r14_san_only_pass", Hostname: "localhost"}, nil, nil)) // test require but give nothing tk.Session().GetSessionVars().TLSConnectionState = nil - require.False(t, tk.Session().Auth(&auth.UserIdentity{Username: "r5", Hostname: "localhost"}, nil, nil)) + require.Error(t, tk.Session().Auth(&auth.UserIdentity{Username: "r5", Hostname: "localhost"}, nil, nil)) // test mismatch cipher tk.Session().GetSessionVars().TLSConnectionState = connectionState( @@ -870,9 +870,9 @@ func TestCheckCertBasedAuth(t *testing.T) { }, }, tls.TLS_AES_256_GCM_SHA384) - require.False(t, tk.Session().Auth(&auth.UserIdentity{Username: "r5", Hostname: "localhost"}, nil, nil)) - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "r6", Hostname: "localhost"}, nil, nil)) // not require cipher - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "r11_cipher_only", Hostname: "localhost"}, nil, nil)) + require.Error(t, tk.Session().Auth(&auth.UserIdentity{Username: "r5", Hostname: "localhost"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "r6", Hostname: "localhost"}, nil, nil)) // not require cipher + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "r11_cipher_only", Hostname: "localhost"}, nil, nil)) // test only subject or only issuer tk.Session().GetSessionVars().TLSConnectionState = connectionState( @@ -897,7 +897,7 @@ func TestCheckCertBasedAuth(t *testing.T) { }, }, tls.TLS_AES_128_GCM_SHA256) - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "r7_issuer_only", Hostname: "localhost"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "r7_issuer_only", Hostname: "localhost"}, nil, nil)) tk.Session().GetSessionVars().TLSConnectionState = connectionState( pkix.Name{ Names: []pkix.AttributeTypeAndValue{ @@ -920,7 +920,7 @@ func TestCheckCertBasedAuth(t *testing.T) { }, }, tls.TLS_AES_128_GCM_SHA256) - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "r8_subject_only", Hostname: "localhost"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "r8_subject_only", Hostname: "localhost"}, nil, nil)) // test disorder issuer or subject tk.Session().GetSessionVars().TLSConnectionState = connectionState( @@ -938,7 +938,7 @@ func TestCheckCertBasedAuth(t *testing.T) { }, }, tls.TLS_AES_128_GCM_SHA256) - require.False(t, tk.Session().Auth(&auth.UserIdentity{Username: "r9_subject_disorder", Hostname: "localhost"}, nil, nil)) + require.Error(t, tk.Session().Auth(&auth.UserIdentity{Username: "r9_subject_disorder", Hostname: "localhost"}, nil, nil)) tk.Session().GetSessionVars().TLSConnectionState = connectionState( pkix.Name{ Names: []pkix.AttributeTypeAndValue{ @@ -954,14 +954,14 @@ func TestCheckCertBasedAuth(t *testing.T) { Names: []pkix.AttributeTypeAndValue{}, }, tls.TLS_AES_128_GCM_SHA256) - require.False(t, tk.Session().Auth(&auth.UserIdentity{Username: "r10_issuer_disorder", Hostname: "localhost"}, nil, nil)) + require.Error(t, tk.Session().Auth(&auth.UserIdentity{Username: "r10_issuer_disorder", Hostname: "localhost"}, nil, nil)) // test mismatch san - require.False(t, tk.Session().Auth(&auth.UserIdentity{Username: "r15_san_only_fail", Hostname: "localhost"}, nil, nil)) + require.Error(t, tk.Session().Auth(&auth.UserIdentity{Username: "r15_san_only_fail", Hostname: "localhost"}, nil, nil)) // test old data and broken data - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "r12_old_tidb_user", Hostname: "localhost"}, nil, nil)) - require.False(t, tk.Session().Auth(&auth.UserIdentity{Username: "r13_broken_user", Hostname: "localhost"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "r12_old_tidb_user", Hostname: "localhost"}, nil, nil)) + require.Error(t, tk.Session().Auth(&auth.UserIdentity{Username: "r13_broken_user", Hostname: "localhost"}, nil, nil)) } func connectionState(issuer, subject pkix.Name, cipher uint16, opt ...func(c *x509.Certificate)) *tls.ConnectionState { @@ -984,13 +984,13 @@ func TestCheckAuthenticate(t *testing.T) { tk.MustExec(`CREATE USER 'u3@example.com'@'localhost';`) tk.MustExec(`CREATE USER u4@localhost;`) - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "u1", Hostname: "localhost"}, nil, nil)) - require.False(t, tk.Session().Auth(&auth.UserIdentity{Username: "u2", Hostname: "localhost"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "u1", Hostname: "localhost"}, nil, nil)) + require.Error(t, tk.Session().Auth(&auth.UserIdentity{Username: "u2", Hostname: "localhost"}, nil, nil)) salt := []byte{85, 92, 45, 22, 58, 79, 107, 6, 122, 125, 58, 80, 12, 90, 103, 32, 90, 10, 74, 82} authentication := []byte{24, 180, 183, 225, 166, 6, 81, 102, 70, 248, 199, 143, 91, 204, 169, 9, 161, 171, 203, 33} - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "u2", Hostname: "localhost"}, authentication, salt)) - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "u3@example.com", Hostname: "localhost"}, nil, nil)) - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "u4", Hostname: "localhost"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "u2", Hostname: "localhost"}, authentication, salt)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "u3@example.com", Hostname: "localhost"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "u4", Hostname: "localhost"}, nil, nil)) tk1 := testkit.NewTestKit(t, store) tk1.MustExec("drop user 'u1'@'localhost'") @@ -998,18 +998,18 @@ func TestCheckAuthenticate(t *testing.T) { tk1.MustExec("drop user 'u3@example.com'@'localhost'") tk1.MustExec("drop user u4@localhost") - require.False(t, tk.Session().Auth(&auth.UserIdentity{Username: "u1", Hostname: "localhost"}, nil, nil)) - require.False(t, tk.Session().Auth(&auth.UserIdentity{Username: "u2", Hostname: "localhost"}, nil, nil)) - require.False(t, tk.Session().Auth(&auth.UserIdentity{Username: "u3@example.com", Hostname: "localhost"}, nil, nil)) - require.False(t, tk.Session().Auth(&auth.UserIdentity{Username: "u4", Hostname: "localhost"}, nil, nil)) + require.Error(t, tk.Session().Auth(&auth.UserIdentity{Username: "u1", Hostname: "localhost"}, nil, nil)) + require.Error(t, tk.Session().Auth(&auth.UserIdentity{Username: "u2", Hostname: "localhost"}, nil, nil)) + require.Error(t, tk.Session().Auth(&auth.UserIdentity{Username: "u3@example.com", Hostname: "localhost"}, nil, nil)) + require.Error(t, tk.Session().Auth(&auth.UserIdentity{Username: "u4", Hostname: "localhost"}, nil, nil)) tk2 := testkit.NewTestKit(t, store) tk2.MustExec("create role 'r1'@'localhost'") tk2.MustExec("create role 'r2'@'localhost'") tk2.MustExec("create role 'r3@example.com'@'localhost'") - require.False(t, tk.Session().Auth(&auth.UserIdentity{Username: "r1", Hostname: "localhost"}, nil, nil)) - require.False(t, tk.Session().Auth(&auth.UserIdentity{Username: "r2", Hostname: "localhost"}, nil, nil)) - require.False(t, tk.Session().Auth(&auth.UserIdentity{Username: "r3@example.com", Hostname: "localhost"}, nil, nil)) + require.Error(t, tk.Session().Auth(&auth.UserIdentity{Username: "r1", Hostname: "localhost"}, nil, nil)) + require.Error(t, tk.Session().Auth(&auth.UserIdentity{Username: "r2", Hostname: "localhost"}, nil, nil)) + require.Error(t, tk.Session().Auth(&auth.UserIdentity{Username: "r3@example.com", Hostname: "localhost"}, nil, nil)) tk1.MustExec("drop user 'r1'@'localhost'") tk1.MustExec("drop user 'r2'@'localhost'") @@ -1025,34 +1025,34 @@ func TestUseDB(t *testing.T) { tk.MustExec("CREATE USER 'usenobody'") tk.MustExec("GRANT ALL ON *.* TO 'usesuper'") // without grant option - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "usesuper", Hostname: "localhost", AuthUsername: "usesuper", AuthHostname: "%"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "usesuper", Hostname: "localhost", AuthUsername: "usesuper", AuthHostname: "%"}, nil, nil)) require.Error(t, tk.ExecToErr("GRANT SELECT ON mysql.* TO 'usenobody'")) // with grant option tk = testkit.NewTestKit(t, store) // high privileged user tk.MustExec("GRANT ALL ON *.* TO 'usesuper' WITH GRANT OPTION") - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "usesuper", Hostname: "localhost", AuthUsername: "usesuper", AuthHostname: "%"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "usesuper", Hostname: "localhost", AuthUsername: "usesuper", AuthHostname: "%"}, nil, nil)) tk.MustExec("use mysql") // low privileged user - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "usenobody", Hostname: "localhost", AuthUsername: "usenobody", AuthHostname: "%"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "usenobody", Hostname: "localhost", AuthUsername: "usenobody", AuthHostname: "%"}, nil, nil)) err := tk.ExecToErr("use mysql") require.Error(t, err) // try again after privilege granted - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "usesuper", Hostname: "localhost", AuthUsername: "usesuper", AuthHostname: "%"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "usesuper", Hostname: "localhost", AuthUsername: "usesuper", AuthHostname: "%"}, nil, nil)) tk.MustExec("GRANT SELECT ON mysql.* TO 'usenobody'") - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "usenobody", Hostname: "localhost", AuthUsername: "usenobody", AuthHostname: "%"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "usenobody", Hostname: "localhost", AuthUsername: "usenobody", AuthHostname: "%"}, nil, nil)) tk.MustExec("use mysql") // test `use db` for role. - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "usesuper", Hostname: "localhost", AuthUsername: "usesuper", AuthHostname: "%"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "usesuper", Hostname: "localhost", AuthUsername: "usesuper", AuthHostname: "%"}, nil, nil)) tk.MustExec(`CREATE DATABASE app_db`) tk.MustExec(`CREATE ROLE 'app_developer'`) tk.MustExec(`GRANT ALL ON app_db.* TO 'app_developer'`) tk.MustExec(`CREATE USER 'dev'@'localhost'`) tk.MustExec(`GRANT 'app_developer' TO 'dev'@'localhost'`) tk.MustExec(`SET DEFAULT ROLE 'app_developer' TO 'dev'@'localhost'`) - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "dev", Hostname: "localhost", AuthUsername: "dev", AuthHostname: "localhost"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "dev", Hostname: "localhost", AuthUsername: "dev", AuthHostname: "localhost"}, nil, nil)) tk.MustExec("use app_db") err = tk.ExecToErr("use mysql") require.Error(t, err) @@ -1067,19 +1067,19 @@ func TestRevokePrivileges(t *testing.T) { tk.MustExec("GRANT ALL ON *.* TO 'hasgrant'") tk.MustExec("GRANT ALL ON mysql.* TO 'withoutgrant'") // Without grant option - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "hasgrant", Hostname: "localhost", AuthUsername: "hasgrant", AuthHostname: "%"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "hasgrant", Hostname: "localhost", AuthUsername: "hasgrant", AuthHostname: "%"}, nil, nil)) require.Error(t, tk.ExecToErr("REVOKE SELECT ON mysql.* FROM 'withoutgrant'")) // With grant option tk = testkit.NewTestKit(t, store) tk.MustExec("GRANT ALL ON *.* TO 'hasgrant' WITH GRANT OPTION") - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "hasgrant", Hostname: "localhost", AuthUsername: "hasgrant", AuthHostname: "%"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "hasgrant", Hostname: "localhost", AuthUsername: "hasgrant", AuthHostname: "%"}, nil, nil)) tk.MustExec("REVOKE SELECT ON mysql.* FROM 'withoutgrant'") tk.MustExec("REVOKE ALL ON mysql.* FROM withoutgrant") // For issue https://github.com/pingcap/tidb/issues/23850 tk.MustExec("CREATE USER u4") tk.MustExec("GRANT ALL ON *.* TO u4 WITH GRANT OPTION") - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "u4", Hostname: "localhost", AuthUsername: "u4", AuthHostname: "%"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "u4", Hostname: "localhost", AuthUsername: "u4", AuthHostname: "%"}, nil, nil)) tk.MustExec("REVOKE ALL ON *.* FROM CURRENT_USER()") } @@ -1090,10 +1090,10 @@ func TestSetGlobal(t *testing.T) { tk.MustExec(`CREATE USER setglobal_b@localhost`) tk.MustExec(`GRANT SUPER ON *.* to setglobal_a@localhost`) - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "setglobal_a", Hostname: "localhost"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "setglobal_a", Hostname: "localhost"}, nil, nil)) tk.MustExec(`set global innodb_commit_concurrency=16`) - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "setglobal_b", Hostname: "localhost"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "setglobal_b", Hostname: "localhost"}, nil, nil)) err := tk.ExecToErr(`set global innodb_commit_concurrency=16`) require.True(t, terror.ErrorEqual(err, core.ErrSpecificAccessDenied)) } @@ -1106,20 +1106,20 @@ func TestCreateDropUser(t *testing.T) { tk.MustExec(`GRANT ALL ON *.* to tcd2 WITH GRANT OPTION`) // should fail - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "tcd1", Hostname: "localhost", AuthUsername: "tcd1", AuthHostname: "%"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "tcd1", Hostname: "localhost", AuthUsername: "tcd1", AuthHostname: "%"}, nil, nil)) err := tk.ExecToErr(`CREATE USER acdc`) require.True(t, terror.ErrorEqual(err, core.ErrSpecificAccessDenied)) err = tk.ExecToErr(`DROP USER tcd2`) require.True(t, terror.ErrorEqual(err, core.ErrSpecificAccessDenied)) // should pass - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "tcd2", Hostname: "localhost", AuthUsername: "tcd2", AuthHostname: "%"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "tcd2", Hostname: "localhost", AuthUsername: "tcd2", AuthHostname: "%"}, nil, nil)) tk.MustExec(`DROP USER tcd1`) tk.MustExec(`CREATE USER tcd1`) // should pass tk.MustExec(`GRANT tcd2 TO tcd1`) - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "tcd1", Hostname: "localhost", AuthUsername: "tcd1", AuthHostname: "%"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "tcd1", Hostname: "localhost", AuthUsername: "tcd1", AuthHostname: "%"}, nil, nil)) tk.MustExec(`SET ROLE tcd2;`) tk.MustExec(`CREATE USER tcd3`) tk.MustExec(`DROP USER tcd3`) @@ -1137,10 +1137,10 @@ func TestConfigPrivilege(t *testing.T) { tk.MustExec(`GRANT ALL ON *.* to tcd2`) tk.MustExec(`REVOKE CONFIG ON *.* FROM tcd2`) - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "tcd1", Hostname: "localhost", AuthHostname: "tcd1", AuthUsername: "%"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "tcd1", Hostname: "localhost", AuthHostname: "tcd1", AuthUsername: "%"}, nil, nil)) tk.MustExec(`SHOW CONFIG`) tk.MustExec(`SET CONFIG TIKV testkey="testval"`) - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "tcd2", Hostname: "localhost", AuthHostname: "tcd2", AuthUsername: "%"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "tcd2", Hostname: "localhost", AuthHostname: "tcd2", AuthUsername: "%"}, nil, nil)) err := tk.ExecToErr(`SHOW CONFIG`) require.Error(t, err) require.Regexp(t, "you need \\(at least one of\\) the CONFIG privilege\\(s\\) for this operation$", err.Error()) @@ -1158,12 +1158,12 @@ func TestShowCreateTable(t *testing.T) { tk.MustExec(`GRANT select ON mysql.* to tsct2`) // should fail - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "tsct1", Hostname: "localhost", AuthUsername: "tsct1", AuthHostname: "%"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "tsct1", Hostname: "localhost", AuthUsername: "tsct1", AuthHostname: "%"}, nil, nil)) err := tk.ExecToErr(`SHOW CREATE TABLE mysql.user`) require.True(t, terror.ErrorEqual(err, core.ErrTableaccessDenied)) // should pass - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "tsct2", Hostname: "localhost", AuthUsername: "tsct2", AuthHostname: "%"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "tsct2", Hostname: "localhost", AuthUsername: "tsct2", AuthHostname: "%"}, nil, nil)) tk.MustExec(`SHOW CREATE TABLE mysql.user`) } @@ -1181,7 +1181,7 @@ func TestReplaceAndInsertOnDuplicate(t *testing.T) { tk.MustExec(`GRANT DELETE ON t1 TO tr_delete`) // Restrict the permission to INSERT only. - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "tr_insert", Hostname: "localhost", AuthUsername: "tr_insert", AuthHostname: "%"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "tr_insert", Hostname: "localhost", AuthUsername: "tr_insert", AuthHostname: "%"}, nil, nil)) // REPLACE requires INSERT + DELETE privileges, having INSERT alone is insufficient. err := tk.ExecToErr(`REPLACE INTO t1 VALUES (1, 2)`) @@ -1197,13 +1197,13 @@ func TestReplaceAndInsertOnDuplicate(t *testing.T) { tk.MustExec(`INSERT INTO t1 VALUES (6, 7)`) // Also check that having DELETE alone is insufficient for REPLACE. - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "tr_delete", Hostname: "localhost", AuthUsername: "tr_delete", AuthHostname: "%"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "tr_delete", Hostname: "localhost", AuthUsername: "tr_delete", AuthHostname: "%"}, nil, nil)) err = tk.ExecToErr(`REPLACE INTO t1 VALUES (8, 9)`) require.True(t, terror.ErrorEqual(err, core.ErrTableaccessDenied)) require.EqualError(t, err, "[planner:1142]INSERT command denied to user 'tr_delete'@'%' for table 't1'") // Also check that having UPDATE alone is insufficient for INSERT ON DUPLICATE. - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "tr_update", Hostname: "localhost", AuthUsername: "tr_update", AuthHostname: "%"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "tr_update", Hostname: "localhost", AuthUsername: "tr_update", AuthHostname: "%"}, nil, nil)) err = tk.ExecToErr(`INSERT INTO t1 VALUES (10, 11) ON DUPLICATE KEY UPDATE b = 12`) require.True(t, terror.ErrorEqual(err, core.ErrTableaccessDenied)) require.EqualError(t, err, "[planner:1142]INSERT command denied to user 'tr_update'@'%' for table 't1'") @@ -1221,10 +1221,10 @@ func TestAnalyzeTable(t *testing.T) { tk.MustExec("use atest") tk.MustExec("CREATE TABLE t1 (a int)") - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "asuper", Hostname: "localhost", AuthUsername: "asuper", AuthHostname: "%"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "asuper", Hostname: "localhost", AuthUsername: "asuper", AuthHostname: "%"}, nil, nil)) tk.MustExec("analyze table mysql.user") // low privileged user - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "anobody", Hostname: "localhost", AuthUsername: "anobody", AuthHostname: "%"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "anobody", Hostname: "localhost", AuthUsername: "anobody", AuthHostname: "%"}, nil, nil)) err := tk.ExecToErr("analyze table t1") require.True(t, terror.ErrorEqual(err, core.ErrTableaccessDenied)) require.EqualError(t, err, "[planner:1142]INSERT command denied to user 'anobody'@'%' for table 't1'") @@ -1233,16 +1233,16 @@ func TestAnalyzeTable(t *testing.T) { require.EqualError(t, err, "[planner:1142]SELECT command denied to user 'anobody'@'%' for table 't1'") // try again after SELECT privilege granted - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "asuper", Hostname: "localhost", AuthUsername: "asuper", AuthHostname: "%"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "asuper", Hostname: "localhost", AuthUsername: "asuper", AuthHostname: "%"}, nil, nil)) tk.MustExec("GRANT SELECT ON atest.* TO 'anobody'") - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "anobody", Hostname: "localhost", AuthUsername: "anobody", AuthHostname: "%"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "anobody", Hostname: "localhost", AuthUsername: "anobody", AuthHostname: "%"}, nil, nil)) err = tk.ExecToErr("analyze table t1") require.True(t, terror.ErrorEqual(err, core.ErrTableaccessDenied)) require.EqualError(t, err, "[planner:1142]INSERT command denied to user 'anobody'@'%' for table 't1'") // Add INSERT privilege and it should work. - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "asuper", Hostname: "localhost", AuthUsername: "asuper", AuthHostname: "%"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "asuper", Hostname: "localhost", AuthUsername: "asuper", AuthHostname: "%"}, nil, nil)) tk.MustExec("GRANT INSERT ON atest.* TO 'anobody'") - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "anobody", Hostname: "localhost", AuthUsername: "anobody", AuthHostname: "%"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "anobody", Hostname: "localhost", AuthUsername: "anobody", AuthHostname: "%"}, nil, nil)) tk.MustExec("analyze table t1") } @@ -1253,7 +1253,7 @@ func TestSystemSchema(t *testing.T) { tk := testkit.NewTestKit(t, store) tk.MustExec(`CREATE USER 'u1'@'localhost';`) tk.MustExec(`GRANT SELECT ON *.* TO 'u1'@'localhost';`) - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "u1", Hostname: "localhost"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "u1", Hostname: "localhost"}, nil, nil)) tk.MustExec(`select * from information_schema.tables`) tk.MustExec(`select * from information_schema.key_column_usage`) err := tk.ExecToErr("create table information_schema.t(a int)") @@ -1292,15 +1292,15 @@ func TestPerformanceSchema(t *testing.T) { tk := testkit.NewTestKit(t, store) tk.MustExec(`CREATE USER 'u1'@'localhost';`) - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "u1", Hostname: "localhost"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "u1", Hostname: "localhost"}, nil, nil)) err := tk.ExecToErr("select * from performance_schema.events_statements_summary_by_digest where schema_name = 'tst'") require.Error(t, err) require.True(t, terror.ErrorEqual(err, core.ErrTableaccessDenied)) - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "root", Hostname: "localhost"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "root", Hostname: "localhost"}, nil, nil)) tk.MustExec(`GRANT SELECT ON *.* TO 'u1'@'localhost';`) - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "u1", Hostname: "localhost"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "u1", Hostname: "localhost"}, nil, nil)) tk.MustExec("select * from performance_schema.events_statements_summary_by_digest where schema_name = 'tst'") tk.MustExec(`select * from performance_schema.events_statements_summary_by_digest`) err = tk.ExecToErr("drop table performance_schema.events_statements_summary_by_digest") @@ -1433,11 +1433,11 @@ func TestAdminCommand(t *testing.T) { tk := testkit.NewTestKit(t, store) tk.MustExec("use test") - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "root", Hostname: "localhost"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "root", Hostname: "localhost"}, nil, nil)) tk.MustExec(`CREATE USER 'test_admin'@'localhost';`) tk.MustExec(`CREATE TABLE t(a int)`) - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "test_admin", Hostname: "localhost"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "test_admin", Hostname: "localhost"}, nil, nil)) err := tk.ExecToErr("ADMIN SHOW DDL JOBS") require.Error(t, err) require.True(t, terror.ErrorEqual(err, core.ErrPrivilegeCheckFail)) @@ -1445,7 +1445,7 @@ func TestAdminCommand(t *testing.T) { require.Error(t, err) require.True(t, terror.ErrorEqual(err, core.ErrPrivilegeCheckFail)) - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "root", Hostname: "localhost"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "root", Hostname: "localhost"}, nil, nil)) tk.MustExec("ADMIN SHOW DDL JOBS") } @@ -1453,12 +1453,12 @@ func TestTableNotExistNoPermissions(t *testing.T) { store := createStoreAndPrepareDB(t) tk := testkit.NewTestKit(t, store) - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "root", Hostname: "localhost"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "root", Hostname: "localhost"}, nil, nil)) tk.MustExec(`CREATE USER 'testnotexist'@'localhost';`) tk.MustExec(`CREATE DATABASE dbexists`) tk.MustExec(`CREATE TABLE dbexists.t1 (a int)`) - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "testnotexist", Hostname: "localhost"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "testnotexist", Hostname: "localhost"}, nil, nil)) tests := []struct { stmt string @@ -1511,24 +1511,24 @@ func TestLoadDataPrivilege(t *testing.T) { tk := testkit.NewTestKit(t, store) tk.MustExec("use test") - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "root", Hostname: "localhost"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "root", Hostname: "localhost"}, nil, nil)) tk.MustExec(`CREATE USER 'test_load'@'localhost';`) tk.MustExec(`CREATE TABLE t_load(a int)`) tk.MustExec(`GRANT SELECT on *.* to 'test_load'@'localhost'`) - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "test_load", Hostname: "localhost"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "test_load", Hostname: "localhost"}, nil, nil)) err = tk.ExecToErr("LOAD DATA LOCAL INFILE '/tmp/load_data_priv.csv' INTO TABLE t_load") require.Error(t, err) require.True(t, terror.ErrorEqual(err, core.ErrTableaccessDenied)) - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "root", Hostname: "localhost"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "root", Hostname: "localhost"}, nil, nil)) tk.MustExec(`GRANT INSERT on *.* to 'test_load'@'localhost'`) - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "test_load", Hostname: "localhost"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "test_load", Hostname: "localhost"}, nil, nil)) tk.MustExec("LOAD DATA LOCAL INFILE '/tmp/load_data_priv.csv' INTO TABLE t_load") - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "root", Hostname: "localhost"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "root", Hostname: "localhost"}, nil, nil)) tk.MustExec(`GRANT INSERT on *.* to 'test_load'@'localhost'`) - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "test_load", Hostname: "localhost"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "test_load", Hostname: "localhost"}, nil, nil)) err = tk.ExecToErr("LOAD DATA LOCAL INFILE '/tmp/load_data_priv.csv' REPLACE INTO TABLE t_load") require.Error(t, err) require.True(t, terror.ErrorEqual(err, core.ErrTableaccessDenied)) @@ -1539,7 +1539,7 @@ func TestSelectIntoNoPermissions(t *testing.T) { tk := testkit.NewTestKit(t, store) tk.MustExec(`CREATE USER 'nofile'@'localhost';`) - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "nofile", Hostname: "localhost"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "nofile", Hostname: "localhost"}, nil, nil)) err := tk.ExecToErr(`select 1 into outfile '/tmp/doesntmatter-no-permissions'`) require.Error(t, err) require.True(t, terror.ErrorEqual(err, core.ErrSpecificAccessDenied)) @@ -1562,11 +1562,11 @@ func TestAuthHost(t *testing.T) { rootTk.MustExec(`CREATE USER 'test_auth_host'@'%';`) rootTk.MustExec(`GRANT ALL ON *.* TO 'test_auth_host'@'%' WITH GRANT OPTION;`) - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "test_auth_host", Hostname: "192.168.0.10"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "test_auth_host", Hostname: "192.168.0.10"}, nil, nil)) tk.MustExec("CREATE USER 'test_auth_host'@'192.168.%';") tk.MustExec("GRANT SELECT ON *.* TO 'test_auth_host'@'192.168.%';") - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "test_auth_host", Hostname: "192.168.0.10"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "test_auth_host", Hostname: "192.168.0.10"}, nil, nil)) err := tk.ExecToErr("create user test_auth_host_a") require.Error(t, err) @@ -1632,7 +1632,7 @@ func TestFieldList(t *testing.T) { // Issue #14237 List fields RPC tk.MustExec("use test") tk.MustExec(`CREATE USER 'tableaccess'@'localhost'`) tk.MustExec(`CREATE TABLE fieldlistt1 (a int)`) - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "tableaccess", Hostname: "localhost"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "tableaccess", Hostname: "localhost"}, nil, nil)) _, err := tk.Session().FieldList("fieldlistt1") require.Error(t, err) require.True(t, terror.ErrorEqual(err, core.ErrTableaccessDenied)) @@ -1647,7 +1647,7 @@ func TestDynamicPrivs(t *testing.T) { rootTk.MustExec("CREATE ROLE anyrolename") tk := testkit.NewTestKit(t, store) - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "notsuper", Hostname: "%"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "notsuper", Hostname: "%"}, nil, nil)) // test SYSTEM_VARIABLES_ADMIN err := tk.ExecToErr("SET GLOBAL wait_timeout = 86400") @@ -1695,12 +1695,12 @@ func TestDynamicGrantOption(t *testing.T) { rootTk.MustExec("GRANT SYSTEM_VARIABLES_ADMIN ON *.* TO varuser2 WITH GRANT OPTION") tk1 := testkit.NewTestKit(t, store) - require.True(t, tk1.Session().Auth(&auth.UserIdentity{Username: "varuser1", Hostname: "%"}, nil, nil)) + require.NoError(t, tk1.Session().Auth(&auth.UserIdentity{Username: "varuser1", Hostname: "%"}, nil, nil)) err := tk1.ExecToErr("GRANT SYSTEM_VARIABLES_ADMIN ON *.* TO varuser3") require.EqualError(t, err, "[planner:1227]Access denied; you need (at least one of) the GRANT OPTION privilege(s) for this operation") tk2 := testkit.NewTestKit(t, store) - require.True(t, tk2.Session().Auth(&auth.UserIdentity{Username: "varuser2", Hostname: "%"}, nil, nil)) + require.NoError(t, tk2.Session().Auth(&auth.UserIdentity{Username: "varuser2", Hostname: "%"}, nil, nil)) tk2.MustExec("GRANT SYSTEM_VARIABLES_ADMIN ON *.* TO varuser3") } @@ -1714,9 +1714,9 @@ func TestSecurityEnhancedModeRestrictedTables(t *testing.T) { cloudAdminTK.MustExec("GRANT CREATE ON mysql.* to cloudadmin") cloudAdminTK.MustExec("CREATE USER uroot") cloudAdminTK.MustExec("GRANT ALL ON *.* to uroot WITH GRANT OPTION") // A "MySQL" all powerful user. - require.True(t, cloudAdminTK.Session().Auth(&auth.UserIdentity{Username: "cloudadmin", Hostname: "%"}, nil, nil)) + require.NoError(t, cloudAdminTK.Session().Auth(&auth.UserIdentity{Username: "cloudadmin", Hostname: "%"}, nil, nil)) urootTk := testkit.NewTestKit(t, store) - require.True(t, urootTk.Session().Auth(&auth.UserIdentity{Username: "uroot", Hostname: "%"}, nil, nil)) + require.NoError(t, urootTk.Session().Auth(&auth.UserIdentity{Username: "uroot", Hostname: "%"}, nil, nil)) sem.Enable() defer sem.Disable() @@ -1917,7 +1917,7 @@ func TestRenameUser(t *testing.T) { rootTk.MustExec("CREATE USER ru3") rootTk.MustExec("CREATE USER ru6@localhost") tk := testkit.NewTestKit(t, store) - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "ru1", Hostname: "localhost"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "ru1", Hostname: "localhost"}, nil, nil)) // Check privileges (need CREATE USER) err := tk.ExecToErr("RENAME USER ru3 TO ru4") @@ -2525,17 +2525,17 @@ func TestPlacementPolicyStmt(t *testing.T) { tk.MustExec("GRANT ALL ON *.* TO super_user") tk.MustExec("GRANT PLACEMENT_ADMIN ON *.* TO placement_user") - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "empty_user", Hostname: "localhost"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "empty_user", Hostname: "localhost"}, nil, nil)) err := tk.ExecToErr(createStmt) require.EqualError(t, err, "[planner:1227]Access denied; you need (at least one of) the SUPER or PLACEMENT_ADMIN privilege(s) for this operation") err = tk.ExecToErr(dropStmt) require.EqualError(t, err, "[planner:1227]Access denied; you need (at least one of) the SUPER or PLACEMENT_ADMIN privilege(s) for this operation") - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "super_user", Hostname: "localhost"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "super_user", Hostname: "localhost"}, nil, nil)) tk.MustExec(createStmt) tk.MustExec(dropStmt) - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "placement_user", Hostname: "localhost"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "placement_user", Hostname: "localhost"}, nil, nil)) tk.MustExec(createStmt) tk.MustExec(dropStmt) } @@ -2795,15 +2795,15 @@ func TestIssue28675(t *testing.T) { tk.MustExec(`create user test_user`) tk.MustExec("create view test.v as select 1") tk.MustExec("grant show view on test.v to test_user") - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "test_user", Hostname: "localhost"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "test_user", Hostname: "localhost"}, nil, nil)) tk.MustQuery("select count(*) from information_schema.columns where table_schema='test' and table_name='v'").Check(testkit.Rows("0")) tk.ExecToErr("desc test.v") tk.ExecToErr("explain test.v") - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "root", Hostname: "localhost"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "root", Hostname: "localhost"}, nil, nil)) tk.MustExec("grant update on test.v to test_user") tk.MustExec("grant select on test.v to test_user") - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "test_user", Hostname: "localhost"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "test_user", Hostname: "localhost"}, nil, nil)) tk.MustQuery("select count(*) from information_schema.columns where table_schema='test' and table_name='v'").Check(testkit.Rows("1")) tk.MustQuery("select count(*) from information_schema.columns where table_schema='Test' and table_name='V'").Check(testkit.Rows("1")) tk.MustQuery("select privileges from information_schema.columns where table_schema='test' and table_name='v'").Check(testkit.Rows("select,update")) @@ -2880,7 +2880,7 @@ func TestIssue29823(t *testing.T) { tk.MustExec("grant r1 to u1") tk2 := testkit.NewTestKit(t, store) - require.True(t, tk2.Session().Auth(&auth.UserIdentity{Username: "u1", Hostname: "%"}, nil, nil)) + require.NoError(t, tk2.Session().Auth(&auth.UserIdentity{Username: "u1", Hostname: "%"}, nil, nil)) tk2.MustExec("set role all") tk2.MustQuery("select current_role()").Check(testkit.Rows("`r1`@`%`")) tk2.MustQuery("select * from test.t1").Check(testkit.Rows()) @@ -2906,7 +2906,7 @@ func TestCheckPreparePrivileges(t *testing.T) { tk.MustExec("insert into t values(1)") tk2 := testkit.NewTestKit(t, store) - require.True(t, tk2.Session().Auth(&auth.UserIdentity{Username: "u1", Hostname: "%"}, nil, nil)) + require.NoError(t, tk2.Session().Auth(&auth.UserIdentity{Username: "u1", Hostname: "%"}, nil, nil)) // sql err := tk2.ExecToErr("prepare s from 'select * from test.t'") diff --git a/server/conn.go b/server/conn.go index ae0bbaa3afaba..7ef7680b294d2 100644 --- a/server/conn.go +++ b/server/conn.go @@ -809,8 +809,8 @@ func (cc *clientConn) openSessionAndDoAuth(authData []byte, authPlugin string) e logutil.BgLogger().Warn("verify session token failed", zap.String("username", cc.user), zap.Error(err)) return errAccessDenied.FastGenByArgs(cc.user, host, hasPassword) } - } else if !cc.ctx.Auth(userIdentity, authData, cc.salt) { - return errAccessDenied.FastGenByArgs(cc.user, host, hasPassword) + } else if err = cc.ctx.Auth(userIdentity, authData, cc.salt); err != nil { + return err } cc.ctx.SetPort(port) if cc.dbname != "" { diff --git a/server/server.go b/server/server.go index 576a50eac9177..1c30156bad8eb 100644 --- a/server/server.go +++ b/server/server.go @@ -97,6 +97,7 @@ var ( errInvalidType = dbterror.ClassServer.NewStd(errno.ErrInvalidType) errNotAllowedCommand = dbterror.ClassServer.NewStd(errno.ErrNotAllowedCommand) errAccessDenied = dbterror.ClassServer.NewStd(errno.ErrAccessDenied) + errAccountHasBeenLocked = dbterror.ClassServer.NewStd(errno.ErrAccountHasBeenLocked) errAccessDeniedNoPassword = dbterror.ClassServer.NewStd(errno.ErrAccessDeniedNoPassword) errConCount = dbterror.ClassServer.NewStd(errno.ErrConCount) errSecureTransportRequired = dbterror.ClassServer.NewStd(errno.ErrSecureTransportRequired) diff --git a/session/session.go b/session/session.go index c8895ea3b09e1..0a52ae37776b2 100644 --- a/session/session.go +++ b/session/session.go @@ -170,7 +170,7 @@ type Session interface { SetCollation(coID int) error SetSessionManager(util.SessionManager) Close() - Auth(user *auth.UserIdentity, auth []byte, salt []byte) bool + Auth(user *auth.UserIdentity, auth []byte, salt []byte) error AuthWithoutVerification(user *auth.UserIdentity) bool AuthPluginForUser(user *auth.UserIdentity) (string, error) MatchIdentity(username, remoteHost string) (*auth.UserIdentity, error) @@ -2498,20 +2498,24 @@ func (s *session) AuthPluginForUser(user *auth.UserIdentity) (string, error) { // Auth validates a user using an authentication string and salt. // If the password fails, it will keep trying other users until exhausted. // This means it can not be refactored to use MatchIdentity yet. -func (s *session) Auth(user *auth.UserIdentity, authentication []byte, salt []byte) bool { +func (s *session) Auth(user *auth.UserIdentity, authentication []byte, salt []byte) error { + hasPassword := "YES" + if len(authentication) == 0 { + hasPassword = "NO" + } pm := privilege.GetPrivilegeManager(s) authUser, err := s.MatchIdentity(user.Username, user.Hostname) if err != nil { - return false + return dbterror.ClassSession.NewStd(mysql.ErrAccessDenied).FastGenByArgs(user.Username, user.Hostname, hasPassword) } - if pm.ConnectionVerification(authUser.Username, authUser.Hostname, authentication, salt, s.sessionVars.TLSConnectionState) { - user.AuthUsername = authUser.Username - user.AuthHostname = authUser.Hostname - s.sessionVars.User = user - s.sessionVars.ActiveRoles = pm.GetDefaultRoles(user.AuthUsername, user.AuthHostname) - return true + if err = pm.ConnectionVerification(authUser.Username, authUser.Hostname, authentication, salt, s.sessionVars.TLSConnectionState); err != nil { + return err } - return false + user.AuthUsername = authUser.Username + user.AuthHostname = authUser.Hostname + s.sessionVars.User = user + s.sessionVars.ActiveRoles = pm.GetDefaultRoles(user.AuthUsername, user.AuthHostname) + return nil } // MatchIdentity finds the matching username + password in the MySQL privilege tables diff --git a/session/session_test/session_test.go b/session/session_test/session_test.go index 4d8307d49ab95..1babe306a974b 100644 --- a/session/session_test/session_test.go +++ b/session/session_test/session_test.go @@ -335,8 +335,8 @@ func TestAutoCommitRespectsReadOnly(t *testing.T) { var wg sync.WaitGroup tk1 := testkit.NewTestKit(t, store) tk2 := testkit.NewTestKit(t, store) - require.True(t, tk1.Session().Auth(&auth.UserIdentity{Username: "root", Hostname: "%"}, nil, nil)) - require.True(t, tk2.Session().Auth(&auth.UserIdentity{Username: "root", Hostname: "%"}, nil, nil)) + require.NoError(t, tk1.Session().Auth(&auth.UserIdentity{Username: "root", Hostname: "%"}, nil, nil)) + require.NoError(t, tk2.Session().Auth(&auth.UserIdentity{Username: "root", Hostname: "%"}, nil, nil)) tk1.MustExec("create table test.auto_commit_test (a int)") wg.Add(1) @@ -1402,11 +1402,11 @@ func TestSkipWithGrant(t *testing.T) { save2 := privileges.SkipWithGrant privileges.SkipWithGrant = false - require.False(t, tk.Session().Auth(&auth.UserIdentity{Username: "user_not_exist"}, []byte("yyy"), []byte("zzz"))) + require.Error(t, tk.Session().Auth(&auth.UserIdentity{Username: "user_not_exist"}, []byte("yyy"), []byte("zzz"))) privileges.SkipWithGrant = true - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "xxx", Hostname: `%`}, []byte("yyy"), []byte("zzz"))) - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "root", Hostname: `%`}, []byte(""), []byte(""))) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "xxx", Hostname: `%`}, []byte("yyy"), []byte("zzz"))) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "root", Hostname: `%`}, []byte(""), []byte(""))) tk.MustExec("use test") tk.MustExec("create table t (id int)") tk.MustExec("create role r_1") @@ -2334,7 +2334,7 @@ func TestUpdatePrivilege(t *testing.T) { tk1 := testkit.NewTestKit(t, store) tk1.MustExec("use test") - require.True(t, tk1.Session().Auth(&auth.UserIdentity{Username: "xxx", Hostname: "localhost"}, []byte(""), []byte(""))) + require.NoError(t, tk1.Session().Auth(&auth.UserIdentity{Username: "xxx", Hostname: "localhost"}, []byte(""), []byte(""))) tk1.MustMatchErrMsg("update t2 set id = 666 where id = 1;", "privilege check.*") @@ -2348,7 +2348,7 @@ func TestUpdatePrivilege(t *testing.T) { tk.MustExec("create table tb_wehub_server (id int, active_count int, used_count int)") tk.MustExec("create user 'weperk'") tk.MustExec("grant all privileges on weperk.* to 'weperk'@'%'") - require.True(t, tk1.Session().Auth(&auth.UserIdentity{Username: "weperk", Hostname: "%"}, []byte(""), []byte(""))) + require.NoError(t, tk1.Session().Auth(&auth.UserIdentity{Username: "weperk", Hostname: "%"}, []byte(""), []byte(""))) tk1.MustExec("use weperk") tk1.MustExec("update tb_wehub_server a set a.active_count=a.active_count+1,a.used_count=a.used_count+1 where id=1") @@ -2384,7 +2384,7 @@ and s.b !='xx';`) tk.MustExec("insert into tp.record (id,name,age) values (1,'john',18),(2,'lary',19),(3,'lily',18)") tk.MustExec("create table ap.record( id int,name varchar(128),age int)") tk.MustExec("insert into ap.record(id) values(1)") - require.True(t, tk1.Session().Auth(&auth.UserIdentity{Username: "xxx", Hostname: "localhost"}, []byte(""), []byte(""))) + require.NoError(t, tk1.Session().Auth(&auth.UserIdentity{Username: "xxx", Hostname: "localhost"}, []byte(""), []byte(""))) tk1.MustExec("update ap.record t inner join tp.record tt on t.id=tt.id set t.name=tt.name") } @@ -3973,7 +3973,7 @@ func TestSessionAuth(t *testing.T) { tk := testkit.NewTestKit(t, store) tk.MustExec("use test") - require.False(t, tk.Session().Auth(&auth.UserIdentity{Username: "Any not exist username with zero password!", Hostname: "anyhost"}, []byte(""), []byte(""))) + require.Error(t, tk.Session().Auth(&auth.UserIdentity{Username: "Any not exist username with zero password!", Hostname: "anyhost"}, []byte(""), []byte(""))) } func TestLastInsertID(t *testing.T) { diff --git a/sessionctx/sessionstates/session_states_test.go b/sessionctx/sessionstates/session_states_test.go index aad78a39924c3..e8b9e85b4bb06 100644 --- a/sessionctx/sessionstates/session_states_test.go +++ b/sessionctx/sessionstates/session_states_test.go @@ -958,14 +958,14 @@ func TestPreparedStatements(t *testing.T) { // rootTk := testkit.NewTestKit(t, store) // rootTk.MustExec(`CREATE USER 'u1'@'localhost'`) // rootTk.MustExec("create table test.t1(id int)") - // require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "u1", Hostname: "localhost"}, nil, nil)) + // require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "u1", Hostname: "localhost"}, nil, nil)) // rootTk.MustExec(`GRANT SELECT ON test.t1 TO 'u1'@'localhost'`) // tk.MustExec("prepare stmt from 'select * from test.t1'") // rootTk.MustExec(`REVOKE SELECT ON test.t1 FROM 'u1'@'localhost'`) // return nil // }, // prepareFunc: func(tk *testkit.TestKit, conn server.MockConn) { - // require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "u1", Hostname: "localhost"}, nil, nil)) + // require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "u1", Hostname: "localhost"}, nil, nil)) // }, // restoreErr: errno.ErrNoSuchTable, // cleanFunc: func(tk *testkit.TestKit) { diff --git a/table/tables/cache_test.go b/table/tables/cache_test.go index 4431b6d25a81d..6f8fc2d4345b4 100644 --- a/table/tables/cache_test.go +++ b/table/tables/cache_test.go @@ -454,7 +454,7 @@ func TestCacheTableWriteOperatorWaitLockLease(t *testing.T) { // This line is a hack, if auth user string is "", the statement summary is skipped, // so it's added to make the later code been covered. - require.True(t, se.Auth(&auth.UserIdentity{Username: "root", Hostname: "localhost"}, nil, nil)) + require.NoError(t, se.Auth(&auth.UserIdentity{Username: "root", Hostname: "localhost"}, nil, nil)) tk.MustExec("drop table if exists wait_tb1") tk.MustExec("create table wait_tb1(id int)") diff --git a/table/tables/tables_test.go b/table/tables/tables_test.go index 5b5711d182434..22551620ed538 100644 --- a/table/tables/tables_test.go +++ b/table/tables/tables_test.go @@ -705,7 +705,7 @@ func TestConstraintCheckForUniqueIndex(t *testing.T) { func TestViewColumns(t *testing.T) { store := testkit.CreateMockStore(t) tk := testkit.NewTestKit(t, store) - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "root", Hostname: "%"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "root", Hostname: "%"}, nil, nil)) tk.MustExec("use test") tk.MustExec("drop table if exists t") tk.MustExec("create table t(a int primary key, b varchar(20))") @@ -762,7 +762,7 @@ func TestTxnAssertion(t *testing.T) { se, err := session.CreateSession4Test(store) se.SetConnectionID(1) require.NoError(t, err) - require.True(t, se.Auth(&auth.UserIdentity{Username: "root", Hostname: "%"}, nil, nil)) + require.NoError(t, se.Auth(&auth.UserIdentity{Username: "root", Hostname: "%"}, nil, nil)) tk := testkit.NewTestKit(t, store) tk.SetSession(se) diff --git a/tests/realtikvtest/pessimistictest/pessimistic_test.go b/tests/realtikvtest/pessimistictest/pessimistic_test.go index da9f936cecd70..7f4348bfbf0a1 100644 --- a/tests/realtikvtest/pessimistictest/pessimistic_test.go +++ b/tests/realtikvtest/pessimistictest/pessimistic_test.go @@ -197,7 +197,7 @@ func TestDeadlock(t *testing.T) { // Use the root user so that the statements can be recorded into statements_summary table, which is necessary // for fetching - require.True(t, tk1.Session().Auth(&auth.UserIdentity{Username: "root", Hostname: "%"}, nil, nil)) + require.NoError(t, tk1.Session().Auth(&auth.UserIdentity{Username: "root", Hostname: "%"}, nil, nil)) tk1.MustExec("drop table if exists deadlock") tk1.MustExec("create table deadlock (k int primary key, v int)") tk1.MustExec("insert into deadlock values (1, 1), (2, 1)") @@ -206,7 +206,7 @@ func TestDeadlock(t *testing.T) { ts1, err := strconv.ParseUint(tk1.MustQuery("select @@tidb_current_ts").Rows()[0][0].(string), 10, 64) require.NoError(t, err) - require.True(t, tk2.Session().Auth(&auth.UserIdentity{Username: "root", Hostname: "%"}, nil, nil)) + require.NoError(t, tk2.Session().Auth(&auth.UserIdentity{Username: "root", Hostname: "%"}, nil, nil)) tk2.MustExec("begin pessimistic") ts2, err := strconv.ParseUint(tk2.MustQuery("select @@tidb_current_ts").Rows()[0][0].(string), 10, 64) require.NoError(t, err) From f8a6cb537818c2a48c3170c0f43e44cdbd212a6d Mon Sep 17 00:00:00 2001 From: cbcwestwolf <1004626265@qq.com> Date: Thu, 11 Aug 2022 19:52:58 +0800 Subject: [PATCH 05/17] bazel --- sessionctx/variable/BUILD.bazel | 2 ++ 1 file changed, 2 insertions(+) diff --git a/sessionctx/variable/BUILD.bazel b/sessionctx/variable/BUILD.bazel index f682f6b4530c5..8a762bfb21516 100644 --- a/sessionctx/variable/BUILD.bazel +++ b/sessionctx/variable/BUILD.bazel @@ -41,6 +41,7 @@ go_library( "//util/collate", "//util/dbterror", "//util/execdetails", + "//util/kvcache", "//util/logutil", "//util/mathutil", "//util/memory", @@ -86,6 +87,7 @@ go_test( "//parser/auth", "//parser/mysql", "//parser/terror", + "//planner/core", "//sessionctx/stmtctx", "//testkit/testsetup", "//util/execdetails", From 28e6770e166a68d39af0c97041f7fef31cd34543 Mon Sep 17 00:00:00 2001 From: cbcwestwolf <1004626265@qq.com> Date: Thu, 11 Aug 2022 20:14:35 +0800 Subject: [PATCH 06/17] Fix --- privilege/privileges/privileges.go | 2 +- server/server.go | 1 - session/bootstrap_test.go | 3 +-- 3 files changed, 2 insertions(+), 4 deletions(-) diff --git a/privilege/privileges/privileges.go b/privilege/privileges/privileges.go index 4388affaa0a0f..daedd2fd413c5 100644 --- a/privilege/privileges/privileges.go +++ b/privilege/privileges/privileges.go @@ -325,7 +325,7 @@ func (p *UserPrivileges) ConnectionVerification(user, host string, authenticatio if len(pwd) == 0 && len(authentication) == 0 { p.user = user p.host = record.Host - return errAccessDenied.FastGenByArgs(user, host, hasPassword) + return nil } if len(pwd) == 0 || len(authentication) == 0 { diff --git a/server/server.go b/server/server.go index 1c30156bad8eb..576a50eac9177 100644 --- a/server/server.go +++ b/server/server.go @@ -97,7 +97,6 @@ var ( errInvalidType = dbterror.ClassServer.NewStd(errno.ErrInvalidType) errNotAllowedCommand = dbterror.ClassServer.NewStd(errno.ErrNotAllowedCommand) errAccessDenied = dbterror.ClassServer.NewStd(errno.ErrAccessDenied) - errAccountHasBeenLocked = dbterror.ClassServer.NewStd(errno.ErrAccountHasBeenLocked) errAccessDeniedNoPassword = dbterror.ClassServer.NewStd(errno.ErrAccessDeniedNoPassword) errConCount = dbterror.ClassServer.NewStd(errno.ErrConCount) errSecureTransportRequired = dbterror.ClassServer.NewStd(errno.ErrSecureTransportRequired) diff --git a/session/bootstrap_test.go b/session/bootstrap_test.go index df8ca83564cb8..7adc0b58666cd 100644 --- a/session/bootstrap_test.go +++ b/session/bootstrap_test.go @@ -57,8 +57,7 @@ func TestBootstrap(t *testing.T) { match(t, rows, `%`, "root", "", "mysql_native_password", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "N", "Y", "Y", "Y", "Y", "Y") r.Close() - ok := se.Auth(&auth.UserIdentity{Username: "root", Hostname: "anyhost"}, []byte(""), []byte("")) - require.True(t, ok) + require.NoError(t, se.Auth(&auth.UserIdentity{Username: "root", Hostname: "anyhost"}, []byte(""), []byte(""))) mustExec(t, se, "use test") From 7437da6d7290eb3c06ac189799bd5d29e3489179 Mon Sep 17 00:00:00 2001 From: cbcwestwolf <1004626265@qq.com> Date: Thu, 11 Aug 2022 21:38:39 +0800 Subject: [PATCH 07/17] Fix --- privilege/privilege.go | 2 +- privilege/privileges/privileges.go | 48 +++++++++++++++--------------- server/tidb_test.go | 1 + session/session.go | 2 +- 4 files changed, 27 insertions(+), 26 deletions(-) diff --git a/privilege/privilege.go b/privilege/privilege.go index 013329b655972..b557ce2f1ca8b 100644 --- a/privilege/privilege.go +++ b/privilege/privilege.go @@ -60,7 +60,7 @@ type Manager interface { // ConnectionVerification verifies user privilege for connection. // Requires exact match on user name and host name. - ConnectionVerification(user, host string, auth, salt []byte, tlsState *tls.ConnectionState) error + ConnectionVerification(user *auth.UserIdentity, authUser, authHost string, auth, salt []byte, tlsState *tls.ConnectionState) error // GetAuthWithoutVerification uses to get auth name without verification. // Requires exact match on user name and host name. diff --git a/privilege/privileges/privileges.go b/privilege/privileges/privileges.go index daedd2fd413c5..140991a73c97c 100644 --- a/privilege/privileges/privileges.go +++ b/privilege/privileges/privileges.go @@ -281,56 +281,56 @@ func (p *UserPrivileges) GetAuthWithoutVerification(user, host string) (success } // ConnectionVerification implements the Manager interface. -func (p *UserPrivileges) ConnectionVerification(user, host string, authentication, salt []byte, tlsState *tls.ConnectionState) error { +func (p *UserPrivileges) ConnectionVerification(user *auth.UserIdentity, authUser, authHost string, authentication, salt []byte, tlsState *tls.ConnectionState) error { hasPassword := "YES" if len(authentication) == 0 { hasPassword = "NO" } if SkipWithGrant { - p.user = user - p.host = host + p.user = authUser + p.host = authHost return nil } mysqlPriv := p.Handle.Get() - record := mysqlPriv.connectionVerification(user, host) + record := mysqlPriv.connectionVerification(authUser, authHost) if record == nil { - logutil.BgLogger().Error("get user privilege record fail", - zap.String("user", user), zap.String("host", host)) - return errAccessDenied.FastGenByArgs(user, host, hasPassword) + logutil.BgLogger().Error("get authUser privilege record fail", + zap.String("authUser", authUser), zap.String("authHost", authHost)) + return errAccessDenied.FastGenByArgs(user.Username, user.Hostname, hasPassword) } - globalPriv := mysqlPriv.matchGlobalPriv(user, host) + globalPriv := mysqlPriv.matchGlobalPriv(authUser, authHost) if globalPriv != nil { if !p.checkSSL(globalPriv, tlsState) { logutil.BgLogger().Error("global priv check ssl fail", - zap.String("user", user), zap.String("host", host)) - return errAccessDenied.FastGenByArgs(user, host, hasPassword) + zap.String("authUser", authUser), zap.String("authHost", authHost)) + return errAccessDenied.FastGenByArgs(user.Username, user.Hostname, hasPassword) } } // Login a locked account is not allowed. locked := record.AccountLocked if locked { - logutil.BgLogger().Error(fmt.Sprintf("Access denied for user '%s'@'%s'. Account is locked.", user, host)) - return errAccountHasBeenLocked.FastGenByArgs(user, host) + logutil.BgLogger().Error(fmt.Sprintf("Access denied for authUser '%s'@'%s'. Account is locked.", authUser, authHost)) + return errAccountHasBeenLocked.FastGenByArgs(user.Username, user.Hostname) } pwd := record.AuthenticationString if !p.isValidHash(record) { - return errAccessDenied.FastGenByArgs(user, host, hasPassword) + return errAccessDenied.FastGenByArgs(user.Username, user.Hostname, hasPassword) } // empty password if len(pwd) == 0 && len(authentication) == 0 { - p.user = user + p.user = authUser p.host = record.Host return nil } if len(pwd) == 0 || len(authentication) == 0 { if record.AuthPlugin != mysql.AuthSocket { - return errAccessDenied.FastGenByArgs(user, host, hasPassword) + return errAccessDenied.FastGenByArgs(user.Username, user.Hostname, hasPassword) } } @@ -338,11 +338,11 @@ func (p *UserPrivileges) ConnectionVerification(user, host string, authenticatio hpwd, err := auth.DecodePassword(pwd) if err != nil { logutil.BgLogger().Error("decode password string failed", zap.Error(err)) - return errAccessDenied.FastGenByArgs(user, host, hasPassword) + return errAccessDenied.FastGenByArgs(user.Username, user.Hostname, hasPassword) } if !auth.CheckScrambledPassword(salt, hpwd, authentication) { - return errAccessDenied.FastGenByArgs(user, host, hasPassword) + return errAccessDenied.FastGenByArgs(user.Username, user.Hostname, hasPassword) } } else if record.AuthPlugin == mysql.AuthCachingSha2Password { authok, err := auth.CheckShaPassword([]byte(pwd), string(authentication)) @@ -351,21 +351,21 @@ func (p *UserPrivileges) ConnectionVerification(user, host string, authenticatio } if !authok { - return errAccessDenied.FastGenByArgs(user, host, hasPassword) + return errAccessDenied.FastGenByArgs(user.Username, user.Hostname, hasPassword) } } else if record.AuthPlugin == mysql.AuthSocket { - if string(authentication) != user && string(authentication) != pwd { - logutil.BgLogger().Error("Failed socket auth", zap.String("user", user), + if string(authentication) != authUser && string(authentication) != pwd { + logutil.BgLogger().Error("Failed socket auth", zap.String("authUser", authUser), zap.String("socket_user", string(authentication)), zap.String("authentication_string", pwd)) - return errAccessDenied.FastGenByArgs(user, host, hasPassword) + return errAccessDenied.FastGenByArgs(user.Username, user.Hostname, hasPassword) } } else { - logutil.BgLogger().Error("unknown authentication plugin", zap.String("user", user), zap.String("plugin", record.AuthPlugin)) - return errAccessDenied.FastGenByArgs(user, host, hasPassword) + logutil.BgLogger().Error("unknown authentication plugin", zap.String("authUser", authUser), zap.String("plugin", record.AuthPlugin)) + return errAccessDenied.FastGenByArgs(user.Username, user.Hostname, hasPassword) } - p.user = user + p.user = authUser p.host = record.Host return nil } diff --git a/server/tidb_test.go b/server/tidb_test.go index 4f213193a0e63..e0a6d6f35b535 100644 --- a/server/tidb_test.go +++ b/server/tidb_test.go @@ -193,6 +193,7 @@ func TestAuth(t *testing.T) { ts.runTestAuth(t) ts.runTestIssue3682(t) + // TODO: Test account lock here } func TestIssues(t *testing.T) { diff --git a/session/session.go b/session/session.go index 0a52ae37776b2..825780bbe6a95 100644 --- a/session/session.go +++ b/session/session.go @@ -2508,7 +2508,7 @@ func (s *session) Auth(user *auth.UserIdentity, authentication []byte, salt []by if err != nil { return dbterror.ClassSession.NewStd(mysql.ErrAccessDenied).FastGenByArgs(user.Username, user.Hostname, hasPassword) } - if err = pm.ConnectionVerification(authUser.Username, authUser.Hostname, authentication, salt, s.sessionVars.TLSConnectionState); err != nil { + if err = pm.ConnectionVerification(user, authUser.Username, authUser.Hostname, authentication, salt, s.sessionVars.TLSConnectionState); err != nil { return err } user.AuthUsername = authUser.Username From f3f9a08d7317b94abe7b2b77741426c913dc2608 Mon Sep 17 00:00:00 2001 From: cbcwestwolf <1004626265@qq.com> Date: Fri, 12 Aug 2022 13:25:52 +0800 Subject: [PATCH 08/17] Add basic UT --- server/server_test.go | 46 +++++++++++++++++++++++++++++++++++++++++++ server/tidb_test.go | 2 +- 2 files changed, 47 insertions(+), 1 deletion(-) diff --git a/server/server_test.go b/server/server_test.go index 65cae9bc612eb..c04d5abad4a05 100644 --- a/server/server_test.go +++ b/server/server_test.go @@ -1833,6 +1833,52 @@ func (cli *testServerClient) runTestIssue3682(t *testing.T) { require.Equal(t, "Error 1045: Access denied for user 'issue3682'@'127.0.0.1' (using password: YES)", err.Error()) } +func (cli *testServerClient) runTestAccountLock(t *testing.T) { + cli.runTests(t, nil, func(dbt *testkit.DBTestKit) { + dbt.MustExec(`CREATE USER 'test1','test2' ACCOUNT LOCK;`) + dbt.MustExec(`GRANT ALL on test.* to 'test1', 'test2'`) + dbt.MustExec(`GRANT ALL on mysql.* to 'test1', 'test2'`) + }) + defer cli.runTests(t, nil, func(dbt *testkit.DBTestKit) { + dbt.MustExec(`DROP USER 'test1', 'test2';`) + }) + + // 1. can not connect with a locked user + db, err := sql.Open("mysql", cli.getDSN(func(config *mysql.Config) { + config.User = "test1" + config.DBName = "test" + })) + require.NoError(t, err) + err = db.Ping() + require.Error(t, err) + require.Equal(t, "Error 3118: Access denied for user 'test1'@'127.0.0.1'. Account is locked.", err.Error()) + require.NoError(t, db.Close()) + + // 2. can connect after unlocked + cli.runTests(t, nil, func(dbt *testkit.DBTestKit) { + dbt.MustExec(`ALTER USER 'test1' ACCOUNT UNLOCK;`) + }) + db, err = sql.Open("mysql", cli.getDSN(func(config *mysql.Config) { + config.User = "test1" + config.DBName = "test" + })) + require.NoError(t, err) + require.NoError(t, db.Ping()) + require.NoError(t, db.Close()) + + // 3. if multiple 'ACCOUNT (UN)LOCK' declared, the last declaration takes effect + cli.runTests(t, nil, func(dbt *testkit.DBTestKit) { + rows := dbt.MustQuery(`SELECT user, account_locked FROM mysql.user WHERE user LIKE 'test%' ORDER BY user;`) + cli.checkRows(t, rows, "test1 N", "test2 Y") + dbt.MustExec(`ALTER USER test1, test2 ACCOUNT LOCK ACCOUNT UNLOCK;`) + rows = dbt.MustQuery(`SELECT user, account_locked FROM mysql.user WHERE user LIKE 'test%' ORDER BY user;`) + cli.checkRows(t, rows, "test1 N", "test2 N") + dbt.MustExec(`ALTER USER test1, test2 ACCOUNT UNLOCK ACCOUNT LOCK;`) + rows = dbt.MustQuery(`SELECT user, account_locked FROM mysql.user WHERE user LIKE 'test%' ORDER BY user;`) + cli.checkRows(t, rows, "test1 Y", "test2 Y") + }) +} + func (cli *testServerClient) runTestDBNameEscape(t *testing.T) { cli.runTests(t, nil, func(dbt *testkit.DBTestKit) { dbt.MustExec("CREATE DATABASE `aa-a`;") diff --git a/server/tidb_test.go b/server/tidb_test.go index e0a6d6f35b535..5bcf04f14a13c 100644 --- a/server/tidb_test.go +++ b/server/tidb_test.go @@ -193,7 +193,7 @@ func TestAuth(t *testing.T) { ts.runTestAuth(t) ts.runTestIssue3682(t) - // TODO: Test account lock here + ts.runTestAccountLock(t) } func TestIssues(t *testing.T) { From fcfb8b1efb70e4b49c7a454ced2203c0170597c7 Mon Sep 17 00:00:00 2001 From: cbcwestwolf <1004626265@qq.com> Date: Sat, 13 Aug 2022 18:14:20 +0800 Subject: [PATCH 09/17] Update test --- server/server_test.go | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/server/server_test.go b/server/server_test.go index c04d5abad4a05..dba1a131f70b0 100644 --- a/server/server_test.go +++ b/server/server_test.go @@ -1835,7 +1835,8 @@ func (cli *testServerClient) runTestIssue3682(t *testing.T) { func (cli *testServerClient) runTestAccountLock(t *testing.T) { cli.runTests(t, nil, func(dbt *testkit.DBTestKit) { - dbt.MustExec(`CREATE USER 'test1','test2' ACCOUNT LOCK;`) + dbt.MustExec(`CREATE USER 'test1' ACCOUNT LOCK;`) + dbt.MustExec(`CREATE USER 'test2';`) // unlocked default dbt.MustExec(`GRANT ALL on test.* to 'test1', 'test2'`) dbt.MustExec(`GRANT ALL on mysql.* to 'test1', 'test2'`) }) @@ -1843,7 +1844,7 @@ func (cli *testServerClient) runTestAccountLock(t *testing.T) { dbt.MustExec(`DROP USER 'test1', 'test2';`) }) - // 1. can not connect with a locked user + // 1. test1 can not connect to server db, err := sql.Open("mysql", cli.getDSN(func(config *mysql.Config) { config.User = "test1" config.DBName = "test" @@ -1854,7 +1855,7 @@ func (cli *testServerClient) runTestAccountLock(t *testing.T) { require.Equal(t, "Error 3118: Access denied for user 'test1'@'127.0.0.1'. Account is locked.", err.Error()) require.NoError(t, db.Close()) - // 2. can connect after unlocked + // 2. test1 can connect after unlocked cli.runTests(t, nil, func(dbt *testkit.DBTestKit) { dbt.MustExec(`ALTER USER 'test1' ACCOUNT UNLOCK;`) }) @@ -1869,13 +1870,16 @@ func (cli *testServerClient) runTestAccountLock(t *testing.T) { // 3. if multiple 'ACCOUNT (UN)LOCK' declared, the last declaration takes effect cli.runTests(t, nil, func(dbt *testkit.DBTestKit) { rows := dbt.MustQuery(`SELECT user, account_locked FROM mysql.user WHERE user LIKE 'test%' ORDER BY user;`) - cli.checkRows(t, rows, "test1 N", "test2 Y") - dbt.MustExec(`ALTER USER test1, test2 ACCOUNT LOCK ACCOUNT UNLOCK;`) - rows = dbt.MustQuery(`SELECT user, account_locked FROM mysql.user WHERE user LIKE 'test%' ORDER BY user;`) cli.checkRows(t, rows, "test1 N", "test2 N") dbt.MustExec(`ALTER USER test1, test2 ACCOUNT UNLOCK ACCOUNT LOCK;`) rows = dbt.MustQuery(`SELECT user, account_locked FROM mysql.user WHERE user LIKE 'test%' ORDER BY user;`) cli.checkRows(t, rows, "test1 Y", "test2 Y") + dbt.MustExec(`ALTER USER test1, test2 ACCOUNT LOCK ACCOUNT UNLOCK;`) + rows = dbt.MustQuery(`SELECT user, account_locked FROM mysql.user WHERE user LIKE 'test%' ORDER BY user;`) + cli.checkRows(t, rows, "test1 N", "test2 N") + dbt.MustExec(`ALTER USER test1, test2;`) // if not specified, remain the same + rows = dbt.MustQuery(`SELECT user, account_locked FROM mysql.user WHERE user LIKE 'test%' ORDER BY user;`) + cli.checkRows(t, rows, "test1 N", "test2 N") }) } From dcafd3bc1351b59294c7046a10536139f38c591f Mon Sep 17 00:00:00 2001 From: cbcwestwolf <1004626265@qq.com> Date: Sat, 13 Aug 2022 19:50:56 +0800 Subject: [PATCH 10/17] Add test for role --- server/server_test.go | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/server/server_test.go b/server/server_test.go index dba1a131f70b0..50b2a338a8598 100644 --- a/server/server_test.go +++ b/server/server_test.go @@ -1881,6 +1881,28 @@ func (cli *testServerClient) runTestAccountLock(t *testing.T) { rows = dbt.MustQuery(`SELECT user, account_locked FROM mysql.user WHERE user LIKE 'test%' ORDER BY user;`) cli.checkRows(t, rows, "test1 N", "test2 N") }) + + // 4. A role can be created default with account locked + // After unlocked by the ALTER USER statement, the role can connect to server like a user + cli.runTests(t, nil, func(dbt *testkit.DBTestKit) { + dbt.MustExec(`CREATE ROLE role1;`) + dbt.MustExec(`GRANT ALL on test.* to 'role1'`) + rows := dbt.MustQuery(`SELECT user, account_locked FROM mysql.user WHERE user = 'role1';`) + cli.checkRows(t, rows, "role1 Y") + dbt.MustExec(`ALTER USER role1 ACCOUNT UNLOCK;`) + rows = dbt.MustQuery(`SELECT user, account_locked FROM mysql.user WHERE user = 'role1';`) + cli.checkRows(t, rows, "role1 N") + }) + defer cli.runTests(t, nil, func(dbt *testkit.DBTestKit) { + dbt.MustExec(`DROP ROLE role1;`) + }) + db, err = sql.Open("mysql", cli.getDSN(func(config *mysql.Config) { + config.User = "role1" + config.DBName = "test" + })) + require.NoError(t, err) + require.NoError(t, db.Ping()) + require.NoError(t, db.Close()) } func (cli *testServerClient) runTestDBNameEscape(t *testing.T) { From 549fa41763d2743269c678b854c1edfe18014699 Mon Sep 17 00:00:00 2001 From: cbcwestwolf <1004626265@qq.com> Date: Sun, 14 Aug 2022 00:44:49 +0800 Subject: [PATCH 11/17] Update test --- server/server_test.go | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/server/server_test.go b/server/server_test.go index 50b2a338a8598..b4fc5a9d4cf0f 100644 --- a/server/server_test.go +++ b/server/server_test.go @@ -1883,14 +1883,26 @@ func (cli *testServerClient) runTestAccountLock(t *testing.T) { }) // 4. A role can be created default with account locked - // After unlocked by the ALTER USER statement, the role can connect to server like a user cli.runTests(t, nil, func(dbt *testkit.DBTestKit) { dbt.MustExec(`CREATE ROLE role1;`) dbt.MustExec(`GRANT ALL on test.* to 'role1'`) rows := dbt.MustQuery(`SELECT user, account_locked FROM mysql.user WHERE user = 'role1';`) cli.checkRows(t, rows, "role1 Y") + }) + // When created, the role is locked by default and cannot log in to TiDB + db, err = sql.Open("mysql", cli.getDSN(func(config *mysql.Config) { + config.User = "role1" + config.DBName = "test" + })) + require.NoError(t, err) + err = db.Ping() + require.Error(t, err) + require.Equal(t, "Error 3118: Access denied for user 'role1'@'127.0.0.1'. Account is locked.", err.Error()) + require.NoError(t, db.Close()) + // After unlocked by the ALTER USER statement, the role can connect to server like a user + cli.runTests(t, nil, func(dbt *testkit.DBTestKit) { dbt.MustExec(`ALTER USER role1 ACCOUNT UNLOCK;`) - rows = dbt.MustQuery(`SELECT user, account_locked FROM mysql.user WHERE user = 'role1';`) + rows := dbt.MustQuery(`SELECT user, account_locked FROM mysql.user WHERE user = 'role1';`) cli.checkRows(t, rows, "role1 N") }) defer cli.runTests(t, nil, func(dbt *testkit.DBTestKit) { From db981cfedf73a302dbc23655f706d796c7d5399c Mon Sep 17 00:00:00 2001 From: cbcwestwolf <1004626265@qq.com> Date: Mon, 15 Aug 2022 16:11:51 +0800 Subject: [PATCH 12/17] Update test --- server/server_test.go | 23 +++++++++++++++++++---- 1 file changed, 19 insertions(+), 4 deletions(-) diff --git a/server/server_test.go b/server/server_test.go index b4fc5a9d4cf0f..6f244dd89eaad 100644 --- a/server/server_test.go +++ b/server/server_test.go @@ -1847,7 +1847,6 @@ func (cli *testServerClient) runTestAccountLock(t *testing.T) { // 1. test1 can not connect to server db, err := sql.Open("mysql", cli.getDSN(func(config *mysql.Config) { config.User = "test1" - config.DBName = "test" })) require.NoError(t, err) err = db.Ping() @@ -1861,7 +1860,6 @@ func (cli *testServerClient) runTestAccountLock(t *testing.T) { }) db, err = sql.Open("mysql", cli.getDSN(func(config *mysql.Config) { config.User = "test1" - config.DBName = "test" })) require.NoError(t, err) require.NoError(t, db.Ping()) @@ -1892,7 +1890,6 @@ func (cli *testServerClient) runTestAccountLock(t *testing.T) { // When created, the role is locked by default and cannot log in to TiDB db, err = sql.Open("mysql", cli.getDSN(func(config *mysql.Config) { config.User = "role1" - config.DBName = "test" })) require.NoError(t, err) err = db.Ping() @@ -1910,11 +1907,29 @@ func (cli *testServerClient) runTestAccountLock(t *testing.T) { }) db, err = sql.Open("mysql", cli.getDSN(func(config *mysql.Config) { config.User = "role1" - config.DBName = "test" })) require.NoError(t, err) require.NoError(t, db.Ping()) require.NoError(t, db.Close()) + + // 5. The ability to use a view is not affected by locking the account. + cli.runTests(t, func(config *mysql.Config) { + config.User = "test1" + }, func(dbt *testkit.DBTestKit) { + dbt.MustExec("CREATE TABLE IF NOT EXISTS t (id INT, name VARCHAR(16))") + dbt.MustExec("INSERT INTO t VALUES (1, 'a'), (2, 'b'), (3, 'c')") + }) + cli.runTests(t, nil, func(dbt *testkit.DBTestKit) { + dbt.MustExec(`ALTER USER test1 ACCOUNT LOCK;`) + rows := dbt.MustQuery(`SELECT user, account_locked FROM mysql.user WHERE user = 'test1';`) + cli.checkRows(t, rows, "test1 Y") + _ = dbt.MustExec("CREATE VIEW v AS SELECT name FROM t WHERE id = 2") + rows = dbt.MustQuery("SELECT definer, security_type FROM information_schema.views WHERE table_name = 'v'") + cli.checkRows(t, rows, "root@% DEFINER") + rows = dbt.MustQuery(`SELECT * FROM v;`) + cli.checkRows(t, rows, "b") + }) + } func (cli *testServerClient) runTestDBNameEscape(t *testing.T) { From d5d36d417e97f4674457c7a15edf72f53e45f8b5 Mon Sep 17 00:00:00 2001 From: cbcwestwolf <1004626265@qq.com> Date: Mon, 15 Aug 2022 20:06:23 +0800 Subject: [PATCH 13/17] Fix fmt --- server/server_test.go | 1 - 1 file changed, 1 deletion(-) diff --git a/server/server_test.go b/server/server_test.go index 6f244dd89eaad..7661cb2ab55e5 100644 --- a/server/server_test.go +++ b/server/server_test.go @@ -1929,7 +1929,6 @@ func (cli *testServerClient) runTestAccountLock(t *testing.T) { rows = dbt.MustQuery(`SELECT * FROM v;`) cli.checkRows(t, rows, "b") }) - } func (cli *testServerClient) runTestDBNameEscape(t *testing.T) { From 266f2bd2d8fb6f99f093b4a0c67c303970c7be09 Mon Sep 17 00:00:00 2001 From: cbcwestwolf <1004626265@qq.com> Date: Mon, 15 Aug 2022 22:11:22 +0800 Subject: [PATCH 14/17] Fix --- executor/slow_query_sql_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/executor/slow_query_sql_test.go b/executor/slow_query_sql_test.go index 088869c53f584..a77e32e3bfb16 100644 --- a/executor/slow_query_sql_test.go +++ b/executor/slow_query_sql_test.go @@ -210,7 +210,7 @@ SELECT original_sql, bind_sql, default_db, status, create_time, update_time, cha func TestIssue37066(t *testing.T) { store := testkit.CreateMockStore(t) tk := testkit.NewTestKit(t, store) - require.True(t, tk.Session().Auth(&auth.UserIdentity{Username: "root", Hostname: "%"}, nil, nil)) + require.NoError(t, tk.Session().Auth(&auth.UserIdentity{Username: "root", Hostname: "%"}, nil, nil)) originCfg := config.GetGlobalConfig() newCfg := *originCfg From 32775e47f11ea229ca02832312eb961153996749 Mon Sep 17 00:00:00 2001 From: cbcwestwolf <1004626265@qq.com> Date: Tue, 16 Aug 2022 23:57:51 +0800 Subject: [PATCH 15/17] Fix --- executor/simple.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/executor/simple.go b/executor/simple.go index 20e9787e5ba8d..50057caae1805 100644 --- a/executor/simple.go +++ b/executor/simple.go @@ -1030,7 +1030,7 @@ func (e *SimpleExec) executeAlterUser(ctx context.Context, s *ast.AlterUserStmt) if len(lockAccount) != 0 { _, _, err := exec.ExecRestrictedSQL(ctx, nil, `UPDATE %n.%n SET account_locked=%? WHERE Host=%? and User=%?;`, - mysql.SystemDB, mysql.UserTable, lockAccount, strings.ToLower(spec.User.Hostname), spec.User.Username) + mysql.SystemDB, mysql.UserTable, lockAccount, spec.User.Hostname, spec.User.Username) if err != nil { failedUsers = append(failedUsers, spec.User.String()) } From ff0513ef1e23e1fb4550ae83f53c34d9540a9e11 Mon Sep 17 00:00:00 2001 From: cbcwestwolf <1004626265@qq.com> Date: Fri, 19 Aug 2022 17:49:10 +0800 Subject: [PATCH 16/17] Update --- privilege/privileges/privileges.go | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/privilege/privileges/privileges.go b/privilege/privileges/privileges.go index 140991a73c97c..bbc93baf1757c 100644 --- a/privilege/privileges/privileges.go +++ b/privilege/privileges/privileges.go @@ -309,13 +309,6 @@ func (p *UserPrivileges) ConnectionVerification(user *auth.UserIdentity, authUse } } - // Login a locked account is not allowed. - locked := record.AccountLocked - if locked { - logutil.BgLogger().Error(fmt.Sprintf("Access denied for authUser '%s'@'%s'. Account is locked.", authUser, authHost)) - return errAccountHasBeenLocked.FastGenByArgs(user.Username, user.Hostname) - } - pwd := record.AuthenticationString if !p.isValidHash(record) { return errAccessDenied.FastGenByArgs(user.Username, user.Hostname, hasPassword) @@ -365,6 +358,13 @@ func (p *UserPrivileges) ConnectionVerification(user *auth.UserIdentity, authUse return errAccessDenied.FastGenByArgs(user.Username, user.Hostname, hasPassword) } + // Login a locked account is not allowed. + locked := record.AccountLocked + if locked { + logutil.BgLogger().Error(fmt.Sprintf("Access denied for authUser '%s'@'%s'. Account is locked.", authUser, authHost)) + return errAccountHasBeenLocked.FastGenByArgs(user.Username, user.Hostname) + } + p.user = authUser p.host = record.Host return nil From a6115df8bf9d94029673ff3b86fe6408fc10d8d4 Mon Sep 17 00:00:00 2001 From: cbcwestwolf <1004626265@qq.com> Date: Thu, 25 Aug 2022 15:13:01 +0800 Subject: [PATCH 17/17] Fix UT --- privilege/privileges/privileges.go | 65 +++++++++++++----------------- 1 file changed, 29 insertions(+), 36 deletions(-) diff --git a/privilege/privileges/privileges.go b/privilege/privileges/privileges.go index bbc93baf1757c..53b776a8798d7 100644 --- a/privilege/privileges/privileges.go +++ b/privilege/privileges/privileges.go @@ -314,48 +314,41 @@ func (p *UserPrivileges) ConnectionVerification(user *auth.UserIdentity, authUse return errAccessDenied.FastGenByArgs(user.Username, user.Hostname, hasPassword) } - // empty password - if len(pwd) == 0 && len(authentication) == 0 { - p.user = authUser - p.host = record.Host - return nil - } - - if len(pwd) == 0 || len(authentication) == 0 { - if record.AuthPlugin != mysql.AuthSocket { - return errAccessDenied.FastGenByArgs(user.Username, user.Hostname, hasPassword) - } - } - - if record.AuthPlugin == mysql.AuthNativePassword { - hpwd, err := auth.DecodePassword(pwd) - if err != nil { - logutil.BgLogger().Error("decode password string failed", zap.Error(err)) - return errAccessDenied.FastGenByArgs(user.Username, user.Hostname, hasPassword) - } + if len(pwd) > 0 && len(authentication) > 0 { + if record.AuthPlugin == mysql.AuthNativePassword { + hpwd, err := auth.DecodePassword(pwd) + if err != nil { + logutil.BgLogger().Error("decode password string failed", zap.Error(err)) + return errAccessDenied.FastGenByArgs(user.Username, user.Hostname, hasPassword) + } - if !auth.CheckScrambledPassword(salt, hpwd, authentication) { - return errAccessDenied.FastGenByArgs(user.Username, user.Hostname, hasPassword) - } - } else if record.AuthPlugin == mysql.AuthCachingSha2Password { - authok, err := auth.CheckShaPassword([]byte(pwd), string(authentication)) - if err != nil { - logutil.BgLogger().Error("Failed to check caching_sha2_password", zap.Error(err)) - } + if !auth.CheckScrambledPassword(salt, hpwd, authentication) { + return errAccessDenied.FastGenByArgs(user.Username, user.Hostname, hasPassword) + } + } else if record.AuthPlugin == mysql.AuthCachingSha2Password { + authok, err := auth.CheckShaPassword([]byte(pwd), string(authentication)) + if err != nil { + logutil.BgLogger().Error("Failed to check caching_sha2_password", zap.Error(err)) + } - if !authok { + if !authok { + return errAccessDenied.FastGenByArgs(user.Username, user.Hostname, hasPassword) + } + } else if record.AuthPlugin == mysql.AuthSocket { + if string(authentication) != authUser && string(authentication) != pwd { + logutil.BgLogger().Error("Failed socket auth", zap.String("authUser", authUser), + zap.String("socket_user", string(authentication)), + zap.String("authentication_string", pwd)) + return errAccessDenied.FastGenByArgs(user.Username, user.Hostname, hasPassword) + } + } else { + logutil.BgLogger().Error("unknown authentication plugin", zap.String("authUser", authUser), zap.String("plugin", record.AuthPlugin)) return errAccessDenied.FastGenByArgs(user.Username, user.Hostname, hasPassword) } - } else if record.AuthPlugin == mysql.AuthSocket { - if string(authentication) != authUser && string(authentication) != pwd { - logutil.BgLogger().Error("Failed socket auth", zap.String("authUser", authUser), - zap.String("socket_user", string(authentication)), - zap.String("authentication_string", pwd)) + } else if len(pwd) > 0 || len(authentication) > 0 { + if record.AuthPlugin != mysql.AuthSocket { return errAccessDenied.FastGenByArgs(user.Username, user.Hostname, hasPassword) } - } else { - logutil.BgLogger().Error("unknown authentication plugin", zap.String("authUser", authUser), zap.String("plugin", record.AuthPlugin)) - return errAccessDenied.FastGenByArgs(user.Username, user.Hostname, hasPassword) } // Login a locked account is not allowed.