diff --git a/CHANGELOG.md b/CHANGELOG.md index 5665b0f..c91edae 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,12 @@ # venus-auth changelog +## v1.10.0-rc2 + +* 简化 authClient 接口,并增加 context [[#126](https://github.com/filecoin-project/venus-auth/pull/126)] +* 重写 url 中的地址参数 [[#127](https://github.com/filecoin-project/venus-auth/pull/127)] +* 增加用户数据隔离的工具 [[#130](https://github.com/filecoin-project/venus-auth/pull/130)] +* 调整 jwtclient.IAtuhClient 接口 [[#137](https://github.com/filecoin-project/venus-auth/pull/137)] + ## v1.10.0-rc1 * github action 增加 dispatch 事件 [[#138](https://github.com/filecoin-project/venus-auth/pull/138)] diff --git a/auth/jwt.go b/auth/jwt.go index 9791ae2..7f69be8 100644 --- a/auth/jwt.go +++ b/auth/jwt.go @@ -321,11 +321,7 @@ func (o *jwtOAuth) RecoverUser(ctx *gin.Context, req *RecoverUserRequest) error } func (o *jwtOAuth) GetUserByMiner(ctx context.Context, req *GetUserByMinerRequest) (*OutputUser, error) { - mAddr, err := address.NewFromString(req.Miner) - if err != nil { - return nil, err - } - user, err := o.store.GetUserByMiner(mAddr) + user, err := o.store.GetUserByMiner(req.Miner) if err != nil { return nil, err } @@ -333,11 +329,7 @@ func (o *jwtOAuth) GetUserByMiner(ctx context.Context, req *GetUserByMinerReques } func (o *jwtOAuth) GetUserBySigner(ctx context.Context, req *GetUserBySignerReq) ([]*OutputUser, error) { - addr, err := address.NewFromString(req.Signer) - if err != nil { - return nil, err - } - users, err := o.store.GetUserBySigner(addr) + users, err := o.store.GetUserBySigner(req.Signer) if err != nil { return nil, err } @@ -371,25 +363,16 @@ func (o jwtOAuth) DelUserRateLimit(ctx context.Context, req *DelUserRateLimitReq } func (o *jwtOAuth) UpsertMiner(ctx context.Context, req *UpsertMinerReq) (bool, error) { - maddr, err := address.NewFromString(req.Miner) - if err != nil || maddr.Empty() { - return false, xerrors.Errorf("invalid miner address:%s, error: %w", req.Miner, err) - } - - if maddr.Protocol() != address.ID { - return false, fmt.Errorf("invalid protocol type: %v", maddr.Protocol()) + mAddr := req.Miner + if mAddr.Protocol() != address.ID { + return false, fmt.Errorf("invalid protocol type: %v", mAddr.Protocol()) } - return o.store.UpsertMiner(maddr, req.User, req.OpenMining) + return o.store.UpsertMiner(mAddr, req.User, req.OpenMining) } func (o *jwtOAuth) HasMiner(ctx context.Context, req *HasMinerRequest) (bool, error) { - mAddr, err := address.NewFromString(req.Miner) - if err != nil { - return false, err - } - - has, err := o.store.HasMiner(mAddr) + has, err := o.store.HasMiner(req.Miner) if err != nil { return false, err } @@ -397,12 +380,7 @@ func (o *jwtOAuth) HasMiner(ctx context.Context, req *HasMinerRequest) (bool, er } func (o *jwtOAuth) MinerExistInUser(ctx context.Context, req *MinerExistInUserRequest) (bool, error) { - mAddr, err := address.NewFromString(req.Miner) - if err != nil { - return false, err - } - - exist, err := o.store.MinerExistInUser(mAddr, req.User) + exist, err := o.store.MinerExistInUser(req.Miner, req.User) if err != nil { return false, err } @@ -417,9 +395,8 @@ func (o *jwtOAuth) ListMiners(ctx context.Context, req *ListMinerReq) (ListMiner outs := make([]*OutputMiner, len(miners)) for idx, m := range miners { - addrStr := m.Miner.Address().String() outs[idx] = &OutputMiner{ - Miner: addrStr, + Miner: m.Miner.Address(), User: m.User, OpenMining: *m.OpenMining, CreatedAt: m.CreatedAt, @@ -430,25 +407,16 @@ func (o *jwtOAuth) ListMiners(ctx context.Context, req *ListMinerReq) (ListMiner } func (o jwtOAuth) DelMiner(ctx context.Context, req *DelMinerReq) (bool, error) { - miner, err := address.NewFromString(req.Miner) - if err != nil { - return false, xerrors.Errorf("invalid miner address:%s, %w", req.Miner, err) - } - return o.store.DelMiner(miner) + return o.store.DelMiner(req.Miner) } func (o *jwtOAuth) RegisterSigners(ctx context.Context, req *RegisterSignersReq) error { for _, signer := range req.Signers { - addr, err := address.NewFromString(signer) - if err != nil || addr.Empty() { - return fmt.Errorf("invalid signer address: %s, error: %w", signer, err) - } - - if !isSignerAddress(addr) { - return fmt.Errorf("invalid protocol type: %v", addr.Protocol()) + if !isSignerAddress(signer) { + return fmt.Errorf("invalid protocol type: %v", signer.Protocol()) } - err = o.store.RegisterSigner(addr, req.User) + err := o.store.RegisterSigner(signer, req.User) if err != nil { return fmt.Errorf("unregister signer:%s, error: %w", signer, err) } @@ -458,11 +426,7 @@ func (o *jwtOAuth) RegisterSigners(ctx context.Context, req *RegisterSignersReq) } func (o *jwtOAuth) SignerExistInUser(ctx context.Context, req *SignerExistInUserReq) (bool, error) { - addr, err := address.NewFromString(req.Signer) - if err != nil { - return false, err - } - + addr := req.Signer if !isSignerAddress(addr) { return false, fmt.Errorf("invalid protocol type: %v", addr.Protocol()) } @@ -482,9 +446,8 @@ func (o *jwtOAuth) ListSigner(ctx context.Context, req *ListSignerReq) (ListSign outs := make([]*OutputSigner, len(signers)) for idx, m := range signers { - addrStr := m.Signer.Address().String() outs[idx] = &OutputSigner{ - Signer: addrStr, + Signer: m.Signer.Address(), User: m.User, CreatedAt: m.CreatedAt, UpdatedAt: m.UpdatedAt, @@ -495,16 +458,11 @@ func (o *jwtOAuth) ListSigner(ctx context.Context, req *ListSignerReq) (ListSign func (o *jwtOAuth) UnregisterSigners(ctx context.Context, req *UnregisterSignersReq) error { for _, signer := range req.Signers { - addr, err := address.NewFromString(signer) - if err != nil || addr.Empty() { - return fmt.Errorf("invalid signer address: %s, error: %w", signer, err) + if !isSignerAddress(signer) { + return fmt.Errorf("invalid protocol type: %v", signer.Protocol()) } - if !isSignerAddress(addr) { - return fmt.Errorf("invalid protocol type: %v", addr.Protocol()) - } - - err = o.store.UnregisterSigner(addr, req.User) + err := o.store.UnregisterSigner(signer, req.User) if err != nil { return fmt.Errorf("unregister signer:%s, error: %w", signer, err) } @@ -514,11 +472,7 @@ func (o *jwtOAuth) UnregisterSigners(ctx context.Context, req *UnregisterSigners } func (o jwtOAuth) HasSigner(ctx context.Context, req *HasSignerReq) (bool, error) { - addr, err := address.NewFromString(req.Signer) - if err != nil { - return false, xerrors.Errorf("invalid signer address:%s, %w", req.Signer, err) - } - + addr := req.Signer if !isSignerAddress(addr) { return false, fmt.Errorf("invalid protocol type: %v", addr.Protocol()) } @@ -527,11 +481,7 @@ func (o jwtOAuth) HasSigner(ctx context.Context, req *HasSignerReq) (bool, error } func (o jwtOAuth) DelSigner(ctx context.Context, req *DelSignerReq) (bool, error) { - addr, err := address.NewFromString(req.Signer) - if err != nil { - return false, xerrors.Errorf("invalid signer address:%s, %w", req.Signer, err) - } - + addr := req.Signer if !isSignerAddress(addr) { return false, fmt.Errorf("invalid protocol type: %v", addr.Protocol()) } diff --git a/auth/jwt_test.go b/auth/jwt_test.go index a47eca4..5f07a75 100644 --- a/auth/jwt_test.go +++ b/auth/jwt_test.go @@ -18,6 +18,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "github.com/filecoin-project/go-address" "github.com/filecoin-project/venus-auth/config" "github.com/filecoin-project/venus-auth/core" "github.com/filecoin-project/venus-auth/storage" @@ -449,9 +450,11 @@ func addUsersAndMiners(t *testing.T, userMiners map[string][]string) { // Add miners openMining := true for _, minerID := range miners { + mAddr, err := address.NewFromString(minerID) + assert.Nil(t, err) ifCreate, err := jwtOAuthInstance.UpsertMiner(ctx, &UpsertMinerReq{ User: userName, - Miner: minerID, + Miner: mAddr, OpenMining: &openMining, }) assert.Nil(t, err) @@ -472,13 +475,17 @@ func testUpsertMiner(t *testing.T, userMiners map[string][]string) { Name: "user_01", State: 1, }) - isCreate, err := jwtOAuthInstance.UpsertMiner(ctx, &UpsertMinerReq{User: "user_01", Miner: "f01034"}) + mAddr, err := address.NewFromString("f01034") + assert.Nil(t, err) + isCreate, err := jwtOAuthInstance.UpsertMiner(ctx, &UpsertMinerReq{User: "user_01", Miner: mAddr}) assert.Nil(t, err) assert.True(t, isCreate) + mAddr, err = address.NewFromString("f1mpvdqt2acgihevibd4greavlsfn3dfph5sckc2a") + assert.Nil(t, err) _, err = jwtOAuthInstance.UpsertMiner(ctx, &UpsertMinerReq{ User: "user_01", - Miner: "f1mpvdqt2acgihevibd4greavlsfn3dfph5sckc2a", + Miner: mAddr, }) assert.NotNil(t, err) require.Contains(t, err.Error(), "invalid protocol type") @@ -497,9 +504,9 @@ func testListMiner(t *testing.T, userMiners map[string][]string) { resp, err := jwtOAuthInstance.ListMiners(ctx, &ListMinerReq{User: validUser1}) assert.Nil(t, err) assert.Equal(t, len(user1Miners), len(resp)) - sort.Slice(resp, func(i, j int) bool { return resp[i].Miner < resp[j].Miner }) + sort.Slice(resp, func(i, j int) bool { return resp[i].Miner.String() < resp[j].Miner.String() }) for i := 0; i < len(user1Miners); i++ { - assert.Equal(t, user1Miners[i], resp[i].Miner) + assert.Equal(t, user1Miners[i], resp[i].Miner.String()) assert.Equal(t, validUser1, resp[i].User) assert.Equal(t, true, resp[i].OpenMining) } @@ -514,21 +521,20 @@ func testHasMiner(t *testing.T, userMiners map[string][]string) { ctx := context.Background() // Has Miner - has, err := jwtOAuthInstance.HasMiner(ctx, &HasMinerRequest{Miner: "t01000"}) + mAddr, err := address.NewFromString("t01000") + assert.Nil(t, err) + has, err := jwtOAuthInstance.HasMiner(ctx, &HasMinerRequest{Miner: mAddr}) assert.Nil(t, err) assert.True(t, has) // Miner Exist In Account - exist, err := jwtOAuthInstance.MinerExistInUser(ctx, &MinerExistInUserRequest{Miner: "t01000", User: "test_user_001"}) + exist, err := jwtOAuthInstance.MinerExistInUser(ctx, &MinerExistInUserRequest{Miner: mAddr, User: "test_user_001"}) assert.Nil(t, err) assert.True(t, exist) - exist, err = jwtOAuthInstance.MinerExistInUser(ctx, &MinerExistInUserRequest{Miner: "t01000", User: "test_user_002"}) + exist, err = jwtOAuthInstance.MinerExistInUser(ctx, &MinerExistInUserRequest{Miner: mAddr, User: "test_user_002"}) assert.Nil(t, err) assert.False(t, exist) - - _, err = jwtOAuthInstance.HasMiner(ctx, &HasMinerRequest{Miner: "invalid address"}) - assert.Error(t, err) } func testGetUserByMiner(t *testing.T, userMiners map[string][]string) { @@ -540,22 +546,20 @@ func testGetUserByMiner(t *testing.T, userMiners map[string][]string) { ctx := context.Background() // Get User By Miner validUser1 := "test_user_001" - user1Miners := []string{"t01000", "t01002", "t01003"} + miner := "t01002" + mAddr, err := address.NewFromString(miner) + assert.Nil(t, err) userInfo, err := jwtOAuthInstance.GetUserByMiner(ctx, &GetUserByMinerRequest{ - Miner: user1Miners[1], + Miner: mAddr, }) assert.Nil(t, err) assert.Equal(t, validUser1, userInfo.Name) - // invalid miner address - _, err = jwtOAuthInstance.GetUserByMiner(ctx, &GetUserByMinerRequest{ - Miner: "invalid address", - }) - assert.Error(t, err) - // miner address not exist + mAddr, err = address.NewFromString("f01989787") + assert.Nil(t, err) _, err = jwtOAuthInstance.GetUserByMiner(ctx, &GetUserByMinerRequest{ - Miner: "f01989787", + Miner: mAddr, }) assert.Error(t, err) } @@ -570,21 +574,25 @@ func testDeleteMiner(t *testing.T, userMiners map[string][]string) { invalidMiner := "t02000" ctx := context.Background() // Delete miner - deleted, err := jwtOAuthInstance.DelMiner(ctx, &DelMinerReq{Miner: user1Miners[0]}) + mAddr, err := address.NewFromString(user1Miners[0]) + assert.Nil(t, err) + deleted, err := jwtOAuthInstance.DelMiner(ctx, &DelMinerReq{Miner: mAddr}) assert.Nil(t, err) assert.True(t, deleted) // Then get this miner - has, err := jwtOAuthInstance.HasMiner(ctx, &HasMinerRequest{Miner: user1Miners[0]}) + has, err := jwtOAuthInstance.HasMiner(ctx, &HasMinerRequest{Miner: mAddr}) assert.Nil(t, err) assert.False(t, has) // Try to get user by this miner _, err = jwtOAuthInstance.GetUserByMiner(ctx, &GetUserByMinerRequest{ - Miner: user1Miners[0], + Miner: mAddr, }) assert.NotNil(t, err) // Delete an invalid miner - deleted, err = jwtOAuthInstance.DelMiner(ctx, &DelMinerReq{Miner: invalidMiner}) + mAddr, err = address.NewFromString(invalidMiner) + assert.Nil(t, err) + deleted, err = jwtOAuthInstance.DelMiner(ctx, &DelMinerReq{Miner: mAddr}) assert.Nil(t, err) assert.False(t, deleted) } @@ -600,9 +608,15 @@ func addUsersAndSigners(t *testing.T, userSigners map[string][]string) { // Create users. _, _ = jwtOAuthInstance.CreateUser(ctx, createUserReq) // Add Signer + signerAddrs := make([]address.Address, 0) + for _, signer := range signers { + signerAddr, err := address.NewFromString(signer) + assert.Nil(t, err) + signerAddrs = append(signerAddrs, signerAddr) + } err := jwtOAuthInstance.RegisterSigners(ctx, &RegisterSignersReq{ User: userName, - Signers: signers, + Signers: signerAddrs, }) assert.Nil(t, err) } @@ -621,19 +635,14 @@ func testRegisterSigner(t *testing.T, userSigners map[string][]string) { Name: "user_01", State: 1, }) - err := jwtOAuthInstance.RegisterSigners(ctx, &RegisterSignersReq{ - User: "user_01", - Signers: []string{"f0128788"}, - }) - assert.NotNil(t, err) - require.Contains(t, err.Error(), "invalid protocol type") - + sAddr, err := address.NewFromString("f0128788") + assert.Nil(t, err) err = jwtOAuthInstance.RegisterSigners(ctx, &RegisterSignersReq{ User: "user_01", - Signers: []string{"128788"}, + Signers: []address.Address{sAddr}, }) assert.NotNil(t, err) - require.Contains(t, err.Error(), "invalid signer address") + require.Contains(t, err.Error(), "invalid protocol type") } func testSignerExistInUser(t *testing.T, userSigners map[string][]string) { @@ -646,9 +655,11 @@ func testSignerExistInUser(t *testing.T, userSigners map[string][]string) { ctx := context.Background() for user, signers := range userSigners { for _, signer := range signers { + sAddr, err := address.NewFromString(signer) + assert.Nil(t, err) bExist, err := jwtOAuthInstance.SignerExistInUser(ctx, &SignerExistInUserReq{ User: user, - Signer: signer, + Signer: sAddr, }) assert.Nil(t, err) assert.True(t, bExist) @@ -669,7 +680,7 @@ func testListSigner(t *testing.T, userSigners map[string][]string) { assert.Nil(t, err) assert.Equal(t, len(user1Signers), len(resp)) for _, signer := range resp { - require.Contains(t, user1Signers, signer.Signer) + require.Contains(t, user1Signers, signer.Signer.String()) } } @@ -680,11 +691,15 @@ func testHasSigner(t *testing.T, userSigners map[string][]string) { addUsersAndSigners(t, userSigners) ctx := context.Background() - has, err := jwtOAuthInstance.HasSigner(ctx, &HasSignerReq{Signer: "t15rynkupqyfx5ebvaishg7duutwb5ooq2qpaikua"}) + sAddr, err := address.NewFromString("t15rynkupqyfx5ebvaishg7duutwb5ooq2qpaikua") + assert.Nil(t, err) + has, err := jwtOAuthInstance.HasSigner(ctx, &HasSignerReq{Signer: sAddr}) assert.Nil(t, err) assert.True(t, has) - has, err = jwtOAuthInstance.HasSigner(ctx, &HasSignerReq{Signer: "f3r72mrymha6wrtb6dzynkzjbnl572az27ddbiq3aovj3d235h2jjgsya4afbf3d37vzfbtsy3dssfnitnhklq"}) + sAddr, err = address.NewFromString("f3r72mrymha6wrtb6dzynkzjbnl572az27ddbiq3aovj3d235h2jjgsya4afbf3d37vzfbtsy3dssfnitnhklq") + assert.Nil(t, err) + has, err = jwtOAuthInstance.HasSigner(ctx, &HasSignerReq{Signer: sAddr}) assert.Nil(t, err) assert.False(t, has) } @@ -696,9 +711,10 @@ func testGetUserBySigner(t *testing.T, userSigners map[string][]string) { addUsersAndSigners(t, userSigners) // Get User By Signer - signer := "t15rynkupqyfx5ebvaishg7duutwb5ooq2qpaikua" + sAddr, err := address.NewFromString("t15rynkupqyfx5ebvaishg7duutwb5ooq2qpaikua") + assert.Nil(t, err) users, err := jwtOAuthInstance.GetUserBySigner(context.Background(), &GetUserBySignerReq{ - Signer: signer, + Signer: sAddr, }) names := make([]string, len(users)) @@ -718,17 +734,18 @@ func testUnregisterSigner(t *testing.T, userSigners map[string][]string) { addUsersAndSigners(t, userSigners) username := "test_user_001" - signer := "t15rynkupqyfx5ebvaishg7duutwb5ooq2qpaikua" + sAddr, err := address.NewFromString("t15rynkupqyfx5ebvaishg7duutwb5ooq2qpaikua") + assert.Nil(t, err) ctx := context.Background() - err := jwtOAuthInstance.UnregisterSigners(ctx, &UnregisterSignersReq{ - Signers: []string{signer}, + err = jwtOAuthInstance.UnregisterSigners(ctx, &UnregisterSignersReq{ + Signers: []address.Address{sAddr}, User: username, }) assert.Nil(t, err) bExist, err := jwtOAuthInstance.SignerExistInUser(ctx, &SignerExistInUserReq{ - Signer: signer, + Signer: sAddr, User: username, }) assert.Nil(t, err) @@ -742,7 +759,8 @@ func testDeleteSigner(t *testing.T, userSigners map[string][]string) { addUsersAndSigners(t, userSigners) // Delete signer - signer := "t15rynkupqyfx5ebvaishg7duutwb5ooq2qpaikua" + signer, err := address.NewFromString("t15rynkupqyfx5ebvaishg7duutwb5ooq2qpaikua") + assert.Nil(t, err) ctx := context.Background() deleted, err := jwtOAuthInstance.DelSigner(ctx, &DelSignerReq{Signer: signer}) assert.Nil(t, err) diff --git a/auth/route.go b/auth/route.go index f6114ca..23d3bb9 100644 --- a/auth/route.go +++ b/auth/route.go @@ -2,7 +2,9 @@ package auth import ( "bytes" + "errors" "net/http" + "net/url" "time" "github.com/filecoin-project/venus-auth/core" @@ -13,6 +15,7 @@ import ( func InitRouter(app OAuthApp) http.Handler { router := gin.New() router.Use(CorsMiddleWare()) + router.Use(RewriteAddressInUrl()) router.GET("/version", func(c *gin.Context) { type version struct { @@ -129,3 +132,23 @@ func CorsMiddleWare() gin.HandlerFunc { c.Next() } } + +func RewriteAddressInUrl() gin.HandlerFunc { + return func(c *gin.Context) { + queryParams := c.Request.URL.Query() + for key, params := range queryParams { + if key == "miner" || key == "signer" { + for index, v := range params { + params[index] = "\"" + v + "\"" + } + } + } + c.Request.RequestURI = c.FullPath() + "?" + queryParams.Encode() + var err error + c.Request.URL, err = url.ParseRequestURI(c.Request.RequestURI) + if err != nil { + _ = c.AbortWithError(http.StatusInternalServerError, errors.New("fail when rewrite request url")) + } + c.Next() + } +} diff --git a/auth/transport.go b/auth/transport.go index d831cac..83814a9 100644 --- a/auth/transport.go +++ b/auth/transport.go @@ -3,6 +3,7 @@ package auth import ( "time" + "github.com/filecoin-project/go-address" "github.com/filecoin-project/venus-auth/core" "github.com/filecoin-project/venus-auth/storage" ) @@ -119,8 +120,7 @@ type RecoverUserRequest struct { } type GetUserByMinerRequest struct { - // todo make miner tobe address - Miner string `form:"miner" binding:"required"` + Miner address.Address `form:"miner" binding:"required"` } func (ls GetUserRateLimitResponse) MatchedLimit(service, api string) *storage.UserRateLimit { @@ -135,18 +135,18 @@ func (ls GetUserRateLimitResponse) MatchedLimit(service, api string) *storage.Us } type UpsertMinerReq struct { - User string `binding:"required"` - Miner string `binding:"required"` - OpenMining *bool `binding:"required"` + User string `binding:"required"` + Miner address.Address `binding:"required"` + OpenMining *bool `binding:"required"` } type HasMinerRequest struct { - Miner string `form:"miner" binding:"required"` + Miner address.Address `form:"miner" binding:"required"` } type MinerExistInUserRequest struct { - Miner string `form:"miner"` - User string `form:"user"` + Miner address.Address `form:"miner"` + User string `form:"user"` } type ListMinerReq struct { @@ -154,30 +154,31 @@ type ListMinerReq struct { } type OutputMiner struct { - Miner, User string + Miner address.Address + User string OpenMining bool CreatedAt, UpdatedAt time.Time } type ListMinerResp []*OutputMiner type DelMinerReq struct { - Miner string `json:"miner"` + Miner address.Address `json:"miner"` } // type definitions for signer type RegisterSignersReq struct { User string - Signers []string + Signers []address.Address } type UnregisterSignersReq struct { User string - Signers []string + Signers []address.Address } type SignerExistInUserReq struct { - Signer string `form:"signer"` - User string `form:"user"` + Signer address.Address `form:"signer"` + User string `form:"user"` } type ListSignerReq struct { @@ -185,19 +186,20 @@ type ListSignerReq struct { } type GetUserBySignerReq struct { - Signer string `form:"signer"` + Signer address.Address `form:"signer"` } type HasSignerReq struct { - Signer string `form:"signer"` + Signer address.Address `form:"signer"` } type DelSignerReq struct { - Signer string `json:"signer"` + Signer address.Address `json:"signer"` } type OutputSigner struct { - Signer, User string + Signer address.Address + User string CreatedAt, UpdatedAt time.Time } type ListSignerResp []*OutputSigner diff --git a/cli/miner.go b/cli/miner.go index 1fe4e27..aa97d2d 100644 --- a/cli/miner.go +++ b/cli/miner.go @@ -6,8 +6,6 @@ import ( "github.com/urfave/cli/v2" "github.com/filecoin-project/go-address" - - "github.com/filecoin-project/venus-auth/auth" ) var minerSubCommand = &cli.Command{ @@ -38,7 +36,7 @@ var minerHasCommand = &cli.Command{ return err } - exist, err := client.HasMiner(&auth.HasMinerRequest{Miner: addr.String()}) + exist, err := client.HasMiner(ctx.Context, addr) if err != nil { return err } diff --git a/cli/signer.go b/cli/signer.go index ad6a71a..128d8c7 100644 --- a/cli/signer.go +++ b/cli/signer.go @@ -37,7 +37,7 @@ var signerHasCommand = &cli.Command{ return err } - exist, err := client.HasSigner(addr.String()) + exist, err := client.HasSigner(ctx.Context, addr) if err != nil { return err } @@ -78,7 +78,7 @@ var signerDelCommand = &cli.Command{ return err } - _, err = client.DelSigner(addr.String()) + _, err = client.DelSigner(ctx.Context, addr.String()) if err != nil { return err } diff --git a/cli/token.go b/cli/token.go index 318993b..76dd905 100644 --- a/cli/token.go +++ b/cli/token.go @@ -56,7 +56,7 @@ var genTokenCmd = &cli.Command{ } extra := ctx.String("extra") - tk, err := client.GenerateToken(name, perm, extra) + tk, err := client.GenerateToken(ctx.Context, name, perm, extra) if err != nil { return err } @@ -84,7 +84,7 @@ var getTokenCmd = &cli.Command{ if err != nil { return err } - tokens, err := client.GetToken(name, token) + tokens, err := client.GetToken(ctx.Context, name, token) if err != nil { return err } @@ -121,7 +121,7 @@ var listTokensCmd = &cli.Command{ } skip := int64(ctx.Uint("skip")) limit := int64(ctx.Uint("limit")) - tks, err := client.Tokens(skip, limit) + tks, err := client.Tokens(ctx.Context, skip, limit) if err != nil { return err } @@ -153,7 +153,7 @@ var removeTokenCmd = &cli.Command{ return err } tk := ctx.Args().First() - err = client.RemoveToken(tk) + err = client.RemoveToken(ctx.Context, tk) if err != nil { return err } @@ -175,7 +175,7 @@ var recoverTokenCmd = &cli.Command{ return err } tk := ctx.Args().First() - err = client.RecoverToken(tk) + err = client.RecoverToken(ctx.Context, tk) if err != nil { return err } diff --git a/cli/user.go b/cli/user.go index 2fbe043..0d61695 100644 --- a/cli/user.go +++ b/cli/user.go @@ -8,6 +8,7 @@ import ( "github.com/urfave/cli/v2" "golang.org/x/xerrors" + "github.com/filecoin-project/go-address" "github.com/filecoin-project/venus-auth/auth" "github.com/filecoin-project/venus-auth/core" "github.com/filecoin-project/venus-auth/storage" @@ -65,7 +66,7 @@ var userAddCmd = &cli.Command{ comment := ctx.String("comment") user.Comment = &comment } - res, err := client.CreateUser(user) + res, err := client.CreateUser(ctx.Context, user) if err != nil { return err } @@ -89,7 +90,7 @@ var userGetCmd = &cli.Command{ return nil } name := ctx.Args().Get(0) - user, err := client.GetUser(&auth.GetUserRequest{Name: name}) + user, err := client.GetUser(ctx.Context, name) if err != nil { return err } @@ -137,7 +138,7 @@ var userUpdateCmd = &cli.Command{ } else { req.State = core.UserStateUndefined } - err = client.UpdateUser(req) + err = client.UpdateUser(ctx.Context, req) if err != nil { return err } @@ -167,7 +168,7 @@ var userActiveCmd = &cli.Command{ State: 1, } - err = client.UpdateUser(req) + err = client.UpdateUser(ctx.Context, req) if err != nil { return err } @@ -210,7 +211,7 @@ var userListCmd = &cli.Command{ req.State = int(core.UserStateUndefined) } - users, err := client.ListUsersWithMiners(req) + users, err := client.ListUsersWithMiners(ctx.Context, req.Skip, req.Limit, core.UserState(req.State)) if err != nil { return err } @@ -219,7 +220,7 @@ var userListCmd = &cli.Command{ fmt.Println("name:", v.Name) fmt.Println("state:", v.State.String()) if len(v.Miners) != 0 { - miners := make([]string, len(v.Miners)) + miners := make([]address.Address, len(v.Miners)) for idx, m := range v.Miners { miners[idx] = m.Miner } @@ -250,7 +251,7 @@ var userDeleteCmd = &cli.Command{ return xerrors.New("expect name") } - has, err := client.HasUser(&auth.HasUserRequest{Name: ctx.Args().First()}) + has, err := client.HasUser(ctx.Context, ctx.Args().First()) if err != nil { return err } @@ -262,7 +263,7 @@ var userDeleteCmd = &cli.Command{ Name: ctx.Args().First(), } - err = client.DeleteUser(req) + err = client.DeleteUser(ctx.Context, req) if err != nil { return err } @@ -289,7 +290,7 @@ var userRecoverCmd = &cli.Command{ Name: ctx.Args().First(), } - err = client.RecoverUser(req) + err = client.RecoverUser(ctx.Context, req) if err != nil { return err } @@ -326,7 +327,7 @@ var rateLimitGet = &cli.Command{ name := ctx.Args().Get(0) var limits []*storage.UserRateLimit - limits, err = client.GetUserRateLimit(name, "") + limits, err = client.GetUserRateLimit(ctx.Context, name, "") if err != nil { return err } @@ -362,7 +363,7 @@ var rateLimitAdd = &cli.Command{ name := ctx.Args().Get(0) - if res, _ := client.GetUserRateLimit(name, ""); len(res) > 0 { + if res, _ := client.GetUserRateLimit(ctx.Context, name, ""); len(res) > 0 { return fmt.Errorf("user rate limit:%s exists", res[0].Id) } @@ -387,7 +388,7 @@ var rateLimitAdd = &cli.Command{ userLimit.Id = ctx.String("id") } - if userLimit.Id, err = client.UpsertUserRateLimit(userLimit); err != nil { + if userLimit.Id, err = client.UpsertUserRateLimit(ctx.Context, userLimit); err != nil { return err } @@ -415,7 +416,7 @@ var rateLimitUpdate = &cli.Command{ name := ctx.Args().Get(0) id := ctx.Args().Get(1) - if res, err := client.GetUserRateLimit(name, id); err != nil { + if res, err := client.GetUserRateLimit(ctx.Context, name, id); err != nil { return err } else if len(res) == 0 { return fmt.Errorf("user rate limit:%s NOT exists", id) @@ -438,7 +439,7 @@ var rateLimitUpdate = &cli.Command{ ReqLimit: storage.ReqLimit{Cap: int64(limitAmount), ResetDur: resetDuration}, } - if userLimit.Id, err = client.UpsertUserRateLimit(userLimit); err != nil { + if userLimit.Id, err = client.UpsertUserRateLimit(ctx.Context, userLimit); err != nil { return err } @@ -468,7 +469,7 @@ var rateLimitDel = &cli.Command{ Id: ctx.Args().Get(1), } - if res, err := client.GetUserRateLimit(delReq.Name, delReq.Id); err != nil { + if res, err := client.GetUserRateLimit(ctx.Context, delReq.Name, delReq.Id); err != nil { return err } else if len(res) == 0 { fmt.Printf("user:%s, rate-limit-id:%s Not exits\n", delReq.Name, delReq.Id) @@ -476,7 +477,7 @@ var rateLimitDel = &cli.Command{ } var id string - if id, err = client.DelUserRateLimit(delReq); err != nil { + if id, err = client.DelUserRateLimit(ctx.Context, delReq); err != nil { return err } fmt.Printf("delete rate limit success, %s\n", id) diff --git a/cli/user_miner.go b/cli/user_miner.go index 24504dc..3df0cde 100644 --- a/cli/user_miner.go +++ b/cli/user_miner.go @@ -10,8 +10,6 @@ import ( "golang.org/x/xerrors" "github.com/filecoin-project/go-address" - - "github.com/filecoin-project/venus-auth/auth" ) var minerSubCmds = &cli.Command{ @@ -49,7 +47,7 @@ var minerAddCmd = &cli.Command{ openMining := ctx.Bool("openMining") var isCreate bool - if isCreate, err = client.UpsertMiner(user, miner, openMining); err != nil { + if isCreate, err = client.UpsertMiner(ctx.Context, user, miner, openMining); err != nil { return err } var opStr string @@ -92,7 +90,7 @@ var minerExistCmd = &cli.Command{ return err } - exist, err := client.MinerExistInUser(user, addr.String()) + exist, err := client.MinerExistInUser(ctx.Context, user, addr) if err != nil { return err } @@ -118,11 +116,11 @@ var minerListCmd = &cli.Command{ } user := args.First() - if _, err := client.GetUser(&auth.GetUserRequest{Name: user}); err != nil { + if _, err := client.GetUser(ctx.Context, user); err != nil { return xerrors.Errorf("list user:%s miner failed: %w", user, err) } - miners, err := client.ListMiners(user) + miners, err := client.ListMiners(ctx.Context, user) if err != nil { return err } @@ -160,7 +158,7 @@ var minerDeleteCmd = &cli.Command{ } miner := args.First() - exists, err := client.DelMiner(miner) + exists, err := client.DelMiner(ctx.Context, miner) if err != nil { return xerrors.Errorf("delete miner:%s failed: %w", miner, err) } diff --git a/cli/user_signer.go b/cli/user_signer.go index b7dcbb6..17293e9 100644 --- a/cli/user_signer.go +++ b/cli/user_signer.go @@ -10,8 +10,6 @@ import ( "golang.org/x/xerrors" "github.com/filecoin-project/go-address" - - "github.com/filecoin-project/venus-auth/auth" ) var signerSubCmds = &cli.Command{ @@ -40,7 +38,11 @@ var signerRegisterCmd = &cli.Command{ } user, addr := ctx.Args().Get(0), ctx.Args().Get(1) - if err = client.RegisterSigners(user, []string{addr}); err != nil { + mAddr, err := address.NewFromString(addr) + if err != nil { + return err + } + if err = client.RegisterSigners(ctx.Context, user, []address.Address{mAddr}); err != nil { return err } @@ -77,7 +79,7 @@ var signerExistCmd = &cli.Command{ return err } - has, err := client.SignerExistInUser(user, addr.String()) + has, err := client.SignerExistInUser(ctx.Context, user, addr) if err != nil { return err } @@ -103,11 +105,11 @@ var signerListCmd = &cli.Command{ } user := args.First() - if _, err := client.GetUser(&auth.GetUserRequest{Name: user}); err != nil { + if _, err := client.GetUser(ctx.Context, user); err != nil { return xerrors.Errorf("list user:%s signer failed: %w", user, err) } - signers, err := client.ListSigners(user) + signers, err := client.ListSigners(ctx.Context, user) if err != nil { return err } @@ -152,7 +154,11 @@ var signerUnregisterCmd = &cli.Command{ signer := args.First() user := ctx.String("user") - err = client.UnregisterSigners(user, []string{signer}) + sAddr, err := address.NewFromString(signer) + if err != nil { + return err + } + err = client.UnregisterSigners(ctx.Context, user, []address.Address{sAddr}) if err != nil { return xerrors.Errorf("unregister signer:%s failed: %w", signer, err) } diff --git a/core/const.go b/core/const.go index a217b71..9c1a824 100644 --- a/core/const.go +++ b/core/const.go @@ -7,7 +7,7 @@ import ( var CurrentCommit string -const BuildVersion = "1.10.0-rc1" +const BuildVersion = "1.10.0-rc2" var Version = BuildVersion + CurrentCommit diff --git a/go.mod b/go.mod index 002d831..79e3b24 100644 --- a/go.mod +++ b/go.mod @@ -13,6 +13,7 @@ require ( github.com/gin-gonic/gin v1.7.7 github.com/go-resty/resty/v2 v2.4.0 github.com/go-sql-driver/mysql v1.6.0 + github.com/golang/mock v1.4.3 github.com/google/uuid v1.2.0 github.com/influxdata/influxdb-client-go/v2 v2.2.2 github.com/ipfs-force-community/metrics v1.0.0 diff --git a/go.sum b/go.sum index 84b51cd..27fd653 100644 --- a/go.sum +++ b/go.sum @@ -175,6 +175,7 @@ github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfb github.com/golang/mock v1.2.0/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= github.com/golang/mock v1.3.1/go.mod h1:sBzyDLLjw3U8JLTeZvSv8jJB+tU5PVekmnlKIyFUx0Y= github.com/golang/mock v1.4.0/go.mod h1:UOMv5ysSaYNkG+OFQykRIcU/QvvxJf3p21QfJ2Bt3cw= +github.com/golang/mock v1.4.3 h1:GV+pQPG/EUUbkh47niozDcADz6go/dUwhVzdUQHIVRw= github.com/golang/mock v1.4.3/go.mod h1:UOMv5ysSaYNkG+OFQykRIcU/QvvxJf3p21QfJ2Bt3cw= github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= diff --git a/integrate_test/miner_test.go b/integrate_test/miner_test.go index ba65ed3..07e2b84 100644 --- a/integrate_test/miner_test.go +++ b/integrate_test/miner_test.go @@ -2,6 +2,7 @@ package integrate import ( + "context" "testing" "github.com/stretchr/testify/assert" @@ -33,21 +34,25 @@ func setupAndAddMiners(t *testing.T) (*jwtclient.AuthClient, *auth.OutputUser, s userName := "Rennbon" miner1 := "t01000" + m1Addr, err := address.NewFromString(miner1) + assert.Nil(t, err) miner2 := "t01002" + m2Addr, err := address.NewFromString(miner2) + assert.Nil(t, err) // Create a user - user, err := client.CreateUser(&auth.CreateUserRequest{Name: userName}) + user, err := client.CreateUser(context.TODO(), &auth.CreateUserRequest{Name: userName}) assert.Nil(t, err) // Add 2 miners - success, err := client.UpsertMiner(userName, miner1, true) + success, err := client.UpsertMiner(context.TODO(), userName, miner1, true) assert.Nil(t, err) assert.True(t, success) - success, err = client.UpsertMiner(userName, miner2, true) + success, err = client.UpsertMiner(context.TODO(), userName, miner2, true) assert.Nil(t, err) assert.True(t, success) - user.Miners = append(user.Miners, &auth.OutputMiner{Miner: miner1, User: userName}, - &auth.OutputMiner{Miner: miner2, User: userName}) + user.Miners = append(user.Miners, &auth.OutputMiner{Miner: m1Addr, User: userName}, + &auth.OutputMiner{Miner: m2Addr, User: userName}) return client, user, tmpDir } @@ -56,11 +61,11 @@ func testUpsertMiners(t *testing.T) { c, user, tmpDir := setupAndAddMiners(t) // `ShouldBind` failed - _, err := c.UpsertMiner("", "f01034", true) + _, err := c.UpsertMiner(context.TODO(), "", "f01034", true) assert.Error(t, err) // invalid address error - _, err = c.UpsertMiner(user.Name, address.Undef.String(), true) + _, err = c.UpsertMiner(context.TODO(), user.Name, address.Undef.String(), true) assert.Error(t, err) shutdown(t, tmpDir) @@ -71,12 +76,12 @@ func testListMinerByUser(t *testing.T) { defer shutdown(t, tmpDir) // List miner by user - listResp, err := client.ListMiners(user.Name) + listResp, err := client.ListMiners(context.Background(), user.Name) assert.Nil(t, err) assert.Equal(t, 2, len(listResp)) // `ShouldBind` failed - _, err = client.ListMiners("") + _, err = client.ListMiners(context.Background(), "") assert.Error(t, err) } @@ -85,21 +90,25 @@ func testHasMiner(t *testing.T) { defer shutdown(t, tmpDir) miner2 := "t01002" + m2Addr, err := address.NewFromString(miner2) + assert.Nil(t, err) miner3 := "t01004" + m3Addr, err := address.NewFromString(miner3) + assert.Nil(t, err) // Has miner - has, err := client.HasMiner(&auth.HasMinerRequest{Miner: miner2}) + has, err := client.HasMiner(context.Background(), m2Addr) assert.Nil(t, err) assert.True(t, has) // Has invalid miner - has, err = client.HasMiner(&auth.HasMinerRequest{Miner: miner3}) + has, err = client.HasMiner(context.Background(), m3Addr) assert.Nil(t, err) assert.False(t, has) // `ShouldBind` failed - has, err = client.HasMiner(&auth.HasMinerRequest{}) - assert.Error(t, err) + has, err = client.HasMiner(context.Background(), address.Undef) + assert.Nil(t, err) assert.False(t, has) } @@ -108,12 +117,14 @@ func testMinerExistInUser(t *testing.T) { defer shutdown(t, tmpDir) notExistMiner := "t010010" + notExistMinerAddr, err := address.NewFromString(notExistMiner) + assert.Nil(t, err) - exist, err := client.MinerExistInUser(user.Name, user.Miners[0].Miner) + exist, err := client.MinerExistInUser(context.Background(), user.Name, user.Miners[0].Miner) assert.Nil(t, err) assert.True(t, exist) - exist, err = client.MinerExistInUser(user.Name, notExistMiner) + exist, err = client.MinerExistInUser(context.Background(), user.Name, notExistMinerAddr) assert.Nil(t, err) assert.False(t, exist) } @@ -123,16 +134,18 @@ func testGetUserByMiner(t *testing.T) { defer shutdown(t, tmpDir) // Get user by miner - getUserInfo, err := client.GetUserByMiner(&auth.GetUserByMinerRequest{Miner: user.Miners[0].Miner}) + getUserInfo, err := client.GetUserByMiner(context.Background(), user.Miners[0].Miner) assert.Nil(t, err) assert.Equal(t, user.Name, getUserInfo.Name) - // `ShouldBind` failed - _, err = client.GetUserByMiner(&auth.GetUserByMinerRequest{}) + // should be not found + _, err = client.GetUserByMiner(context.Background(), address.Undef) assert.Error(t, err) // miner not exists error - _, err = client.GetUserByMiner(&auth.GetUserByMinerRequest{Miner: "f011112222233333"}) + mAddr, err := address.NewFromString("f011112222233333") + assert.Nil(t, err) + _, err = client.GetUserByMiner(context.Background(), mAddr) assert.Error(t, err) } @@ -142,21 +155,21 @@ func testDeleteMiner(t *testing.T) { notExistMiner := "t01004" // Delete a miner - success, err := client.DelMiner(user.Miners[0].Miner) + success, err := client.DelMiner(context.TODO(), user.Miners[0].Miner.String()) assert.Nil(t, err) assert.True(t, success) // Check this miner - has, err := client.HasMiner(&auth.HasMinerRequest{Miner: user.Miners[0].Miner}) + has, err := client.HasMiner(context.Background(), user.Miners[0].Miner) assert.Nil(t, err) assert.False(t, has) // Try to delete not exist miner - success, err = client.DelMiner(notExistMiner) + success, err = client.DelMiner(context.TODO(), notExistMiner) assert.Nil(t, err) assert.False(t, success) // Try to delete a invalid miner - _, err = client.DelMiner("abcdfghijk") + _, err = client.DelMiner(context.TODO(), "abcdfghijk") assert.Error(t, err) } diff --git a/integrate_test/ratelimit_test.go b/integrate_test/ratelimit_test.go index 50685a6..cf090fc 100644 --- a/integrate_test/ratelimit_test.go +++ b/integrate_test/ratelimit_test.go @@ -2,6 +2,7 @@ package integrate import ( + "context" "testing" "github.com/filecoin-project/venus-auth/auth" @@ -28,7 +29,7 @@ func setupAndAddRateLimits(t *testing.T) (*jwtclient.AuthClient, string) { // Create a user userName := "Rennbon" - _, err = client.CreateUser(&auth.CreateUserRequest{Name: userName}) + _, err = client.CreateUser(context.TODO(), &auth.CreateUserRequest{Name: userName}) assert.Nil(t, err) // Insert rate limit @@ -43,7 +44,7 @@ func setupAndAddRateLimits(t *testing.T) (*jwtclient.AuthClient, string) { }, } - upsertResp, err := client.UpsertUserRateLimit(&upsertReq) + upsertResp, err := client.UpsertUserRateLimit(context.TODO(), &upsertReq) assert.Nil(t, err) assert.Equal(t, upsertReq.Id, upsertResp) @@ -54,7 +55,7 @@ func testUpsertUserRateLimit(t *testing.T) { c, tmpDir := setupAndAddRateLimits(t) // `ShouldBind` failed - _, err := c.UpsertUserRateLimit(&auth.UpsertUserRateLimitReq{}) + _, err := c.UpsertUserRateLimit(context.TODO(), &auth.UpsertUserRateLimitReq{}) assert.Error(t, err) shutdown(t, tmpDir) @@ -67,13 +68,13 @@ func testGetRateLimit(t *testing.T) { userName := "Rennbon" reqId := "794fc9a4-2b80-4503-835a-7e8e27360b3d" // Get user rate limit - getResp, err := client.GetUserRateLimit(userName, reqId) + getResp, err := client.GetUserRateLimit(context.Background(), userName, reqId) assert.Nil(t, err) assert.Equal(t, 1, len(getResp)) assert.Equal(t, reqId, getResp[0].Id) // `ShouldBind` failed - _, err = client.GetUserRateLimit("", "") + _, err = client.GetUserRateLimit(context.Background(), "", "") assert.Error(t, err) } @@ -84,16 +85,16 @@ func testDeleteRateLimit(t *testing.T) { userName := "Rennbon" reqId := "794fc9a4-2b80-4503-835a-7e8e27360b3d" // Delete rate limit - deleteResp, err := client.DelUserRateLimit(&auth.DelUserRateLimitReq{Name: userName, Id: reqId}) + deleteResp, err := client.DelUserRateLimit(context.TODO(), &auth.DelUserRateLimitReq{Name: userName, Id: reqId}) assert.Nil(t, err) assert.Equal(t, deleteResp, reqId) // Try to get deleted rate limit - getResp, err := client.GetUserRateLimit(userName, reqId) + getResp, err := client.GetUserRateLimit(context.Background(), userName, reqId) assert.Nil(t, err) assert.Equal(t, 0, len(getResp)) // if there is an error deleting user rate limits - _, err = client.DelUserRateLimit(&auth.DelUserRateLimitReq{}) + _, err = client.DelUserRateLimit(context.TODO(), &auth.DelUserRateLimitReq{}) assert.Error(t, err) } diff --git a/integrate_test/signer_test.go b/integrate_test/signer_test.go index 7ee73bc..dc06889 100644 --- a/integrate_test/signer_test.go +++ b/integrate_test/signer_test.go @@ -1,18 +1,39 @@ package integrate import ( + "context" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "github.com/filecoin-project/go-address" "github.com/filecoin-project/venus-auth/auth" "github.com/filecoin-project/venus-auth/jwtclient" ) -var userSigners = map[string][]string{ - "test_user01": {"t15rynkupqyfx5ebvaishg7duutwb5ooq2qpaikua", "t1sgeoaugenqnzftqp7wvwqebcozkxa5y7i56sy2q"}, - "test_user02": {"t15rynkupqyfx5ebvaishg7duutwb5ooq2qpaikua", "t3wylwd6pclppme4qmbgwled5xpsbgwgqbn2alxa7yahg2gnbfkipsdv6m764xm5coizujmwdmkxeugplmorha"}, +var userSignerAddrs = getUserSignerAddrs() + +func getUserSignerAddrs() map[string][]address.Address { + ret := make(map[string][]address.Address) + + user2signerCase := map[string][]string{ + "test_user01": {"t15rynkupqyfx5ebvaishg7duutwb5ooq2qpaikua", "t1sgeoaugenqnzftqp7wvwqebcozkxa5y7i56sy2q"}, + "test_user02": {"t15rynkupqyfx5ebvaishg7duutwb5ooq2qpaikua", "t3wylwd6pclppme4qmbgwled5xpsbgwgqbn2alxa7yahg2gnbfkipsdv6m764xm5coizujmwdmkxeugplmorha"}, + } + + for user, signers := range user2signerCase { + var sAddrs []address.Address + for _, s := range signers { + addr, err := address.NewFromString(s) + if err != nil { + panic(err) + } + sAddrs = append(sAddrs, addr) + } + ret[user] = sAddrs + } + return ret } func TestSignerAPI(t *testing.T) { @@ -30,12 +51,10 @@ func setupAndAddSigners(t *testing.T) (*jwtclient.AuthClient, string) { client, err := jwtclient.NewAuthClient(server.URL) assert.Nil(t, err) - - for username, signers := range userSigners { - _, err = client.CreateUser(&auth.CreateUserRequest{Name: username}) + for username, signers := range userSignerAddrs { + _, err = client.CreateUser(context.TODO(), &auth.CreateUserRequest{Name: username}) assert.Nil(t, err) - - err = client.RegisterSigners(username, signers) + err = client.RegisterSigners(context.Background(), username, signers) assert.Nil(t, err) } @@ -50,10 +69,9 @@ func testRegisterSigners(t *testing.T) { func testSignerExistInUser(t *testing.T) { client, tmpDir := setupAndAddSigners(t) defer shutdown(t, tmpDir) - - for user, signers := range userSigners { + for user, signers := range userSignerAddrs { for _, signer := range signers { - bExist, err := client.SignerExistInUser(user, signer) + bExist, err := client.SignerExistInUser(context.Background(), user, signer) assert.Nil(t, err) assert.True(t, bExist) } @@ -64,11 +82,11 @@ func testListSignerByUser(t *testing.T) { client, tmpDir := setupAndAddSigners(t) defer shutdown(t, tmpDir) - for user, signers := range userSigners { - ss, err := client.ListSigners(user) + for user, signers := range userSignerAddrs { + ss, err := client.ListSigners(context.Background(), user) assert.Nil(t, err) - ns := make([]string, len(ss)) + ns := make([]address.Address, len(ss)) for idx, s := range ss { ns[idx] = s.Signer } @@ -82,10 +100,9 @@ func testListSignerByUser(t *testing.T) { func testHasSigner(t *testing.T) { client, tmpDir := setupAndAddSigners(t) defer shutdown(t, tmpDir) - - for _, signers := range userSigners { + for _, signers := range userSignerAddrs { for _, signer := range signers { - bExist, err := client.HasSigner(signer) + bExist, err := client.HasSigner(context.Background(), signer) assert.Nil(t, err) assert.True(t, bExist) } @@ -96,8 +113,9 @@ func testGetUserBySigner(t *testing.T) { client, tmpDir := setupAndAddSigners(t) defer shutdown(t, tmpDir) - signer := "t15rynkupqyfx5ebvaishg7duutwb5ooq2qpaikua" - users, err := client.GetUserBySigner(signer) + signer, err := address.NewFromString("t15rynkupqyfx5ebvaishg7duutwb5ooq2qpaikua") + assert.Nil(t, err) + users, err := client.GetUserBySigner(context.Background(), signer) assert.Nil(t, err) names := make([]string, len(users)) @@ -113,12 +131,13 @@ func testUnregisterSigner(t *testing.T) { defer shutdown(t, tmpDir) userName := "test_user01" - signer := "t1sgeoaugenqnzftqp7wvwqebcozkxa5y7i56sy2q" + signer, err := address.NewFromString("t1sgeoaugenqnzftqp7wvwqebcozkxa5y7i56sy2q") + assert.Nil(t, err) - err := client.UnregisterSigners(userName, []string{signer}) + err = client.UnregisterSigners(context.Background(), userName, []address.Address{signer}) assert.Nil(t, err) - bExist, err := client.SignerExistInUser(userName, signer) + bExist, err := client.SignerExistInUser(context.Background(), userName, signer) assert.Nil(t, err) assert.False(t, bExist) } @@ -128,17 +147,19 @@ func testDeleteSigner(t *testing.T) { defer shutdown(t, tmpDir) signer := "t15rynkupqyfx5ebvaishg7duutwb5ooq2qpaikua" + signerAddr, err := address.NewFromString("t15rynkupqyfx5ebvaishg7duutwb5ooq2qpaikua") + assert.Nil(t, err) - bDel, err := client.DelSigner(signer) + bDel, err := client.DelSigner(context.TODO(), signer) assert.Nil(t, err) assert.True(t, bDel) - has, err := client.HasSigner(signer) + has, err := client.HasSigner(context.Background(), signerAddr) assert.Nil(t, err) assert.False(t, has) // delete again - bDel, err = client.DelSigner(signer) + bDel, err = client.DelSigner(context.TODO(), signer) assert.Nil(t, err) assert.False(t, bDel) } diff --git a/integrate_test/token_test.go b/integrate_test/token_test.go index 4df5749..6a52325 100644 --- a/integrate_test/token_test.go +++ b/integrate_test/token_test.go @@ -22,7 +22,7 @@ func setupAndGenerateToken(t *testing.T, name string, perm string) (*jwtclient.A assert.Nil(t, err) // Generate a token - token, err := client.GenerateToken(name, perm, "") + token, err := client.GenerateToken(context.TODO(), name, perm, "") assert.Nil(t, err) return client, tmpDir, token } @@ -55,7 +55,7 @@ func testListToken(t *testing.T) { client, tmpDir, token := setupAndGenerateToken(t, name, perm) defer shutdown(t, tmpDir) - listResp, err := client.Tokens(int64(0), int64(10)) + listResp, err := client.Tokens(context.TODO(), int64(0), int64(10)) assert.Nil(t, err) assert.Equal(t, 1, len(listResp)) assert.Equal(t, token, listResp[0].Token) @@ -69,14 +69,14 @@ func testRemoveAndRecoverToken(t *testing.T) { defer shutdown(t, tmpDir) // Remove and then verify - err := client.RemoveToken(token) + err := client.RemoveToken(context.TODO(), token) assert.Nil(t, err) _, err = client.Verify(context.Background(), token) // Should not succeed this time assert.NotNil(t, err) // Recover this token and then verify - err = client.RecoverToken(token) + err = client.RecoverToken(context.TODO(), token) assert.Nil(t, err) verifyResp, err := client.Verify(context.Background(), token) // Should succeed this time diff --git a/integrate_test/user_test.go b/integrate_test/user_test.go index a26fb27..3c76654 100644 --- a/integrate_test/user_test.go +++ b/integrate_test/user_test.go @@ -2,6 +2,7 @@ package integrate import ( + "context" "testing" "github.com/filecoin-project/venus-auth/auth" @@ -35,7 +36,7 @@ func setupAndAddUser(t *testing.T) (*jwtclient.AuthClient, string, *auth.CreateU userName := "Rennbon" // Create a user - createResp, err := client.CreateUser(&auth.CreateUserRequest{Name: userName}) + createResp, err := client.CreateUser(context.TODO(), &auth.CreateUserRequest{Name: userName}) assert.Nil(t, err) assert.Equal(t, userName, createResp.Name) @@ -46,11 +47,11 @@ func testCreateUser(t *testing.T) { c, tmpDir, userResp := setupAndAddUser(t) // user already exist error, and `BadResponse` - _, err := c.CreateUser(&auth.CreateUserRequest{Name: userResp.Name}) + _, err := c.CreateUser(context.TODO(), &auth.CreateUserRequest{Name: userResp.Name}) assert.Error(t, err) // `ShouldBind` failed - _, err = c.CreateUser(&auth.CreateUserRequest{}) + _, err = c.CreateUser(context.TODO(), &auth.CreateUserRequest{}) assert.Error(t, err) shutdown(t, tmpDir) @@ -61,13 +62,13 @@ func testGetUser(t *testing.T) { shutdown(t, tmpDir) // Get a user - getResp, err := client.GetUser(&auth.GetUserRequest{Name: createResp.Name}) + getResp, err := client.GetUser(context.Background(), createResp.Name) assert.Nil(t, err) assert.Equal(t, createResp.Name, getResp.Name) assert.Equal(t, createResp.Id, getResp.Id) assert.Equal(t, createResp.CreateTime, getResp.CreateTime) - _, err = client.GetUser(&auth.GetUserRequest{Name: "not-exist-user"}) + _, err = client.GetUser(context.Background(), "not-exist-user") assert.Error(t, err) } @@ -77,15 +78,15 @@ func testUpdateUser(t *testing.T) { comment := "updated user comment" updateReq := &auth.UpdateUserRequest{Name: user.Name, Comment: &comment, State: core.UserStateEnabled} - err := c.UpdateUser(updateReq) + err := c.UpdateUser(context.TODO(), updateReq) assert.NoError(t, err) // `ShouldBind` failed - err = c.UpdateUser(&auth.UpdateUserRequest{}) + err = c.UpdateUser(context.TODO(), &auth.UpdateUserRequest{}) assert.Error(t, err) // user not exist error - err = c.UpdateUser(&auth.UpdateUserRequest{Name: "not-exist-user-name"}) + err = c.UpdateUser(context.TODO(), &auth.UpdateUserRequest{Name: "not-exist-user-name"}) assert.Error(t, err) shutdown(t, tmpDir) @@ -96,12 +97,9 @@ func testHasUser(t *testing.T) { shutdown(t, tmpDir) // Has a user - has, err := client.HasUser(&auth.HasUserRequest{Name: createResp.Name}) + has, err := client.HasUser(context.Background(), createResp.Name) assert.Nil(t, err) assert.True(t, has) - // `ShouldBind` failed - _, err = client.HasUser(&auth.HasUserRequest{}) - assert.Error(t, err) } func testListUser(t *testing.T) { @@ -109,7 +107,7 @@ func testListUser(t *testing.T) { shutdown(t, tmpDir) // List users - listResp, err := client.ListUsers(auth.NewListUsersRequest(0, 10, int(core.UserStateUndefined))) + listResp, err := client.ListUsers(context.Background(), 0, 10, core.UserStateUndefined) assert.Nil(t, err) assert.Equal(t, len(listResp), 1) } @@ -121,32 +119,32 @@ func testDeleteUser(t *testing.T) { userName := createResp.Name // Delete user and then try to call get and has - err := client.DeleteUser(&auth.DeleteUserRequest{Name: userName}) + err := client.DeleteUser(context.TODO(), &auth.DeleteUserRequest{Name: userName}) assert.Nil(t, err) // Get should fail - _, err = client.GetUser(&auth.GetUserRequest{Name: userName}) + _, err = client.GetUser(context.Background(), userName) assert.NotNil(t, err) // Has should return false - has, err := client.HasUser(&auth.HasUserRequest{Name: userName}) + has, err := client.HasUser(context.Background(), userName) assert.Nil(t, err) assert.False(t, has) // Recover the user and check - err = client.RecoverUser(&auth.RecoverUserRequest{Name: userName}) + err = client.RecoverUser(context.TODO(), &auth.RecoverUserRequest{Name: userName}) assert.Nil(t, err) - has, err = client.HasUser(&auth.HasUserRequest{Name: userName}) + has, err = client.HasUser(context.Background(), userName) assert.Nil(t, err) assert.True(t, has) // Recover not exist user. - err = client.RecoverUser(&auth.RecoverUserRequest{Name: "not-exist-user"}) + err = client.RecoverUser(context.TODO(), &auth.RecoverUserRequest{Name: "not-exist-user"}) assert.Error(t, err) // `ShouldBind` failed - err = client.DeleteUser(&auth.DeleteUserRequest{}) + err = client.DeleteUser(context.TODO(), &auth.DeleteUserRequest{}) assert.Error(t, err) // Delete a not exists user - err = client.DeleteUser(&auth.DeleteUserRequest{Name: "not-exist-user"}) + err = client.DeleteUser(context.TODO(), &auth.DeleteUserRequest{Name: "not-exist-user"}) assert.Error(t, err) } diff --git a/jwtclient/auth_client.go b/jwtclient/auth_client.go index e7c6c54..e669625 100644 --- a/jwtclient/auth_client.go +++ b/jwtclient/auth_client.go @@ -18,26 +18,30 @@ import ( "github.com/filecoin-project/venus-auth/errcode" ) +//go:generate mockgen -destination=mocks/mock_auth_client.go -package=mocks github.com/filecoin-project/venus-auth/jwtclient IAuthClient + type IAuthClient interface { - VerifyUsers(names []string) error - HasUser(req *auth.HasUserRequest) (bool, error) - GetUser(req *auth.GetUserRequest) (*auth.OutputUser, error) - GetUserByMiner(req *auth.GetUserByMinerRequest) (*auth.OutputUser, error) - GetUserBySigner(signer string) (auth.ListUsersResponse, error) - ListUsers(req *auth.ListUsersRequest) (auth.ListUsersResponse, error) - ListUsersWithMiners(req *auth.ListUsersRequest) (auth.ListUsersResponse, error) - GetUserRateLimit(name, id string) (auth.GetUserRateLimitResponse, error) + Verify(ctx context.Context, token string) (*auth.VerifyResponse, error) + VerifyUsers(ctx context.Context, names []string) error + HasUser(ctx context.Context, name string) (bool, error) + GetUser(ctx context.Context, name string) (*auth.OutputUser, error) + GetUserByMiner(ctx context.Context, miner address.Address) (*auth.OutputUser, error) + GetUserBySigner(ctx context.Context, signer address.Address) (auth.ListUsersResponse, error) + ListUsers(ctx context.Context, skip, limit int64, state core.UserState) (auth.ListUsersResponse, error) + ListUsersWithMiners(ctx context.Context, skip, limit int64, state core.UserState) (auth.ListUsersResponse, error) + GetUserRateLimit(ctx context.Context, name, id string) (auth.GetUserRateLimitResponse, error) - MinerExistInUser(user, miner string) (bool, error) - SignerExistInUser(user, signer string) (bool, error) + MinerExistInUser(ctx context.Context, user string, miner address.Address) (bool, error) + SignerExistInUser(ctx context.Context, user string, signer address.Address) (bool, error) - HasMiner(req *auth.HasMinerRequest) (bool, error) - ListMiners(user string) (auth.ListMinerResp, error) + HasMiner(ctx context.Context, miner address.Address) (bool, error) + ListMiners(ctx context.Context, user string) (auth.ListMinerResp, error) + UpsertMiner(ctx context.Context, user, miner string, openMining bool) (bool, error) - HasSigner(signer string) (bool, error) - ListSigners(user string) (auth.ListSignerResp, error) - RegisterSigners(user string, addrs []string) error - UnregisterSigners(user string, addrs []string) error + HasSigner(ctx context.Context, signer address.Address) (bool, error) + ListSigners(ctx context.Context, user string) (auth.ListSignerResp, error) + RegisterSigners(ctx context.Context, user string, addrs []address.Address) error + UnregisterSigners(ctx context.Context, user string, addrs []address.Address) error } var _ IAuthClient = (*AuthClient)(nil) @@ -79,8 +83,8 @@ func (lc *AuthClient) Verify(ctx context.Context, token string) (*auth.VerifyRes return nil, fmt.Errorf("response code is : %d, msg:%s", resp.StatusCode(), resp.Body()) } -func (lc *AuthClient) GenerateToken(name, perm, extra string) (string, error) { - resp, err := lc.cli.R().SetBody(auth.GenTokenRequest{ +func (lc *AuthClient) GenerateToken(ctx context.Context, name, perm, extra string) (string, error) { + resp, err := lc.cli.R().SetContext(ctx).SetBody(auth.GenTokenRequest{ Name: name, Perm: perm, Extra: extra, @@ -95,8 +99,8 @@ func (lc *AuthClient) GenerateToken(name, perm, extra string) (string, error) { return core.EmptyString, resp.Error().(*errcode.ErrMsg).Err() } -func (lc *AuthClient) GetToken(name, token string) ([]*auth.TokenInfo, error) { - resp, err := lc.cli.R().SetQueryParams(map[string]string{ +func (lc *AuthClient) GetToken(ctx context.Context, name, token string) ([]*auth.TokenInfo, error) { + resp, err := lc.cli.R().SetContext(ctx).SetQueryParams(map[string]string{ "name": name, "token": token, }).SetResult(&[]*auth.TokenInfo{}).SetError(&errcode.ErrMsg{}).Get("/token") @@ -109,8 +113,8 @@ func (lc *AuthClient) GetToken(name, token string) ([]*auth.TokenInfo, error) { return nil, resp.Error().(*errcode.ErrMsg).Err() } -func (lc *AuthClient) Tokens(skip, limit int64) (auth.GetTokensResponse, error) { - resp, err := lc.cli.R().SetQueryParams(map[string]string{ +func (lc *AuthClient) Tokens(ctx context.Context, skip, limit int64) (auth.GetTokensResponse, error) { + resp, err := lc.cli.R().SetContext(ctx).SetQueryParams(map[string]string{ "skip": strconv.FormatInt(skip, 10), "limit": strconv.FormatInt(limit, 10), }).SetResult(&auth.GetTokensResponse{}).SetError(&errcode.ErrMsg{}).Get("/tokens") @@ -123,8 +127,8 @@ func (lc *AuthClient) Tokens(skip, limit int64) (auth.GetTokensResponse, error) return nil, resp.Error().(*errcode.ErrMsg).Err() } -func (lc *AuthClient) RemoveToken(token string) error { - resp, err := lc.cli.R().SetBody(auth.RemoveTokenRequest{ +func (lc *AuthClient) RemoveToken(ctx context.Context, token string) error { + resp, err := lc.cli.R().SetContext(ctx).SetBody(auth.RemoveTokenRequest{ Token: token, }).SetError(&errcode.ErrMsg{}).Delete("/token") if err != nil { @@ -136,8 +140,8 @@ func (lc *AuthClient) RemoveToken(token string) error { return resp.Error().(*errcode.ErrMsg).Err() } -func (lc *AuthClient) RecoverToken(token string) error { - resp, err := lc.cli.R().SetBody(auth.RecoverTokenRequest{ +func (lc *AuthClient) RecoverToken(ctx context.Context, token string) error { + resp, err := lc.cli.R().SetContext(ctx).SetBody(auth.RecoverTokenRequest{ Token: token, }).SetError(&errcode.ErrMsg{}).Post("/recoverToken") if err != nil { @@ -149,8 +153,8 @@ func (lc *AuthClient) RecoverToken(token string) error { return resp.Error().(*errcode.ErrMsg).Err() } -func (lc *AuthClient) CreateUser(req *auth.CreateUserRequest) (*auth.CreateUserResponse, error) { - resp, err := lc.cli.R(). +func (lc *AuthClient) CreateUser(ctx context.Context, req *auth.CreateUserRequest) (*auth.CreateUserResponse, error) { + resp, err := lc.cli.R().SetContext(ctx). SetHeader("Content-Type", "application/json"). SetBody(req). SetResult(&auth.CreateUserResponse{}). @@ -166,8 +170,8 @@ func (lc *AuthClient) CreateUser(req *auth.CreateUserRequest) (*auth.CreateUserR } // UpdateUser -func (lc *AuthClient) UpdateUser(req *auth.UpdateUserRequest) error { - resp, err := lc.cli.R(). +func (lc *AuthClient) UpdateUser(ctx context.Context, req *auth.UpdateUserRequest) error { + resp, err := lc.cli.R().SetContext(ctx). SetHeader("Content-Type", "application/json"). SetBody(req).SetError(&errcode.ErrMsg{}).Post("/user/update") if err != nil { @@ -179,8 +183,9 @@ func (lc *AuthClient) UpdateUser(req *auth.UpdateUserRequest) error { return resp.Error().(*errcode.ErrMsg).Err() } -func (lc *AuthClient) ListUsers(req *auth.ListUsersRequest) (auth.ListUsersResponse, error) { - resp, err := lc.cli.R().SetQueryParams(map[string]string{ +func (lc *AuthClient) ListUsers(ctx context.Context, skip, limit int64, state core.UserState) (auth.ListUsersResponse, error) { + req := auth.NewListUsersRequest(skip, limit, int(state)) + resp, err := lc.cli.R().SetContext(ctx).SetQueryParams(map[string]string{ "skip": strconv.FormatInt(req.Skip, 10), "limit": strconv.FormatInt(req.Limit, 10), "state": strconv.Itoa(req.State), @@ -194,27 +199,22 @@ func (lc *AuthClient) ListUsers(req *auth.ListUsersRequest) (auth.ListUsersRespo return nil, resp.Error().(*errcode.ErrMsg).Err() } -func (lc *AuthClient) ListUsersWithMiners(req *auth.ListUsersRequest) (auth.ListUsersResponse, error) { - resp, err := lc.ListUsers(req) +func (lc *AuthClient) ListUsersWithMiners(ctx context.Context, skip, limit int64, state core.UserState) (auth.ListUsersResponse, error) { + resp, err := lc.ListUsers(ctx, skip, limit, state) if err != nil { return nil, err } for _, user := range resp { - miners, err := lc.ListMiners(user.Name) + miners, err := lc.ListMiners(ctx, user.Name) if err != nil { log.Errorf("list user:%s miners failed:%s", user.Name, err.Error()) continue } user.Miners = make([]*auth.OutputMiner, 0, len(miners)) for _, val := range miners { - addr, err := address.NewFromString(val.Miner) - if err != nil { - log.Errorf("invalid user:%s miner:%s, %s", user.Name, val.Miner, err.Error()) - continue - } user.Miners = append(user.Miners, &auth.OutputMiner{ - Miner: addr.String(), + Miner: val.Miner, User: user.Name, OpenMining: val.OpenMining, CreatedAt: time.Time{}, @@ -225,8 +225,8 @@ func (lc *AuthClient) ListUsersWithMiners(req *auth.ListUsersRequest) (auth.List return resp, nil } -func (lc *AuthClient) VerifyUsers(names []string) error { - resp, err := lc.cli.R().SetBody(&auth.VerifyUsersReq{Names: names}). +func (lc *AuthClient) VerifyUsers(ctx context.Context, names []string) error { + resp, err := lc.cli.R().SetContext(ctx).SetBody(&auth.VerifyUsersReq{Names: names}). SetError(&errcode.ErrMsg{}).Post("/user/verify") if err != nil { return err @@ -237,9 +237,9 @@ func (lc *AuthClient) VerifyUsers(names []string) error { return resp.Error().(*errcode.ErrMsg).Err() } -func (lc *AuthClient) GetUser(req *auth.GetUserRequest) (*auth.OutputUser, error) { - resp, err := lc.cli.R().SetQueryParams(map[string]string{ - "name": req.Name, +func (lc *AuthClient) GetUser(ctx context.Context, name string) (*auth.OutputUser, error) { + resp, err := lc.cli.R().SetContext(ctx).SetQueryParams(map[string]string{ + "name": name, }).SetResult(&auth.OutputUser{}).SetError(&errcode.ErrMsg{}).Get("/user") if err != nil { return nil, err @@ -250,10 +250,10 @@ func (lc *AuthClient) GetUser(req *auth.GetUserRequest) (*auth.OutputUser, error return nil, resp.Error().(*errcode.ErrMsg).Err() } -func (lc *AuthClient) HasUser(req *auth.HasUserRequest) (bool, error) { +func (lc *AuthClient) HasUser(ctx context.Context, name string) (bool, error) { var has bool - resp, err := lc.cli.R().SetQueryParams(map[string]string{ - "name": req.Name, + resp, err := lc.cli.R().SetContext(ctx).SetQueryParams(map[string]string{ + "name": name, }).SetResult(&has).SetError(&errcode.ErrMsg{}).Get("/user/has") if err != nil { return false, err @@ -264,8 +264,8 @@ func (lc *AuthClient) HasUser(req *auth.HasUserRequest) (bool, error) { return false, resp.Error().(*errcode.ErrMsg).Err() } -func (lc *AuthClient) DeleteUser(req *auth.DeleteUserRequest) error { - resp, err := lc.cli.R().SetBody(req).SetError(&errcode.ErrMsg{}).Post("/user/del") +func (lc *AuthClient) DeleteUser(ctx context.Context, req *auth.DeleteUserRequest) error { + resp, err := lc.cli.R().SetContext(ctx).SetBody(req).SetError(&errcode.ErrMsg{}).Post("/user/del") if err != nil { return err } @@ -275,8 +275,8 @@ func (lc *AuthClient) DeleteUser(req *auth.DeleteUserRequest) error { return resp.Error().(*errcode.ErrMsg).Err() } -func (lc *AuthClient) RecoverUser(req *auth.RecoverUserRequest) error { - resp, err := lc.cli.R().SetBody(req).SetError(&errcode.ErrMsg{}).Post("/user/recover") +func (lc *AuthClient) RecoverUser(ctx context.Context, req *auth.RecoverUserRequest) error { + resp, err := lc.cli.R().SetContext(ctx).SetBody(req).SetError(&errcode.ErrMsg{}).Post("/user/recover") if err != nil { return err } @@ -286,7 +286,7 @@ func (lc *AuthClient) RecoverUser(req *auth.RecoverUserRequest) error { return resp.Error().(*errcode.ErrMsg).Err() } -func (lc *AuthClient) GetUserRateLimit(name, id string) (auth.GetUserRateLimitResponse, error) { +func (lc *AuthClient) GetUserRateLimit(ctx context.Context, name, id string) (auth.GetUserRateLimitResponse, error) { param := make(map[string]string) if len(name) != 0 { param["name"] = name @@ -295,7 +295,7 @@ func (lc *AuthClient) GetUserRateLimit(name, id string) (auth.GetUserRateLimitRe param["id"] = id } - resp, err := lc.cli.R().SetQueryParams(param). + resp, err := lc.cli.R().SetContext(ctx).SetQueryParams(param). SetResult(&auth.GetUserRateLimitResponse{}). SetError(&errcode.ErrMsg{}). Get("/user/ratelimit") @@ -308,9 +308,9 @@ func (lc *AuthClient) GetUserRateLimit(name, id string) (auth.GetUserRateLimitRe return nil, resp.Error().(*errcode.ErrMsg).Err() } -func (lc *AuthClient) UpsertUserRateLimit(req *auth.UpsertUserRateLimitReq) (string, error) { +func (lc *AuthClient) UpsertUserRateLimit(ctx context.Context, req *auth.UpsertUserRateLimitReq) (string, error) { var res string - resp, err := lc.cli.R().SetBody(req).SetResult(&res).SetError(&errcode.ErrMsg{}).Post("/user/ratelimit/upsert") + resp, err := lc.cli.R().SetContext(ctx).SetBody(req).SetResult(&res).SetError(&errcode.ErrMsg{}).Post("/user/ratelimit/upsert") if err != nil { return "", err } @@ -320,9 +320,9 @@ func (lc *AuthClient) UpsertUserRateLimit(req *auth.UpsertUserRateLimitReq) (str return "", resp.Error().(*errcode.ErrMsg).Err() } -func (lc *AuthClient) DelUserRateLimit(req *auth.DelUserRateLimitReq) (string, error) { +func (lc *AuthClient) DelUserRateLimit(ctx context.Context, req *auth.DelUserRateLimitReq) (string, error) { var id string - resp, err := lc.cli.R().SetBody(req).SetResult(&id).SetError(&errcode.ErrMsg{}).Post("/user/ratelimit/del") + resp, err := lc.cli.R().SetContext(ctx).SetBody(req).SetResult(&id).SetError(&errcode.ErrMsg{}).Post("/user/ratelimit/del") if err != nil { return "", err } @@ -332,13 +332,17 @@ func (lc *AuthClient) DelUserRateLimit(req *auth.DelUserRateLimitReq) (string, e return "", resp.Error().(*errcode.ErrMsg).Err() } -func (lc *AuthClient) UpsertMiner(user, miner string, openMining bool) (bool, error) { +func (lc *AuthClient) UpsertMiner(ctx context.Context, user, miner string, openMining bool) (bool, error) { if _, err := address.NewFromString(miner); err != nil { return false, xerrors.Errorf("invalid miner address:%s", miner) } var isCreate bool - resp, err := lc.cli.R().SetBody(&auth.UpsertMinerReq{Miner: miner, User: user, OpenMining: &openMining}). + mAddr, err := address.NewFromString(miner) + if err != nil { + return false, err + } + resp, err := lc.cli.R().SetContext(ctx).SetBody(&auth.UpsertMinerReq{Miner: mAddr, User: user, OpenMining: &openMining}). SetResult(&isCreate).SetError(&errcode.ErrMsg{}).Post("/user/miner/add") if err != nil { return false, err @@ -349,10 +353,10 @@ func (lc *AuthClient) UpsertMiner(user, miner string, openMining bool) (bool, er return false, resp.Error().(*errcode.ErrMsg).Err() } -func (lc *AuthClient) HasMiner(req *auth.HasMinerRequest) (bool, error) { +func (lc *AuthClient) HasMiner(ctx context.Context, miner address.Address) (bool, error) { var has bool - resp, err := lc.cli.R().SetQueryParams(map[string]string{ - "miner": req.Miner, + resp, err := lc.cli.R().SetContext(ctx).SetQueryParams(map[string]string{ + "miner": miner.String(), }).SetResult(&has).SetError(&errcode.ErrMsg{}).Get("/miner/has") if err != nil { return false, err @@ -364,10 +368,10 @@ func (lc *AuthClient) HasMiner(req *auth.HasMinerRequest) (bool, error) { return false, resp.Error().(*errcode.ErrMsg).Err() } -func (lc *AuthClient) MinerExistInUser(user, miner string) (bool, error) { +func (lc *AuthClient) MinerExistInUser(ctx context.Context, user string, miner address.Address) (bool, error) { var has bool - resp, err := lc.cli.R().SetQueryParams(map[string]string{ - "miner": miner, + resp, err := lc.cli.R().SetContext(ctx).SetQueryParams(map[string]string{ + "miner": miner.String(), "user": user, }).SetResult(&has).SetError(&errcode.ErrMsg{}).Get("/user/miner/exist") if err != nil { @@ -380,9 +384,9 @@ func (lc *AuthClient) MinerExistInUser(user, miner string) (bool, error) { return false, resp.Error().(*errcode.ErrMsg).Err() } -func (lc *AuthClient) ListMiners(user string) (auth.ListMinerResp, error) { +func (lc *AuthClient) ListMiners(ctx context.Context, user string) (auth.ListMinerResp, error) { var res auth.ListMinerResp - resp, err := lc.cli.R().SetQueryParams(map[string]string{"user": user}). + resp, err := lc.cli.R().SetContext(ctx).SetQueryParams(map[string]string{"user": user}). SetResult(&res).SetError(&errcode.ErrMsg{}).Get("/user/miner/list") if err != nil { return nil, err @@ -393,13 +397,17 @@ func (lc *AuthClient) ListMiners(user string) (auth.ListMinerResp, error) { return nil, resp.Error().(*errcode.ErrMsg).Err() } -func (lc *AuthClient) DelMiner(miner string) (bool, error) { +func (lc *AuthClient) DelMiner(ctx context.Context, miner string) (bool, error) { if _, err := address.NewFromString(miner); err != nil { return false, xerrors.Errorf("invalid miner address:%s", miner) } var has bool - resp, err := lc.cli.R().SetBody(auth.DelMinerReq{Miner: miner}). + mAddr, err := address.NewFromString(miner) + if err != nil { + return false, err + } + resp, err := lc.cli.R().SetContext(ctx).SetBody(auth.DelMinerReq{Miner: mAddr}). SetResult(&has).SetError(&errcode.ErrMsg{}).Post("/user/miner/del") if err != nil { return false, err @@ -410,9 +418,9 @@ func (lc *AuthClient) DelMiner(miner string) (bool, error) { return false, resp.Error().(*errcode.ErrMsg).Err() } -func (lc *AuthClient) GetUserByMiner(req *auth.GetUserByMinerRequest) (*auth.OutputUser, error) { - resp, err := lc.cli.R().SetQueryParams(map[string]string{ - "miner": req.Miner, +func (lc *AuthClient) GetUserByMiner(ctx context.Context, miner address.Address) (*auth.OutputUser, error) { + resp, err := lc.cli.R().SetContext(ctx).SetQueryParams(map[string]string{ + "miner": miner.String(), }).SetResult(&auth.OutputUser{}).SetError(&errcode.ErrMsg{}).Get("/user/miner") if err != nil { return nil, err @@ -423,8 +431,8 @@ func (lc *AuthClient) GetUserByMiner(req *auth.GetUserByMinerRequest) (*auth.Out return nil, resp.Error().(*errcode.ErrMsg).Err() } -func (lc *AuthClient) RegisterSigners(user string, addrs []string) error { - resp, err := lc.cli.R().SetBody(&auth.RegisterSignersReq{Signers: addrs, User: user}). +func (lc *AuthClient) RegisterSigners(ctx context.Context, user string, addrs []address.Address) error { + resp, err := lc.cli.R().SetContext(ctx).SetBody(&auth.RegisterSignersReq{Signers: addrs, User: user}). SetError(&errcode.ErrMsg{}).Post("/user/signer/register") if err != nil { return err @@ -435,10 +443,10 @@ func (lc *AuthClient) RegisterSigners(user string, addrs []string) error { return resp.Error().(*errcode.ErrMsg).Err() } -func (lc *AuthClient) SignerExistInUser(user, signer string) (bool, error) { +func (lc *AuthClient) SignerExistInUser(ctx context.Context, user string, signer address.Address) (bool, error) { var has bool - resp, err := lc.cli.R().SetQueryParams(map[string]string{ - "signer": signer, + resp, err := lc.cli.R().SetContext(ctx).SetQueryParams(map[string]string{ + "signer": signer.String(), "user": user, }).SetResult(&has).SetError(&errcode.ErrMsg{}).Get("/user/signer/exist") if err != nil { @@ -451,8 +459,8 @@ func (lc *AuthClient) SignerExistInUser(user, signer string) (bool, error) { return false, resp.Error().(*errcode.ErrMsg).Err() } -func (lc *AuthClient) ListSigners(user string) (auth.ListSignerResp, error) { - resp, err := lc.cli.R().SetQueryParams(map[string]string{"user": user}). +func (lc *AuthClient) ListSigners(ctx context.Context, user string) (auth.ListSignerResp, error) { + resp, err := lc.cli.R().SetContext(ctx).SetQueryParams(map[string]string{"user": user}). SetResult(&auth.ListSignerResp{}).SetError(&errcode.ErrMsg{}).Get("/user/signer/list") if err != nil { return nil, err @@ -463,8 +471,8 @@ func (lc *AuthClient) ListSigners(user string) (auth.ListSignerResp, error) { return nil, resp.Error().(*errcode.ErrMsg).Err() } -func (lc *AuthClient) UnregisterSigners(user string, addrs []string) error { - resp, err := lc.cli.R().SetBody(&auth.UnregisterSignersReq{Signers: addrs, User: user}). +func (lc *AuthClient) UnregisterSigners(ctx context.Context, user string, addrs []address.Address) error { + resp, err := lc.cli.R().SetContext(ctx).SetBody(&auth.UnregisterSignersReq{Signers: addrs, User: user}). SetError(&errcode.ErrMsg{}).Post("/user/signer/unregister") if err != nil { return err @@ -476,10 +484,10 @@ func (lc *AuthClient) UnregisterSigners(user string, addrs []string) error { return resp.Error().(*errcode.ErrMsg).Err() } -func (lc *AuthClient) HasSigner(signer string) (bool, error) { +func (lc *AuthClient) HasSigner(ctx context.Context, signer address.Address) (bool, error) { var has bool - resp, err := lc.cli.R().SetQueryParams(map[string]string{ - "signer": signer, + resp, err := lc.cli.R().SetContext(ctx).SetQueryParams(map[string]string{ + "signer": signer.String(), }).SetResult(&has).SetError(&errcode.ErrMsg{}).Get("/signer/has") if err != nil { return false, err @@ -491,13 +499,13 @@ func (lc *AuthClient) HasSigner(signer string) (bool, error) { return false, resp.Error().(*errcode.ErrMsg).Err() } -func (lc *AuthClient) DelSigner(signer string) (bool, error) { - if _, err := address.NewFromString(signer); err != nil { - return false, xerrors.Errorf("invalid signer address:%s", signer) - } - +func (lc *AuthClient) DelSigner(ctx context.Context, signer string) (bool, error) { var has bool - resp, err := lc.cli.R().SetBody(auth.DelSignerReq{Signer: signer}). + sAddr, err := address.NewFromString(signer) + if err != nil { + return false, err + } + resp, err := lc.cli.R().SetContext(ctx).SetBody(auth.DelSignerReq{Signer: sAddr}). SetResult(&has).SetError(&errcode.ErrMsg{}).Post("/signer/del") if err != nil { return false, err @@ -508,9 +516,9 @@ func (lc *AuthClient) DelSigner(signer string) (bool, error) { return false, resp.Error().(*errcode.ErrMsg).Err() } -func (lc *AuthClient) GetUserBySigner(signer string) (auth.ListUsersResponse, error) { - resp, err := lc.cli.R().SetQueryParams(map[string]string{ - "signer": signer, +func (lc *AuthClient) GetUserBySigner(ctx context.Context, signer address.Address) (auth.ListUsersResponse, error) { + resp, err := lc.cli.R().SetContext(ctx).SetQueryParams(map[string]string{ + "signer": signer.String(), }).SetResult(&auth.ListUsersResponse{}).SetError(&errcode.ErrMsg{}).Get("/user/signer") if err != nil { return nil, err diff --git a/jwtclient/auth_client_test.go b/jwtclient/auth_client_test.go index f47b97d..ea467ff 100644 --- a/jwtclient/auth_client_test.go +++ b/jwtclient/auth_client_test.go @@ -83,20 +83,21 @@ func TestMain(m *testing.M) { } func TestTokenBusiness(t *testing.T) { + ctx := context.TODO() var originTks []string - tk1, err := cli.GenerateToken("Rennbon1", core.PermAdmin, "custom params") + tk1, err := cli.GenerateToken(context.TODO(), "Rennbon1", core.PermAdmin, "custom params") if err != nil { t.Fatalf("gen token err:%s", err) } originTks = append(originTks, tk1) - tk2, err := cli.GenerateToken("Rennbon2", core.PermRead, "custom params") + tk2, err := cli.GenerateToken(context.TODO(), "Rennbon2", core.PermRead, "custom params") if err != nil { t.Fatalf("gen token err:%s", err) } originTks = append(originTks, tk2) - tks, err := cli.Tokens(0, 0) + tks, err := cli.Tokens(ctx, 0, 0) if err != nil { t.Fatalf("get tokens err:%s", err) } @@ -112,11 +113,11 @@ func TestTokenBusiness(t *testing.T) { assert.Equal(t, find, true) } - err = cli.RemoveToken(tk1) + err = cli.RemoveToken(ctx, tk1) if err != nil { t.Fatalf("remove token err:%s", err) } - tks2, err := cli.Tokens(0, 0) + tks2, err := cli.Tokens(ctx, 0, 0) if err != nil { t.Fatalf("get tokens err:%s", err) } @@ -150,11 +151,11 @@ func TestUserBusiness(t *testing.T) { originUsers := make(map[string]*auth.CreateUserResponse, len(createReqs)) var err error for _, req := range createReqs { - resp, err := cli.CreateUser(req) + resp, err := cli.CreateUser(context.TODO(), req) if err != nil { // user already exists error is ok if strings.Index(err.Error(), "already exists") > 0 { - resp, err := cli.GetUser(&auth.GetUserRequest{Name: req.Name}) + resp, err := cli.GetUser(context.Background(), req.Name) assert.NilError(t, err) originUsers[resp.Id] = resp continue @@ -164,12 +165,7 @@ func TestUserBusiness(t *testing.T) { originUsers[resp.Id] = resp } - users, err := cli.ListUsers(&auth.ListUsersRequest{ - Page: &core.Page{ - Limit: 10, - }, - State: int(core.UserStateUndefined), - }) + users, err := cli.ListUsers(context.Background(), 0, 10, core.UserStateUndefined) if err != nil { t.Fatalf("get tokens err:%s", err) } @@ -189,7 +185,7 @@ func TestUserBusiness(t *testing.T) { newComment := "this is a new comment" for _, res1 := range originUsers { - err = cli.UpdateUser(&auth.UpdateUserRequest{ + err = cli.UpdateUser(context.TODO(), &auth.UpdateUserRequest{ Name: res1.Name, Comment: &newComment, State: 1, @@ -197,55 +193,52 @@ func TestUserBusiness(t *testing.T) { if err != nil { t.Fatal(err) } - _, err = cli.UpsertMiner(res1.Name, "f02345", true) + _, err = cli.UpsertMiner(context.TODO(), res1.Name, "f02345", true) assert.NilError(t, err) break } - user, err := cli.GetUserByMiner(&auth.GetUserByMinerRequest{ - Miner: "f02345", - }) + mAddr1, err := address.NewFromString("f02345") + assert.NilError(t, err) + mAddr2, err := address.NewFromString("f023452") + assert.NilError(t, err) + + user, err := cli.GetUserByMiner(context.Background(), mAddr1) if err != nil { t.Fatalf("get miner err:%s", err) } - has, err := cli.HasMiner(&auth.HasMinerRequest{ - Miner: "f02345", - }) + has, err := cli.HasMiner(context.Background(), mAddr1) if err != nil { fmt.Printf("err: %s\n", err.Error()) } assert.DeepEqual(t, true, has) - has, err = cli.HasMiner(&auth.HasMinerRequest{ - Miner: "f023452", - }) + has, err = cli.HasMiner(context.Background(), mAddr2) if err != nil { t.Fatalf("has miner err:%s", err) } assert.DeepEqual(t, false, has) - exist, err := cli.MinerExistInUser(user.Name, "f02345") + exist, err := cli.MinerExistInUser(context.Background(), user.Name, mAddr1) if err != nil { t.Fatalf("check miner exist in user err:%s", err) } assert.DeepEqual(t, true, exist) - exist, err = cli.MinerExistInUser(user.Name, "f023452") + exist, err = cli.MinerExistInUser(context.Background(), user.Name, mAddr2) if err != nil { t.Fatalf("check miner exist in user err:%s", err) } assert.DeepEqual(t, false, exist) - user, err = cli.GetUser(&auth.GetUserRequest{ - Name: "name2", - }) + user, err = cli.GetUser(context.Background(), "name2") if err != nil { t.Fatalf("get user err:%s", err) } assert.DeepEqual(t, users[1].Name, user.Name) - err = cli.VerifyUsers([]string{"name1", "name2"}) + err = cli.VerifyUsers(context.Background(), []string{"name1", "name2"}) if err != nil { t.Fatalf("verify users err:%s", err) } @@ -256,7 +249,7 @@ func TestClient_Verify(t *testing.T) { t.Skip() } - kps, err := cli.Tokens(0, 10) + kps, err := cli.Tokens(context.TODO(), 0, 10) if err != nil { t.Fatalf("get key-pars failed:%s", err.Error()) } @@ -280,7 +273,7 @@ func TestJWTClient_ListUsers(t *testing.T) { if os.Getenv("CI") == "test" { t.Skip() } - res, err := cli.ListUsers(auth.NewListUsersRequest(0, 20, 1)) + res, err := cli.ListUsers(context.Background(), 0, 20, 1) if err != nil { t.Fatal(err) } diff --git a/jwtclient/inteface.go b/jwtclient/inteface.go index 2fdb719..4ea9a5b 100644 --- a/jwtclient/inteface.go +++ b/jwtclient/inteface.go @@ -16,13 +16,13 @@ type IJwtAuthClient interface { } type jwtAuthClient struct { - *AuthClient + IAuthClient } var _ IJwtAuthClient = &jwtAuthClient{} func (c *jwtAuthClient) Verify(ctx context.Context, token string) ([]auth.Permission, error) { - res, err := c.AuthClient.Verify(ctx, token) + res, err := c.IAuthClient.Verify(ctx, token) if err != nil { return nil, err } @@ -32,8 +32,8 @@ func (c *jwtAuthClient) Verify(ctx context.Context, token string) ([]auth.Permis return perms, nil } -func WarpIJwtAuthClient(cli *AuthClient) IJwtAuthClient { - return &jwtAuthClient{AuthClient: cli} +func WarpIJwtAuthClient(cli IAuthClient) IJwtAuthClient { + return &jwtAuthClient{IAuthClient: cli} } type Logger interface { diff --git a/jwtclient/limiter_warper.go b/jwtclient/limiter_warper.go index 4a88f63..51d6d3c 100644 --- a/jwtclient/limiter_warper.go +++ b/jwtclient/limiter_warper.go @@ -1,29 +1,30 @@ package jwtclient import ( + "context" "errors" "github.com/ipfs-force-community/metrics/ratelimit" ) type limitFinder struct { - *AuthClient + IAuthClient } var _ ratelimit.ILimitFinder = (*limitFinder)(nil) var errNilJwtClient = errors.New("jwt client is nil") -func WarpLimitFinder(client *AuthClient) ratelimit.ILimitFinder { - return &limitFinder{AuthClient: client} +func WarpLimitFinder(client IAuthClient) ratelimit.ILimitFinder { + return &limitFinder{IAuthClient: client} } func (l *limitFinder) GetUserLimit(name, service, api string) (*ratelimit.Limit, error) { - if l.AuthClient == nil { + if l.IAuthClient == nil { return nil, errNilJwtClient } - res, err := l.GetUserRateLimit(name, "") + res, err := l.GetUserRateLimit(context.Background(), name, "") if err != nil { return nil, err } diff --git a/jwtclient/mocks/mock_auth_client.go b/jwtclient/mocks/mock_auth_client.go new file mode 100644 index 0000000..e33a2ef --- /dev/null +++ b/jwtclient/mocks/mock_auth_client.go @@ -0,0 +1,290 @@ +// Code generated by MockGen. DO NOT EDIT. +// Source: github.com/filecoin-project/venus-auth/jwtclient (interfaces: IAuthClient) + +// Package mocks is a generated GoMock package. +package mocks + +import ( + context "context" + reflect "reflect" + + address "github.com/filecoin-project/go-address" + auth "github.com/filecoin-project/venus-auth/auth" + core "github.com/filecoin-project/venus-auth/core" + gomock "github.com/golang/mock/gomock" +) + +// MockIAuthClient is a mock of IAuthClient interface. +type MockIAuthClient struct { + ctrl *gomock.Controller + recorder *MockIAuthClientMockRecorder +} + +// MockIAuthClientMockRecorder is the mock recorder for MockIAuthClient. +type MockIAuthClientMockRecorder struct { + mock *MockIAuthClient +} + +// NewMockIAuthClient creates a new mock instance. +func NewMockIAuthClient(ctrl *gomock.Controller) *MockIAuthClient { + mock := &MockIAuthClient{ctrl: ctrl} + mock.recorder = &MockIAuthClientMockRecorder{mock} + return mock +} + +// EXPECT returns an object that allows the caller to indicate expected use. +func (m *MockIAuthClient) EXPECT() *MockIAuthClientMockRecorder { + return m.recorder +} + +// GetUser mocks base method. +func (m *MockIAuthClient) GetUser(arg0 context.Context, arg1 string) (*auth.OutputUser, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetUser", arg0, arg1) + ret0, _ := ret[0].(*auth.OutputUser) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetUser indicates an expected call of GetUser. +func (mr *MockIAuthClientMockRecorder) GetUser(arg0, arg1 interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetUser", reflect.TypeOf((*MockIAuthClient)(nil).GetUser), arg0, arg1) +} + +// GetUserByMiner mocks base method. +func (m *MockIAuthClient) GetUserByMiner(arg0 context.Context, arg1 address.Address) (*auth.OutputUser, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetUserByMiner", arg0, arg1) + ret0, _ := ret[0].(*auth.OutputUser) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetUserByMiner indicates an expected call of GetUserByMiner. +func (mr *MockIAuthClientMockRecorder) GetUserByMiner(arg0, arg1 interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetUserByMiner", reflect.TypeOf((*MockIAuthClient)(nil).GetUserByMiner), arg0, arg1) +} + +// GetUserBySigner mocks base method. +func (m *MockIAuthClient) GetUserBySigner(arg0 context.Context, arg1 address.Address) ([]*auth.OutputUser, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetUserBySigner", arg0, arg1) + ret0, _ := ret[0].([]*auth.OutputUser) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetUserBySigner indicates an expected call of GetUserBySigner. +func (mr *MockIAuthClientMockRecorder) GetUserBySigner(arg0, arg1 interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetUserBySigner", reflect.TypeOf((*MockIAuthClient)(nil).GetUserBySigner), arg0, arg1) +} + +// GetUserRateLimit mocks base method. +func (m *MockIAuthClient) GetUserRateLimit(arg0 context.Context, arg1, arg2 string) (auth.GetUserRateLimitResponse, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetUserRateLimit", arg0, arg1, arg2) + ret0, _ := ret[0].(auth.GetUserRateLimitResponse) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetUserRateLimit indicates an expected call of GetUserRateLimit. +func (mr *MockIAuthClientMockRecorder) GetUserRateLimit(arg0, arg1, arg2 interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetUserRateLimit", reflect.TypeOf((*MockIAuthClient)(nil).GetUserRateLimit), arg0, arg1, arg2) +} + +// HasMiner mocks base method. +func (m *MockIAuthClient) HasMiner(arg0 context.Context, arg1 address.Address) (bool, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "HasMiner", arg0, arg1) + ret0, _ := ret[0].(bool) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// HasMiner indicates an expected call of HasMiner. +func (mr *MockIAuthClientMockRecorder) HasMiner(arg0, arg1 interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "HasMiner", reflect.TypeOf((*MockIAuthClient)(nil).HasMiner), arg0, arg1) +} + +// HasSigner mocks base method. +func (m *MockIAuthClient) HasSigner(arg0 context.Context, arg1 address.Address) (bool, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "HasSigner", arg0, arg1) + ret0, _ := ret[0].(bool) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// HasSigner indicates an expected call of HasSigner. +func (mr *MockIAuthClientMockRecorder) HasSigner(arg0, arg1 interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "HasSigner", reflect.TypeOf((*MockIAuthClient)(nil).HasSigner), arg0, arg1) +} + +// HasUser mocks base method. +func (m *MockIAuthClient) HasUser(arg0 context.Context, arg1 string) (bool, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "HasUser", arg0, arg1) + ret0, _ := ret[0].(bool) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// HasUser indicates an expected call of HasUser. +func (mr *MockIAuthClientMockRecorder) HasUser(arg0, arg1 interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "HasUser", reflect.TypeOf((*MockIAuthClient)(nil).HasUser), arg0, arg1) +} + +// ListMiners mocks base method. +func (m *MockIAuthClient) ListMiners(arg0 context.Context, arg1 string) (auth.ListMinerResp, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "ListMiners", arg0, arg1) + ret0, _ := ret[0].(auth.ListMinerResp) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// ListMiners indicates an expected call of ListMiners. +func (mr *MockIAuthClientMockRecorder) ListMiners(arg0, arg1 interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListMiners", reflect.TypeOf((*MockIAuthClient)(nil).ListMiners), arg0, arg1) +} + +// ListSigners mocks base method. +func (m *MockIAuthClient) ListSigners(arg0 context.Context, arg1 string) (auth.ListSignerResp, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "ListSigners", arg0, arg1) + ret0, _ := ret[0].(auth.ListSignerResp) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// ListSigners indicates an expected call of ListSigners. +func (mr *MockIAuthClientMockRecorder) ListSigners(arg0, arg1 interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListSigners", reflect.TypeOf((*MockIAuthClient)(nil).ListSigners), arg0, arg1) +} + +// ListUsers mocks base method. +func (m *MockIAuthClient) ListUsers(arg0 context.Context, arg1, arg2 int64, arg3 core.UserState) ([]*auth.OutputUser, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "ListUsers", arg0, arg1, arg2, arg3) + ret0, _ := ret[0].([]*auth.OutputUser) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// ListUsers indicates an expected call of ListUsers. +func (mr *MockIAuthClientMockRecorder) ListUsers(arg0, arg1, arg2, arg3 interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListUsers", reflect.TypeOf((*MockIAuthClient)(nil).ListUsers), arg0, arg1, arg2, arg3) +} + +// ListUsersWithMiners mocks base method. +func (m *MockIAuthClient) ListUsersWithMiners(arg0 context.Context, arg1, arg2 int64, arg3 core.UserState) ([]*auth.OutputUser, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "ListUsersWithMiners", arg0, arg1, arg2, arg3) + ret0, _ := ret[0].([]*auth.OutputUser) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// ListUsersWithMiners indicates an expected call of ListUsersWithMiners. +func (mr *MockIAuthClientMockRecorder) ListUsersWithMiners(arg0, arg1, arg2, arg3 interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListUsersWithMiners", reflect.TypeOf((*MockIAuthClient)(nil).ListUsersWithMiners), arg0, arg1, arg2, arg3) +} + +// MinerExistInUser mocks base method. +func (m *MockIAuthClient) MinerExistInUser(arg0 context.Context, arg1 string, arg2 address.Address) (bool, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "MinerExistInUser", arg0, arg1, arg2) + ret0, _ := ret[0].(bool) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// MinerExistInUser indicates an expected call of MinerExistInUser. +func (mr *MockIAuthClientMockRecorder) MinerExistInUser(arg0, arg1, arg2 interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "MinerExistInUser", reflect.TypeOf((*MockIAuthClient)(nil).MinerExistInUser), arg0, arg1, arg2) +} + +// RegisterSigners mocks base method. +func (m *MockIAuthClient) RegisterSigners(arg0 context.Context, arg1 string, arg2 []address.Address) error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "RegisterSigners", arg0, arg1, arg2) + ret0, _ := ret[0].(error) + return ret0 +} + +// RegisterSigners indicates an expected call of RegisterSigners. +func (mr *MockIAuthClientMockRecorder) RegisterSigners(arg0, arg1, arg2 interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RegisterSigners", reflect.TypeOf((*MockIAuthClient)(nil).RegisterSigners), arg0, arg1, arg2) +} + +// SignerExistInUser mocks base method. +func (m *MockIAuthClient) SignerExistInUser(arg0 context.Context, arg1 string, arg2 address.Address) (bool, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "SignerExistInUser", arg0, arg1, arg2) + ret0, _ := ret[0].(bool) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// SignerExistInUser indicates an expected call of SignerExistInUser. +func (mr *MockIAuthClientMockRecorder) SignerExistInUser(arg0, arg1, arg2 interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SignerExistInUser", reflect.TypeOf((*MockIAuthClient)(nil).SignerExistInUser), arg0, arg1, arg2) +} + +// UnregisterSigners mocks base method. +func (m *MockIAuthClient) UnregisterSigners(arg0 context.Context, arg1 string, arg2 []address.Address) error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "UnregisterSigners", arg0, arg1, arg2) + ret0, _ := ret[0].(error) + return ret0 +} + +// UnregisterSigners indicates an expected call of UnregisterSigners. +func (mr *MockIAuthClientMockRecorder) UnregisterSigners(arg0, arg1, arg2 interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UnregisterSigners", reflect.TypeOf((*MockIAuthClient)(nil).UnregisterSigners), arg0, arg1, arg2) +} + +// Verify mocks base method. +func (m *MockIAuthClient) Verify(arg0 context.Context, arg1 string) (*auth.JWTPayload, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Verify", arg0, arg1) + ret0, _ := ret[0].(*auth.JWTPayload) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// Verify indicates an expected call of Verify. +func (mr *MockIAuthClientMockRecorder) Verify(arg0, arg1 interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Verify", reflect.TypeOf((*MockIAuthClient)(nil).Verify), arg0, arg1) +} + +// VerifyUsers mocks base method. +func (m *MockIAuthClient) VerifyUsers(arg0 context.Context, arg1 []string) error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "VerifyUsers", arg0, arg1) + ret0, _ := ret[0].(error) + return ret0 +} + +// VerifyUsers indicates an expected call of VerifyUsers. +func (mr *MockIAuthClientMockRecorder) VerifyUsers(arg0, arg1 interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "VerifyUsers", reflect.TypeOf((*MockIAuthClient)(nil).VerifyUsers), arg0, arg1) +} diff --git a/jwtclient/utils.go b/jwtclient/utils.go new file mode 100644 index 0000000..df1bc95 --- /dev/null +++ b/jwtclient/utils.go @@ -0,0 +1,71 @@ +package jwtclient + +import ( + "context" + "fmt" + + "github.com/filecoin-project/go-address" + "github.com/filecoin-project/go-jsonrpc/auth" + "github.com/filecoin-project/venus-auth/core" +) + +var ( + // ErrorPermissionDeny is the error message returned when a user does not have permission to perform an action + ErrorPermissionDeny = fmt.Errorf("permission deny") + + // ErrorUserNotFound is the error message returned when a user is not found in context + ErrorUserNotFound = fmt.Errorf("user not found") +) + +// checkPermissionByUser check weather the user has admin permission or is match the username passed in +func CheckPermissionByName(ctx context.Context, name string) error { + if auth.HasPerm(ctx, []auth.Permission{}, core.PermAdmin) { + return nil + } + user, exist := CtxGetName(ctx) + if !exist || user != name { + return ErrorPermissionDeny + } + return nil +} + +func CheckPermissionBySigner(ctx context.Context, client IAuthClient, addrs ...address.Address) error { + if auth.HasPerm(ctx, []auth.Permission{}, core.PermAdmin) { + return nil + } + user, exist := CtxGetName(ctx) + if !exist { + return ErrorUserNotFound + } + + for _, wAddr := range addrs { + ok, err := client.SignerExistInUser(ctx, user, wAddr) + if err != nil { + return fmt.Errorf("check signer exist in user fail %s failed when check permission: %s", wAddr.String(), err) + } + if !ok { + return ErrorPermissionDeny + } + } + return nil +} + +func CheckPermissionByMiner(ctx context.Context, client IAuthClient, addrs ...address.Address) error { + if auth.HasPerm(ctx, []auth.Permission{}, core.PermAdmin) { + return nil + } + user, exist := CtxGetName(ctx) + if !exist { + return ErrorUserNotFound + } + for _, mAddr := range addrs { + ok, err := client.MinerExistInUser(ctx, user, mAddr) + if err != nil { + return fmt.Errorf("check miner exist in user fail %s failed when check permission: %s", mAddr.String(), err) + } + if !ok { + return ErrorPermissionDeny + } + } + return nil +} diff --git a/storage/badger.go b/storage/badger.go index 3c7c199..22fb591 100644 --- a/storage/badger.go +++ b/storage/badger.go @@ -365,9 +365,9 @@ func (s *badgerStore) updateUserRateLimit(name string, limits mapedRatelimit) er } // miner -func (s *badgerStore) getMiner(maddr address.Address) (*Miner, error) { +func (s *badgerStore) getMiner(mAddr address.Address) (*Miner, error) { var miner Miner - if err := s.getUsableObj(minerKey(maddr.String()), &miner); err != nil { + if err := s.getUsableObj(minerKey(mAddr.String()), &miner); err != nil { return nil, err } return &miner, nil @@ -381,26 +381,26 @@ func (s *badgerStore) GetUserByMiner(mAddr address.Address) (*User, error) { return s.GetUser(miner.User) } -func (s *badgerStore) UpsertMiner(maddr address.Address, userName string, openMining *bool) (bool, error) { +func (s *badgerStore) UpsertMiner(mAddr address.Address, userName string, openMining *bool) (bool, error) { miner := &Miner{} now := time.Now() var isCreate bool - userkey, minerkey := userKey(userName), minerKey(maddr.String()) + userkey, minerkey := userKey(userName), minerKey(mAddr.String()) return isCreate, s.db.Update(func(txn *badger.Txn) error { // this 'get(userKey)' purpose to makesure 'user' exist if _, err := txn.Get(userkey); err != nil { if xerrors.Is(err, badger.ErrKeyNotFound) { return xerrors.Errorf("can't bind miner:%s to not exist user:%s", - maddr.String(), userName) + mAddr.String(), userName) } return xerrors.Errorf("bound miner:%s to user:%s failed, %w", - maddr.String(), userName, err) + mAddr.String(), userName, err) } // if miner already exists, update it if item, err := txn.Get(minerkey); err != nil { if xerrors.Is(err, badger.ErrKeyNotFound) { - miner.Miner = storedAddress(maddr) + miner.Miner = storedAddress(mAddr) miner.CreatedAt = now isCreate = true } else { @@ -426,12 +426,12 @@ func (s *badgerStore) UpsertMiner(maddr address.Address, userName string, openMi }) } -func (s *badgerStore) HasMiner(maddr address.Address) (bool, error) { - miner := &Miner{Miner: storedAddress(maddr)} +func (s *badgerStore) HasMiner(mAddr address.Address) (bool, error) { + miner := &Miner{Miner: storedAddress(mAddr)} return s.isExist(miner) } -func (s *badgerStore) MinerExistInUser(maddr address.Address, userName string) (bool, error) { +func (s *badgerStore) MinerExistInUser(mAddr address.Address, userName string) (bool, error) { bExist := false if err := s.walkThroughPrefix([]byte(PrefixMiner), func(item *badger.Item) (isContinueWalk bool, err error) { var miner Miner @@ -440,7 +440,7 @@ func (s *badgerStore) MinerExistInUser(maddr address.Address, userName string) ( return err } - if miner.User == userName && miner.Miner.Address().String() == maddr.String() && !miner.isDeleted() { + if miner.User == userName && miner.Miner.Address().String() == mAddr.String() && !miner.isDeleted() { bExist = true } diff --git a/storage/badger_helper.go b/storage/badger_helper.go index 484bc21..9592988 100644 --- a/storage/badger_helper.go +++ b/storage/badger_helper.go @@ -207,13 +207,13 @@ func (s *badgerStore) MigrateToV1() error { } for _, u := range users { - maddr, err := address.NewFromString(u.Miner) - if err != nil || maddr.Empty() { + mAddr, err := address.NewFromString(u.Miner) + if err != nil || mAddr.Empty() { log.Warnf("won't migrate miner:%s, invalid miner address", u.Miner) continue } b, err := (&Miner{ - Miner: storedAddress(maddr), + Miner: storedAddress(mAddr), User: u.Name, OrmTimestamp: OrmTimestamp{CreatedAt: now, UpdatedAt: now}, }).Bytes() diff --git a/storage/mysql.go b/storage/mysql.go index 18a48d0..668861d 100644 --- a/storage/mysql.go +++ b/storage/mysql.go @@ -301,16 +301,16 @@ func (s *mysqlStore) GetUserByMiner(miner address.Address) (*User, error) { return &user, nil } -func (s *mysqlStore) UpsertMiner(maddr address.Address, userName string, openMining *bool) (bool, error) { +func (s *mysqlStore) UpsertMiner(mAddr address.Address, userName string, openMining *bool) (bool, error) { var isCreate bool - stoMiner := storedAddress(maddr) + stoMiner := storedAddress(mAddr) return isCreate, s.db.Transaction(func(tx *gorm.DB) error { var user User if err := tx.Model(&user).First(&user, "name = ?", userName).Error; err != nil { if xerrors.Is(err, gorm.ErrRecordNotFound) { - return xerrors.Errorf("can't bind miner:%s to not exist user:%s", maddr.String(), userName) + return xerrors.Errorf("can't bind miner:%s to not exist user:%s", mAddr.String(), userName) } - return xerrors.Errorf("bind miner:%s to user:%s failed:%w", maddr.String(), userName, err) + return xerrors.Errorf("bind miner:%s to user:%s failed:%w", mAddr.String(), userName, err) } var count int64 if err := tx.Model(&Miner{}).Where("miner = ?", stoMiner).Count(&count).Error; err != nil { @@ -326,18 +326,18 @@ func (s *mysqlStore) UpsertMiner(maddr address.Address, userName string, openMin }, &sql.TxOptions{Isolation: sql.LevelDefault, ReadOnly: false}) } -func (s mysqlStore) HasMiner(maddr address.Address) (bool, error) { +func (s mysqlStore) HasMiner(mAddr address.Address) (bool, error) { var count int64 - if err := s.db.Table("miners").Where("miner = ? AND deleted_at IS NULL", storedAddress(maddr)).Count(&count).Error; err != nil { + if err := s.db.Table("miners").Where("miner = ? AND deleted_at IS NULL", storedAddress(mAddr)).Count(&count).Error; err != nil { return false, nil } return count > 0, nil } -func (s mysqlStore) MinerExistInUser(maddr address.Address, userName string) (bool, error) { +func (s mysqlStore) MinerExistInUser(mAddr address.Address, userName string) (bool, error) { var count int64 - if err := s.db.Table("miners").Where("miner = ? AND user = ? AND deleted_at IS NULL", storedAddress(maddr), userName).Count(&count).Error; err != nil { + if err := s.db.Table("miners").Where("miner = ? AND user = ? AND deleted_at IS NULL", storedAddress(mAddr), userName).Count(&count).Error; err != nil { return false, nil } @@ -469,15 +469,15 @@ func (s *mysqlStore) MigrateToV1() error { now := time.Now() return s.db.Transaction(func(tx *gorm.DB) error { for _, u := range arr { - maddr, err := address.NewFromString(u.Miner) - if err != nil || maddr.Empty() { + mAddr, err := address.NewFromString(u.Miner) + if err != nil || mAddr.Empty() { log.Warnf("won't migrate miner:%s, invalid miner address", u.Miner) continue } if err := tx.Model(&Miner{}). Clauses(clause.OnConflict{Columns: []clause.Column{{Name: "miner"}}, UpdateAll: true}). Create(&Miner{ - Miner: storedAddress(maddr), + Miner: storedAddress(mAddr), User: u.User, OrmTimestamp: OrmTimestamp{ CreatedAt: now, diff --git a/storage/store.go b/storage/store.go index 830bedc..3bc40f5 100644 --- a/storage/store.go +++ b/storage/store.go @@ -70,13 +70,13 @@ type Store interface { // miner-user(1-1) // first returned bool, 'miner' is created(true) or updated(false) - UpsertMiner(maddr address.Address, userName string, openMining *bool) (bool, error) - HasMiner(maddr address.Address) (bool, error) - MinerExistInUser(maddr address.Address, userName string) (bool, error) - GetUserByMiner(maddr address.Address) (*User, error) + UpsertMiner(mAddr address.Address, userName string, openMining *bool) (bool, error) + HasMiner(mAddr address.Address) (bool, error) + MinerExistInUser(mAddr address.Address, userName string) (bool, error) + GetUserByMiner(mAddr address.Address) (*User, error) ListMiners(user string) ([]*Miner, error) // first returned bool, if miner exists(true) or false - DelMiner(maddr address.Address) (bool, error) + DelMiner(mAddr address.Address) (bool, error) // signer-user(n-n) RegisterSigner(addr address.Address, userName string) error