lib/config: Move the bcrypt password hashing to GUIConfiguration (#8028)
What hash is used to store the password should ideally be an implementation detail, so that every user of the GUIConfiguration object automatically agrees on how to handle it. That is currently distribututed over the confighandler.go and api_auth.go files, plus tests. Add the SetHasedPassword() / CompareHashedPassword() API to keep the hashing method encapsulated. Add a separate test for it and adjust other users and tests. Remove all deprecated imports of the bcrypt package.
This commit is contained in:
@@ -739,6 +739,27 @@ func TestGUIConfigURL(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestGUIPasswordHash(t *testing.T) {
|
||||
var c GUIConfiguration
|
||||
|
||||
testPass := "pass"
|
||||
if err := c.HashAndSetPassword(testPass); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if c.Password == testPass {
|
||||
t.Error("Password hashing resulted in plaintext")
|
||||
}
|
||||
|
||||
if err := c.CompareHashedPassword(testPass); err != nil {
|
||||
t.Errorf("No match on same password: %v", err)
|
||||
}
|
||||
|
||||
failPass := "different"
|
||||
if err := c.CompareHashedPassword(failPass); err == nil {
|
||||
t.Errorf("Match on different password: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDuplicateDevices(t *testing.T) {
|
||||
// Duplicate devices should be removed
|
||||
|
||||
|
||||
@@ -12,6 +12,8 @@ import (
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
|
||||
"github.com/syncthing/syncthing/lib/rand"
|
||||
)
|
||||
|
||||
@@ -113,6 +115,23 @@ func (c GUIConfiguration) URL() string {
|
||||
return u.String()
|
||||
}
|
||||
|
||||
// SetHashedPassword hashes the given plaintext password and stores the new hash.
|
||||
func (c *GUIConfiguration) HashAndSetPassword(password string) error {
|
||||
hash, err := bcrypt.GenerateFromPassword([]byte(password), 0)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
c.Password = string(hash)
|
||||
return nil
|
||||
}
|
||||
|
||||
// CompareHashedPassword returns nil when the given plaintext password matches the stored hash.
|
||||
func (c GUIConfiguration) CompareHashedPassword(password string) error {
|
||||
configPasswordBytes := []byte(c.Password)
|
||||
passwordBytes := []byte(password)
|
||||
return bcrypt.CompareHashAndPassword(configPasswordBytes, passwordBytes)
|
||||
}
|
||||
|
||||
// IsValidAPIKey returns true when the given API key is valid, including both
|
||||
// the value in config and any overrides
|
||||
func (c GUIConfiguration) IsValidAPIKey(apiKey string) bool {
|
||||
|
||||
Reference in New Issue
Block a user