accesscontrol

package
v0.0.85-test Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 8, 2023 License: AGPL-3.0 Imports: 16 Imported by: 0

Documentation

Index

Constants

View Source
const (
	GlobalOrgID      = 0
	GeneralFolderUID = "general"

	ActionAPIKeyRead   = "apikeys:read"
	ActionAPIKeyCreate = "apikeys:create"
	ActionAPIKeyDelete = "apikeys:delete"

	// Users actions
	ActionUsersRead     = "users:read"
	ActionUsersWrite    = "users:write"
	ActionUsersTeamRead = "users.teams:read"
	// We can ignore gosec G101 since this does not contain any credentials.
	// nolint:gosec
	ActionUsersAuthTokenList = "users.authtoken:list"
	// We can ignore gosec G101 since this does not contain any credentials.
	// nolint:gosec
	ActionUsersAuthTokenUpdate = "users.authtoken:update"
	// We can ignore gosec G101 since this does not contain any credentials.
	// nolint:gosec
	ActionUsersPasswordUpdate    = "users.password:update"
	ActionUsersDelete            = "users:delete"
	ActionUsersCreate            = "users:create"
	ActionUsersEnable            = "users:enable"
	ActionUsersDisable           = "users:disable"
	ActionUsersPermissionsUpdate = "users.permissions:update"
	ActionUsersLogout            = "users:logout"
	ActionUsersQuotasList        = "users.quotas:list"
	ActionUsersQuotasUpdate      = "users.quotas:update"

	// Org actions
	ActionOrgUsersRead       = "org.users:read"
	ActionOrgUsersAdd        = "org.users:add"
	ActionOrgUsersRemove     = "org.users:remove"
	ActionOrgUsersRoleUpdate = "org.users.role:update"

	// LDAP actions
	ActionLDAPUsersRead    = "ldap.user:read"
	ActionLDAPUsersSync    = "ldap.user:sync"
	ActionLDAPStatusRead   = "ldap.status:read"
	ActionLDAPConfigReload = "ldap.config:reload"

	// Server actions
	ActionServerStatsRead = "server.stats:read"

	// Settings actions
	ActionSettingsRead = "settings:read"

	// Datasources actions
	ActionDatasourcesExplore = "datasources:explore"

	// Plugin actions
	ActionPluginsManage = "plugins:manage"

	// Global Scopes
	ScopeGlobalUsersAll = "global.users:*"

	// APIKeys scope
	ScopeAPIKeysAll = "apikeys:*"

	// Users scope
	ScopeUsersAll = "users:*"

	// Settings scope
	ScopeSettingsAll = "settings:*"

	// Team related actions
	ActionTeamsCreate           = "teams:create"
	ActionTeamsDelete           = "teams:delete"
	ActionTeamsRead             = "teams:read"
	ActionTeamsWrite            = "teams:write"
	ActionTeamsPermissionsRead  = "teams.permissions:read"
	ActionTeamsPermissionsWrite = "teams.permissions:write"

	// Team related scopes
	ScopeTeamsAll = "teams:*"

	// Annotations related actions
	ActionAnnotationsCreate = "annotations:create"
	ActionAnnotationsDelete = "annotations:delete"
	ActionAnnotationsRead   = "annotations:read"
	ActionAnnotationsWrite  = "annotations:write"

	// Dashboard actions
	ActionDashboardsCreate           = "dashboards:create"
	ActionDashboardsRead             = "dashboards:read"
	ActionDashboardsWrite            = "dashboards:write"
	ActionDashboardsDelete           = "dashboards:delete"
	ActionDashboardsPermissionsRead  = "dashboards.permissions:read"
	ActionDashboardsPermissionsWrite = "dashboards.permissions:write"

	// Dashboard scopes
	ScopeDashboardsAll = "dashboards:*"

	// Alerting rules actions
	ActionAlertingRuleCreate = "alert.rules:create"
	ActionAlertingRuleRead   = "alert.rules:read"
	ActionAlertingRuleUpdate = "alert.rules:update"
	ActionAlertingRuleDelete = "alert.rules:delete"

	// Alerting instances (+silences) actions
	ActionAlertingInstanceCreate = "alert.instances:create"
	ActionAlertingInstanceUpdate = "alert.instances:update"
	ActionAlertingInstanceRead   = "alert.instances:read"

	// Alerting Notification policies actions
	ActionAlertingNotificationsRead  = "alert.notifications:read"
	ActionAlertingNotificationsWrite = "alert.notifications:write"

	// External alerting rule actions. We can only narrow it down to writes or reads, as we don't control the atomicity in the external system.
	ActionAlertingRuleExternalWrite = "alert.rules.external:write"
	ActionAlertingRuleExternalRead  = "alert.rules.external:read"

	// External alerting instances actions. We can only narrow it down to writes or reads, as we don't control the atomicity in the external system.
	ActionAlertingInstancesExternalWrite = "alert.instances.external:write"
	ActionAlertingInstancesExternalRead  = "alert.instances.external:read"

	// External alerting notifications actions. We can only narrow it down to writes or reads, as we don't control the atomicity in the external system.
	ActionAlertingNotificationsExternalWrite = "alert.notifications.external:write"
	ActionAlertingNotificationsExternalRead  = "alert.notifications.external:read"
)
View Source
const FixedRolePrefix = "fixed:"
View Source
const RoleGrafanaAdmin = "Grafana Admin"

Variables

View Source
var (
	ErrFixedRolePrefixMissing = errors.New("fixed role should be prefixed with '" + FixedRolePrefix + "'")
	ErrInvalidBuiltinRole     = errors.New("built-in role is not valid")
	ErrInvalidScope           = errors.New("invalid scope")
)
View Source
var (
	// Team scope
	ScopeTeamsID = Scope("teams", "id", Parameter(":teamId"))

	// Annotation scopes
	ScopeAnnotationsRoot             = "annotations"
	ScopeAnnotationsProvider         = NewScopeProvider(ScopeAnnotationsRoot)
	ScopeAnnotationsAll              = ScopeAnnotationsProvider.GetResourceAllScope()
	ScopeAnnotationsID               = Scope(ScopeAnnotationsRoot, "id", Parameter(":annotationId"))
	ScopeAnnotationsTypeDashboard    = ScopeAnnotationsProvider.GetResourceScopeType(annotations.Dashboard.String())
	ScopeAnnotationsTypeOrganization = ScopeAnnotationsProvider.GetResourceScopeType(annotations.Organization.String())
)
View Source
var NoReq = func(c *models.ReqContext) bool {
	return true
}
View Source
var ReqGrafanaAdmin = func(c *models.ReqContext) bool {
	return c.IsGrafanaAdmin
}
View Source
var ReqOrgAdmin = func(c *models.ReqContext) bool {
	return c.OrgRole == models.ROLE_ADMIN
}
View Source
var ReqOrgAdminOrEditor = func(c *models.ReqContext) bool {
	return c.OrgRole == models.ROLE_ADMIN || c.OrgRole == models.ROLE_EDITOR
}
View Source
var ReqSignedIn = func(c *models.ReqContext) bool {
	return c.IsSignedIn
}
View Source
var ReqViewer = func(c *models.ReqContext) bool {
	return c.OrgRole.Includes(models.ROLE_VIEWER)
}

ReqViewer returns true if the current user has models.ROLE_VIEWER. Note: this can be anonymous user as well

View Source
var (
	SettingsReaderRole = RoleDTO{
		Name:        "fixed:settings:reader",
		DisplayName: "Setting reader",
		Description: "Read Grafana instance settings.",
		Group:       "Settings",
		Version:     4,
		Permissions: []Permission{
			{
				Action: ActionSettingsRead,
				Scope:  ScopeSettingsAll,
			},
		},
	}
)

Roles definition

Functions

func BuildPermissionsMap

func BuildPermissionsMap(permissions []*Permission) map[string]bool

func DeclareFixedRoles

func DeclareFixedRoles(ac AccessControl) error

Declare OSS roles to the accesscontrol service

func Field

func Field(key string) string

Field returns an injectable scope part for selected fields from the request's context available in accesscontrol.ScopeParams. e.g. Scope("orgs", Parameter("OrgID")) or "orgs:" + Parameter("OrgID")

func GetResourceAllIDScope

func GetResourceAllIDScope(resource string) string

func GetResourceAllScope

func GetResourceAllScope(resource string) string

func GetResourceScope

func GetResourceScope(resource string, resourceID string) string

func GetResourceScopeName

func GetResourceScopeName(resource string, resourceID string) string

func GetResourceScopeType

func GetResourceScopeType(resource string, typeName string) string

func GetResourceScopeUID

func GetResourceScopeUID(resource string, resourceID string) string

func GetResourcesMetadata

func GetResourcesMetadata(ctx context.Context, permissions map[string][]string, prefix string, resourceIDs map[string]bool) map[string]Metadata

GetResourcesMetadata returns a map of accesscontrol metadata, listing for each resource, users available actions

func GroupScopesByAction

func GroupScopesByAction(permissions []*Permission) map[string][]string

GroupScopesByAction will group scopes on action

func HasAccess

func HasAccess(ac AccessControl, c *models.ReqContext) func(fallback func(*models.ReqContext) bool, evaluator Evaluator) bool

func HasGlobalAccess

func HasGlobalAccess(ac AccessControl, c *models.ReqContext) func(fallback func(*models.ReqContext) bool, evaluator Evaluator) bool

HasGlobalAccess checks user access with globally assigned permissions only

func IsDisabled

func IsDisabled(cfg *setting.Cfg) bool

func ManagedBuiltInRoleName

func ManagedBuiltInRoleName(builtInRole string) string

func ManagedTeamRoleName

func ManagedTeamRoleName(teamID int64) string

func ManagedUserRoleName

func ManagedUserRoleName(userID int64) string

func Parameter

func Parameter(key string) string

Parameter returns injectable scope part, based on URL parameters. e.g. Scope("users", Parameter(":id")) or "users:" + Parameter(":id")

func ParseScopes

func ParseScopes(prefix string, scopes []string) (ids map[interface{}]struct{}, hasWildcard bool)

func Scope

func Scope(parts ...string) string

Scope builds scope from parts e.g. Scope("users", "*") return "users:*"

func ScopePrefix

func ScopePrefix(scope string) string

ScopePrefix returns the prefix associated to a given scope we assume prefixes are all in the form <resource>:<attribute>:<value> ex: "datasources:name:test" returns "datasources:name:"

func SetAcceptListForTest

func SetAcceptListForTest(list map[string]struct{}) func()

SetAcceptListForTest allow us to mutate the list for blackbox testing

func ValidateBuiltInRoles

func ValidateBuiltInRoles(builtInRoles []string) error

ValidateBuiltInRoles errors when a built-in role does not match expected pattern

func ValidateFixedRole

func ValidateFixedRole(role RoleDTO) error

ValidateFixedRole errors when a fixed role does not match expected pattern

func ValidateScope

func ValidateScope(scope string) bool

Types

type AccessControl

type AccessControl interface {
	// Evaluate evaluates access to the given resources.
	Evaluate(ctx context.Context, user *models.SignedInUser, evaluator Evaluator) (bool, error)

	// GetUserPermissions returns user permissions.
	GetUserPermissions(ctx context.Context, user *models.SignedInUser, options Options) ([]*Permission, error)

	// GetUserRoles returns user roles.
	GetUserRoles(ctx context.Context, user *models.SignedInUser) ([]*RoleDTO, error)

	//IsDisabled returns if access control is enabled or not
	IsDisabled() bool

	// DeclareFixedRoles allows the caller to declare, to the service, fixed roles and their
	// assignments to organization roles ("Viewer", "Editor", "Admin") or "Grafana Admin"
	DeclareFixedRoles(...RoleRegistration) error

	// RegisterAttributeScopeResolver allows the caller to register a scope resolver for a
	// specific scope prefix (ex: datasources:name:)
	RegisterAttributeScopeResolver(scopePrefix string, resolver AttributeScopeResolveFunc)
}

type AttributeScopeResolveFunc

type AttributeScopeResolveFunc func(ctx context.Context, orgID int64, initialScope string) (string, error)

type BuiltinRole

type BuiltinRole struct {
	ID     int64 `json:"id" xorm:"pk autoincr 'id'"`
	RoleID int64 `json:"roleId" xorm:"role_id"`
	OrgID  int64 `json:"orgId" xorm:"org_id"`
	Role   string

	Updated time.Time
	Created time.Time
}

type Evaluator

type Evaluator interface {
	// Evaluate permissions that are grouped by action
	Evaluate(permissions map[string][]string) (bool, error)
	// MutateScopes executes a sequence of ScopeModifier functions on all embedded scopes of an evaluator and returns a new Evaluator
	MutateScopes(context.Context, ...ScopeMutator) (Evaluator, error)
	// String returns a string representation of permission required by the evaluator
	fmt.Stringer
	fmt.GoStringer
}

func EvalAll

func EvalAll(allOf ...Evaluator) Evaluator

EvalAll returns evaluator that requires all passed evaluators to evaluate to true

func EvalAny

func EvalAny(anyOf ...Evaluator) Evaluator

EvalAny returns evaluator that requires at least one of passed evaluators to evaluate to true

func EvalPermission

func EvalPermission(action string, scopes ...string) Evaluator

EvalPermission returns an evaluator that will require all scopes in combination with action to match

type GetUserPermissionsQuery

type GetUserPermissionsQuery struct {
	OrgID   int64 `json:"-"`
	UserID  int64 `json:"userId"`
	Roles   []string
	Actions []string
}

type KeywordScopeResolveFunc

type KeywordScopeResolveFunc func(*models.SignedInUser) (string, error)

type Metadata

type Metadata map[string]bool

Metadata contains user accesses for a given resource Ex: map[string]bool{"create":true, "delete": true}

type Options

type Options struct {
	ReloadCache bool
}

type Permission

type Permission struct {
	ID     int64  `json:"-" xorm:"pk autoincr 'id'"`
	RoleID int64  `json:"-" xorm:"role_id"`
	Action string `json:"action"`
	Scope  string `json:"scope"`

	Updated time.Time `json:"updated"`
	Created time.Time `json:"created"`
}

Permission is the model for access control permissions.

func ConcatPermissions

func ConcatPermissions(permissions ...[]Permission) []Permission

func (Permission) OSSPermission

func (p Permission) OSSPermission() Permission

type PermissionsProvider

type PermissionsProvider interface {
	GetUserPermissions(ctx context.Context, query GetUserPermissionsQuery) ([]*Permission, error)
}

type PermissionsService

type PermissionsService interface {
	// GetPermissions returns all permissions for given resourceID
	GetPermissions(ctx context.Context, user *models.SignedInUser, resourceID string) ([]ResourcePermission, error)
	// SetUserPermission sets permission on resource for a user
	SetUserPermission(ctx context.Context, orgID int64, user User, resourceID, permission string) (*ResourcePermission, error)
	// SetTeamPermission sets permission on resource for a team
	SetTeamPermission(ctx context.Context, orgID, teamID int64, resourceID, permission string) (*ResourcePermission, error)
	// SetBuiltInRolePermission sets permission on resource for a built-in role (Admin, Editor, Viewer)
	SetBuiltInRolePermission(ctx context.Context, orgID int64, builtInRole string, resourceID string, permission string) (*ResourcePermission, error)
	// SetPermissions sets several permissions on resource for either built-in role, team or user
	SetPermissions(ctx context.Context, orgID int64, resourceID string, commands ...SetResourcePermissionCommand) ([]ResourcePermission, error)
	// MapActions will map actions for a ResourcePermissions to it's "friendly" name configured in PermissionsToActions map.
	MapActions(permission ResourcePermission) string
}

type PermissionsServices

type PermissionsServices interface {
	GetTeamService() PermissionsService
	GetFolderService() PermissionsService
	GetDashboardService() PermissionsService
	GetDataSourceService() PermissionsService
}

type RegistrationList

type RegistrationList struct {
	// contains filtered or unexported fields
}

func (*RegistrationList) Append

func (m *RegistrationList) Append(regs ...RoleRegistration)

func (*RegistrationList) Range

func (m *RegistrationList) Range(f func(registration RoleRegistration) bool)

type ResourcePermission

type ResourcePermission struct {
	ID          int64
	RoleName    string
	Actions     []string
	Scope       string
	UserId      int64
	UserLogin   string
	UserEmail   string
	TeamId      int64
	TeamEmail   string
	Team        string
	BuiltInRole string
	IsManaged   bool
	Created     time.Time
	Updated     time.Time
}

ResourcePermission is structure that holds all actions that either a team / user / builtin-role can perform against specific resource.

func (*ResourcePermission) Contains

func (p *ResourcePermission) Contains(targetActions []string) bool

type Role

type Role struct {
	ID          int64  `json:"-" xorm:"pk autoincr 'id'"`
	OrgID       int64  `json:"-" xorm:"org_id"`
	Version     int64  `json:"version"`
	UID         string `xorm:"uid" json:"uid"`
	Name        string `json:"name"`
	DisplayName string `json:"displayName"`
	Group       string `xorm:"group_name" json:"group"`
	Description string `json:"description"`
	Hidden      bool   `json:"hidden"`

	Updated time.Time `json:"updated"`
	Created time.Time `json:"created"`
}

Role is the model for Role in RBAC.

func (Role) GetDisplayName

func (r Role) GetDisplayName() string

func (Role) Global

func (r Role) Global() bool

func (Role) IsFixed

func (r Role) IsFixed() bool

func (Role) MarshalJSON

func (r Role) MarshalJSON() ([]byte, error)

type RoleDTO

type RoleDTO struct {
	Version     int64        `json:"version"`
	UID         string       `xorm:"uid" json:"uid"`
	Name        string       `json:"name"`
	DisplayName string       `json:"displayName"`
	Description string       `json:"description"`
	Group       string       `xorm:"group_name" json:"group"`
	Permissions []Permission `json:"permissions,omitempty"`
	Delegatable *bool        `json:"delegatable,omitempty"`
	Hidden      bool         `json:"hidden,omitempty"`

	ID    int64 `json:"-" xorm:"pk autoincr 'id'"`
	OrgID int64 `json:"-" xorm:"org_id"`

	Updated time.Time `json:"updated"`
	Created time.Time `json:"created"`
}

func (RoleDTO) GetDisplayName

func (r RoleDTO) GetDisplayName() string

func (RoleDTO) Global

func (r RoleDTO) Global() bool

func (RoleDTO) IsFixed

func (r RoleDTO) IsFixed() bool

func (RoleDTO) MarshalJSON

func (r RoleDTO) MarshalJSON() ([]byte, error)

func (RoleDTO) Role

func (r RoleDTO) Role() Role

type RoleRegistration

type RoleRegistration struct {
	Role   RoleDTO
	Grants []string
}

RoleRegistration stores a role and its assignments to built-in roles (Viewer, Editor, Admin, Grafana Admin)

type RoleRegistry

type RoleRegistry interface {
	// RegisterFixedRoles registers all roles declared to AccessControl
	RegisterFixedRoles() error
}

type SQLFilter

type SQLFilter struct {
	Where string
	Args  []interface{}
}

func Filter

func Filter(user *models.SignedInUser, sqlID, prefix string, actions ...string) (SQLFilter, error)

Filter creates a where clause to restrict the view of a query based on a users permissions Scopes that exists for all actions will be parsed and compared against the supplied sqlID Prefix parameter is the prefix of the scope that we support (e.g. "users:id:")

type ScopeMutator

type ScopeMutator func(context.Context, string) (string, error)

ScopeMutator alters a Scope to return a new modified Scope

func ScopeInjector

func ScopeInjector(params ScopeParams) ScopeMutator

Inject params into the evaluator's templated scopes. e.g. "settings:" + eval.Parameters(":id")

type ScopeParams

type ScopeParams struct {
	OrgID     int64
	URLParams map[string]string
}

ScopeParams holds the parameters used to fill in scope templates

type ScopeProvider

type ScopeProvider interface {
	GetResourceScope(resourceID string) string
	GetResourceScopeUID(resourceID string) string
	GetResourceScopeName(resourceID string) string
	GetResourceScopeType(typeName string) string
	GetResourceAllScope() string
	GetResourceAllIDScope() string
}

ScopeProvider provides methods that construct scopes

func NewScopeProvider

func NewScopeProvider(root string) ScopeProvider

NewScopeProvider creates a new ScopeProvider that is configured with specific root scope

type ScopeResolver

type ScopeResolver struct {
	// contains filtered or unexported fields
}

ScopeResolver is used to resolve scope keywords such as `self` or `current` into `id` based scopes and scope attributes such as `name` or `uid` into `id` based scopes.

func NewScopeResolver

func NewScopeResolver() ScopeResolver

func (*ScopeResolver) AddAttributeResolver

func (s *ScopeResolver) AddAttributeResolver(prefix string, fn AttributeScopeResolveFunc)

func (*ScopeResolver) AddKeywordResolver

func (s *ScopeResolver) AddKeywordResolver(keyword string, fn KeywordScopeResolveFunc)

func (*ScopeResolver) GetResolveAttributeScopeMutator

func (s *ScopeResolver) GetResolveAttributeScopeMutator(orgID int64) ScopeMutator

GetResolveAttributeScopeMutator returns a function to resolve scopes with attributes such as `name` or `uid` into `id` based scopes

func (*ScopeResolver) GetResolveKeywordScopeMutator

func (s *ScopeResolver) GetResolveKeywordScopeMutator(user *models.SignedInUser) ScopeMutator

GetResolveKeywordScopeMutator returns a function to resolve scope with keywords such as `self` or `current` into `id` based scopes

type SetResourcePermissionCommand

type SetResourcePermissionCommand struct {
	UserID      int64
	TeamID      int64
	BuiltinRole string
	Permission  string
}

type TeamRole

type TeamRole struct {
	ID     int64 `json:"id" xorm:"pk autoincr 'id'"`
	OrgID  int64 `json:"orgId" xorm:"org_id"`
	RoleID int64 `json:"roleId" xorm:"role_id"`
	TeamID int64 `json:"teamId" xorm:"team_id"`

	Created time.Time
}

type User

type User struct {
	ID         int64
	IsExternal bool
}

type UserRole

type UserRole struct {
	ID     int64 `json:"id" xorm:"pk autoincr 'id'"`
	OrgID  int64 `json:"orgId" xorm:"org_id"`
	RoleID int64 `json:"roleId" xorm:"role_id"`
	UserID int64 `json:"userId" xorm:"user_id"`

	Created time.Time
}

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL