Files
mostlymatter/app/authorization_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

211 строки
7.7 KiB
Go

// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
package app
import (
"context"
"encoding/csv"
"fmt"
"io/ioutil"
"os"
"strconv"
"strings"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/mattermost/mattermost-server/v6/model"
"github.com/mattermost/mattermost-server/v6/plugin/plugintest/mock"
"github.com/mattermost/mattermost-server/v6/store/storetest/mocks"
)
func TestCheckIfRolesGrantPermission(t *testing.T) {
th := Setup(t)
defer th.TearDown()
cases := []struct {
roles []string
permissionId string
shouldGrant bool
}{
{[]string{model.SystemAdminRoleId}, model.PermissionManageSystem.Id, true},
{[]string{model.SystemAdminRoleId}, "non-existent-permission", false},
{[]string{model.ChannelUserRoleId}, model.PermissionReadChannel.Id, true},
{[]string{model.ChannelUserRoleId}, model.PermissionManageSystem.Id, false},
{[]string{model.SystemAdminRoleId, model.ChannelUserRoleId}, model.PermissionManageSystem.Id, true},
{[]string{model.ChannelUserRoleId, model.SystemAdminRoleId}, model.PermissionManageSystem.Id, true},
{[]string{model.TeamUserRoleId, model.TeamAdminRoleId}, model.PermissionManageSlashCommands.Id, true},
{[]string{model.TeamAdminRoleId, model.TeamUserRoleId}, model.PermissionManageSlashCommands.Id, true},
}
for _, testcase := range cases {
require.Equal(t, th.App.RolesGrantPermission(testcase.roles, testcase.permissionId), testcase.shouldGrant)
}
}
func TestChannelRolesGrantPermission(t *testing.T) {
testPermissionInheritance(t, func(t *testing.T, th *TestHelper, testData permissionInheritanceTestData) {
require.Equal(t, testData.shouldHavePermission, th.App.RolesGrantPermission([]string{testData.channelRole.Name}, testData.permission.Id), "row: %+v\n", testData.truthTableRow)
})
}
func TestHasPermissionToTeam(t *testing.T) {
th := Setup(t).InitBasic()
defer th.TearDown()
assert.True(t, th.App.HasPermissionToTeam(th.BasicUser.Id, th.BasicTeam.Id, model.PermissionListTeamChannels))
th.RemoveUserFromTeam(th.BasicUser, th.BasicTeam)
assert.False(t, th.App.HasPermissionToTeam(th.BasicUser.Id, th.BasicTeam.Id, model.PermissionListTeamChannels))
assert.True(t, th.App.HasPermissionToTeam(th.SystemAdminUser.Id, th.BasicTeam.Id, model.PermissionListTeamChannels))
th.LinkUserToTeam(th.SystemAdminUser, th.BasicTeam)
assert.True(t, th.App.HasPermissionToTeam(th.SystemAdminUser.Id, th.BasicTeam.Id, model.PermissionListTeamChannels))
th.RemovePermissionFromRole(model.PermissionListTeamChannels.Id, model.TeamUserRoleId)
assert.True(t, th.App.HasPermissionToTeam(th.SystemAdminUser.Id, th.BasicTeam.Id, model.PermissionListTeamChannels))
th.RemoveUserFromTeam(th.SystemAdminUser, th.BasicTeam)
assert.True(t, th.App.HasPermissionToTeam(th.SystemAdminUser.Id, th.BasicTeam.Id, model.PermissionListTeamChannels))
}
func TestSessionHasPermissionToChannel(t *testing.T) {
th := Setup(t).InitBasic()
defer th.TearDown()
session := model.Session{
UserId: th.BasicUser.Id,
}
t.Run("basic user can access basic channel", func(t *testing.T) {
assert.True(t, th.App.SessionHasPermissionToChannel(session, th.BasicChannel.Id, model.PermissionAddReaction))
})
t.Run("does not panic if fetching channel causes an error", func(t *testing.T) {
// Regression test for MM-29812
// Mock the channel store so getting the channel returns with an error, as per the bug report.
mockStore := mocks.Store{}
mockChannelStore := mocks.ChannelStore{}
mockChannelStore.On("Get", mock.Anything, mock.Anything).Return(nil, fmt.Errorf("arbitrary error"))
mockChannelStore.On("GetAllChannelMembersForUser", mock.Anything, mock.Anything, mock.Anything).Return(th.App.Srv().Store.Channel().GetAllChannelMembersForUser(th.BasicUser.Id, false, false))
mockChannelStore.On("ClearCaches").Return()
mockStore.On("Channel").Return(&mockChannelStore)
mockStore.On("FileInfo").Return(th.App.Srv().Store.FileInfo())
mockStore.On("License").Return(th.App.Srv().Store.License())
mockStore.On("Post").Return(th.App.Srv().Store.Post())
mockStore.On("Role").Return(th.App.Srv().Store.Role())
mockStore.On("System").Return(th.App.Srv().Store.System())
mockStore.On("Team").Return(th.App.Srv().Store.Team())
mockStore.On("User").Return(th.App.Srv().Store.User())
mockStore.On("Webhook").Return(th.App.Srv().Store.Webhook())
mockStore.On("Close").Return(nil)
th.App.Srv().Store = &mockStore
// If there's an error returned from the GetChannel call the code should continue to cascade and since there
// are no session level permissions in this test case, the permission should be denied.
assert.False(t, th.App.SessionHasPermissionToChannel(session, th.BasicUser.Id, model.PermissionAddReaction))
})
}
func TestHasPermissionToCategory(t *testing.T) {
th := Setup(t).InitBasic()
defer th.TearDown()
session, err := th.App.CreateSession(&model.Session{UserId: th.BasicUser.Id, Props: model.StringMap{}})
require.Nil(t, err)
categories, err := th.App.GetSidebarCategories(th.BasicUser.Id, th.BasicTeam.Id)
require.Nil(t, err)
_, err = th.App.GetSession(session.Token)
require.Nil(t, err)
require.True(t, th.App.SessionHasPermissionToCategory(*session, th.BasicUser.Id, th.BasicTeam.Id, categories.Order[0]))
categories2, err := th.App.GetSidebarCategories(th.BasicUser2.Id, th.BasicTeam.Id)
require.Nil(t, err)
require.False(t, th.App.SessionHasPermissionToCategory(*session, th.BasicUser.Id, th.BasicTeam.Id, categories2.Order[0]))
}
func TestSessionHasPermissionToGroup(t *testing.T) {
th := Setup(t).InitBasic()
defer th.TearDown()
file, e := os.Open("tests/group-role-has-permission.csv")
require.NoError(t, e)
defer file.Close()
b, e := ioutil.ReadAll(file)
require.NoError(t, e)
r := csv.NewReader(strings.NewReader(string(b)))
records, e := r.ReadAll()
require.NoError(t, e)
systemRole, err := th.App.GetRoleByName(context.Background(), model.SystemUserRoleId)
require.Nil(t, err)
groupRole, err := th.App.GetRoleByName(context.Background(), model.CustomGroupUserRoleId)
require.Nil(t, err)
group, err := th.App.CreateGroup(&model.Group{
Name: model.NewString(model.NewId()),
DisplayName: model.NewId(),
Source: model.GroupSourceCustom,
AllowReference: true,
})
require.Nil(t, err)
permission := model.PermissionDeleteCustomGroup
for i, row := range records {
// skip csv header
if i == 0 {
continue
}
systemRoleHasPermission, e := strconv.ParseBool(row[0])
require.NoError(t, e)
isGroupMember, e := strconv.ParseBool(row[1])
require.NoError(t, e)
groupRoleHasPermission, e := strconv.ParseBool(row[2])
require.NoError(t, e)
permissionShouldBeGranted, e := strconv.ParseBool(row[3])
require.NoError(t, e)
if systemRoleHasPermission {
th.AddPermissionToRole(permission.Id, systemRole.Name)
} else {
th.RemovePermissionFromRole(permission.Id, systemRole.Name)
}
if isGroupMember {
_, err := th.App.UpsertGroupMember(group.Id, th.BasicUser.Id)
require.Nil(t, err)
} else {
_, err := th.App.DeleteGroupMember(group.Id, th.BasicUser.Id)
if err != nil && err.Id != "app.group.no_rows" {
t.Error(err)
}
}
if groupRoleHasPermission {
th.AddPermissionToRole(permission.Id, groupRole.Name)
} else {
th.RemovePermissionFromRole(permission.Id, groupRole.Name)
}
session, err := th.App.CreateSession(&model.Session{UserId: th.BasicUser.Id, Props: model.StringMap{}, Roles: systemRole.Name})
require.Nil(t, err)
result := th.App.SessionHasPermissionToGroup(*session, group.Id, permission)
if permissionShouldBeGranted {
require.True(t, result, fmt.Sprintf("row: %v", row))
} else {
require.False(t, result, fmt.Sprintf("row: %v", row))
}
}
}