Auth Method API Handler for CRUDL (not updating password specific fields)(#239)

This commit is contained in:
Todd Knight authored and GitHub committed 2020-08-06 12:50:20 -07:00
1 parent 7fefd5e2fe
commit b7bf76a9ba
15 files changed
+3676 -21

No files matched your search

+1 -1
View File
@@ -81,7 +81,7 @@ 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)
accts, err := accounts.NewService(c.PasswordAuthRepoFn)
if err != nil {
return nil, fmt.Errorf("failed to create account handler service: %w", err)
}
@@ -7,7 +7,6 @@ import (
"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"
@@ -35,15 +34,14 @@ func init() {
// 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) {
func NewService(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
return Service{repoFn: repo}, nil
}
var _ pbs.AccountServiceServer = Service{}
@@ -139,7 +137,7 @@ func (s Service) getFromRepo(ctx context.Context, id string) (*pb.Account, error
if u == nil {
return nil, handlers.NotFoundErrorf("Account %q doesn't exist.", id)
}
return s.toProto(u), nil
return toProto(u)
}
func (s Service) createInRepo(ctx context.Context, authMethodId string, item *pb.Account) (*pb.Account, error) {
@@ -169,7 +167,7 @@ func (s Service) createInRepo(ctx context.Context, authMethodId string, item *pb
if out == nil {
return nil, status.Error(codes.Internal, "Unable to create user but no error returned from repository.")
}
return s.toProto(out), nil
return toProto(out)
}
func (s Service) deleteFromRepo(ctx context.Context, id string) (bool, error) {
@@ -198,12 +196,16 @@ func (s Service) listFromRepo(ctx context.Context, authMethodId string) ([]*pb.A
}
var outUl []*pb.Account
for _, u := range ul {
outUl = append(outUl, s.toProto(u))
ou, err := toProto(u)
if err != nil {
return nil, err
}
outUl = append(outUl, ou)
}
return outUl, nil
}
func (s Service) toProto(in *password.Account) *pb.Account {
func toProto(in *password.Account) (*pb.Account, error) {
out := pb.Account{
Id: in.GetPublicId(),
CreatedTime: in.GetCreateTime().GetTimestamp(),
@@ -220,9 +222,9 @@ func (s Service) toProto(in *password.Account) *pb.Account {
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 nil, status.Errorf(codes.Internal, "failed building password attribute struct: %v", err)
}
return &out
return &out, nil
}
// A validateX method should exist for each method above. These methods do not make calls to any backing service but enforce
@@ -7,7 +7,6 @@ import (
"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"
@@ -36,7 +35,7 @@ func TestGet(t *testing.T) {
return password.NewRepository(rw, rw, wrap)
}
s, err := accounts.NewService(hclog.L(), repoFn)
s, err := accounts.NewService(repoFn)
require.NoError(t, err, "Couldn't create new auth token service.")
org, _ := iam.TestScopes(t, conn)
@@ -166,7 +165,7 @@ func TestList(t *testing.T) {
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
s, err := accounts.NewService(hclog.L(), repoFn)
s, err := accounts.NewService(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})
@@ -191,7 +190,7 @@ func TestDelete(t *testing.T) {
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)
s, err := accounts.NewService(repoFn)
require.NoError(t, err, "Error when getting new user service.")
cases := []struct {
@@ -269,7 +268,7 @@ func TestDelete_twice(t *testing.T) {
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)
s, err := accounts.NewService(repoFn)
require.NoError(t, err, "Error when getting new user service")
req := &pbs.DeleteAccountRequest{
AuthMethodId: am.GetPublicId(),
@@ -291,7 +290,7 @@ func TestCreate(t *testing.T) {
return password.NewRepository(rw, rw, wrap)
}
s, err := accounts.NewService(hclog.L(), repoFn)
s, err := accounts.NewService(repoFn)
require.NoError(t, err, "Error when getting new account service.")
o, _ := iam.TestScopes(t, conn)
@@ -0,0 +1,370 @@
package authmethods
import (
"context"
"errors"
"fmt"
"regexp"
"strings"
"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.AuthMethod{}, &store.AuthMethod{}); err != nil {
panic(err)
}
}
// Service handles request as described by the pbs.AuthMethodServiceServer interface.
type Service struct {
repoFn func() (*password.Repository, error)
}
// NewService returns a auth method service which handles auth method related requests to watchtower.
func NewService(repo func() (*password.Repository, error)) (Service, error) {
if repo == nil {
return Service{}, fmt.Errorf("nil iam repository provided")
}
return Service{repoFn: repo}, nil
}
var _ pbs.AuthMethodServiceServer = Service{}
// ListAuthMethods implements the interface pbs.AuthMethodServiceServer.
func (s Service) ListAuthMethods(ctx context.Context, req *pbs.ListAuthMethodsRequest) (*pbs.ListAuthMethodsResponse, 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, authResults.Scope.GetId())
if err != nil {
return nil, err
}
for _, item := range ul {
item.Scope = authResults.Scope
}
return &pbs.ListAuthMethodsResponse{Items: ul}, nil
}
// GetAuthMethods implements the interface pbs.AuthMethodServiceServer.
func (s Service) GetAuthMethod(ctx context.Context, req *pbs.GetAuthMethodRequest) (*pbs.GetAuthMethodResponse, 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.GetAuthMethodResponse{Item: u}, nil
}
// CreateAuthMethod implements the interface pbs.AuthMethodServiceServer.
func (s Service) CreateAuthMethod(ctx context.Context, req *pbs.CreateAuthMethodRequest) (*pbs.CreateAuthMethodResponse, 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, authResults.Scope.GetId(), req.GetItem())
if err != nil {
return nil, err
}
u.Scope = authResults.Scope
return &pbs.CreateAuthMethodResponse{Item: u, Uri: fmt.Sprintf("scopes/%s/auth-methods/%s", authResults.Scope.GetId(), u.GetId())}, nil
}
// UpdateAuthMethod implements the interface pbs.AuthMethodServiceServer.
func (s Service) UpdateAuthMethod(ctx context.Context, req *pbs.UpdateAuthMethodRequest) (*pbs.UpdateAuthMethodResponse, error) {
authResults := auth.Verify(ctx)
if !authResults.Valid {
return nil, handlers.ForbiddenError()
}
if err := validateUpdateRequest(req); err != nil {
return nil, err
}
u, err := s.updateInRepo(ctx, authResults.Scope.GetId(), req.GetId(), req.GetUpdateMask().GetPaths(), req.GetItem())
if err != nil {
return nil, err
}
return &pbs.UpdateAuthMethodResponse{Item: u}, nil
}
// DeleteAuthMethod implements the interface pbs.AuthMethodServiceServer.
func (s Service) DeleteAuthMethod(ctx context.Context, req *pbs.DeleteAuthMethodRequest) (*pbs.DeleteAuthMethodResponse, 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.DeleteAuthMethodResponse{Existed: existed}, nil
}
func (s Service) getFromRepo(ctx context.Context, id string) (*pb.AuthMethod, error) {
repo, err := s.repoFn()
if err != nil {
return nil, err
}
u, err := repo.LookupAuthMethod(ctx, id)
if err != nil {
if errors.Is(err, db.ErrRecordNotFound) {
return nil, handlers.NotFoundErrorf("AuthMethod %q doesn't exist.", id)
}
return nil, err
}
if u == nil {
return nil, handlers.NotFoundErrorf("AuthMethod %q doesn't exist.", id)
}
return toProto(u)
}
func (s Service) listFromRepo(ctx context.Context, scopeId string) ([]*pb.AuthMethod, error) {
repo, err := s.repoFn()
if err != nil {
return nil, err
}
ul, err := repo.ListAuthMethods(ctx, scopeId)
if err != nil {
return nil, err
}
var outUl []*pb.AuthMethod
for _, u := range ul {
ou, err := toProto(u)
if err != nil {
return nil, err
}
outUl = append(outUl, ou)
}
return outUl, nil
}
func (s Service) createInRepo(ctx context.Context, scopeId string, item *pb.AuthMethod) (*pb.AuthMethod, error) {
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()))
}
u, err := password.NewAuthMethod(scopeId, opts...)
if err != nil {
return nil, status.Errorf(codes.Internal, "Unable to build auth method for creation: %v.", err)
}
repo, err := s.repoFn()
if err != nil {
return nil, err
}
out, err := repo.CreateAuthMethod(ctx, u)
if err != nil {
return nil, status.Errorf(codes.Internal, "Unable to create auth method: %v.", err)
}
if out == nil {
return nil, status.Error(codes.Internal, "Unable to create auth method but no error returned from repository.")
}
return toProto(out)
}
func (s Service) updateInRepo(ctx context.Context, scopeId, id string, mask []string, item *pb.AuthMethod) (*pb.AuthMethod, error) {
var opts []password.Option
if desc := item.GetDescription(); desc != nil {
opts = append(opts, password.WithDescription(desc.GetValue()))
}
if name := item.GetName(); name != nil {
opts = append(opts, password.WithName(name.GetValue()))
}
u, err := password.NewAuthMethod(scopeId, opts...)
if err != nil {
return nil, status.Errorf(codes.Internal, "Unable to build auth method for update: %v.", err)
}
u.PublicId = id
dbMask := maskManager.Translate(mask)
if len(dbMask) == 0 {
return nil, handlers.InvalidArgumentErrorf("No valid fields included in the update mask.", map[string]string{"update_mask": "No valid paths provided in the update mask."})
}
repo, err := s.repoFn()
if err != nil {
return nil, err
}
out, rowsUpdated, err := repo.UpdateAuthMethod(ctx, u, dbMask)
if err != nil {
return nil, status.Errorf(codes.Internal, "Unable to update auth method: %v.", err)
}
if rowsUpdated == 0 {
return nil, handlers.NotFoundErrorf("AuthMethod %q doesn't exist.", id)
}
return toProto(out)
}
func (s Service) deleteFromRepo(ctx context.Context, id string) (bool, error) {
repo, err := s.repoFn()
if err != nil {
return false, err
}
rows, err := repo.DeleteAuthMethod(ctx, id)
if err != nil {
if errors.Is(err, db.ErrRecordNotFound) {
return false, nil
}
return false, status.Errorf(codes.Internal, "Unable to delete auth method: %v.", err)
}
return rows > 0, nil
}
func toProto(in *password.AuthMethod) (*pb.AuthMethod, error) {
out := pb.AuthMethod{
Id: in.GetPublicId(),
CreatedTime: in.GetCreateTime().GetTimestamp(),
UpdatedTime: in.GetUpdateTime().GetTimestamp(),
Type: "password",
}
if in.GetDescription() != "" {
out.Description = &wrapperspb.StringValue{Value: in.GetDescription()}
}
if in.GetName() != "" {
out.Name = &wrapperspb.StringValue{Value: in.GetName()}
}
st, err := handlers.ProtoToStruct(&pb.PasswordAuthMethodAttributes{
MinUserNameLength: in.GetMinUserNameLength(),
MinPasswordLength: in.GetMinPasswordLength(),
})
if err != nil {
return nil, status.Errorf(codes.Internal, "failed building password attribute struct: %v", err)
}
out.Attributes = st
return &out, nil
}
// 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.GetAuthMethodRequest) error {
badFields := map[string]string{}
if !validId(req.GetId(), password.AuthMethodPrefix+"_") {
badFields["id"] = "Invalid formatted id."
}
if len(badFields) > 0 {
return handlers.InvalidArgumentErrorf("Improperly formatted identifier.", badFields)
}
return nil
}
func validateListRequest(req *pbs.ListAuthMethodsRequest) error {
badFields := map[string]string{}
if len(badFields) > 0 {
return handlers.InvalidArgumentErrorf("Improperly formatted identifier.", badFields)
}
return nil
}
func validateCreateRequest(req *pbs.CreateAuthMethodRequest) error {
badFields := map[string]string{}
item := req.GetItem()
if item.GetId() != "" {
badFields["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.PasswordAuthMethodAttributes{}
if err := handlers.StructToProto(item.GetAttributes(), pwAttrs); err != nil {
badFields["attributes"] = "Attribute fields do not match the expected format."
}
default:
badFields["type"] = "This is a required field and must be \"password\"."
}
if len(badFields) > 0 {
return handlers.InvalidArgumentErrorf("Argument errors found in the request.", badFields)
}
return nil
}
func validateUpdateRequest(req *pbs.UpdateAuthMethodRequest) error {
badFields := map[string]string{}
if !validId(req.GetId(), password.AuthMethodPrefix+"_") {
badFields["id"] = "Improperly formatted identifier."
}
if req.GetUpdateMask() == nil {
badFields["update_mask"] = "UpdateMask not provided but is required to update this resource."
}
item := req.GetItem()
if item == nil {
// It is legitimate for no item to be specified in an update request as it indicates all fields provided in
// the mask will be marked as unset.
return nil
}
if item.GetId() != "" {
badFields["id"] = "This is a read only field and cannot be specified in an update request."
}
if item.GetCreatedTime() != nil {
badFields["created_time"] = "This is a read only field and cannot be specified in an update request."
}
if item.GetUpdatedTime() != nil {
badFields["updated_time"] = "This is a read only field and cannot be specified in an update request."
}
if item.GetType() != "" {
badFields["type"] = "This is a read only field and cannot be specified in an update request."
}
if len(badFields) > 0 {
return handlers.InvalidArgumentErrorf("Errors in provided fields.", badFields)
}
return nil
}
func validateDeleteRequest(req *pbs.DeleteAuthMethodRequest) error {
badFields := map[string]string{}
if !validId(req.GetId(), password.AuthMethodPrefix+"_") {
badFields["id"] = "Incorrectly formatted identifier."
}
if len(badFields) > 0 {
return handlers.InvalidArgumentErrorf("Errors in provided fields.", 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,709 @@
package authmethods_test
import (
"fmt"
"strings"
"testing"
"github.com/golang/protobuf/ptypes"
"github.com/google/go-cmp/cmp"
"github.com/hashicorp/watchtower/internal/auth"
"github.com/hashicorp/watchtower/internal/auth/password"
"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/authmethods"
"github.com/hashicorp/watchtower/internal/types/scope"
"google.golang.org/genproto/protobuf/field_mask"
"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"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
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)
}
o, _ := iam.TestScopes(t, conn)
am := password.TestAuthMethods(t, conn, o.GetPublicId(), 1)[0]
wantU := &pb.AuthMethod{
Id: am.GetPublicId(),
CreatedTime: am.CreateTime.GetTimestamp(),
UpdatedTime: am.UpdateTime.GetTimestamp(),
Type: "password",
Attributes: &structpb.Struct{Fields: map[string]*structpb.Value{
"min_password_length": structpb.NewNumberValue(8),
"min_user_name_length": structpb.NewNumberValue(5),
}},
Scope: &scopes.ScopeInfo{
Id: o.GetPublicId(),
Type: o.GetType(),
},
}
cases := []struct {
name string
scopeId string
req *pbs.GetAuthMethodRequest
res *pbs.GetAuthMethodResponse
errCode codes.Code
}{
{
name: "Get an Existing AuthMethod",
scopeId: o.GetPublicId(),
req: &pbs.GetAuthMethodRequest{Id: am.GetPublicId()},
res: &pbs.GetAuthMethodResponse{Item: wantU},
errCode: codes.OK,
},
{
name: "Get a non existant AuthMethod",
scopeId: o.GetPublicId(),
req: &pbs.GetAuthMethodRequest{Id: password.AuthMethodPrefix + "_DoesntExis"},
res: nil,
errCode: codes.NotFound,
},
{
name: "Wrong id prefix",
scopeId: o.GetPublicId(),
req: &pbs.GetAuthMethodRequest{Id: "j_1234567890"},
res: nil,
errCode: codes.InvalidArgument,
},
{
name: "space in id",
scopeId: o.GetPublicId(),
req: &pbs.GetAuthMethodRequest{Id: password.AuthMethodPrefix + "_1 23456789"},
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)
s, err := authmethods.NewService(repoFn)
require.NoError(err, "Couldn't create new auth_method service.")
got, gErr := s.GetAuthMethod(auth.DisabledAuthTestContext(auth.WithScopeId(tc.scopeId)), tc.req)
assert.Equal(tc.errCode, status.Code(gErr), "GetAuthMethod(%+v) got error %v, wanted %v", tc.req, gErr, tc.errCode)
assert.Empty(cmp.Diff(got, tc.res, protocmp.Transform()), "GetAuthMethod(%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)
}
oNoAuthMethods, _ := iam.TestScopes(t, conn)
oWithAuthMethods, _ := iam.TestScopes(t, conn)
oWithOtherAuthMethods, _ := iam.TestScopes(t, conn)
var wantSomeAuthMethods []*pb.AuthMethod
for _, am := range password.TestAuthMethods(t, conn, oWithAuthMethods.GetPublicId(), 3) {
wantSomeAuthMethods = append(wantSomeAuthMethods, &pb.AuthMethod{
Id: am.GetPublicId(),
CreatedTime: am.GetCreateTime().GetTimestamp(),
UpdatedTime: am.GetUpdateTime().GetTimestamp(),
Scope: &scopes.ScopeInfo{Id: oWithAuthMethods.GetPublicId(), Type: scope.Org.String()},
Type: "password",
Attributes: &structpb.Struct{Fields: map[string]*structpb.Value{
"min_password_length": structpb.NewNumberValue(8),
"min_user_name_length": structpb.NewNumberValue(5),
}},
})
}
var wantOtherAuthMethods []*pb.AuthMethod
for _, aa := range password.TestAuthMethods(t, conn, oWithOtherAuthMethods.GetPublicId(), 3) {
wantOtherAuthMethods = append(wantOtherAuthMethods, &pb.AuthMethod{
Id: aa.GetPublicId(),
CreatedTime: aa.GetCreateTime().GetTimestamp(),
UpdatedTime: aa.GetUpdateTime().GetTimestamp(),
Scope: &scopes.ScopeInfo{Id: oWithOtherAuthMethods.GetPublicId(), Type: scope.Org.String()},
Type: "password",
Attributes: &structpb.Struct{Fields: map[string]*structpb.Value{
"min_password_length": structpb.NewNumberValue(8),
"min_user_name_length": structpb.NewNumberValue(5),
}},
})
}
cases := []struct {
name string
scopeId string
res *pbs.ListAuthMethodsResponse
errCode codes.Code
}{
{
name: "List Some Auth Methods",
scopeId: oWithAuthMethods.GetPublicId(),
res: &pbs.ListAuthMethodsResponse{Items: wantSomeAuthMethods},
errCode: codes.OK,
},
{
name: "List Other Auth Methods",
scopeId: oWithOtherAuthMethods.GetPublicId(),
res: &pbs.ListAuthMethodsResponse{Items: wantOtherAuthMethods},
errCode: codes.OK,
},
{
name: "List No Auth Methods",
scopeId: oNoAuthMethods.GetPublicId(),
res: &pbs.ListAuthMethodsResponse{},
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",
scopeId: password.AuthMethodPrefix + "_DoesntExis",
res: &pbs.ListAuthMethodsResponse{},
errCode: codes.OK,
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
assert, require := assert.New(t), require.New(t)
s, err := authmethods.NewService(repoFn)
require.NoError(err, "Couldn't create new auth_method service.")
got, gErr := s.ListAuthMethods(auth.DisabledAuthTestContext(auth.WithScopeId(tc.scopeId)), &pbs.ListAuthMethodsRequest{})
assert.Equal(tc.errCode, status.Code(gErr), "ListAuthMethods() for scope %q got error %v, wanted %v", tc.scopeId, gErr, tc.errCode)
assert.Empty(cmp.Diff(got, tc.res, protocmp.Transform()), "ListAuthMethods() for scope %q got response %q, wanted %q", tc.scopeId, 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)
am := password.TestAuthMethods(t, conn, o.GetPublicId(), 1)[0]
s, err := authmethods.NewService(repoFn)
require.NoError(t, err, "Error when getting new auth_method service.")
cases := []struct {
name string
req *pbs.DeleteAuthMethodRequest
res *pbs.DeleteAuthMethodResponse
errCode codes.Code
}{
{
name: "Delete an Existing AuthMethod",
req: &pbs.DeleteAuthMethodRequest{
Id: am.GetPublicId(),
},
res: &pbs.DeleteAuthMethodResponse{
Existed: true,
},
errCode: codes.OK,
},
{
name: "Delete bad auth_method id",
req: &pbs.DeleteAuthMethodRequest{
Id: password.AuthMethodPrefix + "_doesntexis",
},
res: &pbs.DeleteAuthMethodResponse{
Existed: false,
},
errCode: codes.OK,
},
{
name: "Bad AuthMethod Id formatting",
req: &pbs.DeleteAuthMethodRequest{
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.DeleteAuthMethod(auth.DisabledAuthTestContext(auth.WithScopeId(o.GetPublicId())), tc.req)
assert.Equal(tc.errCode, status.Code(gErr), "DeleteAuthMethod(%+v) got error %v, wanted %v", tc.req, gErr, tc.errCode)
assert.EqualValuesf(tc.res, got, "DeleteAuthMethod(%q) got response %q, wanted %q", tc.req, got, tc.res)
})
}
}
func TestDelete_twice(t *testing.T) {
assert, require := assert.New(t), require.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]
s, err := authmethods.NewService(repoFn)
require.NoError(err, "Error when getting new auth_method service.")
req := &pbs.DeleteAuthMethodRequest{
Id: am.GetPublicId(),
}
got, gErr := s.DeleteAuthMethod(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.DeleteAuthMethod(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)
}
o, _ := iam.TestScopes(t, conn)
defaultAm := password.TestAuthMethods(t, conn, o.GetPublicId(), 1)[0]
defaultCreated, err := ptypes.Timestamp(defaultAm.GetCreateTime().GetTimestamp())
require.NoError(t, err, "Error converting proto to timestamp.")
cases := []struct {
name string
req *pbs.CreateAuthMethodRequest
res *pbs.CreateAuthMethodResponse
errCode codes.Code
}{
{
name: "Create a valid AuthMethod",
req: &pbs.CreateAuthMethodRequest{Item: &pb.AuthMethod{
Name: &wrapperspb.StringValue{Value: "name"},
Description: &wrapperspb.StringValue{Value: "desc"},
Type: "password",
}},
res: &pbs.CreateAuthMethodResponse{
Uri: fmt.Sprintf("scopes/%s/auth-methods/%s_", o.GetPublicId(), password.AuthMethodPrefix),
Item: &pb.AuthMethod{
Id: defaultAm.GetPublicId(),
CreatedTime: defaultAm.GetCreateTime().GetTimestamp(),
UpdatedTime: defaultAm.GetUpdateTime().GetTimestamp(),
Name: &wrapperspb.StringValue{Value: "name"},
Description: &wrapperspb.StringValue{Value: "desc"},
Scope: &scopes.ScopeInfo{Id: o.GetPublicId(), Type: scope.Org.String()},
Type: "password",
Attributes: &structpb.Struct{Fields: map[string]*structpb.Value{
"min_password_length": structpb.NewNumberValue(8),
"min_user_name_length": structpb.NewNumberValue(5),
}},
},
},
errCode: codes.OK,
},
{
name: "Can't specify Id",
req: &pbs.CreateAuthMethodRequest{Item: &pb.AuthMethod{
Id: password.AuthMethodPrefix + "_notallowed",
Type: "password",
}},
res: nil,
errCode: codes.InvalidArgument,
},
{
name: "Can't specify Created Time",
req: &pbs.CreateAuthMethodRequest{Item: &pb.AuthMethod{
CreatedTime: ptypes.TimestampNow(),
}},
res: nil,
errCode: codes.InvalidArgument,
},
{
name: "Can't specify Update Time",
req: &pbs.CreateAuthMethodRequest{Item: &pb.AuthMethod{
UpdatedTime: ptypes.TimestampNow(),
Type: "password",
}},
res: nil,
errCode: codes.InvalidArgument,
},
{
name: "Can't specify Update Time",
req: &pbs.CreateAuthMethodRequest{Item: &pb.AuthMethod{
UpdatedTime: ptypes.TimestampNow(),
Type: "password",
}},
res: nil,
errCode: codes.InvalidArgument,
},
{
name: "Must specify type",
req: &pbs.CreateAuthMethodRequest{Item: &pb.AuthMethod{
Name: &wrapperspb.StringValue{Value: "must specify type"},
Description: &wrapperspb.StringValue{Value: "must specify type"},
}},
res: nil,
errCode: codes.InvalidArgument,
},
{
name: "Attributes must be valid for type",
req: &pbs.CreateAuthMethodRequest{Item: &pb.AuthMethod{
Name: &wrapperspb.StringValue{Value: "Attributes must be valid for type"},
Description: &wrapperspb.StringValue{Value: "Attributes must be valid for type"},
Type: "password",
Attributes: &structpb.Struct{Fields: map[string]*structpb.Value{
"invalid_field": structpb.NewStringValue("invalid_value"),
"min_user_name_length": structpb.NewNumberValue(5),
}},
}},
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)
s, err := authmethods.NewService(repoFn)
require.NoError(err, "Error when getting new auth_method service.")
got, gErr := s.CreateAuthMethod(auth.DisabledAuthTestContext(auth.WithScopeId(o.GetPublicId())), tc.req)
assert.Equal(tc.errCode, status.Code(gErr), "CreateAuthMethod(%+v) got error %v, wanted %v", tc.req, gErr, tc.errCode)
if tc.res == nil {
require.Nil(got)
}
if got != nil {
assert.Contains(got.GetUri(), tc.res.Uri)
assert.True(strings.HasPrefix(got.GetItem().GetId(), password.AuthMethodPrefix+"_"))
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 auth_method created after the test setup's default auth_method
assert.True(gotCreateTime.After(defaultCreated), "New auth_method should have been created after default auth_method. Was created %v, which is after %v", gotCreateTime, defaultCreated)
assert.True(gotUpdateTime.After(defaultCreated), "New auth_method should have been updated after default auth_method. 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()), "CreateAuthMethod(%q) got response %q, wanted %q", tc.req, got, tc.res)
})
}
}
func TestUpdate(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)
tested, err := authmethods.NewService(repoFn)
require.NoError(t, err, "Error when getting new auth_method service.")
freshAuthMethod := func() (*pb.AuthMethod, func()) {
am, err := tested.CreateAuthMethod(auth.DisabledAuthTestContext(auth.WithScopeId(o.GetPublicId())),
&pbs.CreateAuthMethodRequest{Item: &pb.AuthMethod{
Name: wrapperspb.String("default"),
Description: wrapperspb.String("default"),
Type: "password",
}})
require.NoError(t, err)
clean := func() {
_, err := tested.DeleteAuthMethod(auth.DisabledAuthTestContext(auth.WithScopeId(o.GetPublicId())),
&pbs.DeleteAuthMethodRequest{Id: am.GetItem().GetId()})
require.NoError(t, err)
}
return am.GetItem(), clean
}
cases := []struct {
name string
req *pbs.UpdateAuthMethodRequest
res *pbs.UpdateAuthMethodResponse
errCode codes.Code
}{
{
name: "Update an Existing AuthMethod",
req: &pbs.UpdateAuthMethodRequest{
UpdateMask: &field_mask.FieldMask{
Paths: []string{"name", "description"},
},
Item: &pb.AuthMethod{
Name: &wrapperspb.StringValue{Value: "new"},
Description: &wrapperspb.StringValue{Value: "desc"},
},
},
res: &pbs.UpdateAuthMethodResponse{
Item: &pb.AuthMethod{
Name: &wrapperspb.StringValue{Value: "new"},
Description: &wrapperspb.StringValue{Value: "desc"},
Type: "password",
Attributes: &structpb.Struct{Fields: map[string]*structpb.Value{
"min_password_length": structpb.NewNumberValue(8),
"min_user_name_length": structpb.NewNumberValue(5),
}},
},
},
errCode: codes.OK,
},
{
name: "Multiple Paths in single string",
req: &pbs.UpdateAuthMethodRequest{
UpdateMask: &field_mask.FieldMask{
Paths: []string{"name,description"},
},
Item: &pb.AuthMethod{
Name: &wrapperspb.StringValue{Value: "new"},
Description: &wrapperspb.StringValue{Value: "desc"},
},
},
res: &pbs.UpdateAuthMethodResponse{
Item: &pb.AuthMethod{
Name: &wrapperspb.StringValue{Value: "new"},
Description: &wrapperspb.StringValue{Value: "desc"},
Type: "password",
Attributes: &structpb.Struct{Fields: map[string]*structpb.Value{
"min_password_length": structpb.NewNumberValue(8),
"min_user_name_length": structpb.NewNumberValue(5),
}},
},
},
errCode: codes.OK,
},
{
name: "No Update Mask",
req: &pbs.UpdateAuthMethodRequest{
Item: &pb.AuthMethod{
Name: &wrapperspb.StringValue{Value: "updated name"},
Description: &wrapperspb.StringValue{Value: "updated desc"},
},
},
errCode: codes.InvalidArgument,
},
{
name: "No Paths in Mask",
req: &pbs.UpdateAuthMethodRequest{
UpdateMask: &field_mask.FieldMask{Paths: []string{}},
Item: &pb.AuthMethod{
Name: &wrapperspb.StringValue{Value: "updated name"},
Description: &wrapperspb.StringValue{Value: "updated desc"},
},
},
errCode: codes.InvalidArgument,
},
{
name: "Only non-existant paths in Mask",
req: &pbs.UpdateAuthMethodRequest{
UpdateMask: &field_mask.FieldMask{Paths: []string{"nonexistant_field"}},
Item: &pb.AuthMethod{
Name: &wrapperspb.StringValue{Value: "updated name"},
Description: &wrapperspb.StringValue{Value: "updated desc"},
},
},
errCode: codes.InvalidArgument,
},
{
name: "Unset Name",
req: &pbs.UpdateAuthMethodRequest{
UpdateMask: &field_mask.FieldMask{
Paths: []string{"name"},
},
Item: &pb.AuthMethod{
Description: &wrapperspb.StringValue{Value: "ignored"},
},
},
res: &pbs.UpdateAuthMethodResponse{
Item: &pb.AuthMethod{
Description: &wrapperspb.StringValue{Value: "default"},
Type: "password",
Attributes: &structpb.Struct{Fields: map[string]*structpb.Value{
"min_password_length": structpb.NewNumberValue(8),
"min_user_name_length": structpb.NewNumberValue(5),
}},
},
},
errCode: codes.OK,
},
{
name: "Update Only Name",
req: &pbs.UpdateAuthMethodRequest{
UpdateMask: &field_mask.FieldMask{
Paths: []string{"name"},
},
Item: &pb.AuthMethod{
Name: &wrapperspb.StringValue{Value: "updated"},
Description: &wrapperspb.StringValue{Value: "ignored"},
},
},
res: &pbs.UpdateAuthMethodResponse{
Item: &pb.AuthMethod{
Name: &wrapperspb.StringValue{Value: "updated"},
Description: &wrapperspb.StringValue{Value: "default"},
Type: "password",
Attributes: &structpb.Struct{Fields: map[string]*structpb.Value{
"min_password_length": structpb.NewNumberValue(8),
"min_user_name_length": structpb.NewNumberValue(5),
}},
},
},
errCode: codes.OK,
},
{
name: "Update Only Description",
req: &pbs.UpdateAuthMethodRequest{
UpdateMask: &field_mask.FieldMask{
Paths: []string{"description"},
},
Item: &pb.AuthMethod{
Name: &wrapperspb.StringValue{Value: "ignored"},
Description: &wrapperspb.StringValue{Value: "notignored"},
},
},
res: &pbs.UpdateAuthMethodResponse{
Item: &pb.AuthMethod{
Name: &wrapperspb.StringValue{Value: "default"},
Description: &wrapperspb.StringValue{Value: "notignored"},
Type: "password",
Attributes: &structpb.Struct{Fields: map[string]*structpb.Value{
"min_password_length": structpb.NewNumberValue(8),
"min_user_name_length": structpb.NewNumberValue(5),
}},
},
},
errCode: codes.OK,
},
// TODO: Updating a non existant auth_method should result in a NotFound exception but currently results in
// the repoFn returning an internal error.
{
name: "Update a Non Existing AuthMethod",
req: &pbs.UpdateAuthMethodRequest{
Id: password.AuthMethodPrefix + "_DoesntExis",
UpdateMask: &field_mask.FieldMask{
Paths: []string{"description"},
},
Item: &pb.AuthMethod{
Name: &wrapperspb.StringValue{Value: "new"},
Description: &wrapperspb.StringValue{Value: "desc"},
},
},
errCode: codes.Internal,
},
{
name: "Cant change Id",
req: &pbs.UpdateAuthMethodRequest{
UpdateMask: &field_mask.FieldMask{
Paths: []string{"id"},
},
Item: &pb.AuthMethod{
Id: password.AuthMethodPrefix + "_somethinge",
Name: &wrapperspb.StringValue{Value: "new"},
Description: &wrapperspb.StringValue{Value: "new desc"},
}},
res: nil,
errCode: codes.InvalidArgument,
},
{
name: "Cant specify Created Time",
req: &pbs.UpdateAuthMethodRequest{
UpdateMask: &field_mask.FieldMask{
Paths: []string{"created_time"},
},
Item: &pb.AuthMethod{
CreatedTime: ptypes.TimestampNow(),
},
},
res: nil,
errCode: codes.InvalidArgument,
},
{
name: "Cant specify Updated Time",
req: &pbs.UpdateAuthMethodRequest{
UpdateMask: &field_mask.FieldMask{
Paths: []string{"updated_time"},
},
Item: &pb.AuthMethod{
UpdatedTime: ptypes.TimestampNow(),
},
},
res: nil,
errCode: codes.InvalidArgument,
},
{
name: "Cant specify Type",
req: &pbs.UpdateAuthMethodRequest{
UpdateMask: &field_mask.FieldMask{
Paths: []string{"type"},
},
Item: &pb.AuthMethod{
Type: "oidc",
},
},
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)
am, cleanup := freshAuthMethod()
defer cleanup()
if tc.req.GetId() == "" {
tc.req.Id = am.GetId()
}
if tc.res != nil && tc.res.Item != nil {
tc.res.Item.Id = am.GetId()
tc.res.Item.CreatedTime = am.GetCreatedTime()
}
got, gErr := tested.UpdateAuthMethod(auth.DisabledAuthTestContext(auth.WithScopeId(o.GetPublicId())), tc.req)
assert.Equal(tc.errCode, status.Code(gErr), "UpdateAuthMethod(%+v) got error %v, wanted %v", tc.req, gErr, tc.errCode)
if tc.res == nil {
require.Nil(got)
}
if got != nil {
assert.NotNilf(tc.res, "Expected UpdateAuthMethod response to be nil, but was %v", got)
gotUpdateTime, err := ptypes.Timestamp(got.GetItem().GetUpdatedTime())
require.NoError(err, "Error converting proto to timestamp")
created, err := ptypes.Timestamp(am.GetCreatedTime())
require.NoError(err, "Error converting proto to timestamp")
// Verify it is a auth_method updated after it was created
assert.True(gotUpdateTime.After(created), "Updated auth_method should have been updated after it's creation. Was updated %v, which is after %v", gotUpdateTime, created)
// Clear all values which are hard to compare against.
got.Item.UpdatedTime, tc.res.Item.UpdatedTime = nil, nil
}
assert.Empty(cmp.Diff(got, tc.res, protocmp.Transform()), "UpdateAuthMethod(%q) got response %q, wanted %q", tc.req, got, tc.res)
})
}
}
@@ -18,7 +18,7 @@ func StructToProto(fields *structpb.Struct, p proto.Message) error {
}
func ProtoToStruct(p proto.Message) (*structpb.Struct, error) {
js, err := protojson.Marshal(p)
js, err := protojson.MarshalOptions{UseProtoNames: true}.Marshal(p)
if err != nil {
return nil, err
}