grafana/pkg/services/accesscontrol/roles_test.go
Gabriel MABILLE 88c11f1cc0
AccessControl: Implement a way to register fixed roles (#35641)
* AccessControl: Implement a way to register fixed roles

* Add context to register func

* Use FixedRoleGrantsMap instead of FixedRoleGrants

* Removed FixedRoles map to sync.map


* Wrote test for accesscontrol and provisioning

* Use mutexes+map instead of sync maps

* Create a sync map struct out of a Map and a Mutex

* Create a sync map struct for grants as well

* Validate builtin roles

* Make validation public to access control

* Handle errors consistently with what seeder does

* Keep errors consistant amongst accesscontrol impl

* Handle registration error

* Reverse the registration direction thanks to a RoleRegistrant interface

* Removed sync map in favor for simple maps since registration now happens during init

* Work on the Registrant interface

* Remove the Register Role from the interface to have services returning their registrations instead

* Adding context to RegisterRegistrantsRoles and update descriptions

* little bit of cosmetics

* Making sure provisioning is ran after role registration

* test for role registration

* Change the accesscontrol interface to use a variadic

* check if accesscontrol is enabled

* Add a new test for RegisterFixedRoles and fix assign which was buggy

* Moved RegistrationList def to roles.go

* Change provisioning role's description

* Better comment on RegisterFixedRoles

* Correct comment on ValidateFixedRole

* Simplify helper func to removeRoleHelper

* Add log to saveFixedRole and assignFixedRole

Co-authored-by: Vardan Torosyan <vardants@gmail.com>
Co-authored-by: Jeremy Price <Jeremy.price@grafana.com>
2021-07-30 09:52:09 +02:00

75 lines
1.3 KiB
Go

package accesscontrol
import (
"sort"
"strings"
"testing"
"github.com/stretchr/testify/assert"
)
func TestPredefinedRoles(t *testing.T) {
for name, role := range FixedRoles {
assert.Truef(t,
strings.HasPrefix(name, "fixed:"),
"expected all fixed roles to be prefixed by 'fixed:', found role '%s'", name,
)
assert.Equal(t, name, role.Name)
assert.NotZero(t, role.Version)
}
}
func TestPredefinedRoleGrants(t *testing.T) {
for _, grants := range FixedRoleGrants {
// Check grants list is sorted
assert.True(t,
sort.SliceIsSorted(grants, func(i, j int) bool {
return grants[i] < grants[j]
}),
"require role grant lists to be sorted",
)
// Check all granted roles have been registered
for _, r := range grants {
assert.Contains(t, FixedRoles, r)
}
}
}
func TestConcatPermissions(t *testing.T) {
perms1 := []Permission{
{
Action: "test",
Scope: "test:*",
},
{
Action: "test1",
Scope: "test1:*",
},
}
perms2 := []Permission{
{
Action: "test1",
Scope: "*",
},
}
expected := []Permission{
{
Action: "test",
Scope: "test:*",
},
{
Action: "test1",
Scope: "test1:*",
},
{
Action: "test1",
Scope: "*",
},
}
perms := ConcatPermissions(perms1, perms2)
assert.ElementsMatch(t, perms, expected)
}