diff --git a/Makefile b/Makefile index 8fd7edc54..1b7497515 100644 --- a/Makefile +++ b/Makefile @@ -56,6 +56,7 @@ protobuild: @protoc-go-inject-tag -input=./internal/oplog/oplog_test/oplog_test.pb.go @protoc-go-inject-tag -input=./internal/iam/store/user.pb.go @protoc-go-inject-tag -input=./internal/iam/store/scope.pb.go + @protoc-go-inject-tag -input=./internal/iam/store/group.pb.go @protoc-go-inject-tag -input=./internal/db/db_test/db_test.pb.go @protoc-go-inject-tag -input=./internal/host/static/store/static.pb.go @rm -R ${TMP_DIR} diff --git a/internal/db/migrations/postgres.gen.go b/internal/db/migrations/postgres.gen.go index 82ae4ed57..9702d223d 100644 --- a/internal/db/migrations/postgres.gen.go +++ b/internal/db/migrations/postgres.gen.go @@ -354,18 +354,12 @@ commit; BEGIN; drop table if exists iam_scope CASCADE; -drop trigger if exists iam_scope_insert; -drop function if exists iam_sub_scopes_func; drop table if exists iam_user cascade; +drop table if exists iam_group cascade; + drop function iam_sub_scopes_func cascade; - --- TODO: we cannot "drop function update_time_column cascade" since it will --- affect more that this migration. It would delete any table in any migration --- that depends on it. We need to move this drop function up to the 01 --- migration, so it's at the top level. Need to discuss with mgaffney - -drop trigger if exists update_iam_scope_update_time on iam_scope; -drop trigger if exists update_iam_scope_create_time on iam_scope; +drop function iam_immutable_scope_type_func cascade; +drop function iam_sub_names cascade; COMMIT; `), @@ -545,6 +539,33 @@ insert on iam_user for each row execute procedure default_create_time(); +create table iam_group ( + public_id wt_public_id not null primary key, + create_time wt_timestamp, + update_time wt_timestamp, + name text, + description text, + scope_id wt_public_id not null references iam_scope(public_id) on delete cascade on update cascade, + unique(name, scope_id), + disabled boolean not null default false + ); + +create trigger + update_time_column +before update on iam_group + for each row execute procedure update_time_column(); + +create trigger + immutable_create_time +before +update on iam_group + for each row execute procedure immutable_create_time_func(); + +create trigger + default_create_time_column +before +insert on iam_group + for each row execute procedure default_create_time(); commit; `), diff --git a/internal/db/migrations/postgres/04_iam.down.sql b/internal/db/migrations/postgres/04_iam.down.sql index 7fa01366f..fe28c36c0 100644 --- a/internal/db/migrations/postgres/04_iam.down.sql +++ b/internal/db/migrations/postgres/04_iam.down.sql @@ -1,17 +1,11 @@ BEGIN; drop table if exists iam_scope CASCADE; -drop trigger if exists iam_scope_insert; -drop function if exists iam_sub_scopes_func; drop table if exists iam_user cascade; +drop table if exists iam_group cascade; + drop function iam_sub_scopes_func cascade; - --- TODO: we cannot "drop function update_time_column cascade" since it will --- affect more that this migration. It would delete any table in any migration --- that depends on it. We need to move this drop function up to the 01 --- migration, so it's at the top level. Need to discuss with mgaffney - -drop trigger if exists update_iam_scope_update_time on iam_scope; -drop trigger if exists update_iam_scope_create_time on iam_scope; +drop function iam_immutable_scope_type_func cascade; +drop function iam_sub_names cascade; COMMIT; \ No newline at end of file diff --git a/internal/db/migrations/postgres/04_iam.up.sql b/internal/db/migrations/postgres/04_iam.up.sql index 1112a817a..8629f2dc5 100644 --- a/internal/db/migrations/postgres/04_iam.up.sql +++ b/internal/db/migrations/postgres/04_iam.up.sql @@ -170,4 +170,31 @@ insert on iam_user for each row execute procedure default_create_time(); +create table iam_group ( + public_id wt_public_id not null primary key, + create_time wt_timestamp, + update_time wt_timestamp, + name text, + description text, + scope_id wt_public_id not null references iam_scope(public_id) on delete cascade on update cascade, + unique(name, scope_id), + disabled boolean not null default false + ); + +create trigger + update_time_column +before update on iam_group + for each row execute procedure update_time_column(); + +create trigger + immutable_create_time +before +update on iam_group + for each row execute procedure immutable_create_time_func(); + +create trigger + default_create_time_column +before +insert on iam_group + for each row execute procedure default_create_time(); commit; diff --git a/internal/iam/group.go b/internal/iam/group.go new file mode 100644 index 000000000..e3f071aa8 --- /dev/null +++ b/internal/iam/group.go @@ -0,0 +1,96 @@ +package iam + +import ( + "context" + "fmt" + + "github.com/hashicorp/watchtower/internal/db" + "github.com/hashicorp/watchtower/internal/iam/store" + "google.golang.org/protobuf/proto" +) + +// Group is made up of principals which are scoped to an organization. +type Group struct { + *store.Group + tableName string `gorm:"-"` +} + +// ensure that Group implements the interfaces of: Resource, Clonable, and db.VetForWriter. +var _ Resource = (*Group)(nil) +var _ Clonable = (*Group)(nil) +var _ db.VetForWriter = (*Group)(nil) + +// NewGroup creates a new in memory group with a scope (project/organization) +// and allowed options include: withDescripion, WithName. +func NewGroup(scopeId string, opt ...Option) (*Group, error) { + if scopeId == "" { + return nil, fmt.Errorf("new group: missing scope id %w", db.ErrInvalidParameter) + } + opts := getOpts(opt...) + g := &Group{ + Group: &store.Group{ + Name: opts.withName, + Description: opts.withDescription, + ScopeId: scopeId, + }, + } + return g, nil +} + +// Clone creates a clone of the Group. +func (g *Group) Clone() interface{} { + cp := proto.Clone(g.Group) + return &Group{ + Group: cp.(*store.Group), + } +} + +func allocGroup() Group { + return Group{ + Group: &store.Group{}, + } +} + +// VetForWrite implements db.VetForWrite() interface and validates the group +// before it's written. +func (g *Group) VetForWrite(ctx context.Context, r db.Reader, opType db.OpType, opt ...db.Option) error { + if g.PublicId == "" { + return fmt.Errorf("group vet for write: missing public id: %w", db.ErrInvalidParameter) + } + if err := validateScopeForWrite(ctx, r, g, opType, opt...); err != nil { + return err + } + return nil +} + +func (u *Group) validScopeTypes() []ScopeType { + return []ScopeType{OrganizationScope, ProjectScope} +} + +// GetScope returns the scope for the Group. +func (g *Group) GetScope(ctx context.Context, r db.Reader) (*Scope, error) { + return LookupScope(ctx, r, g) +} + +// ResourceType returns the type of the Group. +func (*Group) ResourceType() ResourceType { return ResourceTypeGroup } + +// Actions returns the available actions for Group +func (*Group) Actions() map[string]Action { + return CrudActions() +} + +// TableName returns the tablename to override the default gorm table name. +func (g *Group) TableName() string { + if g.tableName != "" { + return g.tableName + } + return "iam_group" +} + +// SetTableName sets the tablename and satisfies the ReplayableMessage interface. +func (g *Group) SetTableName(n string) { + if n != "" { + g.tableName = n + } +} diff --git a/internal/iam/group_test.go b/internal/iam/group_test.go new file mode 100644 index 000000000..63b59b7bc --- /dev/null +++ b/internal/iam/group_test.go @@ -0,0 +1,520 @@ +package iam + +import ( + "context" + "errors" + "testing" + "time" + + "github.com/hashicorp/watchtower/internal/db" + dbassert "github.com/hashicorp/watchtower/internal/db/assert" + "github.com/hashicorp/watchtower/internal/oplog" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "google.golang.org/protobuf/proto" +) + +func TestNewGroup(t *testing.T) { + t.Parallel() + cleanup, conn, _ := db.TestSetup(t, "postgres") + defer func() { + err := cleanup() + assert.NoError(t, err) + err = conn.Close() + assert.NoError(t, err) + }() + org, proj := TestScopes(t, conn) + id := testId(t) + + type args struct { + scopePublicId string + opt []Option + } + tests := []struct { + name string + args args + wantErr bool + wantErrMsg string + wantIsErr error + wantName string + wantDescription string + }{ + { + name: "valid", + args: args{ + scopePublicId: org.PublicId, + opt: []Option{WithName(id), WithDescription("description-" + id)}, + }, + wantErr: false, + wantName: id, + wantDescription: "description-" + id, + }, + { + name: "valid-proj", + args: args{ + scopePublicId: proj.PublicId, + opt: []Option{WithName(id), WithDescription("description-" + id)}, + }, + wantErr: false, + wantName: id, + wantDescription: "description-" + id, + }, + { + name: "valid-with-no-options" + id, + args: args{ + scopePublicId: org.PublicId, + }, + wantErr: false, + }, + { + name: "no-scope", + args: args{ + opt: []Option{WithName(id)}, + }, + wantErr: true, + wantErrMsg: "new group: missing scope id invalid parameter", + wantIsErr: db.ErrInvalidParameter, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + assert, require := assert.New(t), require.New(t) + got, err := NewGroup(tt.args.scopePublicId, tt.args.opt...) + if tt.wantErr { + require.Error(err) + assert.Equal(tt.wantErrMsg, err.Error()) + if tt.wantIsErr != nil { + assert.True(errors.Is(err, tt.wantIsErr)) + } + return + } + require.NoError(err) + assert.Equal(tt.wantName, got.Name) + assert.Equal(tt.wantDescription, got.Description) + assert.Empty(got.PublicId) + }) + } +} + +func Test_GroupCreate(t *testing.T) { + t.Parallel() + cleanup, conn, _ := db.TestSetup(t, "postgres") + defer func() { + err := cleanup() + assert.NoError(t, err) + err = conn.Close() + assert.NoError(t, err) + }() + org, proj := TestScopes(t, conn) + type args struct { + group *Group + } + tests := []struct { + name string + args args + wantDup bool + wantErr bool + wantErrMsg string + wantIsError error + }{ + { + name: "valid-with-org", + args: args{ + group: func() *Group { + id := testId(t) + grp, err := NewGroup(org.PublicId, WithName(id), WithDescription("description-"+id)) + require.NoError(t, err) + grpId, err := newGroupId() + require.NoError(t, err) + grp.PublicId = grpId + return grp + }(), + }, + wantErr: false, + }, + { + name: "valid-with-proj", + args: args{ + group: func() *Group { + id := testId(t) + grp, err := NewGroup(proj.PublicId, WithName(id), WithDescription("description-"+id)) + require.NoError(t, err) + grpId, err := newGroupId() + require.NoError(t, err) + grp.PublicId = grpId + return grp + }(), + }, + wantErr: false, + }, + { + name: "valid-with-dup-null-names-and-descriptions", + args: args{ + group: func() *Group { + grp, err := NewGroup(org.PublicId) + require.NoError(t, err) + grpId, err := newGroupId() + require.NoError(t, err) + grp.PublicId = grpId + return grp + }(), + }, + wantDup: true, + wantErr: false, + }, + { + name: "bad-scope-id", + args: args{ + group: func() *Group { + id := testId(t) + grp, err := NewGroup(id) + require.NoError(t, err) + grpId, err := newGroupId() + require.NoError(t, err) + grp.PublicId = grpId + return grp + }(), + }, + wantErr: true, + wantErrMsg: "create: vet for write failed scope is not found", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + assert, require := assert.New(t), require.New(t) + w := db.New(conn) + if tt.wantDup { + g := tt.args.group.Clone().(*Group) + grpId, err := newGroupId() + require.NoError(err) + g.PublicId = grpId + err = w.Create(context.Background(), g) + require.NoError(err) + } + g := tt.args.group.Clone().(*Group) + err := w.Create(context.Background(), g) + if tt.wantErr { + require.Error(err) + assert.Equal(tt.wantErrMsg, err.Error()) + return + } + assert.NoError(err) + assert.NotEmpty(tt.args.group.PublicId) + + foundGrp := allocGroup() + foundGrp.PublicId = tt.args.group.PublicId + err = w.LookupByPublicId(context.Background(), &foundGrp) + require.NoError(err) + assert.Equal(g, &foundGrp) + }) + } +} + +func Test_GroupUpdate(t *testing.T) { + t.Parallel() + cleanup, conn, _ := db.TestSetup(t, "postgres") + defer func() { + err := cleanup() + assert.NoError(t, err) + err = conn.Close() + assert.NoError(t, err) + }() + id := testId(t) + org, proj := TestScopes(t, conn) + rw := db.New(conn) + type args struct { + name string + description string + fieldMaskPaths []string + nullPaths []string + ScopeId string + } + tests := []struct { + name string + args args + wantRowsUpdate int + wantErr bool + wantErrMsg string + wantDup bool + }{ + { + name: "valid", + args: args{ + name: "valid" + id, + fieldMaskPaths: []string{"Name"}, + ScopeId: org.PublicId, + }, + wantErr: false, + wantRowsUpdate: 1, + }, + { + name: "proj-scope-id", + args: args{ + name: "proj-scope-id" + id, + fieldMaskPaths: []string{"ScopeId"}, + ScopeId: proj.PublicId, + }, + wantErr: true, + wantErrMsg: "update: vet for write failed not allowed to change a resource's scope", + }, + { + name: "proj-scope-id-not-in-mask", + args: args{ + name: "proj-scope-id" + id, + fieldMaskPaths: []string{"Name"}, + ScopeId: proj.PublicId, + }, + wantErr: false, + wantRowsUpdate: 1, + }, + { + name: "empty-scope-id", + args: args{ + name: "empty-scope-id" + id, + fieldMaskPaths: []string{"Name"}, + ScopeId: "", + }, + wantErr: false, + wantRowsUpdate: 1, + }, + { + name: "dup-name", + args: args{ + name: "dup-name" + id, + fieldMaskPaths: []string{"Name"}, + ScopeId: org.PublicId, + }, + wantErr: true, + wantDup: true, + wantErrMsg: `update: failed pq: duplicate key value violates unique constraint "iam_group_name_scope_id_key"`, + }, + { + name: "set description null", + args: args{ + name: "set description null" + id, + fieldMaskPaths: []string{"Name"}, + nullPaths: []string{"Description"}, + ScopeId: org.PublicId, + }, + wantErr: false, + wantRowsUpdate: 1, + }, + { + name: "set name null", + args: args{ + description: "set description null" + id, + fieldMaskPaths: []string{"Description"}, + nullPaths: []string{"Name"}, + ScopeId: org.PublicId, + }, + wantDup: true, + wantErr: false, + wantRowsUpdate: 1, + }, + { + name: "set description null", + args: args{ + name: "set name null" + id, + fieldMaskPaths: []string{"Name"}, + nullPaths: []string{"Description"}, + ScopeId: org.PublicId, + }, + wantErr: false, + wantRowsUpdate: 1, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + assert, require := assert.New(t), require.New(t) + if tt.wantDup { + grp := TestGroup(t, conn, org.PublicId) + grp.Name = tt.args.name + _, err := rw.Update(context.Background(), grp, tt.args.fieldMaskPaths, tt.args.nullPaths) + require.NoError(err) + } + + id := testId(t) + grp := TestGroup(t, conn, org.PublicId, WithDescription(id), WithName(id)) + + updateGrp := allocGroup() + updateGrp.PublicId = grp.PublicId + updateGrp.ScopeId = tt.args.ScopeId + updateGrp.Name = tt.args.name + updateGrp.Description = tt.args.description + + updatedRows, err := rw.Update(context.Background(), &updateGrp, tt.args.fieldMaskPaths, tt.args.nullPaths) + if tt.wantErr { + require.Error(err) + assert.Equal(0, updatedRows) + assert.Equal(tt.wantErrMsg, err.Error()) + err = db.TestVerifyOplog(t, rw, grp.PublicId, db.WithOperation(oplog.OpType_OP_TYPE_UPDATE), db.WithCreateNotBefore(10*time.Second)) + require.Error(err) + assert.Equal("record not found", err.Error()) + return + } + require.NoError(err) + assert.Equal(tt.wantRowsUpdate, updatedRows) + assert.NotEqual(grp.UpdateTime, updateGrp.UpdateTime) + foundGrp := allocGroup() + foundGrp.PublicId = grp.GetPublicId() + err = rw.LookupByPublicId(context.Background(), &foundGrp) + require.NoError(err) + assert.True(proto.Equal(updateGrp, foundGrp)) + if len(tt.args.nullPaths) != 0 { + dbassert := dbassert.New(t, rw) + for _, f := range tt.args.nullPaths { + dbassert.IsNull(&foundGrp, f) + } + } + }) + } + t.Run("update dup names in diff scopes", func(t *testing.T) { + assert, require := assert.New(t), require.New(t) + id := testId(t) + _ = TestGroup(t, conn, org.PublicId, WithDescription(id), WithName(id)) + projGrp := TestGroup(t, conn, proj.PublicId) + projGrp.Name = id + updatedRows, err := rw.Update(context.Background(), projGrp, []string{"Name"}, nil) + require.NoError(err) + assert.Equal(1, updatedRows) + + foundGrp := allocGroup() + foundGrp.PublicId = projGrp.GetPublicId() + err = rw.LookupByPublicId(context.Background(), &foundGrp) + require.NoError(err) + assert.Equal(id, projGrp.Name) + }) +} + +func Test_GroupDelete(t *testing.T) { + t.Parallel() + cleanup, conn, _ := db.TestSetup(t, "postgres") + defer func() { + err := cleanup() + assert.NoError(t, err) + err = conn.Close() + assert.NoError(t, err) + }() + + rw := db.New(conn) + id := testId(t) + org, _ := TestScopes(t, conn) + + tests := []struct { + name string + group *Group + wantRowsDeleted int + wantErr bool + wantErrMsg string + }{ + { + name: "valid", + group: TestGroup(t, conn, org.PublicId), + wantErr: false, + wantRowsDeleted: 1, + }, + { + name: "bad-id", + group: func() *Group { g := allocGroup(); g.PublicId = id; return &g }(), + wantErr: false, + wantRowsDeleted: 0, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + assert, require := assert.New(t), require.New(t) + deleteGroup := allocGroup() + deleteGroup.PublicId = tt.group.GetPublicId() + deletedRows, err := rw.Delete(context.Background(), &deleteGroup) + if tt.wantErr { + require.Error(err) + return + } + require.NoError(err) + if tt.wantRowsDeleted == 0 { + assert.Equal(tt.wantRowsDeleted, deletedRows) + return + } + assert.Equal(tt.wantRowsDeleted, deletedRows) + foundGrp := allocGroup() + foundGrp.PublicId = tt.group.GetPublicId() + err = rw.LookupByPublicId(context.Background(), &foundGrp) + require.Error(err) + assert.True(errors.Is(db.ErrRecordNotFound, err)) + }) + } +} + +func TestGroup_Actions(t *testing.T) { + assert := assert.New(t) + r := &Group{} + a := r.Actions() + assert.Equal(a[ActionCreate.String()], ActionCreate) + assert.Equal(a[ActionUpdate.String()], ActionUpdate) + assert.Equal(a[ActionRead.String()], ActionRead) + assert.Equal(a[ActionDelete.String()], ActionDelete) +} + +func TestGroup_ResourceType(t *testing.T) { + assert := assert.New(t) + r := &Group{} + ty := r.ResourceType() + assert.Equal(ty, ResourceTypeGroup) +} + +func TestGroup_GetScope(t *testing.T) { + t.Parallel() + cleanup, conn, _ := db.TestSetup(t, "postgres") + defer func() { + err := cleanup() + assert.NoError(t, err) + err = conn.Close() + assert.NoError(t, err) + }() + org, proj := TestScopes(t, conn) + + t.Run("valid-org", func(t *testing.T) { + assert, require := assert.New(t), require.New(t) + w := db.New(conn) + grp := TestGroup(t, conn, org.PublicId) + scope, err := grp.GetScope(context.Background(), w) + require.NoError(err) + assert.True(proto.Equal(org, scope)) + }) + t.Run("valid-proj", func(t *testing.T) { + assert, require := assert.New(t), require.New(t) + w := db.New(conn) + grp := TestGroup(t, conn, proj.PublicId) + scope, err := grp.GetScope(context.Background(), w) + require.NoError(err) + assert.True(proto.Equal(proj, scope)) + }) +} + +func TestGroup_Clone(t *testing.T) { + t.Parallel() + cleanup, conn, _ := db.TestSetup(t, "postgres") + defer func() { + err := cleanup() + assert.NoError(t, err) + err = conn.Close() + assert.NoError(t, err) + }() + org, _ := TestScopes(t, conn) + + t.Run("valid", func(t *testing.T) { + assert := assert.New(t) + grp := TestGroup(t, conn, org.PublicId) + cp := grp.Clone() + assert.True(proto.Equal(cp.(*Group).Group, grp.Group)) + }) + t.Run("not-equal", func(t *testing.T) { + assert := assert.New(t) + grp := TestGroup(t, conn, org.PublicId) + grp2 := TestGroup(t, conn, org.PublicId) + + cp := grp.Clone() + assert.True(!proto.Equal(cp.(*Group).Group, grp2.Group)) + }) +} diff --git a/internal/iam/public_ids.go b/internal/iam/public_ids.go new file mode 100644 index 000000000..95ddfe4da --- /dev/null +++ b/internal/iam/public_ids.go @@ -0,0 +1,28 @@ +package iam + +import ( + "fmt" + + "github.com/hashicorp/watchtower/internal/db" +) + +const ( + UserPrefix = "u" + GroupPrefix = "g" +) + +func newUserId() (string, error) { + id, err := db.NewPublicId(UserPrefix) + if err != nil { + return "", fmt.Errorf("new user id: %w", err) + } + return id, nil +} + +func newGroupId() (string, error) { + id, err := db.NewPublicId(GroupPrefix) + if err != nil { + return "", fmt.Errorf("new group id: %w", err) + } + return id, nil +} diff --git a/internal/iam/public_ids_test.go b/internal/iam/public_ids_test.go new file mode 100644 index 000000000..617dd9b99 --- /dev/null +++ b/internal/iam/public_ids_test.go @@ -0,0 +1,22 @@ +package iam + +import ( + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func Test_PublicIds(t *testing.T) { + t.Run("user", func(t *testing.T) { + id, err := newUserId() + require.NoError(t, err) + assert.True(t, strings.HasPrefix(id, UserPrefix+"_")) + }) + t.Run("group", func(t *testing.T) { + id, err := newGroupId() + require.NoError(t, err) + assert.True(t, strings.HasPrefix(id, GroupPrefix+"_")) + }) +} diff --git a/internal/iam/repository_group.go b/internal/iam/repository_group.go new file mode 100644 index 000000000..8b60d7499 --- /dev/null +++ b/internal/iam/repository_group.go @@ -0,0 +1,116 @@ +package iam + +import ( + "context" + "fmt" + "strings" + + "github.com/hashicorp/watchtower/internal/db" +) + +// CreateGroup will create a group in the repository and return the written +// group. No options are currently supported. +func (r *Repository) CreateGroup(ctx context.Context, group *Group, opt ...Option) (*Group, error) { + if group == nil { + return nil, fmt.Errorf("create group: missing group %w", db.ErrNilParameter) + } + if group.Group == nil { + return nil, fmt.Errorf("create group: missing group store %w", db.ErrNilParameter) + } + if group.PublicId != "" { + return nil, fmt.Errorf("create group: public id not empty: %w", db.ErrInvalidParameter) + } + if group.ScopeId == "" { + return nil, fmt.Errorf("create group: missing group scope id: %w", db.ErrInvalidParameter) + } + id, err := newGroupId() + if err != nil { + return nil, fmt.Errorf("create group: %w", err) + } + g := group.Clone().(*Group) + g.PublicId = id + resource, err := r.create(ctx, g) + if err != nil { + if db.IsUniqueError(err) { + return nil, fmt.Errorf("create group: group %s already exists in scope %s: %w", group.Name, group.ScopeId, db.ErrNotUnique) + } + return nil, fmt.Errorf("create group: %w for %s", err, g.PublicId) + } + return resource.(*Group), err +} + +// UpdateGroup will update a group in the repository and return the written +// group. fieldMaskPaths provides field_mask.proto paths for fields that should +// be updated. Fields will be set to NULL if the field is a zero value and +// included in fieldMask. Name and Description are the only updatable fields, +// If no updatable fields are included in the fieldMaskPaths, then an error is returned. +func (r *Repository) UpdateGroup(ctx context.Context, group *Group, fieldMaskPaths []string, opt ...Option) (*Group, int, error) { + if group == nil { + return nil, db.NoRowsAffected, fmt.Errorf("update group: missing group %w", db.ErrNilParameter) + } + if group.Group == nil { + return nil, db.NoRowsAffected, fmt.Errorf("update group: missing group store %w", db.ErrNilParameter) + } + if group.PublicId == "" { + return nil, db.NoRowsAffected, fmt.Errorf("update group: missing group public id %w", db.ErrInvalidParameter) + } + for _, f := range fieldMaskPaths { + switch { + case strings.EqualFold("name", f): + case strings.EqualFold("description", f): + default: + return nil, db.NoRowsAffected, fmt.Errorf("update group: field: %s: %w", f, db.ErrInvalidFieldMask) + } + } + var dbMask, nullFields []string + dbMask, nullFields = buildUpdatePaths( + map[string]interface{}{ + "name": group.Name, + "description": group.Description, + }, + fieldMaskPaths, + ) + if len(dbMask) == 0 && len(nullFields) == 0 { + return nil, db.NoRowsAffected, fmt.Errorf("update group: %w", db.ErrEmptyFieldMask) + } + g := group.Clone().(*Group) + resource, rowsUpdated, err := r.update(ctx, g, dbMask, nullFields) + if err != nil { + if db.IsUniqueError(err) { + return nil, db.NoRowsAffected, fmt.Errorf("update group: group %s already exists in organization %s: %w", group.Name, group.ScopeId, db.ErrNotUnique) + } + return nil, db.NoRowsAffected, fmt.Errorf("update group: %w for %s", err, group.PublicId) + } + return resource.(*Group), rowsUpdated, err +} + +// LookupGroup will look up a group in the repository. If the group is not +// found, it will return nil, nil. +func (r *Repository) LookupGroup(ctx context.Context, withPublicId string, opt ...Option) (*Group, error) { + if withPublicId == "" { + return nil, fmt.Errorf("lookup group: missing public id %w", db.ErrNilParameter) + } + g := allocGroup() + g.PublicId = withPublicId + if err := r.reader.LookupByPublicId(ctx, &g); err != nil { + return nil, fmt.Errorf("lookup group: failed %w for %s", err, withPublicId) + } + return &g, nil +} + +// DeleteGroup will delete a group from the repository. +func (r *Repository) DeleteGroup(ctx context.Context, withPublicId string, opt ...Option) (int, error) { + if withPublicId == "" { + return db.NoRowsAffected, fmt.Errorf("delete group: missing public id %w", db.ErrNilParameter) + } + g := allocGroup() + g.PublicId = withPublicId + if err := r.reader.LookupByPublicId(ctx, &g); err != nil { + return db.NoRowsAffected, fmt.Errorf("delete group: failed %w for %s", err, withPublicId) + } + rowsDeleted, err := r.delete(ctx, &g) + if err != nil { + return db.NoRowsAffected, fmt.Errorf("delete group: failed %w for %s", err, withPublicId) + } + return rowsDeleted, nil +} diff --git a/internal/iam/repository_group_test.go b/internal/iam/repository_group_test.go new file mode 100644 index 000000000..bc77bfd67 --- /dev/null +++ b/internal/iam/repository_group_test.go @@ -0,0 +1,542 @@ +package iam + +import ( + "context" + "errors" + "testing" + "time" + + "github.com/hashicorp/go-uuid" + "github.com/hashicorp/watchtower/internal/db" + dbassert "github.com/hashicorp/watchtower/internal/db/assert" + "github.com/hashicorp/watchtower/internal/oplog" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "google.golang.org/protobuf/proto" +) + +func TestRepository_CreateGroup(t *testing.T) { + t.Parallel() + cleanup, conn, _ := db.TestSetup(t, "postgres") + defer func() { + err := cleanup() + assert.NoError(t, err) + err = conn.Close() + assert.NoError(t, err) + }() + rw := db.New(conn) + wrapper := db.TestWrapper(t) + repo, err := NewRepository(rw, rw, wrapper) + require.NoError(t, err) + id := testId(t) + + org, proj := TestScopes(t, conn) + + type args struct { + group *Group + opt []Option + } + tests := []struct { + name string + args args + wantDup bool + wantErr bool + wantErrMsg string + wantIsError error + }{ + { + name: "valid-org", + args: args{ + group: func() *Group { + g, err := NewGroup(org.PublicId, WithName("valid-org"+id), WithDescription(id)) + assert.NoError(t, err) + return g + }(), + }, + wantErr: false, + }, + { + name: "valid-proj", + args: args{ + group: func() *Group { + g, err := NewGroup(proj.PublicId, WithName("valid-proj"+id), WithDescription(id)) + assert.NoError(t, err) + return g + }(), + }, + wantErr: false, + }, + { + name: "bad-public-id", + args: args{ + group: func() *Group { + g, err := NewGroup(proj.PublicId, WithName("valid-proj"+id), WithDescription(id)) + assert.NoError(t, err) + g.PublicId = id + return g + }(), + }, + wantErrMsg: "create group: public id not empty: invalid parameter", + wantIsError: db.ErrInvalidParameter, + wantErr: true, + }, + { + name: "nil-group", + args: args{ + group: nil, + }, + wantErr: true, + wantErrMsg: "create group: missing group nil parameter", + wantIsError: db.ErrNilParameter, + }, + { + name: "nil-store", + args: args{ + group: func() *Group { + return &Group{ + Group: nil, + } + }(), + }, + wantErr: true, + wantErrMsg: "create group: missing group store nil parameter", + wantIsError: db.ErrNilParameter, + }, + { + name: "bad-scope-id", + args: args{ + group: func() *Group { + g, err := NewGroup(id) + assert.NoError(t, err) + return g + }(), + }, + wantErr: true, + wantErrMsg: "create group: error getting metadata for create: unable to get scope for standard metadata: record not found for", + wantIsError: db.ErrInvalidParameter, + }, + { + name: "dup-name", + args: args{ + group: func() *Group { + g, err := NewGroup(org.PublicId, WithName("dup-name"+id), WithDescription(id)) + assert.NoError(t, err) + return g + }(), + opt: []Option{WithName("dup-name" + id)}, + }, + wantDup: true, + wantErr: true, + wantErrMsg: "already exists in scope ", + wantIsError: db.ErrNotUnique, + }, + { + name: "dup-name-but-diff-scope", + args: args{ + group: func() *Group { + g, err := NewGroup(proj.PublicId, WithName("dup-name-but-diff-scope"+id), WithDescription(id)) + assert.NoError(t, err) + return g + }(), + opt: []Option{WithName("dup-name-but-diff-scope" + id)}, + }, + wantDup: true, + wantErr: false, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + assert := assert.New(t) + + if tt.wantDup { + dup, err := NewGroup(org.PublicId, tt.args.opt...) + assert.NoError(err) + dup, err = repo.CreateGroup(context.Background(), dup, tt.args.opt...) + assert.NoError(err) + assert.NotNil(dup) + } + grp, err := repo.CreateGroup(context.Background(), tt.args.group, tt.args.opt...) + if tt.wantErr { + assert.Error(err) + assert.Nil(grp) + assert.Contains(err.Error(), tt.wantErrMsg) + return + } + assert.NoError(err) + assert.NotNil(grp.CreateTime) + assert.NotNil(grp.UpdateTime) + + foundGrp, err := repo.LookupGroup(context.Background(), grp.PublicId) + assert.NoError(err) + assert.True(proto.Equal(foundGrp, grp)) + + err = db.TestVerifyOplog(t, rw, grp.PublicId, db.WithOperation(oplog.OpType_OP_TYPE_CREATE), db.WithCreateNotBefore(10*time.Second)) + assert.NoError(err) + }) + } +} + +func TestRepository_UpdateGroup(t *testing.T) { + t.Parallel() + cleanup, conn, _ := db.TestSetup(t, "postgres") + defer func() { + err := cleanup() + assert.NoError(t, err) + err = conn.Close() + assert.NoError(t, err) + }() + a := assert.New(t) + rw := db.New(conn) + wrapper := db.TestWrapper(t) + repo, err := NewRepository(rw, rw, wrapper) + a.NoError(err) + id, err := uuid.GenerateUUID() + a.NoError(err) + + org, proj := TestScopes(t, conn) + pubId := func(s string) *string { return &s } + + type args struct { + name string + description string + fieldMaskPaths []string + opt []Option + ScopeId string + PublicId *string + } + tests := []struct { + name string + newScopeId string + newGrpOpts []Option + args args + wantRowsUpdate int + wantErr bool + wantErrMsg string + wantIsError error + wantDup bool + }{ + { + name: "valid", + args: args{ + name: "valid" + id, + fieldMaskPaths: []string{"Name"}, + ScopeId: org.PublicId, + }, + newScopeId: org.PublicId, + wantErr: false, + wantRowsUpdate: 1, + }, + { + name: "valid-no-op", + args: args{ + name: "valid-no-op" + id, + fieldMaskPaths: []string{"Name"}, + ScopeId: org.PublicId, + }, + newScopeId: org.PublicId, + newGrpOpts: []Option{WithName("valid-no-op" + id)}, + wantErr: false, + wantRowsUpdate: 1, + }, + { + name: "not-found", + args: args{ + name: "not-found" + id, + fieldMaskPaths: []string{"Name"}, + ScopeId: org.PublicId, + PublicId: func() *string { s := "1"; return &s }(), + }, + newScopeId: org.PublicId, + wantErr: true, + wantRowsUpdate: 0, + wantErrMsg: "update group: update: lookup error lookup after write: failed record not found for 1", + wantIsError: db.ErrRecordNotFound, + }, + { + name: "null-name", + args: args{ + name: "", + fieldMaskPaths: []string{"Name"}, + ScopeId: org.PublicId, + }, + newScopeId: org.PublicId, + newGrpOpts: []Option{WithName("null-name" + id)}, + wantErr: false, + wantRowsUpdate: 1, + }, + { + name: "null-description", + args: args{ + name: "", + fieldMaskPaths: []string{"Description"}, + ScopeId: org.PublicId, + }, + newScopeId: org.PublicId, + newGrpOpts: []Option{WithDescription("null-description" + id)}, + wantErr: false, + wantRowsUpdate: 1, + }, + { + name: "empty-field-mask", + args: args{ + name: "valid" + id, + fieldMaskPaths: []string{}, + ScopeId: org.PublicId, + }, + newScopeId: org.PublicId, + wantErr: true, + wantRowsUpdate: 0, + wantErrMsg: "update group: empty field mask", + wantIsError: db.ErrEmptyFieldMask, + }, + { + name: "nil-fieldmask", + args: args{ + name: "valid" + id, + fieldMaskPaths: nil, + ScopeId: org.PublicId, + }, + newScopeId: org.PublicId, + wantErr: true, + wantRowsUpdate: 0, + wantErrMsg: "update group: empty field mask", + wantIsError: db.ErrEmptyFieldMask, + }, + { + name: "read-only-fields", + args: args{ + name: "valid" + id, + fieldMaskPaths: []string{"CreateTime"}, + ScopeId: org.PublicId, + }, + newScopeId: org.PublicId, + wantErr: true, + wantRowsUpdate: 0, + wantErrMsg: "update group: field: CreateTime: invalid field mask", + wantIsError: db.ErrInvalidFieldMask, + }, + { + name: "unknown-fields", + args: args{ + name: "valid" + id, + fieldMaskPaths: []string{"Alice"}, + ScopeId: org.PublicId, + }, + newScopeId: org.PublicId, + wantErr: true, + wantRowsUpdate: 0, + wantErrMsg: "update group: field: Alice: invalid field mask", + wantIsError: db.ErrInvalidFieldMask, + }, + { + name: "no-public-id", + args: args{ + name: "valid" + id, + fieldMaskPaths: []string{"Name"}, + ScopeId: org.PublicId, + PublicId: pubId(""), + }, + newScopeId: org.PublicId, + wantErr: true, + wantErrMsg: "update group: missing group public id invalid parameter", + wantIsError: db.ErrInvalidParameter, + wantRowsUpdate: 0, + }, + { + name: "proj-scope-id-no-mask", + args: args{ + name: "proj-scope-id" + id, + ScopeId: proj.PublicId, + }, + newScopeId: org.PublicId, + wantErr: true, + wantErrMsg: "update group: empty field mask", + wantIsError: db.ErrEmptyFieldMask, + }, + { + name: "empty-scope-id-with-name-mask", + args: args{ + name: "empty-scope-id" + id, + fieldMaskPaths: []string{"Name"}, + ScopeId: "", + }, + newScopeId: org.PublicId, + wantErr: false, + wantRowsUpdate: 1, + }, + { + name: "dup-name-in-diff-scope", + args: args{ + name: "dup-name-in-diff-scope" + id, + fieldMaskPaths: []string{"Name"}, + ScopeId: proj.PublicId, + }, + newScopeId: proj.PublicId, + newGrpOpts: []Option{WithName("dup-name-in-diff-scope-pre-update" + id)}, + wantErr: false, + wantRowsUpdate: 1, + wantDup: true, + }, + { + name: "dup-name", + args: args{ + name: "dup-name" + id, + fieldMaskPaths: []string{"Name"}, + ScopeId: org.PublicId, + }, + newScopeId: org.PublicId, + wantErr: true, + wantDup: true, + wantErrMsg: " already exists in organization " + org.PublicId, + wantIsError: db.ErrNotUnique, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + assert := assert.New(t) + if tt.wantDup { + g := TestGroup(t, conn, org.PublicId) + g.Name = tt.args.name + _, _, err := repo.UpdateGroup(context.Background(), g, tt.args.fieldMaskPaths, tt.args.opt...) + assert.NoError(err) + } + + u := TestGroup(t, conn, tt.newScopeId, tt.newGrpOpts...) + + updateGrp := allocGroup() + updateGrp.PublicId = u.PublicId + if tt.args.PublicId != nil { + updateGrp.PublicId = *tt.args.PublicId + } + updateGrp.ScopeId = tt.args.ScopeId + updateGrp.Name = tt.args.name + updateGrp.Description = tt.args.description + + userAfterUpdate, updatedRows, err := repo.UpdateGroup(context.Background(), &updateGrp, tt.args.fieldMaskPaths, tt.args.opt...) + if tt.wantErr { + assert.Error(err) + if tt.wantIsError != nil { + assert.True(errors.Is(err, tt.wantIsError)) + } + assert.Nil(userAfterUpdate) + assert.Equal(0, updatedRows) + assert.Contains(err.Error(), tt.wantErrMsg) + err = db.TestVerifyOplog(t, rw, u.PublicId, db.WithOperation(oplog.OpType_OP_TYPE_UPDATE), db.WithCreateNotBefore(10*time.Second)) + assert.Error(err) + assert.True(errors.Is(db.ErrRecordNotFound, err)) + return + } + assert.NoError(err) + assert.Equal(tt.wantRowsUpdate, updatedRows) + switch tt.name { + case "valid-no-op": + assert.Equal(u.UpdateTime, userAfterUpdate.UpdateTime) + default: + assert.NotEqual(u.UpdateTime, userAfterUpdate.UpdateTime) + } + foundGrp, err := repo.LookupGroup(context.Background(), u.PublicId) + assert.NoError(err) + assert.True(proto.Equal(userAfterUpdate, foundGrp)) + dbassert := dbassert.New(t, rw) + if tt.args.name == "" { + dbassert.IsNull(foundGrp, "name") + } + if tt.args.description == "" { + dbassert.IsNull(foundGrp, "description") + } + + err = db.TestVerifyOplog(t, rw, u.PublicId, db.WithOperation(oplog.OpType_OP_TYPE_UPDATE), db.WithCreateNotBefore(10*time.Second)) + assert.NoError(err) + }) + } +} + +func TestRepository_DeleteGroup(t *testing.T) { + t.Parallel() + cleanup, conn, _ := db.TestSetup(t, "postgres") + defer func() { + err := cleanup() + assert.NoError(t, err) + err = conn.Close() + assert.NoError(t, err) + }() + a := assert.New(t) + rw := db.New(conn) + wrapper := db.TestWrapper(t) + repo, err := NewRepository(rw, rw, wrapper) + a.NoError(err) + org, _ := TestScopes(t, conn) + + type args struct { + group *Group + opt []Option + } + tests := []struct { + name string + args args + wantRowsDeleted int + wantErr bool + wantErrMsg string + }{ + { + name: "valid", + args: args{ + group: TestGroup(t, conn, org.PublicId), + }, + wantRowsDeleted: 1, + wantErr: false, + }, + { + name: "no-public-id", + args: args{ + group: func() *Group { + g := allocGroup() + return &g + }(), + }, + wantRowsDeleted: 0, + wantErr: true, + wantErrMsg: "delete group: missing public id nil parameter", + }, + { + name: "not-found", + args: args{ + group: func() *Group { + id, err := newGroupId() + a.NoError(err) + g, err := NewGroup(org.PublicId) + g.PublicId = id + a.NoError(err) + return g + }(), + }, + wantRowsDeleted: 0, + wantErr: true, + wantErrMsg: "delete group: failed record not found for ", + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + assert := assert.New(t) + deletedRows, err := repo.DeleteGroup(context.Background(), tt.args.group.PublicId, tt.args.opt...) + if tt.wantErr { + assert.Error(err) + assert.Equal(0, deletedRows) + assert.Contains(err.Error(), tt.wantErrMsg) + err = db.TestVerifyOplog(t, rw, tt.args.group.PublicId, db.WithOperation(oplog.OpType_OP_TYPE_DELETE), db.WithCreateNotBefore(10*time.Second)) + assert.Error(err) + assert.True(errors.Is(db.ErrRecordNotFound, err)) + return + } + assert.NoError(err) + assert.Equal(tt.wantRowsDeleted, deletedRows) + foundGroup, err := repo.LookupGroup(context.Background(), tt.args.group.PublicId) + assert.Error(err) + assert.Nil(foundGroup) + assert.True(errors.Is(err, db.ErrRecordNotFound)) + + err = db.TestVerifyOplog(t, rw, tt.args.group.PublicId, db.WithOperation(oplog.OpType_OP_TYPE_DELETE), db.WithCreateNotBefore(10*time.Second)) + assert.NoError(err) + }) + } +} diff --git a/internal/iam/store/group.pb.go b/internal/iam/store/group.pb.go new file mode 100644 index 000000000..496c16ab8 --- /dev/null +++ b/internal/iam/store/group.pb.go @@ -0,0 +1,243 @@ +// Code generated by protoc-gen-go. DO NOT EDIT. +// versions: +// protoc-gen-go v1.24.0 +// protoc v3.12.3 +// source: controller/storage/iam/store/v1/group.proto + +package store + +import ( + proto "github.com/golang/protobuf/proto" + timestamp "github.com/hashicorp/watchtower/internal/db/timestamp" + protoreflect "google.golang.org/protobuf/reflect/protoreflect" + protoimpl "google.golang.org/protobuf/runtime/protoimpl" + reflect "reflect" + sync "sync" +) + +const ( + // Verify that this generated code is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) + // Verify that runtime/protoimpl is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) +) + +// This is a compile-time assertion that a sufficiently up-to-date version +// of the legacy proto package is being used. +const _ = proto.ProtoPackageIsVersion4 + +type Group struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + // public_id is used to access the Group via an API + // @inject_tag: gorm:"primary_key" + PublicId string `protobuf:"bytes,1,opt,name=public_id,json=publicId,proto3" json:"public_id,omitempty" gorm:"primary_key"` + // create_time from the RDBMS + // @inject_tag: `gorm:"default:current_timestamp"` + CreateTime *timestamp.Timestamp `protobuf:"bytes,2,opt,name=create_time,json=createTime,proto3" json:"create_time,omitempty" gorm:"default:current_timestamp"` + // update_time from the RDBMS + // @inject_tag: `gorm:"default:current_timestamp"` + UpdateTime *timestamp.Timestamp `protobuf:"bytes,3,opt,name=update_time,json=updateTime,proto3" json:"update_time,omitempty" gorm:"default:current_timestamp"` + // name is the optional friendly name used to + // access the Group via an API + // @inject_tag: `gorm:"default:null"` + Name string `protobuf:"bytes,4,opt,name=name,proto3" json:"name,omitempty" gorm:"default:null"` + // description of the group + // @inject_tag: `gorm:"default:null"` + Description string `protobuf:"bytes,5,opt,name=description,proto3" json:"description,omitempty" gorm:"default:null"` + // scope id for the group + // @inject_tag: `gorm:"default:null"` + ScopeId string `protobuf:"bytes,6,opt,name=scope_id,json=scopeId,proto3" json:"scope_id,omitempty" gorm:"default:null"` + // disabled is by default false and allows a Group to be marked disabled. + // @inject_tag: `gorm:"default:null"` + Disabled bool `protobuf:"varint,7,opt,name=disabled,proto3" json:"disabled,omitempty" gorm:"default:null"` +} + +func (x *Group) Reset() { + *x = Group{} + if protoimpl.UnsafeEnabled { + mi := &file_controller_storage_iam_store_v1_group_proto_msgTypes[0] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *Group) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*Group) ProtoMessage() {} + +func (x *Group) ProtoReflect() protoreflect.Message { + mi := &file_controller_storage_iam_store_v1_group_proto_msgTypes[0] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use Group.ProtoReflect.Descriptor instead. +func (*Group) Descriptor() ([]byte, []int) { + return file_controller_storage_iam_store_v1_group_proto_rawDescGZIP(), []int{0} +} + +func (x *Group) GetPublicId() string { + if x != nil { + return x.PublicId + } + return "" +} + +func (x *Group) GetCreateTime() *timestamp.Timestamp { + if x != nil { + return x.CreateTime + } + return nil +} + +func (x *Group) GetUpdateTime() *timestamp.Timestamp { + if x != nil { + return x.UpdateTime + } + return nil +} + +func (x *Group) GetName() string { + if x != nil { + return x.Name + } + return "" +} + +func (x *Group) GetDescription() string { + if x != nil { + return x.Description + } + return "" +} + +func (x *Group) GetScopeId() string { + if x != nil { + return x.ScopeId + } + return "" +} + +func (x *Group) GetDisabled() bool { + if x != nil { + return x.Disabled + } + return false +} + +var File_controller_storage_iam_store_v1_group_proto protoreflect.FileDescriptor + +var file_controller_storage_iam_store_v1_group_proto_rawDesc = []byte{ + 0x0a, 0x2b, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x6c, 0x65, 0x72, 0x2f, 0x73, 0x74, 0x6f, + 0x72, 0x61, 0x67, 0x65, 0x2f, 0x69, 0x61, 0x6d, 0x2f, 0x73, 0x74, 0x6f, 0x72, 0x65, 0x2f, 0x76, + 0x31, 0x2f, 0x67, 0x72, 0x6f, 0x75, 0x70, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x1f, 0x63, + 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x6c, 0x65, 0x72, 0x2e, 0x73, 0x74, 0x6f, 0x72, 0x61, 0x67, + 0x65, 0x2e, 0x69, 0x61, 0x6d, 0x2e, 0x73, 0x74, 0x6f, 0x72, 0x65, 0x2e, 0x76, 0x31, 0x1a, 0x2f, + 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x6c, 0x65, 0x72, 0x2f, 0x73, 0x74, 0x6f, 0x72, 0x61, + 0x67, 0x65, 0x2f, 0x74, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x2f, 0x76, 0x31, 0x2f, + 0x74, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, + 0x2b, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x6c, 0x65, 0x72, 0x2f, 0x73, 0x74, 0x6f, 0x72, + 0x61, 0x67, 0x65, 0x2f, 0x69, 0x61, 0x6d, 0x2f, 0x73, 0x74, 0x6f, 0x72, 0x65, 0x2f, 0x76, 0x31, + 0x2f, 0x73, 0x63, 0x6f, 0x70, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0xab, 0x02, 0x0a, + 0x05, 0x47, 0x72, 0x6f, 0x75, 0x70, 0x12, 0x1b, 0x0a, 0x09, 0x70, 0x75, 0x62, 0x6c, 0x69, 0x63, + 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x70, 0x75, 0x62, 0x6c, 0x69, + 0x63, 0x49, 0x64, 0x12, 0x4b, 0x0a, 0x0b, 0x63, 0x72, 0x65, 0x61, 0x74, 0x65, 0x5f, 0x74, 0x69, + 0x6d, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x2a, 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x72, + 0x6f, 0x6c, 0x6c, 0x65, 0x72, 0x2e, 0x73, 0x74, 0x6f, 0x72, 0x61, 0x67, 0x65, 0x2e, 0x74, 0x69, + 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x2e, 0x76, 0x31, 0x2e, 0x54, 0x69, 0x6d, 0x65, 0x73, + 0x74, 0x61, 0x6d, 0x70, 0x52, 0x0a, 0x63, 0x72, 0x65, 0x61, 0x74, 0x65, 0x54, 0x69, 0x6d, 0x65, + 0x12, 0x4b, 0x0a, 0x0b, 0x75, 0x70, 0x64, 0x61, 0x74, 0x65, 0x5f, 0x74, 0x69, 0x6d, 0x65, 0x18, + 0x03, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x2a, 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x6c, + 0x65, 0x72, 0x2e, 0x73, 0x74, 0x6f, 0x72, 0x61, 0x67, 0x65, 0x2e, 0x74, 0x69, 0x6d, 0x65, 0x73, + 0x74, 0x61, 0x6d, 0x70, 0x2e, 0x76, 0x31, 0x2e, 0x54, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, + 0x70, 0x52, 0x0a, 0x75, 0x70, 0x64, 0x61, 0x74, 0x65, 0x54, 0x69, 0x6d, 0x65, 0x12, 0x12, 0x0a, + 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x04, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x6e, 0x61, 0x6d, + 0x65, 0x12, 0x20, 0x0a, 0x0b, 0x64, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, + 0x18, 0x05, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0b, 0x64, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, + 0x69, 0x6f, 0x6e, 0x12, 0x19, 0x0a, 0x08, 0x73, 0x63, 0x6f, 0x70, 0x65, 0x5f, 0x69, 0x64, 0x18, + 0x06, 0x20, 0x01, 0x28, 0x09, 0x52, 0x07, 0x73, 0x63, 0x6f, 0x70, 0x65, 0x49, 0x64, 0x12, 0x1a, + 0x0a, 0x08, 0x64, 0x69, 0x73, 0x61, 0x62, 0x6c, 0x65, 0x64, 0x18, 0x07, 0x20, 0x01, 0x28, 0x08, + 0x52, 0x08, 0x64, 0x69, 0x73, 0x61, 0x62, 0x6c, 0x65, 0x64, 0x42, 0x3a, 0x5a, 0x38, 0x67, 0x69, + 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x68, 0x61, 0x73, 0x68, 0x69, 0x63, 0x6f, + 0x72, 0x70, 0x2f, 0x77, 0x61, 0x74, 0x63, 0x68, 0x74, 0x6f, 0x77, 0x65, 0x72, 0x2f, 0x69, 0x6e, + 0x74, 0x65, 0x72, 0x6e, 0x61, 0x6c, 0x2f, 0x69, 0x61, 0x6d, 0x2f, 0x73, 0x74, 0x6f, 0x72, 0x65, + 0x3b, 0x73, 0x74, 0x6f, 0x72, 0x65, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, +} + +var ( + file_controller_storage_iam_store_v1_group_proto_rawDescOnce sync.Once + file_controller_storage_iam_store_v1_group_proto_rawDescData = file_controller_storage_iam_store_v1_group_proto_rawDesc +) + +func file_controller_storage_iam_store_v1_group_proto_rawDescGZIP() []byte { + file_controller_storage_iam_store_v1_group_proto_rawDescOnce.Do(func() { + file_controller_storage_iam_store_v1_group_proto_rawDescData = protoimpl.X.CompressGZIP(file_controller_storage_iam_store_v1_group_proto_rawDescData) + }) + return file_controller_storage_iam_store_v1_group_proto_rawDescData +} + +var file_controller_storage_iam_store_v1_group_proto_msgTypes = make([]protoimpl.MessageInfo, 1) +var file_controller_storage_iam_store_v1_group_proto_goTypes = []interface{}{ + (*Group)(nil), // 0: controller.storage.iam.store.v1.Group + (*timestamp.Timestamp)(nil), // 1: controller.storage.timestamp.v1.Timestamp +} +var file_controller_storage_iam_store_v1_group_proto_depIdxs = []int32{ + 1, // 0: controller.storage.iam.store.v1.Group.create_time:type_name -> controller.storage.timestamp.v1.Timestamp + 1, // 1: controller.storage.iam.store.v1.Group.update_time:type_name -> controller.storage.timestamp.v1.Timestamp + 2, // [2:2] is the sub-list for method output_type + 2, // [2:2] is the sub-list for method input_type + 2, // [2:2] is the sub-list for extension type_name + 2, // [2:2] is the sub-list for extension extendee + 0, // [0:2] is the sub-list for field type_name +} + +func init() { file_controller_storage_iam_store_v1_group_proto_init() } +func file_controller_storage_iam_store_v1_group_proto_init() { + if File_controller_storage_iam_store_v1_group_proto != nil { + return + } + file_controller_storage_iam_store_v1_scope_proto_init() + if !protoimpl.UnsafeEnabled { + file_controller_storage_iam_store_v1_group_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*Group); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + } + type x struct{} + out := protoimpl.TypeBuilder{ + File: protoimpl.DescBuilder{ + GoPackagePath: reflect.TypeOf(x{}).PkgPath(), + RawDescriptor: file_controller_storage_iam_store_v1_group_proto_rawDesc, + NumEnums: 0, + NumMessages: 1, + NumExtensions: 0, + NumServices: 0, + }, + GoTypes: file_controller_storage_iam_store_v1_group_proto_goTypes, + DependencyIndexes: file_controller_storage_iam_store_v1_group_proto_depIdxs, + MessageInfos: file_controller_storage_iam_store_v1_group_proto_msgTypes, + }.Build() + File_controller_storage_iam_store_v1_group_proto = out.File + file_controller_storage_iam_store_v1_group_proto_rawDesc = nil + file_controller_storage_iam_store_v1_group_proto_goTypes = nil + file_controller_storage_iam_store_v1_group_proto_depIdxs = nil +} diff --git a/internal/iam/testing.go b/internal/iam/testing.go index d322a8b9f..0f39e9722 100644 --- a/internal/iam/testing.go +++ b/internal/iam/testing.go @@ -84,3 +84,20 @@ func TestUser(t *testing.T, conn *gorm.DB, orgId string, opt ...Option) *User { require.NotEmpty(user.PublicId) return user } + +// TestGroup creates a group suitable for testing. +func TestGroup(t *testing.T, conn *gorm.DB, orgId string, opt ...Option) *Group { + t.Helper() + require := require.New(t) + rw := db.New(conn) + + grp, err := NewGroup(orgId, opt...) + require.NoError(err) + id, err := newGroupId() + require.NoError(err) + grp.PublicId = id + err = rw.Create(context.Background(), grp) + require.NoError(err) + require.NotEmpty(grp.PublicId) + return grp +} diff --git a/internal/iam/user.go b/internal/iam/user.go index 07a90bb70..6661a10cb 100644 --- a/internal/iam/user.go +++ b/internal/iam/user.go @@ -95,13 +95,3 @@ func (u *User) SetTableName(n string) { u.tableName = n } } - -const UserPrefix = "u" - -func newUserId() (string, error) { - id, err := db.NewPublicId(UserPrefix) - if err != nil { - return "", fmt.Errorf("new user id: %w", err) - } - return id, nil -} diff --git a/internal/proto/local/controller/storage/iam/store/v1/group.proto b/internal/proto/local/controller/storage/iam/store/v1/group.proto new file mode 100644 index 000000000..861ca8491 --- /dev/null +++ b/internal/proto/local/controller/storage/iam/store/v1/group.proto @@ -0,0 +1,38 @@ +syntax = "proto3"; + +package controller.storage.iam.store.v1; +option go_package = "github.com/hashicorp/watchtower/internal/iam/store;store"; + +import "controller/storage/timestamp/v1/timestamp.proto"; +import "controller/storage/iam/store/v1/scope.proto"; + +message Group { + // public_id is used to access the Group via an API + // @inject_tag: gorm:"primary_key" + string public_id = 1; + + // create_time from the RDBMS + // @inject_tag: `gorm:"default:current_timestamp"` + timestamp.v1.Timestamp create_time = 2; + + // update_time from the RDBMS + // @inject_tag: `gorm:"default:current_timestamp"` + timestamp.v1.Timestamp update_time = 3; + + // name is the optional friendly name used to + // access the Group via an API + // @inject_tag: `gorm:"default:null"` + string name = 4; + + // description of the group + // @inject_tag: `gorm:"default:null"` + string description = 5; + + // scope id for the group + // @inject_tag: `gorm:"default:null"` + string scope_id = 6; + + // disabled is by default false and allows a Group to be marked disabled. + // @inject_tag: `gorm:"default:null"` + bool disabled = 7; +} \ No newline at end of file