diff --git a/server/model/agent.go b/server/model/agent.go index 9ed8faa19ce..94c43e8b1a0 100644 --- a/server/model/agent.go +++ b/server/model/agent.go @@ -15,6 +15,7 @@ package model import ( + "crypto/sha256" "encoding/base32" "fmt" "maps" @@ -31,6 +32,7 @@ type Agent struct { Name string `json:"name" xorm:"name"` OwnerID int64 `json:"owner_id" xorm:"'owner_id'"` Token string `json:"token" xorm:"token"` + TokenHash string `json:"-" xorm:"VARCHAR(64) INDEX 'token_hash'"` LastContact int64 `json:"last_contact" xorm:"last_contact"` LastWork int64 `json:"last_work" xorm:"last_work"` // last time the agent did something, this value is used to determine if the agent is still doing work used by the autoscaler Platform string `json:"platform" xorm:"VARCHAR(100) 'platform'"` @@ -63,6 +65,12 @@ func GenerateNewAgentToken() string { return base32.StdEncoding.EncodeToString(random.GetRandomBytes(32)) } +// HashAgentToken returns the key agents are looked up by in SQL. +// SQL string compares are not constant time, so the database must never compare the token itself. +func HashAgentToken(token string) string { + return fmt.Sprintf("%x", sha256.Sum256([]byte(token))) +} + func (a *Agent) GetServerLabels() (map[string]string, error) { // clone, the returned map is amended below and must not leak back into the agent filters := maps.Clone(a.Filters) diff --git a/server/rpc/auth_server.go b/server/rpc/auth_server.go index 56b48d44882..59192ef9bcc 100644 --- a/server/rpc/auth_server.go +++ b/server/rpc/auth_server.go @@ -16,6 +16,7 @@ package rpc import ( "context" + "crypto/subtle" "errors" "fmt" "net" @@ -64,7 +65,9 @@ func (s *WoodpeckerAuthServer) Auth(ctx context.Context, req *proto.AuthRequest) func (s *WoodpeckerAuthServer) getAgent(agentID int64, agentToken string) (*model.Agent, error) { // global agent secret auth if s.agentMasterToken != "" { - if agentToken == s.agentMasterToken && agentID == -1 { + isMaster := subtle.ConstantTimeCompare([]byte(agentToken), []byte(s.agentMasterToken)) == 1 + + if isMaster && agentID == -1 { agent := &model.Agent{ OwnerID: model.IDNotSet, OrgID: model.IDNotSet, @@ -79,7 +82,7 @@ func (s *WoodpeckerAuthServer) getAgent(agentID int64, agentToken string) (*mode return agent, nil } - if agentToken == s.agentMasterToken { + if isMaster { agent, err := s.store.AgentFind(agentID) if err != nil { if errors.Is(err, types.ErrRecordNotExist) { @@ -96,11 +99,26 @@ func (s *WoodpeckerAuthServer) getAgent(agentID int64, agentToken string) (*mode } // individual agent token auth + if agentID > 0 { + agent, err := s.store.AgentFind(agentID) + if err == nil && subtle.ConstantTimeCompare([]byte(agentToken), []byte(agent.Token)) == 1 { + return agent, nil + } + // a stale agent ID (e.g. agent recreated with a new token) falls back to the token lookup + } + agent, err := s.store.AgentFindByToken(agentToken) - if err != nil && errors.Is(err, types.ErrRecordNotExist) { - return nil, fmt.Errorf("individual agent not found by token: %w", err) + if err != nil { + if errors.Is(err, types.ErrRecordNotExist) { + return nil, fmt.Errorf("individual agent not found by token: %w", err) + } + return nil, err + } + // the hash lookup only finds the row, the token itself is checked here in constant time + if subtle.ConstantTimeCompare([]byte(agentToken), []byte(agent.Token)) != 1 { + return nil, fmt.Errorf("individual agent not found by token: %w", types.ErrRecordNotExist) } - return agent, err + return agent, nil } // logAuthFailure logs a failed agent login in the format the fail2ban docs match. diff --git a/server/rpc/auth_server_test.go b/server/rpc/auth_server_test.go index ce766501a46..4fa7e7bf50c 100644 --- a/server/rpc/auth_server_test.go +++ b/server/rpc/auth_server_test.go @@ -275,6 +275,36 @@ func TestGetAgent(t *testing.T) { assert.Contains(t, err.Error(), "timeout") }) + t.Run("individual token with agentID is checked against that agent", func(t *testing.T) { + t.Parallel() + + agent := &model.Agent{ID: 4, Token: "ind-token"} + store := store_mocks.NewMockStore(t) + store.On("AgentFind", int64(4)).Return(agent, nil).Once() + + srv := newAuthServer(t, "", store) + got, err := srv.getAgent(4, "ind-token") + + require.NoError(t, err) + assert.Equal(t, int64(4), got.ID) + }) + + t.Run("individual token with stale agentID falls back to the token lookup", func(t *testing.T) { + t.Parallel() + + oldAgent := &model.Agent{ID: 4, Token: "old-token"} + newAgent := &model.Agent{ID: 9, Token: "new-token"} + store := store_mocks.NewMockStore(t) + store.On("AgentFind", int64(4)).Return(oldAgent, nil).Once() + store.On("AgentFindByToken", "new-token").Return(newAgent, nil).Once() + + srv := newAuthServer(t, "", store) + got, err := srv.getAgent(4, "new-token") + + require.NoError(t, err) + assert.Equal(t, int64(9), got.ID) + }) + t.Run("master token configured but wrong token falls through to individual auth", func(t *testing.T) { t.Parallel() @@ -299,6 +329,7 @@ func TestAuthLogsFailureWithClientAddress(t *testing.T) { t.Cleanup(func() { log.Logger = orig }) store := store_mocks.NewMockStore(t) + store.On("AgentFind", int64(3)).Return(nil, types.ErrRecordNotExist) store.On("AgentFindByToken", mock.Anything).Return(nil, types.ErrRecordNotExist) srv := newAuthServer(t, "master", store) @@ -322,6 +353,7 @@ func TestAuthLogsForwardedClientAddress(t *testing.T) { t.Cleanup(func() { log.Logger = orig }) store := store_mocks.NewMockStore(t) + store.On("AgentFind", int64(3)).Return(nil, types.ErrRecordNotExist) store.On("AgentFindByToken", mock.Anything).Return(nil, types.ErrRecordNotExist) srv := newAuthServer(t, "master", store) proxy := &peer.Peer{Addr: &net.TCPAddr{IP: net.ParseIP("10.0.0.2"), Port: 41234}} diff --git a/server/store/datastore/agent.go b/server/store/datastore/agent.go index 2ea2279afdf..ee4d2c9e816 100644 --- a/server/store/datastore/agent.go +++ b/server/store/datastore/agent.go @@ -37,15 +37,18 @@ func (s storage) AgentFindByToken(token string) (*model.Agent, error) { return nil, ErrNoTokenProvided } agent := new(model.Agent) - return agent, wrapGet(s.engine.Where("token = ?", token).Get(agent)) + // never query "token = ?", see model.HashAgentToken + return agent, wrapGet(s.engine.Where("token_hash = ?", model.HashAgentToken(token)).Get(agent)) } func (s storage) AgentCreate(agent *model.Agent) error { + agent.TokenHash = model.HashAgentToken(agent.Token) // only Insert set auto created ID back to object return wrapInsert(s.engine.Insert(agent)) } func (s storage) AgentUpdate(agent *model.Agent) error { + agent.TokenHash = model.HashAgentToken(agent.Token) return retryWrite(func() error { return wrapUpdate(s.engine.ID(agent.ID).AllCols().Update(agent)) }) diff --git a/server/store/datastore/migration/033_add_agent_token_hash.go b/server/store/datastore/migration/033_add_agent_token_hash.go new file mode 100644 index 00000000000..8d545507f2a --- /dev/null +++ b/server/store/datastore/migration/033_add_agent_token_hash.go @@ -0,0 +1,52 @@ +// Copyright 2026 Woodpecker Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package migration + +import ( + "fmt" + + "src.techknowlogick.com/xormigrate" + "xorm.io/xorm" + + "go.woodpecker-ci.org/woodpecker/v3/server/model" +) + +var addAgentTokenHash = xormigrate.Migration{ + ID: "add-agent-token-hash", + MigrateSession: func(sess *xorm.Session) error { + type agents struct { + ID int64 `xorm:"pk autoincr 'id'"` + Token string `xorm:"token"` + TokenHash string `xorm:"VARCHAR(64) 'token_hash'"` + } + + if err := sess.Sync(new(agents)); err != nil { + return fmt.Errorf("sync models failed: %w", err) + } + + var list []*agents + if err := sess.Cols("id", "token").Where("token_hash IS NULL OR token_hash = ''").Find(&list); err != nil { + return err + } + + for _, agent := range list { + agent.TokenHash = model.HashAgentToken(agent.Token) + if _, err := sess.ID(agent.ID).Cols("token_hash").Update(agent); err != nil { + return err + } + } + return nil + }, +} diff --git a/server/store/datastore/migration/033_add_agent_token_hash_test.go b/server/store/datastore/migration/033_add_agent_token_hash_test.go new file mode 100644 index 00000000000..b312145b4d5 --- /dev/null +++ b/server/store/datastore/migration/033_add_agent_token_hash_test.go @@ -0,0 +1,60 @@ +// Copyright 2026 Woodpecker Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package migration + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "go.woodpecker-ci.org/woodpecker/v3/server/model" +) + +type agentV031 struct { + ID int64 `xorm:"pk autoincr 'id'"` + Token string `xorm:"token"` +} + +func (agentV031) TableName() string { return "agents" } + +type agentV032 struct { + ID int64 `xorm:"pk autoincr 'id'"` + Token string `xorm:"token"` + TokenHash string `xorm:"token_hash"` +} + +func (agentV032) TableName() string { return "agents" } + +func TestAddAgentTokenHash(t *testing.T) { + engine, closeDB := testDB(t, true) + defer closeDB() + + require.NoError(t, engine.Sync(new(agentV031))) + _, err := engine.Insert(&agentV031{Token: "token-a"}, &agentV031{Token: "token-b"}) + require.NoError(t, err) + + sess := engine.NewSession() + defer sess.Close() + require.NoError(t, addAgentTokenHash.MigrateSession(sess)) + require.NoError(t, sess.Commit()) + + var agents []*agentV032 + require.NoError(t, engine.OrderBy("id").Find(&agents)) + require.Len(t, agents, 2) + for _, agent := range agents { + assert.Equal(t, model.HashAgentToken(agent.Token), agent.TokenHash) + } +} diff --git a/server/store/datastore/migration/migration.go b/server/store/datastore/migration/migration.go index 03f6f3fa000..b54552021af 100644 --- a/server/store/datastore/migration/migration.go +++ b/server/store/datastore/migration/migration.go @@ -61,6 +61,7 @@ var migrationTasks = []*xormigrate.Migration{ &deduplicateLogEntries, &drop024MigrationArtifacts, &removeSQLiteLegacyInlineUnique, + &addAgentTokenHash, } var allBeans = []any{