Account API handler for CRDL operations (#228)

This commit is contained in:
Todd Knight authored and GitHub committed 2020-08-05 10:19:55 -07:00
1 parent 2ca7e0b88e
commit e5ec1f48b2
22 files changed
+3777 -91

No files matched your search

+5 -3
View File
@@ -1,13 +1,15 @@
package common
import (
"github.com/hashicorp/watchtower/internal/auth/password"
"github.com/hashicorp/watchtower/internal/authtoken"
"github.com/hashicorp/watchtower/internal/host/static"
"github.com/hashicorp/watchtower/internal/iam"
)
type (
IamRepoFactory func() (*iam.Repository, error)
StaticRepoFactory func() (*static.Repository, error)
AuthTokenRepoFactory func() (*authtoken.Repository, error)
IamRepoFactory func() (*iam.Repository, error)
StaticRepoFactory func() (*static.Repository, error)
AuthTokenRepoFactory func() (*authtoken.Repository, error)
PasswordAuthRepoFactory func() (*password.Repository, error)
)
@@ -7,6 +7,7 @@ import (
"github.com/hashicorp/go-hclog"
"github.com/hashicorp/vault/sdk/helper/mlock"
"github.com/hashicorp/watchtower/internal/auth/password"
"github.com/hashicorp/watchtower/internal/authtoken"
"github.com/hashicorp/watchtower/internal/db"
"github.com/hashicorp/watchtower/internal/host/static"
@@ -25,6 +26,8 @@ type Controller struct {
IamRepoFn common.IamRepoFactory
StaticHostRepoFn common.StaticRepoFactory
AuthTokenRepoFn common.AuthTokenRepoFactory
PasswordAuthRepoFn common.PasswordAuthRepoFactory
}
func New(conf *Config) (*Controller, error) {
@@ -66,6 +69,9 @@ func New(conf *Config) (*Controller, error) {
c.AuthTokenRepoFn = func() (*authtoken.Repository, error) {
return authtoken.NewRepository(dbase, dbase, c.conf.ControllerKMS)
}
c.PasswordAuthRepoFn = func() (*password.Repository, error) {
return password.NewRepository(dbase, dbase, c.conf.ControllerKMS)
}
return c, nil
}
+8
View File
@@ -16,6 +16,7 @@ import (
"github.com/hashicorp/watchtower/globals"
"github.com/hashicorp/watchtower/internal/auth"
"github.com/hashicorp/watchtower/internal/gen/controller/api/services"
"github.com/hashicorp/watchtower/internal/servers/controller/handlers/accounts"
"github.com/hashicorp/watchtower/internal/servers/controller/handlers"
"github.com/hashicorp/watchtower/internal/servers/controller/handlers/authenticate"
@@ -80,6 +81,13 @@ func handleGrpcGateway(c *Controller) (http.Handler, error) {
if err := services.RegisterHostCatalogServiceHandlerServer(ctx, mux, hcs); err != nil {
return nil, fmt.Errorf("failed to register host catalog service handler: %w", err)
}
accts, err := accounts.NewService(c.logger, c.PasswordAuthRepoFn)
if err != nil {
return nil, fmt.Errorf("failed to create account handler service: %w", err)
}
if err := services.RegisterAccountServiceHandlerServer(ctx, mux, accts); err != nil {
return nil, fmt.Errorf("failed to register account service handler: %w", err)
}
auths, err := authenticate.NewService(c.IamRepoFn, c.AuthTokenRepoFn)
if err != nil {
return nil, fmt.Errorf("failed to create authentication handler service: %w", err)
@@ -46,6 +46,8 @@ func TestHandleImplementedPaths(t *testing.T) {
"v1/scopes/someid",
"v1/scopes/someid/auth-tokens",
"v1/scopes/someid/auth-tokens/someid",
"v1/scopes/someid/auth-methods/someid/accounts",
"v1/scopes/someid/auth-methods/someid/accounts/someid",
"v1/scopes/someid/groups",
"v1/scopes/someid/groups/someid",
"v1/scopes/someid/host-catalogs",
@@ -61,6 +63,7 @@ func TestHandleImplementedPaths(t *testing.T) {
"v1/scopes/someid/groups",
"v1/scopes/someid/roles",
"v1/scopes/someid/users",
"v1/scopes/someid/auth-methods/someid/accounts",
// custom methods
"v1/scopes/someid/auth-methods/someid:authenticate",
@@ -80,6 +83,7 @@ func TestHandleImplementedPaths(t *testing.T) {
"v1/scopes/someid/roles/someid",
"v1/scopes/someid/groups/someid",
"v1/scopes/someid/auth-tokens/someid",
"v1/scopes/someid/auth-methods/someid/accounts/someid",
},
"PATCH": {
"v1/scopes/someid",
@@ -0,0 +1,314 @@
package accounts
import (
"context"
"errors"
"fmt"
"regexp"
"strings"
"github.com/hashicorp/go-hclog"
"github.com/hashicorp/watchtower/internal/auth"
"github.com/hashicorp/watchtower/internal/auth/password"
"github.com/hashicorp/watchtower/internal/auth/password/store"
"github.com/hashicorp/watchtower/internal/db"
pb "github.com/hashicorp/watchtower/internal/gen/controller/api/resources/auth"
pbs "github.com/hashicorp/watchtower/internal/gen/controller/api/services"
"github.com/hashicorp/watchtower/internal/servers/controller/handlers"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/types/known/wrapperspb"
)
var (
maskManager handlers.MaskManager
reInvalidID = regexp.MustCompile("[^A-Za-z0-9]")
)
func init() {
var err error
if maskManager, err = handlers.NewMaskManager(&pb.Account{}, &store.Account{}); err != nil {
panic(err)
}
}
// Service handles request as described by the pbs.AccountServiceServer interface.
type Service struct {
repoFn func() (*password.Repository, error)
log hclog.Logger
}
// NewService returns a user service which handles user related requests to watchtower.
func NewService(log hclog.Logger, repo func() (*password.Repository, error)) (Service, error) {
if repo == nil {
return Service{}, fmt.Errorf("nil password repository provided")
}
return Service{log: log, repoFn: repo}, nil
}
var _ pbs.AccountServiceServer = Service{}
// TODO(ICU-407): Validate that the provided auth method and account are in the provided scope.
// ListAccounts implements the interface pbs.AccountServiceServer.
func (s Service) ListAccounts(ctx context.Context, req *pbs.ListAccountsRequest) (*pbs.ListAccountsResponse, error) {
authResults := auth.Verify(ctx)
if !authResults.Valid {
return nil, handlers.ForbiddenError()
}
if err := validateListRequest(req); err != nil {
return nil, err
}
ul, err := s.listFromRepo(ctx, req.GetAuthMethodId())
if err != nil {
return nil, err
}
for _, item := range ul {
item.Scope = authResults.Scope
}
return &pbs.ListAccountsResponse{Items: ul}, nil
}
// GetAccounts implements the interface pbs.AccountServiceServer.
func (s Service) GetAccount(ctx context.Context, req *pbs.GetAccountRequest) (*pbs.GetAccountResponse, error) {
authResults := auth.Verify(ctx)
if !authResults.Valid {
return nil, handlers.ForbiddenError()
}
if err := validateGetRequest(req); err != nil {
return nil, err
}
u, err := s.getFromRepo(ctx, req.GetId())
if err != nil {
return nil, err
}
u.Scope = authResults.Scope
return &pbs.GetAccountResponse{Item: u}, nil
}
// CreateAccount implements the interface pbs.AccountServiceServer.
func (s Service) CreateAccount(ctx context.Context, req *pbs.CreateAccountRequest) (*pbs.CreateAccountResponse, error) {
authResults := auth.Verify(ctx)
if !authResults.Valid {
return nil, handlers.ForbiddenError()
}
if err := validateCreateRequest(req); err != nil {
return nil, err
}
u, err := s.createInRepo(ctx, req.GetAuthMethodId(), req.GetItem())
if err != nil {
return nil, err
}
u.Scope = authResults.Scope
return &pbs.CreateAccountResponse{Item: u, Uri: fmt.Sprintf("scopes/%s/auth-methods/%s/accounts/%s", authResults.Scope.GetId(), u.GetAuthMethodId(), u.GetId())}, nil
}
// UpdateAccount implements the interface pbs.AccountServiceServer.
func (s Service) UpdateAccount(ctx context.Context, req *pbs.UpdateAccountRequest) (*pbs.UpdateAccountResponse, error) {
panic("UpdateAccount is not implemented.")
}
// DeleteAccount implements the interface pbs.AccountServiceServer.
func (s Service) DeleteAccount(ctx context.Context, req *pbs.DeleteAccountRequest) (*pbs.DeleteAccountResponse, error) {
authResults := auth.Verify(ctx)
if !authResults.Valid {
return nil, handlers.ForbiddenError()
}
if err := validateDeleteRequest(req); err != nil {
return nil, err
}
existed, err := s.deleteFromRepo(ctx, req.GetId())
if err != nil {
return nil, err
}
return &pbs.DeleteAccountResponse{Existed: existed}, nil
}
func (s Service) getFromRepo(ctx context.Context, id string) (*pb.Account, error) {
repo, err := s.repoFn()
if err != nil {
return nil, err
}
u, err := repo.LookupAccount(ctx, id)
if err != nil {
if errors.Is(err, db.ErrRecordNotFound) {
return nil, handlers.NotFoundErrorf("Account %q doesn't exist.", id)
}
return nil, err
}
if u == nil {
return nil, handlers.NotFoundErrorf("Account %q doesn't exist.", id)
}
return s.toProto(u), nil
}
func (s Service) createInRepo(ctx context.Context, authMethodId string, item *pb.Account) (*pb.Account, error) {
pwAttrs := &pb.PasswordAccountAttributes{}
if err := handlers.StructToProto(item.GetAttributes(), pwAttrs); err != nil {
return nil, status.Errorf(codes.InvalidArgument, "Provided attributes don't match expected format.")
}
var opts []password.Option
if item.GetName() != nil {
opts = append(opts, password.WithName(item.GetName().GetValue()))
}
if item.GetDescription() != nil {
opts = append(opts, password.WithDescription(item.GetDescription().GetValue()))
}
a, err := password.NewAccount(authMethodId, pwAttrs.GetUsername(), opts...)
if err != nil {
return nil, status.Errorf(codes.Internal, "Unable to build user for creation: %v.", err)
}
repo, err := s.repoFn()
if err != nil {
return nil, err
}
out, err := repo.CreateAccount(ctx, a)
if err != nil {
return nil, status.Errorf(codes.Internal, "Unable to create user: %v.", err)
}
if out == nil {
return nil, status.Error(codes.Internal, "Unable to create user but no error returned from repository.")
}
return s.toProto(out), nil
}
func (s Service) deleteFromRepo(ctx context.Context, id string) (bool, error) {
repo, err := s.repoFn()
if err != nil {
return false, err
}
rows, err := repo.DeleteAccount(ctx, id)
if err != nil {
if errors.Is(err, db.ErrRecordNotFound) {
return false, nil
}
return false, status.Errorf(codes.Internal, "Unable to delete user: %v.", err)
}
return rows > 0, nil
}
func (s Service) listFromRepo(ctx context.Context, authMethodId string) ([]*pb.Account, error) {
repo, err := s.repoFn()
if err != nil {
return nil, err
}
ul, err := repo.ListAccounts(ctx, authMethodId)
if err != nil {
return nil, err
}
var outUl []*pb.Account
for _, u := range ul {
outUl = append(outUl, s.toProto(u))
}
return outUl, nil
}
func (s Service) toProto(in *password.Account) *pb.Account {
out := pb.Account{
Id: in.GetPublicId(),
CreatedTime: in.GetCreateTime().GetTimestamp(),
UpdatedTime: in.GetUpdateTime().GetTimestamp(),
AuthMethodId: in.GetAuthMethodId(),
Type: "password",
}
if in.GetDescription() != "" {
out.Description = &wrapperspb.StringValue{Value: in.GetDescription()}
}
if in.GetName() != "" {
out.Name = &wrapperspb.StringValue{Value: in.GetName()}
}
if st, err := handlers.ProtoToStruct(&pb.PasswordAccountAttributes{Username: in.GetUserName()}); err == nil {
out.Attributes = st
} else {
s.log.Error("failed converting account attribute to struct", "error", err)
}
return &out
}
// A validateX method should exist for each method above. These methods do not make calls to any backing service but enforce
// requirements on the structure of the request. They verify that:
// * The path passed in is correctly formatted
// * All required parameters are set
// * There are no conflicting parameters provided
func validateGetRequest(req *pbs.GetAccountRequest) error {
badFields := map[string]string{}
if !validId(req.GetId(), password.AccountPrefix+"_") {
badFields["id"] = "Invalid formatted identifier."
}
if !validId(req.GetAuthMethodId(), password.AuthMethodPrefix+"_") {
badFields["auth_method_id"] = "Invalid formatted identifier."
}
if len(badFields) > 0 {
return handlers.InvalidArgumentErrorf("Improperly formatted identifier.", badFields)
}
return nil
}
func validateCreateRequest(req *pbs.CreateAccountRequest) error {
badFields := map[string]string{}
if !validId(req.GetAuthMethodId(), password.AuthMethodPrefix+"_") {
badFields["auth_method_id"] = "Invalid formatted identifier."
}
item := req.GetItem()
if item.GetId() != "" {
badFields["id"] = "This is a read only field."
}
if item.GetAuthMethodId() != "" {
badFields["auth_method_id"] = "This is a read only field."
}
if item.GetCreatedTime() != nil {
badFields["created_time"] = "This is a read only field."
}
if item.GetUpdatedTime() != nil {
badFields["updated_time"] = "This is a read only field."
}
switch item.GetType() {
case "password":
pwAttrs := &pb.PasswordAccountAttributes{}
if err := handlers.StructToProto(item.GetAttributes(), pwAttrs); err != nil {
badFields["attributes"] = "Attribute fields do not match the expected format."
}
if pwAttrs.GetUsername() == "" {
badFields["username"] = "This is a required field for this type."
}
default:
badFields["type"] = "This is a required field."
}
if len(badFields) > 0 {
return handlers.InvalidArgumentErrorf("Argument errors found in the request.", badFields)
}
return nil
}
func validateDeleteRequest(req *pbs.DeleteAccountRequest) error {
badFields := map[string]string{}
if !validId(req.GetAuthMethodId(), password.AuthMethodPrefix+"_") {
badFields["auth_method_id"] = "Invalid formatted identifier."
}
if !validId(req.GetId(), password.AccountPrefix+"_") {
badFields["id"] = "Incorrectly formatted identifier."
}
if len(badFields) > 0 {
return handlers.InvalidArgumentErrorf("Errors in provided fields.", badFields)
}
return nil
}
func validateListRequest(req *pbs.ListAccountsRequest) error {
badFields := map[string]string{}
if !validId(req.GetAuthMethodId(), password.AuthMethodPrefix+"_") {
badFields["auth_method_id"] = "Invalid formatted identifier."
}
if len(badFields) > 0 {
return handlers.InvalidArgumentErrorf("Improperly formatted identifier.", badFields)
}
return nil
}
func validId(id, prefix string) bool {
if !strings.HasPrefix(id, prefix) {
return false
}
id = strings.TrimPrefix(id, prefix)
return !reInvalidID.Match([]byte(id))
}
@@ -0,0 +1,435 @@
package accounts_test
import (
"fmt"
"strings"
"testing"
"github.com/golang/protobuf/ptypes"
"github.com/google/go-cmp/cmp"
"github.com/hashicorp/go-hclog"
"github.com/hashicorp/watchtower/internal/auth"
"github.com/hashicorp/watchtower/internal/auth/password"
"github.com/hashicorp/watchtower/internal/authtoken"
"github.com/hashicorp/watchtower/internal/db"
pb "github.com/hashicorp/watchtower/internal/gen/controller/api/resources/auth"
"github.com/hashicorp/watchtower/internal/gen/controller/api/resources/scopes"
pbs "github.com/hashicorp/watchtower/internal/gen/controller/api/services"
"github.com/hashicorp/watchtower/internal/iam"
"github.com/hashicorp/watchtower/internal/servers/controller/handlers"
"github.com/hashicorp/watchtower/internal/servers/controller/handlers/accounts"
"github.com/hashicorp/watchtower/internal/types/scope"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/testing/protocmp"
"google.golang.org/protobuf/types/known/structpb"
"google.golang.org/protobuf/types/known/wrapperspb"
)
func TestGet(t *testing.T) {
conn, _ := db.TestSetup(t, "postgres")
rw := db.New(conn)
wrap := db.TestWrapper(t)
repoFn := func() (*password.Repository, error) {
return password.NewRepository(rw, rw, wrap)
}
s, err := accounts.NewService(hclog.L(), repoFn)
require.NoError(t, err, "Couldn't create new auth token service.")
org, _ := iam.TestScopes(t, conn)
am := password.TestAuthMethods(t, conn, org.GetPublicId(), 1)[0]
aa := password.TestAccounts(t, conn, am.GetPublicId(), 1)[0]
wireAccount := pb.Account{
Id: aa.GetPublicId(),
AuthMethodId: aa.GetAuthMethodId(),
CreatedTime: aa.GetCreateTime().GetTimestamp(),
UpdatedTime: aa.GetUpdateTime().GetTimestamp(),
Scope: &scopes.ScopeInfo{Id: org.GetPublicId(), Type: scope.Org.String()},
Type: "password",
Attributes: &structpb.Struct{Fields: map[string]*structpb.Value{"username": structpb.NewStringValue(aa.GetUserName())}},
}
cases := []struct {
name string
req *pbs.GetAccountRequest
res *pbs.GetAccountResponse
errCode codes.Code
}{
{
name: "Get an existing account",
req: &pbs.GetAccountRequest{AuthMethodId: wireAccount.GetAuthMethodId(), Id: wireAccount.GetId()},
res: &pbs.GetAccountResponse{Item: &wireAccount},
errCode: codes.OK,
},
{
name: "Get a non existing account",
req: &pbs.GetAccountRequest{AuthMethodId: wireAccount.GetAuthMethodId(), Id: password.AccountPrefix + "_DoesntExis"},
res: nil,
errCode: codes.NotFound,
},
{
name: "Wrong id prefix",
req: &pbs.GetAccountRequest{AuthMethodId: wireAccount.GetAuthMethodId(), Id: "j_1234567890"},
res: nil,
errCode: codes.InvalidArgument,
},
{
name: "space in id",
req: &pbs.GetAccountRequest{AuthMethodId: wireAccount.GetAuthMethodId(), Id: authtoken.AuthTokenPrefix + "_1 23456789"},
res: nil,
errCode: codes.InvalidArgument,
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
assert := assert.New(t)
got, gErr := s.GetAccount(auth.DisabledAuthTestContext(auth.WithScopeId(org.GetPublicId())), tc.req)
assert.Equal(tc.errCode, status.Code(gErr), "GetAccount(%+v) got error %v, wanted %v", tc.req, gErr, tc.errCode)
assert.Empty(cmp.Diff(got, tc.res, protocmp.Transform()), "GetAccount(%q) got response %q, wanted %q", tc.req, got, tc.res)
})
}
}
func TestList(t *testing.T) {
conn, _ := db.TestSetup(t, "postgres")
rw := db.New(conn)
wrap := db.TestWrapper(t)
repoFn := func() (*password.Repository, error) {
return password.NewRepository(rw, rw, wrap)
}
o, _ := iam.TestScopes(t, conn)
ams := password.TestAuthMethods(t, conn, o.GetPublicId(), 3)
amNoAccounts, amSomeAccounts, amOtherAccounts := ams[0], ams[1], ams[2]
var wantSomeAccounts []*pb.Account
for _, aa := range password.TestAccounts(t, conn, amSomeAccounts.GetPublicId(), 3) {
wantSomeAccounts = append(wantSomeAccounts, &pb.Account{
Id: aa.GetPublicId(),
AuthMethodId: aa.GetAuthMethodId(),
CreatedTime: aa.GetCreateTime().GetTimestamp(),
UpdatedTime: aa.GetUpdateTime().GetTimestamp(),
Scope: &scopes.ScopeInfo{Id: o.GetPublicId(), Type: scope.Org.String()},
Type: "password",
Attributes: &structpb.Struct{Fields: map[string]*structpb.Value{"username": structpb.NewStringValue(aa.GetUserName())}},
})
}
var wantOtherAccounts []*pb.Account
for _, aa := range password.TestAccounts(t, conn, amOtherAccounts.GetPublicId(), 3) {
wantOtherAccounts = append(wantOtherAccounts, &pb.Account{
Id: aa.GetPublicId(),
AuthMethodId: aa.GetAuthMethodId(),
CreatedTime: aa.GetCreateTime().GetTimestamp(),
UpdatedTime: aa.GetUpdateTime().GetTimestamp(),
Scope: &scopes.ScopeInfo{Id: o.GetPublicId(), Type: scope.Org.String()},
Type: "password",
Attributes: &structpb.Struct{Fields: map[string]*structpb.Value{"username": structpb.NewStringValue(aa.GetUserName())}},
})
}
cases := []struct {
name string
authMethod string
res *pbs.ListAccountsResponse
errCode codes.Code
}{
{
name: "List Some Accounts",
authMethod: amSomeAccounts.GetPublicId(),
res: &pbs.ListAccountsResponse{Items: wantSomeAccounts},
errCode: codes.OK,
},
{
name: "List Other Accounts",
authMethod: amOtherAccounts.GetPublicId(),
res: &pbs.ListAccountsResponse{Items: wantOtherAccounts},
errCode: codes.OK,
},
{
name: "List No Accounts",
authMethod: amNoAccounts.GetPublicId(),
res: &pbs.ListAccountsResponse{},
errCode: codes.OK,
},
// TODO: When an auth method doesn't exist, we should return a 404 instead of an empty list.
{
name: "Unfound Auth Method",
authMethod: password.AuthMethodPrefix + "_DoesntExis",
res: &pbs.ListAccountsResponse{},
errCode: codes.OK,
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
s, err := accounts.NewService(hclog.L(), repoFn)
require.NoError(t, err, "Couldn't create new user service.")
got, gErr := s.ListAccounts(auth.DisabledAuthTestContext(auth.WithScopeId(o.GetPublicId())), &pbs.ListAccountsRequest{AuthMethodId: tc.authMethod})
assert.Equal(t, tc.errCode, status.Code(gErr), "ListAccounts() with auth method %q got error %v, wanted %v", tc.authMethod, gErr, tc.errCode)
assert.Empty(t, cmp.Diff(got, tc.res, protocmp.Transform(), protocmp.SortRepeatedFields(got)), "ListUsers() with scope %q got response %q, wanted %q", tc.authMethod, got, tc.res)
})
}
}
func TestDelete(t *testing.T) {
conn, _ := db.TestSetup(t, "postgres")
rw := db.New(conn)
wrap := db.TestWrapper(t)
repoFn := func() (*password.Repository, error) {
return password.NewRepository(rw, rw, wrap)
}
o, _ := iam.TestScopes(t, conn)
ams := password.TestAuthMethods(t, conn, o.GetPublicId(), 2)
am1, wrongAm := ams[0], ams[1]
ac := password.TestAccounts(t, conn, am1.GetPublicId(), 1)[0]
wrongAc := password.TestAccounts(t, conn, wrongAm.GetPublicId(), 1)[0]
s, err := accounts.NewService(hclog.L(), repoFn)
require.NoError(t, err, "Error when getting new user service.")
cases := []struct {
name string
scope string
req *pbs.DeleteAccountRequest
res *pbs.DeleteAccountResponse
errCode codes.Code
}{
{
name: "Delete an existing token",
req: &pbs.DeleteAccountRequest{
AuthMethodId: am1.GetPublicId(),
Id: ac.GetPublicId(),
},
res: &pbs.DeleteAccountResponse{
Existed: true,
},
errCode: codes.OK,
},
{
name: "Delete account from wrong auth method",
req: &pbs.DeleteAccountRequest{
AuthMethodId: am1.GetPublicId(),
Id: wrongAc.GetPublicId(),
},
// TODO(toddknight): This should return Existed:false. Figure out if this test is testing something valid
// and if so make it pass.
res: &pbs.DeleteAccountResponse{
Existed: true,
},
errCode: codes.OK,
},
{
name: "Delete bad account id",
req: &pbs.DeleteAccountRequest{
AuthMethodId: am1.GetPublicId(),
Id: password.AccountPrefix + "_doesntexis",
},
res: &pbs.DeleteAccountResponse{
Existed: false,
},
errCode: codes.OK,
},
{
name: "Bad account id formatting",
req: &pbs.DeleteAccountRequest{
AuthMethodId: am1.GetPublicId(),
Id: "bad_format",
},
res: nil,
errCode: codes.InvalidArgument,
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
assert := assert.New(t)
got, gErr := s.DeleteAccount(auth.DisabledAuthTestContext(auth.WithScopeId(o.GetPublicId())), tc.req)
assert.Equal(tc.errCode, status.Code(gErr), "DeleteAccount(%+v) got error %v, wanted %v", tc.req, gErr, tc.errCode)
assert.EqualValuesf(tc.res, got, "DeleteAccount(%q) got response %q, wanted %q", tc.req, got, tc.res)
})
}
}
func TestDelete_twice(t *testing.T) {
assert := assert.New(t)
conn, _ := db.TestSetup(t, "postgres")
rw := db.New(conn)
wrap := db.TestWrapper(t)
repoFn := func() (*password.Repository, error) {
return password.NewRepository(rw, rw, wrap)
}
o, _ := iam.TestScopes(t, conn)
am := password.TestAuthMethods(t, conn, o.GetPublicId(), 1)[0]
ac := password.TestAccounts(t, conn, am.GetPublicId(), 1)[0]
s, err := accounts.NewService(hclog.L(), repoFn)
require.NoError(t, err, "Error when getting new user service")
req := &pbs.DeleteAccountRequest{
AuthMethodId: am.GetPublicId(),
Id: ac.GetPublicId(),
}
got, gErr := s.DeleteAccount(auth.DisabledAuthTestContext(auth.WithScopeId(o.GetPublicId())), req)
assert.NoError(gErr, "First attempt")
assert.True(got.GetExisted(), "Expected existed to be true for the first delete.")
got, gErr = s.DeleteAccount(auth.DisabledAuthTestContext(auth.WithScopeId(o.GetPublicId())), req)
assert.NoError(gErr, "Second attempt")
assert.False(got.GetExisted(), "Expected existed to be false for the second delete.")
}
func TestCreate(t *testing.T) {
conn, _ := db.TestSetup(t, "postgres")
rw := db.New(conn)
wrap := db.TestWrapper(t)
repoFn := func() (*password.Repository, error) {
return password.NewRepository(rw, rw, wrap)
}
s, err := accounts.NewService(hclog.L(), repoFn)
require.NoError(t, err, "Error when getting new account service.")
o, _ := iam.TestScopes(t, conn)
am := password.TestAuthMethods(t, conn, o.GetPublicId(), 1)[0]
defaultAccount := password.TestAccounts(t, conn, am.GetPublicId(), 1)[0]
defaultCreated, err := ptypes.Timestamp(defaultAccount.GetCreateTime().GetTimestamp())
require.NoError(t, err, "Error converting proto to timestamp.")
defaultSt, err := handlers.ProtoToStruct(&pb.PasswordAccountAttributes{Username: "thetestusername"})
require.NoError(t, err, "Error converting proto to struct.")
cases := []struct {
name string
req *pbs.CreateAccountRequest
res *pbs.CreateAccountResponse
errCode codes.Code
}{
{
name: "Create a valid Account",
req: &pbs.CreateAccountRequest{
AuthMethodId: defaultAccount.GetAuthMethodId(),
Item: &pb.Account{
Name: &wrapperspb.StringValue{Value: "name"},
Description: &wrapperspb.StringValue{Value: "desc"},
Type: "password",
Attributes: defaultSt,
},
},
res: &pbs.CreateAccountResponse{
Uri: fmt.Sprintf("scopes/%s/auth-methods/%s/accounts/%s_", o.GetPublicId(), defaultAccount.GetAuthMethodId(), password.AccountPrefix),
Item: &pb.Account{
AuthMethodId: defaultAccount.GetAuthMethodId(),
Name: &wrapperspb.StringValue{Value: "name"},
Description: &wrapperspb.StringValue{Value: "desc"},
Scope: &scopes.ScopeInfo{Id: o.GetPublicId(), Type: scope.Org.String()},
Type: "password",
Attributes: defaultSt,
},
},
errCode: codes.OK,
},
{
name: "Can't specify Id",
req: &pbs.CreateAccountRequest{
AuthMethodId: defaultAccount.GetAuthMethodId(),
Item: &pb.Account{
Id: password.AccountPrefix + "_notallowed",
Type: "password",
Attributes: defaultSt,
},
},
res: nil,
errCode: codes.InvalidArgument,
},
{
name: "Can't specify AuthMethodId",
req: &pbs.CreateAccountRequest{
AuthMethodId: defaultAccount.GetAuthMethodId(),
Item: &pb.Account{
AuthMethodId: defaultAccount.GetAuthMethodId(),
Type: "password",
Attributes: defaultSt,
},
},
res: nil,
errCode: codes.InvalidArgument,
},
{
name: "Can't specify Created Time",
req: &pbs.CreateAccountRequest{
AuthMethodId: defaultAccount.GetAuthMethodId(),
Item: &pb.Account{
CreatedTime: ptypes.TimestampNow(),
Type: "password",
Attributes: defaultSt,
},
},
res: nil,
errCode: codes.InvalidArgument,
},
{
name: "Can't specify Update Time",
req: &pbs.CreateAccountRequest{
AuthMethodId: defaultAccount.GetAuthMethodId(),
Item: &pb.Account{
UpdatedTime: ptypes.TimestampNow(),
Type: "password",
Attributes: defaultSt,
},
},
res: nil,
errCode: codes.InvalidArgument,
},
{
name: "Must specify type",
req: &pbs.CreateAccountRequest{
AuthMethodId: defaultAccount.GetAuthMethodId(),
Item: &pb.Account{
Attributes: defaultSt,
},
},
res: nil,
errCode: codes.InvalidArgument,
},
{
name: "Must specify username for password type",
req: &pbs.CreateAccountRequest{
AuthMethodId: defaultAccount.GetAuthMethodId(),
Item: &pb.Account{
Type: "password",
},
},
res: nil,
errCode: codes.InvalidArgument,
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
assert, require := assert.New(t), require.New(t)
got, gErr := s.CreateAccount(auth.DisabledAuthTestContext(auth.WithScopeId(o.GetPublicId())), tc.req)
assert.Equal(tc.errCode, status.Code(gErr), "CreateAccount(%+v) got error %v, wanted %v", tc.req, gErr, tc.errCode)
if got != nil {
assert.Contains(got.GetUri(), tc.res.Uri)
assert.True(strings.HasPrefix(got.GetItem().GetId(), password.AccountPrefix+"_"))
gotCreateTime, err := ptypes.Timestamp(got.GetItem().GetCreatedTime())
require.NoError(err, "Error converting proto to timestamp.")
gotUpdateTime, err := ptypes.Timestamp(got.GetItem().GetUpdatedTime())
require.NoError(err, "Error converting proto to timestamp.")
// Verify it is a user created after the test setup's default user
assert.True(gotCreateTime.After(defaultCreated), "New account should have been created after default user. Was created %v, which is after %v", gotCreateTime, defaultCreated)
assert.True(gotUpdateTime.After(defaultCreated), "New account should have been updated after default user. Was updated %v, which is after %v", gotUpdateTime, defaultCreated)
// Clear all values which are hard to compare against.
got.Uri, tc.res.Uri = "", ""
got.Item.Id, tc.res.Item.Id = "", ""
got.Item.CreatedTime, got.Item.UpdatedTime, tc.res.Item.CreatedTime, tc.res.Item.UpdatedTime = nil, nil, nil, nil
}
assert.Empty(cmp.Diff(got, tc.res, protocmp.Transform()), "CreateAccount(%q) got response %q, wanted %q", tc.req, got, tc.res)
})
}
}
@@ -15,7 +15,6 @@ import (
"github.com/hashicorp/watchtower/internal/types/scope"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/testing/protocmp"
"github.com/stretchr/testify/assert"
@@ -82,8 +81,8 @@ func TestGet(t *testing.T) {
t.Run(tc.name, func(t *testing.T) {
assert := assert.New(t)
got, gErr := s.GetAuthToken(auth.DisabledAuthTestContext(auth.WithScopeId(org.GetPublicId())), tc.req)
assert.Equal(tc.errCode, status.Code(gErr), "GetOrg(%+v) got error %v, wanted %v", tc.req, gErr, tc.errCode)
assert.True(proto.Equal(got, tc.res), "GetOrg(%q) got response %q, wanted %q", tc.req, got, tc.res)
assert.Equal(tc.errCode, status.Code(gErr), "GetAuthToken(%+v) got error %v, wanted %v", tc.req, gErr, tc.errCode)
assert.Empty(cmp.Diff(got, tc.res, protocmp.Transform()), "GetAuthToken(%q) got response %q, wanted %q", tc.req, got, tc.res)
})
}
}
@@ -168,8 +167,8 @@ func TestList(t *testing.T) {
require.NoError(t, err, "Couldn't create new user service.")
got, gErr := s.ListAuthTokens(auth.DisabledAuthTestContext(auth.WithScopeId(tc.scope)), &pbs.ListAuthTokensRequest{})
assert.Equal(t, tc.errCode, status.Code(gErr), "ListUsers() with scope %q got error %v, wanted %v", tc.scope, gErr, tc.errCode)
assert.Empty(t, cmp.Diff(got, tc.res, protocmp.Transform(), protocmp.SortRepeatedFields(got)), "ListUsers() with scope %q got response %q, wanted %q", tc.scope, got, tc.res)
assert.Equal(t, tc.errCode, status.Code(gErr), "ListAuthTokens() with scope %q got error %v, wanted %v", tc.scope, gErr, tc.errCode)
assert.Empty(t, cmp.Diff(got, tc.res, protocmp.Transform(), protocmp.SortRepeatedFields(got)), "ListAuthTokens() with scope %q got response %q, wanted %q", tc.scope, got, tc.res)
})
}
}
@@ -246,8 +245,8 @@ func TestDelete(t *testing.T) {
t.Run(tc.name, func(t *testing.T) {
assert := assert.New(t)
got, gErr := s.DeleteAuthToken(auth.DisabledAuthTestContext(auth.WithScopeId(tc.scope)), tc.req)
assert.Equal(tc.errCode, status.Code(gErr), "DeleteUser(%+v) got error %v, wanted %v", tc.req, gErr, tc.errCode)
assert.EqualValuesf(tc.res, got, "DeleteUser(%q) got response %q, wanted %q", tc.req, got, tc.res)
assert.Equal(tc.errCode, status.Code(gErr), "DeleteAuthToken(%+v) got error %v, wanted %v", tc.req, gErr, tc.errCode)
assert.EqualValuesf(tc.res, got, "DeleteAuthToken(%q) got response %q, wanted %q", tc.req, got, tc.res)
})
}
}
@@ -270,7 +270,7 @@ func TestList(t *testing.T) {
got, gErr := s.ListGroups(auth.DisabledAuthTestContext(auth.WithScopeId(tc.scopeId)), &pbs.ListGroupsRequest{})
assert.Equal(tc.errCode, status.Code(gErr), "ListGroups(%q) got error %v, wanted %v", tc.scopeId, gErr, tc.errCode)
assert.True(proto.Equal(got, tc.res), "ListGroups(%q) got response %q, wanted %q", tc.scopeId, got, tc.res)
assert.Empty(cmp.Diff(got, tc.res, protocmp.Transform()), "ListGroups(%q) got response %q, wanted %q", tc.scopeId, got, tc.res)
})
}
}
@@ -496,7 +496,7 @@ func TestCreate(t *testing.T) {
got, gErr := s.CreateGroup(auth.DisabledAuthTestContext(auth.WithScopeId(tc.scopeId)), req)
assert.Equal(tc.errCode, status.Code(gErr), "CreateGroup(%+v) got error %v, wanted %v", req, gErr, tc.errCode)
if got != nil {
assert.True(strings.HasPrefix(got.GetUri(), tc.res.Uri), got.GetUri())
assert.Contains(got.GetUri(), tc.res.Uri)
assert.True(strings.HasPrefix(got.GetItem().GetId(), iam.GroupPrefix+"_"))
gotCreateTime, err := ptypes.Timestamp(got.GetItem().GetCreatedTime())
require.NoError(err, "Error converting proto to timestamp.")
@@ -8,6 +8,7 @@ import (
"github.com/golang/protobuf/ptypes"
"github.com/golang/protobuf/ptypes/wrappers"
"github.com/google/go-cmp/cmp"
"github.com/hashicorp/watchtower/internal/auth"
"github.com/hashicorp/watchtower/internal/db"
pb "github.com/hashicorp/watchtower/internal/gen/controller/api/resources/hosts"
@@ -21,6 +22,7 @@ import (
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/testing/protocmp"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
@@ -107,7 +109,7 @@ func TestGet(t *testing.T) {
got, gErr := s.GetHostCatalog(auth.DisabledAuthTestContext(auth.WithScopeId(proj.GetPublicId())), req)
assert.Equal(tc.errCode, status.Code(gErr), "GetHostCatalog(%+v) got error %v, wanted %v", req, gErr, tc.errCode)
assert.True(proto.Equal(got, tc.res), "GetHostCatalog(%q) got response %q, wanted %q", req, got, tc.res)
assert.Empty(cmp.Diff(got, tc.res, protocmp.Transform()), "GetHostCatalog(%q) got response %q, wanted %q", req, got, tc.res)
})
}
}
@@ -296,7 +298,7 @@ func TestCreate(t *testing.T) {
got, gErr := s.CreateHostCatalog(auth.DisabledAuthTestContext(auth.WithScopeId(proj.GetPublicId())), req)
assert.Equal(tc.errCode, status.Code(gErr), "CreateHostCatalog(%+v) got error %v, wanted %v", req, gErr, tc.errCode)
if got != nil {
assert.True(strings.HasPrefix(got.GetUri(), tc.res.GetUri()))
assert.Contains(got.GetUri(), tc.res.GetUri())
assert.True(strings.HasPrefix(got.GetItem().GetId(), static.HostCatalogPrefix))
gotCreateTime, err := ptypes.Timestamp(got.GetItem().GetCreatedTime())
require.NoError(err, "Error converting proto to timestamp.")
@@ -311,7 +313,7 @@ func TestCreate(t *testing.T) {
got.Item.Id, tc.res.Item.Id = "", ""
got.Item.CreatedTime, got.Item.UpdatedTime, tc.res.Item.CreatedTime, tc.res.Item.UpdatedTime = nil, nil, nil, nil
}
assert.True(proto.Equal(got, tc.res), "CreateHostCatalog(%q) got response %q, wanted %q", req, got, tc.res)
assert.Empty(cmp.Diff(got, tc.res, protocmp.Transform()), "CreateHostCatalog(%q) got response %q, wanted %q", req, got, tc.res)
})
}
}
@@ -604,7 +606,7 @@ func TestUpdate(t *testing.T) {
// Clear all values which are hard to compare against.
got.Item.UpdatedTime, tc.res.Item.UpdatedTime = nil, nil
}
assert.True(proto.Equal(got, tc.res), "UpdateHostCatalog(%q) got response %q, wanted %q", req, got, tc.res)
assert.Empty(cmp.Diff(got, tc.res, protocmp.Transform()), "UpdateHostCatalog(%q) got response %q, wanted %q", req, got, tc.res)
})
}
}
@@ -168,7 +168,7 @@ func TestGet(t *testing.T) {
got, gErr := s.GetRole(auth.DisabledAuthTestContext(auth.WithScopeId(tc.scopeId)), req)
assert.Equal(tc.errCode, status.Code(gErr), "GetRole(%+v) got error %v, wanted %v", req, gErr, tc.errCode)
assert.True(proto.Equal(got, tc.res), "GetRole(%q) got response\n%q, wanted\n%q", req, got, tc.res)
assert.Empty(cmp.Diff(got, tc.res, protocmp.Transform()), "GetRole(%q) got response\n%q, wanted\n%q", req, got, tc.res)
})
}
}
@@ -249,7 +249,7 @@ func TestList(t *testing.T) {
got, gErr := s.ListRoles(auth.DisabledAuthTestContext(auth.WithScopeId(tc.scopeId)), tc.req)
assert.Equal(tc.errCode, status.Code(gErr), "ListRoles(%+v) got error %v, wanted %v", tc.req, gErr, tc.errCode)
assert.True(proto.Equal(got, tc.res), "ListRoles(%q) got response %q, wanted %q", tc.req, got, tc.res)
assert.Empty(cmp.Diff(got, tc.res, protocmp.Transform()), "ListRoles(%q) got response %q, wanted %q", tc.req, got, tc.res)
})
}
}
@@ -472,7 +472,7 @@ func TestCreate(t *testing.T) {
got, gErr := s.CreateRole(auth.DisabledAuthTestContext(auth.WithScopeId(tc.scopeId)), req)
assert.Equal(tc.errCode, status.Code(gErr), "CreateRole(%+v) got error %v, wanted %v", req, gErr, tc.errCode)
if got != nil {
assert.True(strings.HasPrefix(got.GetUri(), tc.res.Uri), "Expected %q to have the prefix %q", got.GetUri(), tc.res.GetUri())
assert.Contains(got.GetUri(), tc.res.Uri)
assert.True(strings.HasPrefix(got.GetItem().GetId(), iam.RolePrefix+"_"), "Expected %q to have the prefix %q", got.GetItem().GetId(), iam.RolePrefix+"_")
gotCreateTime, err := ptypes.Timestamp(got.GetItem().GetCreatedTime())
require.NoError(err, "Error converting proto to timestamp.")
@@ -487,7 +487,7 @@ func TestCreate(t *testing.T) {
got.Item.Id, tc.res.Item.Id = "", ""
got.Item.CreatedTime, got.Item.UpdatedTime, tc.res.Item.CreatedTime, tc.res.Item.UpdatedTime = nil, nil, nil, nil
}
assert.True(proto.Equal(got, tc.res), "CreateRole(%q) got response\n%q, wanted\n%q", req, got, tc.res)
assert.Empty(cmp.Diff(got, tc.res, protocmp.Transform()), "CreateRole(%q) got response\n%q, wanted\n%q", req, got, tc.res)
})
}
}
@@ -7,6 +7,7 @@ import (
"github.com/golang/protobuf/ptypes"
"github.com/golang/protobuf/ptypes/wrappers"
"github.com/google/go-cmp/cmp"
"github.com/hashicorp/watchtower/internal/auth"
"github.com/hashicorp/watchtower/internal/db"
pb "github.com/hashicorp/watchtower/internal/gen/controller/api/resources/scopes"
@@ -18,6 +19,7 @@ import (
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/testing/protocmp"
"google.golang.org/protobuf/types/known/wrapperspb"
"github.com/stretchr/testify/assert"
@@ -137,8 +139,8 @@ func TestGet(t *testing.T) {
require.NoError(err, "Couldn't create new project service.")
got, gErr := s.GetScope(auth.DisabledAuthTestContext(auth.WithScopeId(tc.scopeId)), req)
assert.Equal(tc.errCode, status.Code(gErr), "GetProject(%+v) got error\n%v, wanted\n%v", req, gErr, tc.errCode)
assert.True(proto.Equal(got, tc.res), "GetProject(%q) got response\n%q, wanted\n%q", req, got, tc.res)
assert.Equal(tc.errCode, status.Code(gErr), "GetScope(%+v) got error\n%v, wanted\n%v", req, gErr, tc.errCode)
assert.Empty(cmp.Diff(got, tc.res, protocmp.Transform()), "GetScope(%q) got response\n%q, wanted\n%q", req, got, tc.res)
})
}
}
@@ -199,7 +201,7 @@ func TestList(t *testing.T) {
got, gErr := s.ListScopes(auth.DisabledAuthTestContext(auth.WithScopeId(tc.scopeId)), tc.req)
assert.Equal(tc.errCode, status.Code(gErr), "ListScopes(%+v) got error\n%v, wanted\n%v", tc.req, gErr, tc.errCode)
assert.True(proto.Equal(got, tc.res), "ListScopes(%q) got response\n%q\nwanted\n%q", tc.req, got, tc.res)
assert.Empty(cmp.Diff(got, tc.res, protocmp.Transform()), "ListScopes(%q) got response\n%q\nwanted\n%q", tc.req, got, tc.res)
})
}
@@ -264,7 +266,7 @@ func TestList(t *testing.T) {
got, gErr := s.ListScopes(auth.DisabledAuthTestContext(auth.WithScopeId(tc.scopeId)), tc.req)
assert.Equal(tc.errCode, status.Code(gErr), "ListScopes(%+v) got error\n%v, wanted\n%v", tc.req, gErr, tc.errCode)
assert.True(proto.Equal(got, tc.res), "ListScopes(%q) got response\n%q, wanted\n%q", tc.req, got, tc.res)
assert.Empty(cmp.Diff(got, tc.res, protocmp.Transform()), "ListScopes(%q) got response\n%q, wanted\n%q", tc.req, got, tc.res)
})
}
}
@@ -350,8 +352,8 @@ func TestDelete(t *testing.T) {
t.Run(tc.name, func(t *testing.T) {
assert := assert.New(t)
got, gErr := s.DeleteScope(auth.DisabledAuthTestContext(auth.WithScopeId(tc.scopeId)), tc.req)
assert.Equal(tc.errCode, status.Code(gErr), "DeleteProject(%+v) got error %v, wanted %v", tc.req, gErr, tc.errCode)
assert.EqualValuesf(tc.res, got, "DeleteProject(%q) got response %q, wanted %q", tc.req, got, tc.res)
assert.Equal(tc.errCode, status.Code(gErr), "DeleteScope(%+v) got error %v, wanted %v", tc.req, gErr, tc.errCode)
assert.EqualValuesf(tc.res, got, "DeleteScope(%q) got response %q, wanted %q", tc.req, got, tc.res)
})
}
}
@@ -478,9 +480,9 @@ func TestCreate(t *testing.T) {
require.NoError(err, "Error when getting new project service.")
got, gErr := s.CreateScope(auth.DisabledAuthTestContext(auth.WithScopeId(tc.scopeId)), req)
assert.Equal(tc.errCode, status.Code(gErr), "CreateProject(%+v) got error %v, wanted %v", req, gErr, tc.errCode)
assert.Equal(tc.errCode, status.Code(gErr), "CreateScope(%+v) got error %v, wanted %v", req, gErr, tc.errCode)
if got != nil {
assert.True(strings.HasPrefix(got.GetUri(), tc.res.Uri))
assert.Contains(got.GetUri(), tc.res.Uri)
switch tc.scopeId {
case "global":
assert.True(strings.HasPrefix(got.GetItem().GetId(), "o_"))
@@ -500,7 +502,7 @@ func TestCreate(t *testing.T) {
got.Item.Id, tc.res.Item.Id = "", ""
got.Item.CreatedTime, got.Item.UpdatedTime, tc.res.Item.CreatedTime, tc.res.Item.UpdatedTime = nil, nil, nil, nil
}
assert.True(proto.Equal(got, tc.res), "CreateProject(%q) got response %q, wanted %q", req, got, tc.res)
assert.Empty(cmp.Diff(got, tc.res, protocmp.Transform()), "CreateScope(%q) got response %q, wanted %q", req, got, tc.res)
})
}
}
@@ -824,7 +826,7 @@ func TestUpdate(t *testing.T) {
// Clear all values which are hard to compare against.
got.Item.UpdatedTime, tc.res.Item.UpdatedTime = nil, nil
}
assert.True(proto.Equal(got, tc.res), "UpdateScope(%q) got response\n%q, wanted\n%q", req, got, tc.res)
assert.Empty(cmp.Diff(got, tc.res, protocmp.Transform()), "UpdateScope(%q) got response\n%q, wanted\n%q", req, got, tc.res)
})
}
}
@@ -0,0 +1,30 @@
package handlers
import (
"google.golang.org/protobuf/encoding/protojson"
"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/types/known/structpb"
)
func StructToProto(fields *structpb.Struct, p proto.Message) error {
js, err := fields.MarshalJSON()
if err != nil {
return err
}
if err := protojson.Unmarshal(js, p); err != nil {
return err
}
return nil
}
func ProtoToStruct(p proto.Message) (*structpb.Struct, error) {
js, err := protojson.Marshal(p)
if err != nil {
return nil, err
}
st := &structpb.Struct{}
if err := protojson.Unmarshal(js, st); err != nil {
return nil, err
}
return st, nil
}
@@ -0,0 +1,49 @@
package handlers
import (
"testing"
structpb "github.com/golang/protobuf/ptypes/struct"
"github.com/google/go-cmp/cmp"
authpb "github.com/hashicorp/watchtower/internal/gen/controller/api/resources/auth"
hostpb "github.com/hashicorp/watchtower/internal/gen/controller/api/resources/hosts"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"google.golang.org/protobuf/encoding/protojson"
"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/testing/protocmp"
"google.golang.org/protobuf/types/known/wrapperspb"
)
func TestStructToProtoToStruct(t *testing.T) {
testCases := []struct {
name string
pb proto.Message
wantJson string
}{
{
name: "password",
pb: &authpb.PasswordAccountAttributes{Username: "testun", Password: &wrapperspb.StringValue{Value: "testpw"}},
wantJson: `{"username": "testun", "password": "testpw"}`,
},
{
name: "ec2hostcatalog",
pb: &hostpb.AwsEc2HostCatalogDetails{Regions: []string{"r1", "r2"}, AccessKey: &wrapperspb.StringValue{Value: "test"}},
wantJson: `{"regions": ["r1", "r2"], "access_key": "test"}`,
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
st, err := ProtoToStruct(tc.pb)
require.NoError(t, err)
wantStruct := &structpb.Struct{}
require.NoError(t, protojson.Unmarshal([]byte(tc.wantJson), wantStruct))
assert.Empty(t, cmp.Diff(wantStruct, st, protocmp.Transform()))
newPwAttr := tc.pb.ProtoReflect().New().Interface()
StructToProto(st, newPwAttr)
assert.Equal(t, tc.pb, newPwAttr)
})
}
}
@@ -7,6 +7,7 @@ import (
"testing"
"github.com/golang/protobuf/ptypes"
"github.com/google/go-cmp/cmp"
"github.com/hashicorp/watchtower/internal/auth"
"github.com/hashicorp/watchtower/internal/db"
"github.com/hashicorp/watchtower/internal/gen/controller/api/resources/scopes"
@@ -19,6 +20,7 @@ import (
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/testing/protocmp"
"google.golang.org/protobuf/types/known/wrapperspb"
"github.com/stretchr/testify/assert"
@@ -97,7 +99,7 @@ func TestGet(t *testing.T) {
got, gErr := s.GetUser(auth.DisabledAuthTestContext(auth.WithScopeId(u.GetScopeId())), req)
assert.Equal(tc.errCode, status.Code(gErr), "GetUser(%+v) got error %v, wanted %v", req, gErr, tc.errCode)
assert.True(proto.Equal(got, tc.res), "GetUser(%q) got response %q, wanted %q", req, got, tc.res)
assert.Empty(cmp.Diff(got, tc.res, protocmp.Transform()), "GetUser(%q) got response %q, wanted %q", req, got, tc.res)
})
}
}
@@ -159,7 +161,7 @@ func TestList(t *testing.T) {
got, gErr := s.ListUsers(auth.DisabledAuthTestContext(auth.WithScopeId(tc.scopeId)), tc.req)
assert.Equal(tc.errCode, status.Code(gErr), "ListUsers(%+v) got error %v, wanted %v", tc.req, gErr, tc.errCode)
assert.True(proto.Equal(got, tc.res), "ListUsers(%q) got response %q, wanted %q", tc.req, got, tc.res)
assert.Empty(cmp.Diff(got, tc.res, protocmp.Transform()), "ListUsers(%q) got response %q, wanted %q", tc.req, got, tc.res)
})
}
}
@@ -301,7 +303,7 @@ func TestCreate(t *testing.T) {
got, gErr := s.CreateUser(auth.DisabledAuthTestContext(auth.WithScopeId(defaultUser.GetScopeId())), req)
assert.Equal(tc.errCode, status.Code(gErr), "CreateUser(%+v) got error %v, wanted %v", req, gErr, tc.errCode)
if got != nil {
assert.True(strings.HasPrefix(got.GetUri(), tc.res.Uri))
assert.Contains(got.GetUri(), tc.res.Uri)
assert.True(strings.HasPrefix(got.GetItem().GetId(), iam.UserPrefix+"_"))
gotCreateTime, err := ptypes.Timestamp(got.GetItem().GetCreatedTime())
require.NoError(err, "Error converting proto to timestamp.")
@@ -316,7 +318,7 @@ func TestCreate(t *testing.T) {
got.Item.Id, tc.res.Item.Id = "", ""
got.Item.CreatedTime, got.Item.UpdatedTime, tc.res.Item.CreatedTime, tc.res.Item.UpdatedTime = nil, nil, nil, nil
}
assert.True(proto.Equal(got, tc.res), "CreateUser(%q) got response %q, wanted %q", req, got, tc.res)
assert.Empty(cmp.Diff(got, tc.res, protocmp.Transform()), "CreateUser(%q) got response %q, wanted %q", req, got, tc.res)
})
}
}
@@ -564,7 +566,7 @@ func TestUpdate(t *testing.T) {
// Clear all values which are hard to compare against.
got.Item.UpdatedTime, tc.res.Item.UpdatedTime = nil, nil
}
assert.True(proto.Equal(got, tc.res), "UpdateUser(%q) got response %q, wanted %q", req, got, tc.res)
assert.Empty(cmp.Diff(got, tc.res, protocmp.Transform()), "UpdateUser(%q) got response %q, wanted %q", req, got, tc.res)
})
}
}