Remove error returns from crypto random helpers and callers (#37240)

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: wxiaoguang <2114189+wxiaoguang@users.noreply.github.com>
Co-authored-by: wxiaoguang <wxiaoguang@gmail.com>
Co-authored-by: silverwind <115237+silverwind@users.noreply.github.com>
This commit is contained in:
Copilot
2026-04-17 00:59:26 +08:00
committed by GitHub
parent 82bfde2a37
commit 4a2bba9aed
23 changed files with 64 additions and 153 deletions

View File

@@ -171,9 +171,8 @@ func (r *ActionRunner) LoadAttributes(ctx context.Context) error {
return nil return nil
} }
func (r *ActionRunner) GenerateToken() (err error) { func (r *ActionRunner) GenerateAndFillToken() {
r.Token, r.TokenSalt, r.TokenHash, _, err = generateSaltedToken() r.Token, r.TokenSalt, r.TokenHash, _ = generateSaltedToken()
return err
} }
// CanMatchLabels checks whether the runner's labels can match a job's "runs-on" // CanMatchLabels checks whether the runner's labels can match a job's "runs-on"

View File

@@ -97,10 +97,7 @@ func NewRunnerTokenWithValue(ctx context.Context, ownerID, repoID int64, token s
} }
func NewRunnerToken(ctx context.Context, ownerID, repoID int64) (*ActionRunnerToken, error) { func NewRunnerToken(ctx context.Context, ownerID, repoID int64) (*ActionRunnerToken, error) {
token, err := util.CryptoRandomString(40) token := util.CryptoRandomString(40)
if err != nil {
return nil, err
}
return NewRunnerTokenWithValue(ctx, ownerID, repoID, token) return NewRunnerTokenWithValue(ctx, ownerID, repoID, token)
} }

View File

@@ -147,9 +147,8 @@ func (task *ActionTask) LoadAttributes(ctx context.Context) error {
return nil return nil
} }
func (task *ActionTask) GenerateToken() (err error) { func (task *ActionTask) GenerateAndFillToken() {
task.Token, task.TokenSalt, task.TokenHash, task.TokenLastEight, err = generateSaltedToken() task.Token, task.TokenSalt, task.TokenHash, task.TokenLastEight = generateSaltedToken()
return err
} }
func GetTaskByID(ctx context.Context, id int64) (*ActionTask, error) { func GetTaskByID(ctx context.Context, id int64) (*ActionTask, error) {
@@ -288,9 +287,7 @@ func CreateTaskForRunner(ctx context.Context, runner *ActionRunner) (*ActionTask
CommitSHA: job.CommitSHA, CommitSHA: job.CommitSHA,
IsForkPullRequest: job.IsForkPullRequest, IsForkPullRequest: job.IsForkPullRequest,
} }
if err := task.GenerateToken(); err != nil { task.GenerateAndFillToken()
return nil, false, err
}
workflowJob, err := job.ParseJob() workflowJob, err := job.ParseJob()
if err != nil { if err != nil {

View File

@@ -18,18 +18,12 @@ import (
"code.gitea.io/gitea/modules/util" "code.gitea.io/gitea/modules/util"
) )
func generateSaltedToken() (string, string, string, string, error) { func generateSaltedToken() (string, string, string, string) {
salt, err := util.CryptoRandomString(10) salt := util.CryptoRandomString(10)
if err != nil { buf := util.CryptoRandomBytes(20)
return "", "", "", "", err
}
buf, err := util.CryptoRandomBytes(20)
if err != nil {
return "", "", "", "", err
}
token := hex.EncodeToString(buf) token := hex.EncodeToString(buf)
hash := auth_model.HashToken(token, salt) hash := auth_model.HashToken(token, salt)
return token, salt, hash, token[len(token)-8:], nil return token, salt, hash, token[len(token)-8:]
} }
/* /*

View File

@@ -98,19 +98,13 @@ func init() {
// NewAccessToken creates new access token. // NewAccessToken creates new access token.
func NewAccessToken(ctx context.Context, t *AccessToken) error { func NewAccessToken(ctx context.Context, t *AccessToken) error {
salt, err := util.CryptoRandomString(10) salt := util.CryptoRandomString(10)
if err != nil { token := util.CryptoRandomBytes(20)
return err
}
token, err := util.CryptoRandomBytes(20)
if err != nil {
return err
}
t.TokenSalt = salt t.TokenSalt = salt
t.Token = hex.EncodeToString(token) t.Token = hex.EncodeToString(token)
t.TokenHash = HashToken(t.Token, t.TokenSalt) t.TokenHash = HashToken(t.Token, t.TokenSalt)
t.TokenLastEight = t.Token[len(t.Token)-8:] t.TokenLastEight = t.Token[len(t.Token)-8:]
_, err = db.GetEngine(ctx).Insert(t) _, err := db.GetEngine(ctx).Insert(t)
return err return err
} }

View File

@@ -185,10 +185,7 @@ var base32Lower = base32.NewEncoding(lowerBase32Chars).WithPadding(base32.NoPadd
// GenerateClientSecret will generate the client secret and returns the plaintext and saves the hash at the database // GenerateClientSecret will generate the client secret and returns the plaintext and saves the hash at the database
func (app *OAuth2Application) GenerateClientSecret(ctx context.Context) (string, error) { func (app *OAuth2Application) GenerateClientSecret(ctx context.Context) (string, error) {
rBytes, err := util.CryptoRandomBytes(32) rBytes := util.CryptoRandomBytes(32)
if err != nil {
return "", err
}
// Add a prefix to the base32, this is in order to make it easier // Add a prefix to the base32, this is in order to make it easier
// for code scanners to grab sensitive tokens. // for code scanners to grab sensitive tokens.
clientSecret := "gto_" + base32Lower.EncodeToString(rBytes) clientSecret := "gto_" + base32Lower.EncodeToString(rBytes)
@@ -484,10 +481,7 @@ func (grant *OAuth2Grant) TableName() string {
// GenerateNewAuthorizationCode generates a new authorization code for a grant and saves it to the database // GenerateNewAuthorizationCode generates a new authorization code for a grant and saves it to the database
func (grant *OAuth2Grant) GenerateNewAuthorizationCode(ctx context.Context, redirectURI, codeChallenge, codeChallengeMethod string) (code *OAuth2AuthorizationCode, err error) { func (grant *OAuth2Grant) GenerateNewAuthorizationCode(ctx context.Context, redirectURI, codeChallenge, codeChallengeMethod string) (code *OAuth2AuthorizationCode, err error) {
rBytes, err := util.CryptoRandomBytes(32) rBytes := util.CryptoRandomBytes(32)
if err != nil {
return &OAuth2AuthorizationCode{}, err
}
// Add a prefix to the base32, this is in order to make it easier // Add a prefix to the base32, this is in order to make it easier
// for code scanners to grab sensitive tokens. // for code scanners to grab sensitive tokens.
codeSecret := "gta_" + base32Lower.EncodeToString(rBytes) codeSecret := "gta_" + base32Lower.EncodeToString(rBytes)

View File

@@ -65,14 +65,11 @@ func init() {
// GenerateScratchToken recreates the scratch token the user is using. // GenerateScratchToken recreates the scratch token the user is using.
func (t *TwoFactor) GenerateScratchToken() (string, error) { func (t *TwoFactor) GenerateScratchToken() (string, error) {
tokenBytes, err := util.CryptoRandomBytes(6) tokenBytes := util.CryptoRandomBytes(6)
if err != nil {
return "", err
}
// these chars are specially chosen, avoid ambiguous chars like `0`, `O`, `1`, `I`. // these chars are specially chosen, avoid ambiguous chars like `0`, `O`, `1`, `I`.
const base32Chars = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789" const base32Chars = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789"
token := base32.NewEncoding(base32Chars).WithPadding(base32.NoPadding).EncodeToString(tokenBytes) token := base32.NewEncoding(base32Chars).WithPadding(base32.NoPadding).EncodeToString(tokenBytes)
t.ScratchSalt, _ = util.CryptoRandomString(10) t.ScratchSalt = util.CryptoRandomString(10)
t.ScratchHash = HashToken(token, t.ScratchSalt) t.ScratchHash = HashToken(token, t.ScratchSalt)
return token, nil return token, nil
} }

View File

@@ -51,10 +51,7 @@ func AddScratchHash(x *xorm.Engine) error {
for _, tfa := range tfas { for _, tfa := range tfas {
// generate salt // generate salt
salt, err := util.CryptoRandomString(10) salt := util.CryptoRandomString(10)
if err != nil {
return err
}
tfa.ScratchSalt = salt tfa.ScratchSalt = salt
tfa.ScratchHash = base.HashToken(tfa.ScratchToken, salt) tfa.ScratchHash = base.HashToken(tfa.ScratchToken, salt)

View File

@@ -65,10 +65,7 @@ func HashAppToken(x *xorm.Engine) error {
for _, token := range tokens { for _, token := range tokens {
// generate salt // generate salt
salt, err := util.CryptoRandomString(10) salt := util.CryptoRandomString(10)
if err != nil {
return err
}
token.TokenSalt = salt token.TokenSalt = salt
token.TokenHash = base.HashToken(token.Sha1, salt) token.TokenHash = base.HashToken(token.Sha1, salt)
if len(token.Sha1) < 8 { if len(token.Sha1) < 8 {

View File

@@ -116,10 +116,7 @@ func CreateTeamInvite(ctx context.Context, doer *user_model.User, team *Team, em
} }
} }
token, err := util.CryptoRandomString(25) token := util.CryptoRandomString(25)
if err != nil {
return nil, err
}
invite := &TeamInvite{ invite := &TeamInvite{
Token: token, Token: token,

View File

@@ -31,16 +31,13 @@ type PackageBlobUpload struct {
// CreateBlobUpload inserts a blob upload // CreateBlobUpload inserts a blob upload
func CreateBlobUpload(ctx context.Context) (*PackageBlobUpload, error) { func CreateBlobUpload(ctx context.Context) (*PackageBlobUpload, error) {
id, err := util.CryptoRandomString(25) id := util.CryptoRandomString(25)
if err != nil {
return nil, err
}
pbu := &PackageBlobUpload{ pbu := &PackageBlobUpload{
ID: strings.ToLower(id), ID: strings.ToLower(id),
} }
_, err = db.GetEngine(ctx).Insert(pbu) _, err := db.GetEngine(ctx).Insert(pbu)
return pbu, err return pbu, err
} }

View File

@@ -524,10 +524,7 @@ const SaltByteLength = 16
// GetUserSalt returns a random user salt token. // GetUserSalt returns a random user salt token.
func GetUserSalt() (string, error) { func GetUserSalt() (string, error) {
rBytes, err := util.CryptoRandomBytes(SaltByteLength) rBytes := util.CryptoRandomBytes(SaltByteLength)
if err != nil {
return "", err
}
// Returns a 32-byte long string. // Returns a 32-byte long string.
return hex.EncodeToString(rBytes), nil return hex.EncodeToString(rBytes), nil
} }

View File

@@ -65,10 +65,5 @@ func NewJwtSecretWithBase64() ([]byte, string) {
// NewSecretKey generate a new value intended to be used by SECRET_KEY. // NewSecretKey generate a new value intended to be used by SECRET_KEY.
func NewSecretKey() (string, error) { func NewSecretKey() (string, error) {
secretKey, err := util.CryptoRandomString(64) return util.CryptoRandomString(64), nil
if err != nil {
return "", err
}
return secretKey, nil
} }

View File

@@ -61,48 +61,42 @@ func NormalizeEOL(input []byte) []byte {
} }
// CryptoRandomInt returns a crypto random integer between 0 and limit, inclusive // CryptoRandomInt returns a crypto random integer between 0 and limit, inclusive
func CryptoRandomInt(limit int64) (int64, error) { func CryptoRandomInt(limit int64) int64 {
rInt, err := rand.Int(rand.Reader, big.NewInt(limit)) rInt, err := rand.Int(rand.Reader, big.NewInt(limit))
if err != nil { if err != nil {
return 0, err panic(err) // this should never happen
} }
return rInt.Int64(), nil return rInt.Int64()
} }
const alphanumericalChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
// CryptoRandomString generates a crypto random alphanumerical string, each byte is generated by [0,61] range // CryptoRandomString generates a crypto random alphanumerical string, each byte is generated by [0,61] range
func CryptoRandomString(length int64) (string, error) { func CryptoRandomString(length int64) string {
const alphanumericalChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
buf := make([]byte, length) buf := make([]byte, length)
limit := int64(len(alphanumericalChars)) limit := int64(len(alphanumericalChars))
for i := range buf { for i := range buf {
num, err := CryptoRandomInt(limit) num := CryptoRandomInt(limit)
if err != nil {
return "", err
}
buf[i] = alphanumericalChars[num] buf[i] = alphanumericalChars[num]
} }
return string(buf), nil return string(buf)
} }
// CryptoRandomBytes generates `length` crypto bytes // CryptoRandomBytes generates `length` crypto bytes
// This differs from CryptoRandomString, as each byte in CryptoRandomString is generated by [0,61] range // This differs from CryptoRandomString, as each byte in CryptoRandomString is generated by [0,61] range
// This function generates totally random bytes, each byte is generated by [0,255] range // This function generates totally random bytes, each byte is generated by [0,255] range
// TODO: it never fails, remove the "error" in the future func CryptoRandomBytes(length int64) []byte {
func CryptoRandomBytes(length int64) ([]byte, error) {
buf := make([]byte, length) buf := make([]byte, length)
if _, err := rand.Read(buf); err != nil { if _, err := rand.Read(buf); err != nil {
panic(err) // this should never happen, "rand.Read" never fails panic(err) // this should never happen, "rand.Read" never fails
} }
return buf, nil return buf
} }
var chaCha8RandPool = sync.OnceValue(func() *sync.Pool { var chaCha8RandPool = sync.OnceValue(func() *sync.Pool {
return &sync.Pool{ return &sync.Pool{
New: func() any { New: func() any {
var buf [32]byte seed := CryptoRandomBytes(32)
_, _ = rand.Read(buf[:]) return rand2.NewChaCha8([32]byte(seed))
return rand2.NewChaCha8(buf)
}, },
} }
}) })

View File

@@ -86,35 +86,31 @@ func Test_NormalizeEOL(t *testing.T) {
} }
func Test_RandomInt(t *testing.T) { func Test_RandomInt(t *testing.T) {
randInt, err := CryptoRandomInt(255) randInt := CryptoRandomInt(255)
assert.GreaterOrEqual(t, randInt, int64(0)) assert.GreaterOrEqual(t, randInt, int64(0))
assert.LessOrEqual(t, randInt, int64(255)) assert.LessOrEqual(t, randInt, int64(255))
assert.NoError(t, err)
} }
func Test_RandomString(t *testing.T) { func Test_RandomString(t *testing.T) {
str1, err := CryptoRandomString(32) str1 := CryptoRandomString(32)
assert.NoError(t, err) var err error
matches, err := regexp.MatchString(`^[a-zA-Z0-9]{32}$`, str1) matches, err := regexp.MatchString(`^[a-zA-Z0-9]{32}$`, str1)
assert.NoError(t, err) assert.NoError(t, err)
assert.True(t, matches) assert.True(t, matches)
str2, err := CryptoRandomString(32) str2 := CryptoRandomString(32)
assert.NoError(t, err)
matches, err = regexp.MatchString(`^[a-zA-Z0-9]{32}$`, str1) matches, err = regexp.MatchString(`^[a-zA-Z0-9]{32}$`, str1)
assert.NoError(t, err) assert.NoError(t, err)
assert.True(t, matches) assert.True(t, matches)
assert.NotEqual(t, str1, str2) assert.NotEqual(t, str1, str2)
str3, err := CryptoRandomString(256) str3 := CryptoRandomString(256)
assert.NoError(t, err)
matches, err = regexp.MatchString(`^[a-zA-Z0-9]{256}$`, str3) matches, err = regexp.MatchString(`^[a-zA-Z0-9]{256}$`, str3)
assert.NoError(t, err) assert.NoError(t, err)
assert.True(t, matches) assert.True(t, matches)
str4, err := CryptoRandomString(256) str4 := CryptoRandomString(256)
assert.NoError(t, err)
matches, err = regexp.MatchString(`^[a-zA-Z0-9]{256}$`, str4) matches, err = regexp.MatchString(`^[a-zA-Z0-9]{256}$`, str4)
assert.NoError(t, err) assert.NoError(t, err)
assert.True(t, matches) assert.True(t, matches)
@@ -123,19 +119,15 @@ func Test_RandomString(t *testing.T) {
} }
func Test_RandomBytes(t *testing.T) { func Test_RandomBytes(t *testing.T) {
bytes1, err := CryptoRandomBytes(32) bytes1 := CryptoRandomBytes(32)
assert.NoError(t, err)
bytes2, err := CryptoRandomBytes(32) bytes2 := CryptoRandomBytes(32)
assert.NoError(t, err)
assert.NotEqual(t, bytes1, bytes2) assert.NotEqual(t, bytes1, bytes2)
bytes3, err := CryptoRandomBytes(256) bytes3 := CryptoRandomBytes(256)
assert.NoError(t, err)
bytes4, err := CryptoRandomBytes(256) bytes4 := CryptoRandomBytes(256)
assert.NoError(t, err)
assert.NotEqual(t, bytes3, bytes4) assert.NotEqual(t, bytes3, bytes4)
} }

View File

@@ -80,9 +80,7 @@ func (s *Service) Register(
AgentLabels: labels, AgentLabels: labels,
Ephemeral: req.Msg.Ephemeral, Ephemeral: req.Msg.Ephemeral,
} }
if err := runner.GenerateToken(); err != nil { runner.GenerateAndFillToken()
return nil, errors.New("can't generate token")
}
// create new runner // create new runner
if err := actions_model.CreateRunner(ctx, runner); err != nil { if err := actions_model.CreateRunner(ctx, runner); err != nil {

View File

@@ -351,11 +351,7 @@ func CreatePushMirror(ctx *context.APIContext, mirrorOption *api.CreatePushMirro
return return
} }
remoteSuffix, err := util.CryptoRandomString(10) remoteSuffix := util.CryptoRandomString(10)
if err != nil {
ctx.APIErrorInternal(err)
return
}
remoteAddress, err := util.SanitizeURL(mirrorOption.RemoteAddress) remoteAddress, err := util.SanitizeURL(mirrorOption.RemoteAddress)
if err != nil { if err != nil {

View File

@@ -272,7 +272,7 @@ func ConnectOpenIDPost(ctx *context.Context) {
// add OpenID for the user // add OpenID for the user
userOID := &user_model.UserOpenID{UID: u.ID, URI: oid} userOID := &user_model.UserOpenID{UID: u.ID, URI: oid}
if err = user_model.AddUserOpenID(ctx, userOID); err != nil { if err := user_model.AddUserOpenID(ctx, userOID); err != nil {
if user_model.IsErrOpenIDAlreadyUsed(err) { if user_model.IsErrOpenIDAlreadyUsed(err) {
ctx.RenderWithErrDeprecated(ctx.Tr("form.openid_been_used", oid), tplConnectOID, &form) ctx.RenderWithErrDeprecated(ctx.Tr("form.openid_been_used", oid), tplConnectOID, &form)
return return
@@ -345,11 +345,7 @@ func RegisterOpenIDPost(ctx *context.Context) {
} }
length := max(setting.MinPasswordLength, 256) length := max(setting.MinPasswordLength, 256)
password, err := util.CryptoRandomString(int64(length)) password := util.CryptoRandomString(int64(length))
if err != nil {
ctx.RenderWithErrDeprecated(err.Error(), tplSignUpOID, form)
return
}
u := &user_model.User{ u := &user_model.User{
Name: form.UserName, Name: form.UserName,
@@ -363,7 +359,7 @@ func RegisterOpenIDPost(ctx *context.Context) {
// add OpenID for the user // add OpenID for the user
userOID := &user_model.UserOpenID{UID: u.ID, URI: oid} userOID := &user_model.UserOpenID{UID: u.ID, URI: oid}
if err = user_model.AddUserOpenID(ctx, userOID); err != nil { if err := user_model.AddUserOpenID(ctx, userOID); err != nil {
if user_model.IsErrOpenIDAlreadyUsed(err) { if user_model.IsErrOpenIDAlreadyUsed(err) {
ctx.RenderWithErrDeprecated(ctx.Tr("form.openid_been_used", oid), tplSignUpOID, &form) ctx.RenderWithErrDeprecated(ctx.Tr("form.openid_been_used", oid), tplSignUpOID, &form)
return return

View File

@@ -459,11 +459,7 @@ func handleSettingsPostPushMirrorAdd(ctx *context.Context) {
return return
} }
remoteSuffix, err := util.CryptoRandomString(10) remoteSuffix := util.CryptoRandomString(10)
if err != nil {
ctx.ServerError("RandomString", err)
return
}
remoteAddress, err := util.SanitizeURL(form.PushMirrorAddress) remoteAddress, err := util.SanitizeURL(form.PushMirrorAddress)
if err != nil { if err != nil {

View File

@@ -35,7 +35,7 @@ func TestInitToken(t *testing.T) {
}) })
t.Run("EnvToken", func(t *testing.T) { t.Run("EnvToken", func(t *testing.T) {
tokenValue, _ := util.CryptoRandomString(32) tokenValue := util.CryptoRandomString(32)
t.Setenv("GITEA_RUNNER_REGISTRATION_TOKEN", tokenValue) t.Setenv("GITEA_RUNNER_REGISTRATION_TOKEN", tokenValue)
t.Setenv("GITEA_RUNNER_REGISTRATION_TOKEN_FILE", "") t.Setenv("GITEA_RUNNER_REGISTRATION_TOKEN_FILE", "")
err := initGlobalRunnerToken(t.Context()) err := initGlobalRunnerToken(t.Context())
@@ -52,7 +52,7 @@ func TestInitToken(t *testing.T) {
}) })
t.Run("EnvFileToken", func(t *testing.T) { t.Run("EnvFileToken", func(t *testing.T) {
tokenValue, _ := util.CryptoRandomString(32) tokenValue := util.CryptoRandomString(32)
f := t.TempDir() + "/token" f := t.TempDir() + "/token"
_ = os.WriteFile(f, []byte(tokenValue), 0o644) _ = os.WriteFile(f, []byte(tokenValue), 0o644)
t.Setenv("GITEA_RUNNER_REGISTRATION_TOKEN", "") t.Setenv("GITEA_RUNNER_REGISTRATION_TOKEN", "")

View File

@@ -64,10 +64,7 @@ func CheckAuthToken(ctx context.Context, value string) (*auth_model.AuthToken, e
} }
func RegenerateAuthToken(ctx context.Context, t *auth_model.AuthToken) (*auth_model.AuthToken, string, error) { func RegenerateAuthToken(ctx context.Context, t *auth_model.AuthToken) (*auth_model.AuthToken, string, error) {
token, hash, err := generateTokenAndHash() token, hash := generateTokenAndHash()
if err != nil {
return nil, "", err
}
newToken := &auth_model.AuthToken{ newToken := &auth_model.AuthToken{
ID: t.ID, ID: t.ID,
@@ -89,16 +86,9 @@ func CreateAuthTokenForUserID(ctx context.Context, userID int64) (*auth_model.Au
ExpiresUnix: timeutil.TimeStampNow().AddDuration(time.Duration(setting.LogInRememberDays*24) * time.Hour), ExpiresUnix: timeutil.TimeStampNow().AddDuration(time.Duration(setting.LogInRememberDays*24) * time.Hour),
} }
var err error t.ID = util.CryptoRandomString(10)
t.ID, err = util.CryptoRandomString(10)
if err != nil {
return nil, "", err
}
token, hash, err := generateTokenAndHash() token, hash := generateTokenAndHash()
if err != nil {
return nil, "", err
}
t.TokenHash = hash t.TokenHash = hash
@@ -109,15 +99,12 @@ func CreateAuthTokenForUserID(ctx context.Context, userID int64) (*auth_model.Au
return t, token, nil return t, token, nil
} }
func generateTokenAndHash() (string, string, error) { func generateTokenAndHash() (string, string) {
buf, err := util.CryptoRandomBytes(32) buf := util.CryptoRandomBytes(32)
if err != nil {
return "", "", err
}
token := hex.EncodeToString(buf) token := hex.EncodeToString(buf)
hashedToken := sha256.Sum256([]byte(token)) hashedToken := sha256.Sum256([]byte(token))
return token, hex.EncodeToString(hashedToken[:]), nil return token, hex.EncodeToString(hashedToken[:])
} }

View File

@@ -137,7 +137,7 @@ func TestActionsJobTokenPermissiveAccess(t *testing.T) {
require.NoError(t, repo_model.UpdateRepoUnitConfig(t.Context(), repoActionsUnit)) require.NoError(t, repo_model.UpdateRepoUnitConfig(t.Context(), repoActionsUnit))
// prepare task and its token // prepare task and its token
require.NoError(t, task.GenerateToken()) task.GenerateAndFillToken()
task.Status = actions_model.StatusRunning task.Status = actions_model.StatusRunning
task.IsForkPullRequest = tt.isFork task.IsForkPullRequest = tt.isFork
err := actions_model.UpdateTask(t.Context(), task, "token_hash", "token_salt", "token_last_eight", "status", "is_fork_pull_request") err := actions_model.UpdateTask(t.Context(), task, "token_hash", "token_salt", "token_last_eight", "status", "is_fork_pull_request")
@@ -309,7 +309,7 @@ func TestActionsJobTokenPermissionsWriteIssue(t *testing.T) {
repoActionsCfg.MaxTokenPermissions = nil repoActionsCfg.MaxTokenPermissions = nil
require.NoError(t, repo_model.UpdateRepoUnitConfig(t.Context(), repoActionsUnit)) require.NoError(t, repo_model.UpdateRepoUnitConfig(t.Context(), repoActionsUnit))
require.NoError(t, task.GenerateToken()) task.GenerateAndFillToken()
task.Status = actions_model.StatusRunning task.Status = actions_model.StatusRunning
require.NoError(t, actions_model.UpdateTask(t.Context(), task, "token_hash", "token_salt", "token_last_eight", "status")) require.NoError(t, actions_model.UpdateTask(t.Context(), task, "token_hash", "token_salt", "token_last_eight", "status"))
@@ -359,7 +359,7 @@ func createActionTask(t *testing.T, repoID int64, isFork bool) *actions_model.Ac
Status: actions_model.StatusRunning, Status: actions_model.StatusRunning,
IsForkPullRequest: isFork, IsForkPullRequest: isFork,
} }
require.NoError(t, task.GenerateToken()) task.GenerateAndFillToken()
require.NoError(t, db.Insert(t.Context(), task)) require.NoError(t, db.Insert(t.Context(), task))
return task return task
} }

View File

@@ -562,7 +562,7 @@ func TestPackageCleanup(t *testing.T) {
defer tests.PrintCurrentTest(t)() defer tests.PrintCurrentTest(t)()
// Upload and delete a generic package and upload a container blob // Upload and delete a generic package and upload a container blob
data, _ := util.CryptoRandomBytes(5) data := util.CryptoRandomBytes(5)
url := fmt.Sprintf("/api/packages/%s/generic/cleanup-test/1.1.1/file.bin", user.Name) url := fmt.Sprintf("/api/packages/%s/generic/cleanup-test/1.1.1/file.bin", user.Name)
req := NewRequestWithBody(t, "PUT", url, bytes.NewReader(data)). req := NewRequestWithBody(t, "PUT", url, bytes.NewReader(data)).
AddBasicAuth(user.Name) AddBasicAuth(user.Name)
@@ -572,7 +572,7 @@ func TestPackageCleanup(t *testing.T) {
AddBasicAuth(user.Name) AddBasicAuth(user.Name)
MakeRequest(t, req, http.StatusNoContent) MakeRequest(t, req, http.StatusNoContent)
data, _ = util.CryptoRandomBytes(5) data = util.CryptoRandomBytes(5)
url = fmt.Sprintf("/v2/%s/cleanup-test/blobs/uploads?digest=sha256:%x", user.Name, sha256.Sum256(data)) url = fmt.Sprintf("/v2/%s/cleanup-test/blobs/uploads?digest=sha256:%x", user.Name, sha256.Sum256(data))
req = NewRequestWithBody(t, "POST", url, bytes.NewReader(data)). req = NewRequestWithBody(t, "POST", url, bytes.NewReader(data)).
AddBasicAuth(user.Name) AddBasicAuth(user.Name)