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
1 change: 1 addition & 0 deletions docs/docs/20-usage/17-security-boundaries.md
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,7 @@ as they can at least compromise the hosts agents run on!

For private repositories, or with [`WOODPECKER_AUTHENTICATE_PUBLIC_REPOS`](../30-administration/10-configuration/10-server.md#authenticate_public_repos),
Woodpecker creates Git credentials of a forge user. They can also push to the repository.
On [GitLab](../30-administration/10-configuration/12-forges/40-gitlab.md#clone-credentials) Woodpecker uses read-only credentials of only this repository instead, if it can create them.

They are only passed to the default clone step, to plugins in the [trusted clone plugins](./75-project-settings.md#custom-trusted-clone-plugins)
and to every step of a repository with the [security option](#trusted-repositories).
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,13 @@ If you restrict logins using [`WOODPECKER_ORGS`](../10-server.md#orgs) or the [a
Woodpecker only considers GitLab groups in which the user has at least the `Developer` role. A user holding a lower role, such as `Guest` or `Reporter`, is not seen as a member of that group and is denied access even if the group is on the list.
:::

## Clone credentials

Pipelines clone with a read-only deploy token of the project, named `woodpecker-clone`.
Woodpecker creates it when the repository is activated or repaired, and deletes it when the repository is deactivated.
This needs the `Maintainer` role in the project, otherwise pipelines clone with the token of the user who activated the repository.
Repositories activated before get the deploy token when they are repaired.

## Configuration

This is a full list of configuration options. Please note that many of these options use default configuration values that should work for the majority of installations.
Expand Down
12 changes: 11 additions & 1 deletion server/api/repo.go
Original file line number Diff line number Diff line change
Expand Up @@ -532,6 +532,7 @@ func DeleteRepo(c *gin.Context) {
} else {
repo.IsActive = false
repo.UserID = 0
repo.CloneSecret = nil

if err := _store.UpdateRepo(repo); err != nil {
_ = c.AbortWithError(http.StatusInternalServerError, err)
Expand Down Expand Up @@ -693,6 +694,11 @@ func MoveRepo(c *gin.Context) {
c.String(http.StatusInternalServerError, err.Error())
return
}
// keep what the forge wrote on activation, like a new clone secret
if err := _store.UpdateRepo(repo); err != nil {
c.String(http.StatusInternalServerError, err.Error())
return
}
c.Status(http.StatusNoContent)
}

Expand Down Expand Up @@ -848,7 +854,11 @@ func repairRepo(c *gin.Context, repo *model.Repo, updatePermissions bool) error
log.Debug().Err(err).Msgf("deactivate repo '%s' to repair failed", repo.FullName)
}

return _forge.Activate(c, repoUser, repo, hookURL)
if err := _forge.Activate(c, repoUser, repo, hookURL); err != nil {
return err
}
// keep what the forge wrote on activation, like a new clone secret
return _store.UpdateRepo(repo)
}

func repairRepoUser(c *gin.Context, repo *model.Repo, _store store.Store) (*model.User, error) {
Expand Down
48 changes: 47 additions & 1 deletion server/api/repo_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -146,14 +146,19 @@ func TestMoveRepoUpdatesOrg(t *testing.T) {
mockForge.On("Repo", mock.Anything, user, model.ForgeRemoteID(""), "newcorp", "rocket").Return(from, nil)
mockForge.On("Org", mock.Anything, user, "newcorp").Return(&model.Org{Name: "newcorp"}, nil)
mockForge.On("Deactivate", mock.Anything, user, mock.Anything, mock.Anything).Return(nil)
mockForge.On("Activate", mock.Anything, user, mock.Anything, mock.Anything).Return(nil)
mockForge.EXPECT().Activate(mock.Anything, user, mock.Anything, mock.Anything).
RunAndReturn(func(_ context.Context, _ *model.User, activated *model.Repo, _ string) error {
activated.CloneSecret = &model.CloneSecret{ForgeRemoteID: "moved"}
return nil
})

code, body := move(t, user, repo, "newcorp/rocket")
require.Equal(t, http.StatusNoContent, code, body)

stored, err := s.GetRepo(repo.ID)
require.NoError(t, err)
assert.Equal(t, "newcorp/rocket", stored.FullName)
assert.Equal(t, &model.CloneSecret{ForgeRemoteID: "moved"}, stored.CloneSecret, "persist the clone secret written by activation")
assert.NotEqual(t, oldOrg.ID, stored.OrgID, "repo must not stay linked to the old org")

newOrg, err := s.OrgFindByName("newcorp", repo.ForgeID)
Expand Down Expand Up @@ -316,6 +321,7 @@ func TestRepairRepoRotatesWebhookSecret(t *testing.T) {
driver.On("Repo", mock.Anything, mock.Anything, mock.Anything, repo.Owner, repo.Name).Return(from, test.lookupErr)

var oldSecret string
var activatedSecret *model.CloneSecret
if test.lookupErr == nil {
driver.EXPECT().Deactivate(mock.Anything, mock.Anything, mock.Anything, server.Config.Server.WebhookHost).
RunAndReturn(func(_ context.Context, _ *model.User, repairing *model.Repo, _ string) error {
Expand Down Expand Up @@ -343,6 +349,10 @@ func TestRepairRepoRotatesWebhookSecret(t *testing.T) {
return oldSecret, nil
})
assert.Error(t, err, "the new URL must not use the old signing key")
if test.activateErr == nil {
activatedSecret = &model.CloneSecret{ForgeRemoteID: model.ForgeRemoteID("token-" + activated.WebhookSecret)}
activated.CloneSecret = activatedSecret
}
return test.activateErr
})
}
Expand Down Expand Up @@ -383,7 +393,43 @@ func TestRepairRepoRotatesWebhookSecret(t *testing.T) {
assert.NotEqual(t, oldSecret, stored.WebhookSecret)
assert.Error(t, err, "old URLs must remain revoked even when activation fails")
}
if test.lookupErr == nil && test.activateErr == nil {
assert.Equal(t, activatedSecret, stored.CloneSecret, "persist the clone secret written by activation")
}
}
})
}
}

func TestDeactivateRepoDropsCloneSecret(t *testing.T) {
s := newTestStore(t)
user := &model.User{Login: "carol", ForgeID: 1, ForgeRemoteID: "u-carol", Hash: "userhash-carol"}
require.NoError(t, s.CreateUser(user))
repo := &model.Repo{
ForgeID: 1,
ForgeRemoteID: "r-carol",
Owner: "acme",
Name: "carol",
FullName: "acme/carol",
UserID: user.ID,
WebhookSecret: "hash-carol",
IsActive: true,
CloneSecret: &model.CloneSecret{Login: "deploy", Token: "secret", ForgeRemoteID: "1"},
}
require.NoError(t, s.CreateRepo(repo))

mockForge := moveRepoForge(t)
mockForge.On("Deactivate", mock.Anything, user, mock.Anything, mock.Anything).Return(nil)

tc := newTestContext(t, s)
withUser(user)(tc)
withRepo(repo, &model.Perm{Admin: true})(tc)
tc.Ctx.Request = httptest.NewRequest(http.MethodDelete, "/repos/1", nil)
DeleteRepo(tc.Ctx)
require.Equal(t, http.StatusOK, tc.Ctx.Writer.Status(), tc.Recorder.Body.String())

stored, err := s.GetRepo(repo.ID)
require.NoError(t, err)
assert.False(t, stored.IsActive)
assert.Nil(t, stored.CloneSecret, "an inactive repo must not keep clone credentials")
}
63 changes: 43 additions & 20 deletions server/forge/gitlab/gitlab.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ import (
const (
defaultScope = "api"
defaultPerPage = 100
cloneTokenName = "woodpecker-clone"
)

// Opts defines configuration options.
Expand Down Expand Up @@ -491,29 +492,27 @@ func isRejectedStatusTransition(err error) bool {
strings.Contains(errResp.Message, "Cannot transition status")
}

// Netrc returns a netrc file capable of authenticating Gitlab requests and
// cloning Gitlab repositories. The netrc will use the global machine account
// when configured.
// Netrc returns a netrc file capable of cloning Gitlab repositories.
// It uses the deploy token of the repository and falls back to the token of the user.
func (g *GitLab) Netrc(u *model.User, r *model.Repo) (*model.Netrc, error) {
login := ""
token := ""

if u != nil {
login = "oauth2"
token = u.AccessToken
}

host, err := common.ExtractHostFromCloneURL(r.Clone)
if err != nil {
return nil, err
}

return &model.Netrc{
Login: login,
Password: token,
Machine: host,
Type: model.ForgeTypeGitlab,
}, nil
netrc := &model.Netrc{
Machine: host,
Type: model.ForgeTypeGitlab,
}
switch {
case r.CloneSecret != nil:
netrc.Login = r.CloneSecret.Login
netrc.Password = r.CloneSecret.Token
case u != nil:
netrc.Login = "oauth2"
netrc.Password = u.AccessToken
}
return netrc, nil
}

func (g *GitLab) getTokenAndWebURL(link string) (token, webURL string, err error) {
Expand All @@ -527,7 +526,7 @@ func (g *GitLab) getTokenAndWebURL(link string) (token, webURL string, err error
}

// Activate activates a repository by adding a Post-commit hook and
// a Public Deploy key, if applicable.
// a read-only deploy token to clone it, if allowed.
func (g *GitLab) Activate(ctx context.Context, user *model.User, repo *model.Repo, link string) error {
client, err := newClient(g.url, user.AccessToken, g.skipVerify)
if err != nil {
Expand Down Expand Up @@ -557,12 +556,29 @@ func (g *GitLab) Activate(ctx context.Context, user *model.User, repo *model.Rep
DeploymentEvents: new(true),
EnableSSLVerification: new(!g.skipVerify),
}, gitlab.WithContext(ctx))
if err != nil {
return err
}

return err
cloneToken, _, err := client.DeployTokens.CreateProjectDeployToken(_repo.ID, &gitlab.CreateProjectDeployTokenOptions{
Name: new(cloneTokenName),
Scopes: &[]string{"read_repository"},
}, gitlab.WithContext(ctx))
if err != nil {
log.Warn().Err(err).Msgf("could not create a deploy token for %s, pipelines clone with the user token", repo.FullName)
repo.CloneSecret = nil
return nil
}
repo.CloneSecret = &model.CloneSecret{
Login: cloneToken.Username,
Token: cloneToken.Token,
ForgeRemoteID: model.ForgeRemoteID(strconv.FormatInt(cloneToken.ID, 10)),
}
return nil
}

// Deactivate removes a repository by removing all the post-commit hooks
// which are equal to link and removing the SSH deploy key.
// which are equal to link and the deploy token to clone it.
func (g *GitLab) Deactivate(ctx context.Context, user *model.User, repo *model.Repo, link string) error {
client, err := newClient(g.url, user.AccessToken, g.skipVerify)
if err != nil {
Expand All @@ -579,6 +595,13 @@ func (g *GitLab) Deactivate(ctx context.Context, user *model.User, repo *model.R
return err
}

if repo.CloneSecret != nil {
id, _ := strconv.ParseInt(string(repo.CloneSecret.ForgeRemoteID), 10, 64)
if _, err := client.DeployTokens.DeleteProjectDeployToken(_repo.ID, id, gitlab.WithContext(ctx)); err != nil {
log.Warn().Err(err).Msgf("could not delete the deploy token of %s", repo.FullName)
}
}

listProjectHooksOptions := &gitlab.ListProjectHooksOptions{
PerPage: defaultPerPage,
Page: 1,
Expand Down
64 changes: 60 additions & 4 deletions server/forge/gitlab/gitlab_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1106,12 +1106,68 @@ func TestOrg(t *testing.T) {
}

func TestNetrc(t *testing.T) {
client := load("https://gitlab.example.com?client_id=test&client_secret=test")
repo := &model.Repo{Clone: "https://gitlab.example.com/group/repo.git"}
var deleted []string
createStatus := http.StatusCreated
mux := http.NewServeMux()
mux.HandleFunc("GET /api/v4/projects/4", func(w http.ResponseWriter, _ *http.Request) {
_, _ = w.Write([]byte(`{"id":4,"path_with_namespace":"group/repo"}`))
})
mux.HandleFunc("POST /api/v4/projects/4/hooks", func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusCreated)
_, _ = w.Write([]byte(`{"id":1}`))
})
mux.HandleFunc("GET /api/v4/projects/4/hooks", func(w http.ResponseWriter, _ *http.Request) {
_, _ = w.Write([]byte(`[]`))
})
mux.HandleFunc("POST /api/v4/projects/4/deploy_tokens", func(w http.ResponseWriter, r *http.Request) {
var opts struct {
Name string `json:"name"`
Scopes []string `json:"scopes"`
}
assert.NoError(t, json.NewDecoder(r.Body).Decode(&opts))
assert.Equal(t, "woodpecker-clone", opts.Name)
assert.Equal(t, []string{"read_repository"}, opts.Scopes, "the token must only read the repository")
w.WriteHeader(createStatus)
if createStatus == http.StatusCreated {
_, _ = w.Write([]byte(`{"id":7,"name":"woodpecker-clone","username":"gitlab+deploy-token-7","token":"deploy-secret","scopes":["read_repository"]}`))
}
})
mux.HandleFunc("DELETE /api/v4/projects/4/deploy_tokens/{id}", func(w http.ResponseWriter, r *http.Request) {
deleted = append(deleted, r.PathValue("id"))
w.WriteHeader(http.StatusNoContent)
})
server := httptest.NewServer(mux)
defer server.Close()

client := load(server.URL + "?client_id=test&client_secret=test")
user := &model.User{AccessToken: "token"}
repo := &model.Repo{ForgeRemoteID: "4", FullName: "group/repo", Clone: "https://gitlab.example.com/group/repo.git"}
link := "http://example.com/api/hook?access_token=token"
userNetrc := &model.Netrc{Machine: "gitlab.example.com", Login: "oauth2", Password: "token", Type: model.ForgeTypeGitlab}

// a repo without a deploy token clones with the token of the user
netrc, err := client.Netrc(user, repo)
require.NoError(t, err)
assert.Equal(t, userNetrc, netrc)

// activation creates a deploy token that pipelines clone with instead
require.NoError(t, client.Activate(t.Context(), user, repo, link))
assert.Equal(t, &model.CloneSecret{Login: "gitlab+deploy-token-7", Token: "deploy-secret", ForgeRemoteID: "7"}, repo.CloneSecret)
netrc, err = client.Netrc(user, repo)
require.NoError(t, err)
assert.Equal(t, &model.Netrc{Machine: "gitlab.example.com", Login: "gitlab+deploy-token-7", Password: "deploy-secret", Type: model.ForgeTypeGitlab}, netrc)

// deactivation deletes the deploy token
require.NoError(t, client.Deactivate(t.Context(), user, repo, link))
assert.Equal(t, []string{"7"}, deleted)

netrc, err := client.Netrc(&model.User{AccessToken: "token"}, repo)
// without the right to create a deploy token, activation still works and drops the old one
createStatus = http.StatusForbidden
require.NoError(t, client.Activate(t.Context(), user, repo, link))
assert.Nil(t, repo.CloneSecret)
netrc, err = client.Netrc(user, repo)
require.NoError(t, err)
assert.Equal(t, &model.Netrc{Machine: "gitlab.example.com", Login: "oauth2", Password: "token", Type: model.ForgeTypeGitlab}, netrc)
assert.Equal(t, userNetrc, netrc)

// without a user only the machine is known
netrc, err = client.Netrc(nil, repo)
Expand Down
11 changes: 11 additions & 0 deletions server/model/repo.go
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@ type Repo struct {
AllowDeploy bool `json:"allow_deploy" xorm:"allow_deploy"`
Config string `json:"config_file" xorm:"varchar(500) 'config_path'"`
WebhookSecret string `json:"-" xorm:"varchar(500) 'hash'"`
CloneSecret *CloneSecret `json:"-" xorm:"json 'clone_secret'"`
CancelPreviousPipelineEvents []WebhookEvent `json:"cancel_previous_pipeline_events" xorm:"json 'cancel_previous_pipeline_events'"`
NetrcTrustedPlugins []string `json:"netrc_trusted" xorm:"json 'netrc_trusted'"`
ConfigExtensionEndpoint string `json:"config_extension_endpoint" xorm:"varchar(500) 'config_extension_endpoint'"`
Expand All @@ -92,6 +93,16 @@ type Repo struct {
Perm *Perm `json:"-" xorm:"-"`
} // @name Repo

// CloneSecret holds credentials the forge created for Woodpecker to clone only this
// repository, so pipelines do not need the token of the repository user to clone.
type CloneSecret struct {
// Login and Token are the credentials to clone the repository over HTTP(S).
Login string `json:"login,omitempty"`
Token string `json:"token,omitempty"`
// ForgeRemoteID is the forge ID of the credentials, to remove them again.
ForgeRemoteID ForgeRemoteID `json:"forge_remote_id,omitempty"`
}

// TableName return database table name for xorm.
func (Repo) TableName() string {
return "repos"
Expand Down