diff --git a/go.mod b/go.mod index 5e0045200..7439968e3 100644 --- a/go.mod +++ b/go.mod @@ -21,7 +21,7 @@ require ( github.com/sethvargo/go-password v0.1.1 github.com/tsuru/config v0.0.0-20201023175036-375aaee8b560 github.com/tsuru/gnuflag v0.0.0-20151217162021-86b8c1b864aa - github.com/tsuru/go-tsuruclient v0.0.0-20210726185852-a34d558923df + github.com/tsuru/go-tsuruclient v0.0.0-20210813191311-aa50779317a0 github.com/tsuru/tablecli v0.0.0-20190131152944-7ded8a3383c6 github.com/tsuru/tsuru v0.0.0-20210706143918-b89a484dc93f golang.org/x/crypto v0.0.0-20201012173705-84dcc777aaee diff --git a/go.sum b/go.sum index 2173fad79..e50c333fe 100644 --- a/go.sum +++ b/go.sum @@ -438,6 +438,8 @@ github.com/tsuru/go-tsuruclient v0.0.0-20210706193529-586e01e63f2c h1:+DMQy5Egzm github.com/tsuru/go-tsuruclient v0.0.0-20210706193529-586e01e63f2c/go.mod h1:P2AL93lzpzJlgOvu37SOhee4pnLWod1GMJ8YYQq2b7o= github.com/tsuru/go-tsuruclient v0.0.0-20210726185852-a34d558923df h1:EcC/XZqcMWU8yWz2TRsXUsbBJ4PKFZGmrKPT3vqgXiM= github.com/tsuru/go-tsuruclient v0.0.0-20210726185852-a34d558923df/go.mod h1:P2AL93lzpzJlgOvu37SOhee4pnLWod1GMJ8YYQq2b7o= +github.com/tsuru/go-tsuruclient v0.0.0-20210813191311-aa50779317a0 h1:RQ5VuJs7sHVCjGiibwkbml4mlxCmJxowTcldXbg/eQo= +github.com/tsuru/go-tsuruclient v0.0.0-20210813191311-aa50779317a0/go.mod h1:P2AL93lzpzJlgOvu37SOhee4pnLWod1GMJ8YYQq2b7o= github.com/tsuru/monsterqueue v0.0.0-20160909010522-70e946ec66c3 h1:+aJngj5cQjYyx/qSjffQceop25t97hLS0+t8bvx9hg4= github.com/tsuru/monsterqueue v0.0.0-20160909010522-70e946ec66c3/go.mod h1:3KR1vkjfm5b7Lhu5OXuO0NMIyZNG0d0d9xh6ufWYVxg= github.com/tsuru/tablecli v0.0.0-20180215113938-82de88f75181/go.mod h1:ztYpOhW+u1k21FEqp7nZNgpWbr0dUKok5lgGCZi+1AQ= diff --git a/tsuru/client/certificate.go b/tsuru/client/certificate.go index bfcea708e..3c6dacb33 100644 --- a/tsuru/client/certificate.go +++ b/tsuru/client/certificate.go @@ -5,6 +5,7 @@ package client import ( + "context" "crypto/x509" "crypto/x509/pkix" "encoding/json" @@ -18,7 +19,10 @@ import ( "strings" "github.com/tsuru/gnuflag" + tsuruClient "github.com/tsuru/go-tsuruclient/pkg/client" + "github.com/tsuru/go-tsuruclient/pkg/tsuru" "github.com/tsuru/tablecli" + "github.com/tsuru/tsuru-client/tsuru/formatter" "github.com/tsuru/tsuru/cmd" ) @@ -47,8 +51,15 @@ func (c *CertificateSet) Flags() *gnuflag.FlagSet { } return c.fs } - -func (c *CertificateSet) Run(context *cmd.Context, client *cmd.Client) error { +func (c *CertificateSet) CertificateAdd(cert []byte, key []byte) tsuru.CertificateSetData { + certificate := tsuru.CertificateSetData{ + Cname: c.cname, + Certificate: cert, + Key: key, + } + return certificate +} +func (c *CertificateSet) Run(ctx *cmd.Context, client *cmd.Client) error { appName, err := c.AppName() if err != nil { return err @@ -56,33 +67,27 @@ func (c *CertificateSet) Run(context *cmd.Context, client *cmd.Client) error { if c.cname == "" { return errors.New("You must set cname.") } - cert, err := ioutil.ReadFile(context.Args[0]) + cert, err := ioutil.ReadFile(ctx.Args[0]) if err != nil { return err } - key, err := ioutil.ReadFile(context.Args[1]) + key, err := ioutil.ReadFile(ctx.Args[1]) if err != nil { return err } - v := url.Values{} - v.Set("cname", c.cname) - v.Set("certificate", string(cert)) - v.Set("key", string(key)) - u, err := cmd.GetURLVersion("1.2", fmt.Sprintf("/apps/%s/certificate", appName)) + certificate := c.CertificateAdd(cert, key) + apiClient, err := tsuruClient.ClientFromEnvironment(&tsuru.Configuration{ + HTTPClient: client.HTTPClient, + }) if err != nil { return err } - request, err := http.NewRequest(http.MethodPut, u, strings.NewReader(v.Encode())) - if err != nil { - return err - } - request.Header.Set("Content-Type", "application/x-www-form-urlencoded") - response, err := client.Do(request) + response, err := apiClient.AppApi.CertificateSet(context.TODO(), appName, certificate) if err != nil { return err } defer response.Body.Close() - fmt.Fprintln(context.Stdout, "Successfully created the certificated.") + fmt.Fprintln(ctx.Stdout, "Successfully created the certificated.") return nil } @@ -110,7 +115,7 @@ func (c *CertificateUnset) Flags() *gnuflag.FlagSet { return c.fs } -func (c *CertificateUnset) Run(context *cmd.Context, client *cmd.Client) error { +func (c *CertificateUnset) Run(ctx *cmd.Context, client *cmd.Client) error { appName, err := c.AppName() if err != nil { return err @@ -120,21 +125,18 @@ func (c *CertificateUnset) Run(context *cmd.Context, client *cmd.Client) error { } v := url.Values{} v.Set("cname", c.cname) - u, err := cmd.GetURLVersion("1.2", fmt.Sprintf("/apps/%s/certificate?%s", appName, v.Encode())) + apiClient, err := tsuruClient.ClientFromEnvironment(&tsuru.Configuration{ + HTTPClient: client.HTTPClient, + }) if err != nil { return err } - request, err := http.NewRequest(http.MethodDelete, u, nil) - if err != nil { - return err - } - request.Header.Set("Content-Type", "application/x-www-form-urlencoded") - response, err := client.Do(request) + response, err := apiClient.AppApi.CertificatUnset(context.TODO(), appName) if err != nil { return err } defer response.Body.Close() - fmt.Fprintln(context.Stdout, "Certificate removed.") + fmt.Fprintln(ctx.Stdout, "Certificate removed.") return nil } diff --git a/tsuru/client/certificate_test.go b/tsuru/client/certificate_test.go index ab98826a8..0fabb1755 100644 --- a/tsuru/client/certificate_test.go +++ b/tsuru/client/certificate_test.go @@ -10,15 +10,24 @@ import ( "io/ioutil" "net/http" "os" + "strconv" "strings" "time" + "github.com/tsuru/go-tsuruclient/pkg/tsuru" "github.com/tsuru/tsuru-client/tsuru/formatter" "github.com/tsuru/tsuru/cmd" "github.com/tsuru/tsuru/cmd/cmdtest" check "gopkg.in/check.v1" ) +func convert(b []byte) string { + s := make([]string, len(b)) + for i := range b { + s[i] = strconv.Itoa(int(b[i])) + } + return strings.Join(s, ",") +} func (s *S) TestCertificateSetRunSuccessfully(c *check.C) { var stdout, stderr bytes.Buffer context := cmd.Context{ @@ -34,10 +43,23 @@ func (s *S) TestCertificateSetRunSuccessfully(c *check.C) { CondFunc: func(req *http.Request) bool { url := strings.HasSuffix(req.URL.Path, "/apps/secret/certificate") method := req.Method == http.MethodPut - cname := req.FormValue("cname") == "app.io" - certificate := req.FormValue("certificate") == s.mustReadFileString(c, "./testdata/cert/server.crt") - key := req.FormValue("key") == s.mustReadFileString(c, "./testdata/cert/server.key") - return url && method && cname && certificate && key + var cert tsuru.CertificateSetData + err := json.NewDecoder(req.Body).Decode(&cert) + c.Assert(err, check.IsNil) + certifica, err := ioutil.ReadFile("./testdata/cert/server.crt") + if err != nil { + return false + } + key, err := ioutil.ReadFile("./testdata/cert/server.key") + if err != nil { + return false + } + c.Assert(cert, check.DeepEquals, tsuru.CertificateSetData{ + Cname: "app.io", + Certificate: certifica, + Key: key, + }) + return url && method }, } client := cmd.NewClient(&http.Client{Transport: trans}, nil, manager) @@ -82,9 +104,9 @@ func (s *S) TestCertificateUnsetRunSuccessfully(c *check.C) { requestCount++ url := strings.HasSuffix(req.URL.Path, "/apps/secret/certificate") method := req.Method == http.MethodDelete - cname := req.FormValue("cname") == "app.io" + //cname := req.FormValue("cname") == "app.io" - return url && method && cname + return url && method }, } client := cmd.NewClient(&http.Client{Transport: trans}, nil, manager) diff --git a/tsuru/client/permission.go b/tsuru/client/permission.go index 1a716d678..14322e9e2 100644 --- a/tsuru/client/permission.go +++ b/tsuru/client/permission.go @@ -5,6 +5,7 @@ package client import ( + "context" "encoding/json" "errors" "fmt" @@ -15,6 +16,8 @@ import ( "strings" "github.com/tsuru/gnuflag" + tsuruClient "github.com/tsuru/go-tsuruclient/pkg/client" + "github.com/tsuru/go-tsuruclient/pkg/tsuru" "github.com/tsuru/tablecli" "github.com/tsuru/tsuru/cmd" "github.com/tsuru/tsuru/permission" @@ -228,28 +231,31 @@ func (c *RoleAdd) Flags() *gnuflag.FlagSet { return c.fs } -func (c *RoleAdd) Run(context *cmd.Context, client *cmd.Client) error { - roleName := context.Args[0] - contextType := context.Args[1] - description := c.description - params := url.Values{} - params.Set("name", roleName) - params.Set("context", contextType) - params.Set("description", description) - addr, err := cmd.GetURL("/roles") - if err != nil { - return err +func (c *RoleAdd) RoleSet(roleName, contextType, description string) tsuru.RoleAddData { + RoleAdd := tsuru.RoleAddData{ + Name: roleName, + Contexttype: contextType, + Description: description, } - request, err := http.NewRequest("POST", addr, strings.NewReader(params.Encode())) + return RoleAdd +} +func (c *RoleAdd) Run(ctx *cmd.Context, client *cmd.Client) error { + roleName := ctx.Args[0] + contextType := ctx.Args[1] + description := c.description + apiClient, err := tsuruClient.ClientFromEnvironment(&tsuru.Configuration{ + HTTPClient: client.HTTPClient, + }) if err != nil { return err } - request.Header.Add("Content-Type", "application/x-www-form-urlencoded") - _, err = client.Do(request) + roleAdd := c.RoleSet(roleName, contextType, description) + _, err = apiClient.AuthApi.CreateRole(context.TODO(), roleAdd) + if err != nil { return err } - fmt.Fprintf(context.Stdout, "Role successfully created!\n") + fmt.Fprintf(ctx.Stdout, "Role successfully created!\n") return nil } @@ -306,27 +312,31 @@ func (c *RolePermissionAdd) Info() *cmd.Info { MinArgs: 2, } } - -func (c *RolePermissionAdd) Run(context *cmd.Context, client *cmd.Client) error { - roleName := context.Args[0] +func (c *RolePermissionAdd) RolePermAdd(rolename string, permission []string) tsuru.PermissionData { + rolePermAdd := tsuru.PermissionData{ + Name: rolename, + Permission: permission, + } + return rolePermAdd +} +func (c *RolePermissionAdd) Run(ctx *cmd.Context, client *cmd.Client) error { + roleName := ctx.Args[0] params := url.Values{} - for _, p := range context.Args[1:] { + for _, p := range ctx.Args[1:] { params.Add("permission", p) } - addr, err := cmd.GetURL(fmt.Sprintf("/roles/%s/permissions", roleName)) + rolePermAdd := c.RolePermAdd(roleName, params["permission"]) + apiClient, err := tsuruClient.ClientFromEnvironment(&tsuru.Configuration{ + HTTPClient: client.HTTPClient, + }) if err != nil { return err } - request, err := http.NewRequest("POST", addr, strings.NewReader(params.Encode())) + _, err = apiClient.AuthApi.PermissionAdd(context.TODO(), roleName, rolePermAdd) if err != nil { return err } - request.Header.Add("Content-Type", "application/x-www-form-urlencoded") - _, err = client.Do(request) - if err != nil { - return err - } - fmt.Fprintf(context.Stdout, "Permission successfully added!\n") + fmt.Fprintf(ctx.Stdout, "Permission successfully added!\n") return nil } @@ -370,13 +380,22 @@ func (c *RoleAssign) Info() *cmd.Info { MinArgs: 2, } } - -func (c *RoleAssign) Run(context *cmd.Context, client *cmd.Client) error { - roleName := context.Args[0] - roleTarget := context.Args[1] +func (c *RoleAssign) RoleAssignData(roleName, contextValue, roleTarget, suffix, version string) tsuru.RoleAssignData { + roleAdd := tsuru.RoleAssignData{ + Name: roleName, + Contextvalue: contextValue, + Roletarget: roleTarget, + Sufix: suffix, + Version: version, + } + return roleAdd +} +func (c *RoleAssign) Run(ctx *cmd.Context, client *cmd.Client) error { + roleName := ctx.Args[0] + roleTarget := ctx.Args[1] var contextValue string - if len(context.Args) > 2 { - contextValue = context.Args[2] + if len(ctx.Args) > 2 { + contextValue = ctx.Args[2] } params := url.Values{} var suffix, version string @@ -394,20 +413,19 @@ func (c *RoleAssign) Run(context *cmd.Context, client *cmd.Client) error { params.Set("token_id", roleTarget) } params.Set("context", contextValue) - addr, err := cmd.GetURLVersion(version, fmt.Sprintf("/roles/%s/%s", roleName, suffix)) - if err != nil { - return err - } - request, err := http.NewRequest("POST", addr, strings.NewReader(params.Encode())) + roleAssginAdd := c.RoleAssignData(roleName, contextValue, roleTarget, suffix, version) + apiClient, err := tsuruClient.ClientFromEnvironment(&tsuru.Configuration{ + HTTPClient: client.HTTPClient, + }) if err != nil { return err } - request.Header.Add("Content-Type", "application/x-www-form-urlencoded") - _, err = client.Do(request) + _, err = apiClient.AuthApi.RoleAssign(context.TODO(), roleName, roleAssginAdd) + if err != nil { return err } - fmt.Fprintf(context.Stdout, "Role successfully assigned!\n") + fmt.Fprintf(ctx.Stdout, "Role successfully assigned!\n") return nil } @@ -422,12 +440,12 @@ func (c *RoleDissociate) Info() *cmd.Info { } } -func (c *RoleDissociate) Run(context *cmd.Context, client *cmd.Client) error { - roleName := context.Args[0] - emailOrToken := context.Args[1] +func (c *RoleDissociate) Run(ctx *cmd.Context, client *cmd.Client) error { + roleName := ctx.Args[0] + emailOrToken := ctx.Args[1] var contextValue string - if len(context.Args) > 2 { - contextValue = context.Args[2] + if len(ctx.Args) > 2 { + contextValue = ctx.Args[2] } params := url.Values{} var suffix, version string @@ -439,20 +457,25 @@ func (c *RoleDissociate) Run(context *cmd.Context, client *cmd.Client) error { version = "1.6" } params.Set("context", contextValue) - addr, err := cmd.GetURLVersion(version, fmt.Sprintf("/roles/%s/%s?%s", roleName, suffix, params.Encode())) + resp, err := cmd.GetURLVersion(version, fmt.Sprintf("/roles/%s/%s?%s", roleName, suffix, params.Encode())) if err != nil { return err } - request, err := http.NewRequest(http.MethodDelete, addr, nil) + apiClient, err := tsuruClient.ClientFromEnvironment(&tsuru.Configuration{ + HTTPClient: client.HTTPClient, + }) if err != nil { return err } - request.Header.Add("Content-Type", "application/x-www-form-urlencoded") - _, err = client.Do(request) + if strings.Contains(emailOrToken, "@") { + _, err = apiClient.AuthApi.DissociateRole(context.TODO(), roleName, resp) + } else { + _, err = apiClient.AuthApi.DissociateRoleFromToken(context.TODO(), roleName, emailOrToken, contextValue) + } if err != nil { return err } - fmt.Fprintf(context.Stdout, "Role successfully dissociated!\n") + fmt.Fprintf(ctx.Stdout, "Role successfully dissociated!\n") return nil } @@ -521,32 +544,39 @@ func (c *RoleDefaultAdd) Info() *cmd.Info { info.Usage = fmt.Sprintf("%s %s", info.Usage, strings.Join(usage, " ")) return info } - -func (c *RoleDefaultAdd) Run(context *cmd.Context, client *cmd.Client) error { +func (c *RoleDefaultAdd) RoleDefAdd(roleMap map[string][]string) tsuru.RoleDefaultData { + userData := tsuru.RoleDefaultData{ + Rolesmap: roleMap, + } + return userData +} +func (c *RoleDefaultAdd) Run(ctx *cmd.Context, client *cmd.Client) error { params := url.Values{} for name, values := range c.roles { for _, val := range []string(*values) { params.Add(name, val) } } - encodedParams := params.Encode() - if encodedParams == "" { - return fmt.Errorf("You must choose which event to add default roles.") - } - addr, err := cmd.GetURL("/role/default") - if err != nil { - return err + rolname := []string{} + roleMap := make(map[string][]string) + for k := range params { + rolname = append(rolname, k) + for _, n := range params[k] { + roleMap[k] = append(roleMap[k], n) + } } - request, err := http.NewRequest("POST", addr, strings.NewReader(encodedParams)) + rolDef := c.RoleDefAdd(roleMap) + apiClient, err := tsuruClient.ClientFromEnvironment(&tsuru.Configuration{ + HTTPClient: client.HTTPClient, + }) if err != nil { return err } - request.Header.Set("Content-Type", "application/x-www-form-urlencoded") - _, err = client.Do(request) + _, err = apiClient.AuthApi.DefaultRoleAdd(context.TODO(), rolDef) if err != nil { return err } - fmt.Fprintf(context.Stdout, "Roles successfully added as default!\n") + fmt.Fprintf(ctx.Stdout, "Roles successfully added as default!\n") return nil } @@ -696,30 +726,36 @@ func (c *RoleUpdate) Flags() *gnuflag.FlagSet { } return c.fs } - -func (c *RoleUpdate) Run(context *cmd.Context, client *cmd.Client) error { +func (c *RoleUpdate) RoleUpdate(name string) tsuru.RoleUpdateData { + userData := tsuru.RoleUpdateData{ + Name: name, + ContextType: c.contextType, + Description: c.description, + NewName: c.newName, + } + return userData +} +func (c *RoleUpdate) Run(ctx *cmd.Context, client *cmd.Client) error { if (c.newName == "") && (c.description == "") && (c.contextType == "") { return errors.New("Neither the description, context or new name were set. You must define at least one.") } params := url.Values{} - params.Set("name", context.Args[0]) + params.Set("name", ctx.Args[0]) params.Set("newName", c.newName) params.Set("description", c.description) params.Set("contextType", c.contextType) - url, err := cmd.GetURLVersion("1.4", "/roles") - if err != nil { - return err - } - request, err := http.NewRequest("PUT", url, strings.NewReader(params.Encode())) + apiClient, err := tsuruClient.ClientFromEnvironment(&tsuru.Configuration{ + HTTPClient: client.HTTPClient, + }) if err != nil { return err } - request.Header.Set("Content-Type", "application/x-www-form-urlencoded") - _, err = client.Do(request) + roleUpdate := c.RoleUpdate(ctx.Args[0]) + _, err = apiClient.AuthApi.UpdateRole(context.TODO(), roleUpdate) if err != nil { - context.Stderr.Write([]byte("Failed to update role\n")) + ctx.Stderr.Write([]byte("Failed to update role\n")) return err } - context.Stdout.Write([]byte("Role successfully updated\n")) + ctx.Stdout.Write([]byte("Role successfully updated\n")) return nil } diff --git a/tsuru/client/permission_test.go b/tsuru/client/permission_test.go index d93dab520..520fca66c 100644 --- a/tsuru/client/permission_test.go +++ b/tsuru/client/permission_test.go @@ -6,11 +6,13 @@ package client import ( "bytes" + "encoding/json" "net/http" "reflect" "sort" "strings" + "github.com/tsuru/go-tsuruclient/pkg/tsuru" "github.com/tsuru/tsuru/cmd" "github.com/tsuru/tsuru/cmd/cmdtest" "gopkg.in/check.v1" @@ -69,8 +71,14 @@ func (s *S) TestRoleAddRun(c *check.C) { trans := &cmdtest.ConditionalTransport{ Transport: cmdtest.Transport{Message: string(""), Status: http.StatusCreated}, CondFunc: func(req *http.Request) bool { - return strings.HasSuffix(req.URL.Path, "/roles") && req.Method == http.MethodPost && - req.FormValue("name") == "myrole" && req.FormValue("context") == "app" + var rol tsuru.RoleAddData + err := json.NewDecoder(req.Body).Decode(&rol) + c.Assert(err, check.IsNil) + c.Assert(rol, check.DeepEquals, tsuru.RoleAddData{ + Name: "myrole", + Contexttype: "app", + }) + return strings.HasSuffix(req.URL.Path, "/roles") && req.Method == http.MethodPost }, } client := cmd.NewClient(&http.Client{Transport: trans}, nil, manager) @@ -185,8 +193,17 @@ func (s *S) TestRoleAssignRun(c *check.C) { trans := &cmdtest.ConditionalTransport{ Transport: cmdtest.Transport{Message: string(""), Status: http.StatusCreated}, CondFunc: func(req *http.Request) bool { - return strings.HasSuffix(req.URL.Path, "/roles/myrole/user") && req.Method == http.MethodPost && - req.FormValue("email") == "me@me.com" && req.FormValue("context") == "myapp" + var rol tsuru.RoleAssignData + err := json.NewDecoder(req.Body).Decode(&rol) + c.Assert(err, check.IsNil) + c.Assert(rol, check.DeepEquals, tsuru.RoleAssignData{ + Name: "myrole", + Roletarget: "me@me.com", + Sufix: "user", + Version: "1.0", + Contextvalue: "myapp", + }) + return strings.HasSuffix(req.URL.Path, "/roles/myrole/user") && req.Method == http.MethodPost }, } client := cmd.NewClient(&http.Client{Transport: trans}, nil, manager) @@ -206,10 +223,16 @@ func (s *S) TestRoleAssignRunWithToken(c *check.C) { trans := &cmdtest.ConditionalTransport{ Transport: cmdtest.Transport{Message: string(""), Status: http.StatusCreated}, CondFunc: func(req *http.Request) bool { - c.Assert(req.URL.Path, check.Equals, "/1.6/roles/myrole/token") - c.Assert(req.Method, check.Equals, http.MethodPost) - c.Assert(req.FormValue("token_id"), check.Equals, "mytoken") - c.Assert(req.FormValue("context"), check.Equals, "myapp") + var rol tsuru.RoleAssignData + err := json.NewDecoder(req.Body).Decode(&rol) + c.Assert(err, check.IsNil) + c.Assert(rol, check.DeepEquals, tsuru.RoleAssignData{ + Name: "myrole", + Roletarget: "mytoken", + Sufix: "token", + Version: "1.6", + Contextvalue: "myapp", + }) return true }, } @@ -230,10 +253,16 @@ func (s *S) TestRoleAssignRunWithGroup(c *check.C) { trans := &cmdtest.ConditionalTransport{ Transport: cmdtest.Transport{Message: string(""), Status: http.StatusCreated}, CondFunc: func(req *http.Request) bool { - c.Assert(req.URL.Path, check.Equals, "/1.9/roles/myrole/group") - c.Assert(req.Method, check.Equals, http.MethodPost) - c.Assert(req.FormValue("group_name"), check.Equals, "grp1") - c.Assert(req.FormValue("context"), check.Equals, "myapp") + var rol tsuru.RoleAssignData + err := json.NewDecoder(req.Body).Decode(&rol) + c.Assert(err, check.IsNil) + c.Assert(rol, check.DeepEquals, tsuru.RoleAssignData{ + Name: "myrole", + Roletarget: "group:grp1", + Sufix: "group", + Version: "1.9", + Contextvalue: "myapp", + }) return true }, } @@ -306,10 +335,13 @@ func (s *S) TestRolePermissionAddRun(c *check.C) { trans := &cmdtest.ConditionalTransport{ Transport: cmdtest.Transport{Message: string(""), Status: http.StatusCreated}, CondFunc: func(req *http.Request) bool { - req.ParseForm() - sort.Strings(req.Form["permission"]) + //req.ParseForm() + //sort.Strings(req.Form["permission"]) + var perm tsuru.PermissionData + err := json.NewDecoder(req.Body).Decode(&perm) + c.Assert(err, check.IsNil) return strings.HasSuffix(req.URL.Path, "/roles/myrole/permissions") && req.Method == http.MethodPost && - reflect.DeepEqual(req.Form["permission"], []string{"app.create", "app.deploy"}) + reflect.DeepEqual(perm.Permission, []string{"app.create", "app.deploy"}) }, } client := cmd.NewClient(&http.Client{Transport: trans}, nil, manager) @@ -414,11 +446,14 @@ func (s *S) TestRoleDefaultAdd(c *check.C) { trans := &cmdtest.ConditionalTransport{ Transport: cmdtest.Transport{Message: string(""), Status: http.StatusCreated}, CondFunc: func(req *http.Request) bool { - req.ParseForm() - sort.Strings(req.Form["user-create"]) - return strings.HasSuffix(req.URL.Path, "/role/default") && req.Method == http.MethodPost && - reflect.DeepEqual(req.Form["user-create"], []string{"r1", "r2"}) && - reflect.DeepEqual(req.Form["team-create"], []string{"r3"}) + var rolDefault tsuru.RoleDefaultData + err := json.NewDecoder(req.Body).Decode(&rolDefault) + c.Assert(err, check.IsNil) + c.Assert(rolDefault, check.DeepEquals, tsuru.RoleDefaultData{ + Rolesmap: map[string][]string{"team-create": {"r3"}, + "user-create": {"r1", "r2"}}, + }) + return strings.HasSuffix(req.URL.Path, "/role/default") && req.Method == http.MethodPost }, } client := cmd.NewClient(&http.Client{Transport: trans}, nil, manager) @@ -500,10 +535,19 @@ func (s *S) TestRoleUpdate(c *check.C) { trans := &cmdtest.ConditionalTransport{ Transport: cmdtest.Transport{Message: "", Status: http.StatusOK}, CondFunc: func(req *http.Request) bool { - path := req.URL.Path == "/1.4/roles" + path := req.URL.Path == "/1.0/roles" method := req.Method == http.MethodPut - contentType := req.Header.Get("Content-Type") == "application/x-www-form-urlencoded" - return path && method && contentType && req.FormValue("name") == "team-member" && req.FormValue("description") == "a developer" + contentType := req.Header.Get("Content-Type") == "application/json" + var rol tsuru.RoleUpdateData + err := json.NewDecoder(req.Body).Decode(&rol) + c.Assert(err, check.IsNil) + c.Assert(rol, check.DeepEquals, tsuru.RoleUpdateData{ + Name: "team-member", + ContextType: "", + Description: "a developer", + NewName: "", + }) + return path && method && contentType }, } manager := cmd.Manager{} @@ -528,8 +572,17 @@ func (s *S) TestRoleUpdateWithoutFlags(c *check.C) { CondFunc: func(req *http.Request) bool { path := strings.HasSuffix(req.URL.Path, "/roles") method := req.Method == http.MethodPut - contentType := req.Header.Get("Content-Type") == "application/x-www-form-urlencoded" - return path && method && contentType && req.FormValue("name") == "team-member" && req.FormValue("description") == "a developer" + contentType := req.Header.Get("Content-Type") == "application/json" + var rol tsuru.RoleUpdateData + err := json.NewDecoder(req.Body).Decode(&rol) + c.Assert(err, check.IsNil) + c.Assert(rol, check.DeepEquals, tsuru.RoleUpdateData{ + Name: "team-member", + ContextType: "", + Description: "a developer", + NewName: "", + }) + return path && method && contentType }, } manager := cmd.Manager{} @@ -552,8 +605,17 @@ func (s *S) TestRoleUpdateMultipleFlags(c *check.C) { CondFunc: func(req *http.Request) bool { path := strings.HasSuffix(req.URL.Path, "/roles") method := req.Method == http.MethodPut - contentType := req.Header.Get("Content-Type") == "application/x-www-form-urlencoded" - return path && method && contentType && req.FormValue("name") == "team-member" && req.FormValue("description") == "a developer" && req.FormValue("contextType") == "team" && req.FormValue("newName") == "newName" + contentType := req.Header.Get("Content-Type") == "application/json" + var rol tsuru.RoleUpdateData + err := json.NewDecoder(req.Body).Decode(&rol) + c.Assert(err, check.IsNil) + c.Assert(rol, check.DeepEquals, tsuru.RoleUpdateData{ + Name: "team-member", + ContextType: "team", + Description: "a developer", + NewName: "newName", + }) + return path && method && contentType }, } manager := cmd.Manager{} @@ -577,8 +639,15 @@ func (s *S) TestRoleUpdateWithInvalidContent(c *check.C) { CondFunc: func(req *http.Request) bool { path := strings.HasSuffix(req.URL.Path, "/roles") method := req.Method == http.MethodPut - contentType := req.Header.Get("Content-Type") == "application/x-www-form-urlencoded" - return path && method && contentType && req.FormValue("name") == "invalid-role" && req.FormValue("description") == "a developer" + contentType := req.Header.Get("Content-Type") == "application/json" + var rol tsuru.RoleUpdateData + err := json.NewDecoder(req.Body).Decode(&rol) + c.Assert(err, check.IsNil) + c.Assert(rol, check.DeepEquals, tsuru.RoleUpdateData{ + Name: "invalid-role", + Description: "a developer", + }) + return path && method && contentType }, } manager := cmd.Manager{}