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

@ -5,7 +5,6 @@ package e2e
import (
"context"
"crypto/rand"
"encoding/hex"
"fmt"
"net"
@ -23,6 +22,7 @@ import (
"forgejo.org/modules/json"
modules_session "forgejo.org/modules/session"
"forgejo.org/modules/setting"
"forgejo.org/modules/util"
"forgejo.org/tests"
"code.forgejo.org/go-chi/session"
@ -153,11 +153,7 @@ func stateHelper(t testing.TB) func(stateFile string, user *user_model.User) {
require.NoError(t, err)
return func(stateFile string, user *user_model.User) {
buf := make([]byte, opt.IDLength/2)
_, err = rand.Read(buf)
require.NoError(t, err)
sessionID := hex.EncodeToString(buf)
sessionID := hex.EncodeToString(util.CryptoRandomBytes(int64(opt.IDLength) / 2))
s, err := vsp.Read(sessionID)
require.NoError(t, err)