Add global and organization secrets (#1027)

* Implement database changes and store methods for global and organization secrets

* Add tests for new store methods
* Add organization secret API and UI
* Add global secrets API and UI

* Add suggestions

* Update warning style

* Apply suggestions from code review

Co-authored-by: Anbraten <anton@ju60.de>

* Fix lint warning

Co-authored-by: Anbraten <anton@ju60.de>
This commit is contained in:
Lauris BH 2022-08-14 14:48:53 +03:00 committed by GitHub
parent bed3ef104c
commit 1ac2c42652
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
35 changed files with 1777 additions and 130 deletions

View file

@ -6,7 +6,7 @@
"dbaeumer.vscode-eslint",
"esbenp.prettier-vscode",
"voorjaar.windicss-intellisense",
"johnsoncodehk.volar",
"Vue.volar",
"redhat.vscode-yaml",
"davidanson.vscode-markdownlint"
],

4
go.mod
View file

@ -42,8 +42,8 @@ require (
google.golang.org/grpc v1.47.0
google.golang.org/protobuf v1.28.0
gopkg.in/yaml.v3 v3.0.1
xorm.io/builder v0.3.10
xorm.io/xorm v1.3.0
xorm.io/builder v0.3.12
xorm.io/xorm v1.3.1
)
require (

10
go.sum
View file

@ -1199,8 +1199,8 @@ rsc.io/quote/v3 v3.1.0/go.mod h1:yEA65RcK8LyAZtP9Kv3t0HmxON59tX3rD+tICJqUlj0=
rsc.io/sampler v1.3.0/go.mod h1:T1hPZKmBbMNahiBKFy5HrXp6adAjACjK9JXDnKaTXpA=
sigs.k8s.io/yaml v1.1.0/go.mod h1:UJmg0vDUVViEyp3mgSv9WPwZCDxu4rQW1olrI1uml+o=
sourcegraph.com/sourcegraph/appdash v0.0.0-20190731080439-ebfcffb1b5c0/go.mod h1:hI742Nqp5OhwiqlzhgfbWU4mW4yO10fP+LoT9WOswdU=
xorm.io/builder v0.3.9/go.mod h1:aUW0S9eb9VCaPohFCH3j7czOx1PMW3i1HrSzbLYGBSE=
xorm.io/builder v0.3.10 h1:Rvkncad3Lo9YIVqCbgIf6QnpR/HcW3IEr0AANNpuyMQ=
xorm.io/builder v0.3.10/go.mod h1:aUW0S9eb9VCaPohFCH3j7czOx1PMW3i1HrSzbLYGBSE=
xorm.io/xorm v1.3.0 h1:UsVke0wyAk3tJcb0j15gLWv2DEshVUnySVyvcYDny8w=
xorm.io/xorm v1.3.0/go.mod h1:cEaWjDPqoIusTkmDAG+krCcPcTglqo8CDU8geX/yhko=
xorm.io/builder v0.3.11-0.20220531020008-1bd24a7dc978/go.mod h1:aUW0S9eb9VCaPohFCH3j7czOx1PMW3i1HrSzbLYGBSE=
xorm.io/builder v0.3.12 h1:ASZYX7fQmy+o8UJdhlLHSW57JDOkM8DNhcAF5d0LiJM=
xorm.io/builder v0.3.12/go.mod h1:aUW0S9eb9VCaPohFCH3j7czOx1PMW3i1HrSzbLYGBSE=
xorm.io/xorm v1.3.1 h1:z5egKrDoOLqZFhMjcGF4FBHiTmE5/feQoHclfhNidfM=
xorm.io/xorm v1.3.1/go.mod h1:9NbjqdnjX6eyjRRhh01GHm64r6N9shTb/8Ak3YRt8Nw=

123
server/api/global_secret.go Normal file
View file

@ -0,0 +1,123 @@
// Copyright 2022 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 api
import (
"net/http"
"github.com/woodpecker-ci/woodpecker/server"
"github.com/woodpecker-ci/woodpecker/server/model"
"github.com/gin-gonic/gin"
)
// GetGlobalSecretList gets the global secret list from
// the database and writes to the response in json format.
func GetGlobalSecretList(c *gin.Context) {
list, err := server.Config.Services.Secrets.GlobalSecretList()
if err != nil {
c.String(http.StatusInternalServerError, "Error getting global secret list. %s", err)
return
}
// copy the secret detail to remove the sensitive
// password and token fields.
for i, secret := range list {
list[i] = secret.Copy()
}
c.JSON(http.StatusOK, list)
}
// GetGlobalSecret gets the named global secret from the database
// and writes to the response in json format.
func GetGlobalSecret(c *gin.Context) {
name := c.Param("secret")
secret, err := server.Config.Services.Secrets.GlobalSecretFind(name)
if err != nil {
c.String(404, "Error getting global secret %q. %s", name, err)
return
}
c.JSON(200, secret.Copy())
}
// PostGlobalSecret persists a global secret to the database.
func PostGlobalSecret(c *gin.Context) {
in := new(model.Secret)
if err := c.Bind(in); err != nil {
c.String(http.StatusBadRequest, "Error parsing global secret. %s", err)
return
}
secret := &model.Secret{
Name: in.Name,
Value: in.Value,
Events: in.Events,
Images: in.Images,
}
if err := secret.Validate(); err != nil {
c.String(400, "Error inserting global secret. %s", err)
return
}
if err := server.Config.Services.Secrets.GlobalSecretCreate(secret); err != nil {
c.String(500, "Error inserting global secret %q. %s", in.Name, err)
return
}
c.JSON(200, secret.Copy())
}
// PatchGlobalSecret updates a global secret in the database.
func PatchGlobalSecret(c *gin.Context) {
name := c.Param("secret")
in := new(model.Secret)
err := c.Bind(in)
if err != nil {
c.String(http.StatusBadRequest, "Error parsing secret. %s", err)
return
}
secret, err := server.Config.Services.Secrets.GlobalSecretFind(name)
if err != nil {
c.String(404, "Error getting global secret %q. %s", name, err)
return
}
if in.Value != "" {
secret.Value = in.Value
}
if in.Events != nil {
secret.Events = in.Events
}
if in.Images != nil {
secret.Images = in.Images
}
if err := secret.Validate(); err != nil {
c.String(400, "Error updating global secret. %s", err)
return
}
if err := server.Config.Services.Secrets.GlobalSecretUpdate(secret); err != nil {
c.String(500, "Error updating global secret %q. %s", in.Name, err)
return
}
c.JSON(200, secret.Copy())
}
// DeleteGlobalSecret deletes the named global secret from the database.
func DeleteGlobalSecret(c *gin.Context) {
name := c.Param("secret")
if err := server.Config.Services.Secrets.GlobalSecretDelete(name); err != nil {
c.String(500, "Error deleting global secret %q. %s", name, err)
return
}
c.String(204, "")
}

47
server/api/org.go Normal file
View file

@ -0,0 +1,47 @@
// Copyright 2022 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 api
import (
"net/http"
"github.com/woodpecker-ci/woodpecker/server"
"github.com/woodpecker-ci/woodpecker/server/model"
"github.com/woodpecker-ci/woodpecker/server/router/middleware/session"
"github.com/gin-gonic/gin"
)
// GetOrgPermissions returns the permissions of the current user in the given organization.
func GetOrgPermissions(c *gin.Context) {
var (
err error
user = session.User(c)
owner = c.Param("owner")
)
if user == nil {
c.JSON(http.StatusOK, &model.OrgPerm{})
return
}
perm, err := server.Config.Services.Membership.Get(c, user, owner)
if err != nil {
c.String(http.StatusInternalServerError, "Error getting membership for %q. %s", owner, err)
return
}
c.JSON(http.StatusOK, perm)
}

136
server/api/org_secret.go Normal file
View file

@ -0,0 +1,136 @@
// Copyright 2022 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 api
import (
"net/http"
"github.com/woodpecker-ci/woodpecker/server"
"github.com/woodpecker-ci/woodpecker/server/model"
"github.com/gin-gonic/gin"
)
// GetOrgSecret gets the named organization secret from the database
// and writes to the response in json format.
func GetOrgSecret(c *gin.Context) {
var (
owner = c.Param("owner")
name = c.Param("secret")
)
secret, err := server.Config.Services.Secrets.OrgSecretFind(owner, name)
if err != nil {
c.String(404, "Error getting org %q secret %q. %s", owner, name, err)
return
}
c.JSON(200, secret.Copy())
}
// GetOrgSecretList gest the organization secret list from
// the database and writes to the response in json format.
func GetOrgSecretList(c *gin.Context) {
owner := c.Param("owner")
list, err := server.Config.Services.Secrets.OrgSecretList(owner)
if err != nil {
c.String(http.StatusInternalServerError, "Error getting secret list for %q. %s", owner, err)
return
}
// copy the secret detail to remove the sensitive
// password and token fields.
for i, secret := range list {
list[i] = secret.Copy()
}
c.JSON(http.StatusOK, list)
}
// PostOrgSecret persists an organization secret to the database.
func PostOrgSecret(c *gin.Context) {
owner := c.Param("owner")
in := new(model.Secret)
if err := c.Bind(in); err != nil {
c.String(http.StatusBadRequest, "Error parsing org %q secret. %s", owner, err)
return
}
secret := &model.Secret{
Owner: owner,
Name: in.Name,
Value: in.Value,
Events: in.Events,
Images: in.Images,
}
if err := secret.Validate(); err != nil {
c.String(400, "Error inserting org %q secret. %s", owner, err)
return
}
if err := server.Config.Services.Secrets.OrgSecretCreate(owner, secret); err != nil {
c.String(500, "Error inserting org %q secret %q. %s", owner, in.Name, err)
return
}
c.JSON(200, secret.Copy())
}
// PatchOrgSecret updates an organization secret in the database.
func PatchOrgSecret(c *gin.Context) {
var (
owner = c.Param("owner")
name = c.Param("secret")
)
in := new(model.Secret)
err := c.Bind(in)
if err != nil {
c.String(http.StatusBadRequest, "Error parsing secret. %s", err)
return
}
secret, err := server.Config.Services.Secrets.OrgSecretFind(owner, name)
if err != nil {
c.String(404, "Error getting org %q secret %q. %s", owner, name, err)
return
}
if in.Value != "" {
secret.Value = in.Value
}
if in.Events != nil {
secret.Events = in.Events
}
if in.Images != nil {
secret.Images = in.Images
}
if err := secret.Validate(); err != nil {
c.String(400, "Error updating org %q secret. %s", owner, err)
return
}
if err := server.Config.Services.Secrets.OrgSecretUpdate(owner, secret); err != nil {
c.String(500, "Error updating org %q secret %q. %s", owner, in.Name, err)
return
}
c.JSON(200, secret.Copy())
}
// DeleteOrgSecret deletes the named organization secret from the database.
func DeleteOrgSecret(c *gin.Context) {
var (
owner = c.Param("owner")
name = c.Param("secret")
)
if err := server.Config.Services.Secrets.OrgSecretDelete(owner, name); err != nil {
c.String(500, "Error deleting org %q secret %q. %s", owner, name, err)
return
}
c.String(204, "")
}

View file

@ -30,29 +30,47 @@ var (
// SecretService defines a service for managing secrets.
type SecretService interface {
SecretListBuild(*Repo, *Build) ([]*Secret, error)
// Repository secrets
SecretFind(*Repo, string) (*Secret, error)
SecretList(*Repo) ([]*Secret, error)
SecretListBuild(*Repo, *Build) ([]*Secret, error)
SecretCreate(*Repo, *Secret) error
SecretUpdate(*Repo, *Secret) error
SecretDelete(*Repo, string) error
// Organization secrets
OrgSecretFind(string, string) (*Secret, error)
OrgSecretList(string) ([]*Secret, error)
OrgSecretCreate(string, *Secret) error
OrgSecretUpdate(string, *Secret) error
OrgSecretDelete(string, string) error
// Global secrets
GlobalSecretFind(string) (*Secret, error)
GlobalSecretList() ([]*Secret, error)
GlobalSecretCreate(*Secret) error
GlobalSecretUpdate(*Secret) error
GlobalSecretDelete(string) error
}
// SecretStore persists secret information to storage.
type SecretStore interface {
SecretFind(*Repo, string) (*Secret, error)
SecretList(*Repo) ([]*Secret, error)
SecretList(*Repo, bool) ([]*Secret, error)
SecretCreate(*Secret) error
SecretUpdate(*Secret) error
SecretDelete(*Secret) error
OrgSecretFind(string, string) (*Secret, error)
OrgSecretList(string) ([]*Secret, error)
GlobalSecretFind(string) (*Secret, error)
GlobalSecretList() ([]*Secret, error)
}
// Secret represents a secret variable, such as a password or token.
// swagger:model registry
type Secret struct {
ID int64 `json:"id" xorm:"pk autoincr 'secret_id'"`
RepoID int64 `json:"-" xorm:"UNIQUE(s) INDEX 'secret_repo_id'"`
Name string `json:"name" xorm:"UNIQUE(s) INDEX 'secret_name'"`
Owner string `json:"-" xorm:"NOT NULL DEFAULT '' UNIQUE(s) INDEX 'secret_owner'"`
RepoID int64 `json:"-" xorm:"NOT NULL DEFAULT 0 UNIQUE(s) INDEX 'secret_repo_id'"`
Name string `json:"name" xorm:"NOT NULL UNIQUE(s) INDEX 'secret_name'"`
Value string `json:"value,omitempty" xorm:"TEXT 'secret_value'"`
Images []string `json:"image" xorm:"json 'secret_images'"`
Events []WebhookEvent `json:"event" xorm:"json 'secret_events'"`
@ -65,6 +83,16 @@ func (Secret) TableName() string {
return "secrets"
}
// Global secret.
func (s Secret) Global() bool {
return s.RepoID == 0 && s.Owner == ""
}
// Organization secret.
func (s Secret) Organization() bool {
return s.RepoID == 0 && s.Owner != ""
}
// Match returns true if an image and event match the restricted list.
func (s *Secret) Match(event WebhookEvent) bool {
if len(s.Events) == 0 {
@ -119,6 +147,7 @@ func (s *Secret) Validate() error {
func (s *Secret) Copy() *Secret {
return &Secret{
ID: s.ID,
Owner: s.Owner,
RepoID: s.RepoID,
Name: s.Name,
Images: s.Images,

View file

@ -21,11 +21,39 @@ func (b *builtin) SecretFind(repo *model.Repo, name string) (*model.Secret, erro
}
func (b *builtin) SecretList(repo *model.Repo) ([]*model.Secret, error) {
return b.store.SecretList(repo)
return b.store.SecretList(repo, false)
}
func (b *builtin) SecretListBuild(repo *model.Repo, build *model.Build) ([]*model.Secret, error) {
return b.store.SecretList(repo)
s, err := b.store.SecretList(repo, true)
if err != nil {
return nil, err
}
// Return only secrets with unique name
// Priority order in case of duplicate names are repository, user/organization, global
secrets := make([]*model.Secret, 0, len(s))
uniq := make(map[string]struct{})
for _, cond := range []struct {
Global bool
Organization bool
}{
{},
{Organization: true},
{Global: true},
} {
for _, secret := range s {
if secret.Global() == cond.Global && secret.Organization() == cond.Organization {
continue
}
if _, ok := uniq[secret.Name]; ok {
continue
}
uniq[secret.Name] = struct{}{}
secrets = append(secrets, secret)
}
}
return secrets, nil
}
func (b *builtin) SecretCreate(repo *model.Repo, in *model.Secret) error {
@ -43,3 +71,51 @@ func (b *builtin) SecretDelete(repo *model.Repo, name string) error {
}
return b.store.SecretDelete(secret)
}
func (b *builtin) OrgSecretFind(owner, name string) (*model.Secret, error) {
return b.store.OrgSecretFind(owner, name)
}
func (b *builtin) OrgSecretList(owner string) ([]*model.Secret, error) {
return b.store.OrgSecretList(owner)
}
func (b *builtin) OrgSecretCreate(owner string, in *model.Secret) error {
return b.store.SecretCreate(in)
}
func (b *builtin) OrgSecretUpdate(owner string, in *model.Secret) error {
return b.store.SecretUpdate(in)
}
func (b *builtin) OrgSecretDelete(owner, name string) error {
secret, err := b.store.OrgSecretFind(owner, name)
if err != nil {
return err
}
return b.store.SecretDelete(secret)
}
func (b *builtin) GlobalSecretFind(owner string) (*model.Secret, error) {
return b.store.GlobalSecretFind(owner)
}
func (b *builtin) GlobalSecretList() ([]*model.Secret, error) {
return b.store.GlobalSecretList()
}
func (b *builtin) GlobalSecretCreate(in *model.Secret) error {
return b.store.SecretCreate(in)
}
func (b *builtin) GlobalSecretUpdate(in *model.Secret) error {
return b.store.SecretUpdate(in)
}
func (b *builtin) GlobalSecretDelete(name string) error {
secret, err := b.store.GlobalSecretFind(name)
if err != nil {
return err
}
return b.store.SecretDelete(secret)
}

View file

@ -43,6 +43,21 @@ func apiRoutes(e *gin.Engine) {
users.DELETE("/:login", api.DeleteUser)
}
orgBase := e.Group("/api/orgs/:owner")
{
orgBase.GET("/permissions", api.GetOrgPermissions)
org := orgBase.Group("")
{
org.Use(session.MustOrgMember(true))
org.GET("/secrets", api.GetOrgSecretList)
org.POST("/secrets", api.PostOrgSecret)
org.GET("/secrets/:secret", api.GetOrgSecret)
org.PATCH("/secrets/:secret", api.PatchOrgSecret)
org.DELETE("/secrets/:secret", api.DeleteOrgSecret)
}
}
repoBase := e.Group("/api/repos/:owner/:name")
{
repoBase.Use(session.SetRepo())
@ -123,6 +138,16 @@ func apiRoutes(e *gin.Engine) {
queue.GET("/norunningbuilds", api.BlockTilQueueHasRunningItem)
}
secrets := e.Group("/api/secrets")
{
secrets.Use(session.MustAdmin())
secrets.GET("", api.GetGlobalSecretList)
secrets.POST("", api.PostGlobalSecret)
secrets.GET("/:secret", api.GetGlobalSecret)
secrets.PATCH("/:secret", api.PatchGlobalSecret)
secrets.DELETE("/:secret", api.DeleteGlobalSecret)
}
debugger := e.Group("/api/debug")
{
debugger.Use(session.MustAdmin())

View file

@ -0,0 +1,46 @@
// Copyright 2022 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 (
"xorm.io/xorm"
)
type SecretV006 struct {
Owner string `json:"-" xorm:"NOT NULL DEFAULT '' UNIQUE(s) INDEX 'secret_owner'"`
RepoID int64 `json:"-" xorm:"NOT NULL DEFAULT 0 UNIQUE(s) INDEX 'secret_repo_id'"`
Name string `json:"name" xorm:"NOT NULL UNIQUE(s) INDEX 'secret_name'"`
}
// TableName return database table name for xorm
func (SecretV006) TableName() string {
return "secrets"
}
var alterTableSecretsAddUserCol = task{
name: "alter-table-add-secrets-user-id",
fn: func(sess *xorm.Session) error {
if err := sess.Sync2(new(SecretV006)); err != nil {
return err
}
if err := alterColumnDefault(sess, "secrets", "secret_repo_id", "0"); err != nil {
return err
}
if err := alterColumnNull(sess, "secrets", "secret_repo_id", false); err != nil {
return err
}
return alterColumnNull(sess, "secrets", "secret_name", false)
},
}

View file

@ -212,6 +212,42 @@ func dropTableColumns(sess *xorm.Session, tableName string, columnNames ...strin
return nil
}
func alterColumnDefault(sess *xorm.Session, table, column, defValue string) error {
dialect := sess.Engine().Dialect().URI().DBType
switch dialect {
case schemas.MYSQL:
_, err := sess.Exec(fmt.Sprintf("ALTER TABLE `%s` COLUMN `%s` SET DEFAULT %s;", table, column, defValue))
return err
case schemas.POSTGRES:
_, err := sess.Exec(fmt.Sprintf("ALTER TABLE `%s` ALTER COLUMN `%s` SET DEFAULT %s;", table, column, defValue))
return err
case schemas.SQLITE:
return nil
default:
return fmt.Errorf("dialect '%s' not supported", dialect)
}
}
func alterColumnNull(sess *xorm.Session, table, column string, null bool) error {
val := "NULL"
if !null {
val = "NOT NULL"
}
dialect := sess.Engine().Dialect().URI().DBType
switch dialect {
case schemas.MYSQL:
_, err := sess.Exec(fmt.Sprintf("ALTER TABLE `%s` COLUMN `%s` SET %s;", table, column, val))
return err
case schemas.POSTGRES:
_, err := sess.Exec(fmt.Sprintf("ALTER TABLE `%s` ALTER COLUMN `%s` SET %s;", table, column, val))
return err
case schemas.SQLITE:
return nil
default:
return fmt.Errorf("dialect '%s' not supported", dialect)
}
}
var (
whitespaces = regexp.MustCompile(`\s+`)
columnSeparator = regexp.MustCompile(`\s?,\s?`)

View file

@ -34,6 +34,7 @@ var migrationTasks = []*task{
&alterTableReposDropCounter,
&dropSenders,
&alterTableLogUpdateColumnLogDataType,
&alterTableSecretsAddUserCol,
}
var allBeans = []interface{}{

View file

@ -16,6 +16,8 @@ package datastore
import (
"github.com/woodpecker-ci/woodpecker/server/model"
"xorm.io/builder"
)
func (s storage) SecretFind(repo *model.Repo, name string) (*model.Secret, error) {
@ -26,9 +28,14 @@ func (s storage) SecretFind(repo *model.Repo, name string) (*model.Secret, error
return secret, wrapGet(s.engine.Get(secret))
}
func (s storage) SecretList(repo *model.Repo) ([]*model.Secret, error) {
func (s storage) SecretList(repo *model.Repo, includeGlobalAndOrgSecrets bool) ([]*model.Secret, error) {
secrets := make([]*model.Secret, 0, perPage)
return secrets, s.engine.Where("secret_repo_id = ?", repo.ID).Find(&secrets)
var cond builder.Cond = builder.Eq{"secret_repo_id": repo.ID}
if includeGlobalAndOrgSecrets {
cond = cond.Or(builder.Eq{"secret_owner": repo.Owner}).
Or(builder.And(builder.Eq{"secret_owner": ""}, builder.Eq{"secret_repo_id": 0}))
}
return secrets, s.engine.Where(cond).Find(&secrets)
}
func (s storage) SecretCreate(secret *model.Secret) error {
@ -46,3 +53,28 @@ func (s storage) SecretDelete(secret *model.Secret) error {
_, err := s.engine.ID(secret.ID).Delete(new(model.Secret))
return err
}
func (s storage) OrgSecretFind(owner, name string) (*model.Secret, error) {
secret := &model.Secret{
Owner: owner,
Name: name,
}
return secret, wrapGet(s.engine.Get(secret))
}
func (s storage) OrgSecretList(owner string) ([]*model.Secret, error) {
secrets := make([]*model.Secret, 0, perPage)
return secrets, s.engine.Where("secret_owner = ?", owner).Find(&secrets)
}
func (s storage) GlobalSecretFind(name string) (*model.Secret, error) {
secret := &model.Secret{
Name: name,
}
return secret, wrapGet(s.engine.Where(builder.And(builder.Eq{"secret_owner": ""}, builder.Eq{"secret_repo_id": 0})).Get(secret))
}
func (s storage) GlobalSecretList() ([]*model.Secret, error) {
secrets := make([]*model.Secret, 0, perPage)
return secrets, s.engine.Where(builder.And(builder.Eq{"secret_owner": ""}, builder.Eq{"secret_repo_id": 0})).Find(&secrets)
}

View file

@ -70,22 +70,24 @@ func TestSecretList(t *testing.T) {
store, closer := newTestStore(t, new(model.Secret))
defer closer()
assert.NoError(t, store.SecretCreate(&model.Secret{
RepoID: 1,
Name: "foo",
Value: "bar",
}))
assert.NoError(t, store.SecretCreate(&model.Secret{
RepoID: 1,
Name: "baz",
Value: "qux",
}))
createTestSecrets(t, store)
list, err := store.SecretList(&model.Repo{ID: 1})
list, err := store.SecretList(&model.Repo{ID: 1, Owner: "org"}, false)
assert.NoError(t, err)
assert.Len(t, list, 2)
}
func TestSecretBuildList(t *testing.T) {
store, closer := newTestStore(t, new(model.Secret))
defer closer()
createTestSecrets(t, store)
list, err := store.SecretList(&model.Repo{ID: 1, Owner: "org"}, true)
assert.NoError(t, err)
assert.Len(t, list, 4)
}
func TestSecretUpdate(t *testing.T) {
store, closer := newTestStore(t, new(model.Secret))
defer closer()
@ -162,3 +164,135 @@ func TestSecretIndexes(t *testing.T) {
t.Errorf("Unexpected error: duplicate name")
}
}
func createTestSecrets(t *testing.T, store *storage) {
assert.NoError(t, store.SecretCreate(&model.Secret{
Owner: "org",
Name: "usr",
Value: "sec",
}))
assert.NoError(t, store.SecretCreate(&model.Secret{
RepoID: 1,
Name: "foo",
Value: "bar",
}))
assert.NoError(t, store.SecretCreate(&model.Secret{
RepoID: 1,
Name: "baz",
Value: "qux",
}))
assert.NoError(t, store.SecretCreate(&model.Secret{
Name: "global",
Value: "val",
}))
}
func TestOrgSecretFind(t *testing.T) {
store, closer := newTestStore(t, new(model.Secret))
defer closer()
err := store.SecretCreate(&model.Secret{
Owner: "org",
Name: "password",
Value: "correct-horse-battery-staple",
Images: []string{"golang", "node"},
Events: []model.WebhookEvent{"push", "tag"},
})
if err != nil {
t.Errorf("Unexpected error: insert secret: %s", err)
return
}
secret, err := store.OrgSecretFind("org", "password")
if err != nil {
t.Error(err)
return
}
if got, want := secret.Owner, "org"; got != want {
t.Errorf("Want owner %s, got %s", want, got)
}
if got, want := secret.Name, "password"; got != want {
t.Errorf("Want secret name %s, got %s", want, got)
}
if got, want := secret.Value, "correct-horse-battery-staple"; got != want {
t.Errorf("Want secret value %s, got %s", want, got)
}
if got, want := secret.Events[0], model.EventPush; got != want {
t.Errorf("Want secret event %s, got %s", want, got)
}
if got, want := secret.Events[1], model.EventTag; got != want {
t.Errorf("Want secret event %s, got %s", want, got)
}
if got, want := secret.Images[0], "golang"; got != want {
t.Errorf("Want secret image %s, got %s", want, got)
}
if got, want := secret.Images[1], "node"; got != want {
t.Errorf("Want secret image %s, got %s", want, got)
}
}
func TestOrgSecretList(t *testing.T) {
store, closer := newTestStore(t, new(model.Secret))
defer closer()
createTestSecrets(t, store)
list, err := store.OrgSecretList("org")
assert.NoError(t, err)
assert.Len(t, list, 1)
assert.True(t, list[0].Organization())
}
func TestGlobalSecretFind(t *testing.T) {
store, closer := newTestStore(t, new(model.Secret))
defer closer()
err := store.SecretCreate(&model.Secret{
Name: "password",
Value: "correct-horse-battery-staple",
Images: []string{"golang", "node"},
Events: []model.WebhookEvent{"push", "tag"},
})
if err != nil {
t.Errorf("Unexpected error: insert secret: %s", err)
return
}
secret, err := store.GlobalSecretFind("password")
if err != nil {
t.Error(err)
return
}
if got, want := secret.Name, "password"; got != want {
t.Errorf("Want secret name %s, got %s", want, got)
}
if got, want := secret.Value, "correct-horse-battery-staple"; got != want {
t.Errorf("Want secret value %s, got %s", want, got)
}
if got, want := secret.Events[0], model.EventPush; got != want {
t.Errorf("Want secret event %s, got %s", want, got)
}
if got, want := secret.Events[1], model.EventTag; got != want {
t.Errorf("Want secret event %s, got %s", want, got)
}
if got, want := secret.Images[0], "golang"; got != want {
t.Errorf("Want secret image %s, got %s", want, got)
}
if got, want := secret.Images[1], "node"; got != want {
t.Errorf("Want secret image %s, got %s", want, got)
}
}
func TestGlobalSecretList(t *testing.T) {
store, closer := newTestStore(t, new(model.Secret))
defer closer()
createTestSecrets(t, store)
list, err := store.GlobalSecretList()
assert.NoError(t, err)
assert.Len(t, list, 1)
assert.True(t, list[0].Global())
}

View file

@ -106,10 +106,14 @@ type Store interface {
// Secrets
SecretFind(*model.Repo, string) (*model.Secret, error)
SecretList(*model.Repo) ([]*model.Secret, error)
SecretList(*model.Repo, bool) ([]*model.Secret, error)
SecretCreate(*model.Secret) error
SecretUpdate(*model.Secret) error
SecretDelete(*model.Secret) error
OrgSecretFind(string, string) (*model.Secret, error)
OrgSecretList(string) ([]*model.Secret, error)
GlobalSecretFind(string) (*model.Secret, error)
GlobalSecretList() ([]*model.Secret, error)
// Registrys
RegistryFind(*model.Repo, string) (*model.Registry, error)

View file

@ -31,7 +31,7 @@
"branches": "Branches",
"add": "Add repository",
"user_none": "This organization / user does not have any projects yet.",
"not_allowed": "Not allowed to access this repository",
"not_allowed": "You are not allowed to access this repository",
"enable": {
"reload": "Reload repositories",
@ -43,7 +43,7 @@
"settings": {
"settings": "Settings",
"not_allowed": "Not allowed to access this repository's settings",
"not_allowed": "You are not allowed to access this repository's settings",
"general": {
"general": "General",
@ -205,6 +205,67 @@
}
},
"org": {
"settings": {
"settings": "Settings",
"not_allowed": "You are not allowed to access this organization's settings",
"secrets": {
"secrets": "Secrets",
"desc": "Organization secrets can be passed to all organization's repository individual pipeline steps at runtime as environmental variables.",
"none": "There are no organization secrets yet.",
"add": "Add secret",
"save": "Save secret",
"show": "Show secrets",
"name": "Name",
"value": "Value",
"deleted": "Organization secret deleted",
"created": "Organization secret created",
"saved": "Organization secret saved",
"images": {
"images": "Available for following images",
"desc": "Comma separated list of images where this secret is available, leave empty to allow all images"
},
"events": {
"events": "Available at following events",
"pr_warning": "Please be careful with this option as a bad actor can submit a malicious pull request that exposes your secrets."
}
}
}
},
"admin": {
"settings": {
"settings": "Settings",
"not_allowed": "You are not allowed to access server settings",
"secrets": {
"secrets": "Secrets",
"desc": "Global secrets can be passed to all repositories individual pipeline steps at runtime as environmental variables.",
"warning": "These secrets will be available for all server users.",
"none": "There are no global secrets yet.",
"add": "Add secret",
"save": "Save secret",
"show": "Show secrets",
"name": "Name",
"value": "Value",
"deleted": "Global secret deleted",
"created": "Global secret created",
"saved": "Global secret saved",
"images": {
"images": "Available for following images",
"desc": "Comma separated list of images where this secret is available, leave empty to allow all images"
},
"events": {
"events": "Available at following events",
"pr_warning": "Please be careful with this option as a bad actor can submit a malicious pull request that exposes your secrets."
}
}
}
},
"user": {
"oauth_error": "Error while authenticating against OAuth provider",
"internal_error": "Some internal error occurred",

View file

@ -205,6 +205,67 @@
}
},
"org": {
"settings": {
"settings": "Iestatījumi",
"not_allowed": "Nav piekļuves šīs organizācijas iestatījumiem",
"secrets": {
"secrets": "Noslēpumi",
"desc": "Noslēpumus var padot visu organizācijas repozitoriju individuāliem konvejerdarba soļiem izpildes laikā kā vides mainīgos.",
"none": "Pagaidām nav neviena organizācijas noslēpuma.",
"add": "Pievienot noslēpumu",
"save": "Saglabāt noslēpumu",
"show": "Noslēpumu saraksts",
"name": "Nosaukums",
"value": "Vērtība",
"deleted": "Organizācijas noslēpums dzēsts",
"created": "Organizācijas noslēpums izveidots",
"saved": "Organizācijas noslēpums saglabāts",
"images": {
"images": "Pieejami šādiem attēliem",
"desc": "Ar komatiem atdalīts saraksts ar attēliem, kam šis noslēpums būs pieejams, atstājot tukšu, tas būs pieejams visiem attēliem."
},
"events": {
"events": "Pieejams šādiem notikumiem",
"pr_warning": "Uzmanieties, jo šādā veidā tas būs pieejams visiem cilvēkiem, kas var iesūtīt izmaiņu pieprasījumu!"
}
}
}
},
"admin": {
"settings": {
"settings": "Iestatījumi",
"not_allowed": "Nav piekļuves servera iestatījumiem",
"secrets": {
"secrets": "Noslēpumi",
"desc": "Noslēpumus var padot visu repozitoriju individuāliem konvejerdarba soļiem izpildes laikā kā vides mainīgos.",
"warning": "Šie noslēpumi būs pieejami visiem servera lietotājiem.",
"none": "Pagaidām nav neviena globālā noslēpuma.",
"add": "Pievienot noslēpumu",
"save": "Saglabāt noslēpumu",
"show": "Noslēpumu saraksts",
"name": "Nosaukums",
"value": "Vērtība",
"deleted": "Globālais noslēpums dzēsts",
"created": "Globālais noslēpums izveidots",
"saved": "Globālais noslēpums saglabāts",
"images": {
"images": "Pieejami šādiem attēliem",
"desc": "Ar komatiem atdalīts saraksts ar attēliem, kam šis noslēpums būs pieejams, atstājot tukšu, tas būs pieejams visiem attēliem."
},
"events": {
"events": "Pieejams šādiem notikumiem",
"pr_warning": "Uzmanieties, jo šādā veidā tas būs pieejams visiem cilvēkiem, kas var iesūtīt izmaiņu pieprasījumu!"
}
}
}
},
"user": {
"oauth_error": "Neizdevās autorizēties, izmantojot, OAuth piegādātāju",
"internal_error": "Notikusi sistēmas iekšējā kļūda",

View file

@ -0,0 +1,143 @@
<template>
<Panel>
<div class="flex flex-row border-b mb-4 pb-4 items-center dark:border-gray-600">
<div class="ml-2">
<h1 class="text-xl text-color">{{ $t('admin.settings.secrets.secrets') }}</h1>
<p class="text-sm text-color-alt">
{{ $t('admin.settings.secrets.desc') }}
<DocsLink url="docs/usage/secrets" />
</p>
<Warning :text="$t('admin.settings.secrets.warning')" />
</div>
<Button
v-if="selectedSecret"
class="ml-auto"
:text="$t('admin.settings.secrets.show')"
start-icon="back"
@click="selectedSecret = undefined"
/>
<Button
v-else
class="ml-auto"
:text="$t('admin.settings.secrets.add')"
start-icon="plus"
@click="showAddSecret"
/>
</div>
<SecretList
v-if="!selectedSecret"
v-model="secrets"
i18n-prefix="admin.settings.secrets."
:is-deleting="isDeleting"
@edit="editSecret"
@delete="deleteSecret"
/>
<SecretEdit
v-else
v-model="selectedSecret"
i18n-prefix="admin.settings.secrets."
:is-saving="isSaving"
@save="createSecret"
/>
</Panel>
</template>
<script lang="ts">
import { cloneDeep } from 'lodash';
import { computed, defineComponent, onMounted, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import Button from '~/components/atomic/Button.vue';
import DocsLink from '~/components/atomic/DocsLink.vue';
import Warning from '~/components/atomic/Warning.vue';
import Panel from '~/components/layout/Panel.vue';
import SecretEdit from '~/components/secrets/SecretEdit.vue';
import SecretList from '~/components/secrets/SecretList.vue';
import useApiClient from '~/compositions/useApiClient';
import { useAsyncAction } from '~/compositions/useAsyncAction';
import useNotifications from '~/compositions/useNotifications';
import { Secret, WebhookEvents } from '~/lib/api/types';
const emptySecret = {
name: '',
value: '',
image: [],
event: [WebhookEvents.Push],
};
export default defineComponent({
name: 'AdminSecretsTab',
components: {
Button,
Panel,
DocsLink,
SecretList,
SecretEdit,
Warning,
},
setup() {
const apiClient = useApiClient();
const notifications = useNotifications();
const i18n = useI18n();
const secrets = ref<Secret[]>([]);
const selectedSecret = ref<Partial<Secret>>();
const isEditingSecret = computed(() => !!selectedSecret.value?.id);
async function loadSecrets() {
secrets.value = await apiClient.getGlobalSecretList();
}
const { doSubmit: createSecret, isLoading: isSaving } = useAsyncAction(async () => {
if (!selectedSecret.value) {
throw new Error("Unexpected: Can't get secret");
}
if (isEditingSecret.value) {
await apiClient.updateGlobalSecret(selectedSecret.value);
} else {
await apiClient.createGlobalSecret(selectedSecret.value);
}
notifications.notify({
title: i18n.t(isEditingSecret.value ? 'admin.settings.secrets.saved' : 'admin.settings.secrets.created'),
type: 'success',
});
selectedSecret.value = undefined;
await loadSecrets();
});
const { doSubmit: deleteSecret, isLoading: isDeleting } = useAsyncAction(async (_secret: Secret) => {
await apiClient.deleteGlobalSecret(_secret.name);
notifications.notify({ title: i18n.t('admin.settings.secrets.deleted'), type: 'success' });
await loadSecrets();
});
function editSecret(secret: Secret) {
selectedSecret.value = cloneDeep(secret);
}
function showAddSecret() {
selectedSecret.value = cloneDeep(emptySecret);
}
onMounted(async () => {
await loadSecrets();
});
return {
selectedSecret,
secrets,
isDeleting,
isSaving,
showAddSecret,
createSecret,
editSecret,
deleteSecret,
};
},
});
</script>

View file

@ -0,0 +1,22 @@
<template>
<div
class="text-sm text-gray-600 font-bold rounded-md border border-solid p-2 border-yellow-500 bg-yellow-200 dark:bg-yellow-600 dark:border-yellow-800 dark:text-light-100"
>
{{ text }}
</div>
</template>
<script lang="ts">
import { defineComponent } from 'vue';
export default defineComponent({
name: 'Warning',
props: {
text: {
type: String,
required: true,
},
},
});
</script>

View file

@ -26,6 +26,12 @@
class="!text-white !dark:text-gray-500"
@click="darkMode = !darkMode"
/>
<IconButton
v-if="user?.admin"
icon="settings"
class="!text-white !dark:text-gray-500"
:to="{ name: 'admin-settings' }"
/>
<router-link v-if="user" :to="{ name: 'user' }">
<img v-if="user && user.avatar_url" class="w-8" :src="`${user.avatar_url}`" />
</router-link>

View file

@ -0,0 +1,147 @@
<template>
<Panel>
<div class="flex flex-row border-b mb-4 pb-4 items-center dark:border-gray-600">
<div class="ml-2">
<h1 class="text-xl text-color">{{ $t('org.settings.secrets.secrets') }}</h1>
<p class="text-sm text-color-alt">
{{ $t('org.settings.secrets.desc') }}
<DocsLink url="docs/usage/secrets" />
</p>
</div>
<Button
v-if="selectedSecret"
class="ml-auto"
:text="$t('org.settings.secrets.show')"
start-icon="back"
@click="selectedSecret = undefined"
/>
<Button v-else class="ml-auto" :text="$t('org.settings.secrets.add')" start-icon="plus" @click="showAddSecret" />
</div>
<SecretList
v-if="!selectedSecret"
v-model="secrets"
i18n-prefix="org.settings.secrets."
:is-deleting="isDeleting"
@edit="editSecret"
@delete="deleteSecret"
/>
<SecretEdit
v-else
v-model="selectedSecret"
i18n-prefix="org.settings.secrets."
:is-saving="isSaving"
@save="createSecret"
/>
</Panel>
</template>
<script lang="ts">
import { cloneDeep } from 'lodash';
import { computed, defineComponent, inject, onMounted, Ref, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import Button from '~/components/atomic/Button.vue';
import DocsLink from '~/components/atomic/DocsLink.vue';
import Panel from '~/components/layout/Panel.vue';
import SecretEdit from '~/components/secrets/SecretEdit.vue';
import SecretList from '~/components/secrets/SecretList.vue';
import useApiClient from '~/compositions/useApiClient';
import { useAsyncAction } from '~/compositions/useAsyncAction';
import useNotifications from '~/compositions/useNotifications';
import { Org, Secret, WebhookEvents } from '~/lib/api/types';
const emptySecret = {
name: '',
value: '',
image: [],
event: [WebhookEvents.Push],
};
export default defineComponent({
name: 'OrgSecretsTab',
components: {
Button,
Panel,
DocsLink,
SecretList,
SecretEdit,
},
setup() {
const apiClient = useApiClient();
const notifications = useNotifications();
const i18n = useI18n();
const org = inject<Ref<Org>>('org');
const secrets = ref<Secret[]>([]);
const selectedSecret = ref<Partial<Secret>>();
const isEditingSecret = computed(() => !!selectedSecret.value?.id);
async function loadSecrets() {
if (!org?.value) {
throw new Error("Unexpected: Can't load org");
}
secrets.value = await apiClient.getOrgSecretList(org.value.name);
}
const { doSubmit: createSecret, isLoading: isSaving } = useAsyncAction(async () => {
if (!org?.value) {
throw new Error("Unexpected: Can't load org");
}
if (!selectedSecret.value) {
throw new Error("Unexpected: Can't get secret");
}
if (isEditingSecret.value) {
await apiClient.updateOrgSecret(org.value.name, selectedSecret.value);
} else {
await apiClient.createOrgSecret(org.value.name, selectedSecret.value);
}
notifications.notify({
title: i18n.t(isEditingSecret.value ? 'org.settings.secrets.saved' : 'org.settings.secrets.created'),
type: 'success',
});
selectedSecret.value = undefined;
await loadSecrets();
});
const { doSubmit: deleteSecret, isLoading: isDeleting } = useAsyncAction(async (_secret: Secret) => {
if (!org?.value) {
throw new Error("Unexpected: Can't load org");
}
await apiClient.deleteOrgSecret(org.value.name, _secret.name);
notifications.notify({ title: i18n.t('org.settings.secrets.deleted'), type: 'success' });
await loadSecrets();
});
function editSecret(secret: Secret) {
selectedSecret.value = cloneDeep(secret);
}
function showAddSecret() {
selectedSecret.value = cloneDeep(emptySecret);
}
onMounted(async () => {
await loadSecrets();
});
return {
selectedSecret,
secrets,
isDeleting,
isSaving,
showAddSecret,
createSecret,
editSecret,
deleteSecret,
};
},
});
</script>

View file

@ -18,64 +18,22 @@
<Button v-else class="ml-auto" :text="$t('repo.settings.secrets.add')" start-icon="plus" @click="showAddSecret" />
</div>
<div v-if="!selectedSecret" class="space-y-4 text-color">
<ListItem v-for="secret in secrets" :key="secret.id" class="items-center">
<span>{{ secret.name }}</span>
<div class="ml-auto">
<span
v-for="event in secret.event"
:key="event"
class="bg-gray-500 dark:bg-dark-700 dark:text-gray-400 text-white rounded-md mx-1 py-1 px-2 text-sm"
>{{ event }}</span
>
</div>
<IconButton icon="edit" class="ml-2 w-8 h-8" @click="selectedSecret = secret" />
<IconButton
icon="trash"
class="ml-2 w-8 h-8 hover:text-red-400 hover:dark:text-red-500"
:is-loading="isDeleting"
@click="deleteSecret(secret)"
<SecretList
v-if="!selectedSecret"
v-model="secrets"
i18n-prefix="repo.settings.secrets."
:is-deleting="isDeleting"
@edit="editSecret"
@delete="deleteSecret"
/>
</ListItem>
<div v-if="secrets?.length === 0" class="ml-2">{{ $t('repo.settings.secrets.none') }}</div>
</div>
<div v-else class="space-y-4">
<form @submit.prevent="createSecret">
<InputField :label="$t('repo.settings.secrets.name')">
<TextField
v-model="selectedSecret.name"
:placeholder="$t('repo.settings.secrets.name')"
required
:disabled="isEditingSecret"
<SecretEdit
v-else
v-model="selectedSecret"
i18n-prefix="repo.settings.secrets."
:is-saving="isSaving"
@save="createSecret"
/>
</InputField>
<InputField :label="$t('repo.settings.secrets.value')">
<TextField
v-model="selectedSecret.value"
:placeholder="$t('repo.settings.secrets.value')"
:lines="5"
required
/>
</InputField>
<InputField :label="$t('repo.settings.secrets.images.images')">
<TextField v-model="images" :placeholder="$t('repo.settings.secrets.images.desc')" />
</InputField>
<InputField :label="$t('repo.settings.secrets.events.events')">
<CheckboxesField v-model="selectedSecret.event" :options="secretEventsOptions" />
</InputField>
<Button
:is-loading="isSaving"
type="submit"
:text="isEditingSecret ? $t('repo.settings.secrets.save') : $t('repo.settings.secrets.add')"
/>
</form>
</div>
</Panel>
</template>
@ -86,13 +44,9 @@ import { useI18n } from 'vue-i18n';
import Button from '~/components/atomic/Button.vue';
import DocsLink from '~/components/atomic/DocsLink.vue';
import IconButton from '~/components/atomic/IconButton.vue';
import ListItem from '~/components/atomic/ListItem.vue';
import CheckboxesField from '~/components/form/CheckboxesField.vue';
import { CheckboxOption } from '~/components/form/form.types';
import InputField from '~/components/form/InputField.vue';
import TextField from '~/components/form/TextField.vue';
import Panel from '~/components/layout/Panel.vue';
import SecretEdit from '~/components/secrets/SecretEdit.vue';
import SecretList from '~/components/secrets/SecretList.vue';
import useApiClient from '~/compositions/useApiClient';
import { useAsyncAction } from '~/compositions/useAsyncAction';
import useNotifications from '~/compositions/useNotifications';
@ -111,12 +65,9 @@ export default defineComponent({
components: {
Button,
Panel,
ListItem,
IconButton,
InputField,
TextField,
DocsLink,
CheckboxesField,
SecretList,
SecretEdit,
},
setup() {
@ -125,22 +76,9 @@ export default defineComponent({
const i18n = useI18n();
const repo = inject<Ref<Repo>>('repo');
const secrets = ref<Secret[]>();
const secrets = ref<Secret[]>([]);
const selectedSecret = ref<Partial<Secret>>();
const isEditingSecret = computed(() => !!selectedSecret.value?.id);
const images = computed<string>({
get() {
return selectedSecret.value?.image?.join(',') || '';
},
set(value) {
if (selectedSecret.value) {
selectedSecret.value.image = value
.split(',')
.map((s) => s.trim())
.filter((s) => s !== '');
}
},
});
async function loadSecrets() {
if (!repo?.value) {
@ -182,6 +120,10 @@ export default defineComponent({
await loadSecrets();
});
function editSecret(secret: Secret) {
selectedSecret.value = cloneDeep(secret);
}
function showAddSecret() {
selectedSecret.value = cloneDeep(emptySecret);
}
@ -190,27 +132,14 @@ export default defineComponent({
await loadSecrets();
});
const secretEventsOptions: CheckboxOption[] = [
{ value: WebhookEvents.Push, text: i18n.t('repo.build.event.push') },
{ value: WebhookEvents.Tag, text: i18n.t('repo.build.event.tag') },
{
value: WebhookEvents.PullRequest,
text: i18n.t('repo.build.event.pr'),
description: i18n.t('repo.settings.secrets.events.pr_warning'),
},
{ value: WebhookEvents.Deploy, text: i18n.t('repo.build.event.deploy') },
];
return {
secretEventsOptions,
selectedSecret,
secrets,
images,
isEditingSecret,
isSaving,
isDeleting,
isSaving,
showAddSecret,
createSecret,
editSecret,
deleteSecret,
};
},

View file

@ -0,0 +1,132 @@
<template>
<div v-if="innerValue" class="space-y-4">
<form @submit.prevent="save">
<InputField :label="$t(i18nPrefix + 'name')">
<TextField
v-model="innerValue.name"
:placeholder="$t(i18nPrefix + 'name')"
required
:disabled="isEditingSecret"
/>
</InputField>
<InputField :label="$t(i18nPrefix + 'value')">
<TextField v-model="innerValue.value" :placeholder="$t(i18nPrefix + 'value')" :lines="5" required />
</InputField>
<InputField :label="$t(i18nPrefix + 'images.images')">
<TextField v-model="images" :placeholder="$t(i18nPrefix + 'images.desc')" />
</InputField>
<InputField :label="$t(i18nPrefix + 'events.events')">
<CheckboxesField v-model="innerValue.event" :options="secretEventsOptions" />
</InputField>
<Button
:is-loading="isSaving"
type="submit"
:text="isEditingSecret ? $t(i18nPrefix + 'save') : $t(i18nPrefix + 'add')"
/>
</form>
</div>
</template>
<script lang="ts">
import { computed, defineComponent, PropType, toRef } from 'vue';
import { useI18n } from 'vue-i18n';
import Button from '~/components/atomic/Button.vue';
import CheckboxesField from '~/components/form/CheckboxesField.vue';
import { CheckboxOption } from '~/components/form/form.types';
import InputField from '~/components/form/InputField.vue';
import TextField from '~/components/form/TextField.vue';
import { Secret, WebhookEvents } from '~/lib/api/types';
export default defineComponent({
name: 'SecretEdit',
components: {
Button,
InputField,
TextField,
CheckboxesField,
},
props: {
// used by toRef
// eslint-disable-next-line vue/no-unused-properties
modelValue: {
type: Object as PropType<Partial<Secret>>,
default: undefined,
},
isSaving: {
type: Boolean,
},
i18nPrefix: {
type: String,
required: true,
},
},
emits: {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
'update:modelValue': (_value: Partial<Secret> | undefined): boolean => true,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
save: (_value: Partial<Secret>): boolean => true,
},
setup: (props, ctx) => {
const i18n = useI18n();
const modelValue = toRef(props, 'modelValue');
const innerValue = computed({
get: () => modelValue.value,
set: (value) => {
ctx.emit('update:modelValue', value);
},
});
const images = computed<string>({
get() {
return innerValue.value?.image?.join(',') || '';
},
set(value) {
if (innerValue.value) {
innerValue.value.image = value
.split(',')
.map((s) => s.trim())
.filter((s) => s !== '');
}
},
});
const isEditingSecret = computed(() => !!innerValue.value?.id);
const secretEventsOptions: CheckboxOption[] = [
{ value: WebhookEvents.Push, text: i18n.t('repo.build.event.push') },
{ value: WebhookEvents.Tag, text: i18n.t('repo.build.event.tag') },
{
value: WebhookEvents.PullRequest,
text: i18n.t('repo.build.event.pr'),
description: i18n.t('repo.settings.secrets.events.pr_warning'),
},
{ value: WebhookEvents.Deploy, text: i18n.t('repo.build.event.deploy') },
];
function save() {
if (!innerValue.value) {
return;
}
ctx.emit('save', innerValue.value);
}
return {
innerValue,
isEditingSecret,
secretEventsOptions,
images,
save,
};
},
});
</script>

View file

@ -0,0 +1,82 @@
<template>
<div class="space-y-4 text-color">
<ListItem v-for="secret in secrets" :key="secret.id" class="items-center">
<span>{{ secret.name }}</span>
<div class="ml-auto">
<span
v-for="event in secret.event"
:key="event"
class="bg-gray-500 dark:bg-dark-700 dark:text-gray-400 text-white rounded-md mx-1 py-1 px-2 text-sm"
>
{{ event }}
</span>
</div>
<IconButton icon="edit" class="ml-2 w-8 h-8" @click="editSecret(secret)" />
<IconButton
icon="trash"
class="ml-2 w-8 h-8 hover:text-red-400 hover:dark:text-red-500"
:is-loading="isDeleting"
@click="deleteSecret(secret)"
/>
</ListItem>
<div v-if="secrets?.length === 0" class="ml-2">{{ $t(i18nPrefix + 'none') }}</div>
</div>
</template>
<script lang="ts">
import { defineComponent, PropType, toRef } from 'vue';
import IconButton from '~/components/atomic/IconButton.vue';
import ListItem from '~/components/atomic/ListItem.vue';
import { Secret } from '~/lib/api/types';
export default defineComponent({
name: 'SecretList',
components: {
ListItem,
IconButton,
},
props: {
// used by toRef
// eslint-disable-next-line vue/no-unused-properties
modelValue: {
type: Array as PropType<Secret[]>,
required: true,
},
isDeleting: {
type: Boolean,
required: true,
},
i18nPrefix: {
type: String,
required: true,
},
},
emits: {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
edit: (secret: Secret): boolean => true,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
delete: (secret: Secret): boolean => true,
},
setup(props, ctx) {
const secrets = toRef(props, 'modelValue');
function editSecret(secret: Secret) {
ctx.emit('edit', secret);
}
function deleteSecret(secret: Secret) {
ctx.emit('delete', secret);
}
return { secrets, editSecret, deleteSecret };
},
});
</script>

View file

@ -5,6 +5,7 @@ import {
BuildFeed,
BuildLog,
BuildProc,
OrgPermissions,
Registry,
Repo,
RepoPermissions,
@ -135,6 +136,42 @@ export default class WoodpeckerClient extends ApiClient {
return this._delete(`/api/repos/${owner}/${repo}/registry/${registryAddress}`);
}
getOrgPermissions(owner: string): Promise<OrgPermissions> {
return this._get(`/api/orgs/${owner}/permissions`) as Promise<OrgPermissions>;
}
getOrgSecretList(owner: string): Promise<Secret[]> {
return this._get(`/api/orgs/${owner}/secrets`) as Promise<Secret[]>;
}
createOrgSecret(owner: string, secret: Partial<Secret>): Promise<unknown> {
return this._post(`/api/orgs/${owner}/secrets`, secret);
}
updateOrgSecret(owner: string, secret: Partial<Secret>): Promise<unknown> {
return this._patch(`/api/orgs/${owner}/secrets/${secret.name}`, secret);
}
deleteOrgSecret(owner: string, secretName: string): Promise<unknown> {
return this._delete(`/api/orgs/${owner}/secrets/${secretName}`);
}
getGlobalSecretList(): Promise<Secret[]> {
return this._get(`/api/secrets`) as Promise<Secret[]>;
}
createGlobalSecret(secret: Partial<Secret>): Promise<unknown> {
return this._post(`/api/secrets`, secret);
}
updateGlobalSecret(secret: Partial<Secret>): Promise<unknown> {
return this._patch(`/api/secrets/${secret.name}`, secret);
}
deleteGlobalSecret(secretName: string): Promise<unknown> {
return this._delete(`/api/secrets/${secretName}`);
}
getSelf(): Promise<unknown> {
return this._get('/api/user');
}

View file

@ -1,5 +1,6 @@
export * from './build';
export * from './buildConfig';
export * from './org';
export * from './registry';
export * from './repo';
export * from './secret';

View file

@ -0,0 +1,10 @@
// A version control organization.
export type Org = {
// The name of the organization.
name: string;
};
export type OrgPermissions = {
member: boolean;
admin: boolean;
};

View file

@ -28,6 +28,25 @@ const routes: RouteRecordRaw[] = [
component: (): Component => import('~/views/ReposOwner.vue'),
props: true,
},
{
path: '/org/:repoOwner',
component: (): Component => import('~/views/org/OrgWrapper.vue'),
props: true,
children: [
{
path: '',
name: 'org',
redirect: (route) => ({ name: 'repos-owner', params: route.params }),
},
{
path: 'settings',
name: 'org-settings',
component: (): Component => import('~/views/org/OrgSettings.vue'),
meta: { authentication: 'required' },
props: true,
},
],
},
{
path: '/:repoOwner/:repoName',
name: 'repo-wrapper',
@ -99,6 +118,13 @@ const routes: RouteRecordRaw[] = [
meta: { authentication: 'required' },
props: true,
},
{
path: '/admin/settings',
name: 'admin-settings',
component: (): Component => import('~/views/admin/AdminSettings.vue'),
meta: { authentication: 'required' },
props: true,
},
{
path: '/user',
name: 'user',

View file

@ -3,6 +3,7 @@
<div class="flex flex-row flex-wrap md:grid md:grid-cols-3 border-b pb-4 mb-4 dark:border-dark-200">
<h1 class="text-xl text-color">{{ repoOwner }}</h1>
<TextField v-model="search" class="w-auto md:ml-auto md:mr-auto" :placeholder="$t('search')" />
<IconButton v-if="orgPermissions.admin" icon="settings" :to="{ name: 'org-settings' }" class="ml-auto" />
</div>
<div class="space-y-4">
@ -24,10 +25,13 @@
<script lang="ts">
import { computed, defineComponent, onMounted, ref } from 'vue';
import IconButton from '~/components/atomic/IconButton.vue';
import ListItem from '~/components/atomic/ListItem.vue';
import TextField from '~/components/form/TextField.vue';
import FluidContainer from '~/components/layout/FluidContainer.vue';
import useApiClient from '~/compositions/useApiClient';
import { useRepoSearch } from '~/compositions/useRepoSearch';
import { OrgPermissions } from '~/lib/api/types';
import RepoStore from '~/store/repos';
export default defineComponent({
@ -37,6 +41,7 @@ export default defineComponent({
FluidContainer,
ListItem,
TextField,
IconButton,
},
props: {
@ -47,18 +52,21 @@ export default defineComponent({
},
setup(props) {
const apiClient = useApiClient();
const repoStore = RepoStore();
// TODO: filter server side
const repos = computed(() => Object.values(repoStore.repos).filter((v) => v.owner === props.repoOwner));
const search = ref('');
const orgPermissions = ref<OrgPermissions>({ member: false, admin: false });
const { searchedRepos } = useRepoSearch(repos, search);
onMounted(async () => {
await repoStore.loadRepos();
orgPermissions.value = await apiClient.getOrgPermissions(props.repoOwner);
});
return { searchedRepos, search };
return { searchedRepos, search, orgPermissions };
},
});
</script>

View file

@ -0,0 +1,59 @@
<template>
<FluidContainer>
<div class="flex border-b items-center pb-4 mb-4 dark:border-gray-600">
<IconButton icon="back" @click="goBack" />
<h1 class="text-xl ml-2 text-color">{{ $t('admin.settings.settings') }}</h1>
</div>
<Tabs>
<Tab id="secrets" :title="$t('admin.settings.secrets.secrets')">
<AdminSecretsTab />
</Tab>
</Tabs>
</FluidContainer>
</template>
<script lang="ts">
import { defineComponent, onMounted } from 'vue';
import { useI18n } from 'vue-i18n';
import { useRouter } from 'vue-router';
import AdminSecretsTab from '~/components/admin/settings/AdminSecretsTab.vue';
import IconButton from '~/components/atomic/IconButton.vue';
import FluidContainer from '~/components/layout/FluidContainer.vue';
import Tab from '~/components/tabs/Tab.vue';
import Tabs from '~/components/tabs/Tabs.vue';
import useAuthentication from '~/compositions/useAuthentication';
import useNotifications from '~/compositions/useNotifications';
import { useRouteBackOrDefault } from '~/compositions/useRouteBackOrDefault';
export default defineComponent({
name: 'AdminSettings',
components: {
FluidContainer,
IconButton,
Tabs,
Tab,
AdminSecretsTab,
},
setup() {
const notifications = useNotifications();
const router = useRouter();
const i18n = useI18n();
const { user } = useAuthentication();
onMounted(async () => {
if (!user?.admin) {
notifications.notify({ type: 'error', title: i18n.t('admin.settings.not_allowed') });
await router.replace({ name: 'home' });
}
});
return {
goBack: useRouteBackOrDefault({ name: 'home' }),
};
},
});
</script>

View file

@ -0,0 +1,63 @@
<template>
<FluidContainer>
<div class="flex border-b items-center pb-4 mb-4 dark:border-gray-600">
<IconButton icon="back" @click="goBack" />
<h1 class="text-xl ml-2 text-color">{{ $t('org.settings.settings') }}</h1>
</div>
<Tabs>
<Tab id="secrets" :title="$t('org.settings.secrets.secrets')">
<OrgSecretsTab />
</Tab>
</Tabs>
</FluidContainer>
</template>
<script lang="ts">
import { defineComponent, inject, onMounted, Ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { useRouter } from 'vue-router';
import IconButton from '~/components/atomic/IconButton.vue';
import FluidContainer from '~/components/layout/FluidContainer.vue';
import OrgSecretsTab from '~/components/org/settings/OrgSecretsTab.vue';
import Tab from '~/components/tabs/Tab.vue';
import Tabs from '~/components/tabs/Tabs.vue';
import useNotifications from '~/compositions/useNotifications';
import { useRouteBackOrDefault } from '~/compositions/useRouteBackOrDefault';
import { OrgPermissions } from '~/lib/api/types';
export default defineComponent({
name: 'OrgSettings',
components: {
FluidContainer,
IconButton,
Tabs,
Tab,
OrgSecretsTab,
},
setup() {
const notifications = useNotifications();
const router = useRouter();
const i18n = useI18n();
const orgPermissions = inject<Ref<OrgPermissions>>('org-permissions');
if (!orgPermissions) {
throw new Error('Unexpected: "orgPermissions" should be provided at this place');
}
onMounted(async () => {
if (!orgPermissions.value.admin) {
notifications.notify({ type: 'error', title: i18n.t('org.settings.not_allowed') });
await router.replace({ name: 'home' });
}
});
return {
goBack: useRouteBackOrDefault({ name: 'repos-owner' }),
};
},
});
</script>

View file

@ -0,0 +1,61 @@
<template>
<FluidContainer v-if="org && orgPermissions && $route.meta.orgHeader">
<div class="flex flex-wrap border-b items-center pb-4 mb-4 dark:border-gray-600 justify-center">
<h1 class="text-xl text-color w-full md:w-auto text-center mb-4 md:mb-0">
{{ org.name }}
</h1>
<IconButton v-if="orgPermissions.admin" class="ml-2" :to="{ name: 'repo-settings' }" icon="settings" />
</div>
<router-view />
</FluidContainer>
<router-view v-else-if="org && orgPermissions" />
</template>
<script lang="ts">
import { computed, defineComponent, onMounted, provide, ref, toRef, watch } from 'vue';
import IconButton from '~/components/atomic/IconButton.vue';
import FluidContainer from '~/components/layout/FluidContainer.vue';
import useApiClient from '~/compositions/useApiClient';
import { Org, OrgPermissions } from '~/lib/api/types';
export default defineComponent({
name: 'OrgWrapper',
components: { FluidContainer, IconButton },
props: {
// used by toRef
// eslint-disable-next-line vue/no-unused-properties
repoOwner: {
type: String,
required: true,
},
},
setup(props) {
const repoOwner = toRef(props, 'repoOwner');
const apiClient = useApiClient();
const org = computed<Org>(() => ({ name: repoOwner.value }));
const orgPermissions = ref<OrgPermissions>();
provide('org', org);
provide('org-permissions', orgPermissions);
async function load() {
orgPermissions.value = await apiClient.getOrgPermissions(repoOwner.value);
}
onMounted(() => {
load();
});
watch([repoOwner], () => {
load();
});
return { org, orgPermissions };
},
});
</script>

View file

@ -30,6 +30,10 @@ const (
pathRepoSecret = "%s/api/repos/%s/%s/secrets/%s"
pathRepoRegistries = "%s/api/repos/%s/%s/registry"
pathRepoRegistry = "%s/api/repos/%s/%s/registry/%s"
pathOrgSecrets = "%s/api/orgs/%s/secrets"
pathOrgSecret = "%s/api/orgs/%s/secrets/%s"
pathGlobalSecrets = "%s/api/secrets"
pathGlobalSecret = "%s/api/secrets/%s"
pathUsers = "%s/api/users"
pathUser = "%s/api/users/%s"
pathBuildQueue = "%s/api/builds"
@ -360,6 +364,82 @@ func (c *client) SecretDelete(owner, name, secret string) error {
return c.delete(uri)
}
// OrgSecret returns an organization secret by name.
func (c *client) OrgSecret(owner, secret string) (*Secret, error) {
out := new(Secret)
uri := fmt.Sprintf(pathOrgSecret, c.addr, owner, secret)
err := c.get(uri, out)
return out, err
}
// OrgSecretList returns a list of all organization secrets.
func (c *client) OrgSecretList(owner string) ([]*Secret, error) {
var out []*Secret
uri := fmt.Sprintf(pathOrgSecrets, c.addr, owner)
err := c.get(uri, &out)
return out, err
}
// OrgSecretCreate creates an organization secret.
func (c *client) OrgSecretCreate(owner string, in *Secret) (*Secret, error) {
out := new(Secret)
uri := fmt.Sprintf(pathOrgSecrets, c.addr, owner)
err := c.post(uri, in, out)
return out, err
}
// OrgSecretUpdate updates an organization secret.
func (c *client) OrgSecretUpdate(owner string, in *Secret) (*Secret, error) {
out := new(Secret)
uri := fmt.Sprintf(pathOrgSecret, c.addr, owner, in.Name)
err := c.patch(uri, in, out)
return out, err
}
// OrgSecretDelete deletes an organization secret.
func (c *client) OrgSecretDelete(owner, secret string) error {
uri := fmt.Sprintf(pathOrgSecret, c.addr, owner, secret)
return c.delete(uri)
}
// GlobalOrgSecret returns an global secret by name.
func (c *client) GlobalSecret(secret string) (*Secret, error) {
out := new(Secret)
uri := fmt.Sprintf(pathGlobalSecret, c.addr, secret)
err := c.get(uri, out)
return out, err
}
// GlobalSecretList returns a list of all global secrets.
func (c *client) GlobalSecretList() ([]*Secret, error) {
var out []*Secret
uri := fmt.Sprintf(pathGlobalSecrets, c.addr)
err := c.get(uri, &out)
return out, err
}
// GlobalSecretCreate creates a global secret.
func (c *client) GlobalSecretCreate(in *Secret) (*Secret, error) {
out := new(Secret)
uri := fmt.Sprintf(pathGlobalSecrets, c.addr)
err := c.post(uri, in, out)
return out, err
}
// GlobalSecretUpdate updates a global secret.
func (c *client) GlobalSecretUpdate(in *Secret) (*Secret, error) {
out := new(Secret)
uri := fmt.Sprintf(pathGlobalSecret, c.addr, in.Name)
err := c.patch(uri, in, out)
return out, err
}
// GlobalSecretDelete deletes a global secret.
func (c *client) GlobalSecretDelete(secret string) error {
uri := fmt.Sprintf(pathGlobalSecret, c.addr, secret)
return c.delete(uri)
}
// QueueInfo returns queue info
func (c *client) QueueInfo() (*Info, error) {
out := new(Info)

View file

@ -119,15 +119,45 @@ type Client interface {
// SecretList returns a list of all repository secrets.
SecretList(owner, name string) ([]*Secret, error)
// SecretCreate creates a registry.
// SecretCreate creates a secret.
SecretCreate(owner, name string, secret *Secret) (*Secret, error)
// SecretUpdate updates a registry.
// SecretUpdate updates a secret.
SecretUpdate(owner, name string, secret *Secret) (*Secret, error)
// SecretDelete deletes a secret.
SecretDelete(owner, name, secret string) error
// OrgSecret returns an organization secret by name.
OrgSecret(owner, secret string) (*Secret, error)
// OrgSecretList returns a list of all organization secrets.
OrgSecretList(owner string) ([]*Secret, error)
// OrgSecretCreate creates an organization secret.
OrgSecretCreate(owner string, secret *Secret) (*Secret, error)
// OrgSecretUpdate updates an organization secret.
OrgSecretUpdate(owner string, secret *Secret) (*Secret, error)
// OrgSecretDelete deletes an organization secret.
OrgSecretDelete(owner, secret string) error
// GlobalSecret returns an global secret by name.
GlobalSecret(secret string) (*Secret, error)
// GlobalSecretList returns a list of all global secrets.
GlobalSecretList() ([]*Secret, error)
// GlobalSecretCreate creates a global secret.
GlobalSecretCreate(secret *Secret) (*Secret, error)
// GlobalSecretUpdate updates a global secret.
GlobalSecretUpdate(secret *Secret) (*Secret, error)
// GlobalSecretDelete deletes a global secret.
GlobalSecretDelete(secret string) error
// QueueInfo returns the queue state.
QueueInfo() (*Info, error)