mirror of
https://github.com/go-gitea/gitea.git
synced 2026-12-04 15:54:57 +00:00
perf(auth): store tokens as SHA-256 and throttle last-used writes (#39933)
Store PAT, Actions task and runner tokens as SHA-256 instead of PBKDF2, which 160-bit random tokens don't need, and drop the token caches and `SUCCESSFUL_TOKENS_CACHE_SIZE` that PBKDF2 required. Legacy rows are rehashed on first use. Older releases can't verify new or rehashed tokens. A PAT use now writes only its last-used timestamp, at most once a minute. Benchmarks on M2 Max, SQLite, median of 5: | Benchmark | 1 token | 128 tokens | | :--- | ---: | ---: | | PAT lookup | 29.4 → 30.7 µs | 2.24 ms → 29.7 µs | | PAT lookup with last-used | 107 → 29.6 µs | 2.44 ms → 30.1 µs | | Task lookup | 63.2 → 48.4 µs | 2.25 ms → 49.4 µs | | Runner verify, no DB | 122 → 160 ns | 141 → 162 ns | Docs: https://gitea.com/gitea/docs/pulls/607 Assisted-by: Codet Assisted-by: Claude Code:claude-opus-5-5 --------- Co-authored-by: silverwind <me@silverwind.io>
This commit is contained in:
1 parent
02b5bbacab
commit
d821a986ef
16 files changed
+113
-174
No files matched your search
@@ -510,10 +510,6 @@ INTERNAL_TOKEN =
|
||||
;; Validate against https://haveibeenpwned.com/Passwords to see if a password has been exposed
|
||||
;PASSWORD_CHECK_PWN = false
|
||||
;;
|
||||
;; Cache successful token hashes. API tokens are stored in the DB as pbkdf2 hashes however, this means that there is a potentially significant hashing load when there are multiple API operations.
|
||||
;; This cache will store the successfully hashed tokens in a LRU cache as a balance between performance and security.
|
||||
;SUCCESSFUL_TOKENS_CACHE_SIZE = 20
|
||||
;;
|
||||
;; Reject API tokens sent in URL query string (Accept Header-based API tokens only). This avoids security vulnerabilities
|
||||
;; stemming from cached/logged plain-text API tokens.
|
||||
;; In future releases, this will become the default behavior
|
||||
|
||||
@@ -12,6 +12,7 @@ import (
|
||||
"time"
|
||||
|
||||
runnerv1 "gitea.dev/actionslib/runner/v1"
|
||||
auth_model "gitea.dev/models/auth"
|
||||
"gitea.dev/models/db"
|
||||
repo_model "gitea.dev/models/repo"
|
||||
"gitea.dev/models/shared/types"
|
||||
@@ -52,7 +53,7 @@ type ActionRunner struct {
|
||||
|
||||
Token string `xorm:"-"`
|
||||
TokenHash string `xorm:"UNIQUE"` // sha256 of token
|
||||
TokenSalt string
|
||||
TokenSalt string // only set for legacy pbkdf2 hashes
|
||||
// TokenLastEight string `xorm:"token_last_eight"` // it's unnecessary because we don't find runners by token
|
||||
|
||||
LastOnline timeutil.TimeStamp `xorm:"index"`
|
||||
@@ -194,7 +195,7 @@ func (r *ActionRunner) LoadAttributes(ctx context.Context) error {
|
||||
}
|
||||
|
||||
func (r *ActionRunner) GenerateAndFillToken() {
|
||||
r.Token, r.TokenSalt, r.TokenHash, _ = generateSaltedToken()
|
||||
r.Token, r.TokenHash, _ = auth_model.GenerateToken()
|
||||
}
|
||||
|
||||
// CanMatchLabels checks whether the runner's labels can match a job's "runs-on"
|
||||
|
||||
+5
-31
@@ -45,7 +45,7 @@ type ActionTask struct {
|
||||
|
||||
Token string `xorm:"-"`
|
||||
TokenHash string `xorm:"UNIQUE"` // sha256 of token
|
||||
TokenSalt string
|
||||
TokenSalt string // only set for legacy pbkdf2 hashes
|
||||
TokenLastEight string `xorm:"index token_last_eight"`
|
||||
|
||||
LogFilename string // file name of log
|
||||
@@ -138,7 +138,7 @@ func (task *ActionTask) LoadAttributes(ctx context.Context) error {
|
||||
}
|
||||
|
||||
func (task *ActionTask) GenerateAndFillToken() {
|
||||
task.Token, task.TokenSalt, task.TokenHash, task.TokenLastEight = generateSaltedToken()
|
||||
task.Token, task.TokenHash, task.TokenLastEight = auth_model.GenerateToken()
|
||||
}
|
||||
|
||||
func GetTaskByID(ctx context.Context, id int64) (*ActionTask, error) {
|
||||
@@ -186,11 +186,7 @@ func GetTaskRunnerNames(ctx context.Context, taskIDs []int64) (map[int64]string,
|
||||
}
|
||||
|
||||
func GetRunningTaskByToken(ctx context.Context, token string) (*ActionTask, error) {
|
||||
errNotExist := fmt.Errorf("task with token %q: %w", token, util.ErrNotExist)
|
||||
if token == "" {
|
||||
return nil, errNotExist
|
||||
}
|
||||
// A token is defined as being SHA1 sum these are 40 hexadecimal bytes long
|
||||
errNotExist := util.NewNotExistErrorf("task token not found")
|
||||
if len(token) != 40 {
|
||||
return nil, errNotExist
|
||||
}
|
||||
@@ -200,36 +196,14 @@ func GetRunningTaskByToken(ctx context.Context, token string) (*ActionTask, erro
|
||||
}
|
||||
}
|
||||
|
||||
cacheKey := "actions:" + token
|
||||
lastEight := token[len(token)-8:]
|
||||
if cached, _ := auth_model.TokenCache().Get(cacheKey); cached != nil {
|
||||
task := &ActionTask{
|
||||
TokenLastEight: lastEight,
|
||||
}
|
||||
// Re-get the task from the db in case it has been deleted in the intervening period
|
||||
has, err := db.GetEngine(ctx).ID(cached.TokenID).Get(task)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if has && util.CryptoConstTimeEqual(task.TokenHash, cached.TokenHash) {
|
||||
return task, nil
|
||||
}
|
||||
auth_model.TokenCache().Remove(cacheKey)
|
||||
}
|
||||
|
||||
var tasks []*ActionTask
|
||||
// Cancelling tasks are still authenticating — post-run cleanup steps need API access (artifact uploads, cache saves, etc.) before the runner finalizes the task.
|
||||
err := db.GetEngine(ctx).Where("token_last_eight = ? AND status IN (?, ?)", lastEight, StatusRunning, StatusCancelling).Find(&tasks)
|
||||
err := db.GetEngine(ctx).Where("token_last_eight = ? AND status IN (?, ?)", token[len(token)-8:], StatusRunning, StatusCancelling).Find(&tasks)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
} else if len(tasks) == 0 {
|
||||
return nil, errNotExist
|
||||
}
|
||||
|
||||
for _, t := range tasks {
|
||||
tempHash := auth_model.HashToken(token, t.TokenSalt)
|
||||
if util.CryptoConstTimeEqual(t.TokenHash, tempHash) {
|
||||
auth_model.TokenCache().Add(cacheKey, &auth_model.TokenCacheItem{TokenID: t.ID, TokenHash: t.TokenHash})
|
||||
if auth_model.VerifyToken(ctx, t, token, t.TokenSalt, t.TokenHash) {
|
||||
return t, nil
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,12 +11,15 @@ import (
|
||||
"testing"
|
||||
|
||||
runnerv1 "gitea.dev/actionslib/runner/v1"
|
||||
auth_model "gitea.dev/models/auth"
|
||||
"gitea.dev/models/db"
|
||||
repo_model "gitea.dev/models/repo"
|
||||
"gitea.dev/models/unit"
|
||||
"gitea.dev/models/unittest"
|
||||
"gitea.dev/modules/actions/jobparser"
|
||||
"gitea.dev/modules/base"
|
||||
"gitea.dev/modules/timeutil"
|
||||
"gitea.dev/modules/util"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
@@ -51,6 +54,24 @@ func TestGetTaskRunnerNames(t *testing.T) {
|
||||
assert.Equal(t, map[int64]string{task.ID: runner.Name}, names)
|
||||
}
|
||||
|
||||
func TestGetRunningTaskByToken(t *testing.T) {
|
||||
require.NoError(t, unittest.PrepareTestDatabase())
|
||||
ctx := t.Context()
|
||||
task := &ActionTask{Status: StatusRunning, TokenSalt: "salt"}
|
||||
task.GenerateAndFillToken()
|
||||
task.TokenHash = auth_model.HashToken(task.Token, task.TokenSalt)
|
||||
require.NoError(t, db.Insert(ctx, task))
|
||||
_, err := GetRunningTaskByToken(ctx, task.Token)
|
||||
require.NoError(t, err)
|
||||
assert.Empty(t, unittest.AssertExistsAndLoadBean(t, &ActionTask{ID: task.ID, TokenHash: base.EncodeSha256(task.Token)}).TokenSalt)
|
||||
_, err = GetRunningTaskByToken(ctx, task.Token)
|
||||
require.NoError(t, err)
|
||||
_, err = db.GetEngine(ctx).ID(task.ID).Cols("status").Update(&ActionTask{Status: StatusSuccess})
|
||||
require.NoError(t, err)
|
||||
_, err = GetRunningTaskByToken(ctx, task.Token)
|
||||
assert.ErrorIs(t, err, util.ErrNotExist)
|
||||
}
|
||||
|
||||
func TestMakeTaskStepDisplayName(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
|
||||
@@ -6,26 +6,15 @@ package actions
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/binary"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"time"
|
||||
|
||||
auth_model "gitea.dev/models/auth"
|
||||
"gitea.dev/modules/log"
|
||||
"gitea.dev/modules/timeutil"
|
||||
"gitea.dev/modules/util"
|
||||
)
|
||||
|
||||
func generateSaltedToken() (string, string, string, string) {
|
||||
salt := util.CryptoRandomString(10)
|
||||
buf := util.CryptoRandomBytes(20)
|
||||
token := hex.EncodeToString(buf)
|
||||
hash := auth_model.HashToken(token, salt)
|
||||
return token, salt, hash, token[len(token)-8:]
|
||||
}
|
||||
|
||||
/*
|
||||
LogIndexes is the index for mapping log line number to buffer offset.
|
||||
Because it uses varint encoding, it is impossible to predict its size.
|
||||
|
||||
+38
-35
@@ -10,6 +10,8 @@ import (
|
||||
"time"
|
||||
|
||||
"gitea.dev/models/db"
|
||||
"gitea.dev/modules/base"
|
||||
"gitea.dev/modules/log"
|
||||
"gitea.dev/modules/timeutil"
|
||||
"gitea.dev/modules/util"
|
||||
|
||||
@@ -23,7 +25,7 @@ type AccessToken struct {
|
||||
Name string
|
||||
Token string `xorm:"-"`
|
||||
TokenHash string `xorm:"UNIQUE"` // sha256 of token
|
||||
TokenSalt string
|
||||
TokenSalt string // only set for legacy pbkdf2 hashes
|
||||
TokenLastEight string `xorm:"INDEX token_last_eight"`
|
||||
Scope AccessTokenScope
|
||||
|
||||
@@ -43,14 +45,15 @@ func init() {
|
||||
db.RegisterModel(new(AccessToken))
|
||||
}
|
||||
|
||||
// setNewTokenValue generates a fresh random token value and fills in its salt, hash, and last-eight.
|
||||
func GenerateToken() (token, hash, lastEight string) {
|
||||
token = hex.EncodeToString(util.CryptoRandomBytes(20))
|
||||
return token, base.EncodeSha256(token), token[len(token)-8:]
|
||||
}
|
||||
|
||||
// setNewTokenValue generates a fresh random token value and fills in its hash and last-eight.
|
||||
func (t *AccessToken) setNewTokenValue() {
|
||||
salt := util.CryptoRandomString(10)
|
||||
token := util.CryptoRandomBytes(20)
|
||||
t.TokenSalt = salt
|
||||
t.Token = hex.EncodeToString(token)
|
||||
t.TokenHash = HashToken(t.Token, t.TokenSalt)
|
||||
t.TokenLastEight = t.Token[len(t.Token)-8:]
|
||||
t.Token, t.TokenHash, t.TokenLastEight = GenerateToken()
|
||||
t.TokenSalt = ""
|
||||
}
|
||||
|
||||
// NewAccessToken creates new access token.
|
||||
@@ -92,40 +95,34 @@ func GetAccessTokenBySHA(ctx context.Context, token string) (*AccessToken, error
|
||||
return nil, util.NewNotExistErrorf("access token not found")
|
||||
}
|
||||
|
||||
cacheKey := "access:" + token
|
||||
lastEight := token[len(token)-8:]
|
||||
if cached, _ := TokenCache().Get(cacheKey); cached != nil {
|
||||
// Re-get the token from the db in case it has been deleted or regenerated in the intervening period
|
||||
accessToken := &AccessToken{}
|
||||
has, err := db.GetEngine(ctx).ID(cached.TokenID).Get(accessToken)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if has && util.CryptoConstTimeEqual(accessToken.TokenHash, cached.TokenHash) {
|
||||
return accessToken, nil
|
||||
}
|
||||
// either the token has been deleted or changed, invalidate the cache
|
||||
TokenCache().Remove(cacheKey)
|
||||
}
|
||||
|
||||
var tokens []AccessToken
|
||||
err := db.GetEngine(ctx).Table(&AccessToken{}).Where("token_last_eight = ?", lastEight).Find(&tokens)
|
||||
if err != nil {
|
||||
if err := db.GetEngine(ctx).Where("token_last_eight = ?", token[len(token)-8:]).Find(&tokens); err != nil {
|
||||
return nil, err
|
||||
} else if len(tokens) == 0 {
|
||||
return nil, util.NewNotExistErrorf("access token not found")
|
||||
}
|
||||
|
||||
for _, t := range tokens {
|
||||
tempHash := HashToken(token, t.TokenSalt)
|
||||
if util.CryptoConstTimeEqual(t.TokenHash, tempHash) {
|
||||
TokenCache().Add(cacheKey, &TokenCacheItem{TokenID: t.ID, TokenHash: t.TokenHash})
|
||||
if VerifyToken(ctx, &t, token, t.TokenSalt, t.TokenHash) {
|
||||
return &t, nil
|
||||
}
|
||||
}
|
||||
return nil, util.NewNotExistErrorf("access token not found")
|
||||
}
|
||||
|
||||
// VerifyToken checks a token against its row's hash and replaces a legacy pbkdf2 hash with sha256 unless the token was regenerated meanwhile.
|
||||
func VerifyToken(ctx context.Context, bean any, token, salt, hash string) bool {
|
||||
tokenHash := base.EncodeSha256(token)
|
||||
if len(hash) == len(tokenHash) {
|
||||
return util.CryptoConstTimeEqual(hash, tokenHash)
|
||||
}
|
||||
if !util.CryptoConstTimeEqual(hash, HashToken(token, salt)) {
|
||||
return false
|
||||
}
|
||||
if _, err := db.GetEngine(ctx).Table(bean).Where("token_hash = ?", hash).NoAutoTime().
|
||||
Update(map[string]any{"token_hash": tokenHash, "token_salt": ""}); err != nil {
|
||||
log.Error("VerifyToken: %v", err)
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// AccessTokenByNameExists checks if a token name has been used already by a user.
|
||||
func AccessTokenByNameExists(ctx context.Context, token *AccessToken) (bool, error) {
|
||||
return db.GetEngine(ctx).Table("access_token").Where("name = ?", token.Name).And("uid = ?", token.UID).Exist()
|
||||
@@ -152,9 +149,15 @@ func (opts ListAccessTokensOptions) ToOrders() string {
|
||||
return "created_unix DESC"
|
||||
}
|
||||
|
||||
// UpdateAccessToken updates information of access token.
|
||||
func UpdateAccessToken(ctx context.Context, t *AccessToken) error {
|
||||
_, err := db.GetEngine(ctx).ID(t.ID).AllCols().Update(t)
|
||||
// TouchAccessToken records a token use at most once a minute, re-checked in SQL so concurrent stale copies write once.
|
||||
func TouchAccessToken(ctx context.Context, t *AccessToken) error {
|
||||
now := timeutil.TimeStampNow()
|
||||
cutoff := now.AddDuration(-time.Minute)
|
||||
if t.UpdatedUnix > t.CreatedUnix && t.UpdatedUnix > cutoff {
|
||||
return nil
|
||||
}
|
||||
_, err := db.GetEngine(ctx).Where("id = ? AND (updated_unix <= created_unix OR updated_unix <= ?)", t.ID, cutoff).
|
||||
Cols("updated_unix").NoAutoTime().Update(&AccessToken{UpdatedUnix: max(now, t.CreatedUnix+1)})
|
||||
return err
|
||||
}
|
||||
|
||||
|
||||
@@ -5,10 +5,13 @@ package auth_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
auth_model "gitea.dev/models/auth"
|
||||
"gitea.dev/models/db"
|
||||
"gitea.dev/models/unittest"
|
||||
"gitea.dev/modules/base"
|
||||
"gitea.dev/modules/timeutil"
|
||||
"gitea.dev/modules/util"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
@@ -18,12 +21,15 @@ func TestAccessTokenLifecycle(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
|
||||
t.Run("GetAccessTokenBySHA", func(t *testing.T) {
|
||||
token, err := auth_model.GetAccessTokenBySHA(t.Context(), "d2c6c1ba3890b309189a8e618c72a162e4efbf36")
|
||||
const legacyToken = "d2c6c1ba3890b309189a8e618c72a162e4efbf36"
|
||||
token, err := auth_model.GetAccessTokenBySHA(t.Context(), legacyToken)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, int64(1), token.UID)
|
||||
assert.Equal(t, "Token A", token.Name)
|
||||
assert.Equal(t, "2b3668e11cb82d3af8c6e4524fc7841297668f5008d1626f0ad3417e9fa39af84c268248b78c481daa7e5dc437784003494f", token.TokenHash)
|
||||
assert.Equal(t, "e4efbf36", token.TokenLastEight)
|
||||
upgraded := unittest.AssertExistsAndLoadBean(t, &auth_model.AccessToken{ID: 1})
|
||||
assert.Equal(t, base.EncodeSha256(legacyToken), upgraded.TokenHash)
|
||||
assert.Empty(t, upgraded.TokenSalt)
|
||||
|
||||
_, err = auth_model.GetAccessTokenBySHA(t.Context(), "notahash")
|
||||
assert.Error(t, err)
|
||||
@@ -109,7 +115,6 @@ func TestAccessTokenLifecycle(t *testing.T) {
|
||||
t.Run("RegenerateAccessToken", func(t *testing.T) {
|
||||
const oldToken = "d2c6c1ba3890b309189a8e618c72a162e4efbf36"
|
||||
|
||||
// prime the successful-lookup cache with the old token value, as a real request would
|
||||
before, err := auth_model.GetAccessTokenBySHA(t.Context(), oldToken)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, "Token A", before.Name)
|
||||
@@ -122,7 +127,6 @@ func TestAccessTokenLifecycle(t *testing.T) {
|
||||
assert.NotEqual(t, before.TokenHash, regenerated.TokenHash)
|
||||
assert.NotEmpty(t, regenerated.Token)
|
||||
|
||||
// the old token value must stop authenticating, even though it was cached as successful above
|
||||
_, err = auth_model.GetAccessTokenBySHA(t.Context(), oldToken)
|
||||
assert.Error(t, err)
|
||||
assert.ErrorIs(t, err, util.ErrNotExist)
|
||||
@@ -158,12 +162,19 @@ func TestAccessTokenLifecycle(t *testing.T) {
|
||||
})
|
||||
}
|
||||
|
||||
func TestUpdateAccessToken(t *testing.T) {
|
||||
func TestTouchAccessToken(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
token, err := auth_model.GetAccessTokenBySHA(t.Context(), "4c6f36e6cf498e2a448662f915d932c09c5a146c")
|
||||
assert.NoError(t, err)
|
||||
token.Name = "Token Z"
|
||||
|
||||
assert.NoError(t, auth_model.UpdateAccessToken(t.Context(), token))
|
||||
unittest.AssertExistsAndLoadBean(t, token)
|
||||
defer timeutil.MockSet(time.Unix(1000000, 0))()
|
||||
now := timeutil.TimeStampNow()
|
||||
touch := func(created, updated, loadedUpdated timeutil.TimeStamp) timeutil.TimeStamp {
|
||||
_, err := db.Exec(t.Context(), "UPDATE access_token SET created_unix = ?, updated_unix = ? WHERE id = 1", created, updated)
|
||||
assert.NoError(t, err)
|
||||
token := &auth_model.AccessToken{ID: 1, Name: "Token Z", CreatedUnix: created, UpdatedUnix: loadedUpdated}
|
||||
assert.NoError(t, auth_model.TouchAccessToken(t.Context(), token))
|
||||
return unittest.AssertExistsAndLoadBean(t, &auth_model.AccessToken{ID: 1, Name: "Token A"}).UpdatedUnix
|
||||
}
|
||||
assert.Equal(t, now, touch(now-7200, now-3600, now-3600))
|
||||
assert.Equal(t, now-1, touch(now-7200, now-1, now-1))
|
||||
assert.Equal(t, now+1, touch(now, now, now))
|
||||
assert.Equal(t, now+5, touch(now-7200, now+5, now-3600))
|
||||
}
|
||||
@@ -1,23 +0,0 @@
|
||||
// Copyright 2026 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package auth
|
||||
|
||||
import (
|
||||
"sync"
|
||||
|
||||
"gitea.dev/modules/setting"
|
||||
|
||||
lru "github.com/hashicorp/golang-lru/v2"
|
||||
)
|
||||
|
||||
type TokenCacheItem struct {
|
||||
TokenID int64
|
||||
TokenHash string
|
||||
}
|
||||
|
||||
var TokenCache = sync.OnceValue(func() *lru.Cache[string, *TokenCacheItem] {
|
||||
cacheSize := max(setting.SuccessfulTokensCacheSize, 20)
|
||||
c, _ := lru.New[string, *TokenCacheItem](cacheSize) // it only fails when size <= 0
|
||||
return c
|
||||
})
|
||||
@@ -83,7 +83,7 @@ func (t *TwoFactor) GenerateScratchToken() (string, error) {
|
||||
return token, nil
|
||||
}
|
||||
|
||||
// HashToken return the hashable salt
|
||||
// HashToken returns the pbkdf2 hash of token with salt
|
||||
func HashToken(token, salt string) string {
|
||||
tempHash := pbkdf2.Key([]byte(token), []byte(salt), 10000, 50, sha256.New)
|
||||
return hex.EncodeToString(tempHash)
|
||||
|
||||
@@ -74,7 +74,6 @@ var (
|
||||
PasswordComplexity []string
|
||||
PasswordHashAlgo string
|
||||
PasswordCheckPwn bool
|
||||
SuccessfulTokensCacheSize int
|
||||
DisableQueryAuthToken bool
|
||||
RecordUserSignupMetadata = false
|
||||
TwoFactorAuthEnforced = false
|
||||
@@ -178,7 +177,6 @@ func loadSecurityFrom(rootCfg ConfigProvider) {
|
||||
}
|
||||
|
||||
PasswordCheckPwn = sec.Key("PASSWORD_CHECK_PWN").MustBool(false)
|
||||
SuccessfulTokensCacheSize = sec.Key("SUCCESSFUL_TOKENS_CACHE_SIZE").MustInt(20)
|
||||
|
||||
if err := sec.MapTo(&Security); err != nil {
|
||||
log.Fatal("Failed to map security settings: %v", err)
|
||||
|
||||
@@ -5,7 +5,6 @@ package runner
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"errors"
|
||||
"strings"
|
||||
"time"
|
||||
@@ -18,7 +17,6 @@ import (
|
||||
"gitea.dev/modules/util"
|
||||
|
||||
"connectrpc.com/connect/v2"
|
||||
lru "github.com/hashicorp/golang-lru/v2"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
)
|
||||
@@ -28,10 +26,6 @@ const (
|
||||
tokenHeaderKey = protocol.TokenHeader
|
||||
)
|
||||
|
||||
type runnerTokenHash struct{ salt, hash string }
|
||||
|
||||
var verifiedRunnerTokens, _ = lru.New[runnerTokenHash, [sha256.Size]byte](10000) // not auth_model.TokenCache, whose small default size thrashes once more runners poll in turn
|
||||
|
||||
// withErrorMessages sends plain errors to runners as CodeUnknown with their message, like connect v1 did.
|
||||
func withErrorMessages(next connect.ServerFunc) connect.ServerFunc {
|
||||
return func(ctx context.Context, spec connect.Spec, stream connect.ServerStream) error {
|
||||
@@ -63,7 +57,7 @@ func withRunner(next connect.ServerFunc) connect.ServerFunc {
|
||||
}
|
||||
return status.Error(codes.Internal, err.Error())
|
||||
}
|
||||
if !verifyRunnerToken(runner, token) {
|
||||
if !auth_model.VerifyToken(ctx, runner, token, runner.TokenSalt, runner.TokenHash) {
|
||||
return errUnregisteredRunner
|
||||
}
|
||||
|
||||
@@ -94,18 +88,6 @@ func withRunner(next connect.ServerFunc) connect.ServerFunc {
|
||||
}
|
||||
}
|
||||
|
||||
func verifyRunnerToken(runner *actions_model.ActionRunner, token string) bool {
|
||||
key, digest := runnerTokenHash{runner.TokenSalt, runner.TokenHash}, sha256.Sum256([]byte(token))
|
||||
if cached, ok := verifiedRunnerTokens.Get(key); ok && util.CryptoConstTimeEqual(cached[:], digest[:]) {
|
||||
return true
|
||||
}
|
||||
if !util.CryptoConstTimeEqual(runner.TokenHash, auth_model.HashToken(token, runner.TokenSalt)) {
|
||||
return false
|
||||
}
|
||||
verifiedRunnerTokens.Add(key, digest)
|
||||
return true
|
||||
}
|
||||
|
||||
func getMethodName(spec connect.Spec) string {
|
||||
splits := strings.Split(spec.Procedure, "/")
|
||||
if len(splits) > 0 {
|
||||
|
||||
@@ -1,26 +0,0 @@
|
||||
// Copyright 2026 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package runner
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"testing"
|
||||
|
||||
actions_model "gitea.dev/models/actions"
|
||||
auth_model "gitea.dev/models/auth"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestVerifyRunnerToken(t *testing.T) {
|
||||
verifiedRunnerTokens.Purge()
|
||||
runner := &actions_model.ActionRunner{TokenSalt: "salt", TokenHash: auth_model.HashToken("token", "salt")}
|
||||
assert.True(t, verifyRunnerToken(runner, "token"))
|
||||
assert.True(t, verifyRunnerToken(runner, "token"))
|
||||
assert.False(t, verifyRunnerToken(runner, "wrong"))
|
||||
|
||||
other := &actions_model.ActionRunner{TokenSalt: "salt", TokenHash: auth_model.HashToken("other", "salt")}
|
||||
assert.False(t, verifyRunnerToken(other, "token"))
|
||||
assert.Equal(t, [][sha256.Size]byte{sha256.Sum256([]byte("token"))}, verifiedRunnerTokens.Values())
|
||||
}
|
||||
@@ -15,7 +15,6 @@ import (
|
||||
"gitea.dev/modules/auth/httpauth"
|
||||
"gitea.dev/modules/log"
|
||||
"gitea.dev/modules/setting"
|
||||
"gitea.dev/modules/timeutil"
|
||||
"gitea.dev/modules/util"
|
||||
"gitea.dev/services/audit"
|
||||
)
|
||||
@@ -97,9 +96,8 @@ func (b *Basic) VerifyAuthToken(req *http.Request, w http.ResponseWriter, store
|
||||
return nil, err
|
||||
}
|
||||
|
||||
token.UpdatedUnix = timeutil.TimeStampNow()
|
||||
if err = auth_model.UpdateAccessToken(req.Context(), token); err != nil {
|
||||
log.Error("UpdateAccessToken: %v", err)
|
||||
if err = auth_model.TouchAccessToken(req.Context(), token); err != nil {
|
||||
log.Error("VerifyAuthToken: %v", err)
|
||||
}
|
||||
|
||||
u.ExtDoerData = user_model.NewTokenExtDoerData(user_model.CredentialAccessToken, token.ID, token.Scope)
|
||||
|
||||
@@ -17,7 +17,6 @@ import (
|
||||
"gitea.dev/modules/auth/httpauth"
|
||||
"gitea.dev/modules/log"
|
||||
"gitea.dev/modules/setting"
|
||||
"gitea.dev/modules/timeutil"
|
||||
"gitea.dev/modules/util"
|
||||
"gitea.dev/services/actions"
|
||||
"gitea.dev/services/oauth2_provider"
|
||||
@@ -138,9 +137,8 @@ func (o *OAuth2) userFromToken(ctx context.Context, tokenSHA string) (*user_mode
|
||||
return nil, err
|
||||
}
|
||||
|
||||
t.UpdatedUnix = timeutil.TimeStampNow()
|
||||
if err = auth_model.UpdateAccessToken(ctx, t); err != nil {
|
||||
log.Error("UpdateAccessToken: %v", err)
|
||||
if err = auth_model.TouchAccessToken(ctx, t); err != nil {
|
||||
log.Error("userFromToken: %v", err)
|
||||
}
|
||||
user, err := user_model.GetUserByID(ctx, t.UID)
|
||||
if err != nil {
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
@@ -14,7 +15,10 @@ import (
|
||||
"gitea.dev/actionslib/ping/v1/pingv1connect"
|
||||
runnerv1 "gitea.dev/actionslib/runner/v1"
|
||||
"gitea.dev/actionslib/runner/v1/runnerv1connect"
|
||||
actions_model "gitea.dev/models/actions"
|
||||
auth_model "gitea.dev/models/auth"
|
||||
"gitea.dev/models/unittest"
|
||||
"gitea.dev/modules/base"
|
||||
"gitea.dev/modules/setting"
|
||||
|
||||
"connectrpc.com/connect/v2"
|
||||
@@ -24,6 +28,19 @@ import (
|
||||
"google.golang.org/protobuf/types/known/timestamppb"
|
||||
)
|
||||
|
||||
func TestActionsRunnerLegacyToken(t *testing.T) {
|
||||
onGiteaRun(t, func(t *testing.T, _ *url.URL) {
|
||||
runner := &actions_model.ActionRunner{UUID: "legacy-runner", TokenSalt: "legacy-salt"}
|
||||
runner.GenerateAndFillToken()
|
||||
runner.TokenHash = auth_model.HashToken(runner.Token, runner.TokenSalt)
|
||||
require.NoError(t, actions_model.CreateRunner(t.Context(), runner))
|
||||
|
||||
_, err := newMockRunnerClient(runner.UUID, runner.Token).runnerServiceClient.Declare(t.Context(), &runnerv1.DeclareRequest{})
|
||||
require.NoError(t, err)
|
||||
assert.Empty(t, unittest.AssertExistsAndLoadBean(t, &actions_model.ActionRunner{ID: runner.ID, TokenHash: base.EncodeSha256(runner.Token)}).TokenSalt)
|
||||
})
|
||||
}
|
||||
|
||||
type mockRunner struct {
|
||||
client *mockRunnerClient
|
||||
}
|
||||
|
||||
@@ -297,7 +297,7 @@ func testUserSettingsApplications(t *testing.T) {
|
||||
assert.Equal(t, before.Name, after.Name)
|
||||
assert.Equal(t, before.Scope, after.Scope)
|
||||
assert.NotEqual(t, before.TokenHash, after.TokenHash)
|
||||
assert.NotEqual(t, before.TokenSalt, after.TokenSalt)
|
||||
assert.Empty(t, after.TokenSalt)
|
||||
})
|
||||
|
||||
t.Run("OAuth2", func(t *testing.T) {
|
||||
|
||||
Reference in new issue
Block a user