SDK error revamp (#432)

SDK methods now return 1 error.  To differentiate between Client errors and Server errors I've also implemented the AsServerError function which returns an *api.Error if it is an error originating from the remote server or nil otherwise.
This commit is contained in:
Todd Knight authored and GitHub committed 2020-09-24 14:34:58 -07:00
1 parent 94f9d952be
commit fd0da998e8
53 files changed
+1512 -1635

No files matched your search

+48 -50
View File
@@ -9,8 +9,6 @@ import (
"net/url"
"time"
"github.com/kr/pretty"
"github.com/hashicorp/boundary/api"
"github.com/hashicorp/boundary/api/scopes"
)
@@ -109,22 +107,22 @@ func (c *Client) ApiClient() *api.Client {
return c.client
}
func (c *Client) Create(ctx context.Context, authMethodId string, opt ...Option) (*AccountCreateResult, *api.Error, error) {
func (c *Client) Create(ctx context.Context, authMethodId string, opt ...Option) (*AccountCreateResult, error) {
if authMethodId == "" {
return nil, nil, fmt.Errorf("empty authMethodId value passed into Create request")
return nil, fmt.Errorf("empty authMethodId value passed into Create request")
}
opts, apiOpts := getOpts(opt...)
if c.client == nil {
return nil, nil, fmt.Errorf("nil client")
return nil, fmt.Errorf("nil client")
}
opts.postMap["auth_method_id"] = authMethodId
req, err := c.client.NewRequest(ctx, "POST", "accounts", opts.postMap, apiOpts...)
if err != nil {
return nil, nil, fmt.Errorf("error creating Create request: %w", err)
return nil, fmt.Errorf("error creating Create request: %w", err)
}
if len(opts.queryMap) > 0 {
@@ -137,36 +135,36 @@ func (c *Client) Create(ctx context.Context, authMethodId string, opt ...Option)
resp, err := c.client.Do(req)
if err != nil {
return nil, nil, fmt.Errorf("error performing client request during Create call: %w", err)
return nil, fmt.Errorf("error performing client request during Create call: %w", err)
}
target := new(AccountCreateResult)
target.Item = new(Account)
apiErr, err := resp.Decode(target.Item)
if err != nil {
return nil, nil, fmt.Errorf("error decoding Create response: %w", err)
return nil, fmt.Errorf("error decoding Create response: %w", err)
}
if apiErr != nil {
return nil, apiErr, nil
return nil, apiErr
}
target.responseBody = resp.Body
target.responseMap = resp.Map
return target, apiErr, nil
return target, nil
}
func (c *Client) Read(ctx context.Context, accountId string, opt ...Option) (*AccountReadResult, *api.Error, error) {
func (c *Client) Read(ctx context.Context, accountId string, opt ...Option) (*AccountReadResult, error) {
if accountId == "" {
return nil, nil, fmt.Errorf("empty accountId value passed into Read request")
return nil, fmt.Errorf("empty accountId value passed into Read request")
}
if c.client == nil {
return nil, nil, fmt.Errorf("nil client")
return nil, fmt.Errorf("nil client")
}
opts, apiOpts := getOpts(opt...)
req, err := c.client.NewRequest(ctx, "GET", fmt.Sprintf("accounts/%s", accountId), nil, apiOpts...)
if err != nil {
return nil, nil, fmt.Errorf("error creating Read request: %w", err)
return nil, fmt.Errorf("error creating Read request: %w", err)
}
if len(opts.queryMap) > 0 {
@@ -179,49 +177,49 @@ func (c *Client) Read(ctx context.Context, accountId string, opt ...Option) (*Ac
resp, err := c.client.Do(req)
if err != nil {
return nil, nil, fmt.Errorf("error performing client request during Read call: %w", err)
return nil, fmt.Errorf("error performing client request during Read call: %w", err)
}
target := new(AccountReadResult)
target.Item = new(Account)
apiErr, err := resp.Decode(target.Item)
if err != nil {
return nil, nil, fmt.Errorf("error decoding Read response: %w", err)
return nil, fmt.Errorf("error decoding Read response: %w", err)
}
if apiErr != nil {
return nil, apiErr, nil
return nil, apiErr
}
target.responseBody = resp.Body
target.responseMap = resp.Map
return target, apiErr, nil
return target, nil
}
func (c *Client) Update(ctx context.Context, accountId string, version uint32, opt ...Option) (*AccountUpdateResult, *api.Error, error) {
func (c *Client) Update(ctx context.Context, accountId string, version uint32, opt ...Option) (*AccountUpdateResult, error) {
if accountId == "" {
return nil, nil, fmt.Errorf("empty accountId value passed into Update request")
return nil, fmt.Errorf("empty accountId value passed into Update request")
}
if c.client == nil {
return nil, nil, fmt.Errorf("nil client")
return nil, fmt.Errorf("nil client")
}
opts, apiOpts := getOpts(opt...)
if version == 0 {
if !opts.withAutomaticVersioning {
return nil, nil, errors.New("zero version number passed into Update request and automatic versioning not specified")
return nil, errors.New("zero version number passed into Update request and automatic versioning not specified")
}
existingTarget, existingApiErr, existingErr := c.Read(ctx, accountId, opt...)
existingTarget, existingErr := c.Read(ctx, accountId, opt...)
if existingErr != nil {
return nil, nil, fmt.Errorf("error performing initial check-and-set read: %w", existingErr)
}
if existingApiErr != nil {
return nil, nil, fmt.Errorf("error from controller when performing initial check-and-set read: %s", pretty.Sprint(existingApiErr))
if api.AsServerError(existingErr) != nil {
return nil, fmt.Errorf("error from controller when performing initial check-and-set read: %w", existingErr)
}
return nil, fmt.Errorf("error performing initial check-and-set read: %w", existingErr)
}
if existingTarget == nil {
return nil, nil, errors.New("nil resource response found when performing initial check-and-set read")
return nil, errors.New("nil resource response found when performing initial check-and-set read")
}
if existingTarget.Item == nil {
return nil, nil, errors.New("nil resource found when performing initial check-and-set read")
return nil, errors.New("nil resource found when performing initial check-and-set read")
}
version = existingTarget.Item.Version
}
@@ -230,7 +228,7 @@ func (c *Client) Update(ctx context.Context, accountId string, version uint32, o
req, err := c.client.NewRequest(ctx, "PATCH", fmt.Sprintf("accounts/%s", accountId), opts.postMap, apiOpts...)
if err != nil {
return nil, nil, fmt.Errorf("error creating Update request: %w", err)
return nil, fmt.Errorf("error creating Update request: %w", err)
}
if len(opts.queryMap) > 0 {
@@ -243,36 +241,36 @@ func (c *Client) Update(ctx context.Context, accountId string, version uint32, o
resp, err := c.client.Do(req)
if err != nil {
return nil, nil, fmt.Errorf("error performing client request during Update call: %w", err)
return nil, fmt.Errorf("error performing client request during Update call: %w", err)
}
target := new(AccountUpdateResult)
target.Item = new(Account)
apiErr, err := resp.Decode(target.Item)
if err != nil {
return nil, nil, fmt.Errorf("error decoding Update response: %w", err)
return nil, fmt.Errorf("error decoding Update response: %w", err)
}
if apiErr != nil {
return nil, apiErr, nil
return nil, apiErr
}
target.responseBody = resp.Body
target.responseMap = resp.Map
return target, apiErr, nil
return target, nil
}
func (c *Client) Delete(ctx context.Context, accountId string, opt ...Option) (*AccountDeleteResult, *api.Error, error) {
func (c *Client) Delete(ctx context.Context, accountId string, opt ...Option) (*AccountDeleteResult, error) {
if accountId == "" {
return nil, nil, fmt.Errorf("empty accountId value passed into Delete request")
return nil, fmt.Errorf("empty accountId value passed into Delete request")
}
if c.client == nil {
return nil, nil, fmt.Errorf("nil client")
return nil, fmt.Errorf("nil client")
}
opts, apiOpts := getOpts(opt...)
req, err := c.client.NewRequest(ctx, "DELETE", fmt.Sprintf("accounts/%s", accountId), nil, apiOpts...)
if err != nil {
return nil, nil, fmt.Errorf("error creating Delete request: %w", err)
return nil, fmt.Errorf("error creating Delete request: %w", err)
}
if len(opts.queryMap) > 0 {
@@ -285,30 +283,30 @@ func (c *Client) Delete(ctx context.Context, accountId string, opt ...Option) (*
resp, err := c.client.Do(req)
if err != nil {
return nil, nil, fmt.Errorf("error performing client request during Delete call: %w", err)
return nil, fmt.Errorf("error performing client request during Delete call: %w", err)
}
apiErr, err := resp.Decode(nil)
if err != nil {
return nil, nil, fmt.Errorf("error decoding Delete response: %w", err)
return nil, fmt.Errorf("error decoding Delete response: %w", err)
}
if apiErr != nil {
return nil, apiErr, nil
return nil, apiErr
}
target := &AccountDeleteResult{
responseBody: resp.Body,
responseMap: resp.Map,
}
return target, nil, nil
return target, nil
}
func (c *Client) List(ctx context.Context, authMethodId string, opt ...Option) (*AccountListResult, *api.Error, error) {
func (c *Client) List(ctx context.Context, authMethodId string, opt ...Option) (*AccountListResult, error) {
if authMethodId == "" {
return nil, nil, fmt.Errorf("empty authMethodId value passed into List request")
return nil, fmt.Errorf("empty authMethodId value passed into List request")
}
if c.client == nil {
return nil, nil, fmt.Errorf("nil client")
return nil, fmt.Errorf("nil client")
}
opts, apiOpts := getOpts(opt...)
@@ -316,7 +314,7 @@ func (c *Client) List(ctx context.Context, authMethodId string, opt ...Option) (
req, err := c.client.NewRequest(ctx, "GET", "accounts", nil, apiOpts...)
if err != nil {
return nil, nil, fmt.Errorf("error creating List request: %w", err)
return nil, fmt.Errorf("error creating List request: %w", err)
}
if len(opts.queryMap) > 0 {
@@ -329,18 +327,18 @@ func (c *Client) List(ctx context.Context, authMethodId string, opt ...Option) (
resp, err := c.client.Do(req)
if err != nil {
return nil, nil, fmt.Errorf("error performing client request during List call: %w", err)
return nil, fmt.Errorf("error performing client request during List call: %w", err)
}
target := new(AccountListResult)
apiErr, err := resp.Decode(target)
if err != nil {
return nil, nil, fmt.Errorf("error decoding List response: %w", err)
return nil, fmt.Errorf("error decoding List response: %w", err)
}
if apiErr != nil {
return nil, apiErr, nil
return nil, apiErr
}
target.responseBody = resp.Body
target.responseMap = resp.Map
return target, apiErr, nil
return target, nil
}
+40 -49
View File
@@ -30,41 +30,35 @@ func TestList(t *testing.T) {
client.SetToken(token.Token)
org := iam.TestOrg(t, tc.IamRepo(), iam.WithUserId(token.UserId))
amClient := authmethods.NewClient(client)
amResult, apiErr, err := amClient.Create(tc.Context(), "password", org.GetPublicId())
amResult, err := amClient.Create(tc.Context(), "password", org.GetPublicId())
require.NoError(err)
require.Nil(apiErr)
require.NotNil(amResult)
am := amResult.Item
accountClient := accounts.NewClient(client)
lr, apiErr, err := accountClient.List(tc.Context(), am.Id)
lr, err := accountClient.List(tc.Context(), am.Id)
require.NoError(err)
require.Nil(apiErr)
expected := lr.Items
assert.Len(expected, 0)
expected = append(expected, &accounts.Account{Attributes: map[string]interface{}{"login_name": "loginname0"}})
cr, apiErr, err := accountClient.Create(tc.Context(), am.Id, accounts.WithPasswordAccountLoginName(expected[0].Attributes["login_name"].(string)))
cr, err := accountClient.Create(tc.Context(), am.Id, accounts.WithPasswordAccountLoginName(expected[0].Attributes["login_name"].(string)))
require.NoError(err)
require.Nil(apiErr)
expected[0] = cr.Item
ulResult, apiErr, err := accountClient.List(tc.Context(), am.Id)
ulResult, err := accountClient.List(tc.Context(), am.Id)
require.NoError(err)
require.Nil(apiErr)
assert.ElementsMatch(comparableSlice(expected[:1]), comparableSlice(ulResult.Items))
for i := 1; i < 10; i++ {
newAcctResult, apiErr, err := accountClient.Create(tc.Context(), am.Id, accounts.WithPasswordAccountLoginName(fmt.Sprintf("loginname%d", i)))
newAcctResult, err := accountClient.Create(tc.Context(), am.Id, accounts.WithPasswordAccountLoginName(fmt.Sprintf("loginname%d", i)))
require.NoError(err)
require.Nil(apiErr)
expected = append(expected, newAcctResult.Item)
}
ulResult, apiErr, err = accountClient.List(tc.Context(), am.Id)
ulResult, err = accountClient.List(tc.Context(), am.Id)
require.NoError(err)
assert.Nil(apiErr)
assert.ElementsMatch(comparableSlice(expected), comparableSlice(ulResult.Items))
}
@@ -95,11 +89,8 @@ func TestCrud(t *testing.T) {
amId := token.AuthMethodId
accountClient := accounts.NewClient(client)
checkAccount := func(step string, u *accounts.Account, apiErr *api.Error, err error, wantedName string, wantedVersion uint32) {
checkAccount := func(step string, u *accounts.Account, err error, wantedName string, wantedVersion uint32) {
assert.NoError(err, step)
if !assert.Nil(apiErr, step) && apiErr.Message != "" {
t.Errorf("ApiError message: %q", apiErr.Message)
}
require.NotNil(u, "returned no resource", step)
gotName := ""
if u.Name != "" {
@@ -109,21 +100,20 @@ func TestCrud(t *testing.T) {
assert.EqualValues(wantedVersion, u.Version)
}
u, apiErr, err := accountClient.Create(tc.Context(), amId, accounts.WithName("foo"), accounts.WithPasswordAccountLoginName("loginname"))
checkAccount("create", u.Item, apiErr, err, "foo", 1)
u, err := accountClient.Create(tc.Context(), amId, accounts.WithName("foo"), accounts.WithPasswordAccountLoginName("loginname"))
checkAccount("create", u.Item, err, "foo", 1)
u, apiErr, err = accountClient.Read(tc.Context(), u.Item.Id)
checkAccount("read", u.Item, apiErr, err, "foo", 1)
u, err = accountClient.Read(tc.Context(), u.Item.Id)
checkAccount("read", u.Item, err, "foo", 1)
u, apiErr, err = accountClient.Update(tc.Context(), u.Item.Id, u.Item.Version, accounts.WithName("bar"))
checkAccount("update", u.Item, apiErr, err, "bar", 2)
u, err = accountClient.Update(tc.Context(), u.Item.Id, u.Item.Version, accounts.WithName("bar"))
checkAccount("update", u.Item, err, "bar", 2)
u, apiErr, err = accountClient.Update(tc.Context(), u.Item.Id, u.Item.Version, accounts.DefaultName())
checkAccount("update", u.Item, apiErr, err, "", 3)
u, err = accountClient.Update(tc.Context(), u.Item.Id, u.Item.Version, accounts.DefaultName())
checkAccount("update", u.Item, err, "", 3)
_, apiErr, err = accountClient.Delete(tc.Context(), u.Item.Id)
_, err = accountClient.Delete(tc.Context(), u.Item.Id)
require.NoError(err)
assert.Nil(apiErr)
}
func TestCustomMethods(t *testing.T) {
@@ -138,22 +128,19 @@ func TestCustomMethods(t *testing.T) {
accountClient := accounts.NewClient(client)
al, apiErr, err := accountClient.List(tc.Context(), amId)
al, err := accountClient.List(tc.Context(), amId)
require.NoError(err)
require.Nil(apiErr)
require.Len(al.Items, 1)
acct := al.Items[0]
setAcct, apiErr, err := accountClient.SetPassword(tc.Context(), acct.Id, "setpassword", acct.Version)
setAcct, err := accountClient.SetPassword(tc.Context(), acct.Id, "setpassword", acct.Version)
require.NoError(err)
require.Nil(apiErr)
require.NotNil(setAcct)
assert.Equal(acct.Version+1, setAcct.Item.Version)
changeAcct, apiErr, err := accountClient.ChangePassword(tc.Context(), acct.Id, "setpassword", "changepassword", setAcct.Item.Version)
changeAcct, err := accountClient.ChangePassword(tc.Context(), acct.Id, "setpassword", "changepassword", setAcct.Item.Version)
require.NoError(err)
require.Nil(apiErr)
require.NotNil(changeAcct)
assert.Equal(setAcct.Item.Version+1, changeAcct.Item.Version)
}
@@ -169,34 +156,38 @@ func TestErrors(t *testing.T) {
amId := token.AuthMethodId
accountClient := accounts.NewClient(client)
u, apiErr, err := accountClient.Create(tc.Context(), amId, accounts.WithPasswordAccountLoginName("first"))
u, err := accountClient.Create(tc.Context(), amId, accounts.WithPasswordAccountLoginName("first"))
require.NoError(err)
assert.Nil(apiErr)
assert.NotNil(u)
// Updating the wrong version should fail.
_, apiErr, err = accountClient.Update(tc.Context(), u.Item.Id, 73, accounts.WithName("anything"))
require.NoError(err)
assert.NotNil(apiErr)
_, err = accountClient.Update(tc.Context(), u.Item.Id, 73, accounts.WithName("anything"))
require.Error(err)
apiErr := api.AsServerError(err)
require.NotNil(apiErr)
assert.EqualValues(http.StatusNotFound, apiErr.Status)
// Create another resource with the same name.
_, apiErr, err = accountClient.Create(tc.Context(), amId, accounts.WithPasswordAccountLoginName("first"))
require.NoError(err)
assert.NotNil(apiErr)
_, err = accountClient.Create(tc.Context(), amId, accounts.WithPasswordAccountLoginName("first"))
require.Error(err)
apiErr = api.AsServerError(err)
require.NotNil(apiErr)
_, apiErr, err = accountClient.Read(tc.Context(), password.AccountPrefix+"_doesntexis")
require.NoError(err)
assert.NotNil(apiErr)
_, err = accountClient.Read(tc.Context(), password.AccountPrefix+"_doesntexis")
require.Error(err)
apiErr = api.AsServerError(err)
require.NotNil(apiErr)
assert.EqualValues(http.StatusNotFound, apiErr.Status)
_, apiErr, err = accountClient.Read(tc.Context(), "invalid id")
require.NoError(err)
assert.NotNil(apiErr)
_, err = accountClient.Read(tc.Context(), "invalid id")
require.Error(err)
apiErr = api.AsServerError(err)
require.NotNil(apiErr)
assert.EqualValues(http.StatusBadRequest, apiErr.Status)
_, apiErr, err = accountClient.Update(tc.Context(), u.Item.Id, u.Item.Version)
require.NoError(err)
assert.NotNil(apiErr)
_, err = accountClient.Update(tc.Context(), u.Item.Id, u.Item.Version)
require.Error(err)
apiErr = api.AsServerError(err)
require.NotNil(apiErr)
assert.EqualValues(http.StatusBadRequest, apiErr.Status)
}
+18 -15
View File
@@ -6,32 +6,31 @@ import (
"fmt"
"github.com/hashicorp/boundary/api"
"github.com/kr/pretty"
)
func (c *Client) ChangePassword(ctx context.Context, accountId, currentPassword, newPassword string, version uint32, opt ...Option) (*AccountUpdateResult, *api.Error, error) {
func (c *Client) ChangePassword(ctx context.Context, accountId, currentPassword, newPassword string, version uint32, opt ...Option) (*AccountUpdateResult, error) {
if accountId == "" {
return nil, nil, fmt.Errorf("empty accountId value passed into ChangePassword request")
return nil, fmt.Errorf("empty accountId value passed into ChangePassword request")
}
if c.client == nil {
return nil, nil, fmt.Errorf("nil client in ChangePassword request")
return nil, fmt.Errorf("nil client in ChangePassword request")
}
opts, apiOpts := getOpts(opt...)
if version == 0 {
if !opts.withAutomaticVersioning {
return nil, nil, errors.New("zero version number passed into Update request and automatic versioning not specified")
return nil, errors.New("zero version number passed into Update request and automatic versioning not specified")
}
existingTarget, existingApiErr, existingErr := c.Read(ctx, accountId, opt...)
existingTarget, existingErr := c.Read(ctx, accountId, opt...)
if existingErr != nil {
return nil, nil, fmt.Errorf("error performing initial check-and-set read: %w", existingErr)
}
if existingApiErr != nil {
return nil, nil, fmt.Errorf("error from controller when performing initial check-and-set read: %s", pretty.Sprint(existingApiErr))
if api.AsServerError(existingErr) != nil {
return nil, fmt.Errorf("error from controller when performing initial check-and-set read: %w", existingErr)
}
return nil, fmt.Errorf("error performing initial check-and-set read: %w", existingErr)
}
if existingTarget == nil {
return nil, nil, errors.New("nil resource found when performing initial check-and-set read")
return nil, errors.New("nil resource found when performing initial check-and-set read")
}
version = existingTarget.Item.Version
}
@@ -44,20 +43,24 @@ func (c *Client) ChangePassword(ctx context.Context, accountId, currentPassword,
req, err := c.client.NewRequest(ctx, "POST", fmt.Sprintf("accounts/%s:change-password", accountId), reqBody, apiOpts...)
if err != nil {
return nil, nil, fmt.Errorf("error creating ChangePassword request: %w", err)
return nil, fmt.Errorf("error creating ChangePassword request: %w", err)
}
resp, err := c.client.Do(req)
if err != nil {
return nil, nil, fmt.Errorf("error performing client request during ChangePassword call: %w", err)
return nil, fmt.Errorf("error performing client request during ChangePassword call: %w", err)
}
target := new(AccountUpdateResult)
target.Item = new(Account)
apiErr, err := resp.Decode(target.Item)
if err != nil {
return nil, nil, fmt.Errorf("error decoding ChangePassword response: %w", err)
return nil, fmt.Errorf("error decoding ChangePassword response: %w", err)
}
return target, apiErr, nil
if apiErr != nil {
return nil, apiErr
}
return target, nil
}
+17 -15
View File
@@ -6,32 +6,31 @@ import (
"fmt"
"github.com/hashicorp/boundary/api"
"github.com/kr/pretty"
)
func (c *Client) SetPassword(ctx context.Context, accountId, password string, version uint32, opt ...Option) (*AccountUpdateResult, *api.Error, error) {
func (c *Client) SetPassword(ctx context.Context, accountId, password string, version uint32, opt ...Option) (*AccountUpdateResult, error) {
if accountId == "" {
return nil, nil, fmt.Errorf("empty accountId value passed into SetPassword request")
return nil, fmt.Errorf("empty accountId value passed into SetPassword request")
}
if c.client == nil {
return nil, nil, fmt.Errorf("nil client in SetPassword request")
return nil, fmt.Errorf("nil client in SetPassword request")
}
opts, apiOpts := getOpts(opt...)
if version == 0 {
if !opts.withAutomaticVersioning {
return nil, nil, errors.New("zero version number passed into Update request and automatic versioning not specified")
return nil, errors.New("zero version number passed into Update request and automatic versioning not specified")
}
existingTarget, existingApiErr, existingErr := c.Read(ctx, accountId, opt...)
existingTarget, existingErr := c.Read(ctx, accountId, opt...)
if existingErr != nil {
return nil, nil, fmt.Errorf("error performing initial check-and-set read: %w", existingErr)
}
if existingApiErr != nil {
return nil, nil, fmt.Errorf("error from controller when performing initial check-and-set read: %s", pretty.Sprint(existingApiErr))
if api.AsServerError(existingErr) != nil {
return nil, fmt.Errorf("error from controller when performing initial check-and-set read: %w", existingErr)
}
return nil, fmt.Errorf("error performing initial check-and-set read: %w", existingErr)
}
if existingTarget == nil {
return nil, nil, errors.New("nil resource found when performing initial check-and-set read")
return nil, errors.New("nil resource found when performing initial check-and-set read")
}
version = existingTarget.Item.Version
}
@@ -43,20 +42,23 @@ func (c *Client) SetPassword(ctx context.Context, accountId, password string, ve
req, err := c.client.NewRequest(ctx, "POST", fmt.Sprintf("accounts/%s:set-password", accountId), reqBody, apiOpts...)
if err != nil {
return nil, nil, fmt.Errorf("error creating SetPassword request: %w", err)
return nil, fmt.Errorf("error creating SetPassword request: %w", err)
}
resp, err := c.client.Do(req)
if err != nil {
return nil, nil, fmt.Errorf("error performing client request during SetPassword call: %w", err)
return nil, fmt.Errorf("error performing client request during SetPassword call: %w", err)
}
target := new(AccountUpdateResult)
target.Item = new(Account)
apiErr, err := resp.Decode(target.Item)
if err != nil {
return nil, nil, fmt.Errorf("error decoding SetPassword response: %w", err)
return nil, fmt.Errorf("error decoding SetPassword response: %w", err)
}
if apiErr != nil {
return nil, apiErr
}
return target, apiErr, nil
return target, nil
}
+58
View File
@@ -0,0 +1,58 @@
package api
import (
"errors"
"fmt"
"net/http"
"strings"
"google.golang.org/grpc/codes"
)
var (
ErrNotFound = &Error{Status: http.StatusNotFound, Code: codes.NotFound.String()}
ErrInvalidArgument = &Error{Status: http.StatusBadRequest, Code: codes.InvalidArgument.String()}
ErrPermissionDenied = &Error{Status: http.StatusForbidden, Code: codes.PermissionDenied.String()}
ErrUnauthorized = &Error{Status: http.StatusUnauthorized, Code: codes.Unauthenticated.String()}
)
// AsServerError returns an api *Error from the provided error. If the provided error
// is not an api Error nil is returned instead.
func AsServerError(in error) *Error {
var serverErr *Error
if !errors.As(in, &serverErr) {
return nil
}
return serverErr
}
// Error satisfies the error interface.
func (e *Error) Error() string {
res := fmt.Sprintf("Status: %d, Code: %q, Error: %q", e.Status, e.Code, e.Message)
var dets []string
if e.Details != nil {
if e.Details.ErrorId != "" {
dets = append(dets, fmt.Sprintf("error_id: %q", e.Details.ErrorId))
}
if e.Details.RequestId != "" {
dets = append(dets, fmt.Sprintf("request_id: %q", e.Details.RequestId))
}
if e.Details.TraceId != "" {
dets = append(dets, fmt.Sprintf("TraceId: %q", e.Details.TraceId))
}
for _, rf := range e.Details.RequestFields {
dets = append(dets, fmt.Sprintf("request_field: {name: %q, desc: %q}", rf.Name, rf.Description))
}
}
if len(dets) > 0 {
det := strings.Join(dets, ", ")
res = fmt.Sprintf("%s, Details: {%s}", res, det)
}
return res
}
// Errors are considered the same iff they are both api.Errors and their statuses are the same.
func (e *Error) Is(target error) bool {
tApiErr := AsServerError(target)
return tApiErr != nil && tApiErr.Code == e.Code && tApiErr.Status == e.Status
}
+9 -7
View File
@@ -4,13 +4,12 @@ import (
"context"
"fmt"
"github.com/hashicorp/boundary/api"
"github.com/hashicorp/boundary/api/authtokens"
)
func (c *Client) Authenticate(ctx context.Context, authMethodId string, credentials map[string]interface{}, opt ...Option) (*authtokens.AuthTokenReadResult, *api.Error, error) {
func (c *Client) Authenticate(ctx context.Context, authMethodId string, credentials map[string]interface{}, opt ...Option) (*authtokens.AuthTokenReadResult, error) {
if c.client == nil {
return nil, nil, fmt.Errorf("nil client in Authenticate request")
return nil, fmt.Errorf("nil client in Authenticate request")
}
_, apiOpts := getOpts(opt...)
@@ -21,20 +20,23 @@ func (c *Client) Authenticate(ctx context.Context, authMethodId string, credenti
req, err := c.client.NewRequest(ctx, "POST", fmt.Sprintf("auth-methods/%s:authenticate", authMethodId), reqBody, apiOpts...)
if err != nil {
return nil, nil, fmt.Errorf("error creating Authenticate request: %w", err)
return nil, fmt.Errorf("error creating Authenticate request: %w", err)
}
resp, err := c.client.Do(req)
if err != nil {
return nil, nil, fmt.Errorf("error performing client request during Authenticate call: %w", err)
return nil, fmt.Errorf("error performing client request during Authenticate call: %w", err)
}
target := new(authtokens.AuthTokenReadResult)
target.Item = new(authtokens.AuthToken)
apiErr, err := resp.Decode(target.Item)
if err != nil {
return nil, nil, fmt.Errorf("error decoding Authenticate response: %w", err)
return nil, fmt.Errorf("error decoding Authenticate response: %w", err)
}
if apiErr != nil {
return nil, apiErr
}
return target, apiErr, nil
return target, nil
}
+6 -6
View File
@@ -4,9 +4,9 @@ import (
"net/http"
"testing"
"github.com/hashicorp/boundary/api"
"github.com/hashicorp/boundary/api/authmethods"
"github.com/hashicorp/boundary/internal/servers/controller"
"github.com/kr/pretty"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
@@ -24,13 +24,13 @@ func TestAuthenticate(t *testing.T) {
client := tc.Client()
methods := authmethods.NewClient(client)
tok, apiErr, err := methods.Authenticate(tc.Context(), amId, map[string]interface{}{"login_name": "user", "password": "passpass"})
tok, err := methods.Authenticate(tc.Context(), amId, map[string]interface{}{"login_name": "user", "password": "passpass"})
require.NoError(err)
assert.Nil(apiErr, pretty.Sprint(apiErr))
assert.NotNil(tok)
_, apiErr, err = methods.Authenticate(tc.Context(), amId, map[string]interface{}{"login_name": "user", "password": "wrong"})
require.NoError(err)
require.NotNil(t, apiErr)
_, err = methods.Authenticate(tc.Context(), amId, map[string]interface{}{"login_name": "user", "password": "wrong"})
require.Error(err)
apiErr := api.AsServerError(err)
require.NotNil(apiErr)
assert.EqualValuesf(http.StatusUnauthorized, apiErr.Status, "Expected unauthorized, got %q", apiErr.Message)
}
+49 -51
View File
@@ -9,8 +9,6 @@ import (
"net/url"
"time"
"github.com/kr/pretty"
"github.com/hashicorp/boundary/api"
"github.com/hashicorp/boundary/api/scopes"
)
@@ -109,18 +107,18 @@ func (c *Client) ApiClient() *api.Client {
return c.client
}
func (c *Client) Create(ctx context.Context, resourceType string, scopeId string, opt ...Option) (*AuthMethodCreateResult, *api.Error, error) {
func (c *Client) Create(ctx context.Context, resourceType string, scopeId string, opt ...Option) (*AuthMethodCreateResult, error) {
if scopeId == "" {
return nil, nil, fmt.Errorf("empty scopeId value passed into Create request")
return nil, fmt.Errorf("empty scopeId value passed into Create request")
}
opts, apiOpts := getOpts(opt...)
if c.client == nil {
return nil, nil, fmt.Errorf("nil client")
return nil, fmt.Errorf("nil client")
}
if resourceType == "" {
return nil, nil, fmt.Errorf("empty resourceType value passed into Create request")
return nil, fmt.Errorf("empty resourceType value passed into Create request")
} else {
opts.postMap["type"] = resourceType
}
@@ -129,7 +127,7 @@ func (c *Client) Create(ctx context.Context, resourceType string, scopeId string
req, err := c.client.NewRequest(ctx, "POST", "auth-methods", opts.postMap, apiOpts...)
if err != nil {
return nil, nil, fmt.Errorf("error creating Create request: %w", err)
return nil, fmt.Errorf("error creating Create request: %w", err)
}
if len(opts.queryMap) > 0 {
@@ -142,36 +140,36 @@ func (c *Client) Create(ctx context.Context, resourceType string, scopeId string
resp, err := c.client.Do(req)
if err != nil {
return nil, nil, fmt.Errorf("error performing client request during Create call: %w", err)
return nil, fmt.Errorf("error performing client request during Create call: %w", err)
}
target := new(AuthMethodCreateResult)
target.Item = new(AuthMethod)
apiErr, err := resp.Decode(target.Item)
if err != nil {
return nil, nil, fmt.Errorf("error decoding Create response: %w", err)
return nil, fmt.Errorf("error decoding Create response: %w", err)
}
if apiErr != nil {
return nil, apiErr, nil
return nil, apiErr
}
target.responseBody = resp.Body
target.responseMap = resp.Map
return target, apiErr, nil
return target, nil
}
func (c *Client) Read(ctx context.Context, authMethodId string, opt ...Option) (*AuthMethodReadResult, *api.Error, error) {
func (c *Client) Read(ctx context.Context, authMethodId string, opt ...Option) (*AuthMethodReadResult, error) {
if authMethodId == "" {
return nil, nil, fmt.Errorf("empty authMethodId value passed into Read request")
return nil, fmt.Errorf("empty authMethodId value passed into Read request")
}
if c.client == nil {
return nil, nil, fmt.Errorf("nil client")
return nil, fmt.Errorf("nil client")
}
opts, apiOpts := getOpts(opt...)
req, err := c.client.NewRequest(ctx, "GET", fmt.Sprintf("auth-methods/%s", authMethodId), nil, apiOpts...)
if err != nil {
return nil, nil, fmt.Errorf("error creating Read request: %w", err)
return nil, fmt.Errorf("error creating Read request: %w", err)
}
if len(opts.queryMap) > 0 {
@@ -184,49 +182,49 @@ func (c *Client) Read(ctx context.Context, authMethodId string, opt ...Option) (
resp, err := c.client.Do(req)
if err != nil {
return nil, nil, fmt.Errorf("error performing client request during Read call: %w", err)
return nil, fmt.Errorf("error performing client request during Read call: %w", err)
}
target := new(AuthMethodReadResult)
target.Item = new(AuthMethod)
apiErr, err := resp.Decode(target.Item)
if err != nil {
return nil, nil, fmt.Errorf("error decoding Read response: %w", err)
return nil, fmt.Errorf("error decoding Read response: %w", err)
}
if apiErr != nil {
return nil, apiErr, nil
return nil, apiErr
}
target.responseBody = resp.Body
target.responseMap = resp.Map
return target, apiErr, nil
return target, nil
}
func (c *Client) Update(ctx context.Context, authMethodId string, version uint32, opt ...Option) (*AuthMethodUpdateResult, *api.Error, error) {
func (c *Client) Update(ctx context.Context, authMethodId string, version uint32, opt ...Option) (*AuthMethodUpdateResult, error) {
if authMethodId == "" {
return nil, nil, fmt.Errorf("empty authMethodId value passed into Update request")
return nil, fmt.Errorf("empty authMethodId value passed into Update request")
}
if c.client == nil {
return nil, nil, fmt.Errorf("nil client")
return nil, fmt.Errorf("nil client")
}
opts, apiOpts := getOpts(opt...)
if version == 0 {
if !opts.withAutomaticVersioning {
return nil, nil, errors.New("zero version number passed into Update request and automatic versioning not specified")
return nil, errors.New("zero version number passed into Update request and automatic versioning not specified")
}
existingTarget, existingApiErr, existingErr := c.Read(ctx, authMethodId, opt...)
existingTarget, existingErr := c.Read(ctx, authMethodId, opt...)
if existingErr != nil {
return nil, nil, fmt.Errorf("error performing initial check-and-set read: %w", existingErr)
}
if existingApiErr != nil {
return nil, nil, fmt.Errorf("error from controller when performing initial check-and-set read: %s", pretty.Sprint(existingApiErr))
if api.AsServerError(existingErr) != nil {
return nil, fmt.Errorf("error from controller when performing initial check-and-set read: %w", existingErr)
}
return nil, fmt.Errorf("error performing initial check-and-set read: %w", existingErr)
}
if existingTarget == nil {
return nil, nil, errors.New("nil resource response found when performing initial check-and-set read")
return nil, errors.New("nil resource response found when performing initial check-and-set read")
}
if existingTarget.Item == nil {
return nil, nil, errors.New("nil resource found when performing initial check-and-set read")
return nil, errors.New("nil resource found when performing initial check-and-set read")
}
version = existingTarget.Item.Version
}
@@ -235,7 +233,7 @@ func (c *Client) Update(ctx context.Context, authMethodId string, version uint32
req, err := c.client.NewRequest(ctx, "PATCH", fmt.Sprintf("auth-methods/%s", authMethodId), opts.postMap, apiOpts...)
if err != nil {
return nil, nil, fmt.Errorf("error creating Update request: %w", err)
return nil, fmt.Errorf("error creating Update request: %w", err)
}
if len(opts.queryMap) > 0 {
@@ -248,36 +246,36 @@ func (c *Client) Update(ctx context.Context, authMethodId string, version uint32
resp, err := c.client.Do(req)
if err != nil {
return nil, nil, fmt.Errorf("error performing client request during Update call: %w", err)
return nil, fmt.Errorf("error performing client request during Update call: %w", err)
}
target := new(AuthMethodUpdateResult)
target.Item = new(AuthMethod)
apiErr, err := resp.Decode(target.Item)
if err != nil {
return nil, nil, fmt.Errorf("error decoding Update response: %w", err)
return nil, fmt.Errorf("error decoding Update response: %w", err)
}
if apiErr != nil {
return nil, apiErr, nil
return nil, apiErr
}
target.responseBody = resp.Body
target.responseMap = resp.Map
return target, apiErr, nil
return target, nil
}
func (c *Client) Delete(ctx context.Context, authMethodId string, opt ...Option) (*AuthMethodDeleteResult, *api.Error, error) {
func (c *Client) Delete(ctx context.Context, authMethodId string, opt ...Option) (*AuthMethodDeleteResult, error) {
if authMethodId == "" {
return nil, nil, fmt.Errorf("empty authMethodId value passed into Delete request")
return nil, fmt.Errorf("empty authMethodId value passed into Delete request")
}
if c.client == nil {
return nil, nil, fmt.Errorf("nil client")
return nil, fmt.Errorf("nil client")
}
opts, apiOpts := getOpts(opt...)
req, err := c.client.NewRequest(ctx, "DELETE", fmt.Sprintf("auth-methods/%s", authMethodId), nil, apiOpts...)
if err != nil {
return nil, nil, fmt.Errorf("error creating Delete request: %w", err)
return nil, fmt.Errorf("error creating Delete request: %w", err)
}
if len(opts.queryMap) > 0 {
@@ -290,30 +288,30 @@ func (c *Client) Delete(ctx context.Context, authMethodId string, opt ...Option)
resp, err := c.client.Do(req)
if err != nil {
return nil, nil, fmt.Errorf("error performing client request during Delete call: %w", err)
return nil, fmt.Errorf("error performing client request during Delete call: %w", err)
}
apiErr, err := resp.Decode(nil)
if err != nil {
return nil, nil, fmt.Errorf("error decoding Delete response: %w", err)
return nil, fmt.Errorf("error decoding Delete response: %w", err)
}
if apiErr != nil {
return nil, apiErr, nil
return nil, apiErr
}
target := &AuthMethodDeleteResult{
responseBody: resp.Body,
responseMap: resp.Map,
}
return target, nil, nil
return target, nil
}
func (c *Client) List(ctx context.Context, scopeId string, opt ...Option) (*AuthMethodListResult, *api.Error, error) {
func (c *Client) List(ctx context.Context, scopeId string, opt ...Option) (*AuthMethodListResult, error) {
if scopeId == "" {
return nil, nil, fmt.Errorf("empty scopeId value passed into List request")
return nil, fmt.Errorf("empty scopeId value passed into List request")
}
if c.client == nil {
return nil, nil, fmt.Errorf("nil client")
return nil, fmt.Errorf("nil client")
}
opts, apiOpts := getOpts(opt...)
@@ -321,7 +319,7 @@ func (c *Client) List(ctx context.Context, scopeId string, opt ...Option) (*Auth
req, err := c.client.NewRequest(ctx, "GET", "auth-methods", nil, apiOpts...)
if err != nil {
return nil, nil, fmt.Errorf("error creating List request: %w", err)
return nil, fmt.Errorf("error creating List request: %w", err)
}
if len(opts.queryMap) > 0 {
@@ -334,18 +332,18 @@ func (c *Client) List(ctx context.Context, scopeId string, opt ...Option) (*Auth
resp, err := c.client.Do(req)
if err != nil {
return nil, nil, fmt.Errorf("error performing client request during List call: %w", err)
return nil, fmt.Errorf("error performing client request during List call: %w", err)
}
target := new(AuthMethodListResult)
apiErr, err := resp.Decode(target)
if err != nil {
return nil, nil, fmt.Errorf("error decoding List response: %w", err)
return nil, fmt.Errorf("error decoding List response: %w", err)
}
if apiErr != nil {
return nil, apiErr, nil
return nil, apiErr
}
target.responseBody = resp.Body
target.responseMap = resp.Map
return target, apiErr, nil
return target, nil
}
+22 -32
View File
@@ -5,6 +5,7 @@ import (
"sort"
"testing"
"github.com/hashicorp/boundary/api"
"github.com/hashicorp/boundary/api/accounts"
"github.com/hashicorp/boundary/api/authmethods"
"github.com/hashicorp/boundary/api/authtokens"
@@ -32,61 +33,51 @@ func TestList(t *testing.T) {
org := iam.TestOrg(t, tc.IamRepo(), iam.WithUserId(token.UserId))
amClient := authmethods.NewClient(client)
amResult, apiErr, err := amClient.Create(tc.Context(), "password", org.GetPublicId())
amResult, err := amClient.Create(tc.Context(), "password", org.GetPublicId())
require.NoError(err)
require.Nil(apiErr)
require.NotNil(amResult)
amId = amResult.Item.Id
rolesClient := roles.NewClient(client)
role, apiErr, err := rolesClient.Create(tc.Context(), org.GetPublicId())
role, err := rolesClient.Create(tc.Context(), org.GetPublicId())
require.NoError(err)
require.Nil(apiErr)
require.NotNil(role)
role, apiErr, err = rolesClient.AddPrincipals(tc.Context(), role.Item.Id, 0, []string{"u_anon"}, roles.WithAutomaticVersioning(true))
role, err = rolesClient.AddPrincipals(tc.Context(), role.Item.Id, 0, []string{"u_anon"}, roles.WithAutomaticVersioning(true))
require.NoError(err)
require.Nil(apiErr)
require.NotNil(role)
role, apiErr, err = rolesClient.AddGrants(tc.Context(), role.Item.Id, 0, []string{"type=auth-method;actions=authenticate"}, roles.WithAutomaticVersioning(true))
role, err = rolesClient.AddGrants(tc.Context(), role.Item.Id, 0, []string{"type=auth-method;actions=authenticate"}, roles.WithAutomaticVersioning(true))
require.NoError(err)
require.Nil(apiErr)
require.NotNil(role)
acctClient := accounts.NewClient(client)
acct, apiErr, err := acctClient.Create(tc.Context(), amId, accounts.WithPasswordAccountLoginName("user"), accounts.WithPasswordAccountPassword("passpass"))
acct, err := acctClient.Create(tc.Context(), amId, accounts.WithPasswordAccountLoginName("user"), accounts.WithPasswordAccountPassword("passpass"))
require.NoError(err)
require.Nil(apiErr)
require.NotNil(acct)
tokens := authtokens.NewClient(client)
atl, apiErr, err := tokens.List(tc.Context(), org.GetPublicId())
atl, err := tokens.List(tc.Context(), org.GetPublicId())
require.NoError(err)
assert.Nil(apiErr)
assert.Empty(atl.Items)
var expected []*authtokens.AuthToken
methods := authmethods.NewClient(client)
at, apiErr, err := methods.Authenticate(tc.Context(), amId, map[string]interface{}{"login_name": "user", "password": "passpass"})
at, err := methods.Authenticate(tc.Context(), amId, map[string]interface{}{"login_name": "user", "password": "passpass"})
require.NoError(err)
assert.Nil(apiErr)
expected = append(expected, at.Item)
atl, apiErr, err = tokens.List(tc.Context(), org.GetPublicId())
atl, err = tokens.List(tc.Context(), org.GetPublicId())
require.NoError(err)
assert.Nil(apiErr)
assert.ElementsMatch(comparableSlice(expected), comparableSlice(atl.Items))
for i := 1; i < 10; i++ {
at, apiErr, err = methods.Authenticate(tc.Context(), amId, map[string]interface{}{"login_name": "user", "password": "passpass"})
at, err = methods.Authenticate(tc.Context(), amId, map[string]interface{}{"login_name": "user", "password": "passpass"})
require.NoError(err)
assert.Nil(apiErr)
expected = append(expected, at.Item)
}
atl, apiErr, err = tokens.List(tc.Context(), org.GetPublicId())
atl, err = tokens.List(tc.Context(), org.GetPublicId())
require.NoError(err)
assert.Nil(apiErr)
assert.ElementsMatch(comparableSlice(expected), comparableSlice(atl.Items))
}
@@ -129,18 +120,15 @@ func TestCrud(t *testing.T) {
tokens := authtokens.NewClient(client)
methods := authmethods.NewClient(client)
want, apiErr, err := methods.Authenticate(tc.Context(), amId, map[string]interface{}{"login_name": "user", "password": "passpass"})
want, err := methods.Authenticate(tc.Context(), amId, map[string]interface{}{"login_name": "user", "password": "passpass"})
require.NoError(err)
assert.Empty(apiErr)
at, apiErr, err := tokens.Read(tc.Context(), want.Item.Id)
at, err := tokens.Read(tc.Context(), want.Item.Id)
require.NoError(err)
assert.Nil(apiErr)
assert.EqualValues(comparableResource(want.Item), comparableResource(at.Item))
_, _, err = tokens.Delete(tc.Context(), at.Item.Id)
_, err = tokens.Delete(tc.Context(), at.Item.Id)
require.NoError(err)
assert.Nil(apiErr)
}
func TestErrors(t *testing.T) {
@@ -153,13 +141,15 @@ func TestErrors(t *testing.T) {
client.SetToken(token.Token)
tokens := authtokens.NewClient(client)
_, apiErr, err := tokens.Read(tc.Context(), authtoken.AuthTokenPrefix+"_doesntexis")
require.NoError(err)
assert.NotNil(apiErr)
_, err := tokens.Read(tc.Context(), authtoken.AuthTokenPrefix+"_doesntexis")
require.Error(err)
apiErr := api.AsServerError(err)
require.NotNil(apiErr)
assert.EqualValues(http.StatusNotFound, apiErr.Status)
_, apiErr, err = tokens.Read(tc.Context(), "invalid id")
require.NoError(err)
assert.NotNil(apiErr)
_, err = tokens.Read(tc.Context(), "invalid id")
require.Error(err)
apiErr = api.AsServerError(err)
require.NotNil(apiErr)
assert.EqualValues(http.StatusBadRequest, apiErr.Status)
}
+24 -24
View File
@@ -107,19 +107,19 @@ func (c *Client) ApiClient() *api.Client {
return c.client
}
func (c *Client) Read(ctx context.Context, authTokenId string, opt ...Option) (*AuthTokenReadResult, *api.Error, error) {
func (c *Client) Read(ctx context.Context, authTokenId string, opt ...Option) (*AuthTokenReadResult, error) {
if authTokenId == "" {
return nil, nil, fmt.Errorf("empty authTokenId value passed into Read request")
return nil, fmt.Errorf("empty authTokenId value passed into Read request")
}
if c.client == nil {
return nil, nil, fmt.Errorf("nil client")
return nil, fmt.Errorf("nil client")
}
opts, apiOpts := getOpts(opt...)
req, err := c.client.NewRequest(ctx, "GET", fmt.Sprintf("auth-tokens/%s", authTokenId), nil, apiOpts...)
if err != nil {
return nil, nil, fmt.Errorf("error creating Read request: %w", err)
return nil, fmt.Errorf("error creating Read request: %w", err)
}
if len(opts.queryMap) > 0 {
@@ -132,36 +132,36 @@ func (c *Client) Read(ctx context.Context, authTokenId string, opt ...Option) (*
resp, err := c.client.Do(req)
if err != nil {
return nil, nil, fmt.Errorf("error performing client request during Read call: %w", err)
return nil, fmt.Errorf("error performing client request during Read call: %w", err)
}
target := new(AuthTokenReadResult)
target.Item = new(AuthToken)
apiErr, err := resp.Decode(target.Item)
if err != nil {
return nil, nil, fmt.Errorf("error decoding Read response: %w", err)
return nil, fmt.Errorf("error decoding Read response: %w", err)
}
if apiErr != nil {
return nil, apiErr, nil
return nil, apiErr
}
target.responseBody = resp.Body
target.responseMap = resp.Map
return target, apiErr, nil
return target, nil
}
func (c *Client) Delete(ctx context.Context, authTokenId string, opt ...Option) (*AuthTokenDeleteResult, *api.Error, error) {
func (c *Client) Delete(ctx context.Context, authTokenId string, opt ...Option) (*AuthTokenDeleteResult, error) {
if authTokenId == "" {
return nil, nil, fmt.Errorf("empty authTokenId value passed into Delete request")
return nil, fmt.Errorf("empty authTokenId value passed into Delete request")
}
if c.client == nil {
return nil, nil, fmt.Errorf("nil client")
return nil, fmt.Errorf("nil client")
}
opts, apiOpts := getOpts(opt...)
req, err := c.client.NewRequest(ctx, "DELETE", fmt.Sprintf("auth-tokens/%s", authTokenId), nil, apiOpts...)
if err != nil {
return nil, nil, fmt.Errorf("error creating Delete request: %w", err)
return nil, fmt.Errorf("error creating Delete request: %w", err)
}
if len(opts.queryMap) > 0 {
@@ -174,30 +174,30 @@ func (c *Client) Delete(ctx context.Context, authTokenId string, opt ...Option)
resp, err := c.client.Do(req)
if err != nil {
return nil, nil, fmt.Errorf("error performing client request during Delete call: %w", err)
return nil, fmt.Errorf("error performing client request during Delete call: %w", err)
}
apiErr, err := resp.Decode(nil)
if err != nil {
return nil, nil, fmt.Errorf("error decoding Delete response: %w", err)
return nil, fmt.Errorf("error decoding Delete response: %w", err)
}
if apiErr != nil {
return nil, apiErr, nil
return nil, apiErr
}
target := &AuthTokenDeleteResult{
responseBody: resp.Body,
responseMap: resp.Map,
}
return target, nil, nil
return target, nil
}
func (c *Client) List(ctx context.Context, scopeId string, opt ...Option) (*AuthTokenListResult, *api.Error, error) {
func (c *Client) List(ctx context.Context, scopeId string, opt ...Option) (*AuthTokenListResult, error) {
if scopeId == "" {
return nil, nil, fmt.Errorf("empty scopeId value passed into List request")
return nil, fmt.Errorf("empty scopeId value passed into List request")
}
if c.client == nil {
return nil, nil, fmt.Errorf("nil client")
return nil, fmt.Errorf("nil client")
}
opts, apiOpts := getOpts(opt...)
@@ -205,7 +205,7 @@ func (c *Client) List(ctx context.Context, scopeId string, opt ...Option) (*Auth
req, err := c.client.NewRequest(ctx, "GET", "auth-tokens", nil, apiOpts...)
if err != nil {
return nil, nil, fmt.Errorf("error creating List request: %w", err)
return nil, fmt.Errorf("error creating List request: %w", err)
}
if len(opts.queryMap) > 0 {
@@ -218,18 +218,18 @@ func (c *Client) List(ctx context.Context, scopeId string, opt ...Option) (*Auth
resp, err := c.client.Do(req)
if err != nil {
return nil, nil, fmt.Errorf("error performing client request during List call: %w", err)
return nil, fmt.Errorf("error performing client request during List call: %w", err)
}
target := new(AuthTokenListResult)
apiErr, err := resp.Decode(target)
if err != nil {
return nil, nil, fmt.Errorf("error decoding List response: %w", err)
return nil, fmt.Errorf("error decoding List response: %w", err)
}
if apiErr != nil {
return nil, apiErr, nil
return nil, apiErr
}
target.responseBody = resp.Body
target.responseMap = resp.Map
return target, apiErr, nil
return target, nil
}
+98 -100
View File
@@ -9,8 +9,6 @@ import (
"net/url"
"time"
"github.com/kr/pretty"
"github.com/hashicorp/boundary/api"
"github.com/hashicorp/boundary/api/scopes"
)
@@ -109,22 +107,22 @@ func (c *Client) ApiClient() *api.Client {
return c.client
}
func (c *Client) Create(ctx context.Context, scopeId string, opt ...Option) (*GroupCreateResult, *api.Error, error) {
func (c *Client) Create(ctx context.Context, scopeId string, opt ...Option) (*GroupCreateResult, error) {
if scopeId == "" {
return nil, nil, fmt.Errorf("empty scopeId value passed into Create request")
return nil, fmt.Errorf("empty scopeId value passed into Create request")
}
opts, apiOpts := getOpts(opt...)
if c.client == nil {
return nil, nil, fmt.Errorf("nil client")
return nil, fmt.Errorf("nil client")
}
opts.postMap["scope_id"] = scopeId
req, err := c.client.NewRequest(ctx, "POST", "groups", opts.postMap, apiOpts...)
if err != nil {
return nil, nil, fmt.Errorf("error creating Create request: %w", err)
return nil, fmt.Errorf("error creating Create request: %w", err)
}
if len(opts.queryMap) > 0 {
@@ -137,36 +135,36 @@ func (c *Client) Create(ctx context.Context, scopeId string, opt ...Option) (*Gr
resp, err := c.client.Do(req)
if err != nil {
return nil, nil, fmt.Errorf("error performing client request during Create call: %w", err)
return nil, fmt.Errorf("error performing client request during Create call: %w", err)
}
target := new(GroupCreateResult)
target.Item = new(Group)
apiErr, err := resp.Decode(target.Item)
if err != nil {
return nil, nil, fmt.Errorf("error decoding Create response: %w", err)
return nil, fmt.Errorf("error decoding Create response: %w", err)
}
if apiErr != nil {
return nil, apiErr, nil
return nil, apiErr
}
target.responseBody = resp.Body
target.responseMap = resp.Map
return target, apiErr, nil
return target, nil
}
func (c *Client) Read(ctx context.Context, groupId string, opt ...Option) (*GroupReadResult, *api.Error, error) {
func (c *Client) Read(ctx context.Context, groupId string, opt ...Option) (*GroupReadResult, error) {
if groupId == "" {
return nil, nil, fmt.Errorf("empty groupId value passed into Read request")
return nil, fmt.Errorf("empty groupId value passed into Read request")
}
if c.client == nil {
return nil, nil, fmt.Errorf("nil client")
return nil, fmt.Errorf("nil client")
}
opts, apiOpts := getOpts(opt...)
req, err := c.client.NewRequest(ctx, "GET", fmt.Sprintf("groups/%s", groupId), nil, apiOpts...)
if err != nil {
return nil, nil, fmt.Errorf("error creating Read request: %w", err)
return nil, fmt.Errorf("error creating Read request: %w", err)
}
if len(opts.queryMap) > 0 {
@@ -179,49 +177,49 @@ func (c *Client) Read(ctx context.Context, groupId string, opt ...Option) (*Grou
resp, err := c.client.Do(req)
if err != nil {
return nil, nil, fmt.Errorf("error performing client request during Read call: %w", err)
return nil, fmt.Errorf("error performing client request during Read call: %w", err)
}
target := new(GroupReadResult)
target.Item = new(Group)
apiErr, err := resp.Decode(target.Item)
if err != nil {
return nil, nil, fmt.Errorf("error decoding Read response: %w", err)
return nil, fmt.Errorf("error decoding Read response: %w", err)
}
if apiErr != nil {
return nil, apiErr, nil
return nil, apiErr
}
target.responseBody = resp.Body
target.responseMap = resp.Map
return target, apiErr, nil
return target, nil
}
func (c *Client) Update(ctx context.Context, groupId string, version uint32, opt ...Option) (*GroupUpdateResult, *api.Error, error) {
func (c *Client) Update(ctx context.Context, groupId string, version uint32, opt ...Option) (*GroupUpdateResult, error) {
if groupId == "" {
return nil, nil, fmt.Errorf("empty groupId value passed into Update request")
return nil, fmt.Errorf("empty groupId value passed into Update request")
}
if c.client == nil {
return nil, nil, fmt.Errorf("nil client")
return nil, fmt.Errorf("nil client")
}
opts, apiOpts := getOpts(opt...)
if version == 0 {
if !opts.withAutomaticVersioning {
return nil, nil, errors.New("zero version number passed into Update request and automatic versioning not specified")
return nil, errors.New("zero version number passed into Update request and automatic versioning not specified")
}
existingTarget, existingApiErr, existingErr := c.Read(ctx, groupId, opt...)
existingTarget, existingErr := c.Read(ctx, groupId, opt...)
if existingErr != nil {
return nil, nil, fmt.Errorf("error performing initial check-and-set read: %w", existingErr)
}
if existingApiErr != nil {
return nil, nil, fmt.Errorf("error from controller when performing initial check-and-set read: %s", pretty.Sprint(existingApiErr))
if api.AsServerError(existingErr) != nil {
return nil, fmt.Errorf("error from controller when performing initial check-and-set read: %w", existingErr)
}
return nil, fmt.Errorf("error performing initial check-and-set read: %w", existingErr)
}
if existingTarget == nil {
return nil, nil, errors.New("nil resource response found when performing initial check-and-set read")
return nil, errors.New("nil resource response found when performing initial check-and-set read")
}
if existingTarget.Item == nil {
return nil, nil, errors.New("nil resource found when performing initial check-and-set read")
return nil, errors.New("nil resource found when performing initial check-and-set read")
}
version = existingTarget.Item.Version
}
@@ -230,7 +228,7 @@ func (c *Client) Update(ctx context.Context, groupId string, version uint32, opt
req, err := c.client.NewRequest(ctx, "PATCH", fmt.Sprintf("groups/%s", groupId), opts.postMap, apiOpts...)
if err != nil {
return nil, nil, fmt.Errorf("error creating Update request: %w", err)
return nil, fmt.Errorf("error creating Update request: %w", err)
}
if len(opts.queryMap) > 0 {
@@ -243,36 +241,36 @@ func (c *Client) Update(ctx context.Context, groupId string, version uint32, opt
resp, err := c.client.Do(req)
if err != nil {
return nil, nil, fmt.Errorf("error performing client request during Update call: %w", err)
return nil, fmt.Errorf("error performing client request during Update call: %w", err)
}
target := new(GroupUpdateResult)
target.Item = new(Group)
apiErr, err := resp.Decode(target.Item)
if err != nil {
return nil, nil, fmt.Errorf("error decoding Update response: %w", err)
return nil, fmt.Errorf("error decoding Update response: %w", err)
}
if apiErr != nil {
return nil, apiErr, nil
return nil, apiErr
}
target.responseBody = resp.Body
target.responseMap = resp.Map
return target, apiErr, nil
return target, nil
}
func (c *Client) Delete(ctx context.Context, groupId string, opt ...Option) (*GroupDeleteResult, *api.Error, error) {
func (c *Client) Delete(ctx context.Context, groupId string, opt ...Option) (*GroupDeleteResult, error) {
if groupId == "" {
return nil, nil, fmt.Errorf("empty groupId value passed into Delete request")
return nil, fmt.Errorf("empty groupId value passed into Delete request")
}
if c.client == nil {
return nil, nil, fmt.Errorf("nil client")
return nil, fmt.Errorf("nil client")
}
opts, apiOpts := getOpts(opt...)
req, err := c.client.NewRequest(ctx, "DELETE", fmt.Sprintf("groups/%s", groupId), nil, apiOpts...)
if err != nil {
return nil, nil, fmt.Errorf("error creating Delete request: %w", err)
return nil, fmt.Errorf("error creating Delete request: %w", err)
}
if len(opts.queryMap) > 0 {
@@ -285,30 +283,30 @@ func (c *Client) Delete(ctx context.Context, groupId string, opt ...Option) (*Gr
resp, err := c.client.Do(req)
if err != nil {
return nil, nil, fmt.Errorf("error performing client request during Delete call: %w", err)
return nil, fmt.Errorf("error performing client request during Delete call: %w", err)
}
apiErr, err := resp.Decode(nil)
if err != nil {
return nil, nil, fmt.Errorf("error decoding Delete response: %w", err)
return nil, fmt.Errorf("error decoding Delete response: %w", err)
}
if apiErr != nil {
return nil, apiErr, nil
return nil, apiErr
}
target := &GroupDeleteResult{
responseBody: resp.Body,
responseMap: resp.Map,
}
return target, nil, nil
return target, nil
}
func (c *Client) List(ctx context.Context, scopeId string, opt ...Option) (*GroupListResult, *api.Error, error) {
func (c *Client) List(ctx context.Context, scopeId string, opt ...Option) (*GroupListResult, error) {
if scopeId == "" {
return nil, nil, fmt.Errorf("empty scopeId value passed into List request")
return nil, fmt.Errorf("empty scopeId value passed into List request")
}
if c.client == nil {
return nil, nil, fmt.Errorf("nil client")
return nil, fmt.Errorf("nil client")
}
opts, apiOpts := getOpts(opt...)
@@ -316,7 +314,7 @@ func (c *Client) List(ctx context.Context, scopeId string, opt ...Option) (*Grou
req, err := c.client.NewRequest(ctx, "GET", "groups", nil, apiOpts...)
if err != nil {
return nil, nil, fmt.Errorf("error creating List request: %w", err)
return nil, fmt.Errorf("error creating List request: %w", err)
}
if len(opts.queryMap) > 0 {
@@ -329,51 +327,51 @@ func (c *Client) List(ctx context.Context, scopeId string, opt ...Option) (*Grou
resp, err := c.client.Do(req)
if err != nil {
return nil, nil, fmt.Errorf("error performing client request during List call: %w", err)
return nil, fmt.Errorf("error performing client request during List call: %w", err)
}
target := new(GroupListResult)
apiErr, err := resp.Decode(target)
if err != nil {
return nil, nil, fmt.Errorf("error decoding List response: %w", err)
return nil, fmt.Errorf("error decoding List response: %w", err)
}
if apiErr != nil {
return nil, apiErr, nil
return nil, apiErr
}
target.responseBody = resp.Body
target.responseMap = resp.Map
return target, apiErr, nil
return target, nil
}
func (c *Client) AddMembers(ctx context.Context, groupId string, version uint32, memberIds []string, opt ...Option) (*GroupUpdateResult, *api.Error, error) {
func (c *Client) AddMembers(ctx context.Context, groupId string, version uint32, memberIds []string, opt ...Option) (*GroupUpdateResult, error) {
if groupId == "" {
return nil, nil, fmt.Errorf("empty groupId value passed into AddMembers request")
return nil, fmt.Errorf("empty groupId value passed into AddMembers request")
}
if len(memberIds) == 0 {
return nil, nil, errors.New("empty memberIds passed into AddMembers request")
return nil, errors.New("empty memberIds passed into AddMembers request")
}
if c.client == nil {
return nil, nil, errors.New("nil client")
return nil, errors.New("nil client")
}
opts, apiOpts := getOpts(opt...)
if version == 0 {
if !opts.withAutomaticVersioning {
return nil, nil, errors.New("zero version number passed into AddMembers request")
return nil, errors.New("zero version number passed into AddMembers request")
}
existingTarget, existingApiErr, existingErr := c.Read(ctx, groupId, opt...)
existingTarget, existingErr := c.Read(ctx, groupId, opt...)
if existingErr != nil {
return nil, nil, fmt.Errorf("error performing initial check-and-set read: %w", existingErr)
}
if existingApiErr != nil {
return nil, nil, fmt.Errorf("error from controller when performing initial check-and-set read: %s", pretty.Sprint(existingApiErr))
if api.AsServerError(existingErr) != nil {
return nil, fmt.Errorf("error from controller when performing initial check-and-set read: %w", existingErr)
}
return nil, fmt.Errorf("error performing initial check-and-set read: %w", existingErr)
}
if existingTarget == nil {
return nil, nil, errors.New("nil resource response found when performing initial check-and-set read")
return nil, errors.New("nil resource response found when performing initial check-and-set read")
}
if existingTarget.Item == nil {
return nil, nil, errors.New("nil resource found when performing initial check-and-set read")
return nil, errors.New("nil resource found when performing initial check-and-set read")
}
version = existingTarget.Item.Version
}
@@ -383,7 +381,7 @@ func (c *Client) AddMembers(ctx context.Context, groupId string, version uint32,
req, err := c.client.NewRequest(ctx, "POST", fmt.Sprintf("groups/%s:add-members", groupId), opts.postMap, apiOpts...)
if err != nil {
return nil, nil, fmt.Errorf("error creating AddMembers request: %w", err)
return nil, fmt.Errorf("error creating AddMembers request: %w", err)
}
if len(opts.queryMap) > 0 {
@@ -396,50 +394,50 @@ func (c *Client) AddMembers(ctx context.Context, groupId string, version uint32,
resp, err := c.client.Do(req)
if err != nil {
return nil, nil, fmt.Errorf("error performing client request during AddMembers call: %w", err)
return nil, fmt.Errorf("error performing client request during AddMembers call: %w", err)
}
target := new(GroupUpdateResult)
target.Item = new(Group)
apiErr, err := resp.Decode(target.Item)
if err != nil {
return nil, nil, fmt.Errorf("error decoding AddMembers response: %w", err)
return nil, fmt.Errorf("error decoding AddMembers response: %w", err)
}
if apiErr != nil {
return nil, apiErr, nil
return nil, apiErr
}
target.responseBody = resp.Body
target.responseMap = resp.Map
return target, apiErr, nil
return target, nil
}
func (c *Client) SetMembers(ctx context.Context, groupId string, version uint32, memberIds []string, opt ...Option) (*GroupUpdateResult, *api.Error, error) {
func (c *Client) SetMembers(ctx context.Context, groupId string, version uint32, memberIds []string, opt ...Option) (*GroupUpdateResult, error) {
if groupId == "" {
return nil, nil, fmt.Errorf("empty groupId value passed into SetMembers request")
return nil, fmt.Errorf("empty groupId value passed into SetMembers request")
}
if c.client == nil {
return nil, nil, errors.New("nil client")
return nil, errors.New("nil client")
}
opts, apiOpts := getOpts(opt...)
if version == 0 {
if !opts.withAutomaticVersioning {
return nil, nil, errors.New("zero version number passed into SetMembers request")
return nil, errors.New("zero version number passed into SetMembers request")
}
existingTarget, existingApiErr, existingErr := c.Read(ctx, groupId, opt...)
existingTarget, existingErr := c.Read(ctx, groupId, opt...)
if existingErr != nil {
return nil, nil, fmt.Errorf("error performing initial check-and-set read: %w", existingErr)
}
if existingApiErr != nil {
return nil, nil, fmt.Errorf("error from controller when performing initial check-and-set read: %s", pretty.Sprint(existingApiErr))
if api.AsServerError(existingErr) != nil {
return nil, fmt.Errorf("error from controller when performing initial check-and-set read: %w", existingErr)
}
return nil, fmt.Errorf("error performing initial check-and-set read: %w", existingErr)
}
if existingTarget == nil {
return nil, nil, errors.New("nil resource response found when performing initial check-and-set read")
return nil, errors.New("nil resource response found when performing initial check-and-set read")
}
if existingTarget.Item == nil {
return nil, nil, errors.New("nil resource found when performing initial check-and-set read")
return nil, errors.New("nil resource found when performing initial check-and-set read")
}
version = existingTarget.Item.Version
}
@@ -449,7 +447,7 @@ func (c *Client) SetMembers(ctx context.Context, groupId string, version uint32,
req, err := c.client.NewRequest(ctx, "POST", fmt.Sprintf("groups/%s:set-members", groupId), opts.postMap, apiOpts...)
if err != nil {
return nil, nil, fmt.Errorf("error creating SetMembers request: %w", err)
return nil, fmt.Errorf("error creating SetMembers request: %w", err)
}
if len(opts.queryMap) > 0 {
@@ -462,52 +460,52 @@ func (c *Client) SetMembers(ctx context.Context, groupId string, version uint32,
resp, err := c.client.Do(req)
if err != nil {
return nil, nil, fmt.Errorf("error performing client request during SetMembers call: %w", err)
return nil, fmt.Errorf("error performing client request during SetMembers call: %w", err)
}
target := new(GroupUpdateResult)
target.Item = new(Group)
apiErr, err := resp.Decode(target.Item)
if err != nil {
return nil, nil, fmt.Errorf("error decoding SetMembers response: %w", err)
return nil, fmt.Errorf("error decoding SetMembers response: %w", err)
}
if apiErr != nil {
return nil, apiErr, nil
return nil, apiErr
}
target.responseBody = resp.Body
target.responseMap = resp.Map
return target, apiErr, nil
return target, nil
}
func (c *Client) RemoveMembers(ctx context.Context, groupId string, version uint32, memberIds []string, opt ...Option) (*GroupUpdateResult, *api.Error, error) {
func (c *Client) RemoveMembers(ctx context.Context, groupId string, version uint32, memberIds []string, opt ...Option) (*GroupUpdateResult, error) {
if groupId == "" {
return nil, nil, fmt.Errorf("empty groupId value passed into RemoveMembers request")
return nil, fmt.Errorf("empty groupId value passed into RemoveMembers request")
}
if len(memberIds) == 0 {
return nil, nil, errors.New("empty memberIds passed into RemoveMembers request")
return nil, errors.New("empty memberIds passed into RemoveMembers request")
}
if c.client == nil {
return nil, nil, errors.New("nil client")
return nil, errors.New("nil client")
}
opts, apiOpts := getOpts(opt...)
if version == 0 {
if !opts.withAutomaticVersioning {
return nil, nil, errors.New("zero version number passed into RemoveMembers request")
return nil, errors.New("zero version number passed into RemoveMembers request")
}
existingTarget, existingApiErr, existingErr := c.Read(ctx, groupId, opt...)
existingTarget, existingErr := c.Read(ctx, groupId, opt...)
if existingErr != nil {
return nil, nil, fmt.Errorf("error performing initial check-and-set read: %w", existingErr)
}
if existingApiErr != nil {
return nil, nil, fmt.Errorf("error from controller when performing initial check-and-set read: %s", pretty.Sprint(existingApiErr))
if api.AsServerError(existingErr) != nil {
return nil, fmt.Errorf("error from controller when performing initial check-and-set read: %w", existingErr)
}
return nil, fmt.Errorf("error performing initial check-and-set read: %w", existingErr)
}
if existingTarget == nil {
return nil, nil, errors.New("nil resource response found when performing initial check-and-set read")
return nil, errors.New("nil resource response found when performing initial check-and-set read")
}
if existingTarget.Item == nil {
return nil, nil, errors.New("nil resource found when performing initial check-and-set read")
return nil, errors.New("nil resource found when performing initial check-and-set read")
}
version = existingTarget.Item.Version
}
@@ -517,7 +515,7 @@ func (c *Client) RemoveMembers(ctx context.Context, groupId string, version uint
req, err := c.client.NewRequest(ctx, "POST", fmt.Sprintf("groups/%s:remove-members", groupId), opts.postMap, apiOpts...)
if err != nil {
return nil, nil, fmt.Errorf("error creating RemoveMembers request: %w", err)
return nil, fmt.Errorf("error creating RemoveMembers request: %w", err)
}
if len(opts.queryMap) > 0 {
@@ -530,19 +528,19 @@ func (c *Client) RemoveMembers(ctx context.Context, groupId string, version uint
resp, err := c.client.Do(req)
if err != nil {
return nil, nil, fmt.Errorf("error performing client request during RemoveMembers call: %w", err)
return nil, fmt.Errorf("error performing client request during RemoveMembers call: %w", err)
}
target := new(GroupUpdateResult)
target.Item = new(Group)
apiErr, err := resp.Decode(target.Item)
if err != nil {
return nil, nil, fmt.Errorf("error decoding RemoveMembers response: %w", err)
return nil, fmt.Errorf("error decoding RemoveMembers response: %w", err)
}
if apiErr != nil {
return nil, apiErr, nil
return nil, apiErr
}
target.responseBody = resp.Body
target.responseMap = resp.Map
return target, apiErr, nil
return target, nil
}
+43 -49
View File
@@ -41,21 +41,18 @@ func TestList(t *testing.T) {
for _, tt := range cases {
t.Run(tt.name, func(t *testing.T) {
grps := groups.NewClient(client)
pl, apiErr, err := grps.List(tc.Context(), tt.scopeId)
pl, err := grps.List(tc.Context(), tt.scopeId)
assert.NoError(err)
assert.Nil(apiErr)
assert.Empty(pl.Items)
expected := make([]*groups.Group, 10)
for i := 0; i < 10; i++ {
createResult, apiErr, err := grps.Create(tc.Context(), tt.scopeId, groups.WithName(fmt.Sprint(i)))
createResult, err := grps.Create(tc.Context(), tt.scopeId, groups.WithName(fmt.Sprint(i)))
require.NoError(err)
assert.Nil(apiErr)
expected[i] = createResult.Item
}
pl, apiErr, err = grps.List(tc.Context(), tt.scopeId)
pl, err = grps.List(tc.Context(), tt.scopeId)
require.NoError(err)
assert.Nil(apiErr)
require.NotNil(pl)
require.Len(pl.Items, 10)
assert.ElementsMatch(comparableSlice(expected), comparableSlice(pl.Items))
@@ -88,11 +85,8 @@ func TestCrud(t *testing.T) {
client.SetToken(token.Token)
org, proj := iam.TestScopes(t, tc.IamRepo(), iam.WithUserId(token.UserId))
checkGroup := func(step string, g *groups.Group, apiErr *api.Error, err error, wantedName string, wantedVersion uint32, expectedUserIds []string) {
checkGroup := func(step string, g *groups.Group, err error, wantedName string, wantedVersion uint32, expectedUserIds []string) {
require.NoError(err, step)
if !assert.Nil(apiErr, step) && apiErr.Message != "" {
t.Errorf("ApiError message: %q", apiErr.Message)
}
assert.NotNil(g, "returned no resource", step)
gotName := ""
if g.Name != "" {
@@ -120,44 +114,42 @@ func TestCrud(t *testing.T) {
},
}
user1, apiErr, err := users.NewClient(client).Create(tc.Context(), org.GetPublicId())
user1, err := users.NewClient(client).Create(tc.Context(), org.GetPublicId())
require.NoError(err)
require.Nil(apiErr)
user2, apiErr, err := users.NewClient(client).Create(tc.Context(), org.GetPublicId())
user2, err := users.NewClient(client).Create(tc.Context(), org.GetPublicId())
require.NoError(err)
require.Nil(apiErr)
for _, tt := range cases {
t.Run(tt.name, func(t *testing.T) {
groupsClient := groups.NewClient(client)
g, apiErr, err := groupsClient.Create(tc.Context(), tt.scopeId, groups.WithName("foo"))
checkGroup("create", g.Item, apiErr, err, "foo", 1, nil)
g, err := groupsClient.Create(tc.Context(), tt.scopeId, groups.WithName("foo"))
checkGroup("create", g.Item, err, "foo", 1, nil)
g, apiErr, err = groupsClient.Read(tc.Context(), g.Item.Id)
checkGroup("read", g.Item, apiErr, err, "foo", 1, nil)
g, err = groupsClient.Read(tc.Context(), g.Item.Id)
checkGroup("read", g.Item, err, "foo", 1, nil)
g, apiErr, err = groupsClient.Update(tc.Context(), g.Item.Id, g.Item.Version, groups.WithName("bar"))
checkGroup("update", g.Item, apiErr, err, "bar", 2, nil)
g, err = groupsClient.Update(tc.Context(), g.Item.Id, g.Item.Version, groups.WithName("bar"))
checkGroup("update", g.Item, err, "bar", 2, nil)
g, apiErr, err = groupsClient.Update(tc.Context(), g.Item.Id, g.Item.Version, groups.DefaultName())
checkGroup("update", g.Item, apiErr, err, "", 3, nil)
g, err = groupsClient.Update(tc.Context(), g.Item.Id, g.Item.Version, groups.DefaultName())
checkGroup("update", g.Item, err, "", 3, nil)
g, apiErr, err = groupsClient.AddMembers(tc.Context(), g.Item.Id, g.Item.Version, []string{user1.Item.Id})
checkGroup("update", g.Item, apiErr, err, "", 4, []string{user1.Item.Id})
g, err = groupsClient.AddMembers(tc.Context(), g.Item.Id, g.Item.Version, []string{user1.Item.Id})
checkGroup("update", g.Item, err, "", 4, []string{user1.Item.Id})
g, apiErr, err = groupsClient.SetMembers(tc.Context(), g.Item.Id, g.Item.Version, []string{user2.Item.Id})
checkGroup("update", g.Item, apiErr, err, "", 5, []string{user2.Item.Id})
g, err = groupsClient.SetMembers(tc.Context(), g.Item.Id, g.Item.Version, []string{user2.Item.Id})
checkGroup("update", g.Item, err, "", 5, []string{user2.Item.Id})
g, apiErr, err = groupsClient.RemoveMembers(tc.Context(), g.Item.Id, g.Item.Version, []string{user2.Item.Id})
checkGroup("update", g.Item, apiErr, err, "", 6, nil)
g, err = groupsClient.RemoveMembers(tc.Context(), g.Item.Id, g.Item.Version, []string{user2.Item.Id})
checkGroup("update", g.Item, err, "", 6, nil)
_, apiErr, err = groupsClient.Delete(tc.Context(), g.Item.Id)
_, err = groupsClient.Delete(tc.Context(), g.Item.Id)
require.NoError(err)
assert.Nil(apiErr)
_, apiErr, err = groupsClient.Delete(tc.Context(), g.Item.Id)
require.NoError(err)
_, err = groupsClient.Delete(tc.Context(), g.Item.Id)
require.Error(err)
apiErr := api.AsServerError(err)
require.NotNil(apiErr)
assert.EqualValues(http.StatusNotFound, apiErr.Status)
})
@@ -192,35 +184,37 @@ func TestErrors(t *testing.T) {
t.Run(tt.name, func(t *testing.T) {
groupClient := groups.NewClient(client)
g, apiErr, err := groupClient.Create(tc.Context(), tt.scopeId, groups.WithName("first"))
g, err := groupClient.Create(tc.Context(), tt.scopeId, groups.WithName("first"))
require.NoError(err)
assert.Nil(apiErr)
assert.NotNil(g)
// Updating the wrong version should fail.
_, apiErr, err = groupClient.Update(tc.Context(), g.Item.Id, 73, groups.WithName("anything"))
require.NoError(err)
assert.NotNil(apiErr)
_, err = groupClient.Update(tc.Context(), g.Item.Id, 73, groups.WithName("anything"))
require.Error(err)
apiErr := api.AsServerError(err)
require.NotNil(apiErr)
assert.EqualValues(http.StatusNotFound, apiErr.Status)
// Create another resource with the same name.
_, apiErr, err = groupClient.Create(tc.Context(), tt.scopeId, groups.WithName("first"))
require.NoError(err)
assert.NotNil(apiErr)
_, err = groupClient.Create(tc.Context(), tt.scopeId, groups.WithName("first"))
require.Error(err)
_, apiErr, err = groupClient.Read(tc.Context(), iam.GroupPrefix+"_doesntexis")
require.NoError(err)
assert.NotNil(apiErr)
_, err = groupClient.Read(tc.Context(), iam.GroupPrefix+"_doesntexis")
require.Error(err)
apiErr = api.AsServerError(err)
require.NotNil(apiErr)
assert.EqualValues(http.StatusNotFound, apiErr.Status)
_, apiErr, err = groupClient.Read(tc.Context(), "invalid id")
require.NoError(err)
assert.NotNil(apiErr)
_, err = groupClient.Read(tc.Context(), "invalid id")
require.Error(err)
apiErr = api.AsServerError(err)
require.NotNil(apiErr)
assert.EqualValues(http.StatusBadRequest, apiErr.Status)
_, apiErr, err = groupClient.Update(tc.Context(), g.Item.Id, g.Item.Version)
require.NoError(err)
assert.NotNil(apiErr)
_, err = groupClient.Update(tc.Context(), g.Item.Id, g.Item.Version)
require.Error(err)
apiErr = api.AsServerError(err)
require.NotNil(apiErr)
assert.EqualValues(http.StatusBadRequest, apiErr.Status)
})
}
+49 -51
View File
@@ -9,8 +9,6 @@ import (
"net/url"
"time"
"github.com/kr/pretty"
"github.com/hashicorp/boundary/api"
"github.com/hashicorp/boundary/api/scopes"
)
@@ -109,18 +107,18 @@ func (c *Client) ApiClient() *api.Client {
return c.client
}
func (c *Client) Create(ctx context.Context, resourceType string, scopeId string, opt ...Option) (*HostCatalogCreateResult, *api.Error, error) {
func (c *Client) Create(ctx context.Context, resourceType string, scopeId string, opt ...Option) (*HostCatalogCreateResult, error) {
if scopeId == "" {
return nil, nil, fmt.Errorf("empty scopeId value passed into Create request")
return nil, fmt.Errorf("empty scopeId value passed into Create request")
}
opts, apiOpts := getOpts(opt...)
if c.client == nil {
return nil, nil, fmt.Errorf("nil client")
return nil, fmt.Errorf("nil client")
}
if resourceType == "" {
return nil, nil, fmt.Errorf("empty resourceType value passed into Create request")
return nil, fmt.Errorf("empty resourceType value passed into Create request")
} else {
opts.postMap["type"] = resourceType
}
@@ -129,7 +127,7 @@ func (c *Client) Create(ctx context.Context, resourceType string, scopeId string
req, err := c.client.NewRequest(ctx, "POST", "host-catalogs", opts.postMap, apiOpts...)
if err != nil {
return nil, nil, fmt.Errorf("error creating Create request: %w", err)
return nil, fmt.Errorf("error creating Create request: %w", err)
}
if len(opts.queryMap) > 0 {
@@ -142,36 +140,36 @@ func (c *Client) Create(ctx context.Context, resourceType string, scopeId string
resp, err := c.client.Do(req)
if err != nil {
return nil, nil, fmt.Errorf("error performing client request during Create call: %w", err)
return nil, fmt.Errorf("error performing client request during Create call: %w", err)
}
target := new(HostCatalogCreateResult)
target.Item = new(HostCatalog)
apiErr, err := resp.Decode(target.Item)
if err != nil {
return nil, nil, fmt.Errorf("error decoding Create response: %w", err)
return nil, fmt.Errorf("error decoding Create response: %w", err)
}
if apiErr != nil {
return nil, apiErr, nil
return nil, apiErr
}
target.responseBody = resp.Body
target.responseMap = resp.Map
return target, apiErr, nil
return target, nil
}
func (c *Client) Read(ctx context.Context, hostCatalogId string, opt ...Option) (*HostCatalogReadResult, *api.Error, error) {
func (c *Client) Read(ctx context.Context, hostCatalogId string, opt ...Option) (*HostCatalogReadResult, error) {
if hostCatalogId == "" {
return nil, nil, fmt.Errorf("empty hostCatalogId value passed into Read request")
return nil, fmt.Errorf("empty hostCatalogId value passed into Read request")
}
if c.client == nil {
return nil, nil, fmt.Errorf("nil client")
return nil, fmt.Errorf("nil client")
}
opts, apiOpts := getOpts(opt...)
req, err := c.client.NewRequest(ctx, "GET", fmt.Sprintf("host-catalogs/%s", hostCatalogId), nil, apiOpts...)
if err != nil {
return nil, nil, fmt.Errorf("error creating Read request: %w", err)
return nil, fmt.Errorf("error creating Read request: %w", err)
}
if len(opts.queryMap) > 0 {
@@ -184,49 +182,49 @@ func (c *Client) Read(ctx context.Context, hostCatalogId string, opt ...Option)
resp, err := c.client.Do(req)
if err != nil {
return nil, nil, fmt.Errorf("error performing client request during Read call: %w", err)
return nil, fmt.Errorf("error performing client request during Read call: %w", err)
}
target := new(HostCatalogReadResult)
target.Item = new(HostCatalog)
apiErr, err := resp.Decode(target.Item)
if err != nil {
return nil, nil, fmt.Errorf("error decoding Read response: %w", err)
return nil, fmt.Errorf("error decoding Read response: %w", err)
}
if apiErr != nil {
return nil, apiErr, nil
return nil, apiErr
}
target.responseBody = resp.Body
target.responseMap = resp.Map
return target, apiErr, nil
return target, nil
}
func (c *Client) Update(ctx context.Context, hostCatalogId string, version uint32, opt ...Option) (*HostCatalogUpdateResult, *api.Error, error) {
func (c *Client) Update(ctx context.Context, hostCatalogId string, version uint32, opt ...Option) (*HostCatalogUpdateResult, error) {
if hostCatalogId == "" {
return nil, nil, fmt.Errorf("empty hostCatalogId value passed into Update request")
return nil, fmt.Errorf("empty hostCatalogId value passed into Update request")
}
if c.client == nil {
return nil, nil, fmt.Errorf("nil client")
return nil, fmt.Errorf("nil client")
}
opts, apiOpts := getOpts(opt...)
if version == 0 {
if !opts.withAutomaticVersioning {
return nil, nil, errors.New("zero version number passed into Update request and automatic versioning not specified")
return nil, errors.New("zero version number passed into Update request and automatic versioning not specified")
}
existingTarget, existingApiErr, existingErr := c.Read(ctx, hostCatalogId, opt...)
existingTarget, existingErr := c.Read(ctx, hostCatalogId, opt...)
if existingErr != nil {
return nil, nil, fmt.Errorf("error performing initial check-and-set read: %w", existingErr)
}
if existingApiErr != nil {
return nil, nil, fmt.Errorf("error from controller when performing initial check-and-set read: %s", pretty.Sprint(existingApiErr))
if api.AsServerError(existingErr) != nil {
return nil, fmt.Errorf("error from controller when performing initial check-and-set read: %w", existingErr)
}
return nil, fmt.Errorf("error performing initial check-and-set read: %w", existingErr)
}
if existingTarget == nil {
return nil, nil, errors.New("nil resource response found when performing initial check-and-set read")
return nil, errors.New("nil resource response found when performing initial check-and-set read")
}
if existingTarget.Item == nil {
return nil, nil, errors.New("nil resource found when performing initial check-and-set read")
return nil, errors.New("nil resource found when performing initial check-and-set read")
}
version = existingTarget.Item.Version
}
@@ -235,7 +233,7 @@ func (c *Client) Update(ctx context.Context, hostCatalogId string, version uint3
req, err := c.client.NewRequest(ctx, "PATCH", fmt.Sprintf("host-catalogs/%s", hostCatalogId), opts.postMap, apiOpts...)
if err != nil {
return nil, nil, fmt.Errorf("error creating Update request: %w", err)
return nil, fmt.Errorf("error creating Update request: %w", err)
}
if len(opts.queryMap) > 0 {
@@ -248,36 +246,36 @@ func (c *Client) Update(ctx context.Context, hostCatalogId string, version uint3
resp, err := c.client.Do(req)
if err != nil {
return nil, nil, fmt.Errorf("error performing client request during Update call: %w", err)
return nil, fmt.Errorf("error performing client request during Update call: %w", err)
}
target := new(HostCatalogUpdateResult)
target.Item = new(HostCatalog)
apiErr, err := resp.Decode(target.Item)
if err != nil {
return nil, nil, fmt.Errorf("error decoding Update response: %w", err)
return nil, fmt.Errorf("error decoding Update response: %w", err)
}
if apiErr != nil {
return nil, apiErr, nil
return nil, apiErr
}
target.responseBody = resp.Body
target.responseMap = resp.Map
return target, apiErr, nil
return target, nil
}
func (c *Client) Delete(ctx context.Context, hostCatalogId string, opt ...Option) (*HostCatalogDeleteResult, *api.Error, error) {
func (c *Client) Delete(ctx context.Context, hostCatalogId string, opt ...Option) (*HostCatalogDeleteResult, error) {
if hostCatalogId == "" {
return nil, nil, fmt.Errorf("empty hostCatalogId value passed into Delete request")
return nil, fmt.Errorf("empty hostCatalogId value passed into Delete request")
}
if c.client == nil {
return nil, nil, fmt.Errorf("nil client")
return nil, fmt.Errorf("nil client")
}
opts, apiOpts := getOpts(opt...)
req, err := c.client.NewRequest(ctx, "DELETE", fmt.Sprintf("host-catalogs/%s", hostCatalogId), nil, apiOpts...)
if err != nil {
return nil, nil, fmt.Errorf("error creating Delete request: %w", err)
return nil, fmt.Errorf("error creating Delete request: %w", err)
}
if len(opts.queryMap) > 0 {
@@ -290,30 +288,30 @@ func (c *Client) Delete(ctx context.Context, hostCatalogId string, opt ...Option
resp, err := c.client.Do(req)
if err != nil {
return nil, nil, fmt.Errorf("error performing client request during Delete call: %w", err)
return nil, fmt.Errorf("error performing client request during Delete call: %w", err)
}
apiErr, err := resp.Decode(nil)
if err != nil {
return nil, nil, fmt.Errorf("error decoding Delete response: %w", err)
return nil, fmt.Errorf("error decoding Delete response: %w", err)
}
if apiErr != nil {
return nil, apiErr, nil
return nil, apiErr
}
target := &HostCatalogDeleteResult{
responseBody: resp.Body,
responseMap: resp.Map,
}
return target, nil, nil
return target, nil
}
func (c *Client) List(ctx context.Context, scopeId string, opt ...Option) (*HostCatalogListResult, *api.Error, error) {
func (c *Client) List(ctx context.Context, scopeId string, opt ...Option) (*HostCatalogListResult, error) {
if scopeId == "" {
return nil, nil, fmt.Errorf("empty scopeId value passed into List request")
return nil, fmt.Errorf("empty scopeId value passed into List request")
}
if c.client == nil {
return nil, nil, fmt.Errorf("nil client")
return nil, fmt.Errorf("nil client")
}
opts, apiOpts := getOpts(opt...)
@@ -321,7 +319,7 @@ func (c *Client) List(ctx context.Context, scopeId string, opt ...Option) (*Host
req, err := c.client.NewRequest(ctx, "GET", "host-catalogs", nil, apiOpts...)
if err != nil {
return nil, nil, fmt.Errorf("error creating List request: %w", err)
return nil, fmt.Errorf("error creating List request: %w", err)
}
if len(opts.queryMap) > 0 {
@@ -334,18 +332,18 @@ func (c *Client) List(ctx context.Context, scopeId string, opt ...Option) (*Host
resp, err := c.client.Do(req)
if err != nil {
return nil, nil, fmt.Errorf("error performing client request during List call: %w", err)
return nil, fmt.Errorf("error performing client request during List call: %w", err)
}
target := new(HostCatalogListResult)
apiErr, err := resp.Decode(target)
if err != nil {
return nil, nil, fmt.Errorf("error decoding List response: %w", err)
return nil, fmt.Errorf("error decoding List response: %w", err)
}
if apiErr != nil {
return nil, apiErr, nil
return nil, apiErr
}
target.responseBody = resp.Body
target.responseMap = resp.Map
return target, apiErr, nil
return target, nil
}
+32 -37
View File
@@ -25,9 +25,8 @@ func TestList(t *testing.T) {
_, proj := iam.TestScopes(t, tc.IamRepo(), iam.WithUserId(token.UserId))
catalogClient := hostcatalogs.NewClient(client)
ul, apiErr, err := catalogClient.List(tc.Context(), proj.GetPublicId())
ul, err := catalogClient.List(tc.Context(), proj.GetPublicId())
require.NoError(err)
require.Nil(apiErr)
assert.Empty(ul.Items)
var expected []*hostcatalogs.HostCatalog
@@ -35,25 +34,21 @@ func TestList(t *testing.T) {
expected = append(expected, &hostcatalogs.HostCatalog{Name: fmt.Sprint(i)})
}
cr, apiErr, err := catalogClient.Create(tc.Context(), "static", proj.GetPublicId(), hostcatalogs.WithName(expected[0].Name))
cr, err := catalogClient.Create(tc.Context(), "static", proj.GetPublicId(), hostcatalogs.WithName(expected[0].Name))
require.NoError(err)
require.Nil(apiErr)
expected[0] = cr.Item
ul, apiErr, err = catalogClient.List(tc.Context(), proj.GetPublicId())
ul, err = catalogClient.List(tc.Context(), proj.GetPublicId())
require.NoError(err)
require.Nil(apiErr)
assert.ElementsMatch(comparableCatalogSlice(expected[:1]), comparableCatalogSlice(ul.Items))
for i := 1; i < 10; i++ {
cr, apiErr, err = catalogClient.Create(tc.Context(), "static", proj.GetPublicId(), hostcatalogs.WithName(expected[i].Name))
cr, err = catalogClient.Create(tc.Context(), "static", proj.GetPublicId(), hostcatalogs.WithName(expected[i].Name))
require.NoError(err)
require.Nil(apiErr)
expected[i] = cr.Item
}
ul, apiErr, err = catalogClient.List(tc.Context(), proj.GetPublicId())
ul, err = catalogClient.List(tc.Context(), proj.GetPublicId())
require.NoError(err)
assert.Nil(apiErr)
assert.ElementsMatch(comparableCatalogSlice(expected), comparableCatalogSlice(ul.Items))
}
@@ -82,11 +77,8 @@ func TestCrud(t *testing.T) {
client.SetToken(token.Token)
_, proj := iam.TestScopes(t, tc.IamRepo(), iam.WithUserId(token.UserId))
checkCatalog := func(step string, hc *hostcatalogs.HostCatalog, apiErr *api.Error, err error, wantedName string, wantVersion uint32) {
checkCatalog := func(step string, hc *hostcatalogs.HostCatalog, err error, wantedName string, wantVersion uint32) {
require.NoError(err, step)
if !assert.Nil(apiErr, step) && apiErr.Message != "" {
t.Errorf("ApiError message: %q", apiErr.Message)
}
assert.NotNil(hc, "returned no resource", step)
gotName := ""
if hc.Name != "" {
@@ -98,29 +90,28 @@ func TestCrud(t *testing.T) {
hcClient := hostcatalogs.NewClient(client)
hc, apiErr, err := hcClient.Create(tc.Context(), "static", proj.GetPublicId(), hostcatalogs.WithName("foo"))
checkCatalog("create", hc.Item, apiErr, err, "foo", 1)
hc, err := hcClient.Create(tc.Context(), "static", proj.GetPublicId(), hostcatalogs.WithName("foo"))
checkCatalog("create", hc.Item, err, "foo", 1)
hc, apiErr, err = hcClient.Read(tc.Context(), hc.Item.Id)
checkCatalog("read", hc.Item, apiErr, err, "foo", 1)
hc, err = hcClient.Read(tc.Context(), hc.Item.Id)
checkCatalog("read", hc.Item, err, "foo", 1)
hc, apiErr, err = hcClient.Update(tc.Context(), hc.Item.Id, hc.Item.Version, hostcatalogs.WithName("bar"))
checkCatalog("update", hc.Item, apiErr, err, "bar", 2)
hc, err = hcClient.Update(tc.Context(), hc.Item.Id, hc.Item.Version, hostcatalogs.WithName("bar"))
checkCatalog("update", hc.Item, err, "bar", 2)
hc, apiErr, err = hcClient.Update(tc.Context(), hc.Item.Id, hc.Item.Version, hostcatalogs.DefaultName())
checkCatalog("update", hc.Item, apiErr, err, "", 3)
hc, err = hcClient.Update(tc.Context(), hc.Item.Id, hc.Item.Version, hostcatalogs.DefaultName())
checkCatalog("update", hc.Item, err, "", 3)
_, apiErr, err = hcClient.Delete(tc.Context(), hc.Item.Id)
_, err = hcClient.Delete(tc.Context(), hc.Item.Id)
assert.NoError(err)
assert.Nil(apiErr)
_, apiErr, err = hcClient.Delete(tc.Context(), hc.Item.Id)
require.NoError(err)
_, err = hcClient.Delete(tc.Context(), hc.Item.Id)
require.Error(err)
apiErr := api.AsServerError(err)
assert.NotNil(apiErr)
assert.EqualValues(http.StatusNotFound, apiErr.Status)
}
// TODO: Get better coverage for expected errors and error formats.
func TestErrors(t *testing.T) {
assert, require := assert.New(t), require.New(t)
tc := controller.NewTestController(t, nil)
@@ -132,29 +123,33 @@ func TestErrors(t *testing.T) {
_, proj := iam.TestScopes(t, tc.IamRepo(), iam.WithUserId(token.UserId))
pc := hostcatalogs.NewClient(client)
hc, apiErr, err := pc.Create(tc.Context(), "static", proj.GetPublicId(), hostcatalogs.WithName("foo"))
hc, err := pc.Create(tc.Context(), "static", proj.GetPublicId(), hostcatalogs.WithName("foo"))
require.NoError(err)
apiErr := api.AsServerError(err)
assert.Nil(apiErr)
assert.NotNil(hc)
// Updating the wrong version should fail.
_, apiErr, err = pc.Update(tc.Context(), hc.Item.Id, 73, hostcatalogs.WithName("anything"))
require.NoError(err)
_, err = pc.Update(tc.Context(), hc.Item.Id, 73, hostcatalogs.WithName("anything"))
require.Error(err)
apiErr = api.AsServerError(err)
assert.NotNil(apiErr)
assert.EqualValues(http.StatusNotFound, apiErr.Status)
_, apiErr, err = pc.Create(tc.Context(), "static", proj.GetPublicId(), hostcatalogs.WithName("foo"))
require.NoError(err)
_, err = pc.Create(tc.Context(), "static", proj.GetPublicId(), hostcatalogs.WithName("foo"))
require.Error(err)
apiErr = api.AsServerError(err)
assert.NotNil(apiErr)
_, apiErr, err = pc.Read(tc.Context(), static.HostCatalogPrefix+"_doesntexis")
require.NoError(err)
// TODO: Should this be nil instead of just a catalog that has no values set
_, err = pc.Read(tc.Context(), static.HostCatalogPrefix+"_doesntexis")
require.Error(err)
apiErr = api.AsServerError(err)
assert.NotNil(apiErr)
assert.EqualValues(http.StatusNotFound, apiErr.Status)
_, apiErr, err = pc.Read(tc.Context(), "invalid id")
require.NoError(err)
_, err = pc.Read(tc.Context(), "invalid id")
require.Error(err)
apiErr = api.AsServerError(err)
assert.NotNil(apiErr)
assert.EqualValues(http.StatusBadRequest, apiErr.Status)
}
+48 -50
View File
@@ -9,8 +9,6 @@ import (
"net/url"
"time"
"github.com/kr/pretty"
"github.com/hashicorp/boundary/api"
"github.com/hashicorp/boundary/api/scopes"
)
@@ -110,22 +108,22 @@ func (c *Client) ApiClient() *api.Client {
return c.client
}
func (c *Client) Create(ctx context.Context, hostCatalogId string, opt ...Option) (*HostCreateResult, *api.Error, error) {
func (c *Client) Create(ctx context.Context, hostCatalogId string, opt ...Option) (*HostCreateResult, error) {
if hostCatalogId == "" {
return nil, nil, fmt.Errorf("empty hostCatalogId value passed into Create request")
return nil, fmt.Errorf("empty hostCatalogId value passed into Create request")
}
opts, apiOpts := getOpts(opt...)
if c.client == nil {
return nil, nil, fmt.Errorf("nil client")
return nil, fmt.Errorf("nil client")
}
opts.postMap["host_catalog_id"] = hostCatalogId
req, err := c.client.NewRequest(ctx, "POST", "hosts", opts.postMap, apiOpts...)
if err != nil {
return nil, nil, fmt.Errorf("error creating Create request: %w", err)
return nil, fmt.Errorf("error creating Create request: %w", err)
}
if len(opts.queryMap) > 0 {
@@ -138,36 +136,36 @@ func (c *Client) Create(ctx context.Context, hostCatalogId string, opt ...Option
resp, err := c.client.Do(req)
if err != nil {
return nil, nil, fmt.Errorf("error performing client request during Create call: %w", err)
return nil, fmt.Errorf("error performing client request during Create call: %w", err)
}
target := new(HostCreateResult)
target.Item = new(Host)
apiErr, err := resp.Decode(target.Item)
if err != nil {
return nil, nil, fmt.Errorf("error decoding Create response: %w", err)
return nil, fmt.Errorf("error decoding Create response: %w", err)
}
if apiErr != nil {
return nil, apiErr, nil
return nil, apiErr
}
target.responseBody = resp.Body
target.responseMap = resp.Map
return target, apiErr, nil
return target, nil
}
func (c *Client) Read(ctx context.Context, hostId string, opt ...Option) (*HostReadResult, *api.Error, error) {
func (c *Client) Read(ctx context.Context, hostId string, opt ...Option) (*HostReadResult, error) {
if hostId == "" {
return nil, nil, fmt.Errorf("empty hostId value passed into Read request")
return nil, fmt.Errorf("empty hostId value passed into Read request")
}
if c.client == nil {
return nil, nil, fmt.Errorf("nil client")
return nil, fmt.Errorf("nil client")
}
opts, apiOpts := getOpts(opt...)
req, err := c.client.NewRequest(ctx, "GET", fmt.Sprintf("hosts/%s", hostId), nil, apiOpts...)
if err != nil {
return nil, nil, fmt.Errorf("error creating Read request: %w", err)
return nil, fmt.Errorf("error creating Read request: %w", err)
}
if len(opts.queryMap) > 0 {
@@ -180,49 +178,49 @@ func (c *Client) Read(ctx context.Context, hostId string, opt ...Option) (*HostR
resp, err := c.client.Do(req)
if err != nil {
return nil, nil, fmt.Errorf("error performing client request during Read call: %w", err)
return nil, fmt.Errorf("error performing client request during Read call: %w", err)
}
target := new(HostReadResult)
target.Item = new(Host)
apiErr, err := resp.Decode(target.Item)
if err != nil {
return nil, nil, fmt.Errorf("error decoding Read response: %w", err)
return nil, fmt.Errorf("error decoding Read response: %w", err)
}
if apiErr != nil {
return nil, apiErr, nil
return nil, apiErr
}
target.responseBody = resp.Body
target.responseMap = resp.Map
return target, apiErr, nil
return target, nil
}
func (c *Client) Update(ctx context.Context, hostId string, version uint32, opt ...Option) (*HostUpdateResult, *api.Error, error) {
func (c *Client) Update(ctx context.Context, hostId string, version uint32, opt ...Option) (*HostUpdateResult, error) {
if hostId == "" {
return nil, nil, fmt.Errorf("empty hostId value passed into Update request")
return nil, fmt.Errorf("empty hostId value passed into Update request")
}
if c.client == nil {
return nil, nil, fmt.Errorf("nil client")
return nil, fmt.Errorf("nil client")
}
opts, apiOpts := getOpts(opt...)
if version == 0 {
if !opts.withAutomaticVersioning {
return nil, nil, errors.New("zero version number passed into Update request and automatic versioning not specified")
return nil, errors.New("zero version number passed into Update request and automatic versioning not specified")
}
existingTarget, existingApiErr, existingErr := c.Read(ctx, hostId, opt...)
existingTarget, existingErr := c.Read(ctx, hostId, opt...)
if existingErr != nil {
return nil, nil, fmt.Errorf("error performing initial check-and-set read: %w", existingErr)
}
if existingApiErr != nil {
return nil, nil, fmt.Errorf("error from controller when performing initial check-and-set read: %s", pretty.Sprint(existingApiErr))
if api.AsServerError(existingErr) != nil {
return nil, fmt.Errorf("error from controller when performing initial check-and-set read: %w", existingErr)
}
return nil, fmt.Errorf("error performing initial check-and-set read: %w", existingErr)
}
if existingTarget == nil {
return nil, nil, errors.New("nil resource response found when performing initial check-and-set read")
return nil, errors.New("nil resource response found when performing initial check-and-set read")
}
if existingTarget.Item == nil {
return nil, nil, errors.New("nil resource found when performing initial check-and-set read")
return nil, errors.New("nil resource found when performing initial check-and-set read")
}
version = existingTarget.Item.Version
}
@@ -231,7 +229,7 @@ func (c *Client) Update(ctx context.Context, hostId string, version uint32, opt
req, err := c.client.NewRequest(ctx, "PATCH", fmt.Sprintf("hosts/%s", hostId), opts.postMap, apiOpts...)
if err != nil {
return nil, nil, fmt.Errorf("error creating Update request: %w", err)
return nil, fmt.Errorf("error creating Update request: %w", err)
}
if len(opts.queryMap) > 0 {
@@ -244,36 +242,36 @@ func (c *Client) Update(ctx context.Context, hostId string, version uint32, opt
resp, err := c.client.Do(req)
if err != nil {
return nil, nil, fmt.Errorf("error performing client request during Update call: %w", err)
return nil, fmt.Errorf("error performing client request during Update call: %w", err)
}
target := new(HostUpdateResult)
target.Item = new(Host)
apiErr, err := resp.Decode(target.Item)
if err != nil {
return nil, nil, fmt.Errorf("error decoding Update response: %w", err)
return nil, fmt.Errorf("error decoding Update response: %w", err)
}
if apiErr != nil {
return nil, apiErr, nil
return nil, apiErr
}
target.responseBody = resp.Body
target.responseMap = resp.Map
return target, apiErr, nil
return target, nil
}
func (c *Client) Delete(ctx context.Context, hostId string, opt ...Option) (*HostDeleteResult, *api.Error, error) {
func (c *Client) Delete(ctx context.Context, hostId string, opt ...Option) (*HostDeleteResult, error) {
if hostId == "" {
return nil, nil, fmt.Errorf("empty hostId value passed into Delete request")
return nil, fmt.Errorf("empty hostId value passed into Delete request")
}
if c.client == nil {
return nil, nil, fmt.Errorf("nil client")
return nil, fmt.Errorf("nil client")
}
opts, apiOpts := getOpts(opt...)
req, err := c.client.NewRequest(ctx, "DELETE", fmt.Sprintf("hosts/%s", hostId), nil, apiOpts...)
if err != nil {
return nil, nil, fmt.Errorf("error creating Delete request: %w", err)
return nil, fmt.Errorf("error creating Delete request: %w", err)
}
if len(opts.queryMap) > 0 {
@@ -286,30 +284,30 @@ func (c *Client) Delete(ctx context.Context, hostId string, opt ...Option) (*Hos
resp, err := c.client.Do(req)
if err != nil {
return nil, nil, fmt.Errorf("error performing client request during Delete call: %w", err)
return nil, fmt.Errorf("error performing client request during Delete call: %w", err)
}
apiErr, err := resp.Decode(nil)
if err != nil {
return nil, nil, fmt.Errorf("error decoding Delete response: %w", err)
return nil, fmt.Errorf("error decoding Delete response: %w", err)
}
if apiErr != nil {
return nil, apiErr, nil
return nil, apiErr
}
target := &HostDeleteResult{
responseBody: resp.Body,
responseMap: resp.Map,
}
return target, nil, nil
return target, nil
}
func (c *Client) List(ctx context.Context, hostCatalogId string, opt ...Option) (*HostListResult, *api.Error, error) {
func (c *Client) List(ctx context.Context, hostCatalogId string, opt ...Option) (*HostListResult, error) {
if hostCatalogId == "" {
return nil, nil, fmt.Errorf("empty hostCatalogId value passed into List request")
return nil, fmt.Errorf("empty hostCatalogId value passed into List request")
}
if c.client == nil {
return nil, nil, fmt.Errorf("nil client")
return nil, fmt.Errorf("nil client")
}
opts, apiOpts := getOpts(opt...)
@@ -317,7 +315,7 @@ func (c *Client) List(ctx context.Context, hostCatalogId string, opt ...Option)
req, err := c.client.NewRequest(ctx, "GET", "hosts", nil, apiOpts...)
if err != nil {
return nil, nil, fmt.Errorf("error creating List request: %w", err)
return nil, fmt.Errorf("error creating List request: %w", err)
}
if len(opts.queryMap) > 0 {
@@ -330,18 +328,18 @@ func (c *Client) List(ctx context.Context, hostCatalogId string, opt ...Option)
resp, err := c.client.Do(req)
if err != nil {
return nil, nil, fmt.Errorf("error performing client request during List call: %w", err)
return nil, fmt.Errorf("error performing client request during List call: %w", err)
}
target := new(HostListResult)
apiErr, err := resp.Decode(target)
if err != nil {
return nil, nil, fmt.Errorf("error decoding List response: %w", err)
return nil, fmt.Errorf("error decoding List response: %w", err)
}
if apiErr != nil {
return nil, apiErr, nil
return nil, apiErr
}
target.responseBody = resp.Body
target.responseMap = resp.Map
return target, apiErr, nil
return target, nil
}
+34 -43
View File
@@ -25,16 +25,14 @@ func TestList(t *testing.T) {
client.SetToken(token.Token)
_, proj := iam.TestScopes(t, tc.IamRepo(), iam.WithUserId(token.UserId))
hc, apiErr, err := hostcatalogs.NewClient(client).Create(tc.Context(), "static", proj.GetPublicId())
hc, err := hostcatalogs.NewClient(client).Create(tc.Context(), "static", proj.GetPublicId())
require.NoError(err)
require.Nil(apiErr)
require.NotNil(hc)
hClient := hosts.NewClient(client)
ul, apiErr, err := hClient.List(tc.Context(), hc.Item.Id)
ul, err := hClient.List(tc.Context(), hc.Item.Id)
assert.NoError(err)
assert.Nil(apiErr)
assert.Empty(ul.Items)
var expected []*hosts.Host
@@ -42,25 +40,21 @@ func TestList(t *testing.T) {
expected = append(expected, &hosts.Host{Name: fmt.Sprint(i)})
}
hcr, apiErr, err := hClient.Create(tc.Context(), hc.Item.Id, hosts.WithName(expected[0].Name), hosts.WithStaticHostAddress("someaddress"))
hcr, err := hClient.Create(tc.Context(), hc.Item.Id, hosts.WithName(expected[0].Name), hosts.WithStaticHostAddress("someaddress"))
assert.NoError(err)
assert.Nil(apiErr)
expected[0] = hcr.Item
ul, apiErr, err = hClient.List(tc.Context(), hc.Item.Id)
ul, err = hClient.List(tc.Context(), hc.Item.Id)
assert.NoError(err)
assert.Nil(apiErr)
assert.ElementsMatch(comparableHostSlice(expected[:1]), comparableHostSlice(ul.Items))
for i := 1; i < 10; i++ {
hcr, apiErr, err = hClient.Create(tc.Context(), hc.Item.Id, hosts.WithName(expected[i].Name), hosts.WithStaticHostAddress("someaddress"))
hcr, err = hClient.Create(tc.Context(), hc.Item.Id, hosts.WithName(expected[i].Name), hosts.WithStaticHostAddress("someaddress"))
assert.NoError(err)
assert.Nil(apiErr)
expected[i] = hcr.Item
}
ul, apiErr, err = hClient.List(tc.Context(), hc.Item.Id)
ul, err = hClient.List(tc.Context(), hc.Item.Id)
require.NoError(err)
assert.Nil(apiErr)
assert.ElementsMatch(comparableHostSlice(expected), comparableHostSlice(ul.Items))
}
@@ -89,16 +83,12 @@ func TestCrud(t *testing.T) {
client.SetToken(token.Token)
_, proj := iam.TestScopes(t, tc.IamRepo(), iam.WithUserId(token.UserId))
hc, apiErr, err := hostcatalogs.NewClient(client).Create(tc.Context(), "static", proj.GetPublicId())
hc, err := hostcatalogs.NewClient(client).Create(tc.Context(), "static", proj.GetPublicId())
require.NoError(err)
require.Nil(apiErr)
require.NotNil(hc)
checkHost := func(step string, h *hosts.Host, apiErr *api.Error, err error, wantedName string, wantVersion uint32) {
checkHost := func(step string, h *hosts.Host, err error, wantedName string, wantVersion uint32) {
require.NoError(err, step)
if !assert.Nil(apiErr, step) && apiErr.Message != "" {
t.Errorf("ApiError message: %q", apiErr.Message)
}
assert.NotNil(h, "returned no resource", step)
gotName := ""
if h.Name != "" {
@@ -110,29 +100,28 @@ func TestCrud(t *testing.T) {
hClient := hosts.NewClient(client)
h, apiErr, err := hClient.Create(tc.Context(), hc.Item.Id, hosts.WithName("foo"), hosts.WithStaticHostAddress("someaddress"))
checkHost("create", h.Item, apiErr, err, "foo", 1)
h, err := hClient.Create(tc.Context(), hc.Item.Id, hosts.WithName("foo"), hosts.WithStaticHostAddress("someaddress"))
checkHost("create", h.Item, err, "foo", 1)
h, apiErr, err = hClient.Read(tc.Context(), h.Item.Id)
checkHost("read", h.Item, apiErr, err, "foo", 1)
h, err = hClient.Read(tc.Context(), h.Item.Id)
checkHost("read", h.Item, err, "foo", 1)
h, apiErr, err = hClient.Update(tc.Context(), h.Item.Id, h.Item.Version, hosts.WithName("bar"))
checkHost("update", h.Item, apiErr, err, "bar", 2)
h, err = hClient.Update(tc.Context(), h.Item.Id, h.Item.Version, hosts.WithName("bar"))
checkHost("update", h.Item, err, "bar", 2)
h, apiErr, err = hClient.Update(tc.Context(), h.Item.Id, h.Item.Version, hosts.DefaultName())
checkHost("update", h.Item, apiErr, err, "", 3)
h, err = hClient.Update(tc.Context(), h.Item.Id, h.Item.Version, hosts.DefaultName())
checkHost("update", h.Item, err, "", 3)
_, apiErr, err = hClient.Delete(tc.Context(), h.Item.Id)
_, err = hClient.Delete(tc.Context(), h.Item.Id)
assert.NoError(err)
assert.Nil(apiErr)
_, apiErr, err = hClient.Delete(tc.Context(), h.Item.Id)
require.NoError(err)
_, err = hClient.Delete(tc.Context(), h.Item.Id)
require.Error(err)
apiErr := api.AsServerError(err)
assert.NotNil(apiErr)
assert.EqualValues(http.StatusNotFound, apiErr.Status)
}
// TODO: Get better coverage for expected errors and error formats.
func TestErrors(t *testing.T) {
assert, require := assert.New(t), require.New(t)
tc := controller.NewTestController(t, nil)
@@ -143,35 +132,37 @@ func TestErrors(t *testing.T) {
client.SetToken(token.Token)
_, proj := iam.TestScopes(t, tc.IamRepo(), iam.WithUserId(token.UserId))
hc, apiErr, err := hostcatalogs.NewClient(client).Create(tc.Context(), "static", proj.GetPublicId())
hc, err := hostcatalogs.NewClient(client).Create(tc.Context(), "static", proj.GetPublicId())
require.NoError(err)
require.Nil(apiErr)
require.NotNil(hc)
hClient := hosts.NewClient(client)
h, apiErr, err := hClient.Create(tc.Context(), hc.Item.Id, hosts.WithName("foo"), hosts.WithStaticHostAddress("someaddress"))
h, err := hClient.Create(tc.Context(), hc.Item.Id, hosts.WithName("foo"), hosts.WithStaticHostAddress("someaddress"))
require.NoError(err)
require.Nil(apiErr)
assert.NotNil(h)
// Updating the wrong version should fail.
_, apiErr, err = hClient.Update(tc.Context(), h.Item.Id, 73, hosts.WithName("anything"))
require.NoError(err)
_, err = hClient.Update(tc.Context(), h.Item.Id, 73, hosts.WithName("anything"))
require.Error(err)
apiErr := api.AsServerError(err)
assert.NotNil(apiErr)
assert.EqualValues(http.StatusNotFound, apiErr.Status)
_, apiErr, err = hClient.Create(tc.Context(), hc.Item.Id, hosts.WithName("foo"), hosts.WithStaticHostAddress("someaddress"))
require.NoError(err)
_, err = hClient.Create(tc.Context(), hc.Item.Id, hosts.WithName("foo"), hosts.WithStaticHostAddress("someaddress"))
require.Error(err)
apiErr = api.AsServerError(err)
assert.NotNil(apiErr)
_, apiErr, err = hClient.Read(tc.Context(), static.HostPrefix+"_doesntexis")
require.NoError(err)
_, err = hClient.Read(tc.Context(), static.HostPrefix+"_doesntexis")
require.Error(err)
apiErr = api.AsServerError(err)
assert.NotNil(apiErr)
assert.EqualValues(http.StatusNotFound, apiErr.Status)
_, apiErr, err = hClient.Read(tc.Context(), "invalid id")
require.NoError(err)
_, err = hClient.Read(tc.Context(), "invalid id")
require.Error(err)
apiErr = api.AsServerError(err)
assert.NotNil(apiErr)
assert.EqualValues(http.StatusBadRequest, apiErr.Status)
}
+98 -100
View File
@@ -9,8 +9,6 @@ import (
"net/url"
"time"
"github.com/kr/pretty"
"github.com/hashicorp/boundary/api"
"github.com/hashicorp/boundary/api/scopes"
)
@@ -110,22 +108,22 @@ func (c *Client) ApiClient() *api.Client {
return c.client
}
func (c *Client) Create(ctx context.Context, hostCatalogId string, opt ...Option) (*HostSetCreateResult, *api.Error, error) {
func (c *Client) Create(ctx context.Context, hostCatalogId string, opt ...Option) (*HostSetCreateResult, error) {
if hostCatalogId == "" {
return nil, nil, fmt.Errorf("empty hostCatalogId value passed into Create request")
return nil, fmt.Errorf("empty hostCatalogId value passed into Create request")
}
opts, apiOpts := getOpts(opt...)
if c.client == nil {
return nil, nil, fmt.Errorf("nil client")
return nil, fmt.Errorf("nil client")
}
opts.postMap["host_catalog_id"] = hostCatalogId
req, err := c.client.NewRequest(ctx, "POST", "host-sets", opts.postMap, apiOpts...)
if err != nil {
return nil, nil, fmt.Errorf("error creating Create request: %w", err)
return nil, fmt.Errorf("error creating Create request: %w", err)
}
if len(opts.queryMap) > 0 {
@@ -138,36 +136,36 @@ func (c *Client) Create(ctx context.Context, hostCatalogId string, opt ...Option
resp, err := c.client.Do(req)
if err != nil {
return nil, nil, fmt.Errorf("error performing client request during Create call: %w", err)
return nil, fmt.Errorf("error performing client request during Create call: %w", err)
}
target := new(HostSetCreateResult)
target.Item = new(HostSet)
apiErr, err := resp.Decode(target.Item)
if err != nil {
return nil, nil, fmt.Errorf("error decoding Create response: %w", err)
return nil, fmt.Errorf("error decoding Create response: %w", err)
}
if apiErr != nil {
return nil, apiErr, nil
return nil, apiErr
}
target.responseBody = resp.Body
target.responseMap = resp.Map
return target, apiErr, nil
return target, nil
}
func (c *Client) Read(ctx context.Context, hostSetId string, opt ...Option) (*HostSetReadResult, *api.Error, error) {
func (c *Client) Read(ctx context.Context, hostSetId string, opt ...Option) (*HostSetReadResult, error) {
if hostSetId == "" {
return nil, nil, fmt.Errorf("empty hostSetId value passed into Read request")
return nil, fmt.Errorf("empty hostSetId value passed into Read request")
}
if c.client == nil {
return nil, nil, fmt.Errorf("nil client")
return nil, fmt.Errorf("nil client")
}
opts, apiOpts := getOpts(opt...)
req, err := c.client.NewRequest(ctx, "GET", fmt.Sprintf("host-sets/%s", hostSetId), nil, apiOpts...)
if err != nil {
return nil, nil, fmt.Errorf("error creating Read request: %w", err)
return nil, fmt.Errorf("error creating Read request: %w", err)
}
if len(opts.queryMap) > 0 {
@@ -180,49 +178,49 @@ func (c *Client) Read(ctx context.Context, hostSetId string, opt ...Option) (*Ho
resp, err := c.client.Do(req)
if err != nil {
return nil, nil, fmt.Errorf("error performing client request during Read call: %w", err)
return nil, fmt.Errorf("error performing client request during Read call: %w", err)
}
target := new(HostSetReadResult)
target.Item = new(HostSet)
apiErr, err := resp.Decode(target.Item)
if err != nil {
return nil, nil, fmt.Errorf("error decoding Read response: %w", err)
return nil, fmt.Errorf("error decoding Read response: %w", err)
}
if apiErr != nil {
return nil, apiErr, nil
return nil, apiErr
}
target.responseBody = resp.Body
target.responseMap = resp.Map
return target, apiErr, nil
return target, nil
}
func (c *Client) Update(ctx context.Context, hostSetId string, version uint32, opt ...Option) (*HostSetUpdateResult, *api.Error, error) {
func (c *Client) Update(ctx context.Context, hostSetId string, version uint32, opt ...Option) (*HostSetUpdateResult, error) {
if hostSetId == "" {
return nil, nil, fmt.Errorf("empty hostSetId value passed into Update request")
return nil, fmt.Errorf("empty hostSetId value passed into Update request")
}
if c.client == nil {
return nil, nil, fmt.Errorf("nil client")
return nil, fmt.Errorf("nil client")
}
opts, apiOpts := getOpts(opt...)
if version == 0 {
if !opts.withAutomaticVersioning {
return nil, nil, errors.New("zero version number passed into Update request and automatic versioning not specified")
return nil, errors.New("zero version number passed into Update request and automatic versioning not specified")
}
existingTarget, existingApiErr, existingErr := c.Read(ctx, hostSetId, opt...)
existingTarget, existingErr := c.Read(ctx, hostSetId, opt...)
if existingErr != nil {
return nil, nil, fmt.Errorf("error performing initial check-and-set read: %w", existingErr)
}
if existingApiErr != nil {
return nil, nil, fmt.Errorf("error from controller when performing initial check-and-set read: %s", pretty.Sprint(existingApiErr))
if api.AsServerError(existingErr) != nil {
return nil, fmt.Errorf("error from controller when performing initial check-and-set read: %w", existingErr)
}
return nil, fmt.Errorf("error performing initial check-and-set read: %w", existingErr)
}
if existingTarget == nil {
return nil, nil, errors.New("nil resource response found when performing initial check-and-set read")
return nil, errors.New("nil resource response found when performing initial check-and-set read")
}
if existingTarget.Item == nil {
return nil, nil, errors.New("nil resource found when performing initial check-and-set read")
return nil, errors.New("nil resource found when performing initial check-and-set read")
}
version = existingTarget.Item.Version
}
@@ -231,7 +229,7 @@ func (c *Client) Update(ctx context.Context, hostSetId string, version uint32, o
req, err := c.client.NewRequest(ctx, "PATCH", fmt.Sprintf("host-sets/%s", hostSetId), opts.postMap, apiOpts...)
if err != nil {
return nil, nil, fmt.Errorf("error creating Update request: %w", err)
return nil, fmt.Errorf("error creating Update request: %w", err)
}
if len(opts.queryMap) > 0 {
@@ -244,36 +242,36 @@ func (c *Client) Update(ctx context.Context, hostSetId string, version uint32, o
resp, err := c.client.Do(req)
if err != nil {
return nil, nil, fmt.Errorf("error performing client request during Update call: %w", err)
return nil, fmt.Errorf("error performing client request during Update call: %w", err)
}
target := new(HostSetUpdateResult)
target.Item = new(HostSet)
apiErr, err := resp.Decode(target.Item)
if err != nil {
return nil, nil, fmt.Errorf("error decoding Update response: %w", err)
return nil, fmt.Errorf("error decoding Update response: %w", err)
}
if apiErr != nil {
return nil, apiErr, nil
return nil, apiErr
}
target.responseBody = resp.Body
target.responseMap = resp.Map
return target, apiErr, nil
return target, nil
}
func (c *Client) Delete(ctx context.Context, hostSetId string, opt ...Option) (*HostSetDeleteResult, *api.Error, error) {
func (c *Client) Delete(ctx context.Context, hostSetId string, opt ...Option) (*HostSetDeleteResult, error) {
if hostSetId == "" {
return nil, nil, fmt.Errorf("empty hostSetId value passed into Delete request")
return nil, fmt.Errorf("empty hostSetId value passed into Delete request")
}
if c.client == nil {
return nil, nil, fmt.Errorf("nil client")
return nil, fmt.Errorf("nil client")
}
opts, apiOpts := getOpts(opt...)
req, err := c.client.NewRequest(ctx, "DELETE", fmt.Sprintf("host-sets/%s", hostSetId), nil, apiOpts...)
if err != nil {
return nil, nil, fmt.Errorf("error creating Delete request: %w", err)
return nil, fmt.Errorf("error creating Delete request: %w", err)
}
if len(opts.queryMap) > 0 {
@@ -286,30 +284,30 @@ func (c *Client) Delete(ctx context.Context, hostSetId string, opt ...Option) (*
resp, err := c.client.Do(req)
if err != nil {
return nil, nil, fmt.Errorf("error performing client request during Delete call: %w", err)
return nil, fmt.Errorf("error performing client request during Delete call: %w", err)
}
apiErr, err := resp.Decode(nil)
if err != nil {
return nil, nil, fmt.Errorf("error decoding Delete response: %w", err)
return nil, fmt.Errorf("error decoding Delete response: %w", err)
}
if apiErr != nil {
return nil, apiErr, nil
return nil, apiErr
}
target := &HostSetDeleteResult{
responseBody: resp.Body,
responseMap: resp.Map,
}
return target, nil, nil
return target, nil
}
func (c *Client) List(ctx context.Context, hostCatalogId string, opt ...Option) (*HostSetListResult, *api.Error, error) {
func (c *Client) List(ctx context.Context, hostCatalogId string, opt ...Option) (*HostSetListResult, error) {
if hostCatalogId == "" {
return nil, nil, fmt.Errorf("empty hostCatalogId value passed into List request")
return nil, fmt.Errorf("empty hostCatalogId value passed into List request")
}
if c.client == nil {
return nil, nil, fmt.Errorf("nil client")
return nil, fmt.Errorf("nil client")
}
opts, apiOpts := getOpts(opt...)
@@ -317,7 +315,7 @@ func (c *Client) List(ctx context.Context, hostCatalogId string, opt ...Option)
req, err := c.client.NewRequest(ctx, "GET", "host-sets", nil, apiOpts...)
if err != nil {
return nil, nil, fmt.Errorf("error creating List request: %w", err)
return nil, fmt.Errorf("error creating List request: %w", err)
}
if len(opts.queryMap) > 0 {
@@ -330,51 +328,51 @@ func (c *Client) List(ctx context.Context, hostCatalogId string, opt ...Option)
resp, err := c.client.Do(req)
if err != nil {
return nil, nil, fmt.Errorf("error performing client request during List call: %w", err)
return nil, fmt.Errorf("error performing client request during List call: %w", err)
}
target := new(HostSetListResult)
apiErr, err := resp.Decode(target)
if err != nil {
return nil, nil, fmt.Errorf("error decoding List response: %w", err)
return nil, fmt.Errorf("error decoding List response: %w", err)
}
if apiErr != nil {
return nil, apiErr, nil
return nil, apiErr
}
target.responseBody = resp.Body
target.responseMap = resp.Map
return target, apiErr, nil
return target, nil
}
func (c *Client) AddHosts(ctx context.Context, hostSetId string, version uint32, hostIds []string, opt ...Option) (*HostSetUpdateResult, *api.Error, error) {
func (c *Client) AddHosts(ctx context.Context, hostSetId string, version uint32, hostIds []string, opt ...Option) (*HostSetUpdateResult, error) {
if hostSetId == "" {
return nil, nil, fmt.Errorf("empty hostSetId value passed into AddHosts request")
return nil, fmt.Errorf("empty hostSetId value passed into AddHosts request")
}
if len(hostIds) == 0 {
return nil, nil, errors.New("empty hostIds passed into AddHosts request")
return nil, errors.New("empty hostIds passed into AddHosts request")
}
if c.client == nil {
return nil, nil, errors.New("nil client")
return nil, errors.New("nil client")
}
opts, apiOpts := getOpts(opt...)
if version == 0 {
if !opts.withAutomaticVersioning {
return nil, nil, errors.New("zero version number passed into AddHosts request")
return nil, errors.New("zero version number passed into AddHosts request")
}
existingTarget, existingApiErr, existingErr := c.Read(ctx, hostSetId, opt...)
existingTarget, existingErr := c.Read(ctx, hostSetId, opt...)
if existingErr != nil {
return nil, nil, fmt.Errorf("error performing initial check-and-set read: %w", existingErr)
}
if existingApiErr != nil {
return nil, nil, fmt.Errorf("error from controller when performing initial check-and-set read: %s", pretty.Sprint(existingApiErr))
if api.AsServerError(existingErr) != nil {
return nil, fmt.Errorf("error from controller when performing initial check-and-set read: %w", existingErr)
}
return nil, fmt.Errorf("error performing initial check-and-set read: %w", existingErr)
}
if existingTarget == nil {
return nil, nil, errors.New("nil resource response found when performing initial check-and-set read")
return nil, errors.New("nil resource response found when performing initial check-and-set read")
}
if existingTarget.Item == nil {
return nil, nil, errors.New("nil resource found when performing initial check-and-set read")
return nil, errors.New("nil resource found when performing initial check-and-set read")
}
version = existingTarget.Item.Version
}
@@ -384,7 +382,7 @@ func (c *Client) AddHosts(ctx context.Context, hostSetId string, version uint32,
req, err := c.client.NewRequest(ctx, "POST", fmt.Sprintf("host-sets/%s:add-hosts", hostSetId), opts.postMap, apiOpts...)
if err != nil {
return nil, nil, fmt.Errorf("error creating AddHosts request: %w", err)
return nil, fmt.Errorf("error creating AddHosts request: %w", err)
}
if len(opts.queryMap) > 0 {
@@ -397,50 +395,50 @@ func (c *Client) AddHosts(ctx context.Context, hostSetId string, version uint32,
resp, err := c.client.Do(req)
if err != nil {
return nil, nil, fmt.Errorf("error performing client request during AddHosts call: %w", err)
return nil, fmt.Errorf("error performing client request during AddHosts call: %w", err)
}
target := new(HostSetUpdateResult)
target.Item = new(HostSet)
apiErr, err := resp.Decode(target.Item)
if err != nil {
return nil, nil, fmt.Errorf("error decoding AddHosts response: %w", err)
return nil, fmt.Errorf("error decoding AddHosts response: %w", err)
}
if apiErr != nil {
return nil, apiErr, nil
return nil, apiErr
}
target.responseBody = resp.Body
target.responseMap = resp.Map
return target, apiErr, nil
return target, nil
}
func (c *Client) SetHosts(ctx context.Context, hostSetId string, version uint32, hostIds []string, opt ...Option) (*HostSetUpdateResult, *api.Error, error) {
func (c *Client) SetHosts(ctx context.Context, hostSetId string, version uint32, hostIds []string, opt ...Option) (*HostSetUpdateResult, error) {
if hostSetId == "" {
return nil, nil, fmt.Errorf("empty hostSetId value passed into SetHosts request")
return nil, fmt.Errorf("empty hostSetId value passed into SetHosts request")
}
if c.client == nil {
return nil, nil, errors.New("nil client")
return nil, errors.New("nil client")
}
opts, apiOpts := getOpts(opt...)
if version == 0 {
if !opts.withAutomaticVersioning {
return nil, nil, errors.New("zero version number passed into SetHosts request")
return nil, errors.New("zero version number passed into SetHosts request")
}
existingTarget, existingApiErr, existingErr := c.Read(ctx, hostSetId, opt...)
existingTarget, existingErr := c.Read(ctx, hostSetId, opt...)
if existingErr != nil {
return nil, nil, fmt.Errorf("error performing initial check-and-set read: %w", existingErr)
}
if existingApiErr != nil {
return nil, nil, fmt.Errorf("error from controller when performing initial check-and-set read: %s", pretty.Sprint(existingApiErr))
if api.AsServerError(existingErr) != nil {
return nil, fmt.Errorf("error from controller when performing initial check-and-set read: %w", existingErr)
}
return nil, fmt.Errorf("error performing initial check-and-set read: %w", existingErr)
}
if existingTarget == nil {
return nil, nil, errors.New("nil resource response found when performing initial check-and-set read")
return nil, errors.New("nil resource response found when performing initial check-and-set read")
}
if existingTarget.Item == nil {
return nil, nil, errors.New("nil resource found when performing initial check-and-set read")
return nil, errors.New("nil resource found when performing initial check-and-set read")
}
version = existingTarget.Item.Version
}
@@ -450,7 +448,7 @@ func (c *Client) SetHosts(ctx context.Context, hostSetId string, version uint32,
req, err := c.client.NewRequest(ctx, "POST", fmt.Sprintf("host-sets/%s:set-hosts", hostSetId), opts.postMap, apiOpts...)
if err != nil {
return nil, nil, fmt.Errorf("error creating SetHosts request: %w", err)
return nil, fmt.Errorf("error creating SetHosts request: %w", err)
}
if len(opts.queryMap) > 0 {
@@ -463,52 +461,52 @@ func (c *Client) SetHosts(ctx context.Context, hostSetId string, version uint32,
resp, err := c.client.Do(req)
if err != nil {
return nil, nil, fmt.Errorf("error performing client request during SetHosts call: %w", err)
return nil, fmt.Errorf("error performing client request during SetHosts call: %w", err)
}
target := new(HostSetUpdateResult)
target.Item = new(HostSet)
apiErr, err := resp.Decode(target.Item)
if err != nil {
return nil, nil, fmt.Errorf("error decoding SetHosts response: %w", err)
return nil, fmt.Errorf("error decoding SetHosts response: %w", err)
}
if apiErr != nil {
return nil, apiErr, nil
return nil, apiErr
}
target.responseBody = resp.Body
target.responseMap = resp.Map
return target, apiErr, nil
return target, nil
}
func (c *Client) RemoveHosts(ctx context.Context, hostSetId string, version uint32, hostIds []string, opt ...Option) (*HostSetUpdateResult, *api.Error, error) {
func (c *Client) RemoveHosts(ctx context.Context, hostSetId string, version uint32, hostIds []string, opt ...Option) (*HostSetUpdateResult, error) {
if hostSetId == "" {
return nil, nil, fmt.Errorf("empty hostSetId value passed into RemoveHosts request")
return nil, fmt.Errorf("empty hostSetId value passed into RemoveHosts request")
}
if len(hostIds) == 0 {
return nil, nil, errors.New("empty hostIds passed into RemoveHosts request")
return nil, errors.New("empty hostIds passed into RemoveHosts request")
}
if c.client == nil {
return nil, nil, errors.New("nil client")
return nil, errors.New("nil client")
}
opts, apiOpts := getOpts(opt...)
if version == 0 {
if !opts.withAutomaticVersioning {
return nil, nil, errors.New("zero version number passed into RemoveHosts request")
return nil, errors.New("zero version number passed into RemoveHosts request")
}
existingTarget, existingApiErr, existingErr := c.Read(ctx, hostSetId, opt...)
existingTarget, existingErr := c.Read(ctx, hostSetId, opt...)
if existingErr != nil {
return nil, nil, fmt.Errorf("error performing initial check-and-set read: %w", existingErr)
}
if existingApiErr != nil {
return nil, nil, fmt.Errorf("error from controller when performing initial check-and-set read: %s", pretty.Sprint(existingApiErr))
if api.AsServerError(existingErr) != nil {
return nil, fmt.Errorf("error from controller when performing initial check-and-set read: %w", existingErr)
}
return nil, fmt.Errorf("error performing initial check-and-set read: %w", existingErr)
}
if existingTarget == nil {
return nil, nil, errors.New("nil resource response found when performing initial check-and-set read")
return nil, errors.New("nil resource response found when performing initial check-and-set read")
}
if existingTarget.Item == nil {
return nil, nil, errors.New("nil resource found when performing initial check-and-set read")
return nil, errors.New("nil resource found when performing initial check-and-set read")
}
version = existingTarget.Item.Version
}
@@ -518,7 +516,7 @@ func (c *Client) RemoveHosts(ctx context.Context, hostSetId string, version uint
req, err := c.client.NewRequest(ctx, "POST", fmt.Sprintf("host-sets/%s:remove-hosts", hostSetId), opts.postMap, apiOpts...)
if err != nil {
return nil, nil, fmt.Errorf("error creating RemoveHosts request: %w", err)
return nil, fmt.Errorf("error creating RemoveHosts request: %w", err)
}
if len(opts.queryMap) > 0 {
@@ -531,19 +529,19 @@ func (c *Client) RemoveHosts(ctx context.Context, hostSetId string, version uint
resp, err := c.client.Do(req)
if err != nil {
return nil, nil, fmt.Errorf("error performing client request during RemoveHosts call: %w", err)
return nil, fmt.Errorf("error performing client request during RemoveHosts call: %w", err)
}
target := new(HostSetUpdateResult)
target.Item = new(HostSet)
apiErr, err := resp.Decode(target.Item)
if err != nil {
return nil, nil, fmt.Errorf("error decoding RemoveHosts response: %w", err)
return nil, fmt.Errorf("error decoding RemoveHosts response: %w", err)
}
if apiErr != nil {
return nil, apiErr, nil
return nil, apiErr
}
target.responseBody = resp.Body
target.responseMap = resp.Map
return target, apiErr, nil
return target, nil
}
+42 -58
View File
@@ -12,7 +12,6 @@ import (
"github.com/hashicorp/boundary/internal/host/static"
"github.com/hashicorp/boundary/internal/iam"
"github.com/hashicorp/boundary/internal/servers/controller"
"github.com/kr/pretty"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
@@ -27,36 +26,29 @@ func TestCustom(t *testing.T) {
client.SetToken(token.Token)
_, proj := iam.TestScopes(t, tc.IamRepo(), iam.WithUserId(token.UserId))
hc, apiErr, err := hostcatalogs.NewClient(client).Create(tc.Context(), "static", proj.GetPublicId())
hc, err := hostcatalogs.NewClient(client).Create(tc.Context(), "static", proj.GetPublicId())
require.NoError(err)
require.Nil(apiErr)
hClient := hosts.NewClient(client)
h1, apiErr, err := hClient.Create(tc.Context(), hc.Item.Id, hosts.WithStaticHostAddress("someaddress"))
h1, err := hClient.Create(tc.Context(), hc.Item.Id, hosts.WithStaticHostAddress("someaddress"))
require.NoError(err)
require.Nil(apiErr)
h2, apiErr, err := hClient.Create(tc.Context(), hc.Item.Id, hosts.WithStaticHostAddress("someaddress"))
h2, err := hClient.Create(tc.Context(), hc.Item.Id, hosts.WithStaticHostAddress("someaddress"))
require.NoError(err)
require.Nil(apiErr)
hSetClient := hostsets.NewClient(client)
hSet, apiErr, err := hSetClient.Create(tc.Context(), hc.Item.Id)
hSet, err := hSetClient.Create(tc.Context(), hc.Item.Id)
require.NoError(err)
require.Nil(apiErr)
hSet, apiErr, err = hSetClient.AddHosts(tc.Context(), hSet.Item.Id, hSet.Item.Version, []string{h1.Item.Id, h2.Item.Id})
hSet, err = hSetClient.AddHosts(tc.Context(), hSet.Item.Id, hSet.Item.Version, []string{h1.Item.Id, h2.Item.Id})
require.NoError(err)
require.Nil(apiErr)
assert.Contains(hSet.Item.HostIds, h1.Item.Id, h2.Item.Id)
hSet, apiErr, err = hSetClient.SetHosts(tc.Context(), hSet.Item.Id, hSet.Item.Version, []string{h1.Item.Id})
hSet, err = hSetClient.SetHosts(tc.Context(), hSet.Item.Id, hSet.Item.Version, []string{h1.Item.Id})
require.NoError(err)
require.Nil(apiErr, pretty.Sprint(apiErr))
assert.ElementsMatch([]string{h1.Item.Id}, hSet.Item.HostIds)
hSet, apiErr, err = hSetClient.RemoveHosts(tc.Context(), hSet.Item.Id, hSet.Item.Version, []string{h1.Item.Id})
hSet, err = hSetClient.RemoveHosts(tc.Context(), hSet.Item.Id, hSet.Item.Version, []string{h1.Item.Id})
require.NoError(err)
require.Nil(apiErr)
assert.Empty(hSet.Item.HostIds)
}
@@ -70,16 +62,14 @@ func TestList(t *testing.T) {
client.SetToken(token.Token)
_, proj := iam.TestScopes(t, tc.IamRepo(), iam.WithUserId(token.UserId))
hc, apiErr, err := hostcatalogs.NewClient(client).Create(tc.Context(), "static", proj.GetPublicId())
hc, err := hostcatalogs.NewClient(client).Create(tc.Context(), "static", proj.GetPublicId())
require.NoError(err)
require.Nil(apiErr)
require.NotNil(hc)
hClient := hostsets.NewClient(client)
ul, apiErr, err := hClient.List(tc.Context(), hc.Item.Id)
ul, err := hClient.List(tc.Context(), hc.Item.Id)
require.NoError(err)
require.Nil(apiErr)
assert.Empty(ul.Items)
var expected []*hostsets.HostSet
@@ -87,25 +77,21 @@ func TestList(t *testing.T) {
expected = append(expected, &hostsets.HostSet{Name: fmt.Sprint(i)})
}
hcr, apiErr, err := hClient.Create(tc.Context(), hc.Item.Id, hostsets.WithName(expected[0].Name))
hcr, err := hClient.Create(tc.Context(), hc.Item.Id, hostsets.WithName(expected[0].Name))
require.NoError(err)
require.Nil(apiErr)
expected[0] = hcr.Item
ul, apiErr, err = hClient.List(tc.Context(), hc.Item.Id)
ul, err = hClient.List(tc.Context(), hc.Item.Id)
require.NoError(err)
require.Nil(apiErr)
assert.ElementsMatch(comparableSetSlice(expected[:1]), comparableSetSlice(ul.Items))
for i := 1; i < 10; i++ {
hcr, apiErr, err = hClient.Create(tc.Context(), hc.Item.Id, hostsets.WithName(expected[i].Name))
hcr, err = hClient.Create(tc.Context(), hc.Item.Id, hostsets.WithName(expected[i].Name))
require.NoError(err)
require.Nil(apiErr)
expected[i] = hcr.Item
}
ul, apiErr, err = hClient.List(tc.Context(), hc.Item.Id)
ul, err = hClient.List(tc.Context(), hc.Item.Id)
require.NoError(err)
require.Nil(apiErr)
assert.ElementsMatch(comparableSetSlice(expected), comparableSetSlice(ul.Items))
}
@@ -134,17 +120,13 @@ func TestCrud(t *testing.T) {
client.SetToken(token.Token)
_, proj := iam.TestScopes(t, tc.IamRepo(), iam.WithUserId(token.UserId))
hc, apiErr, err := hostcatalogs.NewClient(client).Create(tc.Context(), "static", proj.GetPublicId())
hc, err := hostcatalogs.NewClient(client).Create(tc.Context(), "static", proj.GetPublicId())
require.NoError(err)
require.Nil(apiErr)
require.NotNil(hc)
checkHost := func(t *testing.T, step string, h *hostsets.HostSet, apiErr *api.Error, err error, wantedName string, wantVersion uint32) {
checkHost := func(t *testing.T, step string, h *hostsets.HostSet, err error, wantedName string, wantVersion uint32) {
t.Helper()
require.NoError(err, step)
if !assert.Nil(apiErr, step) && apiErr.Message != "" {
t.Errorf("ApiError message: %q", apiErr.Message)
}
assert.NotNil(h, "returned no resource", step)
gotName := ""
if h.Name != "" {
@@ -156,24 +138,24 @@ func TestCrud(t *testing.T) {
hClient := hostsets.NewClient(client)
h, apiErr, err := hClient.Create(tc.Context(), hc.Item.Id, hostsets.WithName("foo"))
checkHost(t, "create", h.Item, apiErr, err, "foo", 1)
h, err := hClient.Create(tc.Context(), hc.Item.Id, hostsets.WithName("foo"))
checkHost(t, "create", h.Item, err, "foo", 1)
h, apiErr, err = hClient.Read(tc.Context(), h.Item.Id)
checkHost(t, "read", h.Item, apiErr, err, "foo", 1)
h, err = hClient.Read(tc.Context(), h.Item.Id)
checkHost(t, "read", h.Item, err, "foo", 1)
h, apiErr, err = hClient.Update(tc.Context(), h.Item.Id, h.Item.Version, hostsets.WithName("bar"))
checkHost(t, "update", h.Item, apiErr, err, "bar", 2)
h, err = hClient.Update(tc.Context(), h.Item.Id, h.Item.Version, hostsets.WithName("bar"))
checkHost(t, "update", h.Item, err, "bar", 2)
h, apiErr, err = hClient.Update(tc.Context(), h.Item.Id, h.Item.Version, hostsets.DefaultName())
checkHost(t, "update", h.Item, apiErr, err, "", 3)
h, err = hClient.Update(tc.Context(), h.Item.Id, h.Item.Version, hostsets.DefaultName())
checkHost(t, "update", h.Item, err, "", 3)
_, apiErr, err = hClient.Delete(tc.Context(), h.Item.Id)
_, err = hClient.Delete(tc.Context(), h.Item.Id)
assert.NoError(err)
assert.Nil(apiErr)
_, apiErr, err = hClient.Delete(tc.Context(), h.Item.Id)
require.NoError(err)
assert.NotNil(apiErr)
_, err = hClient.Delete(tc.Context(), h.Item.Id)
require.Error(err)
apiErr := api.AsServerError(err)
require.NotNil(apiErr)
assert.EqualValues(http.StatusNotFound, apiErr.Status)
}
@@ -188,36 +170,38 @@ func TestErrors(t *testing.T) {
client.SetToken(token.Token)
_, proj := iam.TestScopes(t, tc.IamRepo(), iam.WithUserId(token.UserId))
hc, apiErr, err := hostcatalogs.NewClient(client).Create(tc.Context(), "static", proj.GetPublicId())
hc, err := hostcatalogs.NewClient(client).Create(tc.Context(), "static", proj.GetPublicId())
require.NoError(err)
require.Nil(apiErr)
require.NotNil(hc)
hClient := hostsets.NewClient(client)
h, apiErr, err := hClient.Create(tc.Context(), hc.Item.Id, hostsets.WithName("foo"))
h, err := hClient.Create(tc.Context(), hc.Item.Id, hostsets.WithName("foo"))
require.NoError(err)
require.Nil(apiErr)
assert.NotNil(h)
// Updating the wrong version should fail.
_, apiErr, err = hClient.Update(tc.Context(), h.Item.Id, 73, hostsets.WithName("anything"))
require.NoError(err)
_, err = hClient.Update(tc.Context(), h.Item.Id, 73, hostsets.WithName("anything"))
require.Error(err)
apiErr := api.AsServerError(err)
assert.NotNil(apiErr)
assert.EqualValues(http.StatusNotFound, apiErr.Status)
h, apiErr, err = hClient.Create(tc.Context(), hc.Item.Id, hostsets.WithName("foo"))
require.NoError(err)
h, err = hClient.Create(tc.Context(), hc.Item.Id, hostsets.WithName("foo"))
require.Error(err)
apiErr = api.AsServerError(err)
assert.NotNil(apiErr)
assert.Nil(h)
_, apiErr, err = hClient.Read(tc.Context(), static.HostSetPrefix+"_doesntexis")
require.NoError(err)
_, err = hClient.Read(tc.Context(), static.HostSetPrefix+"_doesntexis")
require.Error(err)
apiErr = api.AsServerError(err)
assert.NotNil(apiErr)
assert.EqualValues(http.StatusNotFound, apiErr.Status)
_, apiErr, err = hClient.Read(tc.Context(), "invalid id")
require.NoError(err)
_, err = hClient.Read(tc.Context(), "invalid id")
require.Error(err)
apiErr = api.AsServerError(err)
assert.NotNil(apiErr)
assert.EqualValues(http.StatusBadRequest, apiErr.Status)
}
+66 -92
View File
@@ -13,32 +13,6 @@ import (
"github.com/iancoleman/strcase"
)
func toPath(segments []string, action string) string {
// If it's just a collection name, don't do a fmt.Sprintf
if len(segments) == 1 {
ret := segments[0]
if action != "" {
ret = fmt.Sprintf("%s:%s", ret, action)
}
return fmt.Sprintf(`"%s"`, ret)
}
var printfString, printfArg []string
for i, s := range segments {
if i%2 == 0 {
// The first (zero index) is always the resource name, the next will be the id.
printfString = append(printfString, s)
} else {
printfString = append(printfString, "%s")
printfArg = append(printfArg, s)
}
}
if action != "" {
action = fmt.Sprintf(":%s", action)
}
return fmt.Sprintf("fmt.Sprintf(\"%s%s\", %s)", strings.Join(printfString, "/"), action, strings.Join(printfArg, ", "))
}
func getArgsAndPaths(in []string, parentTypeName, action string) (colArg, resArg string, colPath, resPath string) {
resArg = fmt.Sprintf("%sId", strcase.ToLowerCamel(strings.ReplaceAll(in[len(in)-1], "-", "_")))
strToReplace := "scope"
@@ -207,12 +181,12 @@ var listTemplate = template.Must(template.New("").Funcs(
"snakeCase": snakeCase,
},
).Parse(`
func (c *Client) List(ctx context.Context, {{ .CollectionFunctionArg }} string, opt... Option) (*{{ .Name }}ListResult, *api.Error, error) {
func (c *Client) List(ctx context.Context, {{ .CollectionFunctionArg }} string, opt... Option) (*{{ .Name }}ListResult, error) {
if {{ .CollectionFunctionArg }} == "" {
return nil, nil, fmt.Errorf("empty {{ .CollectionFunctionArg }} value passed into List request")
return nil, fmt.Errorf("empty {{ .CollectionFunctionArg }} value passed into List request")
}
if c.client == nil {
return nil, nil, fmt.Errorf("nil client")
return nil, fmt.Errorf("nil client")
}
opts, apiOpts := getOpts(opt...)
@@ -220,7 +194,7 @@ func (c *Client) List(ctx context.Context, {{ .CollectionFunctionArg }} string,
req, err := c.client.NewRequest(ctx, "GET", "{{ .CollectionPath }}", nil, apiOpts...)
if err != nil {
return nil, nil, fmt.Errorf("error creating List request: %w", err)
return nil, fmt.Errorf("error creating List request: %w", err)
}
{{ if ( eq .CollectionPath "\"scopes\"" ) }}
opts.queryMap["scope_id"] = scopeId
@@ -235,37 +209,37 @@ func (c *Client) List(ctx context.Context, {{ .CollectionFunctionArg }} string,
resp, err := c.client.Do(req)
if err != nil {
return nil, nil, fmt.Errorf("error performing client request during List call: %w", err)
return nil, fmt.Errorf("error performing client request during List call: %w", err)
}
target := new({{ .Name }}ListResult)
apiErr, err := resp.Decode(target)
if err != nil {
return nil, nil, fmt.Errorf("error decoding List response: %w", err)
return nil, fmt.Errorf("error decoding List response: %w", err)
}
if apiErr != nil {
return nil, apiErr, nil
return nil, apiErr
}
target.responseBody = resp.Body
target.responseMap = resp.Map
return target, apiErr, nil
return target, nil
}
`))
var readTemplate = template.Must(template.New("").Parse(`
func (c *Client) Read(ctx context.Context, {{ .ResourceFunctionArg }} string, opt... Option) (*{{ .Name }}ReadResult, *api.Error, error) {
func (c *Client) Read(ctx context.Context, {{ .ResourceFunctionArg }} string, opt... Option) (*{{ .Name }}ReadResult, error) {
if {{ .ResourceFunctionArg }} == "" {
return nil, nil, fmt.Errorf("empty {{ .ResourceFunctionArg }} value passed into Read request")
return nil, fmt.Errorf("empty {{ .ResourceFunctionArg }} value passed into Read request")
}
if c.client == nil {
return nil, nil, fmt.Errorf("nil client")
return nil, fmt.Errorf("nil client")
}
opts, apiOpts := getOpts(opt...)
req, err := c.client.NewRequest(ctx, "GET", {{ .ResourcePath }}, nil, apiOpts...)
if err != nil {
return nil, nil, fmt.Errorf("error creating Read request: %w", err)
return nil, fmt.Errorf("error creating Read request: %w", err)
}
if len(opts.queryMap) > 0 {
@@ -278,38 +252,38 @@ func (c *Client) Read(ctx context.Context, {{ .ResourceFunctionArg }} string, op
resp, err := c.client.Do(req)
if err != nil {
return nil, nil, fmt.Errorf("error performing client request during Read call: %w", err)
return nil, fmt.Errorf("error performing client request during Read call: %w", err)
}
target := new({{ .Name }}ReadResult)
target.Item = new({{ .Name }})
apiErr, err := resp.Decode(target.Item)
if err != nil {
return nil, nil, fmt.Errorf("error decoding Read response: %w", err)
return nil, fmt.Errorf("error decoding Read response: %w", err)
}
if apiErr != nil {
return nil, apiErr, nil
return nil, apiErr
}
target.responseBody = resp.Body
target.responseMap = resp.Map
return target, apiErr, nil
return target, nil
}
`))
var deleteTemplate = template.Must(template.New("").Parse(`
func (c *Client) Delete(ctx context.Context, {{ .ResourceFunctionArg }} string, opt... Option) (*{{ .Name }}DeleteResult, *api.Error, error) {
func (c *Client) Delete(ctx context.Context, {{ .ResourceFunctionArg }} string, opt... Option) (*{{ .Name }}DeleteResult, error) {
if {{ .ResourceFunctionArg }} == "" {
return nil, nil, fmt.Errorf("empty {{ .ResourceFunctionArg }} value passed into Delete request")
return nil, fmt.Errorf("empty {{ .ResourceFunctionArg }} value passed into Delete request")
}
if c.client == nil {
return nil, nil, fmt.Errorf("nil client")
return nil, fmt.Errorf("nil client")
}
opts, apiOpts := getOpts(opt...)
req, err := c.client.NewRequest(ctx, "DELETE", {{ .ResourcePath }}, nil, apiOpts...)
if err != nil {
return nil, nil, fmt.Errorf("error creating Delete request: %w", err)
return nil, fmt.Errorf("error creating Delete request: %w", err)
}
if len(opts.queryMap) > 0 {
@@ -322,22 +296,22 @@ func (c *Client) Delete(ctx context.Context, {{ .ResourceFunctionArg }} string,
resp, err := c.client.Do(req)
if err != nil {
return nil, nil, fmt.Errorf("error performing client request during Delete call: %w", err)
return nil, fmt.Errorf("error performing client request during Delete call: %w", err)
}
apiErr, err := resp.Decode(nil)
if err != nil {
return nil, nil, fmt.Errorf("error decoding Delete response: %w", err)
return nil, fmt.Errorf("error decoding Delete response: %w", err)
}
if apiErr != nil {
return nil, apiErr, nil
return nil, apiErr
}
target := &{{ .Name }}DeleteResult{
responseBody: resp.Body,
responseMap: resp.Map,
}
return target, nil, nil
return target, nil
}
`))
@@ -346,18 +320,18 @@ var createTemplate = template.Must(template.New("").Funcs(
"snakeCase": snakeCase,
},
).Parse(`
func (c *Client) Create (ctx context.Context, {{ if .TypeOnCreate }} resourceType string, {{ end }} {{ .CollectionFunctionArg }} string, opt... Option) (*{{ .Name }}CreateResult, *api.Error, error) {
func (c *Client) Create (ctx context.Context, {{ if .TypeOnCreate }} resourceType string, {{ end }} {{ .CollectionFunctionArg }} string, opt... Option) (*{{ .Name }}CreateResult, error) {
if {{ .CollectionFunctionArg }} == "" {
return nil, nil, fmt.Errorf("empty {{ .CollectionFunctionArg }} value passed into Create request")
return nil, fmt.Errorf("empty {{ .CollectionFunctionArg }} value passed into Create request")
}
opts, apiOpts := getOpts(opt...)
if c.client == nil {
return nil, nil, fmt.Errorf("nil client")
return nil, fmt.Errorf("nil client")
}
{{ if .TypeOnCreate }} if resourceType == "" {
return nil, nil, fmt.Errorf("empty resourceType value passed into Create request")
return nil, fmt.Errorf("empty resourceType value passed into Create request")
} else {
opts.postMap["type"] = resourceType
}{{ end }}
@@ -366,7 +340,7 @@ func (c *Client) Create (ctx context.Context, {{ if .TypeOnCreate }} resourceTyp
req, err := c.client.NewRequest(ctx, "POST", "{{ .CollectionPath }}", opts.postMap, apiOpts...)
if err != nil {
return nil, nil, fmt.Errorf("error creating Create request: %w", err)
return nil, fmt.Errorf("error creating Create request: %w", err)
}
{{ if ( eq .CollectionPath "\"scopes\"" ) }}
opts.queryMap["scope_id"] = scopeId
@@ -381,31 +355,31 @@ func (c *Client) Create (ctx context.Context, {{ if .TypeOnCreate }} resourceTyp
resp, err := c.client.Do(req)
if err != nil {
return nil, nil, fmt.Errorf("error performing client request during Create call: %w", err)
return nil, fmt.Errorf("error performing client request during Create call: %w", err)
}
target := new({{ .Name }}CreateResult)
target.Item = new({{ .Name }})
apiErr, err := resp.Decode(target.Item)
if err != nil {
return nil, nil, fmt.Errorf("error decoding Create response: %w", err)
return nil, fmt.Errorf("error decoding Create response: %w", err)
}
if apiErr != nil {
return nil, apiErr, nil
return nil, apiErr
}
target.responseBody = resp.Body
target.responseMap = resp.Map
return target, apiErr, nil
return target, nil
}
`))
var updateTemplate = template.Must(template.New("").Parse(`
func (c *Client) Update(ctx context.Context, {{ .ResourceFunctionArg }} string, version uint32, opt... Option) (*{{ .Name }}UpdateResult, *api.Error, error) {
func (c *Client) Update(ctx context.Context, {{ .ResourceFunctionArg }} string, version uint32, opt... Option) (*{{ .Name }}UpdateResult, error) {
if {{ .ResourceFunctionArg }} == "" {
return nil, nil, fmt.Errorf("empty {{ .ResourceFunctionArg }} value passed into Update request")
return nil, fmt.Errorf("empty {{ .ResourceFunctionArg }} value passed into Update request")
}
if c.client == nil {
return nil, nil, fmt.Errorf("nil client")
return nil, fmt.Errorf("nil client")
}
opts, apiOpts := getOpts(opt...)
@@ -413,20 +387,20 @@ func (c *Client) Update(ctx context.Context, {{ .ResourceFunctionArg }} string,
{{ if .VersionEnabled }}
if version == 0 {
if !opts.withAutomaticVersioning {
return nil, nil, errors.New("zero version number passed into Update request and automatic versioning not specified")
return nil, errors.New("zero version number passed into Update request and automatic versioning not specified")
}
existingTarget, existingApiErr, existingErr := c.Read(ctx, {{ .ResourceFunctionArg }}, opt...)
existingTarget, existingErr := c.Read(ctx, {{ .ResourceFunctionArg }}, opt...)
if existingErr != nil {
return nil, nil, fmt.Errorf("error performing initial check-and-set read: %w", existingErr)
}
if existingApiErr != nil {
return nil, nil, fmt.Errorf("error from controller when performing initial check-and-set read: %s", pretty.Sprint(existingApiErr))
if api.AsServerError(existingErr) != nil {
return nil, fmt.Errorf("error from controller when performing initial check-and-set read: %w", existingErr)
}
return nil, fmt.Errorf("error performing initial check-and-set read: %w", existingErr)
}
if existingTarget == nil {
return nil, nil, errors.New("nil resource response found when performing initial check-and-set read")
return nil, errors.New("nil resource response found when performing initial check-and-set read")
}
if existingTarget.Item == nil {
return nil, nil, errors.New("nil resource found when performing initial check-and-set read")
return nil, errors.New("nil resource found when performing initial check-and-set read")
}
version = existingTarget.Item.Version
}
@@ -436,7 +410,7 @@ func (c *Client) Update(ctx context.Context, {{ .ResourceFunctionArg }} string,
req, err := c.client.NewRequest(ctx, "PATCH", {{ .ResourcePath }}, opts.postMap, apiOpts...)
if err != nil {
return nil, nil, fmt.Errorf("error creating Update request: %w", err)
return nil, fmt.Errorf("error creating Update request: %w", err)
}
if len(opts.queryMap) > 0 {
@@ -449,21 +423,21 @@ func (c *Client) Update(ctx context.Context, {{ .ResourceFunctionArg }} string,
resp, err := c.client.Do(req)
if err != nil {
return nil, nil, fmt.Errorf("error performing client request during Update call: %w", err)
return nil, fmt.Errorf("error performing client request during Update call: %w", err)
}
target := new({{ .Name }}UpdateResult)
target.Item = new({{ .Name }})
apiErr, err := resp.Decode(target.Item)
if err != nil {
return nil, nil, fmt.Errorf("error decoding Update response: %w", err)
return nil, fmt.Errorf("error decoding Update response: %w", err)
}
if apiErr != nil {
return nil, apiErr, nil
return nil, apiErr
}
target.responseBody = resp.Body
target.responseMap = resp.Map
return target, apiErr, nil
return target, nil
}
`))
@@ -481,15 +455,15 @@ var sliceSubTypeTemplate = template.Must(template.New("").Funcs(
{{ $fullName := print $op $key }}
{{ $actionName := kebabCase $fullName }}
{{ $resPath := getPathWithAction $input.PathArgs $input.ParentTypeName $actionName }}
func (c *Client) {{ $fullName }}(ctx context.Context, {{ $input.ResourceFunctionArg }} string, version uint32, {{ $value }} []string, opt... Option) (*{{ $input.Name }}UpdateResult, *api.Error, error) {
func (c *Client) {{ $fullName }}(ctx context.Context, {{ $input.ResourceFunctionArg }} string, version uint32, {{ $value }} []string, opt... Option) (*{{ $input.Name }}UpdateResult, error) {
if {{ $input.ResourceFunctionArg }} == "" {
return nil, nil, fmt.Errorf("empty {{ $input.ResourceFunctionArg }} value passed into {{ $fullName }} request")
return nil, fmt.Errorf("empty {{ $input.ResourceFunctionArg }} value passed into {{ $fullName }} request")
}
{{ if ( not ( eq $op "Set" ) ) }}if len({{ $value }}) == 0 {
return nil, nil, errors.New("empty {{ $value }} passed into {{ $fullName }} request")
return nil, errors.New("empty {{ $value }} passed into {{ $fullName }} request")
}{{ end }}
if c.client == nil {
return nil, nil, errors.New("nil client")
return nil, errors.New("nil client")
}
opts, apiOpts := getOpts(opt...)
@@ -497,20 +471,20 @@ func (c *Client) {{ $fullName }}(ctx context.Context, {{ $input.ResourceFunction
{{ if $input.VersionEnabled }}
if version == 0 {
if !opts.withAutomaticVersioning {
return nil, nil, errors.New("zero version number passed into {{ $fullName }} request")
return nil, errors.New("zero version number passed into {{ $fullName }} request")
}
existingTarget, existingApiErr, existingErr := c.Read(ctx, {{ $input.ResourceFunctionArg }}, opt...)
existingTarget, existingErr := c.Read(ctx, {{ $input.ResourceFunctionArg }}, opt...)
if existingErr != nil {
return nil, nil, fmt.Errorf("error performing initial check-and-set read: %w", existingErr)
}
if existingApiErr != nil {
return nil, nil, fmt.Errorf("error from controller when performing initial check-and-set read: %s", pretty.Sprint(existingApiErr))
if api.AsServerError(existingErr) != nil {
return nil, fmt.Errorf("error from controller when performing initial check-and-set read: %w", existingErr)
}
return nil, fmt.Errorf("error performing initial check-and-set read: %w", existingErr)
}
if existingTarget == nil {
return nil, nil, errors.New("nil resource response found when performing initial check-and-set read")
return nil, errors.New("nil resource response found when performing initial check-and-set read")
}
if existingTarget.Item == nil {
return nil, nil, errors.New("nil resource found when performing initial check-and-set read")
return nil, errors.New("nil resource found when performing initial check-and-set read")
}
version = existingTarget.Item.Version
}
@@ -520,7 +494,7 @@ func (c *Client) {{ $fullName }}(ctx context.Context, {{ $input.ResourceFunction
req, err := c.client.NewRequest(ctx, "POST", {{ $resPath }}, opts.postMap, apiOpts...)
if err != nil {
return nil, nil, fmt.Errorf("error creating {{ $fullName }} request: %w", err)
return nil, fmt.Errorf("error creating {{ $fullName }} request: %w", err)
}
if len(opts.queryMap) > 0 {
@@ -533,21 +507,21 @@ func (c *Client) {{ $fullName }}(ctx context.Context, {{ $input.ResourceFunction
resp, err := c.client.Do(req)
if err != nil {
return nil, nil, fmt.Errorf("error performing client request during {{ $fullName }} call: %w", err)
return nil, fmt.Errorf("error performing client request during {{ $fullName }} call: %w", err)
}
target := new({{ $input.Name }}UpdateResult)
target.Item = new({{ $input.Name }})
apiErr, err := resp.Decode(target.Item)
if err != nil {
return nil, nil, fmt.Errorf("error decoding {{ $fullName }} response: %w", err)
return nil, fmt.Errorf("error decoding {{ $fullName }} response: %w", err)
}
if apiErr != nil {
return nil, apiErr, nil
return nil, apiErr
}
target.responseBody = resp.Body
target.responseMap = resp.Map
return target, apiErr, nil
return target, nil
}
{{ end }}
{{ end }}
+148 -150
View File
@@ -9,8 +9,6 @@ import (
"net/url"
"time"
"github.com/kr/pretty"
"github.com/hashicorp/boundary/api"
"github.com/hashicorp/boundary/api/scopes"
)
@@ -112,22 +110,22 @@ func (c *Client) ApiClient() *api.Client {
return c.client
}
func (c *Client) Create(ctx context.Context, scopeId string, opt ...Option) (*RoleCreateResult, *api.Error, error) {
func (c *Client) Create(ctx context.Context, scopeId string, opt ...Option) (*RoleCreateResult, error) {
if scopeId == "" {
return nil, nil, fmt.Errorf("empty scopeId value passed into Create request")
return nil, fmt.Errorf("empty scopeId value passed into Create request")
}
opts, apiOpts := getOpts(opt...)
if c.client == nil {
return nil, nil, fmt.Errorf("nil client")
return nil, fmt.Errorf("nil client")
}
opts.postMap["scope_id"] = scopeId
req, err := c.client.NewRequest(ctx, "POST", "roles", opts.postMap, apiOpts...)
if err != nil {
return nil, nil, fmt.Errorf("error creating Create request: %w", err)
return nil, fmt.Errorf("error creating Create request: %w", err)
}
if len(opts.queryMap) > 0 {
@@ -140,36 +138,36 @@ func (c *Client) Create(ctx context.Context, scopeId string, opt ...Option) (*Ro
resp, err := c.client.Do(req)
if err != nil {
return nil, nil, fmt.Errorf("error performing client request during Create call: %w", err)
return nil, fmt.Errorf("error performing client request during Create call: %w", err)
}
target := new(RoleCreateResult)
target.Item = new(Role)
apiErr, err := resp.Decode(target.Item)
if err != nil {
return nil, nil, fmt.Errorf("error decoding Create response: %w", err)
return nil, fmt.Errorf("error decoding Create response: %w", err)
}
if apiErr != nil {
return nil, apiErr, nil
return nil, apiErr
}
target.responseBody = resp.Body
target.responseMap = resp.Map
return target, apiErr, nil
return target, nil
}
func (c *Client) Read(ctx context.Context, roleId string, opt ...Option) (*RoleReadResult, *api.Error, error) {
func (c *Client) Read(ctx context.Context, roleId string, opt ...Option) (*RoleReadResult, error) {
if roleId == "" {
return nil, nil, fmt.Errorf("empty roleId value passed into Read request")
return nil, fmt.Errorf("empty roleId value passed into Read request")
}
if c.client == nil {
return nil, nil, fmt.Errorf("nil client")
return nil, fmt.Errorf("nil client")
}
opts, apiOpts := getOpts(opt...)
req, err := c.client.NewRequest(ctx, "GET", fmt.Sprintf("roles/%s", roleId), nil, apiOpts...)
if err != nil {
return nil, nil, fmt.Errorf("error creating Read request: %w", err)
return nil, fmt.Errorf("error creating Read request: %w", err)
}
if len(opts.queryMap) > 0 {
@@ -182,49 +180,49 @@ func (c *Client) Read(ctx context.Context, roleId string, opt ...Option) (*RoleR
resp, err := c.client.Do(req)
if err != nil {
return nil, nil, fmt.Errorf("error performing client request during Read call: %w", err)
return nil, fmt.Errorf("error performing client request during Read call: %w", err)
}
target := new(RoleReadResult)
target.Item = new(Role)
apiErr, err := resp.Decode(target.Item)
if err != nil {
return nil, nil, fmt.Errorf("error decoding Read response: %w", err)
return nil, fmt.Errorf("error decoding Read response: %w", err)
}
if apiErr != nil {
return nil, apiErr, nil
return nil, apiErr
}
target.responseBody = resp.Body
target.responseMap = resp.Map
return target, apiErr, nil
return target, nil
}
func (c *Client) Update(ctx context.Context, roleId string, version uint32, opt ...Option) (*RoleUpdateResult, *api.Error, error) {
func (c *Client) Update(ctx context.Context, roleId string, version uint32, opt ...Option) (*RoleUpdateResult, error) {
if roleId == "" {
return nil, nil, fmt.Errorf("empty roleId value passed into Update request")
return nil, fmt.Errorf("empty roleId value passed into Update request")
}
if c.client == nil {
return nil, nil, fmt.Errorf("nil client")
return nil, fmt.Errorf("nil client")
}
opts, apiOpts := getOpts(opt...)
if version == 0 {
if !opts.withAutomaticVersioning {
return nil, nil, errors.New("zero version number passed into Update request and automatic versioning not specified")
return nil, errors.New("zero version number passed into Update request and automatic versioning not specified")
}
existingTarget, existingApiErr, existingErr := c.Read(ctx, roleId, opt...)
existingTarget, existingErr := c.Read(ctx, roleId, opt...)
if existingErr != nil {
return nil, nil, fmt.Errorf("error performing initial check-and-set read: %w", existingErr)
}
if existingApiErr != nil {
return nil, nil, fmt.Errorf("error from controller when performing initial check-and-set read: %s", pretty.Sprint(existingApiErr))
if api.AsServerError(existingErr) != nil {
return nil, fmt.Errorf("error from controller when performing initial check-and-set read: %w", existingErr)
}
return nil, fmt.Errorf("error performing initial check-and-set read: %w", existingErr)
}
if existingTarget == nil {
return nil, nil, errors.New("nil resource response found when performing initial check-and-set read")
return nil, errors.New("nil resource response found when performing initial check-and-set read")
}
if existingTarget.Item == nil {
return nil, nil, errors.New("nil resource found when performing initial check-and-set read")
return nil, errors.New("nil resource found when performing initial check-and-set read")
}
version = existingTarget.Item.Version
}
@@ -233,7 +231,7 @@ func (c *Client) Update(ctx context.Context, roleId string, version uint32, opt
req, err := c.client.NewRequest(ctx, "PATCH", fmt.Sprintf("roles/%s", roleId), opts.postMap, apiOpts...)
if err != nil {
return nil, nil, fmt.Errorf("error creating Update request: %w", err)
return nil, fmt.Errorf("error creating Update request: %w", err)
}
if len(opts.queryMap) > 0 {
@@ -246,36 +244,36 @@ func (c *Client) Update(ctx context.Context, roleId string, version uint32, opt
resp, err := c.client.Do(req)
if err != nil {
return nil, nil, fmt.Errorf("error performing client request during Update call: %w", err)
return nil, fmt.Errorf("error performing client request during Update call: %w", err)
}
target := new(RoleUpdateResult)
target.Item = new(Role)
apiErr, err := resp.Decode(target.Item)
if err != nil {
return nil, nil, fmt.Errorf("error decoding Update response: %w", err)
return nil, fmt.Errorf("error decoding Update response: %w", err)
}
if apiErr != nil {
return nil, apiErr, nil
return nil, apiErr
}
target.responseBody = resp.Body
target.responseMap = resp.Map
return target, apiErr, nil
return target, nil
}
func (c *Client) Delete(ctx context.Context, roleId string, opt ...Option) (*RoleDeleteResult, *api.Error, error) {
func (c *Client) Delete(ctx context.Context, roleId string, opt ...Option) (*RoleDeleteResult, error) {
if roleId == "" {
return nil, nil, fmt.Errorf("empty roleId value passed into Delete request")
return nil, fmt.Errorf("empty roleId value passed into Delete request")
}
if c.client == nil {
return nil, nil, fmt.Errorf("nil client")
return nil, fmt.Errorf("nil client")
}
opts, apiOpts := getOpts(opt...)
req, err := c.client.NewRequest(ctx, "DELETE", fmt.Sprintf("roles/%s", roleId), nil, apiOpts...)
if err != nil {
return nil, nil, fmt.Errorf("error creating Delete request: %w", err)
return nil, fmt.Errorf("error creating Delete request: %w", err)
}
if len(opts.queryMap) > 0 {
@@ -288,30 +286,30 @@ func (c *Client) Delete(ctx context.Context, roleId string, opt ...Option) (*Rol
resp, err := c.client.Do(req)
if err != nil {
return nil, nil, fmt.Errorf("error performing client request during Delete call: %w", err)
return nil, fmt.Errorf("error performing client request during Delete call: %w", err)
}
apiErr, err := resp.Decode(nil)
if err != nil {
return nil, nil, fmt.Errorf("error decoding Delete response: %w", err)
return nil, fmt.Errorf("error decoding Delete response: %w", err)
}
if apiErr != nil {
return nil, apiErr, nil
return nil, apiErr
}
target := &RoleDeleteResult{
responseBody: resp.Body,
responseMap: resp.Map,
}
return target, nil, nil
return target, nil
}
func (c *Client) List(ctx context.Context, scopeId string, opt ...Option) (*RoleListResult, *api.Error, error) {
func (c *Client) List(ctx context.Context, scopeId string, opt ...Option) (*RoleListResult, error) {
if scopeId == "" {
return nil, nil, fmt.Errorf("empty scopeId value passed into List request")
return nil, fmt.Errorf("empty scopeId value passed into List request")
}
if c.client == nil {
return nil, nil, fmt.Errorf("nil client")
return nil, fmt.Errorf("nil client")
}
opts, apiOpts := getOpts(opt...)
@@ -319,7 +317,7 @@ func (c *Client) List(ctx context.Context, scopeId string, opt ...Option) (*Role
req, err := c.client.NewRequest(ctx, "GET", "roles", nil, apiOpts...)
if err != nil {
return nil, nil, fmt.Errorf("error creating List request: %w", err)
return nil, fmt.Errorf("error creating List request: %w", err)
}
if len(opts.queryMap) > 0 {
@@ -332,51 +330,51 @@ func (c *Client) List(ctx context.Context, scopeId string, opt ...Option) (*Role
resp, err := c.client.Do(req)
if err != nil {
return nil, nil, fmt.Errorf("error performing client request during List call: %w", err)
return nil, fmt.Errorf("error performing client request during List call: %w", err)
}
target := new(RoleListResult)
apiErr, err := resp.Decode(target)
if err != nil {
return nil, nil, fmt.Errorf("error decoding List response: %w", err)
return nil, fmt.Errorf("error decoding List response: %w", err)
}
if apiErr != nil {
return nil, apiErr, nil
return nil, apiErr
}
target.responseBody = resp.Body
target.responseMap = resp.Map
return target, apiErr, nil
return target, nil
}
func (c *Client) AddGrants(ctx context.Context, roleId string, version uint32, grantStrings []string, opt ...Option) (*RoleUpdateResult, *api.Error, error) {
func (c *Client) AddGrants(ctx context.Context, roleId string, version uint32, grantStrings []string, opt ...Option) (*RoleUpdateResult, error) {
if roleId == "" {
return nil, nil, fmt.Errorf("empty roleId value passed into AddGrants request")
return nil, fmt.Errorf("empty roleId value passed into AddGrants request")
}
if len(grantStrings) == 0 {
return nil, nil, errors.New("empty grantStrings passed into AddGrants request")
return nil, errors.New("empty grantStrings passed into AddGrants request")
}
if c.client == nil {
return nil, nil, errors.New("nil client")
return nil, errors.New("nil client")
}
opts, apiOpts := getOpts(opt...)
if version == 0 {
if !opts.withAutomaticVersioning {
return nil, nil, errors.New("zero version number passed into AddGrants request")
return nil, errors.New("zero version number passed into AddGrants request")
}
existingTarget, existingApiErr, existingErr := c.Read(ctx, roleId, opt...)
existingTarget, existingErr := c.Read(ctx, roleId, opt...)
if existingErr != nil {
return nil, nil, fmt.Errorf("error performing initial check-and-set read: %w", existingErr)
}
if existingApiErr != nil {
return nil, nil, fmt.Errorf("error from controller when performing initial check-and-set read: %s", pretty.Sprint(existingApiErr))
if api.AsServerError(existingErr) != nil {
return nil, fmt.Errorf("error from controller when performing initial check-and-set read: %w", existingErr)
}
return nil, fmt.Errorf("error performing initial check-and-set read: %w", existingErr)
}
if existingTarget == nil {
return nil, nil, errors.New("nil resource response found when performing initial check-and-set read")
return nil, errors.New("nil resource response found when performing initial check-and-set read")
}
if existingTarget.Item == nil {
return nil, nil, errors.New("nil resource found when performing initial check-and-set read")
return nil, errors.New("nil resource found when performing initial check-and-set read")
}
version = existingTarget.Item.Version
}
@@ -386,7 +384,7 @@ func (c *Client) AddGrants(ctx context.Context, roleId string, version uint32, g
req, err := c.client.NewRequest(ctx, "POST", fmt.Sprintf("roles/%s:add-grants", roleId), opts.postMap, apiOpts...)
if err != nil {
return nil, nil, fmt.Errorf("error creating AddGrants request: %w", err)
return nil, fmt.Errorf("error creating AddGrants request: %w", err)
}
if len(opts.queryMap) > 0 {
@@ -399,52 +397,52 @@ func (c *Client) AddGrants(ctx context.Context, roleId string, version uint32, g
resp, err := c.client.Do(req)
if err != nil {
return nil, nil, fmt.Errorf("error performing client request during AddGrants call: %w", err)
return nil, fmt.Errorf("error performing client request during AddGrants call: %w", err)
}
target := new(RoleUpdateResult)
target.Item = new(Role)
apiErr, err := resp.Decode(target.Item)
if err != nil {
return nil, nil, fmt.Errorf("error decoding AddGrants response: %w", err)
return nil, fmt.Errorf("error decoding AddGrants response: %w", err)
}
if apiErr != nil {
return nil, apiErr, nil
return nil, apiErr
}
target.responseBody = resp.Body
target.responseMap = resp.Map
return target, apiErr, nil
return target, nil
}
func (c *Client) AddPrincipals(ctx context.Context, roleId string, version uint32, principalIds []string, opt ...Option) (*RoleUpdateResult, *api.Error, error) {
func (c *Client) AddPrincipals(ctx context.Context, roleId string, version uint32, principalIds []string, opt ...Option) (*RoleUpdateResult, error) {
if roleId == "" {
return nil, nil, fmt.Errorf("empty roleId value passed into AddPrincipals request")
return nil, fmt.Errorf("empty roleId value passed into AddPrincipals request")
}
if len(principalIds) == 0 {
return nil, nil, errors.New("empty principalIds passed into AddPrincipals request")
return nil, errors.New("empty principalIds passed into AddPrincipals request")
}
if c.client == nil {
return nil, nil, errors.New("nil client")
return nil, errors.New("nil client")
}
opts, apiOpts := getOpts(opt...)
if version == 0 {
if !opts.withAutomaticVersioning {
return nil, nil, errors.New("zero version number passed into AddPrincipals request")
return nil, errors.New("zero version number passed into AddPrincipals request")
}
existingTarget, existingApiErr, existingErr := c.Read(ctx, roleId, opt...)
existingTarget, existingErr := c.Read(ctx, roleId, opt...)
if existingErr != nil {
return nil, nil, fmt.Errorf("error performing initial check-and-set read: %w", existingErr)
}
if existingApiErr != nil {
return nil, nil, fmt.Errorf("error from controller when performing initial check-and-set read: %s", pretty.Sprint(existingApiErr))
if api.AsServerError(existingErr) != nil {
return nil, fmt.Errorf("error from controller when performing initial check-and-set read: %w", existingErr)
}
return nil, fmt.Errorf("error performing initial check-and-set read: %w", existingErr)
}
if existingTarget == nil {
return nil, nil, errors.New("nil resource response found when performing initial check-and-set read")
return nil, errors.New("nil resource response found when performing initial check-and-set read")
}
if existingTarget.Item == nil {
return nil, nil, errors.New("nil resource found when performing initial check-and-set read")
return nil, errors.New("nil resource found when performing initial check-and-set read")
}
version = existingTarget.Item.Version
}
@@ -454,7 +452,7 @@ func (c *Client) AddPrincipals(ctx context.Context, roleId string, version uint3
req, err := c.client.NewRequest(ctx, "POST", fmt.Sprintf("roles/%s:add-principals", roleId), opts.postMap, apiOpts...)
if err != nil {
return nil, nil, fmt.Errorf("error creating AddPrincipals request: %w", err)
return nil, fmt.Errorf("error creating AddPrincipals request: %w", err)
}
if len(opts.queryMap) > 0 {
@@ -467,50 +465,50 @@ func (c *Client) AddPrincipals(ctx context.Context, roleId string, version uint3
resp, err := c.client.Do(req)
if err != nil {
return nil, nil, fmt.Errorf("error performing client request during AddPrincipals call: %w", err)
return nil, fmt.Errorf("error performing client request during AddPrincipals call: %w", err)
}
target := new(RoleUpdateResult)
target.Item = new(Role)
apiErr, err := resp.Decode(target.Item)
if err != nil {
return nil, nil, fmt.Errorf("error decoding AddPrincipals response: %w", err)
return nil, fmt.Errorf("error decoding AddPrincipals response: %w", err)
}
if apiErr != nil {
return nil, apiErr, nil
return nil, apiErr
}
target.responseBody = resp.Body
target.responseMap = resp.Map
return target, apiErr, nil
return target, nil
}
func (c *Client) SetGrants(ctx context.Context, roleId string, version uint32, grantStrings []string, opt ...Option) (*RoleUpdateResult, *api.Error, error) {
func (c *Client) SetGrants(ctx context.Context, roleId string, version uint32, grantStrings []string, opt ...Option) (*RoleUpdateResult, error) {
if roleId == "" {
return nil, nil, fmt.Errorf("empty roleId value passed into SetGrants request")
return nil, fmt.Errorf("empty roleId value passed into SetGrants request")
}
if c.client == nil {
return nil, nil, errors.New("nil client")
return nil, errors.New("nil client")
}
opts, apiOpts := getOpts(opt...)
if version == 0 {
if !opts.withAutomaticVersioning {
return nil, nil, errors.New("zero version number passed into SetGrants request")
return nil, errors.New("zero version number passed into SetGrants request")
}
existingTarget, existingApiErr, existingErr := c.Read(ctx, roleId, opt...)
existingTarget, existingErr := c.Read(ctx, roleId, opt...)
if existingErr != nil {
return nil, nil, fmt.Errorf("error performing initial check-and-set read: %w", existingErr)
}
if existingApiErr != nil {
return nil, nil, fmt.Errorf("error from controller when performing initial check-and-set read: %s", pretty.Sprint(existingApiErr))
if api.AsServerError(existingErr) != nil {
return nil, fmt.Errorf("error from controller when performing initial check-and-set read: %w", existingErr)
}
return nil, fmt.Errorf("error performing initial check-and-set read: %w", existingErr)
}
if existingTarget == nil {
return nil, nil, errors.New("nil resource response found when performing initial check-and-set read")
return nil, errors.New("nil resource response found when performing initial check-and-set read")
}
if existingTarget.Item == nil {
return nil, nil, errors.New("nil resource found when performing initial check-and-set read")
return nil, errors.New("nil resource found when performing initial check-and-set read")
}
version = existingTarget.Item.Version
}
@@ -520,7 +518,7 @@ func (c *Client) SetGrants(ctx context.Context, roleId string, version uint32, g
req, err := c.client.NewRequest(ctx, "POST", fmt.Sprintf("roles/%s:set-grants", roleId), opts.postMap, apiOpts...)
if err != nil {
return nil, nil, fmt.Errorf("error creating SetGrants request: %w", err)
return nil, fmt.Errorf("error creating SetGrants request: %w", err)
}
if len(opts.queryMap) > 0 {
@@ -533,50 +531,50 @@ func (c *Client) SetGrants(ctx context.Context, roleId string, version uint32, g
resp, err := c.client.Do(req)
if err != nil {
return nil, nil, fmt.Errorf("error performing client request during SetGrants call: %w", err)
return nil, fmt.Errorf("error performing client request during SetGrants call: %w", err)
}
target := new(RoleUpdateResult)
target.Item = new(Role)
apiErr, err := resp.Decode(target.Item)
if err != nil {
return nil, nil, fmt.Errorf("error decoding SetGrants response: %w", err)
return nil, fmt.Errorf("error decoding SetGrants response: %w", err)
}
if apiErr != nil {
return nil, apiErr, nil
return nil, apiErr
}
target.responseBody = resp.Body
target.responseMap = resp.Map
return target, apiErr, nil
return target, nil
}
func (c *Client) SetPrincipals(ctx context.Context, roleId string, version uint32, principalIds []string, opt ...Option) (*RoleUpdateResult, *api.Error, error) {
func (c *Client) SetPrincipals(ctx context.Context, roleId string, version uint32, principalIds []string, opt ...Option) (*RoleUpdateResult, error) {
if roleId == "" {
return nil, nil, fmt.Errorf("empty roleId value passed into SetPrincipals request")
return nil, fmt.Errorf("empty roleId value passed into SetPrincipals request")
}
if c.client == nil {
return nil, nil, errors.New("nil client")
return nil, errors.New("nil client")
}
opts, apiOpts := getOpts(opt...)
if version == 0 {
if !opts.withAutomaticVersioning {
return nil, nil, errors.New("zero version number passed into SetPrincipals request")
return nil, errors.New("zero version number passed into SetPrincipals request")
}
existingTarget, existingApiErr, existingErr := c.Read(ctx, roleId, opt...)
existingTarget, existingErr := c.Read(ctx, roleId, opt...)
if existingErr != nil {
return nil, nil, fmt.Errorf("error performing initial check-and-set read: %w", existingErr)
}
if existingApiErr != nil {
return nil, nil, fmt.Errorf("error from controller when performing initial check-and-set read: %s", pretty.Sprint(existingApiErr))
if api.AsServerError(existingErr) != nil {
return nil, fmt.Errorf("error from controller when performing initial check-and-set read: %w", existingErr)
}
return nil, fmt.Errorf("error performing initial check-and-set read: %w", existingErr)
}
if existingTarget == nil {
return nil, nil, errors.New("nil resource response found when performing initial check-and-set read")
return nil, errors.New("nil resource response found when performing initial check-and-set read")
}
if existingTarget.Item == nil {
return nil, nil, errors.New("nil resource found when performing initial check-and-set read")
return nil, errors.New("nil resource found when performing initial check-and-set read")
}
version = existingTarget.Item.Version
}
@@ -586,7 +584,7 @@ func (c *Client) SetPrincipals(ctx context.Context, roleId string, version uint3
req, err := c.client.NewRequest(ctx, "POST", fmt.Sprintf("roles/%s:set-principals", roleId), opts.postMap, apiOpts...)
if err != nil {
return nil, nil, fmt.Errorf("error creating SetPrincipals request: %w", err)
return nil, fmt.Errorf("error creating SetPrincipals request: %w", err)
}
if len(opts.queryMap) > 0 {
@@ -599,52 +597,52 @@ func (c *Client) SetPrincipals(ctx context.Context, roleId string, version uint3
resp, err := c.client.Do(req)
if err != nil {
return nil, nil, fmt.Errorf("error performing client request during SetPrincipals call: %w", err)
return nil, fmt.Errorf("error performing client request during SetPrincipals call: %w", err)
}
target := new(RoleUpdateResult)
target.Item = new(Role)
apiErr, err := resp.Decode(target.Item)
if err != nil {
return nil, nil, fmt.Errorf("error decoding SetPrincipals response: %w", err)
return nil, fmt.Errorf("error decoding SetPrincipals response: %w", err)
}
if apiErr != nil {
return nil, apiErr, nil
return nil, apiErr
}
target.responseBody = resp.Body
target.responseMap = resp.Map
return target, apiErr, nil
return target, nil
}
func (c *Client) RemoveGrants(ctx context.Context, roleId string, version uint32, grantStrings []string, opt ...Option) (*RoleUpdateResult, *api.Error, error) {
func (c *Client) RemoveGrants(ctx context.Context, roleId string, version uint32, grantStrings []string, opt ...Option) (*RoleUpdateResult, error) {
if roleId == "" {
return nil, nil, fmt.Errorf("empty roleId value passed into RemoveGrants request")
return nil, fmt.Errorf("empty roleId value passed into RemoveGrants request")
}
if len(grantStrings) == 0 {
return nil, nil, errors.New("empty grantStrings passed into RemoveGrants request")
return nil, errors.New("empty grantStrings passed into RemoveGrants request")
}
if c.client == nil {
return nil, nil, errors.New("nil client")
return nil, errors.New("nil client")
}
opts, apiOpts := getOpts(opt...)
if version == 0 {
if !opts.withAutomaticVersioning {
return nil, nil, errors.New("zero version number passed into RemoveGrants request")
return nil, errors.New("zero version number passed into RemoveGrants request")
}
existingTarget, existingApiErr, existingErr := c.Read(ctx, roleId, opt...)
existingTarget, existingErr := c.Read(ctx, roleId, opt...)
if existingErr != nil {
return nil, nil, fmt.Errorf("error performing initial check-and-set read: %w", existingErr)
}
if existingApiErr != nil {
return nil, nil, fmt.Errorf("error from controller when performing initial check-and-set read: %s", pretty.Sprint(existingApiErr))
if api.AsServerError(existingErr) != nil {
return nil, fmt.Errorf("error from controller when performing initial check-and-set read: %w", existingErr)
}
return nil, fmt.Errorf("error performing initial check-and-set read: %w", existingErr)
}
if existingTarget == nil {
return nil, nil, errors.New("nil resource response found when performing initial check-and-set read")
return nil, errors.New("nil resource response found when performing initial check-and-set read")
}
if existingTarget.Item == nil {
return nil, nil, errors.New("nil resource found when performing initial check-and-set read")
return nil, errors.New("nil resource found when performing initial check-and-set read")
}
version = existingTarget.Item.Version
}
@@ -654,7 +652,7 @@ func (c *Client) RemoveGrants(ctx context.Context, roleId string, version uint32
req, err := c.client.NewRequest(ctx, "POST", fmt.Sprintf("roles/%s:remove-grants", roleId), opts.postMap, apiOpts...)
if err != nil {
return nil, nil, fmt.Errorf("error creating RemoveGrants request: %w", err)
return nil, fmt.Errorf("error creating RemoveGrants request: %w", err)
}
if len(opts.queryMap) > 0 {
@@ -667,52 +665,52 @@ func (c *Client) RemoveGrants(ctx context.Context, roleId string, version uint32
resp, err := c.client.Do(req)
if err != nil {
return nil, nil, fmt.Errorf("error performing client request during RemoveGrants call: %w", err)
return nil, fmt.Errorf("error performing client request during RemoveGrants call: %w", err)
}
target := new(RoleUpdateResult)
target.Item = new(Role)
apiErr, err := resp.Decode(target.Item)
if err != nil {
return nil, nil, fmt.Errorf("error decoding RemoveGrants response: %w", err)
return nil, fmt.Errorf("error decoding RemoveGrants response: %w", err)
}
if apiErr != nil {
return nil, apiErr, nil
return nil, apiErr
}
target.responseBody = resp.Body
target.responseMap = resp.Map
return target, apiErr, nil
return target, nil
}
func (c *Client) RemovePrincipals(ctx context.Context, roleId string, version uint32, principalIds []string, opt ...Option) (*RoleUpdateResult, *api.Error, error) {
func (c *Client) RemovePrincipals(ctx context.Context, roleId string, version uint32, principalIds []string, opt ...Option) (*RoleUpdateResult, error) {
if roleId == "" {
return nil, nil, fmt.Errorf("empty roleId value passed into RemovePrincipals request")
return nil, fmt.Errorf("empty roleId value passed into RemovePrincipals request")
}
if len(principalIds) == 0 {
return nil, nil, errors.New("empty principalIds passed into RemovePrincipals request")
return nil, errors.New("empty principalIds passed into RemovePrincipals request")
}
if c.client == nil {
return nil, nil, errors.New("nil client")
return nil, errors.New("nil client")
}
opts, apiOpts := getOpts(opt...)
if version == 0 {
if !opts.withAutomaticVersioning {
return nil, nil, errors.New("zero version number passed into RemovePrincipals request")
return nil, errors.New("zero version number passed into RemovePrincipals request")
}
existingTarget, existingApiErr, existingErr := c.Read(ctx, roleId, opt...)
existingTarget, existingErr := c.Read(ctx, roleId, opt...)
if existingErr != nil {
return nil, nil, fmt.Errorf("error performing initial check-and-set read: %w", existingErr)
}
if existingApiErr != nil {
return nil, nil, fmt.Errorf("error from controller when performing initial check-and-set read: %s", pretty.Sprint(existingApiErr))
if api.AsServerError(existingErr) != nil {
return nil, fmt.Errorf("error from controller when performing initial check-and-set read: %w", existingErr)
}
return nil, fmt.Errorf("error performing initial check-and-set read: %w", existingErr)
}
if existingTarget == nil {
return nil, nil, errors.New("nil resource response found when performing initial check-and-set read")
return nil, errors.New("nil resource response found when performing initial check-and-set read")
}
if existingTarget.Item == nil {
return nil, nil, errors.New("nil resource found when performing initial check-and-set read")
return nil, errors.New("nil resource found when performing initial check-and-set read")
}
version = existingTarget.Item.Version
}
@@ -722,7 +720,7 @@ func (c *Client) RemovePrincipals(ctx context.Context, roleId string, version ui
req, err := c.client.NewRequest(ctx, "POST", fmt.Sprintf("roles/%s:remove-principals", roleId), opts.postMap, apiOpts...)
if err != nil {
return nil, nil, fmt.Errorf("error creating RemovePrincipals request: %w", err)
return nil, fmt.Errorf("error creating RemovePrincipals request: %w", err)
}
if len(opts.queryMap) > 0 {
@@ -735,19 +733,19 @@ func (c *Client) RemovePrincipals(ctx context.Context, roleId string, version ui
resp, err := c.client.Do(req)
if err != nil {
return nil, nil, fmt.Errorf("error performing client request during RemovePrincipals call: %w", err)
return nil, fmt.Errorf("error performing client request during RemovePrincipals call: %w", err)
}
target := new(RoleUpdateResult)
target.Item = new(Role)
apiErr, err := resp.Decode(target.Item)
if err != nil {
return nil, nil, fmt.Errorf("error decoding RemovePrincipals response: %w", err)
return nil, fmt.Errorf("error decoding RemovePrincipals response: %w", err)
}
if apiErr != nil {
return nil, apiErr, nil
return nil, apiErr
}
target.responseBody = resp.Body
target.responseMap = resp.Map
return target, apiErr, nil
return target, nil
}
+41 -56
View File
@@ -11,7 +11,6 @@ import (
"github.com/hashicorp/boundary/api/users"
"github.com/hashicorp/boundary/internal/iam"
"github.com/hashicorp/boundary/internal/servers/controller"
"github.com/kr/pretty"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
@@ -40,9 +39,8 @@ func TestCustom(t *testing.T) {
},
}
user, apiErr, err := users.NewClient(client).Create(tc.Context(), org.GetPublicId())
user, err := users.NewClient(client).Create(tc.Context(), org.GetPublicId())
require.NoError(err)
require.Nil(apiErr)
hasPrincipal := func(role *roles.Role, principalId string) bool {
var foundInPrincipals bool
@@ -62,59 +60,51 @@ func TestCustom(t *testing.T) {
for _, tt := range cases {
t.Run(tt.name, func(t *testing.T) {
g, apiErr, err := groups.NewClient(client).Create(tc.Context(), tt.scopeId)
g, err := groups.NewClient(client).Create(tc.Context(), tt.scopeId)
require.NoError(err)
require.Nil(apiErr)
require.NotNil(g)
rc := roles.NewClient(client)
var version uint32 = 1
r, apiErr, err := rc.Create(tc.Context(), tt.scopeId, roles.WithName("foo"))
r, err := rc.Create(tc.Context(), tt.scopeId, roles.WithName("foo"))
require.NoError(err)
require.Nil(apiErr)
require.NotNil(r)
require.EqualValues(r.Item.Version, version)
version++
updatedRole, apiErr, err := rc.AddPrincipals(tc.Context(), r.Item.Id, r.Item.Version, []string{g.Item.Id})
updatedRole, err := rc.AddPrincipals(tc.Context(), r.Item.Id, r.Item.Version, []string{g.Item.Id})
require.NoError(err)
require.Nil(apiErr, "Got error ", pretty.Sprint(apiErr))
assert.EqualValues(updatedRole.Item.Version, version)
assert.True(hasPrincipal(updatedRole.Item, g.Item.Id))
version++
updatedRole, apiErr, err = rc.SetPrincipals(tc.Context(), updatedRole.Item.Id, updatedRole.Item.Version, []string{user.Item.Id})
updatedRole, err = rc.SetPrincipals(tc.Context(), updatedRole.Item.Id, updatedRole.Item.Version, []string{user.Item.Id})
require.NoError(err)
require.Nil(apiErr, "Got error ", apiErr)
assert.EqualValues(updatedRole.Item.Version, version)
assert.True(hasPrincipal(updatedRole.Item, user.Item.Id))
version++
updatedRole, apiErr, err = rc.RemovePrincipals(tc.Context(), updatedRole.Item.Id, updatedRole.Item.Version, []string{user.Item.Id})
updatedRole, err = rc.RemovePrincipals(tc.Context(), updatedRole.Item.Id, updatedRole.Item.Version, []string{user.Item.Id})
require.NoError(err)
require.Nil(apiErr, "Got error ", apiErr)
assert.EqualValues(updatedRole.Item.Version, version)
assert.Empty(updatedRole.Item.Principals)
version++
updatedRole, apiErr, err = rc.AddGrants(tc.Context(), updatedRole.Item.Id, updatedRole.Item.Version, []string{"id=*;actions=read"})
updatedRole, err = rc.AddGrants(tc.Context(), updatedRole.Item.Id, updatedRole.Item.Version, []string{"id=*;actions=read"})
require.NoError(err)
require.Nil(apiErr, "Got error ", apiErr)
assert.EqualValues(updatedRole.Item.Version, version)
assert.Contains(updatedRole.Item.GrantStrings, "id=*;actions=read")
version++
updatedRole, apiErr, err = rc.SetGrants(tc.Context(), updatedRole.Item.Id, updatedRole.Item.Version, []string{"id=*;actions=*"})
updatedRole, err = rc.SetGrants(tc.Context(), updatedRole.Item.Id, updatedRole.Item.Version, []string{"id=*;actions=*"})
require.NoError(err)
require.Nil(apiErr, "Got error ", apiErr)
assert.EqualValues(updatedRole.Item.Version, version)
assert.Contains(updatedRole.Item.GrantStrings, "id=*;actions=*")
version++
updatedRole, apiErr, err = rc.RemoveGrants(tc.Context(), updatedRole.Item.Id, updatedRole.Item.Version, []string{"id=*;actions=*"})
updatedRole, err = rc.RemoveGrants(tc.Context(), updatedRole.Item.Id, updatedRole.Item.Version, []string{"id=*;actions=*"})
require.NoError(err)
require.Nil(apiErr, "Got error ", apiErr)
assert.EqualValues(updatedRole.Item.Version, version)
assert.Empty(updatedRole.Item.Grants)
version++
@@ -151,9 +141,8 @@ func TestList(t *testing.T) {
var expected []*roles.Role
roleClient := roles.NewClient(client)
p1, apiErr, err := roleClient.List(tc.Context(), tt.scopeId)
p1, err := roleClient.List(tc.Context(), tt.scopeId)
require.NoError(err)
assert.Nil(apiErr)
require.Len(p1.Items, 1)
expected = append(expected, p1.Items[0])
@@ -161,25 +150,21 @@ func TestList(t *testing.T) {
expected = append(expected, &roles.Role{Name: fmt.Sprint(i)})
}
rcr, apiErr, err := roleClient.Create(tc.Context(), tt.scopeId, roles.WithName(expected[1].Name))
rcr, err := roleClient.Create(tc.Context(), tt.scopeId, roles.WithName(expected[1].Name))
require.NoError(err)
require.Nil(apiErr)
expected[1] = rcr.Item
p2, apiErr, err := roleClient.List(tc.Context(), tt.scopeId)
p2, err := roleClient.List(tc.Context(), tt.scopeId)
require.NoError(err)
require.Nil(apiErr)
assert.ElementsMatch(comparableSlice(expected[0:2]), comparableSlice(p2.Items))
for i := 2; i < 11; i++ {
rcr, apiErr, err = roleClient.Create(tc.Context(), tt.scopeId, roles.WithName(expected[i].Name))
rcr, err = roleClient.Create(tc.Context(), tt.scopeId, roles.WithName(expected[i].Name))
assert.NoError(err)
assert.Nil(apiErr)
expected[i] = rcr.Item
}
p3, apiErr, err := roleClient.List(tc.Context(), tt.scopeId)
p3, err := roleClient.List(tc.Context(), tt.scopeId)
require.NoError(err)
require.Nil(apiErr)
assert.ElementsMatch(comparableSlice(expected), comparableSlice(p3.Items))
})
}
@@ -224,11 +209,8 @@ func TestCrud(t *testing.T) {
},
}
checkRole := func(step string, g *roles.Role, apiErr *api.Error, err error, wantedName string, wantedVersion uint32) {
checkRole := func(step string, g *roles.Role, err error, wantedName string, wantedVersion uint32) {
assert.NoError(err, step)
if !assert.Nil(apiErr, step) && apiErr.Message != "" {
t.Errorf("ApiError message: %q", apiErr.Message)
}
assert.NotNil(g, "returned no resource", step)
gotName := ""
if g.Name != "" {
@@ -241,27 +223,25 @@ func TestCrud(t *testing.T) {
for _, tt := range cases {
t.Run(tt.name, func(t *testing.T) {
roleClient := roles.NewClient(client)
g, apiErr, err := roleClient.Create(tc.Context(), tt.scopeId, roles.WithName("foo"))
checkRole("create", g.Item, apiErr, err, "foo", 1)
g, err := roleClient.Create(tc.Context(), tt.scopeId, roles.WithName("foo"))
checkRole("create", g.Item, err, "foo", 1)
g, apiErr, err = roleClient.Read(tc.Context(), g.Item.Id)
checkRole("read", g.Item, apiErr, err, "foo", 1)
g, err = roleClient.Read(tc.Context(), g.Item.Id)
checkRole("read", g.Item, err, "foo", 1)
g, apiErr, err = roleClient.Update(tc.Context(), g.Item.Id, g.Item.Version, roles.WithName("bar"))
checkRole("update", g.Item, apiErr, err, "bar", 2)
g, err = roleClient.Update(tc.Context(), g.Item.Id, g.Item.Version, roles.WithName("bar"))
checkRole("update", g.Item, err, "bar", 2)
g, apiErr, err = roleClient.Update(tc.Context(), g.Item.Id, g.Item.Version, roles.DefaultName())
checkRole("update", g.Item, apiErr, err, "", 3)
g, err = roleClient.Update(tc.Context(), g.Item.Id, g.Item.Version, roles.DefaultName())
checkRole("update", g.Item, err, "", 3)
_, apiErr, err = roleClient.Delete(tc.Context(), g.Item.Id)
_, err = roleClient.Delete(tc.Context(), g.Item.Id)
require.NoError(err)
assert.Nil(apiErr)
})
}
}
func TestErrors(t *testing.T) {
assert, require := assert.New(t), require.New(t)
tc := controller.NewTestController(t, nil)
defer tc.Shutdown()
@@ -286,35 +266,40 @@ func TestErrors(t *testing.T) {
for _, tt := range cases {
t.Run(tt.name, func(t *testing.T) {
assert, require := assert.New(t), require.New(t)
roleClient := roles.NewClient(client)
u, apiErr, err := roleClient.Create(tc.Context(), tt.scopeId, roles.WithName("first"))
u, err := roleClient.Create(tc.Context(), tt.scopeId, roles.WithName("first"))
require.NoError(err)
assert.Nil(apiErr)
assert.NotNil(u)
// Updating the wrong version should fail.
_, apiErr, err = roleClient.Update(tc.Context(), u.Item.Id, 73, roles.WithName("anything"))
require.NoError(err)
_, err = roleClient.Update(tc.Context(), u.Item.Id, 73, roles.WithName("anything"))
require.Error(err)
apiErr := api.AsServerError(err)
assert.NotNil(apiErr)
assert.EqualValues(http.StatusNotFound, apiErr.Status)
// Create another resource with the same name.
_, apiErr, err = roleClient.Create(tc.Context(), tt.scopeId, roles.WithName("first"))
require.NoError(err)
_, err = roleClient.Create(tc.Context(), tt.scopeId, roles.WithName("first"))
require.Error(err)
apiErr = api.AsServerError(err)
assert.NotNil(apiErr)
_, apiErr, err = roleClient.Read(tc.Context(), iam.RolePrefix+"_doesntexis")
require.NoError(err)
_, err = roleClient.Read(tc.Context(), iam.RolePrefix+"_doesntexis")
require.Error(err)
apiErr = api.AsServerError(err)
assert.NotNil(apiErr)
assert.EqualValues(http.StatusNotFound, apiErr.Status)
_, apiErr, err = roleClient.Read(tc.Context(), "invalid id")
require.NoError(err)
_, err = roleClient.Read(tc.Context(), "invalid id")
require.Error(err)
apiErr = api.AsServerError(err)
assert.NotNil(apiErr)
assert.EqualValues(http.StatusBadRequest, apiErr.Status)
_, apiErr, err = roleClient.Update(tc.Context(), u.Item.Id, u.Item.Version)
require.NoError(err)
_, err = roleClient.Update(tc.Context(), u.Item.Id, u.Item.Version)
require.Error(err)
apiErr = api.AsServerError(err)
assert.NotNil(apiErr)
assert.EqualValues(http.StatusBadRequest, apiErr.Status)
})
+48 -50
View File
@@ -9,8 +9,6 @@ import (
"net/url"
"time"
"github.com/kr/pretty"
"github.com/hashicorp/boundary/api"
)
@@ -107,22 +105,22 @@ func (c *Client) ApiClient() *api.Client {
return c.client
}
func (c *Client) Create(ctx context.Context, scopeId string, opt ...Option) (*ScopeCreateResult, *api.Error, error) {
func (c *Client) Create(ctx context.Context, scopeId string, opt ...Option) (*ScopeCreateResult, error) {
if scopeId == "" {
return nil, nil, fmt.Errorf("empty scopeId value passed into Create request")
return nil, fmt.Errorf("empty scopeId value passed into Create request")
}
opts, apiOpts := getOpts(opt...)
if c.client == nil {
return nil, nil, fmt.Errorf("nil client")
return nil, fmt.Errorf("nil client")
}
opts.postMap["scope_id"] = scopeId
req, err := c.client.NewRequest(ctx, "POST", "scopes", opts.postMap, apiOpts...)
if err != nil {
return nil, nil, fmt.Errorf("error creating Create request: %w", err)
return nil, fmt.Errorf("error creating Create request: %w", err)
}
if len(opts.queryMap) > 0 {
@@ -135,36 +133,36 @@ func (c *Client) Create(ctx context.Context, scopeId string, opt ...Option) (*Sc
resp, err := c.client.Do(req)
if err != nil {
return nil, nil, fmt.Errorf("error performing client request during Create call: %w", err)
return nil, fmt.Errorf("error performing client request during Create call: %w", err)
}
target := new(ScopeCreateResult)
target.Item = new(Scope)
apiErr, err := resp.Decode(target.Item)
if err != nil {
return nil, nil, fmt.Errorf("error decoding Create response: %w", err)
return nil, fmt.Errorf("error decoding Create response: %w", err)
}
if apiErr != nil {
return nil, apiErr, nil
return nil, apiErr
}
target.responseBody = resp.Body
target.responseMap = resp.Map
return target, apiErr, nil
return target, nil
}
func (c *Client) Read(ctx context.Context, scopeId string, opt ...Option) (*ScopeReadResult, *api.Error, error) {
func (c *Client) Read(ctx context.Context, scopeId string, opt ...Option) (*ScopeReadResult, error) {
if scopeId == "" {
return nil, nil, fmt.Errorf("empty scopeId value passed into Read request")
return nil, fmt.Errorf("empty scopeId value passed into Read request")
}
if c.client == nil {
return nil, nil, fmt.Errorf("nil client")
return nil, fmt.Errorf("nil client")
}
opts, apiOpts := getOpts(opt...)
req, err := c.client.NewRequest(ctx, "GET", fmt.Sprintf("scopes/%s", scopeId), nil, apiOpts...)
if err != nil {
return nil, nil, fmt.Errorf("error creating Read request: %w", err)
return nil, fmt.Errorf("error creating Read request: %w", err)
}
if len(opts.queryMap) > 0 {
@@ -177,49 +175,49 @@ func (c *Client) Read(ctx context.Context, scopeId string, opt ...Option) (*Scop
resp, err := c.client.Do(req)
if err != nil {
return nil, nil, fmt.Errorf("error performing client request during Read call: %w", err)
return nil, fmt.Errorf("error performing client request during Read call: %w", err)
}
target := new(ScopeReadResult)
target.Item = new(Scope)
apiErr, err := resp.Decode(target.Item)
if err != nil {
return nil, nil, fmt.Errorf("error decoding Read response: %w", err)
return nil, fmt.Errorf("error decoding Read response: %w", err)
}
if apiErr != nil {
return nil, apiErr, nil
return nil, apiErr
}
target.responseBody = resp.Body
target.responseMap = resp.Map
return target, apiErr, nil
return target, nil
}
func (c *Client) Update(ctx context.Context, scopeId string, version uint32, opt ...Option) (*ScopeUpdateResult, *api.Error, error) {
func (c *Client) Update(ctx context.Context, scopeId string, version uint32, opt ...Option) (*ScopeUpdateResult, error) {
if scopeId == "" {
return nil, nil, fmt.Errorf("empty scopeId value passed into Update request")
return nil, fmt.Errorf("empty scopeId value passed into Update request")
}
if c.client == nil {
return nil, nil, fmt.Errorf("nil client")
return nil, fmt.Errorf("nil client")
}
opts, apiOpts := getOpts(opt...)
if version == 0 {
if !opts.withAutomaticVersioning {
return nil, nil, errors.New("zero version number passed into Update request and automatic versioning not specified")
return nil, errors.New("zero version number passed into Update request and automatic versioning not specified")
}
existingTarget, existingApiErr, existingErr := c.Read(ctx, scopeId, opt...)
existingTarget, existingErr := c.Read(ctx, scopeId, opt...)
if existingErr != nil {
return nil, nil, fmt.Errorf("error performing initial check-and-set read: %w", existingErr)
}
if existingApiErr != nil {
return nil, nil, fmt.Errorf("error from controller when performing initial check-and-set read: %s", pretty.Sprint(existingApiErr))
if api.AsServerError(existingErr) != nil {
return nil, fmt.Errorf("error from controller when performing initial check-and-set read: %w", existingErr)
}
return nil, fmt.Errorf("error performing initial check-and-set read: %w", existingErr)
}
if existingTarget == nil {
return nil, nil, errors.New("nil resource response found when performing initial check-and-set read")
return nil, errors.New("nil resource response found when performing initial check-and-set read")
}
if existingTarget.Item == nil {
return nil, nil, errors.New("nil resource found when performing initial check-and-set read")
return nil, errors.New("nil resource found when performing initial check-and-set read")
}
version = existingTarget.Item.Version
}
@@ -228,7 +226,7 @@ func (c *Client) Update(ctx context.Context, scopeId string, version uint32, opt
req, err := c.client.NewRequest(ctx, "PATCH", fmt.Sprintf("scopes/%s", scopeId), opts.postMap, apiOpts...)
if err != nil {
return nil, nil, fmt.Errorf("error creating Update request: %w", err)
return nil, fmt.Errorf("error creating Update request: %w", err)
}
if len(opts.queryMap) > 0 {
@@ -241,36 +239,36 @@ func (c *Client) Update(ctx context.Context, scopeId string, version uint32, opt
resp, err := c.client.Do(req)
if err != nil {
return nil, nil, fmt.Errorf("error performing client request during Update call: %w", err)
return nil, fmt.Errorf("error performing client request during Update call: %w", err)
}
target := new(ScopeUpdateResult)
target.Item = new(Scope)
apiErr, err := resp.Decode(target.Item)
if err != nil {
return nil, nil, fmt.Errorf("error decoding Update response: %w", err)
return nil, fmt.Errorf("error decoding Update response: %w", err)
}
if apiErr != nil {
return nil, apiErr, nil
return nil, apiErr
}
target.responseBody = resp.Body
target.responseMap = resp.Map
return target, apiErr, nil
return target, nil
}
func (c *Client) Delete(ctx context.Context, scopeId string, opt ...Option) (*ScopeDeleteResult, *api.Error, error) {
func (c *Client) Delete(ctx context.Context, scopeId string, opt ...Option) (*ScopeDeleteResult, error) {
if scopeId == "" {
return nil, nil, fmt.Errorf("empty scopeId value passed into Delete request")
return nil, fmt.Errorf("empty scopeId value passed into Delete request")
}
if c.client == nil {
return nil, nil, fmt.Errorf("nil client")
return nil, fmt.Errorf("nil client")
}
opts, apiOpts := getOpts(opt...)
req, err := c.client.NewRequest(ctx, "DELETE", fmt.Sprintf("scopes/%s", scopeId), nil, apiOpts...)
if err != nil {
return nil, nil, fmt.Errorf("error creating Delete request: %w", err)
return nil, fmt.Errorf("error creating Delete request: %w", err)
}
if len(opts.queryMap) > 0 {
@@ -283,30 +281,30 @@ func (c *Client) Delete(ctx context.Context, scopeId string, opt ...Option) (*Sc
resp, err := c.client.Do(req)
if err != nil {
return nil, nil, fmt.Errorf("error performing client request during Delete call: %w", err)
return nil, fmt.Errorf("error performing client request during Delete call: %w", err)
}
apiErr, err := resp.Decode(nil)
if err != nil {
return nil, nil, fmt.Errorf("error decoding Delete response: %w", err)
return nil, fmt.Errorf("error decoding Delete response: %w", err)
}
if apiErr != nil {
return nil, apiErr, nil
return nil, apiErr
}
target := &ScopeDeleteResult{
responseBody: resp.Body,
responseMap: resp.Map,
}
return target, nil, nil
return target, nil
}
func (c *Client) List(ctx context.Context, scopeId string, opt ...Option) (*ScopeListResult, *api.Error, error) {
func (c *Client) List(ctx context.Context, scopeId string, opt ...Option) (*ScopeListResult, error) {
if scopeId == "" {
return nil, nil, fmt.Errorf("empty scopeId value passed into List request")
return nil, fmt.Errorf("empty scopeId value passed into List request")
}
if c.client == nil {
return nil, nil, fmt.Errorf("nil client")
return nil, fmt.Errorf("nil client")
}
opts, apiOpts := getOpts(opt...)
@@ -314,7 +312,7 @@ func (c *Client) List(ctx context.Context, scopeId string, opt ...Option) (*Scop
req, err := c.client.NewRequest(ctx, "GET", "scopes", nil, apiOpts...)
if err != nil {
return nil, nil, fmt.Errorf("error creating List request: %w", err)
return nil, fmt.Errorf("error creating List request: %w", err)
}
if len(opts.queryMap) > 0 {
@@ -327,18 +325,18 @@ func (c *Client) List(ctx context.Context, scopeId string, opt ...Option) (*Scop
resp, err := c.client.Do(req)
if err != nil {
return nil, nil, fmt.Errorf("error performing client request during List call: %w", err)
return nil, fmt.Errorf("error performing client request during List call: %w", err)
}
target := new(ScopeListResult)
apiErr, err := resp.Decode(target)
if err != nil {
return nil, nil, fmt.Errorf("error decoding List response: %w", err)
return nil, fmt.Errorf("error decoding List response: %w", err)
}
if apiErr != nil {
return nil, apiErr, nil
return nil, apiErr
}
target.responseBody = resp.Body
target.responseMap = resp.Map
return target, apiErr, nil
return target, nil
}
+26 -30
View File
@@ -25,21 +25,18 @@ func TestList(t *testing.T) {
scps := scopes.NewClient(client)
pl, apiErr, err := scps.List(tc.Context(), org.GetPublicId())
pl, err := scps.List(tc.Context(), org.GetPublicId())
require.NoError(err)
assert.Nil(apiErr)
assert.Empty(pl.Items)
expected := make([]*scopes.Scope, 10)
for i := 0; i < 10; i++ {
scr, apiErr, err := scps.Create(tc.Context(), org.GetPublicId(), scopes.WithName(fmt.Sprintf("%d", i)))
scr, err := scps.Create(tc.Context(), org.GetPublicId(), scopes.WithName(fmt.Sprintf("%d", i)))
require.NoError(err)
assert.Nil(apiErr)
expected[i] = scr.Item
}
pl, apiErr, err = scps.List(tc.Context(), org.GetPublicId())
pl, err = scps.List(tc.Context(), org.GetPublicId())
require.NoError(err)
assert.Nil(apiErr)
assert.ElementsMatch(comparableSlice(expected), comparableSlice(pl.Items))
}
@@ -71,9 +68,8 @@ func TestCrud(t *testing.T) {
scps := scopes.NewClient(client)
checkProject := func(step string, s *scopes.Scope, apiErr *api.Error, err error, wantedName string, wantedVersion uint32) {
checkProject := func(step string, s *scopes.Scope, err error, wantedName string, wantedVersion uint32) {
require.NoError(err, step)
assert.Nil(apiErr, step)
assert.NotNil(s, "returned project", step)
gotName := ""
if s.Name != "" {
@@ -83,29 +79,28 @@ func TestCrud(t *testing.T) {
assert.Equal(wantedVersion, s.Version)
}
s, apiErr, err := scps.Create(tc.Context(), org.GetPublicId(), scopes.WithName("foo"))
checkProject("create", s.Item, apiErr, err, "foo", 1)
s, err := scps.Create(tc.Context(), org.GetPublicId(), scopes.WithName("foo"))
checkProject("create", s.Item, err, "foo", 1)
s, apiErr, err = scps.Read(tc.Context(), s.Item.Id)
checkProject("read", s.Item, apiErr, err, "foo", 1)
s, err = scps.Read(tc.Context(), s.Item.Id)
checkProject("read", s.Item, err, "foo", 1)
s, apiErr, err = scps.Update(tc.Context(), s.Item.Id, s.Item.Version, scopes.WithName("bar"))
checkProject("update", s.Item, apiErr, err, "bar", 2)
s, err = scps.Update(tc.Context(), s.Item.Id, s.Item.Version, scopes.WithName("bar"))
checkProject("update", s.Item, err, "bar", 2)
s, apiErr, err = scps.Update(tc.Context(), s.Item.Id, s.Item.Version, scopes.DefaultName())
checkProject("update, unset name", s.Item, apiErr, err, "", 3)
s, err = scps.Update(tc.Context(), s.Item.Id, s.Item.Version, scopes.DefaultName())
checkProject("update, unset name", s.Item, err, "", 3)
_, apiErr, err = scps.Delete(tc.Context(), s.Item.Id)
_, err = scps.Delete(tc.Context(), s.Item.Id)
require.NoError(err)
assert.Nil(apiErr)
_, apiErr, err = scps.Delete(tc.Context(), s.Item.Id)
require.NoError(err)
_, err = scps.Delete(tc.Context(), s.Item.Id)
require.Error(err)
apiErr := api.AsServerError(err)
assert.NotNil(apiErr)
assert.EqualValues(http.StatusNotFound, apiErr.Status)
}
// TODO: Get better coverage for expected errors and error formats.
func TestErrors(t *testing.T) {
assert, require := assert.New(t), require.New(t)
tc := controller.NewTestController(t, nil)
@@ -118,25 +113,26 @@ func TestErrors(t *testing.T) {
scps := scopes.NewClient(client)
createdProj, apiErr, err := scps.Create(tc.Context(), org.GetPublicId())
createdProj, err := scps.Create(tc.Context(), org.GetPublicId())
require.NoError(err)
assert.NotNil(createdProj)
assert.Nil(apiErr)
// Updating the wrong version should fail.
_, apiErr, err = scps.Update(tc.Context(), createdProj.Item.Id, 73, scopes.WithName("anything"))
require.NoError(err)
_, err = scps.Update(tc.Context(), createdProj.Item.Id, 73, scopes.WithName("anything"))
require.Error(err)
apiErr := api.AsServerError(err)
assert.NotNil(apiErr)
assert.EqualValues(http.StatusNotFound, apiErr.Status)
_, apiErr, err = scps.Read(tc.Context(), "p_doesntexis")
require.NoError(err)
// TODO: Should this be nil instead of just a Project that has no values set
_, err = scps.Read(tc.Context(), "p_doesntexis")
require.Error(err)
apiErr = api.AsServerError(err)
assert.NotNil(apiErr)
assert.EqualValues(http.StatusNotFound, apiErr.Status)
_, apiErr, err = scps.Read(tc.Context(), "invalid id")
assert.NoError(err)
_, err = scps.Read(tc.Context(), "invalid id")
assert.Error(err)
apiErr = api.AsServerError(err)
assert.NotNil(apiErr)
assert.EqualValues(http.StatusBadRequest, apiErr.Status)
}
+16 -17
View File
@@ -7,35 +7,34 @@ import (
"net/url"
"github.com/hashicorp/boundary/api"
"github.com/kr/pretty"
)
func (c *Client) Cancel(ctx context.Context, sessionId string, version uint32, opt ...Option) (*SessionUpdateResult, *api.Error, error) {
func (c *Client) Cancel(ctx context.Context, sessionId string, version uint32, opt ...Option) (*SessionUpdateResult, error) {
if sessionId == "" {
return nil, nil, fmt.Errorf("empty sessionId value passed into Cancel request")
return nil, fmt.Errorf("empty sessionId value passed into Cancel request")
}
if c.client == nil {
return nil, nil, errors.New("nil client")
return nil, errors.New("nil client")
}
opts, apiOpts := getOpts(opt...)
if version == 0 {
if !opts.withAutomaticVersioning {
return nil, nil, errors.New("zero version number passed into Cancel request")
return nil, errors.New("zero version number passed into Cancel request")
}
existingSession, existingApiErr, existingErr := c.Read(ctx, sessionId, opt...)
existingSession, existingErr := c.Read(ctx, sessionId, opt...)
if existingErr != nil {
return nil, nil, fmt.Errorf("error performing initial check-and-set read: %w", existingErr)
}
if existingApiErr != nil {
return nil, nil, fmt.Errorf("error from controller when performing initial check-and-set read: %s", pretty.Sprint(existingApiErr))
if api.AsServerError(existingErr) != nil {
return nil, fmt.Errorf("error from controller when performing initial check-and-set read: %w", existingErr)
}
return nil, fmt.Errorf("error performing initial check-and-set read: %w", existingErr)
}
if existingSession == nil {
return nil, nil, errors.New("nil resource response found when performing initial check-and-set read")
return nil, errors.New("nil resource response found when performing initial check-and-set read")
}
if existingSession.Item == nil {
return nil, nil, errors.New("nil resource found when performing initial check-and-set read")
return nil, errors.New("nil resource found when performing initial check-and-set read")
}
version = existingSession.Item.Version
}
@@ -44,7 +43,7 @@ func (c *Client) Cancel(ctx context.Context, sessionId string, version uint32, o
req, err := c.client.NewRequest(ctx, "POST", fmt.Sprintf("sessions/%s:cancel", sessionId), opts.postMap, apiOpts...)
if err != nil {
return nil, nil, fmt.Errorf("error creating Cancel request: %w", err)
return nil, fmt.Errorf("error creating Cancel request: %w", err)
}
if len(opts.queryMap) > 0 {
@@ -57,19 +56,19 @@ func (c *Client) Cancel(ctx context.Context, sessionId string, version uint32, o
resp, err := c.client.Do(req)
if err != nil {
return nil, nil, fmt.Errorf("error performing client request during Cancel call: %w", err)
return nil, fmt.Errorf("error performing client request during Cancel call: %w", err)
}
target := new(SessionUpdateResult)
target.Item = new(Session)
apiErr, err := resp.Decode(target.Item)
if err != nil {
return nil, nil, fmt.Errorf("error decoding Cancel response: %w", err)
return nil, fmt.Errorf("error decoding Cancel response: %w", err)
}
if apiErr != nil {
return nil, apiErr, nil
return nil, apiErr
}
target.responseBody = resp.Body
target.responseMap = resp.Map
return target, apiErr, nil
return target, nil
}
+16 -16
View File
@@ -114,19 +114,19 @@ func (c *Client) ApiClient() *api.Client {
return c.client
}
func (c *Client) Read(ctx context.Context, sessionId string, opt ...Option) (*SessionReadResult, *api.Error, error) {
func (c *Client) Read(ctx context.Context, sessionId string, opt ...Option) (*SessionReadResult, error) {
if sessionId == "" {
return nil, nil, fmt.Errorf("empty sessionId value passed into Read request")
return nil, fmt.Errorf("empty sessionId value passed into Read request")
}
if c.client == nil {
return nil, nil, fmt.Errorf("nil client")
return nil, fmt.Errorf("nil client")
}
opts, apiOpts := getOpts(opt...)
req, err := c.client.NewRequest(ctx, "GET", fmt.Sprintf("sessions/%s", sessionId), nil, apiOpts...)
if err != nil {
return nil, nil, fmt.Errorf("error creating Read request: %w", err)
return nil, fmt.Errorf("error creating Read request: %w", err)
}
if len(opts.queryMap) > 0 {
@@ -139,29 +139,29 @@ func (c *Client) Read(ctx context.Context, sessionId string, opt ...Option) (*Se
resp, err := c.client.Do(req)
if err != nil {
return nil, nil, fmt.Errorf("error performing client request during Read call: %w", err)
return nil, fmt.Errorf("error performing client request during Read call: %w", err)
}
target := new(SessionReadResult)
target.Item = new(Session)
apiErr, err := resp.Decode(target.Item)
if err != nil {
return nil, nil, fmt.Errorf("error decoding Read response: %w", err)
return nil, fmt.Errorf("error decoding Read response: %w", err)
}
if apiErr != nil {
return nil, apiErr, nil
return nil, apiErr
}
target.responseBody = resp.Body
target.responseMap = resp.Map
return target, apiErr, nil
return target, nil
}
func (c *Client) List(ctx context.Context, scopeId string, opt ...Option) (*SessionListResult, *api.Error, error) {
func (c *Client) List(ctx context.Context, scopeId string, opt ...Option) (*SessionListResult, error) {
if scopeId == "" {
return nil, nil, fmt.Errorf("empty scopeId value passed into List request")
return nil, fmt.Errorf("empty scopeId value passed into List request")
}
if c.client == nil {
return nil, nil, fmt.Errorf("nil client")
return nil, fmt.Errorf("nil client")
}
opts, apiOpts := getOpts(opt...)
@@ -169,7 +169,7 @@ func (c *Client) List(ctx context.Context, scopeId string, opt ...Option) (*Sess
req, err := c.client.NewRequest(ctx, "GET", "sessions", nil, apiOpts...)
if err != nil {
return nil, nil, fmt.Errorf("error creating List request: %w", err)
return nil, fmt.Errorf("error creating List request: %w", err)
}
if len(opts.queryMap) > 0 {
@@ -182,18 +182,18 @@ func (c *Client) List(ctx context.Context, scopeId string, opt ...Option) (*Sess
resp, err := c.client.Do(req)
if err != nil {
return nil, nil, fmt.Errorf("error performing client request during List call: %w", err)
return nil, fmt.Errorf("error performing client request during List call: %w", err)
}
target := new(SessionListResult)
apiErr, err := resp.Decode(target)
if err != nil {
return nil, nil, fmt.Errorf("error decoding List response: %w", err)
return nil, fmt.Errorf("error decoding List response: %w", err)
}
if apiErr != nil {
return nil, apiErr, nil
return nil, apiErr
}
target.responseBody = resp.Body
target.responseMap = resp.Map
return target, apiErr, nil
return target, nil
}
+8 -10
View File
@@ -5,8 +5,6 @@ import (
"context"
"fmt"
"net/url"
"github.com/hashicorp/boundary/api"
)
type SessionAuthorizationResult struct {
@@ -27,20 +25,20 @@ func (n SessionAuthorizationResult) GetResponseMap() map[string]interface{} {
return n.responseMap
}
func (c *Client) Authorize(ctx context.Context, targetId string, opt ...Option) (*SessionAuthorizationResult, *api.Error, error) {
func (c *Client) Authorize(ctx context.Context, targetId string, opt ...Option) (*SessionAuthorizationResult, error) {
if targetId == "" {
return nil, nil, fmt.Errorf("empty targetId value passed into Authorize request")
return nil, fmt.Errorf("empty targetId value passed into Authorize request")
}
opts, apiOpts := getOpts(opt...)
if c.client == nil {
return nil, nil, fmt.Errorf("nil client")
return nil, fmt.Errorf("nil client")
}
req, err := c.client.NewRequest(ctx, "POST", fmt.Sprintf("targets/%s:authorize", targetId), opts.postMap, apiOpts...)
if err != nil {
return nil, nil, fmt.Errorf("error creating Authorize request: %w", err)
return nil, fmt.Errorf("error creating Authorize request: %w", err)
}
if len(opts.queryMap) > 0 {
@@ -53,19 +51,19 @@ func (c *Client) Authorize(ctx context.Context, targetId string, opt ...Option)
resp, err := c.client.Do(req)
if err != nil {
return nil, nil, fmt.Errorf("error performing client request during Authorize call: %w", err)
return nil, fmt.Errorf("error performing client request during Authorize call: %w", err)
}
sar := new(SessionAuthorizationResult)
sar.Item = new(SessionAuthorization)
apiErr, err := resp.Decode(sar.Item)
if err != nil {
return nil, nil, fmt.Errorf("error decoding Authorize response: %w", err)
return nil, fmt.Errorf("error decoding Authorize response: %w", err)
}
if apiErr != nil {
return nil, apiErr, nil
return nil, apiErr
}
sar.responseBody = resp.Body
sar.responseMap = resp.Map
return sar, apiErr, nil
return sar, nil
}
+99 -101
View File
@@ -9,8 +9,6 @@ import (
"net/url"
"time"
"github.com/kr/pretty"
"github.com/hashicorp/boundary/api"
"github.com/hashicorp/boundary/api/scopes"
)
@@ -113,18 +111,18 @@ func (c *Client) ApiClient() *api.Client {
return c.client
}
func (c *Client) Create(ctx context.Context, resourceType string, scopeId string, opt ...Option) (*TargetCreateResult, *api.Error, error) {
func (c *Client) Create(ctx context.Context, resourceType string, scopeId string, opt ...Option) (*TargetCreateResult, error) {
if scopeId == "" {
return nil, nil, fmt.Errorf("empty scopeId value passed into Create request")
return nil, fmt.Errorf("empty scopeId value passed into Create request")
}
opts, apiOpts := getOpts(opt...)
if c.client == nil {
return nil, nil, fmt.Errorf("nil client")
return nil, fmt.Errorf("nil client")
}
if resourceType == "" {
return nil, nil, fmt.Errorf("empty resourceType value passed into Create request")
return nil, fmt.Errorf("empty resourceType value passed into Create request")
} else {
opts.postMap["type"] = resourceType
}
@@ -133,7 +131,7 @@ func (c *Client) Create(ctx context.Context, resourceType string, scopeId string
req, err := c.client.NewRequest(ctx, "POST", "targets", opts.postMap, apiOpts...)
if err != nil {
return nil, nil, fmt.Errorf("error creating Create request: %w", err)
return nil, fmt.Errorf("error creating Create request: %w", err)
}
if len(opts.queryMap) > 0 {
@@ -146,36 +144,36 @@ func (c *Client) Create(ctx context.Context, resourceType string, scopeId string
resp, err := c.client.Do(req)
if err != nil {
return nil, nil, fmt.Errorf("error performing client request during Create call: %w", err)
return nil, fmt.Errorf("error performing client request during Create call: %w", err)
}
target := new(TargetCreateResult)
target.Item = new(Target)
apiErr, err := resp.Decode(target.Item)
if err != nil {
return nil, nil, fmt.Errorf("error decoding Create response: %w", err)
return nil, fmt.Errorf("error decoding Create response: %w", err)
}
if apiErr != nil {
return nil, apiErr, nil
return nil, apiErr
}
target.responseBody = resp.Body
target.responseMap = resp.Map
return target, apiErr, nil
return target, nil
}
func (c *Client) Read(ctx context.Context, targetId string, opt ...Option) (*TargetReadResult, *api.Error, error) {
func (c *Client) Read(ctx context.Context, targetId string, opt ...Option) (*TargetReadResult, error) {
if targetId == "" {
return nil, nil, fmt.Errorf("empty targetId value passed into Read request")
return nil, fmt.Errorf("empty targetId value passed into Read request")
}
if c.client == nil {
return nil, nil, fmt.Errorf("nil client")
return nil, fmt.Errorf("nil client")
}
opts, apiOpts := getOpts(opt...)
req, err := c.client.NewRequest(ctx, "GET", fmt.Sprintf("targets/%s", targetId), nil, apiOpts...)
if err != nil {
return nil, nil, fmt.Errorf("error creating Read request: %w", err)
return nil, fmt.Errorf("error creating Read request: %w", err)
}
if len(opts.queryMap) > 0 {
@@ -188,49 +186,49 @@ func (c *Client) Read(ctx context.Context, targetId string, opt ...Option) (*Tar
resp, err := c.client.Do(req)
if err != nil {
return nil, nil, fmt.Errorf("error performing client request during Read call: %w", err)
return nil, fmt.Errorf("error performing client request during Read call: %w", err)
}
target := new(TargetReadResult)
target.Item = new(Target)
apiErr, err := resp.Decode(target.Item)
if err != nil {
return nil, nil, fmt.Errorf("error decoding Read response: %w", err)
return nil, fmt.Errorf("error decoding Read response: %w", err)
}
if apiErr != nil {
return nil, apiErr, nil
return nil, apiErr
}
target.responseBody = resp.Body
target.responseMap = resp.Map
return target, apiErr, nil
return target, nil
}
func (c *Client) Update(ctx context.Context, targetId string, version uint32, opt ...Option) (*TargetUpdateResult, *api.Error, error) {
func (c *Client) Update(ctx context.Context, targetId string, version uint32, opt ...Option) (*TargetUpdateResult, error) {
if targetId == "" {
return nil, nil, fmt.Errorf("empty targetId value passed into Update request")
return nil, fmt.Errorf("empty targetId value passed into Update request")
}
if c.client == nil {
return nil, nil, fmt.Errorf("nil client")
return nil, fmt.Errorf("nil client")
}
opts, apiOpts := getOpts(opt...)
if version == 0 {
if !opts.withAutomaticVersioning {
return nil, nil, errors.New("zero version number passed into Update request and automatic versioning not specified")
return nil, errors.New("zero version number passed into Update request and automatic versioning not specified")
}
existingTarget, existingApiErr, existingErr := c.Read(ctx, targetId, opt...)
existingTarget, existingErr := c.Read(ctx, targetId, opt...)
if existingErr != nil {
return nil, nil, fmt.Errorf("error performing initial check-and-set read: %w", existingErr)
}
if existingApiErr != nil {
return nil, nil, fmt.Errorf("error from controller when performing initial check-and-set read: %s", pretty.Sprint(existingApiErr))
if api.AsServerError(existingErr) != nil {
return nil, fmt.Errorf("error from controller when performing initial check-and-set read: %w", existingErr)
}
return nil, fmt.Errorf("error performing initial check-and-set read: %w", existingErr)
}
if existingTarget == nil {
return nil, nil, errors.New("nil resource response found when performing initial check-and-set read")
return nil, errors.New("nil resource response found when performing initial check-and-set read")
}
if existingTarget.Item == nil {
return nil, nil, errors.New("nil resource found when performing initial check-and-set read")
return nil, errors.New("nil resource found when performing initial check-and-set read")
}
version = existingTarget.Item.Version
}
@@ -239,7 +237,7 @@ func (c *Client) Update(ctx context.Context, targetId string, version uint32, op
req, err := c.client.NewRequest(ctx, "PATCH", fmt.Sprintf("targets/%s", targetId), opts.postMap, apiOpts...)
if err != nil {
return nil, nil, fmt.Errorf("error creating Update request: %w", err)
return nil, fmt.Errorf("error creating Update request: %w", err)
}
if len(opts.queryMap) > 0 {
@@ -252,36 +250,36 @@ func (c *Client) Update(ctx context.Context, targetId string, version uint32, op
resp, err := c.client.Do(req)
if err != nil {
return nil, nil, fmt.Errorf("error performing client request during Update call: %w", err)
return nil, fmt.Errorf("error performing client request during Update call: %w", err)
}
target := new(TargetUpdateResult)
target.Item = new(Target)
apiErr, err := resp.Decode(target.Item)
if err != nil {
return nil, nil, fmt.Errorf("error decoding Update response: %w", err)
return nil, fmt.Errorf("error decoding Update response: %w", err)
}
if apiErr != nil {
return nil, apiErr, nil
return nil, apiErr
}
target.responseBody = resp.Body
target.responseMap = resp.Map
return target, apiErr, nil
return target, nil
}
func (c *Client) Delete(ctx context.Context, targetId string, opt ...Option) (*TargetDeleteResult, *api.Error, error) {
func (c *Client) Delete(ctx context.Context, targetId string, opt ...Option) (*TargetDeleteResult, error) {
if targetId == "" {
return nil, nil, fmt.Errorf("empty targetId value passed into Delete request")
return nil, fmt.Errorf("empty targetId value passed into Delete request")
}
if c.client == nil {
return nil, nil, fmt.Errorf("nil client")
return nil, fmt.Errorf("nil client")
}
opts, apiOpts := getOpts(opt...)
req, err := c.client.NewRequest(ctx, "DELETE", fmt.Sprintf("targets/%s", targetId), nil, apiOpts...)
if err != nil {
return nil, nil, fmt.Errorf("error creating Delete request: %w", err)
return nil, fmt.Errorf("error creating Delete request: %w", err)
}
if len(opts.queryMap) > 0 {
@@ -294,30 +292,30 @@ func (c *Client) Delete(ctx context.Context, targetId string, opt ...Option) (*T
resp, err := c.client.Do(req)
if err != nil {
return nil, nil, fmt.Errorf("error performing client request during Delete call: %w", err)
return nil, fmt.Errorf("error performing client request during Delete call: %w", err)
}
apiErr, err := resp.Decode(nil)
if err != nil {
return nil, nil, fmt.Errorf("error decoding Delete response: %w", err)
return nil, fmt.Errorf("error decoding Delete response: %w", err)
}
if apiErr != nil {
return nil, apiErr, nil
return nil, apiErr
}
target := &TargetDeleteResult{
responseBody: resp.Body,
responseMap: resp.Map,
}
return target, nil, nil
return target, nil
}
func (c *Client) List(ctx context.Context, scopeId string, opt ...Option) (*TargetListResult, *api.Error, error) {
func (c *Client) List(ctx context.Context, scopeId string, opt ...Option) (*TargetListResult, error) {
if scopeId == "" {
return nil, nil, fmt.Errorf("empty scopeId value passed into List request")
return nil, fmt.Errorf("empty scopeId value passed into List request")
}
if c.client == nil {
return nil, nil, fmt.Errorf("nil client")
return nil, fmt.Errorf("nil client")
}
opts, apiOpts := getOpts(opt...)
@@ -325,7 +323,7 @@ func (c *Client) List(ctx context.Context, scopeId string, opt ...Option) (*Targ
req, err := c.client.NewRequest(ctx, "GET", "targets", nil, apiOpts...)
if err != nil {
return nil, nil, fmt.Errorf("error creating List request: %w", err)
return nil, fmt.Errorf("error creating List request: %w", err)
}
if len(opts.queryMap) > 0 {
@@ -338,51 +336,51 @@ func (c *Client) List(ctx context.Context, scopeId string, opt ...Option) (*Targ
resp, err := c.client.Do(req)
if err != nil {
return nil, nil, fmt.Errorf("error performing client request during List call: %w", err)
return nil, fmt.Errorf("error performing client request during List call: %w", err)
}
target := new(TargetListResult)
apiErr, err := resp.Decode(target)
if err != nil {
return nil, nil, fmt.Errorf("error decoding List response: %w", err)
return nil, fmt.Errorf("error decoding List response: %w", err)
}
if apiErr != nil {
return nil, apiErr, nil
return nil, apiErr
}
target.responseBody = resp.Body
target.responseMap = resp.Map
return target, apiErr, nil
return target, nil
}
func (c *Client) AddHostSets(ctx context.Context, targetId string, version uint32, hostSetIds []string, opt ...Option) (*TargetUpdateResult, *api.Error, error) {
func (c *Client) AddHostSets(ctx context.Context, targetId string, version uint32, hostSetIds []string, opt ...Option) (*TargetUpdateResult, error) {
if targetId == "" {
return nil, nil, fmt.Errorf("empty targetId value passed into AddHostSets request")
return nil, fmt.Errorf("empty targetId value passed into AddHostSets request")
}
if len(hostSetIds) == 0 {
return nil, nil, errors.New("empty hostSetIds passed into AddHostSets request")
return nil, errors.New("empty hostSetIds passed into AddHostSets request")
}
if c.client == nil {
return nil, nil, errors.New("nil client")
return nil, errors.New("nil client")
}
opts, apiOpts := getOpts(opt...)
if version == 0 {
if !opts.withAutomaticVersioning {
return nil, nil, errors.New("zero version number passed into AddHostSets request")
return nil, errors.New("zero version number passed into AddHostSets request")
}
existingTarget, existingApiErr, existingErr := c.Read(ctx, targetId, opt...)
existingTarget, existingErr := c.Read(ctx, targetId, opt...)
if existingErr != nil {
return nil, nil, fmt.Errorf("error performing initial check-and-set read: %w", existingErr)
}
if existingApiErr != nil {
return nil, nil, fmt.Errorf("error from controller when performing initial check-and-set read: %s", pretty.Sprint(existingApiErr))
if api.AsServerError(existingErr) != nil {
return nil, fmt.Errorf("error from controller when performing initial check-and-set read: %w", existingErr)
}
return nil, fmt.Errorf("error performing initial check-and-set read: %w", existingErr)
}
if existingTarget == nil {
return nil, nil, errors.New("nil resource response found when performing initial check-and-set read")
return nil, errors.New("nil resource response found when performing initial check-and-set read")
}
if existingTarget.Item == nil {
return nil, nil, errors.New("nil resource found when performing initial check-and-set read")
return nil, errors.New("nil resource found when performing initial check-and-set read")
}
version = existingTarget.Item.Version
}
@@ -392,7 +390,7 @@ func (c *Client) AddHostSets(ctx context.Context, targetId string, version uint3
req, err := c.client.NewRequest(ctx, "POST", fmt.Sprintf("targets/%s:add-host-sets", targetId), opts.postMap, apiOpts...)
if err != nil {
return nil, nil, fmt.Errorf("error creating AddHostSets request: %w", err)
return nil, fmt.Errorf("error creating AddHostSets request: %w", err)
}
if len(opts.queryMap) > 0 {
@@ -405,50 +403,50 @@ func (c *Client) AddHostSets(ctx context.Context, targetId string, version uint3
resp, err := c.client.Do(req)
if err != nil {
return nil, nil, fmt.Errorf("error performing client request during AddHostSets call: %w", err)
return nil, fmt.Errorf("error performing client request during AddHostSets call: %w", err)
}
target := new(TargetUpdateResult)
target.Item = new(Target)
apiErr, err := resp.Decode(target.Item)
if err != nil {
return nil, nil, fmt.Errorf("error decoding AddHostSets response: %w", err)
return nil, fmt.Errorf("error decoding AddHostSets response: %w", err)
}
if apiErr != nil {
return nil, apiErr, nil
return nil, apiErr
}
target.responseBody = resp.Body
target.responseMap = resp.Map
return target, apiErr, nil
return target, nil
}
func (c *Client) SetHostSets(ctx context.Context, targetId string, version uint32, hostSetIds []string, opt ...Option) (*TargetUpdateResult, *api.Error, error) {
func (c *Client) SetHostSets(ctx context.Context, targetId string, version uint32, hostSetIds []string, opt ...Option) (*TargetUpdateResult, error) {
if targetId == "" {
return nil, nil, fmt.Errorf("empty targetId value passed into SetHostSets request")
return nil, fmt.Errorf("empty targetId value passed into SetHostSets request")
}
if c.client == nil {
return nil, nil, errors.New("nil client")
return nil, errors.New("nil client")
}
opts, apiOpts := getOpts(opt...)
if version == 0 {
if !opts.withAutomaticVersioning {
return nil, nil, errors.New("zero version number passed into SetHostSets request")
return nil, errors.New("zero version number passed into SetHostSets request")
}
existingTarget, existingApiErr, existingErr := c.Read(ctx, targetId, opt...)
existingTarget, existingErr := c.Read(ctx, targetId, opt...)
if existingErr != nil {
return nil, nil, fmt.Errorf("error performing initial check-and-set read: %w", existingErr)
}
if existingApiErr != nil {
return nil, nil, fmt.Errorf("error from controller when performing initial check-and-set read: %s", pretty.Sprint(existingApiErr))
if api.AsServerError(existingErr) != nil {
return nil, fmt.Errorf("error from controller when performing initial check-and-set read: %w", existingErr)
}
return nil, fmt.Errorf("error performing initial check-and-set read: %w", existingErr)
}
if existingTarget == nil {
return nil, nil, errors.New("nil resource response found when performing initial check-and-set read")
return nil, errors.New("nil resource response found when performing initial check-and-set read")
}
if existingTarget.Item == nil {
return nil, nil, errors.New("nil resource found when performing initial check-and-set read")
return nil, errors.New("nil resource found when performing initial check-and-set read")
}
version = existingTarget.Item.Version
}
@@ -458,7 +456,7 @@ func (c *Client) SetHostSets(ctx context.Context, targetId string, version uint3
req, err := c.client.NewRequest(ctx, "POST", fmt.Sprintf("targets/%s:set-host-sets", targetId), opts.postMap, apiOpts...)
if err != nil {
return nil, nil, fmt.Errorf("error creating SetHostSets request: %w", err)
return nil, fmt.Errorf("error creating SetHostSets request: %w", err)
}
if len(opts.queryMap) > 0 {
@@ -471,52 +469,52 @@ func (c *Client) SetHostSets(ctx context.Context, targetId string, version uint3
resp, err := c.client.Do(req)
if err != nil {
return nil, nil, fmt.Errorf("error performing client request during SetHostSets call: %w", err)
return nil, fmt.Errorf("error performing client request during SetHostSets call: %w", err)
}
target := new(TargetUpdateResult)
target.Item = new(Target)
apiErr, err := resp.Decode(target.Item)
if err != nil {
return nil, nil, fmt.Errorf("error decoding SetHostSets response: %w", err)
return nil, fmt.Errorf("error decoding SetHostSets response: %w", err)
}
if apiErr != nil {
return nil, apiErr, nil
return nil, apiErr
}
target.responseBody = resp.Body
target.responseMap = resp.Map
return target, apiErr, nil
return target, nil
}
func (c *Client) RemoveHostSets(ctx context.Context, targetId string, version uint32, hostSetIds []string, opt ...Option) (*TargetUpdateResult, *api.Error, error) {
func (c *Client) RemoveHostSets(ctx context.Context, targetId string, version uint32, hostSetIds []string, opt ...Option) (*TargetUpdateResult, error) {
if targetId == "" {
return nil, nil, fmt.Errorf("empty targetId value passed into RemoveHostSets request")
return nil, fmt.Errorf("empty targetId value passed into RemoveHostSets request")
}
if len(hostSetIds) == 0 {
return nil, nil, errors.New("empty hostSetIds passed into RemoveHostSets request")
return nil, errors.New("empty hostSetIds passed into RemoveHostSets request")
}
if c.client == nil {
return nil, nil, errors.New("nil client")
return nil, errors.New("nil client")
}
opts, apiOpts := getOpts(opt...)
if version == 0 {
if !opts.withAutomaticVersioning {
return nil, nil, errors.New("zero version number passed into RemoveHostSets request")
return nil, errors.New("zero version number passed into RemoveHostSets request")
}
existingTarget, existingApiErr, existingErr := c.Read(ctx, targetId, opt...)
existingTarget, existingErr := c.Read(ctx, targetId, opt...)
if existingErr != nil {
return nil, nil, fmt.Errorf("error performing initial check-and-set read: %w", existingErr)
}
if existingApiErr != nil {
return nil, nil, fmt.Errorf("error from controller when performing initial check-and-set read: %s", pretty.Sprint(existingApiErr))
if api.AsServerError(existingErr) != nil {
return nil, fmt.Errorf("error from controller when performing initial check-and-set read: %w", existingErr)
}
return nil, fmt.Errorf("error performing initial check-and-set read: %w", existingErr)
}
if existingTarget == nil {
return nil, nil, errors.New("nil resource response found when performing initial check-and-set read")
return nil, errors.New("nil resource response found when performing initial check-and-set read")
}
if existingTarget.Item == nil {
return nil, nil, errors.New("nil resource found when performing initial check-and-set read")
return nil, errors.New("nil resource found when performing initial check-and-set read")
}
version = existingTarget.Item.Version
}
@@ -526,7 +524,7 @@ func (c *Client) RemoveHostSets(ctx context.Context, targetId string, version ui
req, err := c.client.NewRequest(ctx, "POST", fmt.Sprintf("targets/%s:remove-host-sets", targetId), opts.postMap, apiOpts...)
if err != nil {
return nil, nil, fmt.Errorf("error creating RemoveHostSets request: %w", err)
return nil, fmt.Errorf("error creating RemoveHostSets request: %w", err)
}
if len(opts.queryMap) > 0 {
@@ -539,19 +537,19 @@ func (c *Client) RemoveHostSets(ctx context.Context, targetId string, version ui
resp, err := c.client.Do(req)
if err != nil {
return nil, nil, fmt.Errorf("error performing client request during RemoveHostSets call: %w", err)
return nil, fmt.Errorf("error performing client request during RemoveHostSets call: %w", err)
}
target := new(TargetUpdateResult)
target.Item = new(Target)
apiErr, err := resp.Decode(target.Item)
if err != nil {
return nil, nil, fmt.Errorf("error decoding RemoveHostSets response: %w", err)
return nil, fmt.Errorf("error decoding RemoveHostSets response: %w", err)
}
if apiErr != nil {
return nil, apiErr, nil
return nil, apiErr
}
target.responseBody = resp.Body
target.responseMap = resp.Map
return target, apiErr, nil
return target, nil
}
+36 -48
View File
@@ -26,42 +26,35 @@ func TestCustom(t *testing.T) {
client := tc.Client().Clone()
client.SetToken(token.Token)
hc, apiErr, err := hostcatalogs.NewClient(client).Create(tc.Context(), "static", proj.GetPublicId())
hc, err := hostcatalogs.NewClient(client).Create(tc.Context(), "static", proj.GetPublicId())
require.NoError(err)
require.Nil(apiErr)
hSetClient := hostsets.NewClient(client)
hSet, apiErr, err := hSetClient.Create(tc.Context(), hc.Item.Id)
hSet, err := hSetClient.Create(tc.Context(), hc.Item.Id)
require.NoError(err)
require.Nil(apiErr)
require.NotNil(hSet)
hSet2, apiErr, err := hSetClient.Create(tc.Context(), hc.Item.Id)
hSet2, err := hSetClient.Create(tc.Context(), hc.Item.Id)
require.NoError(err)
require.Nil(apiErr)
require.NotNil(hSet2)
tarClient := targets.NewClient(client)
tar, apiErr, err := tarClient.Create(tc.Context(), "tcp", proj.GetPublicId(), targets.WithName("foo"))
tar, err := tarClient.Create(tc.Context(), "tcp", proj.GetPublicId(), targets.WithName("foo"))
require.NoError(err)
require.Nil(apiErr)
require.NotNil(tar)
assert.Empty(tar.Item.HostSetIds)
tar, apiErr, err = tarClient.AddHostSets(tc.Context(), tar.Item.Id, tar.Item.Version, []string{hSet.Item.Id})
tar, err = tarClient.AddHostSets(tc.Context(), tar.Item.Id, tar.Item.Version, []string{hSet.Item.Id})
require.NoError(err)
require.Nil(apiErr)
require.NotNil(tar)
assert.ElementsMatch(tar.Item.HostSetIds, []string{hSet.Item.Id})
tar, apiErr, err = tarClient.SetHostSets(tc.Context(), tar.Item.Id, tar.Item.Version, []string{hSet2.Item.Id})
tar, err = tarClient.SetHostSets(tc.Context(), tar.Item.Id, tar.Item.Version, []string{hSet2.Item.Id})
require.NoError(err)
require.Nil(apiErr)
require.NotNil(tar)
assert.ElementsMatch(tar.Item.HostSetIds, []string{hSet2.Item.Id})
tar, apiErr, err = tarClient.RemoveHostSets(tc.Context(), tar.Item.Id, tar.Item.Version, []string{hSet2.Item.Id})
tar, err = tarClient.RemoveHostSets(tc.Context(), tar.Item.Id, tar.Item.Version, []string{hSet2.Item.Id})
require.NoError(err)
require.Nil(apiErr)
require.NotNil(tar)
assert.Empty(tar.Item.HostSetIds)
}
@@ -77,9 +70,8 @@ func TestList(t *testing.T) {
_, proj := iam.TestScopes(t, tc.IamRepo(), iam.WithUserId(token.UserId))
tarClient := targets.NewClient(client)
ul, apiErr, err := tarClient.List(tc.Context(), proj.GetPublicId())
ul, err := tarClient.List(tc.Context(), proj.GetPublicId())
require.NoError(err)
require.Nil(apiErr)
assert.Empty(ul.Items)
var expected []*targets.Target
@@ -87,25 +79,21 @@ func TestList(t *testing.T) {
expected = append(expected, &targets.Target{Name: fmt.Sprint(i)})
}
tcr, apiErr, err := tarClient.Create(tc.Context(), "tcp", proj.GetPublicId(), targets.WithName(expected[0].Name))
tcr, err := tarClient.Create(tc.Context(), "tcp", proj.GetPublicId(), targets.WithName(expected[0].Name))
require.NoError(err)
require.Nil(apiErr)
expected[0] = tcr.Item
ul, apiErr, err = tarClient.List(tc.Context(), proj.GetPublicId())
ul, err = tarClient.List(tc.Context(), proj.GetPublicId())
require.NoError(err)
require.Nil(apiErr)
assert.ElementsMatch(comparableSlice(expected[:1]), comparableSlice(ul.Items))
for i := 1; i < 10; i++ {
tcr, apiErr, err = tarClient.Create(tc.Context(), "tcp", proj.GetPublicId(), targets.WithName(expected[i].Name))
tcr, err = tarClient.Create(tc.Context(), "tcp", proj.GetPublicId(), targets.WithName(expected[i].Name))
require.NoError(err)
require.Nil(apiErr)
expected[i] = tcr.Item
}
ul, apiErr, err = tarClient.List(tc.Context(), proj.GetPublicId())
ul, err = tarClient.List(tc.Context(), proj.GetPublicId())
require.NoError(err)
require.Nil(apiErr)
assert.ElementsMatch(comparableSlice(expected), comparableSlice(ul.Items))
}
@@ -134,12 +122,9 @@ func TestCrud(t *testing.T) {
client.SetToken(token.Token)
_, proj := iam.TestScopes(t, tc.IamRepo(), iam.WithUserId(token.UserId))
checkResource := func(t *testing.T, step string, h *targets.Target, apiErr *api.Error, err error, wantedName string, wantVersion uint32) {
checkResource := func(t *testing.T, step string, h *targets.Target, err error, wantedName string, wantVersion uint32) {
t.Helper()
require.NoError(err, step)
if !assert.Nil(apiErr, step) && apiErr.Message != "" {
t.Errorf("ApiError message: %q", apiErr.Message)
}
assert.NotNil(h, "returned no resource", step)
gotName := ""
if h.Name != "" {
@@ -151,21 +136,21 @@ func TestCrud(t *testing.T) {
tarClient := targets.NewClient(client)
tar, apiErr, err := tarClient.Create(tc.Context(), "tcp", proj.GetPublicId(), targets.WithName("foo"))
checkResource(t, "create", tar.Item, apiErr, err, "foo", 1)
tar, err := tarClient.Create(tc.Context(), "tcp", proj.GetPublicId(), targets.WithName("foo"))
checkResource(t, "create", tar.Item, err, "foo", 1)
tar, apiErr, err = tarClient.Read(tc.Context(), tar.Item.Id)
checkResource(t, "read", tar.Item, apiErr, err, "foo", 1)
tar, err = tarClient.Read(tc.Context(), tar.Item.Id)
checkResource(t, "read", tar.Item, err, "foo", 1)
tar, apiErr, err = tarClient.Update(tc.Context(), tar.Item.Id, tar.Item.Version, targets.WithName("bar"))
checkResource(t, "update", tar.Item, apiErr, err, "bar", 2)
tar, err = tarClient.Update(tc.Context(), tar.Item.Id, tar.Item.Version, targets.WithName("bar"))
checkResource(t, "update", tar.Item, err, "bar", 2)
_, apiErr, err = tarClient.Delete(tc.Context(), tar.Item.Id)
_, err = tarClient.Delete(tc.Context(), tar.Item.Id)
assert.NoError(err)
assert.Nil(apiErr)
_, apiErr, err = tarClient.Delete(tc.Context(), tar.Item.Id)
assert.NoError(err)
_, err = tarClient.Delete(tc.Context(), tar.Item.Id)
assert.Error(err)
apiErr := api.AsServerError(err)
assert.NotNil(apiErr)
assert.EqualValues(http.StatusNotFound, apiErr.Status)
}
@@ -182,29 +167,32 @@ func TestSet_Errors(t *testing.T) {
tarClient := targets.NewClient(client)
tar, apiErr, err := tarClient.Create(tc.Context(), "tcp", proj.GetPublicId(), targets.WithName("foo"))
tar, err := tarClient.Create(tc.Context(), "tcp", proj.GetPublicId(), targets.WithName("foo"))
require.NoError(err)
require.Nil(apiErr)
assert.NotNil(tar)
// Updating the wrong version should fail.
_, apiErr, err = tarClient.Update(tc.Context(), tar.Item.Id, 73, targets.WithName("anything"))
require.NoError(err)
_, err = tarClient.Update(tc.Context(), tar.Item.Id, 73, targets.WithName("anything"))
require.Error(err)
apiErr := api.AsServerError(err)
assert.NotNil(apiErr)
assert.EqualValues(http.StatusNotFound, apiErr.Status)
tar, apiErr, err = tarClient.Create(tc.Context(), "tcp", proj.GetPublicId(), targets.WithName("foo"))
require.NoError(err)
tar, err = tarClient.Create(tc.Context(), "tcp", proj.GetPublicId(), targets.WithName("foo"))
require.Error(err)
apiErr = api.AsServerError(err)
assert.NotNil(apiErr)
assert.Nil(tar)
_, apiErr, err = tarClient.Read(tc.Context(), target.TcpTargetPrefix+"_doesntexis")
require.NoError(err)
_, err = tarClient.Read(tc.Context(), target.TcpTargetPrefix+"_doesntexis")
require.Error(err)
apiErr = api.AsServerError(err)
assert.NotNil(apiErr)
assert.EqualValues(http.StatusNotFound, apiErr.Status)
_, apiErr, err = tarClient.Read(tc.Context(), "invalid id")
require.NoError(err)
_, err = tarClient.Read(tc.Context(), "invalid id")
require.Error(err)
apiErr = api.AsServerError(err)
assert.NotNil(apiErr)
assert.EqualValues(http.StatusBadRequest, apiErr.Status)
}
+48 -50
View File
@@ -9,8 +9,6 @@ import (
"net/url"
"time"
"github.com/kr/pretty"
"github.com/hashicorp/boundary/api"
"github.com/hashicorp/boundary/api/scopes"
)
@@ -107,22 +105,22 @@ func (c *Client) ApiClient() *api.Client {
return c.client
}
func (c *Client) Create(ctx context.Context, scopeId string, opt ...Option) (*UserCreateResult, *api.Error, error) {
func (c *Client) Create(ctx context.Context, scopeId string, opt ...Option) (*UserCreateResult, error) {
if scopeId == "" {
return nil, nil, fmt.Errorf("empty scopeId value passed into Create request")
return nil, fmt.Errorf("empty scopeId value passed into Create request")
}
opts, apiOpts := getOpts(opt...)
if c.client == nil {
return nil, nil, fmt.Errorf("nil client")
return nil, fmt.Errorf("nil client")
}
opts.postMap["scope_id"] = scopeId
req, err := c.client.NewRequest(ctx, "POST", "users", opts.postMap, apiOpts...)
if err != nil {
return nil, nil, fmt.Errorf("error creating Create request: %w", err)
return nil, fmt.Errorf("error creating Create request: %w", err)
}
if len(opts.queryMap) > 0 {
@@ -135,36 +133,36 @@ func (c *Client) Create(ctx context.Context, scopeId string, opt ...Option) (*Us
resp, err := c.client.Do(req)
if err != nil {
return nil, nil, fmt.Errorf("error performing client request during Create call: %w", err)
return nil, fmt.Errorf("error performing client request during Create call: %w", err)
}
target := new(UserCreateResult)
target.Item = new(User)
apiErr, err := resp.Decode(target.Item)
if err != nil {
return nil, nil, fmt.Errorf("error decoding Create response: %w", err)
return nil, fmt.Errorf("error decoding Create response: %w", err)
}
if apiErr != nil {
return nil, apiErr, nil
return nil, apiErr
}
target.responseBody = resp.Body
target.responseMap = resp.Map
return target, apiErr, nil
return target, nil
}
func (c *Client) Read(ctx context.Context, userId string, opt ...Option) (*UserReadResult, *api.Error, error) {
func (c *Client) Read(ctx context.Context, userId string, opt ...Option) (*UserReadResult, error) {
if userId == "" {
return nil, nil, fmt.Errorf("empty userId value passed into Read request")
return nil, fmt.Errorf("empty userId value passed into Read request")
}
if c.client == nil {
return nil, nil, fmt.Errorf("nil client")
return nil, fmt.Errorf("nil client")
}
opts, apiOpts := getOpts(opt...)
req, err := c.client.NewRequest(ctx, "GET", fmt.Sprintf("users/%s", userId), nil, apiOpts...)
if err != nil {
return nil, nil, fmt.Errorf("error creating Read request: %w", err)
return nil, fmt.Errorf("error creating Read request: %w", err)
}
if len(opts.queryMap) > 0 {
@@ -177,49 +175,49 @@ func (c *Client) Read(ctx context.Context, userId string, opt ...Option) (*UserR
resp, err := c.client.Do(req)
if err != nil {
return nil, nil, fmt.Errorf("error performing client request during Read call: %w", err)
return nil, fmt.Errorf("error performing client request during Read call: %w", err)
}
target := new(UserReadResult)
target.Item = new(User)
apiErr, err := resp.Decode(target.Item)
if err != nil {
return nil, nil, fmt.Errorf("error decoding Read response: %w", err)
return nil, fmt.Errorf("error decoding Read response: %w", err)
}
if apiErr != nil {
return nil, apiErr, nil
return nil, apiErr
}
target.responseBody = resp.Body
target.responseMap = resp.Map
return target, apiErr, nil
return target, nil
}
func (c *Client) Update(ctx context.Context, userId string, version uint32, opt ...Option) (*UserUpdateResult, *api.Error, error) {
func (c *Client) Update(ctx context.Context, userId string, version uint32, opt ...Option) (*UserUpdateResult, error) {
if userId == "" {
return nil, nil, fmt.Errorf("empty userId value passed into Update request")
return nil, fmt.Errorf("empty userId value passed into Update request")
}
if c.client == nil {
return nil, nil, fmt.Errorf("nil client")
return nil, fmt.Errorf("nil client")
}
opts, apiOpts := getOpts(opt...)
if version == 0 {
if !opts.withAutomaticVersioning {
return nil, nil, errors.New("zero version number passed into Update request and automatic versioning not specified")
return nil, errors.New("zero version number passed into Update request and automatic versioning not specified")
}
existingTarget, existingApiErr, existingErr := c.Read(ctx, userId, opt...)
existingTarget, existingErr := c.Read(ctx, userId, opt...)
if existingErr != nil {
return nil, nil, fmt.Errorf("error performing initial check-and-set read: %w", existingErr)
}
if existingApiErr != nil {
return nil, nil, fmt.Errorf("error from controller when performing initial check-and-set read: %s", pretty.Sprint(existingApiErr))
if api.AsServerError(existingErr) != nil {
return nil, fmt.Errorf("error from controller when performing initial check-and-set read: %w", existingErr)
}
return nil, fmt.Errorf("error performing initial check-and-set read: %w", existingErr)
}
if existingTarget == nil {
return nil, nil, errors.New("nil resource response found when performing initial check-and-set read")
return nil, errors.New("nil resource response found when performing initial check-and-set read")
}
if existingTarget.Item == nil {
return nil, nil, errors.New("nil resource found when performing initial check-and-set read")
return nil, errors.New("nil resource found when performing initial check-and-set read")
}
version = existingTarget.Item.Version
}
@@ -228,7 +226,7 @@ func (c *Client) Update(ctx context.Context, userId string, version uint32, opt
req, err := c.client.NewRequest(ctx, "PATCH", fmt.Sprintf("users/%s", userId), opts.postMap, apiOpts...)
if err != nil {
return nil, nil, fmt.Errorf("error creating Update request: %w", err)
return nil, fmt.Errorf("error creating Update request: %w", err)
}
if len(opts.queryMap) > 0 {
@@ -241,36 +239,36 @@ func (c *Client) Update(ctx context.Context, userId string, version uint32, opt
resp, err := c.client.Do(req)
if err != nil {
return nil, nil, fmt.Errorf("error performing client request during Update call: %w", err)
return nil, fmt.Errorf("error performing client request during Update call: %w", err)
}
target := new(UserUpdateResult)
target.Item = new(User)
apiErr, err := resp.Decode(target.Item)
if err != nil {
return nil, nil, fmt.Errorf("error decoding Update response: %w", err)
return nil, fmt.Errorf("error decoding Update response: %w", err)
}
if apiErr != nil {
return nil, apiErr, nil
return nil, apiErr
}
target.responseBody = resp.Body
target.responseMap = resp.Map
return target, apiErr, nil
return target, nil
}
func (c *Client) Delete(ctx context.Context, userId string, opt ...Option) (*UserDeleteResult, *api.Error, error) {
func (c *Client) Delete(ctx context.Context, userId string, opt ...Option) (*UserDeleteResult, error) {
if userId == "" {
return nil, nil, fmt.Errorf("empty userId value passed into Delete request")
return nil, fmt.Errorf("empty userId value passed into Delete request")
}
if c.client == nil {
return nil, nil, fmt.Errorf("nil client")
return nil, fmt.Errorf("nil client")
}
opts, apiOpts := getOpts(opt...)
req, err := c.client.NewRequest(ctx, "DELETE", fmt.Sprintf("users/%s", userId), nil, apiOpts...)
if err != nil {
return nil, nil, fmt.Errorf("error creating Delete request: %w", err)
return nil, fmt.Errorf("error creating Delete request: %w", err)
}
if len(opts.queryMap) > 0 {
@@ -283,30 +281,30 @@ func (c *Client) Delete(ctx context.Context, userId string, opt ...Option) (*Use
resp, err := c.client.Do(req)
if err != nil {
return nil, nil, fmt.Errorf("error performing client request during Delete call: %w", err)
return nil, fmt.Errorf("error performing client request during Delete call: %w", err)
}
apiErr, err := resp.Decode(nil)
if err != nil {
return nil, nil, fmt.Errorf("error decoding Delete response: %w", err)
return nil, fmt.Errorf("error decoding Delete response: %w", err)
}
if apiErr != nil {
return nil, apiErr, nil
return nil, apiErr
}
target := &UserDeleteResult{
responseBody: resp.Body,
responseMap: resp.Map,
}
return target, nil, nil
return target, nil
}
func (c *Client) List(ctx context.Context, scopeId string, opt ...Option) (*UserListResult, *api.Error, error) {
func (c *Client) List(ctx context.Context, scopeId string, opt ...Option) (*UserListResult, error) {
if scopeId == "" {
return nil, nil, fmt.Errorf("empty scopeId value passed into List request")
return nil, fmt.Errorf("empty scopeId value passed into List request")
}
if c.client == nil {
return nil, nil, fmt.Errorf("nil client")
return nil, fmt.Errorf("nil client")
}
opts, apiOpts := getOpts(opt...)
@@ -314,7 +312,7 @@ func (c *Client) List(ctx context.Context, scopeId string, opt ...Option) (*User
req, err := c.client.NewRequest(ctx, "GET", "users", nil, apiOpts...)
if err != nil {
return nil, nil, fmt.Errorf("error creating List request: %w", err)
return nil, fmt.Errorf("error creating List request: %w", err)
}
if len(opts.queryMap) > 0 {
@@ -327,18 +325,18 @@ func (c *Client) List(ctx context.Context, scopeId string, opt ...Option) (*User
resp, err := c.client.Do(req)
if err != nil {
return nil, nil, fmt.Errorf("error performing client request during List call: %w", err)
return nil, fmt.Errorf("error performing client request during List call: %w", err)
}
target := new(UserListResult)
apiErr, err := resp.Decode(target)
if err != nil {
return nil, nil, fmt.Errorf("error decoding List response: %w", err)
return nil, fmt.Errorf("error decoding List response: %w", err)
}
if apiErr != nil {
return nil, apiErr, nil
return nil, apiErr
}
target.responseBody = resp.Body
target.responseMap = resp.Map
return target, apiErr, nil
return target, nil
}
+34 -38
View File
@@ -24,9 +24,8 @@ func TestList(t *testing.T) {
org := iam.TestOrg(t, tc.IamRepo(), iam.WithUserId(token.UserId))
userClient := users.NewClient(client)
ul, apiErr, err := userClient.List(tc.Context(), org.GetPublicId())
ul, err := userClient.List(tc.Context(), org.GetPublicId())
assert.NoError(err)
assert.Nil(apiErr)
assert.Empty(ul.Items)
var expected []*users.User
@@ -34,25 +33,21 @@ func TestList(t *testing.T) {
expected = append(expected, &users.User{Name: fmt.Sprint(i)})
}
ucr, apiErr, err := userClient.Create(tc.Context(), org.GetPublicId(), users.WithName(expected[0].Name))
ucr, err := userClient.Create(tc.Context(), org.GetPublicId(), users.WithName(expected[0].Name))
assert.NoError(err)
assert.Nil(apiErr)
expected[0] = ucr.Item
ul, apiErr, err = userClient.List(tc.Context(), org.GetPublicId())
ul, err = userClient.List(tc.Context(), org.GetPublicId())
assert.NoError(err)
assert.Nil(apiErr)
assert.ElementsMatch(comparableSlice(expected[:1]), comparableSlice(ul.Items))
for i := 1; i < 10; i++ {
ucr, apiErr, err = userClient.Create(tc.Context(), org.GetPublicId(), users.WithName(expected[i].Name))
ucr, err = userClient.Create(tc.Context(), org.GetPublicId(), users.WithName(expected[i].Name))
assert.NoError(err)
assert.Nil(apiErr)
expected[i] = ucr.Item
}
ul, apiErr, err = userClient.List(tc.Context(), org.GetPublicId())
ul, err = userClient.List(tc.Context(), org.GetPublicId())
require.NoError(err)
assert.Nil(apiErr)
assert.ElementsMatch(comparableSlice(expected), comparableSlice(ul.Items))
}
@@ -82,11 +77,8 @@ func TestCrud(t *testing.T) {
org := iam.TestOrg(t, tc.IamRepo(), iam.WithUserId(token.UserId))
userClient := users.NewClient(client)
checkUser := func(step string, u *users.User, apiErr *api.Error, err error, wantedName string, wantedVersion uint32) {
checkUser := func(step string, u *users.User, err error, wantedName string, wantedVersion uint32) {
assert.NoError(err, step)
if !assert.Nil(apiErr, step) && apiErr.Message != "" {
t.Errorf("ApiError message: %q", apiErr.Message)
}
assert.NotNil(u, "returned no resource", step)
gotName := ""
if u.Name != "" {
@@ -96,24 +88,24 @@ func TestCrud(t *testing.T) {
assert.EqualValues(wantedVersion, u.Version)
}
u, apiErr, err := userClient.Create(tc.Context(), org.GetPublicId(), users.WithName("foo"))
checkUser("create", u.Item, apiErr, err, "foo", 1)
u, err := userClient.Create(tc.Context(), org.GetPublicId(), users.WithName("foo"))
checkUser("create", u.Item, err, "foo", 1)
u, apiErr, err = userClient.Read(tc.Context(), u.Item.Id)
checkUser("read", u.Item, apiErr, err, "foo", 1)
u, err = userClient.Read(tc.Context(), u.Item.Id)
checkUser("read", u.Item, err, "foo", 1)
u, apiErr, err = userClient.Update(tc.Context(), u.Item.Id, u.Item.Version, users.WithName("bar"))
checkUser("update", u.Item, apiErr, err, "bar", 2)
u, err = userClient.Update(tc.Context(), u.Item.Id, u.Item.Version, users.WithName("bar"))
checkUser("update", u.Item, err, "bar", 2)
u, apiErr, err = userClient.Update(tc.Context(), u.Item.Id, u.Item.Version, users.DefaultName())
checkUser("update", u.Item, apiErr, err, "", 3)
u, err = userClient.Update(tc.Context(), u.Item.Id, u.Item.Version, users.DefaultName())
checkUser("update", u.Item, err, "", 3)
_, apiErr, err = userClient.Delete(tc.Context(), u.Item.Id)
_, err = userClient.Delete(tc.Context(), u.Item.Id)
require.NoError(err)
assert.Nil(apiErr)
_, apiErr, err = userClient.Delete(tc.Context(), u.Item.Id)
require.NoError(err)
_, err = userClient.Delete(tc.Context(), u.Item.Id)
require.Error(err)
apiErr := api.AsServerError(err)
assert.NotNil(apiErr)
assert.EqualValues(http.StatusNotFound, apiErr.Status)
}
@@ -129,34 +121,38 @@ func TestErrors(t *testing.T) {
org := iam.TestOrg(t, tc.IamRepo(), iam.WithUserId(token.UserId))
userClient := users.NewClient(client)
u, apiErr, err := userClient.Create(tc.Context(), org.GetPublicId(), users.WithName("first"))
u, err := userClient.Create(tc.Context(), org.GetPublicId(), users.WithName("first"))
require.NoError(err)
assert.Nil(apiErr)
assert.NotNil(u)
// Updating the wrong version should fail.
_, apiErr, err = userClient.Update(tc.Context(), u.Item.Id, 73, users.WithName("anything"))
require.NoError(err)
_, err = userClient.Update(tc.Context(), u.Item.Id, 73, users.WithName("anything"))
require.Error(err)
apiErr := api.AsServerError(err)
assert.NotNil(apiErr)
assert.EqualValues(http.StatusNotFound, apiErr.Status)
// Create another resource with the same name.
_, apiErr, err = userClient.Create(tc.Context(), org.GetPublicId(), users.WithName("first"))
require.NoError(err)
_, err = userClient.Create(tc.Context(), org.GetPublicId(), users.WithName("first"))
require.Error(err)
apiErr = api.AsServerError(err)
assert.NotNil(apiErr)
_, apiErr, err = userClient.Read(tc.Context(), iam.UserPrefix+"_doesntexis")
require.NoError(err)
_, err = userClient.Read(tc.Context(), iam.UserPrefix+"_doesntexis")
require.Error(err)
apiErr = api.AsServerError(err)
assert.NotNil(apiErr)
assert.EqualValues(http.StatusNotFound, apiErr.Status)
_, apiErr, err = userClient.Read(tc.Context(), "invalid id")
require.NoError(err)
_, err = userClient.Read(tc.Context(), "invalid id")
require.Error(err)
apiErr = api.AsServerError(err)
assert.NotNil(apiErr)
assert.EqualValues(http.StatusBadRequest, apiErr.Status)
_, apiErr, err = userClient.Update(tc.Context(), u.Item.Id, u.Item.Version)
require.NoError(err)
_, err = userClient.Update(tc.Context(), u.Item.Id, u.Item.Version)
require.Error(err)
apiErr = api.AsServerError(err)
assert.NotNil(apiErr)
assert.EqualValues(http.StatusBadRequest, apiErr.Status)
}
+11 -13
View File
@@ -13,7 +13,6 @@ import (
"github.com/hashicorp/boundary/internal/types/resource"
"github.com/hashicorp/boundary/sdk/strutil"
"github.com/hashicorp/vault/sdk/helper/password"
"github.com/kr/pretty"
"github.com/mitchellh/cli"
"github.com/posener/complete"
)
@@ -264,23 +263,22 @@ func (c *Command) Run(args []string) int {
existed := true
var result api.GenericResult
var listResult api.GenericListResult
var apiErr *api.Error
switch c.Func {
case "read":
result, apiErr, err = accountClient.Read(c.Context, c.FlagId, opts...)
result, err = accountClient.Read(c.Context, c.FlagId, opts...)
case "delete":
_, apiErr, err = accountClient.Delete(c.Context, c.FlagId, opts...)
if apiErr != nil && apiErr.Status == int32(http.StatusNotFound) {
_, err = accountClient.Delete(c.Context, c.FlagId, opts...)
if apiErr := api.AsServerError(err); apiErr != nil && apiErr.Status == int32(http.StatusNotFound) {
existed = false
apiErr = nil
err = nil
}
case "list":
listResult, apiErr, err = accountClient.List(c.Context, c.flagAuthMethodId, opts...)
listResult, err = accountClient.List(c.Context, c.flagAuthMethodId, opts...)
case "set-password":
result, apiErr, err = accountClient.SetPassword(c.Context, c.FlagId, c.flagPassword, version, opts...)
result, err = accountClient.SetPassword(c.Context, c.FlagId, c.flagPassword, version, opts...)
case "change-password":
result, apiErr, err = accountClient.ChangePassword(c.Context, c.FlagId, c.flagCurrentPassword, c.flagNewPassword, version, opts...)
result, err = accountClient.ChangePassword(c.Context, c.FlagId, c.flagCurrentPassword, c.flagNewPassword, version, opts...)
}
plural := "account"
@@ -288,13 +286,13 @@ func (c *Command) Run(args []string) int {
plural = "accounts"
}
if err != nil {
if api.AsServerError(err) != nil {
c.UI.Error(fmt.Sprintf("Error from controller when performing %s on %s: %s", c.Func, plural, err.Error()))
return 1
}
c.UI.Error(fmt.Sprintf("Error trying to %s %s: %s", c.Func, plural, err.Error()))
return 2
}
if apiErr != nil {
c.UI.Error(fmt.Sprintf("Error from controller when performing %s on %s: %s", c.Func, plural, pretty.Sprint(apiErr)))
return 1
}
switch c.Func {
case "delete":
+6 -8
View File
@@ -12,7 +12,6 @@ import (
"github.com/hashicorp/boundary/internal/cmd/common"
"github.com/hashicorp/boundary/sdk/strutil"
"github.com/hashicorp/vault/sdk/helper/password"
"github.com/kr/pretty"
"github.com/mitchellh/cli"
"github.com/posener/complete"
)
@@ -207,24 +206,23 @@ func (c *PasswordCommand) Run(args []string) int {
}
var result api.GenericResult
var apiErr *api.Error
switch c.Func {
case "create":
result, apiErr, err = accountClient.Create(c.Context, c.flagAuthMethodId, opts...)
result, err = accountClient.Create(c.Context, c.flagAuthMethodId, opts...)
case "update":
result, apiErr, err = accountClient.Update(c.Context, c.FlagId, version, opts...)
result, err = accountClient.Update(c.Context, c.FlagId, version, opts...)
}
plural := "password-type account"
if err != nil {
if api.AsServerError(err) != nil {
c.UI.Error(fmt.Sprintf("Error from controller when performing %s on %s: %s", c.Func, plural, err.Error()))
return 1
}
c.UI.Error(fmt.Sprintf("Error trying to %s %s: %s", c.Func, plural, err.Error()))
return 2
}
if apiErr != nil {
c.UI.Error(fmt.Sprintf("Error from controller when performing %s on %s: %s", c.Func, plural, pretty.Sprint(apiErr)))
return 1
}
account := result.GetItem().(*accounts.Account)
switch base.Format(c.UI) {
@@ -8,10 +8,10 @@ import (
"time"
"github.com/btcsuite/btcutil/base58"
"github.com/hashicorp/boundary/api"
"github.com/hashicorp/boundary/api/authmethods"
"github.com/hashicorp/boundary/internal/cmd/base"
"github.com/hashicorp/vault/sdk/helper/password"
"github.com/kr/pretty"
"github.com/mitchellh/cli"
"github.com/mitchellh/go-wordwrap"
"github.com/posener/complete"
@@ -121,19 +121,19 @@ func (c *PasswordCommand) Run(args []string) int {
// note: Authenticate() calls SetToken() under the hood to set the
// auth bearer on the client so we do not need to do anything with the
// returned token after this call, so we ignore it
result, apiErr, err := authmethods.NewClient(client).Authenticate(c.Context, c.flagAuthMethodId,
result, err := authmethods.NewClient(client).Authenticate(c.Context, c.flagAuthMethodId,
map[string]interface{}{
"login_name": c.flagLoginName,
"password": c.flagPassword,
})
if err != nil {
if api.AsServerError(err) != nil {
c.UI.Error(fmt.Sprintf("Error from controller when performing authentication: %s", err.Error()))
return 1
}
c.UI.Error(fmt.Sprintf("Error trying to perform authentication: %s", err.Error()))
return 2
}
if apiErr != nil {
c.UI.Error(fmt.Sprintf("Error from controller when performing authentication: %s", pretty.Sprint(apiErr)))
return 1
}
token := result.Item
switch base.Format(c.UI) {
@@ -10,7 +10,6 @@ import (
"github.com/hashicorp/boundary/internal/cmd/common"
"github.com/hashicorp/boundary/internal/types/resource"
"github.com/hashicorp/boundary/sdk/strutil"
"github.com/kr/pretty"
"github.com/mitchellh/cli"
"github.com/posener/complete"
)
@@ -157,19 +156,18 @@ func (c *Command) Run(args []string) int {
existed := true
var result api.GenericResult
var listResult api.GenericListResult
var apiErr *api.Error
switch c.Func {
case "read":
result, apiErr, err = authmethodClient.Read(c.Context, c.FlagId, opts...)
result, err = authmethodClient.Read(c.Context, c.FlagId, opts...)
case "delete":
_, apiErr, err = authmethodClient.Delete(c.Context, c.FlagId, opts...)
if apiErr != nil && apiErr.Status == int32(http.StatusNotFound) {
_, err = authmethodClient.Delete(c.Context, c.FlagId, opts...)
if apiErr := api.AsServerError(err); apiErr != nil && apiErr.Status == int32(http.StatusNotFound) {
existed = false
apiErr = nil
err = nil
}
case "list":
listResult, apiErr, err = authmethodClient.List(c.Context, c.FlagScopeId, opts...)
listResult, err = authmethodClient.List(c.Context, c.FlagScopeId, opts...)
}
plural := "auth method"
@@ -177,13 +175,13 @@ func (c *Command) Run(args []string) int {
plural = "auth methods"
}
if err != nil {
if api.AsServerError(err) != nil {
c.UI.Error(fmt.Sprintf("Error from controller when performing %s on %s: %s", c.Func, plural, err.Error()))
return 1
}
c.UI.Error(fmt.Sprintf("Error trying to %s %s: %s", c.Func, plural, err.Error()))
return 2
}
if apiErr != nil {
c.UI.Error(fmt.Sprintf("Error from controller when performing %s on %s: %s", c.Func, plural, pretty.Sprint(apiErr)))
return 1
}
switch c.Func {
case "delete":
@@ -10,7 +10,6 @@ import (
"github.com/hashicorp/boundary/internal/cmd/base"
"github.com/hashicorp/boundary/internal/cmd/common"
"github.com/hashicorp/boundary/sdk/strutil"
"github.com/kr/pretty"
"github.com/mitchellh/cli"
"github.com/posener/complete"
)
@@ -185,24 +184,23 @@ func (c *PasswordCommand) Run(args []string) int {
}
var result api.GenericResult
var apiErr *api.Error
switch c.Func {
case "create":
result, apiErr, err = authmethodClient.Create(c.Context, "password", c.FlagScopeId, opts...)
result, err = authmethodClient.Create(c.Context, "password", c.FlagScopeId, opts...)
case "update":
result, apiErr, err = authmethodClient.Update(c.Context, c.FlagId, version, opts...)
result, err = authmethodClient.Update(c.Context, c.FlagId, version, opts...)
}
plural := "password-type auth-method"
if err != nil {
if api.AsServerError(err) != nil {
c.UI.Error(fmt.Sprintf("Error from controller when performing %s on %s: %s", c.Func, plural, err.Error()))
return 1
}
c.UI.Error(fmt.Sprintf("Error trying to %s %s: %s", c.Func, plural, err.Error()))
return 2
}
if apiErr != nil {
c.UI.Error(fmt.Sprintf("Error from controller when performing %s on %s: %s", c.Func, plural, pretty.Sprint(apiErr)))
return 1
}
method := result.GetItem().(*authmethods.AuthMethod)
switch base.Format(c.UI) {
+9 -11
View File
@@ -11,7 +11,6 @@ import (
"github.com/hashicorp/boundary/internal/cmd/common"
"github.com/hashicorp/boundary/internal/types/resource"
"github.com/hashicorp/boundary/sdk/strutil"
"github.com/kr/pretty"
"github.com/mitchellh/cli"
"github.com/posener/complete"
)
@@ -94,19 +93,18 @@ func (c *Command) Run(args []string) int {
existed := true
var result api.GenericResult
var listResult api.GenericListResult
var apiErr *api.Error
switch c.Func {
case "read":
result, apiErr, err = authtokenClient.Read(c.Context, c.FlagId)
result, err = authtokenClient.Read(c.Context, c.FlagId)
case "delete":
_, apiErr, err = authtokenClient.Delete(c.Context, c.FlagId)
if apiErr != nil && apiErr.Status == int32(http.StatusNotFound) {
_, err = authtokenClient.Delete(c.Context, c.FlagId)
if apiErr := api.AsServerError(err); apiErr != nil && apiErr.Status == int32(http.StatusNotFound) {
existed = false
apiErr = nil
err = nil
}
case "list":
listResult, apiErr, err = authtokenClient.List(c.Context, c.FlagScopeId)
listResult, err = authtokenClient.List(c.Context, c.FlagScopeId)
}
plural := "auth token"
@@ -114,13 +112,13 @@ func (c *Command) Run(args []string) int {
plural = "auth tokens"
}
if err != nil {
if api.AsServerError(err) != nil {
c.UI.Error(fmt.Sprintf("Error from controller when performing %s on %s: %s", c.Func, plural, err.Error()))
return 1
}
c.UI.Error(fmt.Sprintf("Error trying to %s %s: %s", c.Func, plural, err.Error()))
return 2
}
if apiErr != nil {
c.UI.Error(fmt.Sprintf("Error from controller when performing %s on %s: %s", c.Func, plural, pretty.Sprint(apiErr)))
return 1
}
switch c.Func {
case "delete":
+14 -16
View File
@@ -9,7 +9,6 @@ import (
"github.com/hashicorp/boundary/internal/cmd/base"
"github.com/hashicorp/boundary/internal/cmd/common"
"github.com/hashicorp/boundary/sdk/strutil"
"github.com/kr/pretty"
"github.com/mitchellh/cli"
"github.com/posener/complete"
)
@@ -165,29 +164,28 @@ func (c *Command) Run(args []string) int {
existed := true
var result api.GenericResult
var listResult api.GenericListResult
var apiErr *api.Error
switch c.Func {
case "create":
result, apiErr, err = groupClient.Create(c.Context, c.FlagScopeId, opts...)
result, err = groupClient.Create(c.Context, c.FlagScopeId, opts...)
case "update":
result, apiErr, err = groupClient.Update(c.Context, c.FlagId, version, opts...)
result, err = groupClient.Update(c.Context, c.FlagId, version, opts...)
case "read":
result, apiErr, err = groupClient.Read(c.Context, c.FlagId, opts...)
result, err = groupClient.Read(c.Context, c.FlagId, opts...)
case "delete":
_, apiErr, err = groupClient.Delete(c.Context, c.FlagId, opts...)
if apiErr != nil && apiErr.Status == int32(http.StatusNotFound) {
_, err = groupClient.Delete(c.Context, c.FlagId, opts...)
if apiErr := api.AsServerError(err); apiErr != nil && apiErr.Status == int32(http.StatusNotFound) {
existed = false
apiErr = nil
err = nil
}
case "list":
listResult, apiErr, err = groupClient.List(c.Context, c.FlagScopeId, opts...)
listResult, err = groupClient.List(c.Context, c.FlagScopeId, opts...)
case "add-members":
result, apiErr, err = groupClient.AddMembers(c.Context, c.FlagId, version, members, opts...)
result, err = groupClient.AddMembers(c.Context, c.FlagId, version, members, opts...)
case "set-members":
result, apiErr, err = groupClient.SetMembers(c.Context, c.FlagId, version, members, opts...)
result, err = groupClient.SetMembers(c.Context, c.FlagId, version, members, opts...)
case "remove-members":
result, apiErr, err = groupClient.RemoveMembers(c.Context, c.FlagId, version, members, opts...)
result, err = groupClient.RemoveMembers(c.Context, c.FlagId, version, members, opts...)
}
plural := "group"
@@ -195,13 +193,13 @@ func (c *Command) Run(args []string) int {
plural = "groups"
}
if err != nil {
if api.AsServerError(err) != nil {
c.UI.Error(fmt.Sprintf("Error from controller when performing %s on %s: %s", c.Func, plural, err.Error()))
return 1
}
c.UI.Error(fmt.Sprintf("Error trying to %s %s: %s", c.Func, plural, err.Error()))
return 2
}
if apiErr != nil {
c.UI.Error(fmt.Sprintf("Error from controller when performing %s on %s: %s", c.Func, plural, pretty.Sprint(apiErr)))
return 1
}
switch c.Func {
case "delete":
@@ -10,7 +10,6 @@ import (
"github.com/hashicorp/boundary/internal/cmd/common"
"github.com/hashicorp/boundary/internal/types/resource"
"github.com/hashicorp/boundary/sdk/strutil"
"github.com/kr/pretty"
"github.com/mitchellh/cli"
"github.com/posener/complete"
)
@@ -157,19 +156,18 @@ func (c *Command) Run(args []string) int {
existed := true
var result api.GenericResult
var listResult api.GenericListResult
var apiErr *api.Error
switch c.Func {
case "read":
result, apiErr, err = hostcatalogClient.Read(c.Context, c.FlagId, opts...)
result, err = hostcatalogClient.Read(c.Context, c.FlagId, opts...)
case "delete":
_, apiErr, err = hostcatalogClient.Delete(c.Context, c.FlagId, opts...)
if apiErr != nil && apiErr.Status == int32(http.StatusNotFound) {
_, err = hostcatalogClient.Delete(c.Context, c.FlagId, opts...)
if apiErr := api.AsServerError(err); apiErr != nil && apiErr.Status == int32(http.StatusNotFound) {
existed = false
apiErr = nil
err = nil
}
case "list":
listResult, apiErr, err = hostcatalogClient.List(c.Context, c.FlagScopeId, opts...)
listResult, err = hostcatalogClient.List(c.Context, c.FlagScopeId, opts...)
}
plural := "host catalog"
@@ -177,13 +175,13 @@ func (c *Command) Run(args []string) int {
plural = "host catalogs"
}
if err != nil {
if api.AsServerError(err) != nil {
c.UI.Error(fmt.Sprintf("Error from controller when performing %s on %s: %s", c.Func, plural, err.Error()))
return 1
}
c.UI.Error(fmt.Sprintf("Error trying to %s %s: %s", c.Func, plural, err.Error()))
return 2
}
if apiErr != nil {
c.UI.Error(fmt.Sprintf("Error from controller when performing %s on %s: %s", c.Func, plural, pretty.Sprint(apiErr)))
return 1
}
switch c.Func {
case "delete":
+6 -8
View File
@@ -9,7 +9,6 @@ import (
"github.com/hashicorp/boundary/internal/cmd/base"
"github.com/hashicorp/boundary/internal/cmd/common"
"github.com/hashicorp/boundary/sdk/strutil"
"github.com/kr/pretty"
"github.com/mitchellh/cli"
"github.com/posener/complete"
)
@@ -141,24 +140,23 @@ func (c *StaticCommand) Run(args []string) int {
}
var result api.GenericResult
var apiErr *api.Error
switch c.Func {
case "create":
result, apiErr, err = hostcatalogClient.Create(c.Context, "static", c.FlagScopeId, opts...)
result, err = hostcatalogClient.Create(c.Context, "static", c.FlagScopeId, opts...)
case "update":
result, apiErr, err = hostcatalogClient.Update(c.Context, c.FlagId, version, opts...)
result, err = hostcatalogClient.Update(c.Context, c.FlagId, version, opts...)
}
plural := "static-type host-catalog"
if err != nil {
if api.AsServerError(err) != nil {
c.UI.Error(fmt.Sprintf("Error from controller when performing %s on %s: %s", c.Func, plural, err.Error()))
return 1
}
c.UI.Error(fmt.Sprintf("Error trying to %s %s: %s", c.Func, plural, err.Error()))
return 2
}
if apiErr != nil {
c.UI.Error(fmt.Sprintf("Error from controller when performing %s on %s: %s", c.Func, plural, pretty.Sprint(apiErr)))
return 1
}
catalog := result.GetItem().(*hostcatalogs.HostCatalog)
switch base.Format(c.UI) {
+9 -11
View File
@@ -10,7 +10,6 @@ import (
"github.com/hashicorp/boundary/internal/cmd/common"
"github.com/hashicorp/boundary/internal/types/resource"
"github.com/hashicorp/boundary/sdk/strutil"
"github.com/kr/pretty"
"github.com/mitchellh/cli"
"github.com/posener/complete"
)
@@ -168,19 +167,18 @@ func (c *Command) Run(args []string) int {
existed := true
var result api.GenericResult
var listResult api.GenericListResult
var apiErr *api.Error
switch c.Func {
case "read":
result, apiErr, err = hostClient.Read(c.Context, c.FlagId, opts...)
result, err = hostClient.Read(c.Context, c.FlagId, opts...)
case "delete":
_, apiErr, err = hostClient.Delete(c.Context, c.FlagId, opts...)
if apiErr != nil && apiErr.Status == int32(http.StatusNotFound) {
_, err = hostClient.Delete(c.Context, c.FlagId, opts...)
if apiErr := api.AsServerError(err); apiErr != nil && apiErr.Status == int32(http.StatusNotFound) {
existed = false
apiErr = nil
err = nil
}
case "list":
listResult, apiErr, err = hostClient.List(c.Context, c.flagHostCatalogId, opts...)
listResult, err = hostClient.List(c.Context, c.flagHostCatalogId, opts...)
}
plural := "host"
@@ -188,13 +186,13 @@ func (c *Command) Run(args []string) int {
plural = "hosts"
}
if err != nil {
if api.AsServerError(err) != nil {
c.UI.Error(fmt.Sprintf("Error from controller when performing %s on %s: %s", c.Func, plural, err.Error()))
return 1
}
c.UI.Error(fmt.Sprintf("Error trying to %s %s: %s", c.Func, plural, err.Error()))
return 2
}
if apiErr != nil {
c.UI.Error(fmt.Sprintf("Error from controller when performing %s on %s: %s", c.Func, plural, pretty.Sprint(apiErr)))
return 1
}
switch c.Func {
case "delete":
+6 -8
View File
@@ -9,7 +9,6 @@ import (
"github.com/hashicorp/boundary/internal/cmd/base"
"github.com/hashicorp/boundary/internal/cmd/common"
"github.com/hashicorp/boundary/sdk/strutil"
"github.com/kr/pretty"
"github.com/mitchellh/cli"
"github.com/posener/complete"
)
@@ -181,24 +180,23 @@ func (c *StaticCommand) Run(args []string) int {
}
var result api.GenericResult
var apiErr *api.Error
switch c.Func {
case "create":
result, apiErr, err = hostClient.Create(c.Context, c.flagHostCatalogId, opts...)
result, err = hostClient.Create(c.Context, c.flagHostCatalogId, opts...)
case "update":
result, apiErr, err = hostClient.Update(c.Context, c.FlagId, version, opts...)
result, err = hostClient.Update(c.Context, c.FlagId, version, opts...)
}
plural := "static-type host"
if err != nil {
if api.AsServerError(err) != nil {
c.UI.Error(fmt.Sprintf("Error from controller when performing %s on %s: %s", c.Func, plural, err.Error()))
return 1
}
c.UI.Error(fmt.Sprintf("Error trying to %s %s: %s", c.Func, plural, err.Error()))
return 2
}
if apiErr != nil {
c.UI.Error(fmt.Sprintf("Error from controller when performing %s on %s: %s", c.Func, plural, pretty.Sprint(apiErr)))
return 1
}
host := result.GetItem().(*hosts.Host)
switch base.Format(c.UI) {
+12 -14
View File
@@ -10,7 +10,6 @@ import (
"github.com/hashicorp/boundary/internal/cmd/common"
"github.com/hashicorp/boundary/internal/types/resource"
"github.com/hashicorp/boundary/sdk/strutil"
"github.com/kr/pretty"
"github.com/mitchellh/cli"
"github.com/posener/complete"
)
@@ -248,25 +247,24 @@ func (c *Command) Run(args []string) int {
existed := true
var result api.GenericResult
var listResult api.GenericListResult
var apiErr *api.Error
switch c.Func {
case "read":
result, apiErr, err = hostsetClient.Read(c.Context, c.FlagId, opts...)
result, err = hostsetClient.Read(c.Context, c.FlagId, opts...)
case "delete":
_, apiErr, err = hostsetClient.Delete(c.Context, c.FlagId, opts...)
if apiErr != nil && apiErr.Status == int32(http.StatusNotFound) {
_, err = hostsetClient.Delete(c.Context, c.FlagId, opts...)
if apiErr := api.AsServerError(err); apiErr != nil && apiErr.Status == int32(http.StatusNotFound) {
existed = false
apiErr = nil
err = nil
}
case "list":
listResult, apiErr, err = hostsetClient.List(c.Context, c.flagHostCatalogId, opts...)
listResult, err = hostsetClient.List(c.Context, c.flagHostCatalogId, opts...)
case "add-hosts":
result, apiErr, err = hostsetClient.AddHosts(c.Context, c.FlagId, version, hosts, opts...)
result, err = hostsetClient.AddHosts(c.Context, c.FlagId, version, hosts, opts...)
case "remove-hosts":
result, apiErr, err = hostsetClient.RemoveHosts(c.Context, c.FlagId, version, hosts, opts...)
result, err = hostsetClient.RemoveHosts(c.Context, c.FlagId, version, hosts, opts...)
case "set-hosts":
result, apiErr, err = hostsetClient.SetHosts(c.Context, c.FlagId, version, hosts, opts...)
result, err = hostsetClient.SetHosts(c.Context, c.FlagId, version, hosts, opts...)
}
plural := "host set"
@@ -274,13 +272,13 @@ func (c *Command) Run(args []string) int {
plural = "host sets"
}
if err != nil {
if api.AsServerError(err) != nil {
c.UI.Error(fmt.Sprintf("Error from controller when performing %s on %s: %s", c.Func, plural, err.Error()))
return 1
}
c.UI.Error(fmt.Sprintf("Error trying to %s %s: %s", c.Func, plural, err.Error()))
return 2
}
if apiErr != nil {
c.UI.Error(fmt.Sprintf("Error from controller when performing %s on %s: %s", c.Func, plural, pretty.Sprint(apiErr)))
return 1
}
switch c.Func {
case "delete":
+6 -8
View File
@@ -9,7 +9,6 @@ import (
"github.com/hashicorp/boundary/internal/cmd/base"
"github.com/hashicorp/boundary/internal/cmd/common"
"github.com/hashicorp/boundary/sdk/strutil"
"github.com/kr/pretty"
"github.com/mitchellh/cli"
"github.com/posener/complete"
)
@@ -152,24 +151,23 @@ func (c *StaticCommand) Run(args []string) int {
}
var result api.GenericResult
var apiErr *api.Error
switch c.Func {
case "create":
result, apiErr, err = hostsetClient.Create(c.Context, c.flagHostCatalogId, opts...)
result, err = hostsetClient.Create(c.Context, c.flagHostCatalogId, opts...)
case "update":
result, apiErr, err = hostsetClient.Update(c.Context, c.FlagId, version, opts...)
result, err = hostsetClient.Update(c.Context, c.FlagId, version, opts...)
}
plural := "static-type host-set"
if err != nil {
if api.AsServerError(err) != nil {
c.UI.Error(fmt.Sprintf("Error from controller when performing %s on %s: %s", c.Func, plural, err.Error()))
return 1
}
c.UI.Error(fmt.Sprintf("Error trying to %s %s: %s", c.Func, plural, err.Error()))
return 2
}
if apiErr != nil {
c.UI.Error(fmt.Sprintf("Error from controller when performing %s on %s: %s", c.Func, plural, pretty.Sprint(apiErr)))
return 1
}
set := result.GetItem().(*hostsets.HostSet)
switch base.Format(c.UI) {
+6 -6
View File
@@ -21,6 +21,7 @@ import (
"time"
"github.com/btcsuite/btcutil/base58"
"github.com/hashicorp/boundary/api"
"github.com/hashicorp/boundary/api/targets"
"github.com/hashicorp/boundary/globals"
"github.com/hashicorp/boundary/internal/cmd/base"
@@ -28,7 +29,6 @@ import (
"github.com/hashicorp/boundary/internal/proxy"
"github.com/hashicorp/go-cleanhttp"
"github.com/hashicorp/vault/sdk/helper/base62"
"github.com/kr/pretty"
"github.com/mitchellh/cli"
"github.com/posener/complete"
"go.uber.org/atomic"
@@ -318,15 +318,15 @@ func (c *Command) Run(args []string) (retCode int) {
opts = append(opts, targets.WithHostId(c.flagHostId))
}
sar, apiErr, err := targetClient.Authorize(c.Context, c.flagTargetId, opts...)
sar, err := targetClient.Authorize(c.Context, c.flagTargetId, opts...)
if err != nil {
if api.AsServerError(err) != nil {
c.UI.Error(fmt.Sprintf("Error from controller when performing authorize on a session against target: %s", err.Error()))
return 1
}
c.UI.Error(fmt.Sprintf("Error trying to authorize a session against target: %s", err.Error()))
return 2
}
if apiErr != nil {
c.UI.Error(fmt.Sprintf("Error from controller when performing authorize on a session against target: %s", pretty.Sprint(apiErr)))
return 1
}
sa := sar.GetItem().(*targets.SessionAuthorization)
authzString = sa.AuthorizationToken
}
+17 -19
View File
@@ -10,7 +10,6 @@ import (
"github.com/hashicorp/boundary/internal/cmd/common"
"github.com/hashicorp/boundary/internal/perms"
"github.com/hashicorp/boundary/sdk/strutil"
"github.com/kr/pretty"
"github.com/mitchellh/cli"
"github.com/posener/complete"
)
@@ -210,35 +209,34 @@ func (c *Command) Run(args []string) int {
existed := true
var result api.GenericResult
var listResult api.GenericListResult
var apiErr *api.Error
switch c.Func {
case "create":
result, apiErr, err = roleClient.Create(c.Context, c.FlagScopeId, opts...)
result, err = roleClient.Create(c.Context, c.FlagScopeId, opts...)
case "update":
result, apiErr, err = roleClient.Update(c.Context, c.FlagId, version, opts...)
result, err = roleClient.Update(c.Context, c.FlagId, version, opts...)
case "read":
result, apiErr, err = roleClient.Read(c.Context, c.FlagId, opts...)
result, err = roleClient.Read(c.Context, c.FlagId, opts...)
case "delete":
_, apiErr, err = roleClient.Delete(c.Context, c.FlagId, opts...)
if apiErr != nil && apiErr.Status == int32(http.StatusNotFound) {
_, err = roleClient.Delete(c.Context, c.FlagId, opts...)
if apiErr := api.AsServerError(err); apiErr != nil && apiErr.Status == int32(http.StatusNotFound) {
existed = false
apiErr = nil
err = nil
}
case "list":
listResult, apiErr, err = roleClient.List(c.Context, c.FlagScopeId, opts...)
listResult, err = roleClient.List(c.Context, c.FlagScopeId, opts...)
case "add-principals":
result, apiErr, err = roleClient.AddPrincipals(c.Context, c.FlagId, version, principals, opts...)
result, err = roleClient.AddPrincipals(c.Context, c.FlagId, version, principals, opts...)
case "set-principals":
result, apiErr, err = roleClient.SetPrincipals(c.Context, c.FlagId, version, principals, opts...)
result, err = roleClient.SetPrincipals(c.Context, c.FlagId, version, principals, opts...)
case "remove-principals":
result, apiErr, err = roleClient.RemovePrincipals(c.Context, c.FlagId, version, principals, opts...)
result, err = roleClient.RemovePrincipals(c.Context, c.FlagId, version, principals, opts...)
case "add-grants":
result, apiErr, err = roleClient.AddGrants(c.Context, c.FlagId, version, grants, opts...)
result, err = roleClient.AddGrants(c.Context, c.FlagId, version, grants, opts...)
case "set-grants":
result, apiErr, err = roleClient.SetGrants(c.Context, c.FlagId, version, grants, opts...)
result, err = roleClient.SetGrants(c.Context, c.FlagId, version, grants, opts...)
case "remove-grants":
result, apiErr, err = roleClient.RemoveGrants(c.Context, c.FlagId, version, grants, opts...)
result, err = roleClient.RemoveGrants(c.Context, c.FlagId, version, grants, opts...)
}
plural := "role"
@@ -246,13 +244,13 @@ func (c *Command) Run(args []string) int {
plural = "roles"
}
if err != nil {
if api.AsServerError(err) != nil {
c.UI.Error(fmt.Sprintf("Error from controller when performing %s on %s: %s", c.Func, plural, err.Error()))
return 1
}
c.UI.Error(fmt.Sprintf("Error trying to %s %s: %s", c.Func, plural, err.Error()))
return 2
}
if apiErr != nil {
c.UI.Error(fmt.Sprintf("Error from controller when performing %s on %s: %s", c.Func, plural, pretty.Sprint(apiErr)))
return 1
}
switch c.Func {
case "delete":
+11 -13
View File
@@ -10,7 +10,6 @@ import (
"github.com/hashicorp/boundary/internal/cmd/common"
"github.com/hashicorp/boundary/internal/types/resource"
"github.com/hashicorp/boundary/sdk/strutil"
"github.com/kr/pretty"
"github.com/mitchellh/cli"
"github.com/posener/complete"
)
@@ -140,23 +139,22 @@ func (c *Command) Run(args []string) int {
existed := true
var result api.GenericResult
var listResult api.GenericListResult
var apiErr *api.Error
switch c.Func {
case "create":
result, apiErr, err = scopeClient.Create(c.Context, c.FlagScopeId, opts...)
result, err = scopeClient.Create(c.Context, c.FlagScopeId, opts...)
case "update":
result, apiErr, err = scopeClient.Update(c.Context, c.FlagId, version, opts...)
result, err = scopeClient.Update(c.Context, c.FlagId, version, opts...)
case "read":
result, apiErr, err = scopeClient.Read(c.Context, c.FlagId, opts...)
result, err = scopeClient.Read(c.Context, c.FlagId, opts...)
case "delete":
_, apiErr, err = scopeClient.Delete(c.Context, c.FlagId, opts...)
if apiErr != nil && apiErr.Status == int32(http.StatusNotFound) {
_, err = scopeClient.Delete(c.Context, c.FlagId, opts...)
if apiErr := api.AsServerError(err); apiErr != nil && apiErr.Status == int32(http.StatusNotFound) {
existed = false
apiErr = nil
err = nil
}
case "list":
listResult, apiErr, err = scopeClient.List(c.Context, c.FlagScopeId, opts...)
listResult, err = scopeClient.List(c.Context, c.FlagScopeId, opts...)
}
plural := "scope"
@@ -164,13 +162,13 @@ func (c *Command) Run(args []string) int {
plural = "scopes"
}
if err != nil {
if api.AsServerError(err) != nil {
c.UI.Error(fmt.Sprintf("Error from controller when performing %s on %s: %s", c.Func, plural, err.Error()))
return 1
}
c.UI.Error(fmt.Sprintf("Error trying to %s %s: %s", c.Func, plural, err.Error()))
return 2
}
if apiErr != nil {
c.UI.Error(fmt.Sprintf("Error from controller when performing %s on %s: %s", c.Func, plural, pretty.Sprint(apiErr)))
return 1
}
switch c.Func {
case "delete":
+7 -9
View File
@@ -10,7 +10,6 @@ import (
"github.com/hashicorp/boundary/internal/cmd/common"
"github.com/hashicorp/boundary/internal/types/resource"
"github.com/hashicorp/boundary/sdk/strutil"
"github.com/kr/pretty"
"github.com/mitchellh/cli"
"github.com/posener/complete"
)
@@ -116,15 +115,14 @@ func (c *Command) Run(args []string) int {
var result api.GenericResult
var listResult api.GenericListResult
var apiErr *api.Error
switch c.Func {
case "read":
result, apiErr, err = sessionClient.Read(c.Context, c.FlagId)
result, err = sessionClient.Read(c.Context, c.FlagId)
case "cancel":
result, apiErr, err = sessionClient.Cancel(c.Context, c.FlagId, 0, sessions.WithAutomaticVersioning(true))
result, err = sessionClient.Cancel(c.Context, c.FlagId, 0, sessions.WithAutomaticVersioning(true))
case "list":
listResult, apiErr, err = sessionClient.List(c.Context, c.FlagScopeId)
listResult, err = sessionClient.List(c.Context, c.FlagScopeId)
}
plural := "session"
@@ -132,13 +130,13 @@ func (c *Command) Run(args []string) int {
plural = "sessions"
}
if err != nil {
if api.AsServerError(err) != nil {
c.UI.Error(fmt.Sprintf("Error from controller when performing %s on %s: %s", c.Func, plural, err.Error()))
return 1
}
c.UI.Error(fmt.Sprintf("Error trying to %s %s: %s", c.Func, plural, err.Error()))
return 2
}
if apiErr != nil {
c.UI.Error(fmt.Sprintf("Error from controller when performing %s on %s: %s", c.Func, plural, pretty.Sprint(apiErr)))
return 1
}
switch c.Func {
case "list":
+13 -15
View File
@@ -11,7 +11,6 @@ import (
"github.com/hashicorp/boundary/internal/cmd/common"
"github.com/hashicorp/boundary/internal/types/resource"
"github.com/hashicorp/boundary/sdk/strutil"
"github.com/kr/pretty"
"github.com/mitchellh/cli"
"github.com/posener/complete"
)
@@ -264,28 +263,27 @@ func (c *Command) Run(args []string) int {
existed := true
var result api.GenericResult
var listResult api.GenericListResult
var apiErr *api.Error
var sar *targets.SessionAuthorizationResult
switch c.Func {
case "read":
result, apiErr, err = targetClient.Read(c.Context, c.FlagId, opts...)
result, err = targetClient.Read(c.Context, c.FlagId, opts...)
case "delete":
_, apiErr, err = targetClient.Delete(c.Context, c.FlagId, opts...)
if apiErr != nil && apiErr.Status == int32(http.StatusNotFound) {
_, err = targetClient.Delete(c.Context, c.FlagId, opts...)
if apiErr := api.AsServerError(err); apiErr != nil && apiErr.Status == int32(http.StatusNotFound) {
existed = false
apiErr = nil
err = nil
}
case "list":
listResult, apiErr, err = targetClient.List(c.Context, c.FlagScopeId, opts...)
listResult, err = targetClient.List(c.Context, c.FlagScopeId, opts...)
case "add-host-sets":
result, apiErr, err = targetClient.AddHostSets(c.Context, c.FlagId, version, hostSets, opts...)
result, err = targetClient.AddHostSets(c.Context, c.FlagId, version, hostSets, opts...)
case "remove-host-sets":
result, apiErr, err = targetClient.RemoveHostSets(c.Context, c.FlagId, version, hostSets, opts...)
result, err = targetClient.RemoveHostSets(c.Context, c.FlagId, version, hostSets, opts...)
case "set-host-sets":
result, apiErr, err = targetClient.SetHostSets(c.Context, c.FlagId, version, hostSets, opts...)
result, err = targetClient.SetHostSets(c.Context, c.FlagId, version, hostSets, opts...)
case "authorize":
sar, apiErr, err = targetClient.Authorize(c.Context, c.FlagId, opts...)
sar, err = targetClient.Authorize(c.Context, c.FlagId, opts...)
}
plural := "target"
@@ -296,13 +294,13 @@ func (c *Command) Run(args []string) int {
plural = "a session against target"
}
if err != nil {
if api.AsServerError(err) != nil {
c.UI.Error(fmt.Sprintf("Error from controller when performing %s on %s: %s", c.Func, plural, err.Error()))
return 1
}
c.UI.Error(fmt.Sprintf("Error trying to %s %s: %s", c.Func, plural, err.Error()))
return 2
}
if apiErr != nil {
c.UI.Error(fmt.Sprintf("Error from controller when performing %s on %s: %s", c.Func, plural, pretty.Sprint(apiErr)))
return 1
}
switch c.Func {
case "delete":
+6 -8
View File
@@ -11,7 +11,6 @@ import (
"github.com/hashicorp/boundary/internal/cmd/base"
"github.com/hashicorp/boundary/internal/cmd/common"
"github.com/hashicorp/boundary/sdk/strutil"
"github.com/kr/pretty"
"github.com/mitchellh/cli"
"github.com/posener/complete"
)
@@ -213,24 +212,23 @@ func (c *TcpCommand) Run(args []string) int {
}
var result api.GenericResult
var apiErr *api.Error
switch c.Func {
case "create":
result, apiErr, err = targetClient.Create(c.Context, "tcp", c.FlagScopeId, opts...)
result, err = targetClient.Create(c.Context, "tcp", c.FlagScopeId, opts...)
case "update":
result, apiErr, err = targetClient.Update(c.Context, c.FlagId, version, opts...)
result, err = targetClient.Update(c.Context, c.FlagId, version, opts...)
}
plural := "tcp-type target"
if err != nil {
if api.AsServerError(err) != nil {
c.UI.Error(fmt.Sprintf("Error from controller when performing %s on %s: %s", c.Func, plural, err.Error()))
return 1
}
c.UI.Error(fmt.Sprintf("Error trying to %s %s: %s", c.Func, plural, err.Error()))
return 2
}
if apiErr != nil {
c.UI.Error(fmt.Sprintf("Error from controller when performing %s on %s: %s", c.Func, plural, pretty.Sprint(apiErr)))
return 1
}
target := result.GetItem().(*targets.Target)
switch base.Format(c.UI) {
+11 -13
View File
@@ -10,7 +10,6 @@ import (
"github.com/hashicorp/boundary/internal/cmd/common"
"github.com/hashicorp/boundary/internal/types/resource"
"github.com/hashicorp/boundary/sdk/strutil"
"github.com/kr/pretty"
"github.com/mitchellh/cli"
"github.com/posener/complete"
)
@@ -127,23 +126,22 @@ func (c *Command) Run(args []string) int {
existed := true
var result api.GenericResult
var listResult api.GenericListResult
var apiErr *api.Error
switch c.Func {
case "create":
result, apiErr, err = userClient.Create(c.Context, c.FlagScopeId, opts...)
result, err = userClient.Create(c.Context, c.FlagScopeId, opts...)
case "update":
result, apiErr, err = userClient.Update(c.Context, c.FlagId, version, opts...)
result, err = userClient.Update(c.Context, c.FlagId, version, opts...)
case "read":
result, apiErr, err = userClient.Read(c.Context, c.FlagId, opts...)
result, err = userClient.Read(c.Context, c.FlagId, opts...)
case "delete":
_, apiErr, err = userClient.Delete(c.Context, c.FlagId, opts...)
if apiErr != nil && apiErr.Status == int32(http.StatusNotFound) {
_, err = userClient.Delete(c.Context, c.FlagId, opts...)
if apiErr := api.AsServerError(err); apiErr != nil && apiErr.Status == int32(http.StatusNotFound) {
existed = false
apiErr = nil
err = nil
}
case "list":
listResult, apiErr, err = userClient.List(c.Context, c.FlagScopeId, opts...)
listResult, err = userClient.List(c.Context, c.FlagScopeId, opts...)
}
plural := "user"
@@ -151,13 +149,13 @@ func (c *Command) Run(args []string) int {
plural = "users"
}
if err != nil {
if api.AsServerError(err) != nil {
c.UI.Error(fmt.Sprintf("Error from controller when performing %s on %s: %s", c.Func, plural, err.Error()))
return 1
}
c.UI.Error(fmt.Sprintf("Error trying to %s %s: %s", c.Func, plural, err.Error()))
return 2
}
if apiErr != nil {
c.UI.Error(fmt.Sprintf("Error from controller when performing %s on %s: %s", c.Func, plural, pretty.Sprint(apiErr)))
return 1
}
switch c.Func {
case "delete":
+4 -8
View File
@@ -36,17 +36,15 @@ func TestAuthenticationMulti(t *testing.T) {
defer c2.Shutdown()
auth := authmethods.NewClient(c1.Client())
token1Result, apiErr, err := auth.Authenticate(c1.Context(), amId, map[string]interface{}{"login_name": user, "password": password})
token1Result, err := auth.Authenticate(c1.Context(), amId, map[string]interface{}{"login_name": user, "password": password})
require.Nil(err)
require.Nil(apiErr)
token1 := token1Result.Item
require.NotNil(token1)
time.Sleep(5 * time.Second)
auth = authmethods.NewClient(c2.Client())
token2Result, apiErr, err := auth.Authenticate(c2.Context(), amId, map[string]interface{}{"login_name": user, "password": password})
token2Result, err := auth.Authenticate(c2.Context(), amId, map[string]interface{}{"login_name": user, "password": password})
require.Nil(err)
require.Nil(apiErr)
token2 := token2Result.Item
require.NotNil(token2)
@@ -56,13 +54,11 @@ func TestAuthenticationMulti(t *testing.T) {
c2.Client().SetToken(token1.Token) // Same token, as it should work on both
// Create a project, read from the other
org, apiErr, err := scopes.NewClient(c1.Client()).Create(c1.Context(), scope.Global.String())
org, err := scopes.NewClient(c1.Client()).Create(c1.Context(), scope.Global.String())
require.NoError(err)
require.Nil(apiErr)
require.NotNil(org.Item)
proj, apiErr, err := scopes.NewClient(c2.Client()).Read(c2.Context(), org.Item.Id)
proj, err := scopes.NewClient(c2.Client()).Read(c2.Context(), org.Item.Id)
require.NoError(err)
require.Nil(apiErr)
require.NotNil(proj.Item)
}
+1 -6
View File
@@ -20,7 +20,6 @@ import (
wrapping "github.com/hashicorp/go-kms-wrapping"
"github.com/hashicorp/vault/sdk/helper/base62"
"github.com/jinzhu/gorm"
"github.com/kr/pretty"
)
const (
@@ -119,7 +118,7 @@ func (tc *TestController) Token() *authtokens.AuthToken {
tc.t.Error("no default auth method ID configured")
return nil
}
token, apiErr, err := authmethods.NewClient(tc.Client()).Authenticate(
token, err := authmethods.NewClient(tc.Client()).Authenticate(
tc.Context(),
tc.b.DevAuthMethodId,
map[string]interface{}{
@@ -131,10 +130,6 @@ func (tc *TestController) Token() *authtokens.AuthToken {
tc.t.Error(fmt.Errorf("error logging in: %w", err))
return nil
}
if apiErr != nil {
tc.t.Error(fmt.Errorf("api err from logging in: %s", pretty.Sprint(apiErr)))
return nil
}
return token.Item
}
+6 -10
View File
@@ -41,26 +41,23 @@ func TestRecoveryNonces(t *testing.T) {
// Token 1, try 1
client.SetToken(token1)
roleClient := roles.NewClient(client)
_, apiErr, err := roleClient.Create(tc.Context(), scope.Global.String())
_, err = roleClient.Create(tc.Context(), scope.Global.String())
require.NoError(err)
assert.Nil(apiErr)
nonces, err := repo.ListNonces(tc.Context())
require.NoError(err)
assert.Len(nonces, 1)
// Token 1, try 2
_, apiErr, err = roleClient.Create(tc.Context(), scope.Global.String())
require.NoError(err)
assert.NotNil(apiErr)
_, err = roleClient.Create(tc.Context(), scope.Global.String())
require.Error(err)
nonces, err = repo.ListNonces(tc.Context())
require.NoError(err)
assert.Len(nonces, 1)
// Token 2
roleClient.ApiClient().SetToken(token2)
_, apiErr, err = roleClient.Create(tc.Context(), scope.Global.String())
_, err = roleClient.Create(tc.Context(), scope.Global.String())
require.NoError(err)
assert.Nil(apiErr)
nonces, err = repo.ListNonces(tc.Context())
require.NoError(err)
assert.Len(nonces, 2)
@@ -74,9 +71,8 @@ func TestRecoveryNonces(t *testing.T) {
// And finally, make sure they still can't be used
for _, token := range []string{token1, token2} {
roleClient.ApiClient().SetToken(token)
_, apiErr, err = roleClient.Create(tc.Context(), scope.Global.String())
require.NoError(err)
assert.NotNil(apiErr)
_, err = roleClient.Create(tc.Context(), scope.Global.String())
require.Error(err)
nonces, err = repo.ListNonces(tc.Context())
require.NoError(err)
assert.Len(nonces, 0)