Annotations: Lift parts of RBAC from xorm store into auth service (#76967)

* [WIP] Lift RBAC from xorm store

* Cleanup RBAC, fix tests

* Use the scope type map as a map
* Remove dependency on dashboard service
* Make dashboards a map for constant time lookups (useful later)
---
* Lift RBAC tests into a new file to test at service level
* Add necessary access resource structs to xorm store tests

* Move authorization into separate service

* Pass features to searchstore.Builder

* Sort imports

* Code cleanup

* Remove useless scope type check

* Lift permission check into `Authorize()`

* Use clearer language when checking scope types

* Include dashboard permissions in test to ensure they're ignored

* Switch to errutil

* Cleanup sql.Cfg refs
This commit is contained in:
William Wernert
2023-11-14 18:11:01 -05:00
committed by GitHub
parent 2b1e731c15
commit 1a53a716e9
12 changed files with 922 additions and 537 deletions

View File

@@ -0,0 +1,125 @@
package accesscontrol
import (
"context"
"github.com/grafana/grafana/pkg/infra/db"
ac "github.com/grafana/grafana/pkg/services/accesscontrol"
"github.com/grafana/grafana/pkg/services/annotations"
"github.com/grafana/grafana/pkg/services/auth/identity"
"github.com/grafana/grafana/pkg/services/dashboards"
"github.com/grafana/grafana/pkg/services/featuremgmt"
"github.com/grafana/grafana/pkg/services/sqlstore/permissions"
"github.com/grafana/grafana/pkg/services/sqlstore/searchstore"
"github.com/grafana/grafana/pkg/util/errutil"
)
var (
ErrReadForbidden = errutil.NewBase(
errutil.StatusForbidden,
"annotations.accesscontrol.read",
errutil.WithPublicMessage("User missing permissions"),
)
ErrAccessControlInternal = errutil.NewBase(
errutil.StatusInternal,
"annotations.accesscontrol.internal",
errutil.WithPublicMessage("Internal error while checking permissions"),
)
)
type AuthService struct {
db db.DB
features featuremgmt.FeatureToggles
}
func NewAuthService(db db.DB, features featuremgmt.FeatureToggles) *AuthService {
return &AuthService{
db: db,
features: features,
}
}
// Authorize checks if the user has permission to read annotations, then returns a struct containing dashboards and scope types that the user has access to.
func (authz *AuthService) Authorize(ctx context.Context, orgID int64, user identity.Requester) (*AccessResources, error) {
if user == nil || user.IsNil() {
return nil, ErrReadForbidden.Errorf("missing user")
}
scopes, has := user.GetPermissions()[ac.ActionAnnotationsRead]
if !has {
return nil, ErrReadForbidden.Errorf("user does not have permission to read annotations")
}
scopeTypes := annotationScopeTypes(scopes)
var visibleDashboards map[string]int64
var err error
if _, ok := scopeTypes[annotations.Dashboard.String()]; ok {
visibleDashboards, err = authz.userVisibleDashboards(ctx, user, orgID)
if err != nil {
return nil, ErrAccessControlInternal.Errorf("failed to fetch dashboards: %w", err)
}
}
return &AccessResources{
Dashboards: visibleDashboards,
ScopeTypes: scopeTypes,
}, nil
}
func (authz *AuthService) userVisibleDashboards(ctx context.Context, user identity.Requester, orgID int64) (map[string]int64, error) {
recursiveQueriesSupported, err := authz.db.RecursiveQueriesAreSupported()
if err != nil {
return nil, err
}
filters := []any{
permissions.NewAccessControlDashboardPermissionFilter(user, dashboards.PERMISSION_VIEW, searchstore.TypeDashboard, authz.features, recursiveQueriesSupported),
searchstore.OrgFilter{OrgId: orgID},
}
sb := &searchstore.Builder{Dialect: authz.db.GetDialect(), Filters: filters, Features: authz.features}
visibleDashboards := make(map[string]int64)
var page int64 = 1
var limit int64 = 1000
for {
var res []dashboardProjection
sql, params := sb.ToSQL(limit, page)
err = authz.db.WithDbSession(ctx, func(sess *db.Session) error {
return sess.SQL(sql, params...).Find(&res)
})
if err != nil {
return nil, err
}
for _, p := range res {
visibleDashboards[p.UID] = p.ID
}
// if the result is less than the limit, we have reached the end
if len(res) < int(limit) {
break
}
page++
}
return visibleDashboards, nil
}
func annotationScopeTypes(scopes []string) map[any]struct{} {
allScopeTypes := map[any]struct{}{
annotations.Dashboard.String(): {},
annotations.Organization.String(): {},
}
types, hasWildcardScope := ac.ParseScopes(ac.ScopeAnnotationsProvider.GetResourceScopeType(""), scopes)
if hasWildcardScope {
types = allScopeTypes
}
return types
}

View File

@@ -0,0 +1,130 @@
package accesscontrol
import (
"context"
"fmt"
"testing"
"github.com/grafana/grafana/pkg/components/simplejson"
"github.com/grafana/grafana/pkg/infra/db"
"github.com/grafana/grafana/pkg/services/accesscontrol"
"github.com/grafana/grafana/pkg/services/annotations"
"github.com/grafana/grafana/pkg/services/annotations/testutil"
"github.com/grafana/grafana/pkg/services/dashboards"
"github.com/grafana/grafana/pkg/services/featuremgmt"
"github.com/grafana/grafana/pkg/services/user"
"github.com/stretchr/testify/require"
)
var (
dashScopeType = annotations.Dashboard.String()
orgScopeType = annotations.Organization.String()
)
func TestIntegrationAuthorize(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test")
}
sql := db.InitTestDB(t)
authz := NewAuthService(sql, featuremgmt.WithFeatures())
dash1 := testutil.CreateDashboard(t, sql, featuremgmt.WithFeatures(), dashboards.SaveDashboardCommand{
UserID: 1,
OrgID: 1,
Dashboard: simplejson.NewFromAny(map[string]any{
"title": "Dashboard 1",
}),
})
dash2 := testutil.CreateDashboard(t, sql, featuremgmt.WithFeatures(), dashboards.SaveDashboardCommand{
UserID: 1,
OrgID: 1,
Dashboard: simplejson.NewFromAny(map[string]any{
"title": "Dashboard 2",
}),
})
u := &user.SignedInUser{
UserID: 1,
OrgID: 1,
}
role := testutil.SetupRBACRole(t, sql, u)
type testCase struct {
name string
permissions map[string][]string
expectedResources *AccessResources
expectedErr error
}
testCases := []testCase{
{
name: "should have both scopes and all dashboards",
permissions: map[string][]string{
accesscontrol.ActionAnnotationsRead: {accesscontrol.ScopeAnnotationsAll},
dashboards.ActionDashboardsRead: {dashboards.ScopeDashboardsAll},
},
expectedResources: &AccessResources{
Dashboards: map[string]int64{dash1.UID: dash1.ID, dash2.UID: dash2.ID},
ScopeTypes: map[any]struct{}{dashScopeType: {}, orgScopeType: {}},
},
},
{
name: "should have only organization scope and no dashboards",
permissions: map[string][]string{
accesscontrol.ActionAnnotationsRead: {accesscontrol.ScopeAnnotationsTypeOrganization},
dashboards.ActionDashboardsRead: {dashboards.ScopeDashboardsAll},
},
expectedResources: &AccessResources{
Dashboards: nil,
ScopeTypes: map[any]struct{}{orgScopeType: {}},
},
},
{
name: "should have only dashboard scope and all dashboards",
permissions: map[string][]string{
accesscontrol.ActionAnnotationsRead: {accesscontrol.ScopeAnnotationsTypeDashboard},
dashboards.ActionDashboardsRead: {dashboards.ScopeDashboardsAll},
},
expectedResources: &AccessResources{
Dashboards: map[string]int64{dash1.UID: dash1.ID, dash2.UID: dash2.ID},
ScopeTypes: map[any]struct{}{dashScopeType: {}},
},
},
{
name: "should have only dashboard scope and only dashboard 1",
permissions: map[string][]string{
accesscontrol.ActionAnnotationsRead: {accesscontrol.ScopeAnnotationsTypeDashboard},
dashboards.ActionDashboardsRead: {fmt.Sprintf("dashboards:uid:%s", dash1.UID)},
},
expectedResources: &AccessResources{
Dashboards: map[string]int64{dash1.UID: dash1.ID},
ScopeTypes: map[any]struct{}{dashScopeType: {}},
},
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
u.Permissions = map[int64]map[string][]string{1: tc.permissions}
testutil.SetupRBACPermission(t, sql, role, u)
resources, err := authz.Authorize(context.Background(), 1, u)
require.NoError(t, err)
if tc.expectedResources.Dashboards != nil {
require.Equal(t, tc.expectedResources.Dashboards, resources.Dashboards)
}
if tc.expectedResources.ScopeTypes != nil {
require.Equal(t, tc.expectedResources.ScopeTypes, resources.ScopeTypes)
}
if tc.expectedErr != nil {
require.Equal(t, tc.expectedErr, err)
}
})
}
}

View File

@@ -0,0 +1,14 @@
package accesscontrol
// AccessResources contains resources that are used to filter annotations based on RBAC.
type AccessResources struct {
// Dashboards is a map of dashboard UIDs to IDs
Dashboards map[string]int64
// ScopeTypes contains the scope types that the user has access to. At most `dashboard` and `organization`
ScopeTypes map[any]struct{}
}
type dashboardProjection struct {
ID int64 `xorm:"id"`
UID string `xorm:"uid"`
}