Files
mostlymatter/app/app_test.go
mkraft 7fa6b321ae Custom groups (#18839)
* WIP

* adding initial creategroup endpoint

* fetching by group source

* fixing startup error

* updating create endpoint to take an array of user_ids, this will allow us to create the group with one request

* adding delete group endpoint and appropriate test

* adding source param for getGroups

* adding add members and delete members endpoints

* locking down crud endpoints to only be allowed for custom groups

* user search stuff

* allowing remoteid be null by changing field to pointer

* code cleanup and store level tests

* adding new tests and removing unused endpoint

* resolving conflicts

* Adds authz check for group.

* Adds authz checks to groups APIs.

* Updated create group authz tests.

* Updates delete group tests.

* Tests create group.

* Adds some tests and validations.

* adding new parameter so I can get users not in a group

* Fixed all lint warnings.

* Fix type.

* fixing search users not in group

* Fixes some lint errors.

* Moves entry in JSON array.

* Fixed SQL query.

* Fixes permission migration test.

* Fixes migration test.

* Fixes some group store tests.

* Fix test.

* Fix test.

* Revert lint change.

* Migrated CreateWithUserIds to sqlx.

* Adds tests for GetMember; migrates implementation to sqlx.

* Tests GetNonMemberUsersPage and hanles wrong group id.

* Fixes test.

* Switches GetMaster to GetMasterX.

* Switches GetReplica to GetReplicaX.

* Fixes logic.

* Fixes shadow declaration.

* Adds include_member_count to get group API endpoint.

* Adds filter_has_member param to getGroups.

* Fixes.

* Removes array of group sources.

* fixing error

* Testing reverting CreateWithUserIds back to gorp.

* Added websocket event for CreateGroupWithUserIds.

* Changed a few response status codes. Switched to correct permission.

* Added member count to ws payload for group when updating or creating.

* Adds feature flag checks for custom groups.

* Added middleware function to require license. Added config to disable custom groups.

* Change for function signature change of executePossiblyEmptyQuery.

* Lint fixes.

* Adds telemetry none comment.

* Adds translations.

* Migrated to sqlx.

* Temp. removal of translation.

* Fixed typo.

* Added an intermediary model to query with a field that is now ignored by sqlx on read queries.

* Re-used existing store struct.

* Inludes member count.

* Fix for merge error.'

* Require license for group endpoints.

* Updates translations.

* Fix shadow declaration.

* Renames permissions. Switches to new method to retrieve remoteid.

* Added WS events for upsert and delete member(s).

* Added new store error type ErrUniqueConstraint.

* Added EnableCustonGroups to the client config.

* Sanitized some user records.

* Added parameter to include_total_count for listing groups.

* Added translations.

* adding deleteAt field to getByUsers query

* Revert sanitize.

* Added uniqueness constraint error to UpdateGroup.

* Removed the FutureFeatures flag so that the feature is not enabled on old Enterprise licenses.

* Renamed function.

* Updates authz check for user search related to groups.

* Removed debug statement.

* Removed unused app method.

* Added telemetry for enable_custom_groups.

* Returns early from nil license.

* Updates test.

* Returned early to avoid nesting in (*SqlGroupStore).checkUserExist. Switched to reading from replica in (*SqlGroupStore).GetMember. Handled JSON marshal error in (*Client4).UpsertGroupMembers

* Switched to SanitizeProfile.

* Switched to model.NewInt.

* Switched from status NotImplemented to Forbidden for missing license.

* Removed deactivated users from 'exists' set.

* Revert gotool update.

* Ignored lint error that I think is invalid.

* Added the approprate access tag for disabling custom groups.

* Revert change to response status.

* Fixed refactor mistake.

* Limited the group member WS events to individual users.

* Removed WS event of deleted groups.

* Updated license check for searchUsers endpoint.

* Switched from license feature to license sku.

* Update app/group.go

Co-authored-by: Claudio Costa <cstcld91@gmail.com>

* Update app/group.go

Co-authored-by: Claudio Costa <cstcld91@gmail.com>

* Remove linter ignore comment.

* Added function to create sku-specific license.

* Fixed typo. Removed comment.

* Fixed for wrong type.

* Added missing param to client. Removed unnecessary props setting. Added test for retrieving groups by source.

* Updated some tests now that we're validating group membership not created for deactivated user.

* Fix for groups endpoint returning all group types by default.

* Changes constant names. Adds migration for all users to manage custom group members.

* Removes requirement for manage_system permission to filter user search by group.

* Added migration mock.

* Removes default permissions from custom_group_user role.

* Fixes migration.

* Fixes emoji migration test.

* fixing issue with member counts

* fixing search issue for deleted members

Co-authored-by: Benjamin Cooke <benjamincooke@Benjamins-MacBook-Pro.local>
Co-authored-by: Benjamin Cooke <benjamincooke@Benjamins-MBP.ht.home>
Co-authored-by: Mattermod <mattermod@users.noreply.github.com>
Co-authored-by: Benjamin Cooke <benjamincooke@Benjamins-MacBook-Pro.fritz.box>
Co-authored-by: Claudio Costa <cstcld91@gmail.com>
2022-02-17 12:34:39 -05:00

272 строки
8.5 KiB
Go

// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
package app
import (
"context"
"fmt"
"sort"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/mock"
"github.com/mattermost/mattermost-server/v6/model"
"github.com/mattermost/mattermost-server/v6/store/storetest/mocks"
)
/* Temporarily comment out until MM-11108
func TestAppRace(t *testing.T) {
for i := 0; i < 10; i++ {
a, err := New()
require.NoError(t, err)
a.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.ListenAddress = ":0" })
serverErr := a.StartServer()
require.NoError(t, serverErr)
a.Srv().Shutdown()
}
}
*/
var allPermissionIDs []string
func init() {
for _, perm := range model.AllPermissions {
allPermissionIDs = append(allPermissionIDs, perm.Id)
}
}
func TestUnitUpdateConfig(t *testing.T) {
th := SetupWithStoreMock(t)
defer th.TearDown()
mockStore := th.App.Srv().Store.(*mocks.Store)
mockUserStore := mocks.UserStore{}
mockUserStore.On("Count", mock.Anything).Return(int64(10), nil)
mockPostStore := mocks.PostStore{}
mockPostStore.On("GetMaxPostSize").Return(65535, nil)
mockSystemStore := mocks.SystemStore{}
mockSystemStore.On("GetByName", "UpgradedFromTE").Return(&model.System{Name: "UpgradedFromTE", Value: "false"}, nil)
mockSystemStore.On("GetByName", "InstallationDate").Return(&model.System{Name: "InstallationDate", Value: "10"}, nil)
mockSystemStore.On("GetByName", "FirstServerRunTimestamp").Return(&model.System{Name: "FirstServerRunTimestamp", Value: "10"}, nil)
mockLicenseStore := mocks.LicenseStore{}
mockLicenseStore.On("Get", "").Return(&model.LicenseRecord{}, nil)
mockStore.On("User").Return(&mockUserStore)
mockStore.On("Post").Return(&mockPostStore)
mockStore.On("System").Return(&mockSystemStore)
mockStore.On("License").Return(&mockLicenseStore)
prev := *th.App.Config().ServiceSettings.SiteURL
th.App.AddConfigListener(func(old, current *model.Config) {
assert.Equal(t, prev, *old.ServiceSettings.SiteURL)
assert.Equal(t, "http://foo.com", *current.ServiceSettings.SiteURL)
})
th.App.UpdateConfig(func(cfg *model.Config) {
*cfg.ServiceSettings.SiteURL = "http://foo.com"
})
}
func TestDoAdvancedPermissionsMigration(t *testing.T) {
th := Setup(t)
defer th.TearDown()
th.ResetRoleMigration()
th.App.DoAdvancedPermissionsMigration()
roleNames := []string{
"system_user",
"system_admin",
"team_user",
"team_admin",
"channel_user",
"channel_admin",
"system_post_all",
"system_post_all_public",
"system_user_access_token",
"team_post_all",
"team_post_all_public",
"playbook_admin",
"playbook_member",
"run_admin",
"run_member",
}
roles1, err1 := th.App.GetRolesByNames(roleNames)
assert.Nil(t, err1)
assert.Equal(t, len(roles1), len(roleNames))
expected1 := map[string][]string{
"channel_user": {
model.PermissionReadChannel.Id,
model.PermissionAddReaction.Id,
model.PermissionRemoveReaction.Id,
model.PermissionManagePublicChannelMembers.Id,
model.PermissionUploadFile.Id,
model.PermissionGetPublicLink.Id,
model.PermissionCreatePost.Id,
model.PermissionUseChannelMentions.Id,
model.PermissionUseSlashCommands.Id,
model.PermissionManagePublicChannelProperties.Id,
model.PermissionDeletePublicChannel.Id,
model.PermissionManagePrivateChannelProperties.Id,
model.PermissionDeletePrivateChannel.Id,
model.PermissionManagePrivateChannelMembers.Id,
model.PermissionDeletePost.Id,
model.PermissionEditPost.Id,
},
"channel_admin": {
model.PermissionManageChannelRoles.Id,
model.PermissionUseGroupMentions.Id,
},
"team_user": {
model.PermissionListTeamChannels.Id,
model.PermissionJoinPublicChannels.Id,
model.PermissionReadPublicChannel.Id,
model.PermissionViewTeam.Id,
model.PermissionCreatePublicChannel.Id,
model.PermissionCreatePrivateChannel.Id,
model.PermissionInviteUser.Id,
model.PermissionAddUserToTeam.Id,
},
"team_post_all": {
model.PermissionCreatePost.Id,
model.PermissionUseChannelMentions.Id,
},
"team_post_all_public": {
model.PermissionCreatePostPublic.Id,
model.PermissionUseChannelMentions.Id,
},
"team_admin": {
model.PermissionRemoveUserFromTeam.Id,
model.PermissionManageTeam.Id,
model.PermissionImportTeam.Id,
model.PermissionManageTeamRoles.Id,
model.PermissionManageChannelRoles.Id,
model.PermissionManageOthersIncomingWebhooks.Id,
model.PermissionManageOthersOutgoingWebhooks.Id,
model.PermissionManageSlashCommands.Id,
model.PermissionManageOthersSlashCommands.Id,
model.PermissionManageIncomingWebhooks.Id,
model.PermissionManageOutgoingWebhooks.Id,
model.PermissionConvertPublicChannelToPrivate.Id,
model.PermissionConvertPrivateChannelToPublic.Id,
model.PermissionDeletePost.Id,
model.PermissionDeleteOthersPosts.Id,
},
"system_user": {
model.PermissionListPublicTeams.Id,
model.PermissionJoinPublicTeams.Id,
model.PermissionCreateDirectChannel.Id,
model.PermissionCreateGroupChannel.Id,
model.PermissionViewMembers.Id,
model.PermissionCreateTeam.Id,
model.PermissionCreateCustomGroup.Id,
model.PermissionEditCustomGroup.Id,
model.PermissionDeleteCustomGroup.Id,
model.PermissionManageCustomGroupMembers.Id,
},
"system_post_all": {
model.PermissionCreatePost.Id,
model.PermissionUseChannelMentions.Id,
},
"system_post_all_public": {
model.PermissionCreatePostPublic.Id,
model.PermissionUseChannelMentions.Id,
},
"system_user_access_token": {
model.PermissionCreateUserAccessToken.Id,
model.PermissionReadUserAccessToken.Id,
model.PermissionRevokeUserAccessToken.Id,
},
"system_admin": allPermissionIDs,
}
assert.Contains(t, allPermissionIDs, model.PermissionManageSharedChannels.Id, "manage_shared_channels permission not found")
assert.Contains(t, allPermissionIDs, model.PermissionManageSecureConnections.Id, "manage_secure_connections permission not found")
// Check the migration matches what's expected.
for name, permissions := range expected1 {
role, err := th.App.GetRoleByName(context.Background(), name)
assert.Nil(t, err)
assert.Equal(t, role.Permissions, permissions, fmt.Sprintf("role %q didn't match", name))
}
th.App.Srv().SetLicense(model.NewTestLicense())
// Check the migration doesn't change anything if run again.
th.App.DoAdvancedPermissionsMigration()
roles2, err2 := th.App.GetRolesByNames(roleNames)
assert.Nil(t, err2)
assert.Equal(t, len(roles2), len(roleNames))
for name, permissions := range expected1 {
role, err := th.App.GetRoleByName(context.Background(), name)
assert.Nil(t, err)
assert.Equal(t, permissions, role.Permissions)
}
}
func TestDoEmojisPermissionsMigration(t *testing.T) {
th := SetupWithoutPreloadMigrations(t)
defer th.TearDown()
expectedSystemAdmin := allPermissionIDs
sort.Strings(expectedSystemAdmin)
th.ResetEmojisMigration()
th.App.DoEmojisPermissionsMigration()
role3, err3 := th.App.GetRoleByName(context.Background(), model.SystemUserRoleId)
assert.Nil(t, err3)
expected3 := []string{
model.PermissionCreateCustomGroup.Id,
model.PermissionEditCustomGroup.Id,
model.PermissionDeleteCustomGroup.Id,
model.PermissionManageCustomGroupMembers.Id,
model.PermissionListPublicTeams.Id,
model.PermissionJoinPublicTeams.Id,
model.PermissionCreateDirectChannel.Id,
model.PermissionCreateGroupChannel.Id,
model.PermissionCreateTeam.Id,
model.PermissionCreateEmojis.Id,
model.PermissionDeleteEmojis.Id,
model.PermissionViewMembers.Id,
}
sort.Strings(expected3)
sort.Strings(role3.Permissions)
assert.Equal(t, expected3, role3.Permissions, fmt.Sprintf("'%v' did not have expected permissions", model.SystemUserRoleId))
systemAdmin2, systemAdminErr2 := th.App.GetRoleByName(context.Background(), model.SystemAdminRoleId)
assert.Nil(t, systemAdminErr2)
sort.Strings(systemAdmin2.Permissions)
assert.Equal(t, expectedSystemAdmin, systemAdmin2.Permissions, fmt.Sprintf("'%v' did not have expected permissions", model.SystemAdminRoleId))
}
func TestDBHealthCheckWriteAndDelete(t *testing.T) {
th := Setup(t)
defer th.TearDown()
expectedKey := "health_check_" + th.App.GetClusterId()
assert.Equal(t, expectedKey, th.App.dbHealthCheckKey())
_, err := th.App.Srv().Store.System().GetByName(expectedKey)
assert.Error(t, err)
err = th.App.DBHealthCheckWrite()
assert.NoError(t, err)
systemVal, err := th.App.Srv().Store.System().GetByName(expectedKey)
assert.NoError(t, err)
assert.NotNil(t, systemVal)
err = th.App.DBHealthCheckDelete()
assert.NoError(t, err)
_, err = th.App.Srv().Store.System().GetByName(expectedKey)
assert.Error(t, err)
}