Alerting: Extract alerting rules authorization logic to a service (#77006)

* extract alerting authorization logic to separate package
* convert authorization logic to service
This commit is contained in:
Yuri Tseretyan
2023-11-15 18:54:54 +02:00
committed by GitHub
parent 441403729f
commit 7cec741bae
17 changed files with 734 additions and 612 deletions
@@ -0,0 +1,9 @@
package accesscontrol
import (
"errors"
)
var (
ErrAuthorization = errors.New("user is not authorized")
)
+152
View File
@@ -0,0 +1,152 @@
package accesscontrol
import (
"fmt"
"golang.org/x/net/context"
"github.com/grafana/grafana/pkg/expr"
"github.com/grafana/grafana/pkg/infra/log"
"github.com/grafana/grafana/pkg/services/accesscontrol"
"github.com/grafana/grafana/pkg/services/auth/identity"
"github.com/grafana/grafana/pkg/services/dashboards"
"github.com/grafana/grafana/pkg/services/datasources"
"github.com/grafana/grafana/pkg/services/ngalert/models"
"github.com/grafana/grafana/pkg/services/ngalert/store"
)
const (
ruleCreate = accesscontrol.ActionAlertingRuleCreate
ruleRead = accesscontrol.ActionAlertingRuleRead
ruleUpdate = accesscontrol.ActionAlertingRuleUpdate
ruleDelete = accesscontrol.ActionAlertingRuleDelete
)
var logger = log.New("ngalert.accesscontrol")
type RuleService struct {
ac accesscontrol.AccessControl
}
func NewRuleService(ac accesscontrol.AccessControl) *RuleService {
return &RuleService{
ac: ac,
}
}
// HasAccess returns true if the user has all permissions specified by the evaluator
func (r *RuleService) HasAccess(ctx context.Context, user identity.Requester, evaluator accesscontrol.Evaluator) bool {
result, err := r.ac.Evaluate(ctx, user, evaluator)
if err != nil { // this is how accesscontrol.HasAccess works. //TODO change when AuthorizeDatasourceAccessForRule can return errors
logger.FromContext(ctx).Error("Failed to evaluate access control", "error", err)
return false
}
return result
}
// AuthorizeDatasourceAccessForRule checks that user has access to all data sources declared by the rule
func (r *RuleService) AuthorizeDatasourceAccessForRule(ctx context.Context, user identity.Requester, rule *models.AlertRule) bool {
for _, query := range rule.Data {
if query.QueryType == expr.DatasourceType || query.DatasourceUID == expr.DatasourceUID || query.
DatasourceUID == expr.OldDatasourceUID {
continue
}
if !r.HasAccess(ctx, user, accesscontrol.EvalPermission(datasources.ActionQuery, datasources.ScopeProvider.GetResourceScopeUID(query.DatasourceUID))) {
return false
}
}
return true
}
// AuthorizeAccessToRuleGroup checks all rules against AuthorizeDatasourceAccessForRule and exits on the first negative result
func (r *RuleService) AuthorizeAccessToRuleGroup(ctx context.Context, user identity.Requester, rules models.RulesGroup) bool {
for _, rule := range rules {
if !r.AuthorizeDatasourceAccessForRule(ctx, user, rule) {
return false
}
}
return true
}
// AuthorizeRuleChanges analyzes changes in the rule group, and checks whether the changes are authorized.
// NOTE: if there are rules for deletion, and the user does not have access to data sources that a rule uses, the rule is removed from the list.
// If the user is not authorized to perform the changes the function returns ErrAuthorization with a description of what action is not authorized.
// Return changes that the user is authorized to perform or ErrAuthorization
func (r *RuleService) AuthorizeRuleChanges(ctx context.Context, user identity.Requester, change *store.GroupDelta) error {
namespaceScope := dashboards.ScopeFoldersProvider.GetResourceScopeUID(change.GroupKey.NamespaceUID)
rules, ok := change.AffectedGroups[change.GroupKey]
if ok { // not ok can be when user creates a new rule group or moves existing alerts to a new group
if !r.AuthorizeAccessToRuleGroup(ctx, user, rules) { // if user is not authorized to do operation in the group that is being changed
return fmt.Errorf("%w to change group %s because it does not have access to one or many rules in this group", ErrAuthorization, change.GroupKey.RuleGroup)
}
} else if len(change.Delete) > 0 {
// add a safeguard in the case of inconsistency. If user hit this then there is a bug in the calculating of changes struct
return fmt.Errorf("failed to authorize changes in rule group %s. Detected %d deletes but group was not provided", change.GroupKey.RuleGroup, len(change.Delete))
}
if len(change.Delete) > 0 {
allowed := r.HasAccess(ctx, user, accesscontrol.EvalPermission(ruleDelete, namespaceScope))
if !allowed {
return fmt.Errorf("%w to delete alert rules that belong to folder %s", ErrAuthorization, change.GroupKey.NamespaceUID)
}
for _, rule := range change.Delete {
if !r.AuthorizeDatasourceAccessForRule(ctx, user, rule) {
return fmt.Errorf("%w to delete an alert rule '%s' because the user does not have read permissions for one or many datasources the rule uses", ErrAuthorization, rule.UID)
}
}
}
var addAuthorized, updateAuthorized bool
if len(change.New) > 0 {
addAuthorized = r.HasAccess(ctx, user, accesscontrol.EvalPermission(ruleCreate, namespaceScope))
if !addAuthorized {
return fmt.Errorf("%w to create alert rules in the folder %s", ErrAuthorization, change.GroupKey.NamespaceUID)
}
for _, rule := range change.New {
if !r.AuthorizeDatasourceAccessForRule(ctx, user, rule) {
return fmt.Errorf("%w to create a new alert rule '%s' because the user does not have read permissions for one or many datasources the rule uses", ErrAuthorization, rule.Title)
}
}
}
for _, rule := range change.Update {
if !r.AuthorizeDatasourceAccessForRule(ctx, user, rule.New) {
return fmt.Errorf("%w to update alert rule '%s' (UID: %s) because the user does not have read permissions for one or many datasources the rule uses", ErrAuthorization, rule.Existing.Title, rule.Existing.UID)
}
// Check if the rule is moved from one folder to the current. If yes, then the user must have the authorization to delete rules from the source folder and add rules to the target folder.
if rule.Existing.NamespaceUID != rule.New.NamespaceUID {
allowed := r.HasAccess(ctx, user, accesscontrol.EvalPermission(ruleDelete, dashboards.ScopeFoldersProvider.GetResourceScopeUID(rule.Existing.NamespaceUID)))
if !allowed {
return fmt.Errorf("%w to delete alert rules from folder UID %s", ErrAuthorization, rule.Existing.NamespaceUID)
}
if !addAuthorized {
addAuthorized = r.HasAccess(ctx, user, accesscontrol.EvalPermission(ruleCreate, namespaceScope))
if !addAuthorized {
return fmt.Errorf("%w to create alert rules in the folder '%s'", ErrAuthorization, change.GroupKey.NamespaceUID)
}
}
} else if !updateAuthorized { // if it is false then the authorization was not checked. If it is true then the user is authorized to update rules
updateAuthorized = r.HasAccess(ctx, user, accesscontrol.EvalPermission(ruleUpdate, namespaceScope))
if !updateAuthorized {
return fmt.Errorf("%w to update alert rules that belong to folder %s", ErrAuthorization, change.GroupKey.NamespaceUID)
}
}
if rule.Existing.NamespaceUID != rule.New.NamespaceUID || rule.Existing.RuleGroup != rule.New.RuleGroup {
key := rule.Existing.GetGroupKey()
rules, ok = change.AffectedGroups[key]
if !ok {
// add a safeguard in the case of inconsistency. If user hit this then there is a bug in the calculating of changes struct
return fmt.Errorf("failed to authorize moving an alert rule %s between groups because unable to check access to group %s from which the rule is moved", rule.Existing.UID, rule.Existing.RuleGroup)
}
if !r.AuthorizeAccessToRuleGroup(ctx, user, rules) {
return fmt.Errorf("%w to move rule %s between two different groups because user does not have access to the source group %s", ErrAuthorization, rule.Existing.UID, rule.Existing.RuleGroup)
}
}
}
return nil
}
@@ -0,0 +1,458 @@
package accesscontrol
import (
"context"
"math"
"math/rand"
"testing"
"github.com/stretchr/testify/require"
"github.com/grafana/grafana/pkg/expr"
"github.com/grafana/grafana/pkg/services/accesscontrol"
"github.com/grafana/grafana/pkg/services/auth/identity"
"github.com/grafana/grafana/pkg/services/dashboards"
"github.com/grafana/grafana/pkg/services/datasources"
"github.com/grafana/grafana/pkg/services/ngalert/models"
"github.com/grafana/grafana/pkg/services/ngalert/store"
"github.com/grafana/grafana/pkg/services/user"
"github.com/grafana/grafana/pkg/util"
)
func createAllCombinationsOfPermissions(permissions map[string][]string) []map[string][]string {
type actionscope struct {
action string
scope string
}
var flattenPermissions []actionscope
for action, scopes := range permissions {
for _, scope := range scopes {
flattenPermissions = append(flattenPermissions, actionscope{
action,
scope,
})
}
}
l := len(flattenPermissions)
// this is all possible combinations of the permissions
var permissionCombinations []map[string][]string
for bit := uint(0); bit < uint(math.Pow(2, float64(l))); bit++ {
var tuple []actionscope
for idx := 0; idx < l; idx++ {
if (bit>>idx)&1 == 1 {
tuple = append(tuple, flattenPermissions[idx])
}
}
combination := make(map[string][]string)
for _, perm := range tuple {
combination[perm.action] = append(combination[perm.action], perm.scope)
}
permissionCombinations = append(permissionCombinations, combination)
}
return permissionCombinations
}
func getDatasourceScopesForRules(rules models.RulesGroup) []string {
scopesMap := map[string]struct{}{}
var result []string
for _, rule := range rules {
for _, query := range rule.Data {
scope := datasources.ScopeProvider.GetResourceScopeUID(query.DatasourceUID)
if _, ok := scopesMap[scope]; ok {
continue
}
result = append(result, scope)
scopesMap[scope] = struct{}{}
}
}
return result
}
func mapUpdates(updates []store.RuleDelta, mapFunc func(store.RuleDelta) *models.AlertRule) models.RulesGroup {
result := make(models.RulesGroup, 0, len(updates))
for _, update := range updates {
result = append(result, mapFunc(update))
}
return result
}
func createUserWithPermissions(permissions map[string][]string) identity.Requester {
return &user.SignedInUser{OrgID: 1, Permissions: map[int64]map[string][]string{
1: permissions,
}}
}
func TestAuthorizeRuleChanges(t *testing.T) {
groupKey := models.GenerateGroupKey(rand.Int63())
namespaceIdScope := dashboards.ScopeFoldersProvider.GetResourceScopeUID(groupKey.NamespaceUID)
testCases := []struct {
name string
changes func() *store.GroupDelta
permissions func(c *store.GroupDelta) map[string][]string
}{
{
name: "if there are rules to add it should check create action and query for datasource",
changes: func() *store.GroupDelta {
return &store.GroupDelta{
GroupKey: groupKey,
New: models.GenerateAlertRules(rand.Intn(4)+1, models.AlertRuleGen(models.WithGroupKey(groupKey))),
Update: nil,
Delete: nil,
}
},
permissions: func(c *store.GroupDelta) map[string][]string {
var scopes []string
for _, rule := range c.New {
for _, query := range rule.Data {
scopes = append(scopes, datasources.ScopeProvider.GetResourceScopeUID(query.DatasourceUID))
}
}
return map[string][]string{
ruleCreate: {
namespaceIdScope,
},
datasources.ActionQuery: scopes,
}
},
},
{
name: "if there are rules to delete it should check delete action and query for datasource",
changes: func() *store.GroupDelta {
rules := models.GenerateAlertRules(rand.Intn(4)+1, models.AlertRuleGen(models.WithGroupKey(groupKey)))
rules2 := models.GenerateAlertRules(rand.Intn(4)+1, models.AlertRuleGen(models.WithGroupKey(groupKey)))
return &store.GroupDelta{
GroupKey: groupKey,
AffectedGroups: map[models.AlertRuleGroupKey]models.RulesGroup{
groupKey: append(rules, rules2...),
},
New: nil,
Update: nil,
Delete: rules2,
}
},
permissions: func(c *store.GroupDelta) map[string][]string {
return map[string][]string{
ruleDelete: {
namespaceIdScope,
},
datasources.ActionQuery: getDatasourceScopesForRules(c.AffectedGroups[c.GroupKey]),
}
},
},
{
name: "if there are rules to update within the same namespace it should check update action and access to datasource",
changes: func() *store.GroupDelta {
rules1 := models.GenerateAlertRules(rand.Intn(4)+1, models.AlertRuleGen(models.WithGroupKey(groupKey)))
rules := models.GenerateAlertRules(rand.Intn(4)+1, models.AlertRuleGen(models.WithGroupKey(groupKey)))
updates := make([]store.RuleDelta, 0, len(rules))
for _, rule := range rules {
cp := models.CopyRule(rule)
cp.Data = []models.AlertQuery{models.GenerateAlertQuery()}
updates = append(updates, store.RuleDelta{
Existing: rule,
New: cp,
Diff: nil,
})
}
return &store.GroupDelta{
GroupKey: groupKey,
AffectedGroups: map[models.AlertRuleGroupKey]models.RulesGroup{
groupKey: append(rules, rules1...),
},
New: nil,
Update: updates,
Delete: nil,
}
},
permissions: func(c *store.GroupDelta) map[string][]string {
scopes := getDatasourceScopesForRules(append(c.AffectedGroups[c.GroupKey], mapUpdates(c.Update, func(update store.RuleDelta) *models.AlertRule {
return update.New
})...))
return map[string][]string{
ruleUpdate: {
namespaceIdScope,
},
datasources.ActionQuery: scopes,
}
},
},
{
name: "if there are rules that are moved between namespaces it should check delete+add action and access to group where rules come from",
changes: func() *store.GroupDelta {
rules1 := models.GenerateAlertRules(rand.Intn(4)+1, models.AlertRuleGen(models.WithGroupKey(groupKey)))
rules := models.GenerateAlertRules(rand.Intn(4)+1, models.AlertRuleGen(models.WithGroupKey(groupKey)))
targetGroupKey := models.GenerateGroupKey(groupKey.OrgID)
updates := make([]store.RuleDelta, 0, len(rules))
for _, rule := range rules {
cp := models.CopyRule(rule)
models.WithGroupKey(targetGroupKey)(cp)
cp.Data = []models.AlertQuery{
models.GenerateAlertQuery(),
}
updates = append(updates, store.RuleDelta{
Existing: rule,
New: cp,
})
}
return &store.GroupDelta{
GroupKey: targetGroupKey,
AffectedGroups: map[models.AlertRuleGroupKey]models.RulesGroup{
groupKey: append(rules, rules1...),
},
New: nil,
Update: updates,
Delete: nil,
}
},
permissions: func(c *store.GroupDelta) map[string][]string {
dsScopes := getDatasourceScopesForRules(
append(append(append(c.AffectedGroups[c.GroupKey],
mapUpdates(c.Update, func(update store.RuleDelta) *models.AlertRule {
return update.New
})...,
), mapUpdates(c.Update, func(update store.RuleDelta) *models.AlertRule {
return update.Existing
})...), c.AffectedGroups[groupKey]...),
)
var deleteScopes []string
for key := range c.AffectedGroups {
deleteScopes = append(deleteScopes, dashboards.ScopeFoldersProvider.GetResourceScopeUID(key.NamespaceUID))
}
return map[string][]string{
ruleDelete: deleteScopes,
ruleCreate: {
dashboards.ScopeFoldersProvider.GetResourceScopeUID(c.GroupKey.NamespaceUID),
},
datasources.ActionQuery: dsScopes,
}
},
},
{
name: "if there are rules that are moved between groups in the same namespace it should check update action and access to all groups (source+target)",
changes: func() *store.GroupDelta {
targetGroupKey := models.AlertRuleGroupKey{
OrgID: groupKey.OrgID,
NamespaceUID: groupKey.NamespaceUID,
RuleGroup: util.GenerateShortUID(),
}
sourceGroup := models.GenerateAlertRules(rand.Intn(4)+1, models.AlertRuleGen(models.WithGroupKey(groupKey)))
targetGroup := models.GenerateAlertRules(rand.Intn(4)+1, models.AlertRuleGen(models.WithGroupKey(targetGroupKey)))
updates := make([]store.RuleDelta, 0, len(sourceGroup))
toCopy := len(sourceGroup)
if toCopy > 1 {
toCopy = rand.Intn(toCopy-1) + 1
}
for i := 0; i < toCopy; i++ {
rule := sourceGroup[0]
cp := models.CopyRule(rule)
models.WithGroupKey(targetGroupKey)(cp)
cp.Data = []models.AlertQuery{
models.GenerateAlertQuery(),
}
updates = append(updates, store.RuleDelta{
Existing: rule,
New: cp,
})
}
return &store.GroupDelta{
GroupKey: targetGroupKey,
AffectedGroups: map[models.AlertRuleGroupKey]models.RulesGroup{
groupKey: sourceGroup,
targetGroupKey: targetGroup,
},
New: nil,
Update: updates,
Delete: nil,
}
},
permissions: func(c *store.GroupDelta) map[string][]string {
scopes := make(map[string]struct{})
for _, update := range c.Update {
for _, query := range update.New.Data {
scopes[datasources.ScopeProvider.GetResourceScopeUID(query.DatasourceUID)] = struct{}{}
}
for _, query := range update.Existing.Data {
scopes[datasources.ScopeProvider.GetResourceScopeUID(query.DatasourceUID)] = struct{}{}
}
}
for _, rules := range c.AffectedGroups {
for _, rule := range rules {
for _, query := range rule.Data {
scopes[datasources.ScopeProvider.GetResourceScopeUID(query.DatasourceUID)] = struct{}{}
}
}
}
dsScopes := make([]string, 0, len(scopes))
for key := range scopes {
dsScopes = append(dsScopes, key)
}
return map[string][]string{
ruleUpdate: {
dashboards.ScopeFoldersProvider.GetResourceScopeUID(c.GroupKey.NamespaceUID),
},
datasources.ActionQuery: dsScopes,
}
},
},
}
for _, testCase := range testCases {
t.Run(testCase.name, func(t *testing.T) {
groupChanges := testCase.changes()
permissions := testCase.permissions(groupChanges)
t.Run("should fail with insufficient permissions", func(t *testing.T) {
permissionCombinations := createAllCombinationsOfPermissions(permissions)
permissionCombinations = permissionCombinations[0 : len(permissionCombinations)-1] // exclude all permissions
for _, missing := range permissionCombinations {
ac := &recordingAccessControlFake{}
srv := RuleService{
ac: ac,
}
err := srv.AuthorizeRuleChanges(context.Background(), createUserWithPermissions(missing), groupChanges)
require.Errorf(t, err, "expected error because less permissions than expected were provided. Provided: %v; Expected: %v", missing, permissions)
require.ErrorIs(t, err, ErrAuthorization)
require.NotEmptyf(t, ac.EvaluateRecordings, "Access control was supposed to be called but it was not")
}
})
ac := &recordingAccessControlFake{
Callback: func(user identity.Requester, evaluator accesscontrol.Evaluator) (bool, error) {
response := evaluator.Evaluate(user.GetPermissions())
require.Truef(t, response, "provided permissions [%v] is not enough for requested permissions [%s]", permissions, evaluator.GoString())
return response, nil
},
}
srv := RuleService{
ac: ac,
}
err := srv.AuthorizeRuleChanges(context.Background(), createUserWithPermissions(permissions), groupChanges)
require.NoError(t, err)
require.NotEmptyf(t, ac.EvaluateRecordings, "evaluation function is expected to be called but it was not.")
})
}
}
func TestCheckDatasourcePermissionsForRule(t *testing.T) {
rule := models.AlertRuleGen()()
expressionByType := models.GenerateAlertQuery()
expressionByType.QueryType = expr.DatasourceType
expressionByUID := models.GenerateAlertQuery()
expressionByUID.DatasourceUID = expr.DatasourceUID
var data []models.AlertQuery
var scopes []string
expectedExecutions := rand.Intn(3) + 2
for i := 0; i < expectedExecutions; i++ {
q := models.GenerateAlertQuery()
scopes = append(scopes, datasources.ScopeProvider.GetResourceScopeUID(q.DatasourceUID))
data = append(data, q)
}
data = append(data, expressionByType, expressionByUID)
rand.Shuffle(len(data), func(i, j int) {
data[j], data[i] = data[i], data[j]
})
rule.Data = data
t.Run("should check only expressions", func(t *testing.T) {
permissions := map[string][]string{
datasources.ActionQuery: scopes,
}
ac := &recordingAccessControlFake{}
svc := RuleService{
ac: ac,
}
eval := svc.AuthorizeDatasourceAccessForRule(context.Background(), createUserWithPermissions(permissions), rule)
require.True(t, eval)
require.Len(t, ac.EvaluateRecordings, expectedExecutions)
})
t.Run("should return on first negative evaluation", func(t *testing.T) {
ac := &recordingAccessControlFake{
Callback: func(user identity.Requester, evaluator accesscontrol.Evaluator) (bool, error) {
return false, nil
},
}
svc := RuleService{
ac: ac,
}
eval := svc.AuthorizeDatasourceAccessForRule(context.Background(), createUserWithPermissions(nil), rule)
require.False(t, eval)
require.Len(t, ac.EvaluateRecordings, 1)
})
}
func Test_authorizeAccessToRuleGroup(t *testing.T) {
t.Run("should return true if user has access to all datasources of all rules in group", func(t *testing.T) {
rules := models.GenerateAlertRules(rand.Intn(4)+1, models.AlertRuleGen())
var scopes []string
for _, rule := range rules {
for _, query := range rule.Data {
scopes = append(scopes, datasources.ScopeProvider.GetResourceScopeUID(query.DatasourceUID))
}
}
permissions := map[string][]string{
datasources.ActionQuery: scopes,
}
ac := &recordingAccessControlFake{}
svc := RuleService{
ac: ac,
}
result := svc.AuthorizeAccessToRuleGroup(context.Background(), createUserWithPermissions(permissions), rules)
require.True(t, result)
require.NotEmpty(t, ac.EvaluateRecordings)
})
t.Run("should return false if user does not have access to at least one rule in group", func(t *testing.T) {
rules := models.GenerateAlertRules(rand.Intn(4)+1, models.AlertRuleGen())
var scopes []string
for _, rule := range rules {
for _, query := range rule.Data {
scopes = append(scopes, datasources.ScopeProvider.GetResourceScopeUID(query.DatasourceUID))
}
}
permissions := map[string][]string{
datasources.ActionQuery: scopes,
}
rule := models.AlertRuleGen()()
rules = append(rules, rule)
ac := &recordingAccessControlFake{}
svc := RuleService{
ac: ac,
}
result := svc.AuthorizeAccessToRuleGroup(context.Background(), createUserWithPermissions(permissions), rules)
require.False(t, result)
})
}
@@ -0,0 +1,39 @@
package accesscontrol
import (
"context"
"github.com/grafana/grafana/pkg/services/accesscontrol"
"github.com/grafana/grafana/pkg/services/auth/identity"
)
type recordingAccessControlFake struct {
Disabled bool
EvaluateRecordings []struct {
Permissions map[string][]string
Evaluator accesscontrol.Evaluator
}
Callback func(user identity.Requester, evaluator accesscontrol.Evaluator) (bool, error)
}
func (a *recordingAccessControlFake) Evaluate(_ context.Context, ur identity.Requester, evaluator accesscontrol.Evaluator) (bool, error) {
a.EvaluateRecordings = append(a.EvaluateRecordings, struct {
Permissions map[string][]string
Evaluator accesscontrol.Evaluator
}{Permissions: ur.GetPermissions(), Evaluator: evaluator})
if a.Callback == nil {
return evaluator.Evaluate(ur.GetPermissions()), nil
}
return a.Callback(ur, evaluator)
}
func (a *recordingAccessControlFake) RegisterScopeAttributeResolver(prefix string, resolver accesscontrol.ScopeAttributeResolver) {
// TODO implement me
panic("implement me")
}
func (a *recordingAccessControlFake) IsDisabled() bool {
return a.Disabled
}
var _ accesscontrol.AccessControl = &recordingAccessControlFake{}