Skip to content

Commit 93abc50

Browse files
authored
Merge pull request #57 from jiaozifs/test/add_branch_integration_test
Test/add branch integration test
2 parents 41590c7 + ffbc5d5 commit 93abc50

File tree

18 files changed

+464
-77
lines changed

18 files changed

+464
-77
lines changed

auth/session_store.go

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
package auth
22

33
import (
4+
"encoding/hex"
5+
46
"github.com/gorilla/sessions"
57
"github.com/jiaozifs/jiaozifs/auth/crypt"
68
"github.com/jiaozifs/jiaozifs/config"
@@ -10,6 +12,10 @@ func NewSessionStore(secretStrore crypt.SecretStore) sessions.Store {
1012
return sessions.NewCookieStore(secretStrore.SharedSecret())
1113
}
1214

13-
func NewSectetStore(authConfig *config.AuthConfig) crypt.SecretStore {
14-
return crypt.NewSecretStore(authConfig.SecretKey)
15+
func NewSectetStore(authConfig *config.AuthConfig) (crypt.SecretStore, error) {
16+
secretKey, err := hex.DecodeString(authConfig.SecretKey)
17+
if err != nil {
18+
return nil, err
19+
}
20+
return crypt.NewSecretStore(secretKey), nil
1521
}

cmd/init.go

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
package cmd
22

33
import (
4-
"fmt"
54
"os"
65

76
"github.com/jiaozifs/jiaozifs/config"
@@ -38,7 +37,7 @@ var initCmd = &cobra.Command{
3837
if err != nil {
3938
return err
4039
}
41-
fmt.Println(cfg.API.Listen)
40+
4241
if cfg.Blockstore.Type == "local" {
4342
_, err = os.Stat(cfg.Blockstore.Local.Path)
4443
if os.IsNotExist(err) {

cmd/root.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ func RootCmd() *cobra.Command {
3030
return rootCmd
3131
}
3232
func init() {
33-
rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.jiaozifs/config.yaml)")
33+
rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "~/.jiaozifs/config.toml", "config file (default is $HOME/.jiaozifs/config.toml)")
3434
rootCmd.PersistentFlags().String("listen", config.DefaultLocalBSPath, "config blockstore path")
3535
_ = viper.BindPFlag("api.listen", rootCmd.PersistentFlags().Lookup("listen"))
3636
_ = viper.BindPFlag("config", rootCmd.PersistentFlags().Lookup("config"))

config/config.go

Lines changed: 40 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@ import (
55
"os"
66
"path"
77

8+
"github.com/mitchellh/go-homedir"
9+
810
ms "github.com/mitchellh/mapstructure"
911
"github.com/spf13/cobra"
1012
"github.com/spf13/viper"
@@ -39,7 +41,7 @@ type DatabaseConfig struct {
3941
}
4042

4143
type AuthConfig struct {
42-
SecretKey []byte `mapstructure:"secretKey"`
44+
SecretKey string `mapstructure:"secretKey"`
4345

4446
UIConfig struct {
4547
RBAC string `mapstructure:"rbac"`
@@ -52,33 +54,47 @@ type AuthConfig struct {
5254
} `mapstructure:"ui_config"`
5355
}
5456

55-
func InitConfig(cfgPath string) error {
56-
// Search config in home directory with name ".jiaozifs" (without extension).
57-
viper.AddConfigPath(cfgPath)
58-
viper.SetConfigType("toml")
59-
viper.SetConfigName("config")
60-
if len(viper.ConfigFileUsed()) == 0 {
61-
data := make(map[string]interface{})
62-
err := ms.Decode(defaultCfg, &data)
63-
if err != nil {
64-
return err
65-
}
66-
for k, v := range data {
67-
viper.SetDefault(k, v)
68-
}
69-
70-
basePath := path.Dir(cfgPath)
71-
err = os.MkdirAll(basePath, 0755)
72-
if err != nil {
73-
return err
74-
}
75-
return viper.WriteConfigAs(cfgPath)
57+
func InitConfig(cfgFile string) error {
58+
var err error
59+
cfgFile, err = homedir.Expand(cfgFile)
60+
if err != nil {
61+
return err
62+
}
63+
64+
_, err = os.Stat(cfgFile)
65+
if err == nil {
66+
return fmt.Errorf("config already exit in %s", cfgFile)
67+
}
68+
if err != nil && !os.IsNotExist(err) {
69+
return err
70+
}
71+
72+
viper.SetConfigFile(cfgFile)
73+
74+
data := make(map[string]interface{})
75+
err = ms.Decode(defaultCfg, &data)
76+
if err != nil {
77+
return err
78+
}
79+
for k, v := range data {
80+
viper.SetDefault(k, v)
81+
}
82+
83+
basePath := path.Dir(cfgFile)
84+
err = os.MkdirAll(basePath, 0755)
85+
if err != nil {
86+
return err
7687
}
77-
return fmt.Errorf("config already exit in %s", cfgPath)
88+
return viper.WriteConfigAs(cfgFile)
7889
}
7990

8091
// LoadConfig reads in config file and ENV variables if set.
8192
func LoadConfig(cfgFile string) (*Config, error) {
93+
var err error
94+
cfgFile, err = homedir.Expand(cfgFile)
95+
if err != nil {
96+
return nil, err
97+
}
8298
if len(cfgFile) > 0 {
8399
// Use config file from the flag.
84100
viper.SetConfigFile(cfgFile)
@@ -96,7 +112,7 @@ func LoadConfig(cfgFile string) (*Config, error) {
96112
viper.AutomaticEnv() // read in environment variables that match
97113

98114
// If a config file is found, read it in.
99-
err := viper.ReadInConfig()
115+
err = viper.ReadInConfig()
100116
if err != nil {
101117
return nil, err
102118
}

config/default.go

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,10 @@
11
package config
22

3-
import "github.com/jiaozifs/jiaozifs/utils"
3+
import (
4+
"encoding/hex"
5+
6+
"github.com/jiaozifs/jiaozifs/utils"
7+
)
48

59
var DefaultLocalBSPath = "~/.jiaozifs/blockstore"
610

@@ -28,7 +32,7 @@ var defaultCfg = Config{
2832
}{Path: DefaultLocalBSPath, ImportEnabled: false, ImportHidden: false, AllowedExternalPrefixes: nil}),
2933
},
3034
Auth: AuthConfig{
31-
SecretKey: []byte("THIS_MUST_BE_CHANGED_IN_PRODUCTION"),
35+
SecretKey: hex.EncodeToString([]byte("THIS_MUST_BE_CHANGED_IN_PRODUCTION")),
3236
UIConfig: struct {
3337
RBAC string `mapstructure:"rbac"`
3438
LoginURL string `mapstructure:"login_url"`

controller/branch_ctl.go

Lines changed: 60 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,16 +3,46 @@ package controller
33
import (
44
"context"
55
"errors"
6+
"fmt"
67
"net/http"
8+
"regexp"
9+
"strings"
710
"time"
811

12+
"github.com/jiaozifs/jiaozifs/utils/hash"
13+
914
"github.com/jiaozifs/jiaozifs/auth"
1015

1116
"github.com/jiaozifs/jiaozifs/api"
1217
"github.com/jiaozifs/jiaozifs/models"
1318
"go.uber.org/fx"
1419
)
1520

21+
var maxBranchNameLength = 20
22+
var branchNameRegex = regexp.MustCompile("^[a-zA-Z0-9_]*$")
23+
24+
func CheckBranchName(name string) error {
25+
for _, blackName := range RepoNameBlackList {
26+
if name == blackName {
27+
return errors.New("repository name is black list")
28+
}
29+
}
30+
31+
if len(name) > maxBranchNameLength {
32+
return fmt.Errorf("branch name is too long")
33+
}
34+
35+
seg := strings.Split(name, "/")
36+
if len(seg) > 2 {
37+
return fmt.Errorf("ref format must be <name> or <name>/<name>")
38+
}
39+
40+
if !branchNameRegex.Match([]byte(seg[0])) || !branchNameRegex.Match([]byte(seg[1])) {
41+
return fmt.Errorf("branch name must be combination of number and letter or combine with '/'")
42+
}
43+
return nil
44+
}
45+
1646
type BranchController struct {
1747
fx.In
1848

@@ -60,6 +90,11 @@ func (bct BranchController) ListBranches(ctx context.Context, w *api.JiaozifsRes
6090
}
6191

6292
func (bct BranchController) CreateBranch(ctx context.Context, w *api.JiaozifsResponse, _ *http.Request, body api.CreateBranchJSONRequestBody, ownerName string, repositoryName string) {
93+
if err := CheckBranchName(body.Name); err != nil {
94+
w.BadRequest(err.Error())
95+
return
96+
}
97+
6398
operator, err := auth.GetOperator(ctx)
6499
if err != nil {
65100
w.Error(err)
@@ -84,18 +119,33 @@ func (bct BranchController) CreateBranch(ctx context.Context, w *api.JiaozifsRes
84119
return
85120
}
86121

87-
// Get source ref
88-
ref, err := bct.Repo.RefRepo().Get(ctx, models.NewGetRefParams().SetName(body.Name).SetRepositoryID(repository.ID))
122+
//check exit
123+
_, err = bct.Repo.RefRepo().Get(ctx, models.NewGetRefParams().SetName(body.Name).SetRepositoryID(repository.ID))
124+
if err == nil {
125+
w.BadRequest(fmt.Sprintf("%s already exit", body.Name))
126+
return
127+
}
89128
if err != nil && !errors.Is(err, models.ErrNotFound) {
90129
w.Error(err)
91130
return
92131
}
132+
//get source ref
133+
sourceRef, err := bct.Repo.RefRepo().Get(ctx, models.NewGetRefParams().SetName(body.Source).SetRepositoryID(repository.ID))
134+
if err != nil && !errors.Is(err, models.ErrNotFound) {
135+
w.Error(err)
136+
return
137+
}
138+
139+
commitHash := hash.EmptyHash
140+
if sourceRef != nil {
141+
commitHash = sourceRef.CommitHash
142+
}
143+
93144
// Create branch
94145
newRef := &models.Ref{
95146
RepositoryID: repository.ID,
96-
CommitHash: ref.CommitHash,
147+
CommitHash: commitHash,
97148
Name: body.Name,
98-
Description: ref.Description,
99149
CreatorID: operator.ID,
100150
CreatedAt: time.Now(),
101151
UpdatedAt: time.Now(),
@@ -142,6 +192,12 @@ func (bct BranchController) DeleteBranch(ctx context.Context, w *api.JiaozifsRes
142192
return
143193
}
144194

195+
_, err = bct.Repo.RefRepo().Get(ctx, models.NewGetRefParams().SetName(params.RefName).SetRepositoryID(repository.ID))
196+
if err != nil {
197+
w.Error(err)
198+
return
199+
}
200+
145201
// Delete branch
146202
err = bct.Repo.RefRepo().Delete(ctx, models.NewDeleteRefParams().SetName(params.RefName).SetRepositoryID(repository.ID))
147203
if err != nil {

controller/user_ctl.go

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package controller
22

33
import (
44
"context"
5+
"encoding/hex"
56
"net/http"
67
"time"
78

@@ -54,7 +55,11 @@ func (userCtl UserController) Login(ctx context.Context, w *api.JiaozifsResponse
5455
// Generate user token
5556
loginTime := time.Now()
5657
expires := loginTime.Add(auth.ExpirationDuration)
57-
secretKey := userCtl.Config.SecretKey
58+
secretKey, err := hex.DecodeString(userCtl.Config.SecretKey)
59+
if err != nil {
60+
w.Error(err)
61+
return
62+
}
5863

5964
tokenString, err := auth.GenerateJWTLogin(secretKey, body.Username, loginTime, expires)
6065
if err != nil {

0 commit comments

Comments
 (0)