accesscontrol

package
v11.1.4-modfix Latest Latest
Warning

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

Go to latest
Published: Aug 20, 2024 License: AGPL-3.0 Imports: 33 Imported by: 0

Documentation

Index

Constants

View Source
const (
	CacheHit  = "hit"
	CacheMiss = "miss"
)
View Source
const (
	GlobalOrgID      = 0
	NoOrgID          = int64(-1)
	GeneralFolderUID = "general"
	RoleGrafanaAdmin = "Grafana Admin"

	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"
	ActionUsersPermissionsRead   = "users.permissions:read"

	// 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"
	ActionSettingsWrite = "settings:write"

	// Datasources actions
	ActionDatasourcesExplore = "datasources:explore"

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

	// APIKeys scope
	ScopeAPIKeysAll = "apikeys:*"

	// Users scope
	ScopeUsersAll    = "users:*"
	ScopeUsersPrefix = "users:id:"

	// Settings scope
	ScopeSettingsAll  = "settings:*"
	ScopeSettingsSAML = "settings:auth.saml:*"

	// 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"

	ActionAlertingSilencesRead   = "alert.silences:read"
	ActionAlertingSilencesCreate = "alert.silences:create"
	ActionAlertingSilencesWrite  = "alert.silences:write"

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

	// Alerting notifications time interval actions
	ActionAlertingNotificationsTimeIntervalsRead  = "alert.notifications.time-intervals:read"
	ActionAlertingNotificationsTimeIntervalsWrite = "alert.notifications.time-intervals:write"

	// Alerting receiver actions
	ActionAlertingReceiversList        = "alert.notifications.receivers:list"
	ActionAlertingReceiversRead        = "alert.notifications.receivers:read"
	ActionAlertingReceiversReadSecrets = "alert.notifications.receivers.secrets:read"

	// 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"
	ActionAlertingProvisioningReadSecrets        = "alert.provisioning.secrets:read"
	ActionAlertingProvisioningWrite              = "alert.provisioning:write"
	ActionAlertingRulesProvisioningRead          = "alert.rules.provisioning:read"
	ActionAlertingRulesProvisioningWrite         = "alert.rules.provisioning:write"
	ActionAlertingNotificationsProvisioningRead  = "alert.notifications.provisioning:read"
	ActionAlertingNotificationsProvisioningWrite = "alert.notifications.provisioning:write"

	// ActionAlertingProvisioningSetStatus Gives access to set provisioning status to alerting resources. Cannot be used alone. Only in conjunction with other permissions.
	ActionAlertingProvisioningSetStatus = "alert.provisioning.provenance:write"

	// Feature Management actions
	ActionFeatureManagementRead  = "featuremgmt.read"
	ActionFeatureManagementWrite = "featuremgmt.write"

	// Library Panel actions
	ActionLibraryPanelsCreate = "library.panels:create"
	ActionLibraryPanelsRead   = "library.panels:read"
	ActionLibraryPanelsWrite  = "library.panels:write"
	ActionLibraryPanelsDelete = "library.panels:delete"

	// Usage stats actions
	ActionUsageStatsRead = "server.usagestats.report:read"
)
View Source
const (
	BasicRolePrefix    = "basic:"
	BasicRoleUIDPrefix = "basic_"

	ExternalServiceRolePrefix    = "extsvc:"
	ExternalServiceRoleUIDPrefix = "extsvc_"

	FixedRolePrefix    = "fixed:"
	FixedRoleUIDPrefix = "fixed_"

	ManagedRolePrefix = "managed:"

	PluginRolePrefix = "plugins:"

	BasicRoleNoneUID  = "basic_none"
	BasicRoleNoneName = "basic:none"

	FixedCloudRolePrefix = "fixed:cloud:"
	FixedCloudViewerRole = "fixed:cloud:viewer"
	FixedCloudEditorRole = "fixed:cloud:editor"
	FixedCloudAdminRole  = "fixed:cloud:admin"
)

Variables

View Source
var (
	ErrInvalidBuiltinRole = errutil.BadRequest("accesscontrol.invalidBuiltInRole").
							MustTemplate(invalidBuiltInRoleMessage, errutil.WithPublic(invalidBuiltInRoleMessage))
	ErrNoneRoleAssignment       = errutil.BadRequest("accesscontrol.noneRoleAssignment", errutil.WithPublicMessage("none role cannot receive permissions"))
	ErrAssignmentEntityNotFound = errutil.BadRequest("accesscontrol.assignmentEntityNotFound").
								MustTemplate(assignmentEntityNotFoundMessage, errutil.WithPublic(assignmentEntityNotFoundMessage))

	// Note: these are intended to be replaced by equivalent errutil implementations.
	// Avoid creating new errors with errors.New and prefer errutil
	ErrInvalidRequestBody     = errors.New("invalid request body")
	ErrFixedRolePrefixMissing = errors.New("fixed role should be prefixed with '" + FixedRolePrefix + "'")
	ErrInvalidScope           = errors.New("invalid scope")
	ErrResolverNotFound       = errors.New("no resolver found")
	ErrPluginIDRequired       = errors.New("plugin ID is required")
	ErrRoleNotFound           = errors.New("role not found")
)
View Source
var (
	ErrInternal        = errutil.Internal("accesscontrol.internal")
	CacheUsageStatuses = []string{CacheHit, CacheMiss}
)
View Source
var (
	// Team scope
	ScopeTeamsID = Scope("teams", "id", Parameter(":teamId"))

	ScopeSettingsOAuth = func(provider string) string {
		return Scope("settings", "auth."+provider, "*")
	}

	// 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 ApiKeyAccessEvaluator = EvalPermission(ActionAPIKeyRead)

ApiKeyAccessEvaluator is used to protect the "Configuration > API keys" page access

OrgPreferencesAccessEvaluator is used to protect the "Configure > Preferences" page access

View Source
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)

OrgsCreateAccessEvaluator is used to protect the "Server Admin > Orgs > New Org" page access

View Source
var ReqGrafanaAdmin = func(c *contextmodel.ReqContext) bool {
	return c.SignedInUser.GetIsGrafanaAdmin()
}
View Source
var ReqSignedIn = func(c *contextmodel.ReqContext) bool {
	return c.IsSignedIn
}
View Source
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

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

TeamsEditAccessEvaluator is used to protect the "Configuration > Teams > edit" page access

Functions

func AuthorizeInOrgMiddleware

func AuthorizeInOrgMiddleware(ac AccessControl, authnService authn.Service) func(OrgIDGetter, Evaluator) web.Handler

func BackgroundUser

func BackgroundUser(name string, orgID int64, role org.RoleType, permissions []Permission) identity.Requester

func BuildBasicRoleDefinitions

func BuildBasicRoleDefinitions() map[string]*RoleDTO

func BuildPermissionsMap

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

func BuiltInRolesWithParents

func BuiltInRolesWithParents(builtInRoles []string) map[string]struct{}

func Checker

func Checker(user *user.SignedInUser, action string) func(scopes ...string) bool

func CloneRequest

func CloneRequest(req *http.Request) (*http.Request, error)

CloneRequest creates request copy including request body

func CopyRequestBody

func CopyRequestBody(req *http.Request) (io.ReadCloser, error)

CopyRequestBody returns copy of request body and keeps the original one to prevent error when reading closed body

func DeclareFixedRoles

func DeclareFixedRoles(service Service, cfg *setting.Cfg) error

Declare OSS roles to the accesscontrol service

func ErrAssignmentEntityNotFoundData

func ErrAssignmentEntityNotFoundData(assignment string) errutil.TemplateData

func ErrInvalidBuiltinRoleData

func ErrInvalidBuiltinRoleData(builtInRole string) errutil.TemplateData

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 GetBasicRolePermissionCacheKey

func GetBasicRolePermissionCacheKey(role string, orgID int64) string

func GetOrgRoles

func GetOrgRoles(user identity.Requester) []string

GetOrgRoles returns legacy org roles for a user

func GetPermissionCacheKey

func GetPermissionCacheKey(user identity.Requester) string

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 GetSearchPermissionCacheKey

func GetSearchPermissionCacheKey(user identity.Requester, searchOptions SearchOptions) string

func GetTeamPermissionCacheKey

func GetTeamPermissionCacheKey(teamID int64, orgID int64) string

func GetUserDirectPermissionCacheKey

func GetUserDirectPermissionCacheKey(user identity.Requester) string

func GroupScopesByAction

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

GroupScopesByAction will group scopes on action

func HasAccess

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

func HasGlobalAccess

func HasGlobalAccess(ac AccessControl, authnService authn.Service, c *contextmodel.ReqContext) func(evaluator Evaluator) bool

HasGlobalAccess checks user access with globally assigned permissions only

func ManagedBuiltInRoleName

func ManagedBuiltInRoleName(builtInRole string) string

func ManagedTeamRoleName

func ManagedTeamRoleName(teamID int64) string

func ManagedUserRoleName

func ManagedUserRoleName(userID int64) string

func Middleware

func Middleware(ac AccessControl) func(Evaluator) web.Handler

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 ParseScopeID

func ParseScopeID(scope string) (int64, error)

func ParseScopeUID

func ParseScopeUID(scope string) (string, error)

func ParseScopes

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

func PrefixedRoleUID

func PrefixedRoleUID(roleName string) string

PrefixedRoleUID generates a uid from name with the same prefix. Generated uid is 28 bytes + length of prefix: <prefix>_base64(sha1(roleName))

func Reduce

func Reduce(ps []Permission) map[string][]string

Reduce will reduce a list of permissions to its minimal form, grouping scopes by action

func ReqHasRole

func ReqHasRole(role org.RoleType) func(c *contextmodel.ReqContext) bool

ReqHasRole generates a fallback to check whether the user has a role ReqHasRole(org.RoleAdmin) will always return true for Grafana server admins, eg, a Grafana Admin / Viewer role combination

func RolePrefixesFilter

func RolePrefixesFilter(rolePrefixes []string) (string, []any)

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 ScopeSuffix

func ScopeSuffix(scope string) string

func SetAcceptListForTest

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

SetAcceptListForTest allow us to mutate the list for blackbox testing

func UseGlobalOrg

func UseGlobalOrg(c *contextmodel.ReqContext) (int64, error)

func UseOrgFromContextParams

func UseOrgFromContextParams(c *contextmodel.ReqContext) (int64, error)

func UseOrgFromRequestData

func UseOrgFromRequestData(c *contextmodel.ReqContext) (int64, error)

UseOrgFromRequestData returns the organization from the request data. If no org is specified, then the org where user is logged in is returned.

func UserRolesFilter

func UserRolesFilter(orgID, userID int64, teamIDs []int64, roles []string) (string, []any)

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 identity.Requester, 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)
}

type ActionResolver

type ActionResolver interface {
	ExpandActionSets(permissions []Permission) []Permission
}

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 DashboardPermissionsService

type DashboardPermissionsService interface {
	PermissionsService
}

type DatasourcePermissionsService

type DatasourcePermissionsService interface {
	PermissionsService
}

type ErrorActionPrefixMissing

type ErrorActionPrefixMissing struct {
	Action   string
	Prefixes []string
}

func (*ErrorActionPrefixMissing) Error

func (e *ErrorActionPrefixMissing) Error() string

func (*ErrorActionPrefixMissing) Unwrap

func (e *ErrorActionPrefixMissing) Unwrap() error

type ErrorInvalidRole

type ErrorInvalidRole struct{}

func (*ErrorInvalidRole) Error

func (e *ErrorInvalidRole) Error() string

type ErrorRoleNameMissing

type ErrorRoleNameMissing struct{}

func (*ErrorRoleNameMissing) Error

func (e *ErrorRoleNameMissing) Error() string

func (*ErrorRoleNameMissing) Unwrap

func (e *ErrorRoleNameMissing) Unwrap() error

type ErrorRolePrefixMissing

type ErrorRolePrefixMissing struct {
	Role     string
	Prefixes []string
}

func (*ErrorRolePrefixMissing) Error

func (e *ErrorRolePrefixMissing) Error() string

func (*ErrorRolePrefixMissing) Unwrap

func (e *ErrorRolePrefixMissing) Unwrap() error

type ErrorScopeTarget

type ErrorScopeTarget struct {
	Action        string
	Scope         string
	ExpectedScope string
}

func (*ErrorScopeTarget) Error

func (e *ErrorScopeTarget) Error() string

func (*ErrorScopeTarget) Unwrap

func (e *ErrorScopeTarget) Unwrap() error

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 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 at least one of passed scopes to match

type FolderPermissionsService

type FolderPermissionsService interface {
	PermissionsService
}

type GetUserPermissionsQuery

type GetUserPermissionsQuery struct {
	OrgID        int64
	UserID       int64
	Roles        []string
	TeamIDs      []int64
	RolePrefixes []string
}

type Metadata

type Metadata map[string]bool

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

func MergeMeta

func MergeMeta(prefix string, first Metadata, second Metadata) Metadata

MergeMeta will merge actions matching prefix of second metadata into first

type Options

type Options struct {
	ReloadCache bool
}

type OrgIDGetter

type OrgIDGetter func(c *contextmodel.ReqContext) (int64, error)

func UseGlobalOrSingleOrg

func UseGlobalOrSingleOrg(cfg *setting.Cfg) OrgIDGetter

UseGlobalOrSingleOrg returns the global organization or the current organization in a single organization setup

func UseGlobalOrgFromRequestData

func UseGlobalOrgFromRequestData(cfg *setting.Cfg) OrgIDGetter

UseGlobalOrgFromRequestData returns global org if `global` flag is set or the org where user is logged in. If RBACSingleOrganization is set, the org where user is logged in is returned - this is intended only for cloud workflows, where instances are limited to a single organization.

func UseGlobalOrgFromRequestParams

func UseGlobalOrgFromRequestParams(cfg *setting.Cfg) OrgIDGetter

UseGlobalOrgFromRequestParams returns global org if `global` flag is set or the org where user is logged in.

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"`

	Kind       string `json:"-"`
	Attribute  string `json:"-"`
	Identifier string `json:"-"`

	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

func (Permission) SplitScope

func (p Permission) SplitScope() (string, string, string)

SplitScope returns kind, attribute and Identifier

type PermissionsService

type PermissionsService interface {
	// GetPermissions returns all permissions for given resourceID
	GetPermissions(ctx context.Context, user identity.Requester, 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
	// DeleteResourcePermissions removes all permissions for a resource
	DeleteResourcePermissions(ctx context.Context, orgID int64, resourceID string) error
}

type QueryWithOrg

type QueryWithOrg struct {
	OrgId  *int64 `json:"orgId"`
	Global bool   `json:"global"`
}

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)

func (*RegistrationList) Slice

func (m *RegistrationList) Slice() []RoleRegistration

type Resolvers

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

func NewResolvers

func NewResolvers(log log.Logger) Resolvers

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
	IsServiceAccount 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,omitempty"`
	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) Global

func (r *Role) Global() bool

func (*Role) IsBasic

func (r *Role) IsBasic() 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,omitempty"`
	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"`
}

swagger:ignore

func (*RoleDTO) Global

func (r *RoleDTO) Global() bool

func (*RoleDTO) IsBasic

func (r *RoleDTO) IsBasic() bool

func (*RoleDTO) IsExternalService

func (r *RoleDTO) IsExternalService() bool

func (*RoleDTO) IsFixed

func (r *RoleDTO) IsFixed() bool

func (*RoleDTO) IsManaged

func (r *RoleDTO) IsManaged() bool

func (*RoleDTO) IsPlugin

func (r *RoleDTO) IsPlugin() bool

func (*RoleDTO) LogID

func (r *RoleDTO) LogID() string

func (RoleDTO) MarshalJSON

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

func (*RoleDTO) Role

func (r *RoleDTO) Role() Role

type RoleDTOStatic

type RoleDTOStatic struct {
	RoleDTO
	Global bool `json:"global" xorm:"-"`
}

swagger:model RoleDTO

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(ctx context.Context) error
}

type SQLFilter

type SQLFilter struct {
	Where string
	Args  []any
}

func Filter

func Filter(user identity.Requester, 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 SaveExternalServiceRoleCommand

type SaveExternalServiceRoleCommand struct {
	AssignmentOrgID   int64
	ExternalServiceID string
	ServiceAccountID  int64
	Permissions       []Permission
}

func (*SaveExternalServiceRoleCommand) Validate

func (cmd *SaveExternalServiceRoleCommand) Validate() error

type ScopeAttributeMutator

type ScopeAttributeMutator func(context.Context, string) ([]string, error)

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

func (ScopeAttributeResolverFunc) Resolve

func (f ScopeAttributeResolverFunc) Resolve(ctx context.Context, orgID int64, scope string) ([]string, error)

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 SearchOptions

type SearchOptions struct {
	ActionPrefix string // Needed for the PoC v1, it's probably going to be removed.
	Action       string
	Scope        string
	NamespacedID string // ID of the identity (ex: user:3, service-account:4)

	RolePrefixes []string
	// contains filtered or unexported fields
}

func (*SearchOptions) ComputeUserID

func (s *SearchOptions) ComputeUserID() (int64, error)

func (*SearchOptions) Wildcards

func (s *SearchOptions) Wildcards() []string

Wildcards computes the wildcard scopes that include the scope

type Service

type Service interface {
	registry.ProvidesUsageStats
	// GetRoleByName returns a role by name
	GetRoleByName(ctx context.Context, orgID int64, roleName string) (*RoleDTO, error)
	// GetUserPermissions returns user permissions with only action and scope fields set.
	GetUserPermissions(ctx context.Context, user identity.Requester, options Options) ([]Permission, error)
	// SearchUsersPermissions returns all users' permissions filtered by an action prefix
	SearchUsersPermissions(ctx context.Context, user identity.Requester, options SearchOptions) (map[int64][]Permission, error)
	// ClearUserPermissionCache removes the permission cache entry for the given user
	ClearUserPermissionCache(user identity.Requester)
	// SearchUserPermissions returns single user's permissions filtered by an action prefix or an action
	SearchUserPermissions(ctx context.Context, orgID int64, filterOptions SearchOptions) ([]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
	// DeleteTeamPermissions removes all role assignments and permissions granted to a team
	// and removes permissions scoped to the team.
	DeleteTeamPermissions(ctx context.Context, orgID, teamID 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
	// SaveExternalServiceRole creates or updates an external service's role and assigns it to a given service account id.
	SaveExternalServiceRole(ctx context.Context, cmd SaveExternalServiceRoleCommand) error
	// DeleteExternalServiceRole removes an external service's role and its assignment.
	DeleteExternalServiceRole(ctx context.Context, externalServiceID string) error
	// SyncUserRoles adds provided roles to user
	SyncUserRoles(ctx context.Context, orgID int64, cmd SyncUserRolesCommand) error
}

type ServiceAccountPermissionsService

type ServiceAccountPermissionsService interface {
	PermissionsService
}

type SetResourcePermissionCommand

type SetResourcePermissionCommand struct {
	UserID      int64  `json:"userId,omitempty"`
	TeamID      int64  `json:"teamId,omitempty"`
	BuiltinRole string `json:"builtInRole,omitempty"`
	Permission  string `json:"permission"`
}

type Store

type Store interface {
	GetUserPermissions(ctx context.Context, query GetUserPermissionsQuery) ([]Permission, error)
	GetBasicRolesPermissions(ctx context.Context, query GetUserPermissionsQuery) ([]Permission, error)
	GetTeamsPermissions(ctx context.Context, query GetUserPermissionsQuery) (map[int64][]Permission, error)
	SearchUsersPermissions(ctx context.Context, orgID int64, options SearchOptions) (map[int64][]Permission, error)
	GetUsersBasicRoles(ctx context.Context, userFilter []int64, orgID int64) (map[int64][]string, error)
	DeleteUserPermissions(ctx context.Context, orgID, userID int64) error
	DeleteTeamPermissions(ctx context.Context, orgID, teamID int64) error
	SaveExternalServiceRole(ctx context.Context, cmd SaveExternalServiceRoleCommand) error
	DeleteExternalServiceRole(ctx context.Context, externalServiceID string) error
}

type SyncUserRolesCommand

type SyncUserRolesCommand struct {
	UserID int64
	// name of roles the user should have
	RolesToAdd []string
	// name of roles the user should not have
	RolesToRemove []string
}

type TeamPermissionsService

type TeamPermissionsService interface {
	GetPermissions(ctx context.Context, user identity.Requester, resourceID string) ([]ResourcePermission, error)
	SetUserPermission(ctx context.Context, orgID int64, user User, resourceID, permission string) (*ResourcePermission, error)
	SetPermissions(ctx context.Context, orgID int64, resourceID string, commands ...SetResourcePermissionCommand) ([]ResourcePermission, error)
}

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
}

type Wildcards

type Wildcards []string

func WildcardsFromPrefix

func WildcardsFromPrefix(prefix string) Wildcards

func WildcardsFromPrefixes

func WildcardsFromPrefixes(prefixes []string) Wildcards

WildcardsFromPrefixes generates valid wildcards from prefixes datasource:uid: => "*", "datasource:*", "datasource:uid:*"

func (Wildcards) Contains

func (wildcards Wildcards) Contains(scope string) bool

Contains check if wildcards contains scope

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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