Documentation ¶
Index ¶
- Constants
- Variables
- func AuthorizeInOrgMiddleware(ac AccessControl, service Service, cache userCache) func(web.Handler, OrgIDGetter, Evaluator) web.Handler
- func BackgroundUser(name string, orgID int64, role org.RoleType, permissions []Permission) *user.SignedInUser
- func BuildBasicRoleDefinitions() map[string]*RoleDTO
- func BuildPermissionsMap(permissions []Permission) map[string]bool
- func BuiltInRolesWithParents(builtInRoles []string) map[string]struct{}
- func DeclareFixedRoles(service Service) error
- func Field(key string) string
- func GetOrgRoles(user *user.SignedInUser) []string
- func GetResourceAllIDScope(resource string) string
- func GetResourceAllScope(resource string) string
- func GetResourceScope(resource string, resourceID string) string
- func GetResourceScopeName(resource string, resourceID string) string
- func GetResourceScopeType(resource string, typeName string) string
- func GetResourceScopeUID(resource string, resourceID string) string
- func GetResourcesMetadata(ctx context.Context, permissions map[string][]string, prefix string, ...) map[string]Metadata
- func GroupScopesByAction(permissions []Permission) map[string][]string
- func HasAccess(ac AccessControl, c *models.ReqContext) func(fallback func(*models.ReqContext) bool, evaluator Evaluator) bool
- func HasGlobalAccess(ac AccessControl, service Service, c *models.ReqContext) func(fallback func(*models.ReqContext) bool, evaluator Evaluator) bool
- func IsDisabled(cfg *setting.Cfg) bool
- func LoadPermissionsMiddleware(service Service) web.Handler
- func ManagedBuiltInRoleName(builtInRole string) string
- func ManagedTeamRoleName(teamID int64) string
- func ManagedUserRoleName(userID int64) string
- func Middleware(ac AccessControl) func(web.Handler, Evaluator) web.Handler
- func Parameter(key string) string
- func ParseScopeID(scope string) (int64, error)
- func ParseScopeUID(scope string) (string, error)
- func ParseScopes(prefix string, scopes []string) (ids map[interface{}]struct{}, hasWildcard bool)
- func ReqHasRole(role org.RoleType) func(c *models.ReqContext) bool
- func Scope(parts ...string) string
- func ScopePrefix(scope string) string
- func ScopeSuffix(scope string) string
- func SetAcceptListForTest(list map[string]struct{}) func()
- func UseGlobalOrg(c *models.ReqContext) (int64, error)
- func UseOrgFromContextParams(c *models.ReqContext) (int64, error)
- func ValidateBuiltInRoles(builtInRoles []string) error
- func ValidateFixedRole(role RoleDTO) error
- func ValidateScope(scope string) bool
- type AccessControl
- type BuiltinRole
- type DashboardPermissionsService
- type DatasourcePermissionsService
- type Evaluator
- type FolderPermissionsService
- type GetUserPermissionsQuery
- type Metadata
- type Options
- type OrgIDGetter
- type Permission
- type PermissionsService
- type RegistrationList
- type Resolvers
- type ResourcePermission
- type Role
- type RoleDTO
- type RoleRegistration
- type RoleRegistry
- type SQLFilter
- type ScopeAttributeMutator
- type ScopeAttributeResolver
- type ScopeAttributeResolverFunc
- type ScopeProvider
- type Service
- type ServiceAccountPermissionsService
- type SetResourcePermissionCommand
- type TeamPermissionsService
- type TeamRole
- type User
- type UserRole
- type Wildcards
Constants ¶
const ( GlobalOrgID = 0 FixedRolePrefix = "fixed:" ManagedRolePrefix = "managed:" BasicRolePrefix = "basic:" BasicRoleUIDPrefix = "basic_" RoleGrafanaAdmin = "Grafana Admin" GeneralFolderUID = "general" ActionAPIKeyRead = "apikeys:read" ActionAPIKeyCreate = "apikeys:create" ActionAPIKeyDelete = "apikeys:delete" // Users actions ActionUsersRead = "users:read" ActionUsersWrite = "users:write" // We can ignore gosec G101 since this does not contain any credentials. // nolint:gosec ActionUsersAuthTokenList = "users.authtoken:read" // We can ignore gosec G101 since this does not contain any credentials. // nolint:gosec ActionUsersAuthTokenUpdate = "users.authtoken:write" // We can ignore gosec G101 since this does not contain any credentials. // nolint:gosec ActionUsersPasswordUpdate = "users.password:write" ActionUsersDelete = "users:delete" ActionUsersCreate = "users:create" ActionUsersEnable = "users:enable" ActionUsersDisable = "users:disable" ActionUsersPermissionsUpdate = "users.permissions:write" ActionUsersLogout = "users:logout" ActionUsersQuotasList = "users.quotas:read" ActionUsersQuotasUpdate = "users.quotas:write" // Org actions ActionOrgsRead = "orgs:read" ActionOrgsPreferencesRead = "orgs.preferences:read" ActionOrgsQuotasRead = "orgs.quotas:read" ActionOrgsWrite = "orgs:write" ActionOrgsPreferencesWrite = "orgs.preferences:write" ActionOrgsQuotasWrite = "orgs.quotas:write" ActionOrgsDelete = "orgs:delete" ActionOrgsCreate = "orgs:create" ActionOrgUsersRead = "org.users:read" ActionOrgUsersAdd = "org.users:add" ActionOrgUsersRemove = "org.users:remove" ActionOrgUsersWrite = "org.users:write" // 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" // 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" // Alerting rules actions ActionAlertingRuleCreate = "alert.rules:create" ActionAlertingRuleRead = "alert.rules:read" ActionAlertingRuleUpdate = "alert.rules:write" ActionAlertingRuleDelete = "alert.rules:delete" // Alerting instances (+silences) actions ActionAlertingInstanceCreate = "alert.instances:create" ActionAlertingInstanceUpdate = "alert.instances:write" 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" // Alerting provisioning actions ActionAlertingProvisioningRead = "alert.provisioning:read" ActionAlertingProvisioningWrite = "alert.provisioning:write" )
Variables ¶
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") ErrResolverNotFound = errors.New("no resolver found") )
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()) )
var ApiKeyAccessEvaluator = EvalPermission(ActionAPIKeyRead)
ApiKeyAccessEvaluator is used to protect the "Configuration > API keys" page access
var OrgPreferencesAccessEvaluator = EvalAny( EvalAll( EvalPermission(ActionOrgsRead), EvalPermission(ActionOrgsWrite), ), EvalAll( EvalPermission(ActionOrgsPreferencesRead), EvalPermission(ActionOrgsPreferencesWrite), ), )
OrgPreferencesAccessEvaluator is used to protect the "Configure > Preferences" page access
var OrgsAccessEvaluator = EvalPermission(ActionOrgsRead)
OrgsAccessEvaluator is used to protect the "Server Admin > Orgs" page access (you need to have read access to update or delete orgs; read is the minimum)
var OrgsCreateAccessEvaluator = EvalAll( EvalPermission(ActionOrgsRead), EvalPermission(ActionOrgsCreate), )
OrgsCreateAccessEvaluator is used to protect the "Server Admin > Orgs > New Org" page access
var ReqGrafanaAdmin = func(c *models.ReqContext) bool {
return c.IsGrafanaAdmin
}
var ReqOrgAdmin = func(c *models.ReqContext) bool { return c.OrgRole == org.RoleAdmin }
var ReqOrgAdminOrEditor = func(c *models.ReqContext) bool { return c.OrgRole == org.RoleAdmin || c.OrgRole == org.RoleEditor }
var ReqSignedIn = func(c *models.ReqContext) bool {
return c.IsSignedIn
}
var ReqViewer = func(c *models.ReqContext) bool { return c.OrgRole.Includes(org.RoleViewer) }
ReqViewer returns true if the current user has org.RoleViewer. Note: this can be anonymous user as well
var ( SettingsReaderRole = RoleDTO{ Name: "fixed:settings:reader", DisplayName: "Setting reader", Description: "Read Grafana instance settings.", Group: "Settings", Permissions: []Permission{ { Action: ActionSettingsRead, Scope: ScopeSettingsAll, }, }, } )
Roles definition
var TeamsAccessEvaluator = EvalAny( EvalPermission(ActionTeamsCreate), EvalAll( EvalPermission(ActionTeamsRead), EvalAny( EvalPermission(ActionTeamsWrite), EvalPermission(ActionTeamsPermissionsWrite), ), ), )
TeamsAccessEvaluator is used to protect the "Configuration > Teams" page access grants access to a user when they can either create teams or can read and update a team
var TeamsEditAccessEvaluator = EvalAll( EvalPermission(ActionTeamsRead), EvalAny( EvalPermission(ActionTeamsCreate), EvalPermission(ActionTeamsWrite), EvalPermission(ActionTeamsPermissionsWrite), ), )
TeamsEditAccessEvaluator is used to protect the "Configuration > Teams > edit" page access
Functions ¶
func AuthorizeInOrgMiddleware ¶
func AuthorizeInOrgMiddleware(ac AccessControl, service Service, cache userCache) func(web.Handler, OrgIDGetter, Evaluator) web.Handler
func BackgroundUser ¶
func BackgroundUser(name string, orgID int64, role org.RoleType, permissions []Permission) *user.SignedInUser
func BuildPermissionsMap ¶
func BuildPermissionsMap(permissions []Permission) map[string]bool
func BuiltInRolesWithParents ¶
func DeclareFixedRoles ¶
Declare OSS roles to the accesscontrol service
func Field ¶
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 GetOrgRoles ¶
func GetOrgRoles(user *user.SignedInUser) []string
GetOrgRoles returns legacy org roles for a user
func GetResourceAllIDScope ¶
func GetResourceAllScope ¶
func GetResourceScope ¶
func GetResourceScopeName ¶
func GetResourceScopeType ¶
func GetResourceScopeUID ¶
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, service Service, c *models.ReqContext) func(fallback func(*models.ReqContext) bool, evaluator Evaluator) bool
HasGlobalAccess checks user access with globally assigned permissions only
func IsDisabled ¶
func ManagedBuiltInRoleName ¶
func ManagedTeamRoleName ¶
func ManagedUserRoleName ¶
func Middleware ¶
func Parameter ¶
Parameter returns injectable scope part, based on URL parameters. e.g. Scope("users", Parameter(":id")) or "users:" + Parameter(":id")
func ParseScopeID ¶
func ParseScopeUID ¶
func ParseScopes ¶
func ReqHasRole ¶
func ReqHasRole(role org.RoleType) func(c *models.ReqContext) bool
ReqHasRole generates a fallback to check whether the user has a role Note that while ReqOrgAdmin returns false for a Grafana Admin / Viewer, ReqHasRole(org.RoleAdmin) will return true
func ScopePrefix ¶
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 ScopeSuffix ¶
func SetAcceptListForTest ¶
func SetAcceptListForTest(list map[string]struct{}) func()
SetAcceptListForTest allow us to mutate the list for blackbox testing
func UseGlobalOrg ¶
func UseGlobalOrg(c *models.ReqContext) (int64, error)
func UseOrgFromContextParams ¶
func UseOrgFromContextParams(c *models.ReqContext) (int64, error)
func ValidateBuiltInRoles ¶
ValidateBuiltInRoles errors when a built-in role does not match expected pattern
func ValidateFixedRole ¶
ValidateFixedRole errors when a fixed role does not match expected pattern
func ValidateScope ¶
Types ¶
type AccessControl ¶
type AccessControl interface { // Evaluate evaluates access to the given resources. Evaluate(ctx context.Context, user *user.SignedInUser, evaluator Evaluator) (bool, error) // RegisterScopeAttributeResolver allows the caller to register a scope resolver for a // specific scope prefix (ex: datasources:name:) RegisterScopeAttributeResolver(prefix string, resolver ScopeAttributeResolver) //IsDisabled returns if access control is enabled or not IsDisabled() bool }
type BuiltinRole ¶
type DashboardPermissionsService ¶
type DashboardPermissionsService interface { PermissionsService }
type DatasourcePermissionsService ¶
type DatasourcePermissionsService interface { PermissionsService }
type Evaluator ¶
type Evaluator interface { // Evaluate permissions that are grouped by action Evaluate(permissions map[string][]string) bool // MutateScopes executes a sequence of ScopeModifier functions on all embedded scopes of an evaluator and returns a new Evaluator MutateScopes(ctx context.Context, mutate ScopeAttributeMutator) (Evaluator, error) // String returns a string representation of permission required by the evaluator fmt.Stringer fmt.GoStringer }
func EvalAny ¶
EvalAny returns evaluator that requires at least one of passed evaluators to evaluate to true
func EvalPermission ¶
EvalPermission returns an evaluator that will require at least one of passed scopes to match
type FolderPermissionsService ¶
type FolderPermissionsService interface { PermissionsService }
type GetUserPermissionsQuery ¶
type Metadata ¶
Metadata contains user accesses for a given resource Ex: map[string]bool{"create":true, "delete": true}
type OrgIDGetter ¶
type OrgIDGetter func(c *models.ReqContext) (int64, error)
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 PermissionsService ¶
type PermissionsService interface { // GetPermissions returns all permissions for given resourceID GetPermissions(ctx context.Context, user *user.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 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 Resolvers ¶
type Resolvers struct {
// contains filtered or unexported fields
}
func NewResolvers ¶
func (*Resolvers) AddScopeAttributeResolver ¶
func (s *Resolvers) AddScopeAttributeResolver(prefix string, resolver ScopeAttributeResolver)
func (*Resolvers) GetScopeAttributeMutator ¶
func (s *Resolvers) GetScopeAttributeMutator(orgID int64) ScopeAttributeMutator
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 IsInherited 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 (Role) MarshalJSON ¶
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 (RoleDTO) MarshalJSON ¶
type RoleRegistration ¶
RoleRegistration stores a role and its assignments to built-in roles (Viewer, Editor, Admin, Grafana Admin)
type RoleRegistry ¶
type SQLFilter ¶
type SQLFilter struct { Where string Args []interface{} }
type ScopeAttributeMutator ¶
type ScopeAttributeResolver ¶
type ScopeAttributeResolver interface {
Resolve(ctx context.Context, orgID int64, scope string) ([]string, error)
}
ScopeAttributeResolver is used to resolve attributes in scopes to one or more scopes that are evaluated by logical or. E.g. "dashboards:id:1" -> "dashboards:uid:test-dashboard" or "folder:uid:test-folder"
type ScopeAttributeResolverFunc ¶
type ScopeAttributeResolverFunc func(ctx context.Context, orgID int64, scope string) ([]string, error)
ScopeAttributeResolverFunc is an adapter to allow functions to implement ScopeAttributeResolver interface
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 Service ¶
type Service interface { registry.ProvidesUsageStats // GetUserPermissions returns user permissions with only action and scope fields set. GetUserPermissions(ctx context.Context, user *user.SignedInUser, options Options) ([]Permission, error) // DeleteUserPermissions removes all permissions user has in org and all permission to that user // If orgID is set to 0 remove permissions from all orgs DeleteUserPermissions(ctx context.Context, orgID, userID int64) error // DeclareFixedRoles allows the caller to declare, to the service, fixed roles and their // assignments to organization roles ("Viewer", "Editor", "Admin") or "Grafana Admin" DeclareFixedRoles(registrations ...RoleRegistration) error //IsDisabled returns if access control is enabled or not IsDisabled() bool }
type ServiceAccountPermissionsService ¶
type ServiceAccountPermissionsService interface { PermissionsService }
type TeamPermissionsService ¶
type TeamPermissionsService interface { GetPermissions(ctx context.Context, user *user.SignedInUser, resourceID string) ([]ResourcePermission, error) SetUserPermission(ctx context.Context, orgID int64, user User, resourceID, permission string) (*ResourcePermission, error) }
type Wildcards ¶
type Wildcards []string
func WildcardsFromPrefix ¶
WildcardsFromPrefix generates valid wildcards from prefix datasource:uid: => "*", "datasource:*", "datasource:uid:*"