Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion api/session_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import (
"github.com/gotify/server/v2/model"
"github.com/gotify/server/v2/test/testdb"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/stretchr/testify/suite"
)

Expand All @@ -39,9 +40,12 @@ func (s *SessionSuite) BeforeTest(suiteName, testName string) {
s.notified = false
s.a = &SessionAPI{DB: s.db, NotifyDeleted: s.notify}
Comment thread
jmattheis marked this conversation as resolved.

pw, err := password.CreatePassword("testpass", 5)
require.NoError(s.T(), err)

s.db.CreateUser(&model.User{
Name: "testuser",
Pass: password.CreatePassword("testpass", 5),
Pass: pw,
})
}

Expand Down
33 changes: 30 additions & 3 deletions api/user.go
Original file line number Diff line number Diff line change
Expand Up @@ -188,10 +188,19 @@ func (a *UserAPI) GetCurrentUser(ctx *gin.Context) {
func (a *UserAPI) CreateUser(ctx *gin.Context) {
user := model.CreateUserExternal{}
if err := ctx.Bind(&user); err == nil {
if err := password.ValidateNewPassword(user.Pass); err != nil {
ctx.AbortWithError(http.StatusBadRequest, err)
return
}
pw, err := password.CreatePassword(user.Pass, a.PasswordStrength)
if err != nil {
ctx.AbortWithError(http.StatusInternalServerError, fmt.Errorf("failed to prepare password: %s", err))
return
}
internal := &model.User{
Name: user.Name,
Admin: user.Admin,
Pass: password.CreatePassword(user.Pass, a.PasswordStrength),
Pass: pw,
}
existingUser, err := a.DB.GetUserByName(internal.Name)
if success := successOrAbort(ctx, 500, err); !success {
Expand Down Expand Up @@ -389,11 +398,20 @@ func (a *UserAPI) DeleteUserByID(ctx *gin.Context) {
func (a *UserAPI) ChangePassword(ctx *gin.Context) {
pw := model.UserExternalPass{}
if err := ctx.Bind(&pw); err == nil {
if err := password.ValidateNewPassword(pw.Pass); err != nil {
ctx.AbortWithError(http.StatusBadRequest, err)
return
}
user, err := a.DB.GetUserByID(auth.GetUserID(ctx))
if success := successOrAbort(ctx, 500, err); !success {
return
}
user.Pass = password.CreatePassword(pw.Pass, a.PasswordStrength)
pw, err := password.CreatePassword(pw.Pass, a.PasswordStrength)
if err != nil {
ctx.AbortWithError(http.StatusInternalServerError, fmt.Errorf("failed to prepare password: %s", err))
return
}
user.Pass = pw
successOrAbort(ctx, 500, a.DB.UpdateUser(user))
}
}
Expand Down Expand Up @@ -465,7 +483,16 @@ func (a *UserAPI) UpdateUserByID(ctx *gin.Context) {
dbUser.Admin = updatedUser.Admin

if updatedUser.Pass != "" {
dbUser.Pass = password.CreatePassword(updatedUser.Pass, a.PasswordStrength)
if err := password.ValidateNewPassword(updatedUser.Pass); err != nil {
ctx.AbortWithError(http.StatusBadRequest, err)
return
}
pw, err := password.CreatePassword(updatedUser.Pass, a.PasswordStrength)
if err != nil {
ctx.AbortWithError(http.StatusInternalServerError, fmt.Errorf("failed to prepare password: %s", err))
return
}
dbUser.Pass = pw
}
if success := successOrAbort(ctx, 500, a.DB.UpdateUser(dbUser)); !success {
return
Expand Down
69 changes: 65 additions & 4 deletions api/user_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import (
"github.com/gotify/server/v2/test"
"github.com/gotify/server/v2/test/testdb"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/stretchr/testify/suite"
)

Expand Down Expand Up @@ -320,6 +321,24 @@ func (s *UserSuite) Test_CreateUser_NameAlreadyExists() {
assert.Equal(s.T(), 400, s.recorder.Code)
}

func (s *UserSuite) Test_CreateUser_EmptyPassword_Expect400() {
s.loginAdmin()

s.ctx.Request = httptest.NewRequest("POST", "/user", strings.NewReader(`{"name": "admin", "pass": "", "admin": false}`))
s.ctx.Request.Header.Set("Content-Type", "application/json")
s.a.CreateUser(s.ctx)
assert.Equal(s.T(), 400, s.recorder.Code)
}

func (s *UserSuite) Test_CreateUser_TooLongPassword_Expect400() {
s.loginAdmin()

s.ctx.Request = httptest.NewRequest("POST", "/user", strings.NewReader(`{"name": "admin", "pass": "`+strings.Repeat("a", 100)+`", "admin": false}`))
s.ctx.Request.Header.Set("Content-Type", "application/json")
s.a.CreateUser(s.ctx)
assert.Equal(s.T(), 400, s.recorder.Code)
}

func (s *UserSuite) Test_UpdateUserByID_InvalidID() {
s.ctx.Params = gin.Params{{Key: "id", Value: "abc"}}

Expand All @@ -331,6 +350,28 @@ func (s *UserSuite) Test_UpdateUserByID_InvalidID() {
assert.Equal(s.T(), 400, s.recorder.Code)
}

func (s *UserSuite) Test_UpdateUserByID_EmptyPassword_Expect400() {
s.loginAdmin()

s.ctx.Params = gin.Params{{Key: "id", Value: "1"}}

s.ctx.Request = httptest.NewRequest("POST", "/user/1", strings.NewReader(`{"name": "admin", "pass": "", "admin": false}`))
s.ctx.Request.Header.Set("Content-Type", "application/json")
s.a.UpdateUserByID(s.ctx)
assert.Equal(s.T(), 400, s.recorder.Code)
}

func (s *UserSuite) Test_UpdateUserByID_TooLongPassword_Expect400() {
s.loginAdmin()

s.ctx.Params = gin.Params{{Key: "id", Value: "1"}}

s.ctx.Request = httptest.NewRequest("POST", "/user/1", strings.NewReader(`{"name": "admin", "pass": "`+strings.Repeat("a", 100)+`", "admin": false}`))
s.ctx.Request.Header.Set("Content-Type", "application/json")
s.a.UpdateUserByID(s.ctx)
assert.Equal(s.T(), 400, s.recorder.Code)
}

func (s *UserSuite) Test_UpdateUserByID_LastAdmin_Expect400() {
s.db.CreateUser(&model.User{
ID: 7,
Expand Down Expand Up @@ -359,7 +400,9 @@ func (s *UserSuite) Test_UpdateUserByID_UnknownUser() {
}

func (s *UserSuite) Test_UpdateUserByID_UpdateNotPassword() {
s.db.CreateUser(&model.User{ID: 2, Name: "nico", Pass: password.CreatePassword("old", 5)})
pw, err := password.CreatePassword("old", 5)
require.NoError(s.T(), err)
s.db.CreateUser(&model.User{ID: 2, Name: "nico", Pass: pw})

s.ctx.Params = gin.Params{{Key: "id", Value: "2"}}

Expand All @@ -376,7 +419,9 @@ func (s *UserSuite) Test_UpdateUserByID_UpdateNotPassword() {
}

func (s *UserSuite) Test_UpdateUserByID_UpdatePassword() {
s.db.CreateUser(&model.User{ID: 2, Name: "tom", Pass: password.CreatePassword("old", 5)})
pw, err := password.CreatePassword("old", 5)
require.NoError(s.T(), err)
s.db.CreateUser(&model.User{ID: 2, Name: "tom", Pass: pw})

s.ctx.Params = gin.Params{{Key: "id", Value: "2"}}

Expand Down Expand Up @@ -413,7 +458,9 @@ func (s *UserSuite) Test_UpdateUserByID_PreservesOIDCID() {
}

func (s *UserSuite) Test_UpdatePassword() {
s.db.CreateUser(&model.User{ID: 1, Name: "jmattheis", Pass: password.CreatePassword("old", 5)})
pw, err := password.CreatePassword("old", 5)
require.NoError(s.T(), err)
s.db.CreateUser(&model.User{ID: 1, Name: "jmattheis", Pass: pw})

test.WithUser(s.ctx, 1)
s.ctx.Request = httptest.NewRequest("POST", "/user/current/password", strings.NewReader(`{"pass": "new"}`))
Expand All @@ -429,7 +476,9 @@ func (s *UserSuite) Test_UpdatePassword() {
}

func (s *UserSuite) Test_UpdatePassword_EmptyPassword() {
s.db.CreateUser(&model.User{ID: 1, Name: "jmattheis", Pass: password.CreatePassword("old", 5)})
pw, err := password.CreatePassword("old", 5)
require.NoError(s.T(), err)
s.db.CreateUser(&model.User{ID: 1, Name: "jmattheis", Pass: pw})

test.WithUser(s.ctx, 1)
s.ctx.Request = httptest.NewRequest("POST", "/user/current/password", strings.NewReader(`{"pass":""}`))
Expand All @@ -444,6 +493,18 @@ func (s *UserSuite) Test_UpdatePassword_EmptyPassword() {
assert.True(s.T(), password.ComparePassword(user.Pass, []byte("old")))
}

func (s *UserSuite) Test_UpdatePassword_TooLongPassword_Expect400() {
pw, err := password.CreatePassword("old", 5)
require.NoError(s.T(), err)
s.db.CreateUser(&model.User{ID: 1, Name: "jmattheis", Pass: pw})

test.WithUser(s.ctx, 1)
s.ctx.Request = httptest.NewRequest("POST", "/user/current/password", strings.NewReader(`{"pass": "`+strings.Repeat("a", 100)+`"}`))
s.ctx.Request.Header.Set("Content-Type", "application/json")
s.a.ChangePassword(s.ctx)
assert.Equal(s.T(), 400, s.recorder.Code)
}

func (s *UserSuite) loginAdmin() {
s.db.CreateUser(&model.User{ID: 1, Name: "admin", Admin: true})
auth.RegisterUser(s.ctx, &model.User{ID: 1, Admin: true})
Expand Down
8 changes: 6 additions & 2 deletions auth/authentication_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import (
"github.com/gotify/server/v2/model"
"github.com/gotify/server/v2/test/testdb"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/stretchr/testify/suite"
)

Expand All @@ -37,9 +38,12 @@ func (s *AuthenticationSuite) SetupSuite() {
elevated := now.Add(time.Hour)
expired := now.Add(-time.Hour)

pw, err := password.CreatePassword("pw", 5)
require.NoError(s.T(), err)

s.DB.CreateUser(&model.User{
Name: "existing",
Pass: password.CreatePassword("pw", 5),
Pass: pw,
Admin: false,
Applications: []model.Application{{Token: "apptoken", Name: "backup server1", Description: "irrelevant"}},
Clients: []model.Client{
Expand All @@ -51,7 +55,7 @@ func (s *AuthenticationSuite) SetupSuite() {

s.DB.CreateUser(&model.User{
Name: "admin",
Pass: password.CreatePassword("pw", 5),
Pass: pw,
Admin: true,
Applications: []model.Application{{Token: "apptoken_admin", Name: "backup server2", Description: "irrelevant"}},
Clients: []model.Client{
Expand Down
23 changes: 17 additions & 6 deletions auth/password/password.go
Original file line number Diff line number Diff line change
@@ -1,14 +1,25 @@
package password

import "golang.org/x/crypto/bcrypt"
import (
"errors"

"golang.org/x/crypto/bcrypt"
)

func ValidateNewPassword(pw string) error {
if pw == "" {
Comment thread
jmattheis marked this conversation as resolved.
return errors.New("password must not be empty")
}
if len([]byte(pw)) > 72 {
return bcrypt.ErrPasswordTooLong
}
return nil
}

// CreatePassword returns a hashed version of the given password.
func CreatePassword(pw string, strength int) []byte {
func CreatePassword(pw string, strength int) ([]byte, error) {
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(pw), strength)
if err != nil {
panic(err)
}
return hashedPassword
return hashedPassword, err
}

// ComparePassword compares a hashed password with its possible plaintext equivalent.
Expand Down
14 changes: 10 additions & 4 deletions auth/password/password_test.go
Original file line number Diff line number Diff line change
@@ -1,21 +1,27 @@
package password

import (
"strings"
"testing"

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"golang.org/x/crypto/bcrypt"
)

func TestPasswordSuccess(t *testing.T) {
password := CreatePassword("secret", 5)
password, err := CreatePassword("secret", 5)
require.NoError(t, err)
assert.Equal(t, true, ComparePassword(password, []byte("secret")))
}

func TestPasswordFailure(t *testing.T) {
password := CreatePassword("secret", 5)
password, err := CreatePassword("secret", 5)
require.NoError(t, err)
assert.Equal(t, false, ComparePassword(password, []byte("secretx")))
}

func TestBCryptFailure(t *testing.T) {
assert.Panics(t, func() { CreatePassword("secret", 12312) })
func TestBCryptoTooLongErrorIsReturned(t *testing.T) {
_, err := CreatePassword(strings.Repeat("a", 100), 5)
assert.ErrorIs(t, err, bcrypt.ErrPasswordTooLong)
}
3 changes: 2 additions & 1 deletion config/config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@ func TestConfigEnv(t *testing.T) {
mode.Set(mode.TestDev)
os.Setenv("GOTIFY_DEFAULTUSER_NAME", "jmattheis")
os.Setenv("GOTIFY_SERVER_SSL_LETSENCRYPT_HOSTS", "push.example.tld,push.other.tld")
os.Setenv("GOTIFY_SERVER_RESPONSEHEADERS",
os.Setenv(
"GOTIFY_SERVER_RESPONSEHEADERS",
`{"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"GET,POST"}`,
)
os.Setenv("GOTIFY_SERVER_CORS_ALLOWORIGINS", ".+.example.com,otherdomain.com")
Expand Down
6 changes: 5 additions & 1 deletion database/database.go
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,11 @@ func New(dialect, connection, defaultUser, defaultPass string, strength int, cre
userCount := int64(0)
db.Find(new(model.User)).Count(&userCount)
if createDefaultUserIfNotExist && userCount == 0 {
db.Create(&model.User{Name: defaultUser, Pass: password.CreatePassword(defaultPass, strength), Admin: true})
pass, err := password.CreatePassword(defaultPass, strength)
if err != nil {
return nil, err
}
db.Create(&model.User{Name: defaultUser, Pass: pass, Admin: true})
}

if err := db.Transaction(fillMissingSortKeys, &sql.TxOptions{Isolation: sql.LevelSerializable}); err != nil {
Expand Down
2 changes: 1 addition & 1 deletion plugin/testing/mock/mock.go
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,7 @@ func (c *PluginInstance) DefaultConfig() any {

// ValidateAndSetConfig implements compat.Configuror
func (c *PluginInstance) ValidateAndSetConfig(config any) error {
if (config.(*PluginConfig)).IsNotValid {
if config.(*PluginConfig).IsNotValid {
return errors.New("conf is not valid")
}
c.Config = config.(*PluginConfig)
Expand Down
3 changes: 2 additions & 1 deletion router/router.go
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,8 @@ func Create(db *database.GormDatabase, vInfo *model.VersionInfo, conf *config.Co
})
}
streamHandler := stream.New(
time.Duration(conf.Server.Stream.PingPeriodSeconds)*time.Second, 15*time.Second, conf.Server.Stream.AllowedOrigins)
time.Duration(conf.Server.Stream.PingPeriodSeconds)*time.Second, 15*time.Second, conf.Server.Stream.AllowedOrigins,
)
go func() {
ticker := time.NewTicker(5 * time.Minute)
for range ticker.C {
Expand Down
Loading
Loading