1
0
Fork 0
mirror of https://codeberg.org/forgejo/forgejo.git synced 2025-08-05 09:55:20 +02:00

chore(sec): unify usage of crypto/rand.Read (#7453)

- Unify the usage of [`crypto/rand.Read`](https://pkg.go.dev/crypto/rand#Read) to `util.CryptoRandomBytes`.
- Refactor `util.CryptoRandomBytes` to never return an error. It is documented by Go, https://go.dev/issue/66821, to always succeed. So if we still receive a error or if the returned bytes read is not equal to the expected bytes to be read we panic (just to be on the safe side).
- This simplifies a lot of code to no longer care about error handling.

Reviewed-on: https://codeberg.org/forgejo/forgejo/pulls/7453
Reviewed-by: Earl Warren <earl-warren@noreply.codeberg.org>
Co-authored-by: Gusted <postmaster@gusted.xyz>
Co-committed-by: Gusted <postmaster@gusted.xyz>
This commit is contained in:
Gusted 2025-04-04 03:31:37 +00:00 committed by Earl Warren
parent 99fc04b763
commit 53df0bf9a4
25 changed files with 61 additions and 163 deletions

View file

@ -387,9 +387,7 @@ func (u *User) SetPassword(passwd string) (err error) {
return err
}
if u.Salt, err = GetUserSalt(); err != nil {
return err
}
u.Salt = GetUserSalt()
if u.Passwd, err = hash.Parse(setting.PasswordHashAlgo).Hash(passwd, u.Salt); err != nil {
return err
}
@ -559,13 +557,9 @@ func IsUserExist(ctx context.Context, uid int64, name string) (bool, error) {
const SaltByteLength = 16
// GetUserSalt returns a random user salt token.
func GetUserSalt() (string, error) {
rBytes, err := util.CryptoRandomBytes(SaltByteLength)
if err != nil {
return "", err
}
func GetUserSalt() string {
// Returns a 32 bytes long string.
return hex.EncodeToString(rBytes), nil
return hex.EncodeToString(util.CryptoRandomBytes(SaltByteLength))
}
// Note: The set of characters here can safely expand without a breaking change,
@ -772,9 +766,7 @@ func createUser(ctx context.Context, u *User, createdByAdmin bool, overwriteDefa
u.LowerName = strings.ToLower(u.Name)
u.AvatarEmail = u.Email
if u.Rands, err = GetUserSalt(); err != nil {
return err
}
u.Rands = GetUserSalt()
if u.Passwd != "" {
if err = u.SetPassword(u.Passwd); err != nil {
return err