2021-11-18 20:42:27 +03:00
|
|
|
// Copyright 2021 The Gitea Authors. All rights reserved.
|
2022-11-27 21:20:29 +03:00
|
|
|
// SPDX-License-Identifier: MIT
|
2021-11-18 20:42:27 +03:00
|
|
|
|
|
|
|
package user
|
|
|
|
|
|
|
|
import (
|
2023-08-03 04:38:51 +03:00
|
|
|
"fmt"
|
2024-12-06 00:32:09 +03:00
|
|
|
"os"
|
|
|
|
"path/filepath"
|
2023-08-03 04:38:51 +03:00
|
|
|
"strings"
|
2021-11-18 20:42:27 +03:00
|
|
|
"testing"
|
2024-03-29 16:53:56 +03:00
|
|
|
"time"
|
2021-11-18 20:42:27 +03:00
|
|
|
|
|
|
|
"code.gitea.io/gitea/models"
|
2024-12-06 00:32:09 +03:00
|
|
|
asymkey_model "code.gitea.io/gitea/models/asymkey"
|
2023-08-03 04:38:51 +03:00
|
|
|
"code.gitea.io/gitea/models/auth"
|
2021-11-18 20:42:27 +03:00
|
|
|
"code.gitea.io/gitea/models/db"
|
2022-03-29 09:29:02 +03:00
|
|
|
"code.gitea.io/gitea/models/organization"
|
2021-12-10 04:27:50 +03:00
|
|
|
repo_model "code.gitea.io/gitea/models/repo"
|
2021-11-18 20:42:27 +03:00
|
|
|
"code.gitea.io/gitea/models/unittest"
|
2021-11-24 12:49:20 +03:00
|
|
|
user_model "code.gitea.io/gitea/models/user"
|
2021-11-18 20:42:27 +03:00
|
|
|
"code.gitea.io/gitea/modules/setting"
|
2024-12-06 00:32:09 +03:00
|
|
|
"code.gitea.io/gitea/modules/test"
|
2024-03-29 16:53:56 +03:00
|
|
|
"code.gitea.io/gitea/modules/timeutil"
|
2021-11-18 20:42:27 +03:00
|
|
|
|
|
|
|
"github.com/stretchr/testify/assert"
|
2024-07-30 22:41:10 +03:00
|
|
|
"github.com/stretchr/testify/require"
|
2021-11-18 20:42:27 +03:00
|
|
|
)
|
|
|
|
|
|
|
|
func TestMain(m *testing.M) {
|
2023-09-28 04:38:53 +03:00
|
|
|
unittest.MainTest(m)
|
2021-11-18 20:42:27 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
func TestDeleteUser(t *testing.T) {
|
|
|
|
test := func(userID int64) {
|
2024-07-30 22:41:10 +03:00
|
|
|
require.NoError(t, unittest.PrepareTestDatabase())
|
2022-08-16 05:22:25 +03:00
|
|
|
user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: userID})
|
2021-11-18 20:42:27 +03:00
|
|
|
|
2021-12-10 04:27:50 +03:00
|
|
|
ownedRepos := make([]*repo_model.Repository, 0, 10)
|
2024-07-30 22:41:10 +03:00
|
|
|
require.NoError(t, db.GetEngine(db.DefaultContext).Find(&ownedRepos, &repo_model.Repository{OwnerID: userID}))
|
2021-11-18 20:42:27 +03:00
|
|
|
if len(ownedRepos) > 0 {
|
2022-07-14 10:22:09 +03:00
|
|
|
err := DeleteUser(db.DefaultContext, user, false)
|
2024-07-30 22:41:10 +03:00
|
|
|
require.Error(t, err)
|
2021-11-18 20:42:27 +03:00
|
|
|
assert.True(t, models.IsErrUserOwnRepos(err))
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2022-03-29 09:29:02 +03:00
|
|
|
orgUsers := make([]*organization.OrgUser, 0, 10)
|
2024-07-30 22:41:10 +03:00
|
|
|
require.NoError(t, db.GetEngine(db.DefaultContext).Find(&orgUsers, &organization.OrgUser{UID: userID}))
|
2021-11-18 20:42:27 +03:00
|
|
|
for _, orgUser := range orgUsers {
|
2023-10-15 18:46:06 +03:00
|
|
|
if err := models.RemoveOrgUser(db.DefaultContext, orgUser.OrgID, orgUser.UID); err != nil {
|
2022-03-29 09:29:02 +03:00
|
|
|
assert.True(t, organization.IsErrLastOrgOwner(err))
|
2021-11-18 20:42:27 +03:00
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
2024-07-30 22:41:10 +03:00
|
|
|
require.NoError(t, DeleteUser(db.DefaultContext, user, false))
|
2021-11-24 12:49:20 +03:00
|
|
|
unittest.AssertNotExistsBean(t, &user_model.User{ID: userID})
|
2021-12-10 04:27:50 +03:00
|
|
|
unittest.CheckConsistencyFor(t, &user_model.User{}, &repo_model.Repository{})
|
2021-11-18 20:42:27 +03:00
|
|
|
}
|
|
|
|
test(2)
|
|
|
|
test(4)
|
|
|
|
test(8)
|
|
|
|
test(11)
|
|
|
|
|
2022-08-16 05:22:25 +03:00
|
|
|
org := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 3})
|
2024-07-30 22:41:10 +03:00
|
|
|
require.Error(t, DeleteUser(db.DefaultContext, org, false))
|
2021-11-18 20:42:27 +03:00
|
|
|
}
|
|
|
|
|
2022-07-22 00:31:22 +03:00
|
|
|
func TestPurgeUser(t *testing.T) {
|
2024-12-06 00:32:09 +03:00
|
|
|
defer unittest.OverrideFixtures(
|
|
|
|
unittest.FixturesOptions{
|
|
|
|
Dir: filepath.Join(setting.AppWorkPath, "models/fixtures/"),
|
|
|
|
Base: setting.AppWorkPath,
|
|
|
|
Dirs: []string{"services/user/TestPurgeUser/"},
|
|
|
|
},
|
|
|
|
)()
|
|
|
|
require.NoError(t, unittest.PrepareTestDatabase())
|
|
|
|
defer test.MockVariableValue(&setting.SSH.RootPath, t.TempDir())()
|
|
|
|
defer test.MockVariableValue(&setting.SSH.CreateAuthorizedKeysFile, true)()
|
|
|
|
defer test.MockVariableValue(&setting.SSH.CreateAuthorizedPrincipalsFile, true)()
|
|
|
|
defer test.MockVariableValue(&setting.SSH.StartBuiltinServer, false)()
|
|
|
|
require.NoError(t, asymkey_model.RewriteAllPublicKeys(db.DefaultContext))
|
|
|
|
require.NoError(t, asymkey_model.RewriteAllPrincipalKeys(db.DefaultContext))
|
|
|
|
|
|
|
|
test := func(userID int64, modifySSHKey bool) {
|
2024-07-30 22:41:10 +03:00
|
|
|
require.NoError(t, unittest.PrepareTestDatabase())
|
2022-08-16 05:22:25 +03:00
|
|
|
user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: userID})
|
2022-07-22 00:31:22 +03:00
|
|
|
|
2024-12-06 00:32:09 +03:00
|
|
|
fAuthorizedKeys, err := os.Open(filepath.Join(setting.SSH.RootPath, "authorized_keys"))
|
|
|
|
require.NoError(t, err)
|
|
|
|
authorizedKeysStatBefore, err := fAuthorizedKeys.Stat()
|
|
|
|
require.NoError(t, err)
|
|
|
|
fAuthorizedPrincipals, err := os.Open(filepath.Join(setting.SSH.RootPath, "authorized_principals"))
|
|
|
|
require.NoError(t, err)
|
|
|
|
authorizedPrincipalsBefore, err := fAuthorizedPrincipals.Stat()
|
2024-07-30 22:41:10 +03:00
|
|
|
require.NoError(t, err)
|
2022-07-22 00:31:22 +03:00
|
|
|
|
2024-12-06 00:32:09 +03:00
|
|
|
require.NoError(t, DeleteUser(db.DefaultContext, user, true))
|
|
|
|
|
2022-07-22 00:31:22 +03:00
|
|
|
unittest.AssertNotExistsBean(t, &user_model.User{ID: userID})
|
|
|
|
unittest.CheckConsistencyFor(t, &user_model.User{}, &repo_model.Repository{})
|
2024-12-06 00:32:09 +03:00
|
|
|
|
|
|
|
fAuthorizedKeys, err = os.Open(filepath.Join(setting.SSH.RootPath, "authorized_keys"))
|
|
|
|
require.NoError(t, err)
|
|
|
|
fAuthorizedPrincipals, err = os.Open(filepath.Join(setting.SSH.RootPath, "authorized_principals"))
|
|
|
|
require.NoError(t, err)
|
|
|
|
|
|
|
|
authorizedKeysStatAfter, err := fAuthorizedKeys.Stat()
|
|
|
|
require.NoError(t, err)
|
|
|
|
authorizedPrincipalsAfter, err := fAuthorizedPrincipals.Stat()
|
|
|
|
require.NoError(t, err)
|
|
|
|
|
|
|
|
if modifySSHKey {
|
|
|
|
assert.Greater(t, authorizedKeysStatAfter.ModTime(), authorizedKeysStatBefore.ModTime())
|
|
|
|
assert.Greater(t, authorizedPrincipalsAfter.ModTime(), authorizedPrincipalsBefore.ModTime())
|
|
|
|
} else {
|
|
|
|
assert.Equal(t, authorizedKeysStatAfter.ModTime(), authorizedKeysStatBefore.ModTime())
|
|
|
|
assert.Equal(t, authorizedPrincipalsAfter.ModTime(), authorizedPrincipalsBefore.ModTime())
|
|
|
|
}
|
2022-07-22 00:31:22 +03:00
|
|
|
}
|
2024-12-06 00:32:09 +03:00
|
|
|
test(2, true)
|
|
|
|
test(4, false)
|
|
|
|
test(8, false)
|
|
|
|
test(11, false)
|
2022-07-22 00:31:22 +03:00
|
|
|
|
2022-08-16 05:22:25 +03:00
|
|
|
org := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 3})
|
2024-07-30 22:41:10 +03:00
|
|
|
require.Error(t, DeleteUser(db.DefaultContext, org, false))
|
2022-07-22 00:31:22 +03:00
|
|
|
}
|
|
|
|
|
2021-11-18 20:42:27 +03:00
|
|
|
func TestCreateUser(t *testing.T) {
|
2021-11-24 12:49:20 +03:00
|
|
|
user := &user_model.User{
|
2021-11-18 20:42:27 +03:00
|
|
|
Name: "GiteaBot",
|
|
|
|
Email: "GiteaBot@gitea.io",
|
|
|
|
Passwd: ";p['////..-++']",
|
|
|
|
IsAdmin: false,
|
|
|
|
Theme: setting.UI.DefaultTheme,
|
|
|
|
MustChangePassword: false,
|
|
|
|
}
|
|
|
|
|
2024-07-30 22:41:10 +03:00
|
|
|
require.NoError(t, user_model.CreateUser(db.DefaultContext, user))
|
2021-11-18 20:42:27 +03:00
|
|
|
|
2024-07-30 22:41:10 +03:00
|
|
|
require.NoError(t, DeleteUser(db.DefaultContext, user, false))
|
2021-11-18 20:42:27 +03:00
|
|
|
}
|
|
|
|
|
2023-08-03 04:38:51 +03:00
|
|
|
func TestRenameUser(t *testing.T) {
|
2024-07-30 22:41:10 +03:00
|
|
|
require.NoError(t, unittest.PrepareTestDatabase())
|
2023-08-03 04:38:51 +03:00
|
|
|
user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 21})
|
|
|
|
|
|
|
|
t.Run("Non-Local", func(t *testing.T) {
|
|
|
|
u := &user_model.User{
|
|
|
|
Type: user_model.UserTypeIndividual,
|
|
|
|
LoginType: auth.OAuth2,
|
|
|
|
}
|
2024-07-30 22:41:10 +03:00
|
|
|
require.ErrorIs(t, RenameUser(db.DefaultContext, u, "user_rename"), user_model.ErrUserIsNotLocal{})
|
2023-08-03 04:38:51 +03:00
|
|
|
})
|
|
|
|
|
|
|
|
t.Run("Same username", func(t *testing.T) {
|
2024-07-30 22:41:10 +03:00
|
|
|
require.NoError(t, RenameUser(db.DefaultContext, user, user.Name))
|
2023-08-03 04:38:51 +03:00
|
|
|
})
|
|
|
|
|
|
|
|
t.Run("Non usable username", func(t *testing.T) {
|
2024-10-13 10:13:04 +03:00
|
|
|
usernames := []string{"--diff", ".well-known", "gitea-actions", "aaa.atom", "aa.png"}
|
2023-08-03 04:38:51 +03:00
|
|
|
for _, username := range usernames {
|
2024-10-13 10:13:04 +03:00
|
|
|
require.Error(t, user_model.IsUsableUsername(username), "non-usable username: %s", username)
|
|
|
|
require.Error(t, RenameUser(db.DefaultContext, user, username), "non-usable username: %s", username)
|
2023-08-03 04:38:51 +03:00
|
|
|
}
|
|
|
|
})
|
|
|
|
|
|
|
|
t.Run("Only capitalization", func(t *testing.T) {
|
|
|
|
caps := strings.ToUpper(user.Name)
|
|
|
|
unittest.AssertNotExistsBean(t, &user_model.User{ID: user.ID, Name: caps})
|
|
|
|
unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{OwnerID: user.ID, OwnerName: user.Name})
|
|
|
|
|
2024-07-30 22:41:10 +03:00
|
|
|
require.NoError(t, RenameUser(db.DefaultContext, user, caps))
|
2023-08-03 04:38:51 +03:00
|
|
|
|
|
|
|
unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: user.ID, Name: caps})
|
|
|
|
unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{OwnerID: user.ID, OwnerName: caps})
|
|
|
|
})
|
|
|
|
|
|
|
|
t.Run("Already exists", func(t *testing.T) {
|
|
|
|
existUser := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1})
|
|
|
|
|
2024-07-30 22:41:10 +03:00
|
|
|
require.ErrorIs(t, RenameUser(db.DefaultContext, user, existUser.Name), user_model.ErrUserAlreadyExist{Name: existUser.Name})
|
|
|
|
require.ErrorIs(t, RenameUser(db.DefaultContext, user, existUser.LowerName), user_model.ErrUserAlreadyExist{Name: existUser.LowerName})
|
2023-08-03 04:38:51 +03:00
|
|
|
newUsername := fmt.Sprintf("uSEr%d", existUser.ID)
|
2024-07-30 22:41:10 +03:00
|
|
|
require.ErrorIs(t, RenameUser(db.DefaultContext, user, newUsername), user_model.ErrUserAlreadyExist{Name: newUsername})
|
2023-08-03 04:38:51 +03:00
|
|
|
})
|
|
|
|
|
|
|
|
t.Run("Normal", func(t *testing.T) {
|
|
|
|
oldUsername := user.Name
|
|
|
|
newUsername := "User_Rename"
|
|
|
|
|
2024-07-30 22:41:10 +03:00
|
|
|
require.NoError(t, RenameUser(db.DefaultContext, user, newUsername))
|
2023-08-03 04:38:51 +03:00
|
|
|
unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: user.ID, Name: newUsername, LowerName: strings.ToLower(newUsername)})
|
|
|
|
|
2023-09-25 16:17:37 +03:00
|
|
|
redirectUID, err := user_model.LookupUserRedirect(db.DefaultContext, oldUsername)
|
2024-07-30 22:41:10 +03:00
|
|
|
require.NoError(t, err)
|
2023-08-03 04:38:51 +03:00
|
|
|
assert.EqualValues(t, user.ID, redirectUID)
|
|
|
|
|
|
|
|
unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{OwnerID: user.ID, OwnerName: user.Name})
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2021-11-18 20:42:27 +03:00
|
|
|
func TestCreateUser_Issue5882(t *testing.T) {
|
|
|
|
// Init settings
|
|
|
|
_ = setting.Admin
|
|
|
|
|
|
|
|
passwd := ".//.;1;;//.,-=_"
|
|
|
|
|
|
|
|
tt := []struct {
|
2021-11-24 12:49:20 +03:00
|
|
|
user *user_model.User
|
2021-11-18 20:42:27 +03:00
|
|
|
disableOrgCreation bool
|
|
|
|
}{
|
2021-11-24 12:49:20 +03:00
|
|
|
{&user_model.User{Name: "GiteaBot", Email: "GiteaBot@gitea.io", Passwd: passwd, MustChangePassword: false}, false},
|
|
|
|
{&user_model.User{Name: "GiteaBot2", Email: "GiteaBot2@gitea.io", Passwd: passwd, MustChangePassword: false}, true},
|
2021-11-18 20:42:27 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
setting.Service.DefaultAllowCreateOrganization = true
|
|
|
|
|
|
|
|
for _, v := range tt {
|
|
|
|
setting.Admin.DisableRegularOrgCreation = v.disableOrgCreation
|
|
|
|
|
2024-07-30 22:41:10 +03:00
|
|
|
require.NoError(t, user_model.CreateUser(db.DefaultContext, v.user))
|
2021-11-18 20:42:27 +03:00
|
|
|
|
Add context cache as a request level cache (#22294)
To avoid duplicated load of the same data in an HTTP request, we can set
a context cache to do that. i.e. Some pages may load a user from a
database with the same id in different areas on the same page. But the
code is hidden in two different deep logic. How should we share the
user? As a result of this PR, now if both entry functions accept
`context.Context` as the first parameter and we just need to refactor
`GetUserByID` to reuse the user from the context cache. Then it will not
be loaded twice on an HTTP request.
But of course, sometimes we would like to reload an object from the
database, that's why `RemoveContextData` is also exposed.
The core context cache is here. It defines a new context
```go
type cacheContext struct {
ctx context.Context
data map[any]map[any]any
lock sync.RWMutex
}
var cacheContextKey = struct{}{}
func WithCacheContext(ctx context.Context) context.Context {
return context.WithValue(ctx, cacheContextKey, &cacheContext{
ctx: ctx,
data: make(map[any]map[any]any),
})
}
```
Then you can use the below 4 methods to read/write/del the data within
the same context.
```go
func GetContextData(ctx context.Context, tp, key any) any
func SetContextData(ctx context.Context, tp, key, value any)
func RemoveContextData(ctx context.Context, tp, key any)
func GetWithContextCache[T any](ctx context.Context, cacheGroupKey string, cacheTargetID any, f func() (T, error)) (T, error)
```
Then let's take a look at how `system.GetString` implement it.
```go
func GetSetting(ctx context.Context, key string) (string, error) {
return cache.GetWithContextCache(ctx, contextCacheKey, key, func() (string, error) {
return cache.GetString(genSettingCacheKey(key), func() (string, error) {
res, err := GetSettingNoCache(ctx, key)
if err != nil {
return "", err
}
return res.SettingValue, nil
})
})
}
```
First, it will check if context data include the setting object with the
key. If not, it will query from the global cache which may be memory or
a Redis cache. If not, it will get the object from the database. In the
end, if the object gets from the global cache or database, it will be
set into the context cache.
An object stored in the context cache will only be destroyed after the
context disappeared.
2023-02-15 16:37:34 +03:00
|
|
|
u, err := user_model.GetUserByEmail(db.DefaultContext, v.user.Email)
|
2024-07-30 22:41:10 +03:00
|
|
|
require.NoError(t, err)
|
2021-11-18 20:42:27 +03:00
|
|
|
|
|
|
|
assert.Equal(t, !u.AllowCreateOrganization, v.disableOrgCreation)
|
|
|
|
|
2024-07-30 22:41:10 +03:00
|
|
|
require.NoError(t, DeleteUser(db.DefaultContext, v.user, false))
|
2021-11-18 20:42:27 +03:00
|
|
|
}
|
|
|
|
}
|
2024-03-29 16:53:56 +03:00
|
|
|
|
|
|
|
func TestDeleteInactiveUsers(t *testing.T) {
|
2024-07-30 22:41:10 +03:00
|
|
|
require.NoError(t, unittest.PrepareTestDatabase())
|
2024-03-29 16:53:56 +03:00
|
|
|
// Add an inactive user older than a minute, with an associated email_address record.
|
|
|
|
oldUser := &user_model.User{Name: "OldInactive", LowerName: "oldinactive", Email: "old@example.com", CreatedUnix: timeutil.TimeStampNow().Add(-120)}
|
|
|
|
_, err := db.GetEngine(db.DefaultContext).NoAutoTime().Insert(oldUser)
|
2024-07-30 22:41:10 +03:00
|
|
|
require.NoError(t, err)
|
2024-03-29 16:53:56 +03:00
|
|
|
oldEmail := &user_model.EmailAddress{UID: oldUser.ID, IsPrimary: true, Email: "old@example.com", LowerEmail: "old@example.com"}
|
|
|
|
err = db.Insert(db.DefaultContext, oldEmail)
|
2024-07-30 22:41:10 +03:00
|
|
|
require.NoError(t, err)
|
2024-03-29 16:53:56 +03:00
|
|
|
|
|
|
|
// Add an inactive user that's not older than a minute, with an associated email_address record.
|
|
|
|
newUser := &user_model.User{Name: "NewInactive", LowerName: "newinactive", Email: "new@example.com"}
|
|
|
|
err = db.Insert(db.DefaultContext, newUser)
|
2024-07-30 22:41:10 +03:00
|
|
|
require.NoError(t, err)
|
2024-03-29 16:53:56 +03:00
|
|
|
newEmail := &user_model.EmailAddress{UID: newUser.ID, IsPrimary: true, Email: "new@example.com", LowerEmail: "new@example.com"}
|
|
|
|
err = db.Insert(db.DefaultContext, newEmail)
|
2024-07-30 22:41:10 +03:00
|
|
|
require.NoError(t, err)
|
2024-03-29 16:53:56 +03:00
|
|
|
|
|
|
|
err = DeleteInactiveUsers(db.DefaultContext, time.Minute)
|
2024-07-30 22:41:10 +03:00
|
|
|
require.NoError(t, err)
|
2024-03-29 16:53:56 +03:00
|
|
|
|
|
|
|
// User older than a minute should be deleted along with their email address.
|
|
|
|
unittest.AssertExistsIf(t, false, oldUser)
|
|
|
|
unittest.AssertExistsIf(t, false, oldEmail)
|
|
|
|
|
|
|
|
// User not older than a minute shouldn't be deleted and their emaill address should still exist.
|
|
|
|
unittest.AssertExistsIf(t, true, newUser)
|
|
|
|
unittest.AssertExistsIf(t, true, newEmail)
|
|
|
|
}
|