Org List and Get API Methods (#132)
* Create the organization Get handler. * Added org listing. * Make sure the cmp.Diff always sorts the returned organizations before comparing. * Connect organization service to the Controller handler.
This commit is contained in:
1 parent
0ebb38bbe5
commit
0a0d37668d
8 files changed
+1260
-3
No files matched your search
@@ -21,6 +21,7 @@ import (
|
||||
"github.com/hashicorp/watchtower/internal/servers/controller/handlers/host_catalogs"
|
||||
"github.com/hashicorp/watchtower/internal/servers/controller/handlers/host_sets"
|
||||
"github.com/hashicorp/watchtower/internal/servers/controller/handlers/hosts"
|
||||
"github.com/hashicorp/watchtower/internal/servers/controller/handlers/organizations"
|
||||
"github.com/hashicorp/watchtower/internal/servers/controller/handlers/projects"
|
||||
"github.com/hashicorp/watchtower/internal/servers/controller/handlers/users"
|
||||
)
|
||||
@@ -79,6 +80,13 @@ func handleGrpcGateway(c *Controller) (http.Handler, error) {
|
||||
if err := services.RegisterHostServiceHandlerServer(ctx, mux, &hosts.Service{}); err != nil {
|
||||
return nil, fmt.Errorf("failed to register host service handler: %w", err)
|
||||
}
|
||||
os, err := organizations.NewService(c.IamRepoFn)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to create organization handler service: %w", err)
|
||||
}
|
||||
if err := services.RegisterOrganizationServiceHandlerServer(ctx, mux, os); err != nil {
|
||||
return nil, fmt.Errorf("failed to register organization service handler: %w", err)
|
||||
}
|
||||
ps, err := projects.NewService(c.IamRepoFn)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to create project handler service: %w", err)
|
||||
|
||||
@@ -0,0 +1,127 @@
|
||||
package organizations
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
pb "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/common"
|
||||
"github.com/hashicorp/watchtower/internal/servers/controller/handlers"
|
||||
"google.golang.org/protobuf/types/known/wrapperspb"
|
||||
)
|
||||
|
||||
const orgIdFieldName = "org_id"
|
||||
|
||||
var (
|
||||
reInvalidID = regexp.MustCompile("[^A-Za-z0-9]")
|
||||
)
|
||||
|
||||
// Service handles request as described by the pbs.OrganizationServiceServer interface.
|
||||
type Service struct {
|
||||
repo common.IamRepoFactory
|
||||
}
|
||||
|
||||
// NewService returns an organization service which handles organization related requests to watchtower.
|
||||
func NewService(repo common.IamRepoFactory) (Service, error) {
|
||||
if repo == nil {
|
||||
return Service{}, fmt.Errorf("nil iam repository provided")
|
||||
}
|
||||
return Service{repo: repo}, nil
|
||||
}
|
||||
|
||||
var _ pbs.OrganizationServiceServer = Service{}
|
||||
|
||||
// ListOrganizations is not yet implemented but will implement the interface pbs.OrganizationServiceServer.
|
||||
func (s Service) ListOrganizations(ctx context.Context, req *pbs.ListOrganizationsRequest) (*pbs.ListOrganizationsResponse, error) {
|
||||
ol, err := s.listFromRepo(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &pbs.ListOrganizationsResponse{Items: ol}, nil
|
||||
}
|
||||
|
||||
// GetOrganizations implements the interface pbs.OrganizationServiceServer.
|
||||
func (s Service) GetOrganization(ctx context.Context, req *pbs.GetOrganizationRequest) (*pbs.GetOrganizationResponse, error) {
|
||||
if err := validateGetRequest(req); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
o, err := s.getFromRepo(ctx, req.GetId())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &pbs.GetOrganizationResponse{Item: o}, nil
|
||||
}
|
||||
|
||||
func (s Service) getFromRepo(ctx context.Context, id string) (*pb.Organization, error) {
|
||||
repo, err := s.repo()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
p, err := repo.LookupScope(ctx, id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if p == nil {
|
||||
return nil, handlers.NotFoundErrorf("Organization %q doesn't exist.", id)
|
||||
}
|
||||
return toProto(p), nil
|
||||
}
|
||||
|
||||
func (s Service) listFromRepo(ctx context.Context) ([]*pb.Organization, error) {
|
||||
repo, err := s.repo()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ol, err := repo.ListOrganizations(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var outOl []*pb.Organization
|
||||
for _, o := range ol {
|
||||
outOl = append(outOl, toProto(o))
|
||||
}
|
||||
return outOl, nil
|
||||
}
|
||||
|
||||
func toProto(in *iam.Scope) *pb.Organization {
|
||||
out := pb.Organization{
|
||||
Id: in.GetPublicId(),
|
||||
CreatedTime: in.GetCreateTime().GetTimestamp(),
|
||||
UpdatedTime: in.GetUpdateTime().GetTimestamp(),
|
||||
}
|
||||
if in.GetDescription() != "" {
|
||||
out.Description = &wrapperspb.StringValue{Value: in.GetDescription()}
|
||||
}
|
||||
if in.GetName() != "" {
|
||||
out.Name = &wrapperspb.StringValue{Value: in.GetName()}
|
||||
}
|
||||
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.GetOrganizationRequest) error {
|
||||
badFields := make(map[string]string)
|
||||
if !validId(req.GetId(), iam.OrganizationScope.Prefix()+"_") {
|
||||
badFields["id"] = "Invalid formatted organization id."
|
||||
}
|
||||
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,144 @@
|
||||
package organizations_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"github.com/google/go-cmp/cmp"
|
||||
"github.com/hashicorp/watchtower/internal/db"
|
||||
pb "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/organizations"
|
||||
"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"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func createDefaultOrganizationAndRepo(t *testing.T) (*iam.Scope, func() (*iam.Repository, error)) {
|
||||
t.Helper()
|
||||
cleanup, conn, _ := db.TestSetup(t, "postgres")
|
||||
t.Cleanup(func() {
|
||||
if err := conn.Close(); err != nil {
|
||||
t.Errorf("Error when closing gorm DB: %v", err)
|
||||
}
|
||||
if err := cleanup(); err != nil {
|
||||
t.Errorf("Error when cleaning up TestSetup: %v", err)
|
||||
}
|
||||
})
|
||||
rw := db.New(conn)
|
||||
wrap := db.TestWrapper(t)
|
||||
repoFn := func() (*iam.Repository, error) {
|
||||
return iam.NewRepository(rw, rw, wrap)
|
||||
}
|
||||
|
||||
oRes, _ := iam.TestScopes(t, conn)
|
||||
oRes.Name = "default"
|
||||
oRes.Description = "default"
|
||||
repo, err := repoFn()
|
||||
require.NoError(t, err)
|
||||
oRes, _, err = repo.UpdateScope(context.Background(), oRes, []string{"Name", "Description"})
|
||||
require.NoError(t, err)
|
||||
return oRes, repoFn
|
||||
}
|
||||
|
||||
func TestGet(t *testing.T) {
|
||||
assert := assert.New(t)
|
||||
require := require.New(t)
|
||||
org, repo := createDefaultOrganizationAndRepo(t)
|
||||
toMerge := &pbs.GetOrganizationRequest{
|
||||
Id: org.GetPublicId(),
|
||||
}
|
||||
|
||||
pOrganization := &pb.Organization{
|
||||
Id: org.GetPublicId(),
|
||||
Name: &wrapperspb.StringValue{Value: org.GetName()},
|
||||
Description: &wrapperspb.StringValue{Value: org.GetDescription()},
|
||||
CreatedTime: org.CreateTime.GetTimestamp(),
|
||||
UpdatedTime: org.UpdateTime.GetTimestamp(),
|
||||
}
|
||||
|
||||
cases := []struct {
|
||||
name string
|
||||
req *pbs.GetOrganizationRequest
|
||||
res *pbs.GetOrganizationResponse
|
||||
errCode codes.Code
|
||||
}{
|
||||
{
|
||||
name: "Get an Existing organization",
|
||||
req: &pbs.GetOrganizationRequest{Id: org.GetPublicId()},
|
||||
res: &pbs.GetOrganizationResponse{Item: pOrganization},
|
||||
errCode: codes.OK,
|
||||
},
|
||||
{
|
||||
name: "Get a non existing organization",
|
||||
req: &pbs.GetOrganizationRequest{Id: iam.OrganizationScope.Prefix() + "_DoesntExis"},
|
||||
res: nil,
|
||||
errCode: codes.NotFound,
|
||||
},
|
||||
{
|
||||
name: "Wrong id prefix",
|
||||
req: &pbs.GetOrganizationRequest{Id: "j_1234567890"},
|
||||
res: nil,
|
||||
errCode: codes.InvalidArgument,
|
||||
},
|
||||
{
|
||||
name: "space in id",
|
||||
req: &pbs.GetOrganizationRequest{Id: iam.OrganizationScope.Prefix() + "_1 23456789"},
|
||||
res: nil,
|
||||
errCode: codes.InvalidArgument,
|
||||
},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
req := proto.Clone(toMerge).(*pbs.GetOrganizationRequest)
|
||||
proto.Merge(req, tc.req)
|
||||
|
||||
s, err := organizations.NewService(repo)
|
||||
require.NoError(err, "Couldn't create new project service.")
|
||||
|
||||
got, gErr := s.GetOrganization(context.Background(), req)
|
||||
assert.Equal(tc.errCode, status.Code(gErr), "GetOrganization(%+v) got error %v, wanted %v", req, gErr, tc.errCode)
|
||||
assert.True(proto.Equal(got, tc.res), "GetOrganization(%q) got response %q, wanted %q", req, got, tc.res)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestList(t *testing.T) {
|
||||
assert, require := assert.New(t), require.New(t)
|
||||
cleanup, conn, _ := db.TestSetup(t, "postgres")
|
||||
t.Cleanup(func() {
|
||||
if err := conn.Close(); err != nil {
|
||||
t.Errorf("Error when closing gorm DB: %v", err)
|
||||
}
|
||||
if err := cleanup(); err != nil {
|
||||
t.Errorf("Error when cleaning up TestSetup: %v", err)
|
||||
}
|
||||
})
|
||||
rw := db.New(conn)
|
||||
wrap := db.TestWrapper(t)
|
||||
repoFn := func() (*iam.Repository, error) {
|
||||
return iam.NewRepository(rw, rw, wrap)
|
||||
}
|
||||
|
||||
s, err := organizations.NewService(repoFn)
|
||||
require.NoError(err)
|
||||
ctx := context.Background()
|
||||
resp, err := s.ListOrganizations(ctx, &pbs.ListOrganizationsRequest{})
|
||||
assert.NoError(err)
|
||||
assert.Equal(&pbs.ListOrganizationsResponse{}, resp)
|
||||
|
||||
var orgs []*pb.Organization
|
||||
for i := 0; i < 10; i++ {
|
||||
o, _ := iam.TestScopes(t, conn)
|
||||
orgs = append(orgs, &pb.Organization{Id: o.PublicId, CreatedTime: o.GetCreateTime().GetTimestamp(), UpdatedTime: o.GetUpdateTime().GetTimestamp()})
|
||||
}
|
||||
resp, err = s.ListOrganizations(ctx, &pbs.ListOrganizationsRequest{})
|
||||
assert.NoError(err)
|
||||
assert.Empty(cmp.Diff(resp, &pbs.ListOrganizationsResponse{Items: orgs}, protocmp.Transform(), protocmp.SortRepeatedFields(&pbs.ListOrganizationsResponse{}, "items")))
|
||||
}
|
||||
Reference in new issue
Block a user