Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions server/model/agent.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
package model

import (
"crypto/sha256"
"encoding/base32"
"fmt"
"maps"
Expand All @@ -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'"`
Expand Down Expand Up @@ -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)
Expand Down
28 changes: 23 additions & 5 deletions server/rpc/auth_server.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ package rpc

import (
"context"
"crypto/subtle"
"errors"
"fmt"
"net"
Expand Down Expand Up @@ -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,
Expand All @@ -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) {
Expand All @@ -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.
Expand Down
32 changes: 32 additions & 0 deletions server/rpc/auth_server_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()

Expand All @@ -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)

Expand All @@ -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}}
Expand Down
5 changes: 4 additions & 1 deletion server/store/datastore/agent.go
Original file line number Diff line number Diff line change
Expand Up @@ -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))
})
Expand Down
52 changes: 52 additions & 0 deletions server/store/datastore/migration/033_add_agent_token_hash.go
Original file line number Diff line number Diff line change
@@ -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
},
}
60 changes: 60 additions & 0 deletions server/store/datastore/migration/033_add_agent_token_hash_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
}
1 change: 1 addition & 0 deletions server/store/datastore/migration/migration.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ var migrationTasks = []*xormigrate.Migration{
&deduplicateLogEntries,
&drop024MigrationArtifacts,
&removeSQLiteLegacyInlineUnique,
&addAgentTokenHash,
}

var allBeans = []any{
Expand Down