mirror of
https://codeberg.org/forgejo/forgejo.git
synced 2025-08-01 17:38:33 +00: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:
parent
99fc04b763
commit
53df0bf9a4
25 changed files with 61 additions and 163 deletions
|
@ -5,10 +5,8 @@
|
|||
package generate
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"io"
|
||||
"time"
|
||||
|
||||
"forgejo.org/modules/util"
|
||||
|
@ -18,18 +16,11 @@ import (
|
|||
|
||||
// NewInternalToken generate a new value intended to be used by INTERNAL_TOKEN.
|
||||
func NewInternalToken() (string, error) {
|
||||
secretBytes := make([]byte, 32)
|
||||
_, err := io.ReadFull(rand.Reader, secretBytes)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
secretKey := base64.RawURLEncoding.EncodeToString(secretBytes)
|
||||
secretKey := base64.RawURLEncoding.EncodeToString(util.CryptoRandomBytes(32))
|
||||
|
||||
now := time.Now()
|
||||
|
||||
var internalToken string
|
||||
internalToken, err = jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
|
||||
internalToken, err := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
|
||||
"nbf": now.Unix(),
|
||||
}).SignedString([]byte(secretKey))
|
||||
if err != nil {
|
||||
|
@ -54,14 +45,9 @@ func DecodeJwtSecret(src string) ([]byte, error) {
|
|||
}
|
||||
|
||||
// NewJwtSecret generates a new base64 encoded value intended to be used for JWT secrets.
|
||||
func NewJwtSecret() ([]byte, string, error) {
|
||||
bytes := make([]byte, 32)
|
||||
_, err := rand.Read(bytes)
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
|
||||
return bytes, base64.RawURLEncoding.EncodeToString(bytes), nil
|
||||
func NewJwtSecret() ([]byte, string) {
|
||||
bytes := util.CryptoRandomBytes(32)
|
||||
return bytes, base64.RawURLEncoding.EncodeToString(bytes)
|
||||
}
|
||||
|
||||
// NewSecretKey generate a new value intended to be used by SECRET_KEY.
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue