Skip to content
Open
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}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Have you thought about adding validation to the model, and letting the password handling as is? E.g.

	Pass string `json:"pass,omitempty" form:"pass" query:"pass" binding:"required,max=72"`

This likely makes the error message more explicit. I'm okay with the current solution, but this may be a better solution.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We will have to hardcode this number. I can see in the future users might request we migrate to other password hashes so I didn't go that route.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, but the error message will be better, currently it's a 500 internal server error for something that the user provided an invalid value for. How about we do both? Your change and the extra validation?


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
21 changes: 18 additions & 3 deletions api/user.go
Original file line number Diff line number Diff line change
Expand Up @@ -188,10 +188,15 @@ func (a *UserAPI) GetCurrentUser(ctx *gin.Context) {
func (a *UserAPI) CreateUser(ctx *gin.Context) {
user := model.CreateUserExternal{}
if err := ctx.Bind(&user); err == nil {
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 @@ -393,7 +398,12 @@ func (a *UserAPI) ChangePassword(ctx *gin.Context) {
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 +475,12 @@ func (a *UserAPI) UpdateUserByID(ctx *gin.Context) {
dbUser.Admin = updatedUser.Admin

if updatedUser.Pass != "" {
dbUser.Pass = password.CreatePassword(updatedUser.Pass, a.PasswordStrength)
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
17 changes: 13 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 @@ -359,7 +360,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 +379,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 +418,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 +436,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 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
16 changes: 11 additions & 5 deletions auth/password/password.go
Original file line number Diff line number Diff line change
@@ -1,14 +1,20 @@
package password

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

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

var ErrUnexpectedError = errors.New("unexpected error")

// 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)
if err != nil && err != bcrypt.ErrPasswordTooLong {
err = ErrUnexpectedError

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If we mask the error here, we don't get the initial error anywhere, meaning if a user misconfigures the passstrength, it will always return unexpected error without any log about the actual error. I think we can pass the full error without masking into the 500 internal server error, and with the extra validation the length check is done before and results in a 400.

}
return hashedPassword
return hashedPassword, err
}

// ComparePassword compares a hashed password with its possible plaintext equivalent.
Expand Down
19 changes: 15 additions & 4 deletions auth/password/password_test.go
Original file line number Diff line number Diff line change
@@ -1,21 +1,32 @@
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)
}

func TestBCryptErrorIsMasked(t *testing.T) {
_, err := CreatePassword("secret", 12312)
assert.ErrorIs(t, err, ErrUnexpectedError)
}
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
24 changes: 16 additions & 8 deletions router/router_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,8 @@ func (s *IntegrationSuite) BeforeTest(string, string) {
s.db = testdb.NewDBWithDefaultUser(s.T())
assert.Nil(s.T(), err)

g, closable := Create(s.db.GormDatabase,
g, closable := Create(
s.db.GormDatabase,
&model.VersionInfo{Version: "1.0.0", BuildDate: "2018-02-20-17:30:47", Commit: "asdasds"},
&config.Configuration{PassStrength: 5},
)
Expand Down Expand Up @@ -79,7 +80,8 @@ func TestHeadersFromConfiguration(t *testing.T) {
"Access-Control-Allow-Origin": "http://test1.com",
}

g, closable := Create(db.GormDatabase,
g, closable := Create(
db.GormDatabase,
&model.VersionInfo{Version: "1.0.0", BuildDate: "2018-02-20-17:30:47", Commit: "asdasds"},
&config,
)
Expand Down Expand Up @@ -108,7 +110,8 @@ func TestHeadersFromCORSConfig(t *testing.T) {
config := config.Configuration{PassStrength: 5}
config.Server.Cors.AllowOrigins = []string{"---", "http://test.com"}

g, closable := Create(db.GormDatabase,
g, closable := Create(
db.GormDatabase,
&model.VersionInfo{Version: "1.0.0", BuildDate: "2018-02-20-17:30:47", Commit: "asdasds"},
&config,
)
Expand Down Expand Up @@ -137,7 +140,8 @@ func TestInvalidOrigin(t *testing.T) {
config := config.Configuration{PassStrength: 5}
config.Server.Cors.AllowOrigins = []string{"---", "http://test.com"}

g, closable := Create(db.GormDatabase,
g, closable := Create(
db.GormDatabase,
&model.VersionInfo{Version: "1.0.0", BuildDate: "2018-02-20-17:30:47", Commit: "asdasds"},
&config,
)
Expand Down Expand Up @@ -169,7 +173,8 @@ func TestAllowedOriginFromResponseHeaders(t *testing.T) {
"Access-Control-Allow-Methods": "GET,POST",
}

g, closable := Create(db.GormDatabase,
g, closable := Create(
db.GormDatabase,
&model.VersionInfo{Version: "1.0.0", BuildDate: "2018-02-20-17:30:47", Commit: "asdasds"},
&config,
)
Expand Down Expand Up @@ -207,7 +212,8 @@ func TestAllowedWildcardOriginInHeader(t *testing.T) {
"Access-Control-Allow-Methods": "GET,POST",
}

g, closable := Create(db.GormDatabase,
g, closable := Create(
db.GormDatabase,
&model.VersionInfo{Version: "1.0.0", BuildDate: "2018-02-20-17:30:47", Commit: "asdasds"},
&config,
)
Expand Down Expand Up @@ -236,7 +242,8 @@ func TestCORSHeaderRegex(t *testing.T) {
config := config.Configuration{PassStrength: 5}
config.Server.Cors.AllowOrigins = []string{"---", "^http://test\\d{3}.com$"}

g, closable := Create(db.GormDatabase,
g, closable := Create(
db.GormDatabase,
&model.VersionInfo{Version: "1.0.0", BuildDate: "2018-02-20-17:30:47", Commit: "asdasds"},
&config,
)
Expand Down Expand Up @@ -274,7 +281,8 @@ func TestCORSConfigOverride(t *testing.T) {
config.Server.Cors.AllowMethods = []string{"GET", "OPTIONS"}
config.Server.Cors.AllowHeaders = []string{"Content-Type"}

g, closable := Create(db.GormDatabase,
g, closable := Create(
db.GormDatabase,
&model.VersionInfo{Version: "1.0.0", BuildDate: "2018-02-20-17:30:47", Commit: "asdasds"},
&config,
)
Expand Down
Loading