fix: cleanup (#1312)

* fix: remove unused code

* fix: remove unused code

* fix: remove unused code

* fix: remove unused code
This commit is contained in:
Fabi
2021-02-19 14:35:42 +01:00
committed by GitHub
parent 00fec8830a
commit a7cc57822b
63 changed files with 33 additions and 38138 deletions

View File

@@ -1,56 +0,0 @@
package model
import es_models "github.com/caos/zitadel/internal/eventstore/models"
type UserGrant struct {
es_models.ObjectRoot
State UserGrantState
UserID string
ProjectID string
GrantID string
RoleKeys []string
}
type UserGrantState int32
const (
UserGrantStateActive UserGrantState = iota
UserGrantStateInactive
UserGrantStateRemoved
)
func (u *UserGrant) IsValid() bool {
return u.ProjectID != "" && u.UserID != ""
}
func (u *UserGrant) IsActive() bool {
return u.State == UserGrantStateActive
}
func (u *UserGrant) IsInactive() bool {
return u.State == UserGrantStateInactive
}
func (u *UserGrant) RemoveRoleKeyIfExisting(key string) bool {
for i, role := range u.RoleKeys {
if role == key {
u.RoleKeys[i] = u.RoleKeys[len(u.RoleKeys)-1]
u.RoleKeys[len(u.RoleKeys)-1] = ""
u.RoleKeys = u.RoleKeys[:len(u.RoleKeys)-1]
return true
}
}
return false
}
func (u *UserGrant) RemoveRoleKeysIfExisting(keys []string) bool {
exists := false
for _, key := range keys {
keyExists := u.RemoveRoleKeyIfExisting(key)
if keyExists {
exists = true
}
}
return exists
}

View File

@@ -29,6 +29,14 @@ type UserGrantView struct {
Sequence uint64
}
type UserGrantState int32
const (
UserGrantStateActive UserGrantState = iota
UserGrantStateInactive
UserGrantStateRemoved
)
type UserGrantSearchRequest struct {
Offset uint64
Limit uint64

View File

@@ -1,34 +0,0 @@
package eventsourcing
import (
"github.com/caos/logging"
"github.com/caos/zitadel/internal/cache"
"github.com/caos/zitadel/internal/cache/config"
"github.com/caos/zitadel/internal/eventstore/models"
"github.com/caos/zitadel/internal/usergrant/repository/eventsourcing/model"
)
type UserGrantCache struct {
userGrantCache cache.Cache
}
func StartCache(conf *config.CacheConfig) (*UserGrantCache, error) {
userGrantCache, err := conf.Config.NewCache()
logging.Log("EVENT-8EhUZ").OnError(err).Panic("unable to create user grant cache")
return &UserGrantCache{userGrantCache: userGrantCache}, nil
}
func (c *UserGrantCache) getUserGrant(ID string) *model.UserGrant {
user := &model.UserGrant{ObjectRoot: models.ObjectRoot{AggregateID: ID}}
err := c.userGrantCache.Get(ID, user)
logging.Log("EVENT-QAd7T").OnError(err).Debug("error in getting cache")
return user
}
func (c *UserGrantCache) cacheUserGrant(grant *model.UserGrant) {
err := c.userGrantCache.Set(grant.AggregateID, grant)
logging.Log("EVENT-w2KNQ").OnError(err).Debug("error in setting user grant cache")
}

View File

@@ -1,233 +0,0 @@
package eventsourcing
import (
"context"
"github.com/caos/zitadel/internal/cache/config"
caos_errs "github.com/caos/zitadel/internal/errors"
es_int "github.com/caos/zitadel/internal/eventstore"
"github.com/caos/zitadel/internal/eventstore/models"
es_models "github.com/caos/zitadel/internal/eventstore/models"
es_sdk "github.com/caos/zitadel/internal/eventstore/sdk"
"github.com/caos/zitadel/internal/id"
grant_model "github.com/caos/zitadel/internal/usergrant/model"
"github.com/caos/zitadel/internal/usergrant/repository/eventsourcing/model"
)
type UserGrantEventStore struct {
es_int.Eventstore
userGrantCache *UserGrantCache
idGenerator id.Generator
}
type UserGrantConfig struct {
es_int.Eventstore
Cache *config.CacheConfig
}
func StartUserGrant(conf UserGrantConfig) (*UserGrantEventStore, error) {
userGrantCache, err := StartCache(conf.Cache)
if err != nil {
return nil, err
}
return &UserGrantEventStore{
Eventstore: conf.Eventstore,
userGrantCache: userGrantCache,
idGenerator: id.SonyFlakeGenerator,
}, nil
}
func (es *UserGrantEventStore) UserGrantByID(ctx context.Context, id string) (*grant_model.UserGrant, error) {
grant := es.userGrantCache.getUserGrant(id)
query, err := UserGrantByIDQuery(grant.AggregateID, grant.Sequence)
if err != nil {
return nil, err
}
err = es_sdk.Filter(ctx, es.FilterEvents, grant.AppendEvents, query)
if err != nil && caos_errs.IsNotFound(err) && grant.Sequence == 0 {
return nil, err
}
es.userGrantCache.cacheUserGrant(grant)
if grant.State == int32(grant_model.UserGrantStateRemoved) {
return nil, caos_errs.ThrowNotFound(nil, "EVENT-2ks8d", "Errors.UserGrant.NotFound")
}
return model.UserGrantToModel(grant), nil
}
func (es *UserGrantEventStore) AddUserGrant(ctx context.Context, grant *grant_model.UserGrant) (*grant_model.UserGrant, error) {
repoGrant, addAggregates, err := es.PrepareAddUserGrant(ctx, grant)
if err != nil {
return nil, err
}
err = es_sdk.PushAggregates(ctx, es.PushAggregates, repoGrant.AppendEvents, addAggregates...)
if err != nil {
return nil, err
}
return model.UserGrantToModel(repoGrant), nil
}
func (es *UserGrantEventStore) AddUserGrants(ctx context.Context, grants ...*grant_model.UserGrant) error {
aggregates := make([]*es_models.Aggregate, 0)
for _, grant := range grants {
_, addAggregates, err := es.PrepareAddUserGrant(ctx, grant)
if err != nil {
return err
}
for _, agg := range addAggregates {
aggregates = append(aggregates, agg)
}
}
return es_sdk.PushAggregates(ctx, es.PushAggregates, nil, aggregates...)
}
func (es *UserGrantEventStore) PrepareAddUserGrant(ctx context.Context, grant *grant_model.UserGrant) (*model.UserGrant, []*es_models.Aggregate, error) {
if grant == nil || !grant.IsValid() {
return nil, nil, caos_errs.ThrowPreconditionFailed(nil, "EVENT-sdiw3", "Errors.UserGrant.Invalid")
}
id, err := es.idGenerator.Next()
if err != nil {
return nil, nil, err
}
grant.AggregateID = id
repoGrant := model.UserGrantFromModel(grant)
addAggregates, err := UserGrantAddedAggregate(ctx, es.Eventstore.AggregateCreator(), repoGrant)
if err != nil {
return nil, nil, err
}
return repoGrant, addAggregates, nil
}
func (es *UserGrantEventStore) PrepareChangeUserGrant(ctx context.Context, grant *grant_model.UserGrant, cascade bool) (*model.UserGrant, *es_models.Aggregate, error) {
if grant == nil {
return nil, nil, caos_errs.ThrowPreconditionFailed(nil, "EVENT-lo0s9", "Errors.UserGrant.Invalid")
}
existingGrant, err := es.UserGrantByID(ctx, grant.AggregateID)
if err != nil {
return nil, nil, err
}
repoExistingGrant := model.UserGrantFromModel(existingGrant)
repoGrant := model.UserGrantFromModel(grant)
aggFunc := UserGrantChangedAggregate(es.Eventstore.AggregateCreator(), repoExistingGrant, repoGrant, cascade)
projectAggregate, err := aggFunc(ctx)
if err != nil {
return nil, nil, err
}
return repoExistingGrant, projectAggregate, err
}
func (es *UserGrantEventStore) ChangeUserGrant(ctx context.Context, grant *grant_model.UserGrant) (*grant_model.UserGrant, error) {
repoGrant, agg, err := es.PrepareChangeUserGrant(ctx, grant, false)
if err != nil {
return nil, err
}
err = es_sdk.PushAggregates(ctx, es.PushAggregates, repoGrant.AppendEvents, agg)
if err != nil {
return nil, err
}
es.userGrantCache.cacheUserGrant(repoGrant)
return model.UserGrantToModel(repoGrant), nil
}
func (es *UserGrantEventStore) ChangeUserGrants(ctx context.Context, grants ...*grant_model.UserGrant) error {
aggregates := make([]*es_models.Aggregate, len(grants))
for i, grant := range grants {
_, agg, err := es.PrepareChangeUserGrant(ctx, grant, false)
if err != nil {
return err
}
aggregates[i] = agg
}
return es_sdk.PushAggregates(ctx, es.PushAggregates, nil, aggregates...)
}
func (es *UserGrantEventStore) RemoveUserGrant(ctx context.Context, grantID string) error {
grant, projectAggregates, err := es.PrepareRemoveUserGrant(ctx, grantID, false)
if err != nil {
return err
}
err = es_sdk.PushAggregates(ctx, es.PushAggregates, grant.AppendEvents, projectAggregates...)
if err != nil {
return err
}
es.userGrantCache.cacheUserGrant(grant)
return nil
}
func (es *UserGrantEventStore) RemoveUserGrants(ctx context.Context, grantIDs ...string) error {
aggregates := make([]*es_models.Aggregate, 0)
for _, grantID := range grantIDs {
_, aggs, err := es.PrepareRemoveUserGrant(ctx, grantID, false)
if err != nil {
return err
}
for _, agg := range aggs {
aggregates = append(aggregates, agg)
}
}
return es_sdk.PushAggregates(ctx, es.PushAggregates, nil, aggregates...)
}
func (es *UserGrantEventStore) PrepareRemoveUserGrant(ctx context.Context, grantID string, cascade bool) (*model.UserGrant, []*es_models.Aggregate, error) {
grant, err := es.UserGrantByID(ctx, grantID)
if err != nil {
return nil, nil, err
}
repoExisting := model.UserGrantFromModel(grant)
repoGrant := &model.UserGrant{ObjectRoot: models.ObjectRoot{AggregateID: grantID}}
projectAggregates, err := UserGrantRemovedAggregate(ctx, es.Eventstore.AggregateCreator(), repoExisting, repoGrant, cascade)
if err != nil {
return nil, nil, err
}
return repoExisting, projectAggregates, nil
}
func (es *UserGrantEventStore) DeactivateUserGrant(ctx context.Context, grantID string) (*grant_model.UserGrant, error) {
if grantID == "" {
return nil, caos_errs.ThrowPreconditionFailed(nil, "EVENT-8si34", "Errors.UserGrant.IDMissing")
}
grant, err := es.UserGrantByID(ctx, grantID)
if err != nil {
return nil, err
}
if !grant.IsActive() {
return nil, caos_errs.ThrowPreconditionFailed(nil, "EVENT-lo9sw", "Errors.UserGrant.NotActive")
}
repoExistingGrant := model.UserGrantFromModel(grant)
repoGrant := &model.UserGrant{ObjectRoot: models.ObjectRoot{AggregateID: grantID}}
projectAggregate := UserGrantDeactivatedAggregate(es.Eventstore.AggregateCreator(), repoExistingGrant, repoGrant)
err = es_sdk.Push(ctx, es.PushAggregates, repoExistingGrant.AppendEvents, projectAggregate)
if err != nil {
return nil, err
}
es.userGrantCache.cacheUserGrant(repoGrant)
return model.UserGrantToModel(repoExistingGrant), nil
}
func (es *UserGrantEventStore) ReactivateUserGrant(ctx context.Context, grantID string) (*grant_model.UserGrant, error) {
if grantID == "" {
return nil, caos_errs.ThrowPreconditionFailed(nil, "EVENT-sksiw", "Errors.UserGrant.IDMissing")
}
grant, err := es.UserGrantByID(ctx, grantID)
if err != nil {
return nil, err
}
if !grant.IsInactive() {
return nil, caos_errs.ThrowPreconditionFailed(nil, "EVENT-lo9sw", "Errors.UserGrant.NotInactive")
}
repoExistingGrant := model.UserGrantFromModel(grant)
repoGrant := &model.UserGrant{ObjectRoot: models.ObjectRoot{AggregateID: grantID}}
projectAggregate := UserGrantReactivatedAggregate(es.Eventstore.AggregateCreator(), repoExistingGrant, repoGrant)
err = es_sdk.Push(ctx, es.PushAggregates, repoExistingGrant.AppendEvents, projectAggregate)
if err != nil {
return nil, err
}
es.userGrantCache.cacheUserGrant(repoExistingGrant)
return model.UserGrantToModel(repoExistingGrant), nil
}

View File

@@ -1,113 +0,0 @@
package eventsourcing
import (
"encoding/json"
mock_cache "github.com/caos/zitadel/internal/cache/mock"
"github.com/caos/zitadel/internal/eventstore/mock"
es_models "github.com/caos/zitadel/internal/eventstore/models"
"github.com/caos/zitadel/internal/id"
"github.com/caos/zitadel/internal/usergrant/repository/eventsourcing/model"
"github.com/golang/mock/gomock"
)
func GetMockedEventstore(ctrl *gomock.Controller, mockEs *mock.MockEventstore) *UserGrantEventStore {
return &UserGrantEventStore{
Eventstore: mockEs,
userGrantCache: GetMockCache(ctrl),
idGenerator: GetSonyFlacke(),
}
}
func GetMockCache(ctrl *gomock.Controller) *UserGrantCache {
mockCache := mock_cache.NewMockCache(ctrl)
mockCache.EXPECT().Get(gomock.Any(), gomock.Any()).Return(nil).AnyTimes()
mockCache.EXPECT().Set(gomock.Any(), gomock.Any()).Return(nil).AnyTimes()
return &UserGrantCache{userGrantCache: mockCache}
}
func GetSonyFlacke() id.Generator {
return id.SonyFlakeGenerator
}
func GetMockUserGrantByIDOK(ctrl *gomock.Controller) *UserGrantEventStore {
user := model.UserGrant{
UserID: "UserID",
ProjectID: "ProjectID",
RoleKeys: []string{"Key"},
}
data, _ := json.Marshal(user)
events := []*es_models.Event{
&es_models.Event{AggregateID: "AggregateID", Sequence: 1, Type: model.UserGrantAdded, Data: data},
}
mockEs := mock.NewMockEventstore(ctrl)
mockEs.EXPECT().FilterEvents(gomock.Any(), gomock.Any()).Return(events, nil)
return GetMockedEventstore(ctrl, mockEs)
}
func GetMockUserGrantByIDRemoved(ctrl *gomock.Controller) *UserGrantEventStore {
user := model.UserGrant{
UserID: "UserID",
ProjectID: "ProjectID",
RoleKeys: []string{"Key"},
}
data, _ := json.Marshal(user)
events := []*es_models.Event{
&es_models.Event{AggregateID: "AggregateID", Sequence: 1, Type: model.UserGrantAdded, Data: data},
&es_models.Event{AggregateID: "AggregateID", Sequence: 1, Type: model.UserGrantRemoved},
}
mockEs := mock.NewMockEventstore(ctrl)
mockEs.EXPECT().FilterEvents(gomock.Any(), gomock.Any()).Return(events, nil)
return GetMockedEventstore(ctrl, mockEs)
}
func GetMockUserGrantByIDNoEvents(ctrl *gomock.Controller) *UserGrantEventStore {
events := []*es_models.Event{}
mockEs := mock.NewMockEventstore(ctrl)
mockEs.EXPECT().FilterEvents(gomock.Any(), gomock.Any()).Return(events, nil)
return GetMockedEventstore(ctrl, mockEs)
}
func GetMockManipulateUserGrant(ctrl *gomock.Controller) *UserGrantEventStore {
user := model.UserGrant{
UserID: "UserID",
ProjectID: "ProjectID",
RoleKeys: []string{"Key"},
}
data, _ := json.Marshal(user)
events := []*es_models.Event{
&es_models.Event{AggregateID: "AggregateID", Sequence: 1, Type: model.UserGrantAdded, Data: data},
}
mockEs := mock.NewMockEventstore(ctrl)
mockEs.EXPECT().FilterEvents(gomock.Any(), gomock.Any()).Return(events, nil)
mockEs.EXPECT().AggregateCreator().Return(es_models.NewAggregateCreator("TEST"))
mockEs.EXPECT().PushAggregates(gomock.Any(), gomock.Any()).Return(nil)
return GetMockedEventstore(ctrl, mockEs)
}
func GetMockManipulateUserGrantInactive(ctrl *gomock.Controller) *UserGrantEventStore {
user := model.UserGrant{
UserID: "UserID",
ProjectID: "ProjectID",
RoleKeys: []string{"Key"},
}
data, _ := json.Marshal(user)
events := []*es_models.Event{
&es_models.Event{AggregateID: "AggregateID", Sequence: 1, Type: model.UserGrantAdded, Data: data},
&es_models.Event{AggregateID: "AggregateID", Sequence: 1, Type: model.UserGrantDeactivated},
}
mockEs := mock.NewMockEventstore(ctrl)
mockEs.EXPECT().FilterEvents(gomock.Any(), gomock.Any()).Return(events, nil)
mockEs.EXPECT().AggregateCreator().Return(es_models.NewAggregateCreator("TEST"))
mockEs.EXPECT().PushAggregates(gomock.Any(), gomock.Any()).Return(nil)
return GetMockedEventstore(ctrl, mockEs)
}
func GetMockManipulateUserGrantNoEvents(ctrl *gomock.Controller) *UserGrantEventStore {
events := []*es_models.Event{}
mockEs := mock.NewMockEventstore(ctrl)
mockEs.EXPECT().FilterEvents(gomock.Any(), gomock.Any()).Return(events, nil)
mockEs.EXPECT().AggregateCreator().Return(es_models.NewAggregateCreator("TEST"))
mockEs.EXPECT().PushAggregates(gomock.Any(), gomock.Any()).Return(nil)
return GetMockedEventstore(ctrl, mockEs)
}

View File

@@ -1,441 +0,0 @@
package eventsourcing
import (
"context"
"reflect"
"testing"
"github.com/golang/mock/gomock"
"github.com/caos/zitadel/internal/api/authz"
caos_errs "github.com/caos/zitadel/internal/errors"
es_models "github.com/caos/zitadel/internal/eventstore/models"
"github.com/caos/zitadel/internal/usergrant/model"
)
func TestUserByID(t *testing.T) {
ctrl := gomock.NewController(t)
type args struct {
es *UserGrantEventStore
grant *model.UserGrant
}
type res struct {
grant *model.UserGrant
wantErr bool
errFunc func(err error) bool
}
tests := []struct {
name string
args args
res res
}{
{
name: "user from events, ok",
args: args{
es: GetMockUserGrantByIDOK(ctrl),
grant: &model.UserGrant{ObjectRoot: es_models.ObjectRoot{AggregateID: "AggregateID", Sequence: 1}},
},
res: res{
grant: &model.UserGrant{ObjectRoot: es_models.ObjectRoot{AggregateID: "AggregateID", Sequence: 1}, UserID: "UserID", ProjectID: "ProjectID", RoleKeys: []string{"Key"}},
},
},
{
name: "no events found",
args: args{
es: GetMockUserGrantByIDNoEvents(ctrl),
grant: &model.UserGrant{ObjectRoot: es_models.ObjectRoot{AggregateID: "AggregateID", Sequence: 1}},
},
res: res{
wantErr: true,
errFunc: caos_errs.IsNotFound,
},
},
{
name: "no id",
args: args{
es: GetMockUserGrantByIDOK(ctrl),
grant: &model.UserGrant{ObjectRoot: es_models.ObjectRoot{AggregateID: "", Sequence: 1}},
},
res: res{
wantErr: true,
errFunc: caos_errs.IsPreconditionFailed,
},
},
{
name: "removed state",
args: args{
es: GetMockUserGrantByIDRemoved(ctrl),
grant: &model.UserGrant{ObjectRoot: es_models.ObjectRoot{AggregateID: "AggregateID", Sequence: 1}},
},
res: res{
wantErr: true,
errFunc: caos_errs.IsNotFound,
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result, err := tt.args.es.UserGrantByID(nil, tt.args.grant.AggregateID)
if !tt.res.wantErr && result.AggregateID != tt.res.grant.AggregateID {
t.Errorf("got wrong result name: expected: %v, actual: %v ", tt.res.grant.AggregateID, result.AggregateID)
}
if tt.res.wantErr && !tt.res.errFunc(err) {
t.Errorf("got wrong err: %v ", err)
}
})
}
}
func TestAddUserGrant(t *testing.T) {
ctrl := gomock.NewController(t)
type args struct {
es *UserGrantEventStore
ctx context.Context
grant *model.UserGrant
}
type res struct {
result *model.UserGrant
wantErr bool
errFunc func(err error) bool
}
tests := []struct {
name string
args args
res res
}{
{
name: "add grant, ok",
args: args{
es: GetMockManipulateUserGrant(ctrl),
ctx: authz.NewMockContext("orgID", "userID"),
grant: &model.UserGrant{ObjectRoot: es_models.ObjectRoot{AggregateID: "AggregateID", Sequence: 1},
ProjectID: "ProjectID",
UserID: "UserID",
RoleKeys: []string{"Key"},
},
},
res: res{
result: &model.UserGrant{ObjectRoot: es_models.ObjectRoot{AggregateID: "AggregateID", Sequence: 1},
ProjectID: "ProjectID",
UserID: "UserID",
RoleKeys: []string{"Key"},
},
},
},
{
name: "invalid grant",
args: args{
es: GetMockManipulateUserGrant(ctrl),
ctx: authz.NewMockContext("orgID", "userID"),
grant: &model.UserGrant{ObjectRoot: es_models.ObjectRoot{AggregateID: "AggregateID", Sequence: 1}},
},
res: res{
wantErr: true,
errFunc: caos_errs.IsPreconditionFailed,
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result, err := tt.args.es.AddUserGrant(tt.args.ctx, tt.args.grant)
if !tt.res.wantErr && result.AggregateID == "" {
t.Errorf("result has no id")
}
if !tt.res.wantErr && result.UserID == "" {
t.Errorf("result has no id")
}
if tt.res.wantErr && !tt.res.errFunc(err) {
t.Errorf("got wrong err: %v ", err)
}
})
}
}
func TestChangeUserGrant(t *testing.T) {
ctrl := gomock.NewController(t)
type args struct {
es *UserGrantEventStore
ctx context.Context
grant *model.UserGrant
}
type res struct {
result *model.UserGrant
wantErr bool
errFunc func(err error) bool
}
tests := []struct {
name string
args args
res res
}{
{
name: "change grant, ok",
args: args{
es: GetMockManipulateUserGrant(ctrl),
ctx: authz.NewMockContext("orgID", "userID"),
grant: &model.UserGrant{ObjectRoot: es_models.ObjectRoot{AggregateID: "AggregateID", Sequence: 1},
RoleKeys: []string{"KeyChanged"},
},
},
res: res{
result: &model.UserGrant{ObjectRoot: es_models.ObjectRoot{AggregateID: "AggregateID", Sequence: 1},
RoleKeys: []string{"KeyChanged"},
},
},
},
{
name: "invalid grant",
args: args{
es: GetMockManipulateUserGrant(ctrl),
ctx: authz.NewMockContext("orgID", "userID"),
grant: nil,
},
res: res{
wantErr: true,
errFunc: caos_errs.IsPreconditionFailed,
},
},
{
name: "existing user not found",
args: args{
es: GetMockManipulateUserGrantNoEvents(ctrl),
ctx: authz.NewMockContext("orgID", "userID"),
grant: &model.UserGrant{ObjectRoot: es_models.ObjectRoot{AggregateID: "AggregateID", Sequence: 1},
RoleKeys: []string{"KeyChanged"},
},
},
res: res{
wantErr: true,
errFunc: caos_errs.IsNotFound,
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result, err := tt.args.es.ChangeUserGrant(tt.args.ctx, tt.args.grant)
if !tt.res.wantErr && result.AggregateID == "" {
t.Errorf("result has no id")
}
if !tt.res.wantErr && !reflect.DeepEqual(result.RoleKeys, tt.res.result.RoleKeys) {
t.Errorf("got wrong result name: expected: %v, actual: %v ", tt.res.result.RoleKeys, result.RoleKeys)
}
if tt.res.wantErr && !tt.res.errFunc(err) {
t.Errorf("got wrong err: %v ", err)
}
})
}
}
func TestRemoveUserGrant(t *testing.T) {
ctrl := gomock.NewController(t)
type args struct {
es *UserGrantEventStore
ctx context.Context
grant *model.UserGrant
}
type res struct {
wantErr bool
errFunc func(err error) bool
}
tests := []struct {
name string
args args
res res
}{
{
name: "remove grant, ok",
args: args{
es: GetMockManipulateUserGrant(ctrl),
ctx: authz.NewMockContext("orgID", "userID"),
grant: &model.UserGrant{ObjectRoot: es_models.ObjectRoot{AggregateID: "AggregateID", Sequence: 1}},
},
},
{
name: "no grantID",
args: args{
es: GetMockManipulateUserGrant(ctrl),
ctx: authz.NewMockContext("orgID", "userID"),
grant: &model.UserGrant{ObjectRoot: es_models.ObjectRoot{AggregateID: "", Sequence: 1}},
},
res: res{
wantErr: true,
errFunc: caos_errs.IsPreconditionFailed,
},
},
{
name: "existing grant not found",
args: args{
es: GetMockManipulateUserGrantNoEvents(ctrl),
ctx: authz.NewMockContext("orgID", "userID"),
grant: &model.UserGrant{ObjectRoot: es_models.ObjectRoot{AggregateID: "AggregateID", Sequence: 1}},
},
res: res{
wantErr: true,
errFunc: caos_errs.IsNotFound,
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
err := tt.args.es.RemoveUserGrant(tt.args.ctx, tt.args.grant.AggregateID)
if !tt.res.wantErr && err != nil {
t.Errorf("should not get err")
}
if tt.res.wantErr && !tt.res.errFunc(err) {
t.Errorf("got wrong err: %v ", err)
}
})
}
}
func TestDeactivateUserGrant(t *testing.T) {
ctrl := gomock.NewController(t)
type args struct {
es *UserGrantEventStore
ctx context.Context
grant *model.UserGrant
}
type res struct {
result *model.UserGrant
wantErr bool
errFunc func(err error) bool
}
tests := []struct {
name string
args args
res res
}{
{
name: "deactivate, ok",
args: args{
es: GetMockManipulateUserGrant(ctrl),
ctx: authz.NewMockContext("orgID", "userID"),
grant: &model.UserGrant{ObjectRoot: es_models.ObjectRoot{AggregateID: "AggregateID", Sequence: 1}},
},
res: res{
result: &model.UserGrant{ObjectRoot: es_models.ObjectRoot{AggregateID: "AggregateID", Sequence: 1},
ProjectID: "ProjectID",
State: model.UserGrantStateInactive,
},
},
},
{
name: "no grant id",
args: args{
es: GetMockManipulateUserGrant(ctrl),
ctx: authz.NewMockContext("orgID", "userID"),
grant: &model.UserGrant{ObjectRoot: es_models.ObjectRoot{AggregateID: "", Sequence: 1}},
},
res: res{
wantErr: true,
errFunc: caos_errs.IsPreconditionFailed,
},
},
{
name: "grant not existing",
args: args{
es: GetMockManipulateUserGrantNoEvents(ctrl),
ctx: authz.NewMockContext("orgID", "userID"),
grant: &model.UserGrant{ObjectRoot: es_models.ObjectRoot{AggregateID: "ID", Sequence: 1}},
},
res: res{
wantErr: true,
errFunc: caos_errs.IsNotFound,
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result, err := tt.args.es.DeactivateUserGrant(tt.args.ctx, tt.args.grant.AggregateID)
if !tt.res.wantErr && result.AggregateID == "" {
t.Errorf("result has no id")
}
if !tt.res.wantErr && result.ProjectID != tt.res.result.ProjectID {
t.Errorf("got wrong result AppID: expected: %v, actual: %v ", tt.res.result.ProjectID, result.ProjectID)
}
if !tt.res.wantErr && result.State != tt.res.result.State {
t.Errorf("got wrong result state: expected: %v, actual: %v ", tt.res.result.State, result.State)
}
if tt.res.wantErr && !tt.res.errFunc(err) {
t.Errorf("got wrong err: %v ", err)
}
})
}
}
func TestReactivateUserGrant(t *testing.T) {
ctrl := gomock.NewController(t)
type args struct {
es *UserGrantEventStore
ctx context.Context
grant *model.UserGrant
}
type res struct {
result *model.UserGrant
wantErr bool
errFunc func(err error) bool
}
tests := []struct {
name string
args args
res res
}{
{
name: "reactivate, ok",
args: args{
es: GetMockManipulateUserGrantInactive(ctrl),
ctx: authz.NewMockContext("orgID", "userID"),
grant: &model.UserGrant{ObjectRoot: es_models.ObjectRoot{AggregateID: "AggregateID", Sequence: 1}},
},
res: res{
result: &model.UserGrant{ObjectRoot: es_models.ObjectRoot{AggregateID: "AggregateID", Sequence: 1},
State: model.UserGrantStateActive,
},
},
},
{
name: "no grant id",
args: args{
es: GetMockManipulateUserGrant(ctrl),
ctx: authz.NewMockContext("orgID", "userID"),
grant: &model.UserGrant{ObjectRoot: es_models.ObjectRoot{AggregateID: "", Sequence: 1}},
},
res: res{
wantErr: true,
errFunc: caos_errs.IsPreconditionFailed,
},
},
{
name: "grant not existing",
args: args{
es: GetMockManipulateUserGrantNoEvents(ctrl),
ctx: authz.NewMockContext("orgID", "userID"),
grant: &model.UserGrant{ObjectRoot: es_models.ObjectRoot{AggregateID: "AggregateID", Sequence: 1}},
},
res: res{
wantErr: true,
errFunc: caos_errs.IsNotFound,
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result, err := tt.args.es.ReactivateUserGrant(tt.args.ctx, tt.args.grant.AggregateID)
if !tt.res.wantErr && result.AggregateID == "" {
t.Errorf("result has no id")
}
if !tt.res.wantErr && result.State != tt.res.result.State {
t.Errorf("got wrong result state: expected: %v, actual: %v ", tt.res.result.State, result.State)
}
if tt.res.wantErr && !tt.res.errFunc(err) {
t.Errorf("got wrong err: %v ", err)
}
})
}
}

View File

@@ -3,16 +3,13 @@ package model
import "github.com/caos/zitadel/internal/eventstore/models"
const (
UserGrantAggregate models.AggregateType = "usergrant"
UserGrantUniqueAggregate models.AggregateType = "usergrant.unique"
UserGrantAggregate models.AggregateType = "usergrant"
UserGrantAdded models.EventType = "user.grant.added"
UserGrantChanged models.EventType = "user.grant.changed"
UserGrantRemoved models.EventType = "user.grant.removed"
UserGrantDeactivated models.EventType = "user.grant.deactivated"
UserGrantReactivated models.EventType = "user.grant.reactivated"
UserGrantReserved models.EventType = "user.grant.reserved"
UserGrantReleased models.EventType = "user.grant.released"
UserGrantCascadeRemoved models.EventType = "user.grant.cascade.removed"
UserGrantCascadeChanged models.EventType = "user.grant.cascade.changed"

View File

@@ -1,16 +1,7 @@
package model
import (
"encoding/json"
"github.com/caos/logging"
caos_errs "github.com/caos/zitadel/internal/errors"
es_models "github.com/caos/zitadel/internal/eventstore/models"
"github.com/caos/zitadel/internal/usergrant/model"
"reflect"
)
const (
UserGrantVersion = "v1"
)
type UserGrant struct {
@@ -22,77 +13,3 @@ type UserGrant struct {
GrantID string `json:"grantId,omitempty"`
RoleKeys []string `json:"roleKeys,omitempty"`
}
type UserGrantID struct {
es_models.ObjectRoot
GrantID string `json:"grantId"`
}
func (g *UserGrant) Changes(changed *UserGrant) map[string]interface{} {
changes := make(map[string]interface{}, 1)
if !reflect.DeepEqual(g.RoleKeys, changed.RoleKeys) {
changes["roleKeys"] = changed.RoleKeys
}
return changes
}
func UserGrantFromModel(grant *model.UserGrant) *UserGrant {
return &UserGrant{
ObjectRoot: grant.ObjectRoot,
UserID: grant.UserID,
ProjectID: grant.ProjectID,
GrantID: grant.GrantID,
State: int32(grant.State),
RoleKeys: grant.RoleKeys,
}
}
func UserGrantToModel(grant *UserGrant) *model.UserGrant {
return &model.UserGrant{
ObjectRoot: grant.ObjectRoot,
UserID: grant.UserID,
ProjectID: grant.ProjectID,
GrantID: grant.GrantID,
State: model.UserGrantState(grant.State),
RoleKeys: grant.RoleKeys,
}
}
func (g *UserGrant) AppendEvents(events ...*es_models.Event) error {
for _, event := range events {
if err := g.AppendEvent(event); err != nil {
return err
}
}
return nil
}
func (g *UserGrant) AppendEvent(event *es_models.Event) error {
g.ObjectRoot.AppendEvent(event)
switch event.Type {
case UserGrantAdded,
UserGrantChanged,
UserGrantCascadeChanged:
return g.setData(event)
case UserGrantDeactivated:
g.appendGrantStateEvent(model.UserGrantStateInactive)
case UserGrantReactivated:
g.appendGrantStateEvent(model.UserGrantStateActive)
case UserGrantRemoved,
UserGrantCascadeRemoved:
g.appendGrantStateEvent(model.UserGrantStateRemoved)
}
return nil
}
func (g *UserGrant) appendGrantStateEvent(state model.UserGrantState) {
g.State = int32(state)
}
func (g *UserGrant) setData(event *es_models.Event) error {
if err := json.Unmarshal(event.Data, g); err != nil {
logging.Log("EVEN-lso9x").WithError(err).Error("could not unmarshal event data")
return caos_errs.ThrowInternal(err, "MODEL-o0se3", "could not unmarshal event")
}
return nil
}

View File

@@ -1,61 +0,0 @@
package model
import (
"testing"
es_models "github.com/caos/zitadel/internal/eventstore/models"
"github.com/caos/zitadel/internal/usergrant/model"
)
func TestAppendGrantStateEvent(t *testing.T) {
type args struct {
grant *UserGrant
grantID *UserGrantID
event *es_models.Event
state model.UserGrantState
}
tests := []struct {
name string
args args
result *UserGrant
}{
{
name: "append deactivate grant event",
args: args{
grant: &UserGrant{ObjectRoot: es_models.ObjectRoot{AggregateID: "ID"}, UserID: "UserID", ProjectID: "ProjectID", RoleKeys: []string{"Key"}},
grantID: &UserGrantID{GrantID: "ProjectGrantID"},
event: &es_models.Event{},
state: model.UserGrantStateInactive,
},
result: &UserGrant{ObjectRoot: es_models.ObjectRoot{AggregateID: "ID"}, UserID: "UserID", ProjectID: "ProjectID", RoleKeys: []string{"Key"}, State: int32(model.UserGrantStateInactive)},
},
{
name: "append reactivate grant event",
args: args{
grant: &UserGrant{ObjectRoot: es_models.ObjectRoot{AggregateID: "ID"}, UserID: "UserID", ProjectID: "ProjectID", RoleKeys: []string{"Key"}},
grantID: &UserGrantID{GrantID: "ProjectGrantID"},
event: &es_models.Event{},
state: model.UserGrantStateActive,
},
result: &UserGrant{ObjectRoot: es_models.ObjectRoot{AggregateID: "ID"}, UserID: "UserID", ProjectID: "ProjectID", RoleKeys: []string{"Key"}, State: int32(model.UserGrantStateActive)},
},
{
name: "append remove grant event",
args: args{
grant: &UserGrant{ObjectRoot: es_models.ObjectRoot{AggregateID: "ID"}, UserID: "UserID", ProjectID: "ProjectID", RoleKeys: []string{"Key"}},
grantID: &UserGrantID{GrantID: "ProjectGrantID"},
event: &es_models.Event{},
state: model.UserGrantStateRemoved,
},
result: &UserGrant{ObjectRoot: es_models.ObjectRoot{AggregateID: "ID"}, UserID: "UserID", ProjectID: "ProjectID", RoleKeys: []string{"Key"}, State: int32(model.UserGrantStateRemoved)},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
tt.args.grant.appendGrantStateEvent(tt.args.state)
if tt.args.grant.State != tt.result.State {
t.Errorf("got wrong result: actual: %v, expected: %v ", tt.result.State, tt.args.grant.State)
}
})
}
}

View File

@@ -1,258 +0,0 @@
package eventsourcing
import (
"context"
"github.com/caos/zitadel/internal/api/authz"
"github.com/caos/zitadel/internal/errors"
es_models "github.com/caos/zitadel/internal/eventstore/models"
org_es_model "github.com/caos/zitadel/internal/org/repository/eventsourcing/model"
proj_model "github.com/caos/zitadel/internal/project/model"
proj_es_model "github.com/caos/zitadel/internal/project/repository/eventsourcing/model"
usr_model "github.com/caos/zitadel/internal/user/repository/eventsourcing/model"
"github.com/caos/zitadel/internal/usergrant/repository/eventsourcing/model"
)
func UserGrantByIDQuery(id string, latestSequence uint64) (*es_models.SearchQuery, error) {
if id == "" {
return nil, errors.ThrowPreconditionFailed(nil, "EVENT-ols34", "id should be filled")
}
return UserGrantQuery(latestSequence).
AggregateIDFilter(id), nil
}
func UserGrantQuery(latestSequence uint64) *es_models.SearchQuery {
return es_models.NewSearchQuery().
AggregateTypeFilter(model.UserGrantAggregate).
LatestSequenceFilter(latestSequence)
}
func UserGrantUniqueQuery(resourceOwner, projectID, userID string) *es_models.SearchQuery {
grantID := resourceOwner + projectID + userID
return es_models.NewSearchQuery().
AggregateTypeFilter(model.UserGrantUniqueAggregate).
AggregateIDFilter(grantID).
OrderDesc().
SetLimit(1)
}
func UserGrantAggregate(ctx context.Context, aggCreator *es_models.AggregateCreator, grant *model.UserGrant) (*es_models.Aggregate, error) {
if grant == nil {
return nil, errors.ThrowPreconditionFailed(nil, "EVENT-dis83", "existing grant should not be nil")
}
return aggCreator.NewAggregate(ctx, grant.AggregateID, model.UserGrantAggregate, model.UserGrantVersion, grant.Sequence)
}
func UserGrantAddedAggregate(ctx context.Context, aggCreator *es_models.AggregateCreator, grant *model.UserGrant) ([]*es_models.Aggregate, error) {
agg, err := UserGrantAggregate(ctx, aggCreator, grant)
if err != nil {
return nil, err
}
validationQuery := es_models.NewSearchQuery().
AggregateTypeFilter(usr_model.UserAggregate, org_es_model.OrgAggregate, proj_es_model.ProjectAggregate).
AggregateIDsFilter(grant.UserID, authz.GetCtxData(ctx).OrgID, grant.ProjectID)
validation := addUserGrantValidation(authz.GetCtxData(ctx).OrgID, grant)
agg, err = agg.SetPrecondition(validationQuery, validation).AppendEvent(model.UserGrantAdded, grant)
if err != nil {
return nil, err
}
uniqueAggregate, err := reservedUniqueUserGrantAggregate(ctx, aggCreator, grant)
if err != nil {
return nil, err
}
return []*es_models.Aggregate{
agg,
uniqueAggregate,
}, nil
}
func reservedUniqueUserGrantAggregate(ctx context.Context, aggCreator *es_models.AggregateCreator, grant *model.UserGrant) (*es_models.Aggregate, error) {
grantID := authz.GetCtxData(ctx).OrgID + grant.ProjectID + grant.UserID
aggregate, err := aggCreator.NewAggregate(ctx, grantID, model.UserGrantUniqueAggregate, model.UserGrantVersion, 0)
if err != nil {
return nil, err
}
aggregate, err = aggregate.AppendEvent(model.UserGrantReserved, nil)
if err != nil {
return nil, err
}
return aggregate.SetPrecondition(UserGrantUniqueQuery(authz.GetCtxData(ctx).OrgID, grant.ProjectID, grant.UserID), isEventValidation(aggregate, model.UserGrantReserved)), nil
}
func releasedUniqueUserGrantAggregate(ctx context.Context, aggCreator *es_models.AggregateCreator, grant *model.UserGrant) (aggregate *es_models.Aggregate, err error) {
grantID := grant.ResourceOwner + grant.ProjectID + grant.UserID
aggregate, err = aggCreator.NewAggregate(ctx, grantID, model.UserGrantUniqueAggregate, model.UserGrantVersion, 0)
if err != nil {
return nil, err
}
aggregate, err = aggregate.AppendEvent(model.UserGrantReleased, nil)
if err != nil {
return nil, err
}
return aggregate.SetPrecondition(UserGrantUniqueQuery(grant.ResourceOwner, grant.ProjectID, grant.UserID), isEventValidation(aggregate, model.UserGrantReleased)), nil
}
func UserGrantChangedAggregate(aggCreator *es_models.AggregateCreator, existingGrant *model.UserGrant, grant *model.UserGrant, cascade bool) func(ctx context.Context) (*es_models.Aggregate, error) {
return func(ctx context.Context) (*es_models.Aggregate, error) {
if grant == nil {
return nil, errors.ThrowPreconditionFailed(nil, "EVENT-osl8x", "grant should not be nil")
}
agg, err := UserGrantAggregate(ctx, aggCreator, existingGrant)
if err != nil {
return nil, err
}
changes := existingGrant.Changes(grant)
if !cascade {
return agg.AppendEvent(model.UserGrantChanged, changes)
}
return agg.AppendEvent(model.UserGrantCascadeChanged, changes)
}
}
func UserGrantDeactivatedAggregate(aggCreator *es_models.AggregateCreator, existingGrant *model.UserGrant, grant *model.UserGrant) func(ctx context.Context) (*es_models.Aggregate, error) {
return func(ctx context.Context) (*es_models.Aggregate, error) {
if grant == nil {
return nil, errors.ThrowPreconditionFailed(nil, "EVENT-lo21s", "grant should not be nil")
}
agg, err := UserGrantAggregate(ctx, aggCreator, existingGrant)
if err != nil {
return nil, err
}
return agg.AppendEvent(model.UserGrantDeactivated, nil)
}
}
func UserGrantReactivatedAggregate(aggCreator *es_models.AggregateCreator, existingGrant *model.UserGrant, grant *model.UserGrant) func(ctx context.Context) (*es_models.Aggregate, error) {
return func(ctx context.Context) (*es_models.Aggregate, error) {
if grant == nil {
return nil, errors.ThrowPreconditionFailed(nil, "EVENT-mks34", "grant should not be nil")
}
agg, err := UserGrantAggregate(ctx, aggCreator, existingGrant)
if err != nil {
return nil, err
}
return agg.AppendEvent(model.UserGrantReactivated, nil)
}
}
func UserGrantRemovedAggregate(ctx context.Context, aggCreator *es_models.AggregateCreator, existingGrant *model.UserGrant, grant *model.UserGrant, cascade bool) ([]*es_models.Aggregate, error) {
if grant == nil {
return nil, errors.ThrowPreconditionFailed(nil, "EVENT-lo21s", "grant should not be nil")
}
agg, err := UserGrantAggregate(ctx, aggCreator, existingGrant)
if err != nil {
return nil, err
}
eventType := model.UserGrantRemoved
if cascade {
eventType = model.UserGrantCascadeRemoved
}
agg, err = agg.AppendEvent(eventType, nil)
if err != nil {
return nil, err
}
uniqueAggregate, err := releasedUniqueUserGrantAggregate(ctx, aggCreator, existingGrant)
if err != nil {
return nil, err
}
return []*es_models.Aggregate{
agg,
uniqueAggregate,
}, nil
}
func isEventValidation(aggregate *es_models.Aggregate, eventType es_models.EventType) func(...*es_models.Event) error {
return func(events ...*es_models.Event) error {
if len(events) == 0 {
aggregate.PreviousSequence = 0
return nil
}
if events[0].Type == eventType {
return errors.ThrowPreconditionFailedf(nil, "EVENT-eJQqe", "user_grant is already %v", eventType)
}
aggregate.PreviousSequence = events[0].Sequence
return nil
}
}
func addUserGrantValidation(resourceOwner string, grant *model.UserGrant) func(...*es_models.Event) error {
return func(events ...*es_models.Event) error {
existsOrg := false
existsUser := false
project := new(proj_es_model.Project)
for _, event := range events {
switch event.AggregateType {
case usr_model.UserAggregate:
switch event.Type {
case usr_model.UserAdded, usr_model.UserRegistered, usr_model.HumanRegistered, usr_model.HumanAdded, usr_model.MachineAdded:
existsUser = true
case usr_model.UserRemoved:
existsUser = false
}
case org_es_model.OrgAggregate:
switch event.Type {
case org_es_model.OrgAdded:
existsOrg = true
case org_es_model.OrgRemoved:
existsOrg = false
}
case proj_es_model.ProjectAggregate:
project.AppendEvent(event)
}
}
if !existsOrg {
return errors.ThrowPreconditionFailed(nil, "EVENT-3OfIm", "org doesn't exist")
}
if !existsUser {
return errors.ThrowPreconditionFailed(nil, "EVENT-Sl8uS", "user doesn't exist")
}
return checkProjectConditions(resourceOwner, grant, project)
}
}
//TODO: rethink this function i know it's ugly.
func checkProjectConditions(resourceOwner string, grant *model.UserGrant, project *proj_es_model.Project) error {
if grant.ProjectID != project.AggregateID {
return errors.ThrowInvalidArgument(nil, "EVENT-ixlMx", "project doesn't exist")
}
if project.State == int32(proj_model.ProjectStateRemoved) {
return errors.ThrowPreconditionFailed(nil, "EVENT-Lxp0s", "project doesn't exist")
}
if resourceOwner == project.ResourceOwner {
return checkIfProjectHasRoles(grant.RoleKeys, project.Roles)
}
if _, projectGrant := proj_es_model.GetProjectGrantByOrgID(project.Grants, resourceOwner); projectGrant != nil {
return checkIfProjectGrantHasRoles(grant.RoleKeys, projectGrant.RoleKeys)
}
return nil
}
func checkIfProjectHasRoles(roles []string, existingRoles []*proj_es_model.ProjectRole) error {
for _, roleKey := range roles {
if _, role := proj_es_model.GetProjectRole(existingRoles, roleKey); role == nil {
return errors.ThrowPreconditionFailedf(nil, "EVENT-Lxp0s", "project doesn't have role %v", roleKey)
}
}
return nil
}
func checkIfProjectGrantHasRoles(roles []string, existingRoles []string) error {
roleExists := false
for _, roleKey := range roles {
for _, existingRoleKey := range existingRoles {
if roleKey == existingRoleKey {
roleExists = true
continue
}
}
if !roleExists {
return errors.ThrowPreconditionFailed(nil, "EVENT-LSpwi", "project grant doesn't have role")
}
}
return nil
}

View File

@@ -1,451 +0,0 @@
package eventsourcing
import (
"context"
"testing"
"github.com/caos/zitadel/internal/api/authz"
caos_errs "github.com/caos/zitadel/internal/errors"
"github.com/caos/zitadel/internal/eventstore/models"
"github.com/caos/zitadel/internal/usergrant/repository/eventsourcing/model"
)
func TestUserGrantAddedAggregate(t *testing.T) {
type args struct {
ctx context.Context
grant *model.UserGrant
aggCreator *models.AggregateCreator
}
type res struct {
eventLen int
eventType models.EventType
errFunc func(err error) bool
}
tests := []struct {
name string
args args
res res
}{
{
name: "usergrant added ok",
args: args{
ctx: authz.NewMockContext("orgID", "userID"),
grant: &model.UserGrant{ObjectRoot: models.ObjectRoot{AggregateID: "ID"}, UserID: "UserID", ProjectID: "ProjectID"},
aggCreator: models.NewAggregateCreator("Test"),
},
res: res{
eventLen: 1,
eventType: model.UserGrantAdded,
},
},
{
name: "grant nil",
args: args{
ctx: authz.NewMockContext("orgID", "userID"),
grant: nil,
aggCreator: models.NewAggregateCreator("Test"),
},
res: res{
errFunc: caos_errs.IsPreconditionFailed,
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
aggregates, err := UserGrantAddedAggregate(tt.args.ctx, tt.args.aggCreator, tt.args.grant)
if tt.res.errFunc == nil && len(aggregates[0].Events) != tt.res.eventLen {
t.Errorf("got wrong event len: expected: %v, actual: %v ", tt.res.eventLen, len(aggregates[0].Events))
}
if tt.res.errFunc == nil && aggregates[0].Events[0].Type != tt.res.eventType {
t.Errorf("got wrong event type: expected: %v, actual: %v ", tt.res.eventType, aggregates[0].Events[0].Type.String())
}
if tt.res.errFunc == nil && aggregates[0].Events[0].Data == nil {
t.Errorf("should have data in event")
}
if tt.res.errFunc != nil && !tt.res.errFunc(err) {
t.Errorf("got wrong err: %v ", err)
}
})
}
}
func TestUserGrantChangedAggregate(t *testing.T) {
type args struct {
ctx context.Context
existingGrant *model.UserGrant
newGrant *model.UserGrant
cascade bool
aggCreator *models.AggregateCreator
}
type res struct {
eventLen int
eventTypes []models.EventType
errFunc func(err error) bool
}
tests := []struct {
name string
args args
res res
}{
{
name: "change project grant",
args: args{
ctx: authz.NewMockContext("orgID", "userID"),
existingGrant: &model.UserGrant{
ObjectRoot: models.ObjectRoot{AggregateID: "ID"},
UserID: "UserID",
ProjectID: "ProjectID",
RoleKeys: []string{"Key"}},
newGrant: &model.UserGrant{
ObjectRoot: models.ObjectRoot{AggregateID: "ID"},
UserID: "UserID",
ProjectID: "ProjectID",
RoleKeys: []string{"KeyChanged"},
},
aggCreator: models.NewAggregateCreator("Test"),
},
res: res{
eventLen: 1,
eventTypes: []models.EventType{model.UserGrantChanged},
},
},
{
name: "change project grant cascade",
args: args{
ctx: authz.NewMockContext("orgID", "userID"),
existingGrant: &model.UserGrant{
ObjectRoot: models.ObjectRoot{AggregateID: "ID"},
UserID: "UserID",
ProjectID: "ProjectID",
RoleKeys: []string{"Key"}},
newGrant: &model.UserGrant{
ObjectRoot: models.ObjectRoot{AggregateID: "ID"},
UserID: "UserID",
ProjectID: "ProjectID",
RoleKeys: []string{"KeyChanged"},
},
cascade: true,
aggCreator: models.NewAggregateCreator("Test"),
},
res: res{
eventLen: 1,
eventTypes: []models.EventType{model.UserGrantCascadeChanged},
},
},
{
name: "existing grant nil",
args: args{
ctx: authz.NewMockContext("orgID", "userID"),
existingGrant: nil,
newGrant: &model.UserGrant{
ObjectRoot: models.ObjectRoot{AggregateID: "ID"},
UserID: "UserID",
ProjectID: "ProjectID",
RoleKeys: []string{"Key"}},
aggCreator: models.NewAggregateCreator("Test"),
},
res: res{
errFunc: caos_errs.IsPreconditionFailed,
},
},
{
name: "grant nil",
args: args{
ctx: authz.NewMockContext("orgID", "userID"),
existingGrant: &model.UserGrant{
ObjectRoot: models.ObjectRoot{AggregateID: "ID"},
UserID: "UserID",
ProjectID: "ProjectID",
RoleKeys: []string{"Key"}},
newGrant: nil,
aggCreator: models.NewAggregateCreator("Test"),
},
res: res{
errFunc: caos_errs.IsPreconditionFailed,
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
agg, err := UserGrantChangedAggregate(tt.args.aggCreator, tt.args.existingGrant, tt.args.newGrant, tt.args.cascade)(tt.args.ctx)
if tt.res.errFunc == nil && len(agg.Events) != tt.res.eventLen {
t.Errorf("got wrong event len: expected: %v, actual: %v ", tt.res.eventLen, len(agg.Events))
}
for i := 0; i < tt.res.eventLen; i++ {
if tt.res.errFunc == nil && agg.Events[i].Type != tt.res.eventTypes[i] {
t.Errorf("got wrong event type: expected: %v, actual: %v ", tt.res.eventTypes[i], agg.Events[i].Type.String())
}
if tt.res.errFunc == nil && agg.Events[i].Data == nil {
t.Errorf("should have data in event")
}
}
if tt.res.errFunc != nil && !tt.res.errFunc(err) {
t.Errorf("got wrong err: %v ", err)
}
})
}
}
func TestUserGrantRemovedAggregate(t *testing.T) {
type args struct {
ctx context.Context
existingGrant *model.UserGrant
newGrant *model.UserGrant
cascade bool
aggCreator *models.AggregateCreator
}
type res struct {
eventLen int
eventTypes []models.EventType
errFunc func(err error) bool
}
tests := []struct {
name string
args args
res res
}{
{
name: "remove app",
args: args{
ctx: authz.NewMockContext("orgID", "userID"),
existingGrant: &model.UserGrant{
ObjectRoot: models.ObjectRoot{AggregateID: "ID"},
UserID: "UserID",
ProjectID: "ProjectID",
RoleKeys: []string{"Key"}},
newGrant: &model.UserGrant{
ObjectRoot: models.ObjectRoot{AggregateID: "ID"},
},
aggCreator: models.NewAggregateCreator("Test"),
},
res: res{
eventLen: 1,
eventTypes: []models.EventType{model.UserGrantRemoved},
},
},
{
name: "remove app cascade",
args: args{
ctx: authz.NewMockContext("orgID", "userID"),
existingGrant: &model.UserGrant{
ObjectRoot: models.ObjectRoot{AggregateID: "ID"},
UserID: "UserID",
ProjectID: "ProjectID",
RoleKeys: []string{"Key"}},
newGrant: &model.UserGrant{
ObjectRoot: models.ObjectRoot{AggregateID: "ID"},
},
cascade: true,
aggCreator: models.NewAggregateCreator("Test"),
},
res: res{
eventLen: 1,
eventTypes: []models.EventType{model.UserGrantCascadeRemoved},
},
},
{
name: "existing project nil",
args: args{
ctx: authz.NewMockContext("orgID", "userID"),
existingGrant: nil,
aggCreator: models.NewAggregateCreator("Test"),
},
res: res{
errFunc: caos_errs.IsPreconditionFailed,
},
},
{
name: "grant nil",
args: args{
ctx: authz.NewMockContext("orgID", "userID"),
existingGrant: &model.UserGrant{
ObjectRoot: models.ObjectRoot{AggregateID: "ID"},
UserID: "UserID",
ProjectID: "ProjectID",
RoleKeys: []string{"Key"}},
newGrant: nil,
aggCreator: models.NewAggregateCreator("Test"),
},
res: res{
errFunc: caos_errs.IsPreconditionFailed,
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
aggregates, err := UserGrantRemovedAggregate(tt.args.ctx, tt.args.aggCreator, tt.args.existingGrant, tt.args.newGrant, tt.args.cascade)
if tt.res.errFunc == nil && len(aggregates[0].Events) != tt.res.eventLen {
t.Errorf("got wrong event len: expected: %v, actual: %v ", tt.res.eventLen, len(aggregates[0].Events))
}
for i := 0; i < tt.res.eventLen; i++ {
if tt.res.errFunc == nil && aggregates[0].Events[i].Type != tt.res.eventTypes[i] {
t.Errorf("got wrong event type: expected: %v, actual: %v ", tt.res.eventTypes[i], aggregates[0].Events[i].Type.String())
}
}
if tt.res.errFunc != nil && !tt.res.errFunc(err) {
t.Errorf("got wrong err: %v ", err)
}
})
}
}
func TestUserGrantDeactivatedAggregate(t *testing.T) {
type args struct {
ctx context.Context
existingGrant *model.UserGrant
newGrant *model.UserGrant
aggCreator *models.AggregateCreator
}
type res struct {
eventLen int
eventTypes []models.EventType
errFunc func(err error) bool
}
tests := []struct {
name string
args args
res res
}{
{
name: "deactivate project grant",
args: args{
ctx: authz.NewMockContext("orgID", "userID"),
existingGrant: &model.UserGrant{
ObjectRoot: models.ObjectRoot{AggregateID: "ID"},
},
newGrant: &model.UserGrant{
ObjectRoot: models.ObjectRoot{AggregateID: "ID"},
},
aggCreator: models.NewAggregateCreator("Test"),
},
res: res{
eventLen: 1,
eventTypes: []models.EventType{model.UserGrantDeactivated},
},
},
{
name: "existing grant nil",
args: args{
ctx: authz.NewMockContext("orgID", "userID"),
existingGrant: nil,
aggCreator: models.NewAggregateCreator("Test"),
},
res: res{
errFunc: caos_errs.IsPreconditionFailed,
},
},
{
name: "grant nil",
args: args{
ctx: authz.NewMockContext("orgID", "userID"),
existingGrant: &model.UserGrant{ObjectRoot: models.ObjectRoot{AggregateID: "ID"}},
newGrant: nil,
aggCreator: models.NewAggregateCreator("Test"),
},
res: res{
errFunc: caos_errs.IsPreconditionFailed,
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
agg, err := UserGrantDeactivatedAggregate(tt.args.aggCreator, tt.args.existingGrant, tt.args.newGrant)(tt.args.ctx)
if tt.res.errFunc == nil && len(agg.Events) != tt.res.eventLen {
t.Errorf("got wrong event len: expected: %v, actual: %v ", tt.res.eventLen, len(agg.Events))
}
for i := 0; i < tt.res.eventLen; i++ {
if tt.res.errFunc == nil && agg.Events[i].Type != tt.res.eventTypes[i] {
t.Errorf("got wrong event type: expected: %v, actual: %v ", tt.res.eventTypes[i], agg.Events[i].Type.String())
}
}
if tt.res.errFunc != nil && !tt.res.errFunc(err) {
t.Errorf("got wrong err: %v ", err)
}
})
}
}
func TestUserGrantReactivatedAggregate(t *testing.T) {
type args struct {
ctx context.Context
existingGrant *model.UserGrant
newGrant *model.UserGrant
aggCreator *models.AggregateCreator
}
type res struct {
eventLen int
eventTypes []models.EventType
errFunc func(err error) bool
}
tests := []struct {
name string
args args
res res
}{
{
name: "reactivate project grant",
args: args{
ctx: authz.NewMockContext("orgID", "userID"),
existingGrant: &model.UserGrant{
ObjectRoot: models.ObjectRoot{AggregateID: "ID"},
},
newGrant: &model.UserGrant{
ObjectRoot: models.ObjectRoot{AggregateID: "ID"},
},
aggCreator: models.NewAggregateCreator("Test"),
},
res: res{
eventLen: 1,
eventTypes: []models.EventType{model.UserGrantReactivated},
},
},
{
name: "existing grant nil",
args: args{
ctx: authz.NewMockContext("orgID", "userID"),
existingGrant: nil,
aggCreator: models.NewAggregateCreator("Test"),
},
res: res{
errFunc: caos_errs.IsPreconditionFailed,
},
},
{
name: "grant nil",
args: args{
ctx: authz.NewMockContext("orgID", "userID"),
existingGrant: &model.UserGrant{ObjectRoot: models.ObjectRoot{AggregateID: "ID"}},
newGrant: nil,
aggCreator: models.NewAggregateCreator("Test"),
},
res: res{
errFunc: caos_errs.IsPreconditionFailed,
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
agg, err := UserGrantReactivatedAggregate(tt.args.aggCreator, tt.args.existingGrant, tt.args.newGrant)(tt.args.ctx)
if tt.res.errFunc == nil && len(agg.Events) != tt.res.eventLen {
t.Errorf("got wrong event len: expected: %v, actual: %v ", tt.res.eventLen, len(agg.Events))
}
for i := 0; i < tt.res.eventLen; i++ {
if tt.res.errFunc == nil && agg.Events[i].Type != tt.res.eventTypes[i] {
t.Errorf("got wrong event type: expected: %v, actual: %v ", tt.res.eventTypes[i], agg.Events[i].Type.String())
}
}
if tt.res.errFunc != nil && !tt.res.errFunc(err) {
t.Errorf("got wrong err: %v ", err)
}
})
}
}