rbac
packageThis package is not in the latest version of its module.
Details
Validgo.mod file
The Go module system was introduced in Go 1.11 and is the official dependency management solution for Go.
Redistributable license
Redistributable licenses place minimal restrictions on how software can be used, modified, and redistributed.
Tagged version
Modules with tagged versions give importers more predictable builds.
Stable version
When a project reaches major version v1 it is considered stable.
- Learn more about best practices
Repository
Links
README¶
Authz
Packagerbac
implements Role-Based Access Control for Coder.
SeeUSAGE.md for a hands-on approach to using this package.
Overview
Authorization defines whatpermission asubject has to performactions toobjects:
- Permission is binary:yes (allowed) orno (denied).
- Subject in this case is anything that implements interface
rbac.Subject
. - Action here is an enumerated list of actions. Actions can differ for each object type. They typically read like,
Create
,Read
,Update
,Delete
, etc. - Object here is anything that implements
rbac.Object
.
Permission Structure
Apermission is a rule that grants or denies access for asubject to perform anaction on aobject.Apermission is always applied at a givenlevel:
- site level applies to all objects in a given Coder deployment.
- org level applies to all objects that have an organization owner (
org_owner
) - user level applies to all objects that have an owner with the same ID as the subject.
Permissions at a higherlevel always override permissions at alower level.
The effect of apermission can be:
- positive (allows)
- negative (denies)
- abstain (neither allows or denies, not applicable)
Negative permissionsalways overridepositive permissions at the same level.Bothnegative andpositive permissions overrideabstain at the same level.
This can be represented by the following truth table, where Y representspositive, N representsnegative, and _ representsabstain:
Action | Positive | Negative | Result |
---|---|---|---|
read | Y | _ | Y |
read | Y | N | N |
read | _ | _ | _ |
read | _ | N | N |
Permission Representation
Permissions are represented in string format as<sign>?<level>.<object>.<id>.<action>
, where:
negated
can be either+
or-
. If it is omitted, sign is assumed to be+
.level
is eithersite
,org
, oruser
.object
is any valid resource type.id
is any valid UUID v4.id
is included in the permission syntax, however only scopes may useid
to specify a specific object.action
is typicallycreate
,read
,modify
,delete
, but you can define other verbs as needed.
Example Permissions
+site.app.*.read
: allowed to perform theread
action against all objects of typeapp
in a given Coder deployment.-user.workspace.*.create
: user is not allowed to create workspaces.
Roles
Arole is a set of permissions. When evaluating a role's permission to form an action, all the relevant permissions for the role are combined at each level. Permissions at a higher level override permissions at a lower level.
The following table shows the per-level role evaluation.Y indicates that the role provides positive permissions, N indicates the role provides negative permissions, andindicates the role does not provide positive or negative permissions. YN indicates that the value in the cell does not matter for the access result.
Role (example) | Site | Org | User | Result |
---|---|---|---|---|
site-admin | Y | YN_ | YN_ | Y |
no-permission | N | YN_ | YN_ | N |
org-admin | _ | Y | YN_ | Y |
non-org-member | _ | N | YN_ | N |
user | _ | _ | Y | Y |
_ | _ | N | N | |
unauthenticated | _ | _ | _ | N |
Scopes
Scopes can restrict a given set of permissions. The format of a scope matches a role with the addition of a list of resource ids. For a authorization call to be successful, the subject's roles and the subject's scopes must both allow the action. This means the resulting permissions is the intersection of the subject's roles and the subject's scopes.
An example to give a readonly token is to grant a readonly scope across all resources+site.*.*.read
. The intersection with the user's permissions will be the readonly set of their permissions.
Resource IDs
There exists use cases that require specifying a specific resource. If resource IDs are allowed in the roles, then there isan unbounded set of resource IDs that be added to an "allow_list", as the number of roles a user can have is unbounded. This also adds a level of complexity to the role evaluation logic that has large costs at scale.
The use case for specifying this type of permission in a role is limited, and does not justify the extra cost. To solve this for the remaining cases (eg. workspace agent tokens), we can apply anallow_list
on a scope. For most cases, theallow_list
will just be["*"]
which means the scope is allowed to be applied to any resource. This adds negligible cost to the role evaluation logic and 0 cost to partial evaluations.
Example of a scope for a workspace agent token, using anallow_list
containing a single resource id.
"scope": { "name": "workspace_agent", "display_name": "Workspace_Agent", // The ID of the given workspace the agent token correlates to. "allow_list": ["10d03e62-7703-4df5-a358-4f76577d4e2f"], "site": [/* ... perms ... */], "org": {/* ... perms ... */}, "user": [/* ... perms ... */] }
Testing
You can test outside of golang by using theopa
cli.
Evaluation
opa eval --format=pretty "data.authz.allow" -d policy.rego -i input.json
Partial Evaluation
opa eval --partial --format=pretty 'data.authz.allow' -d policy.rego --unknowns input.object.owner --unknowns input.object.org_owner --unknowns input.object.acl_user_list --unknowns input.object.acl_group_list -i input.json
Documentation¶
Overview¶
Code generated by typegen/main.go. DO NOT EDIT.
Index¶
- Variables
- func AllActions() []policy.Action
- func CanAssignRole(subjectHasRoles ExpandableRoles, assignedRole RoleIdentifier) bool
- func ChangeRoleSet(from []RoleIdentifier, to []RoleIdentifier) (added []RoleIdentifier, removed []RoleIdentifier)
- func ConfigWithACL() regosql.ConvertConfig
- func ConfigWithoutACL() regosql.ConvertConfig
- func ConfigWorkspaces() regosql.ConvertConfig
- func Filter[O Objecter](ctx context.Context, auth Authorizer, subject Subject, action policy.Action, ...) ([]O, error)
- func IsUnauthorizedError(err error) bool
- func ReloadBuiltinRoles(opts *RoleOptions)
- func ReservedRoleName(name string) bool
- func RoleOrgAdmin() string
- func RoleOrgAuditor() string
- func RoleOrgMember() string
- func RoleOrgTemplateAdmin() string
- func RoleOrgUserAdmin() string
- func RoleOrgWorkspaceCreationBan() string
- func WithAuthzCheckRecorder(ctx context.Context) context.Context
- type AuthCall
- type AuthorizeFilter
- type Authorizer
- type AuthzCheckRecorder
- type ExpandableRoles
- type ExpandableScope
- type Object
- func (z Object) All() Object
- func (z Object) AnyOrganization() Object
- func (z Object) AvailableActions() []policy.Action
- func (z Object) Equal(b Object) bool
- func (z Object) InOrg(orgID uuid.UUID) Object
- func (z Object) RBACObject() Object
- func (z Object) String() string
- func (z Object) ValidAction(action policy.Action) error
- func (z Object) WithACLUserList(acl map[string][]policy.Action) Object
- func (z Object) WithGroupACL(groups map[string][]policy.Action) Object
- func (z Object) WithID(id uuid.UUID) Object
- func (z Object) WithIDString(id string) Object
- func (z Object) WithOwner(ownerID string) Object
- type Objecter
- type PartialAuthorizer
- type Permission
- type PreparedAuthorized
- type RegoAuthorizer
- type Role
- type RoleIdentifier
- func CustomOrganizationRole(orgID uuid.UUID) RoleIdentifier
- func CustomSiteRole() RoleIdentifier
- func RoleAuditor() RoleIdentifier
- func RoleMember() RoleIdentifier
- func RoleNameFromString(input string) (RoleIdentifier, error)
- func RoleOwner() RoleIdentifier
- func RoleTemplateAdmin() RoleIdentifier
- func RoleUserAdmin() RoleIdentifier
- func ScopedRoleOrgAdmin(organizationID uuid.UUID) RoleIdentifier
- func ScopedRoleOrgAuditor(organizationID uuid.UUID) RoleIdentifier
- func ScopedRoleOrgMember(organizationID uuid.UUID) RoleIdentifier
- func ScopedRoleOrgTemplateAdmin(organizationID uuid.UUID) RoleIdentifier
- func ScopedRoleOrgUserAdmin(organizationID uuid.UUID) RoleIdentifier
- func ScopedRoleOrgWorkspaceCreationBan(organizationID uuid.UUID) RoleIdentifier
- type RoleIdentifiers
- type RoleOptions
- type Roles
- type Scope
- type ScopeName
- type Subject
- type SubjectType
- type UnauthorizedError
- func (*UnauthorizedError) As(target interface{}) bool
- func (e UnauthorizedError) Error() string
- func (e *UnauthorizedError) Input() map[string]interface{}
- func (e *UnauthorizedError) Internal() error
- func (UnauthorizedError) IsUnauthorized() bool
- func (e *UnauthorizedError) Output() rego.ResultSet
- func (e *UnauthorizedError) SetInternal(err error)
- func (e UnauthorizedError) Unwrap() error
- type WorkspaceAgentScopeParams
Constants¶
This section is empty.
Variables¶
var (// ResourceWildcard// Valid ActionsResourceWildcard =Object{Type: "*",}// ResourceApiKey// Valid Actions// - "ActionCreate" :: create an api key// - "ActionDelete" :: delete an api key// - "ActionRead" :: read api key details (secrets are not stored)// - "ActionUpdate" :: update an api key, eg expiresResourceApiKey =Object{Type: "api_key",}// ResourceAssignOrgRole// Valid Actions// - "ActionAssign" :: assign org scoped roles// - "ActionCreate" :: create/delete custom roles within an organization// - "ActionDelete" :: delete roles within an organization// - "ActionRead" :: view what roles are assignable within an organization// - "ActionUnassign" :: unassign org scoped roles// - "ActionUpdate" :: edit custom roles within an organizationResourceAssignOrgRole =Object{Type: "assign_org_role",}// ResourceAssignRole// Valid Actions// - "ActionAssign" :: assign user roles// - "ActionRead" :: view what roles are assignable// - "ActionUnassign" :: unassign user rolesResourceAssignRole =Object{Type: "assign_role",}// ResourceAuditLog// Valid Actions// - "ActionCreate" :: create new audit log entries// - "ActionRead" :: read audit logsResourceAuditLog =Object{Type: "audit_log",}// ResourceChat// Valid Actions// - "ActionCreate" :: create a chat// - "ActionDelete" :: delete a chat// - "ActionRead" :: read a chat// - "ActionUpdate" :: update a chatResourceChat =Object{Type: "chat",}// ResourceCryptoKey// Valid Actions// - "ActionCreate" :: create crypto keys// - "ActionDelete" :: delete crypto keys// - "ActionRead" :: read crypto keys// - "ActionUpdate" :: update crypto keysResourceCryptoKey =Object{Type: "crypto_key",}// ResourceDebugInfo// Valid Actions// - "ActionRead" :: access to debug routesResourceDebugInfo =Object{Type: "debug_info",}// ResourceDeploymentConfig// Valid Actions// - "ActionRead" :: read deployment config// - "ActionUpdate" :: updating health informationResourceDeploymentConfig =Object{Type: "deployment_config",}// ResourceDeploymentStats// Valid Actions// - "ActionRead" :: read deployment statsResourceDeploymentStats =Object{Type: "deployment_stats",}// ResourceFile// Valid Actions// - "ActionCreate" :: create a file// - "ActionRead" :: read filesResourceFile =Object{Type: "file",}// ResourceGroup// Valid Actions// - "ActionCreate" :: create a group// - "ActionDelete" :: delete a group// - "ActionRead" :: read groups// - "ActionUpdate" :: update a groupResourceGroup =Object{Type: "group",}// ResourceGroupMember// Valid Actions// - "ActionRead" :: read group membersResourceGroupMember =Object{Type: "group_member",}// ResourceIdpsyncSettings// Valid Actions// - "ActionRead" :: read IdP sync settings// - "ActionUpdate" :: update IdP sync settingsResourceIdpsyncSettings =Object{Type: "idpsync_settings",}// ResourceInboxNotification// Valid Actions// - "ActionCreate" :: create inbox notifications// - "ActionRead" :: read inbox notifications// - "ActionUpdate" :: update inbox notificationsResourceInboxNotification =Object{Type: "inbox_notification",}// ResourceLicense// Valid Actions// - "ActionCreate" :: create a license// - "ActionDelete" :: delete license// - "ActionRead" :: read licensesResourceLicense =Object{Type: "license",}// ResourceNotificationMessage// Valid Actions// - "ActionCreate" :: create notification messages// - "ActionDelete" :: delete notification messages// - "ActionRead" :: read notification messages// - "ActionUpdate" :: update notification messagesResourceNotificationMessage =Object{Type: "notification_message",}// ResourceNotificationPreference// Valid Actions// - "ActionRead" :: read notification preferences// - "ActionUpdate" :: update notification preferencesResourceNotificationPreference =Object{Type: "notification_preference",}// ResourceNotificationTemplate// Valid Actions// - "ActionRead" :: read notification templates// - "ActionUpdate" :: update notification templatesResourceNotificationTemplate =Object{Type: "notification_template",}// ResourceOauth2App// Valid Actions// - "ActionCreate" :: make an OAuth2 app// - "ActionDelete" :: delete an OAuth2 app// - "ActionRead" :: read OAuth2 apps// - "ActionUpdate" :: update the properties of the OAuth2 appResourceOauth2App =Object{Type: "oauth2_app",}// ResourceOauth2AppCodeToken// Valid Actions// - "ActionCreate" :: create an OAuth2 app code token// - "ActionDelete" :: delete an OAuth2 app code token// - "ActionRead" :: read an OAuth2 app code tokenResourceOauth2AppCodeToken =Object{Type: "oauth2_app_code_token",}// ResourceOauth2AppSecret// Valid Actions// - "ActionCreate" :: create an OAuth2 app secret// - "ActionDelete" :: delete an OAuth2 app secret// - "ActionRead" :: read an OAuth2 app secret// - "ActionUpdate" :: update an OAuth2 app secretResourceOauth2AppSecret =Object{Type: "oauth2_app_secret",}// ResourceOrganization// Valid Actions// - "ActionCreate" :: create an organization// - "ActionDelete" :: delete an organization// - "ActionRead" :: read organizations// - "ActionUpdate" :: update an organizationResourceOrganization =Object{Type: "organization",}// ResourceOrganizationMember// Valid Actions// - "ActionCreate" :: create an organization member// - "ActionDelete" :: delete member// - "ActionRead" :: read member// - "ActionUpdate" :: update an organization memberResourceOrganizationMember =Object{Type: "organization_member",}// ResourceProvisionerDaemon// Valid Actions// - "ActionCreate" :: create a provisioner daemon/key// - "ActionDelete" :: delete a provisioner daemon/key// - "ActionRead" :: read provisioner daemon// - "ActionUpdate" :: update a provisioner daemonResourceProvisionerDaemon =Object{Type: "provisioner_daemon",}// ResourceProvisionerJobs// Valid Actions// - "ActionCreate" :: create provisioner jobs// - "ActionRead" :: read provisioner jobs// - "ActionUpdate" :: update provisioner jobsResourceProvisionerJobs =Object{Type: "provisioner_jobs",}// ResourceReplicas// Valid Actions// - "ActionRead" :: read replicasResourceReplicas =Object{Type: "replicas",}// ResourceSystem// Valid Actions// - "ActionCreate" :: create system resources// - "ActionDelete" :: delete system resources// - "ActionRead" :: view system resources// - "ActionUpdate" :: update system resources// DEPRECATED: New resources should be created for new things, rather than adding them to System, which has become// an unmanaged collection of things that don't relate to one another. We can't effectively enforce// least privilege access control when unrelated resources are grouped together.ResourceSystem =Object{Type: "system",}// ResourceTailnetCoordinator// Valid Actions// - "ActionCreate" :: create a Tailnet coordinator// - "ActionDelete" :: delete a Tailnet coordinator// - "ActionRead" :: view info about a Tailnet coordinator// - "ActionUpdate" :: update a Tailnet coordinatorResourceTailnetCoordinator =Object{Type: "tailnet_coordinator",}// ResourceTemplate// Valid Actions// - "ActionCreate" :: create a template// - "ActionDelete" :: delete a template// - "ActionRead" :: read template// - "ActionUpdate" :: update a template// - "ActionUse" :: use the template to initially create a workspace, then workspace lifecycle permissions take over// - "ActionViewInsights" :: view insightsResourceTemplate =Object{Type: "template",}// ResourceUser// Valid Actions// - "ActionCreate" :: create a new user// - "ActionDelete" :: delete an existing user// - "ActionRead" :: read user data// - "ActionReadPersonal" :: read personal user data like user settings and auth links// - "ActionUpdate" :: update an existing user// - "ActionUpdatePersonal" :: update personal dataResourceUser =Object{Type: "user",}// ResourceWebpushSubscription// Valid Actions// - "ActionCreate" :: create webpush subscriptions// - "ActionDelete" :: delete webpush subscriptions// - "ActionRead" :: read webpush subscriptionsResourceWebpushSubscription =Object{Type: "webpush_subscription",}// ResourceWorkspace// Valid Actions// - "ActionApplicationConnect" :: connect to workspace apps via browser// - "ActionCreate" :: create a new workspace// - "ActionCreateAgent" :: create a new workspace agent// - "ActionDelete" :: delete workspace// - "ActionDeleteAgent" :: delete an existing workspace agent// - "ActionRead" :: read workspace data to view on the UI// - "ActionSSH" :: ssh into a given workspace// - "ActionWorkspaceStart" :: allows starting a workspace// - "ActionWorkspaceStop" :: allows stopping a workspace// - "ActionUpdate" :: edit workspace settings (scheduling, permissions, parameters)ResourceWorkspace =Object{Type: "workspace",}// ResourceWorkspaceAgentDevcontainers// Valid Actions// - "ActionCreate" :: create workspace agent devcontainersResourceWorkspaceAgentDevcontainers =Object{Type: "workspace_agent_devcontainers",}// ResourceWorkspaceAgentResourceMonitor// Valid Actions// - "ActionCreate" :: create workspace agent resource monitor// - "ActionRead" :: read workspace agent resource monitor// - "ActionUpdate" :: update workspace agent resource monitorResourceWorkspaceAgentResourceMonitor =Object{Type: "workspace_agent_resource_monitor",}// ResourceWorkspaceDormant// Valid Actions// - "ActionApplicationConnect" :: connect to workspace apps via browser// - "ActionCreate" :: create a new workspace// - "ActionCreateAgent" :: create a new workspace agent// - "ActionDelete" :: delete workspace// - "ActionDeleteAgent" :: delete an existing workspace agent// - "ActionRead" :: read workspace data to view on the UI// - "ActionSSH" :: ssh into a given workspace// - "ActionWorkspaceStart" :: allows starting a workspace// - "ActionWorkspaceStop" :: allows stopping a workspace// - "ActionUpdate" :: edit workspace settings (scheduling, permissions, parameters)ResourceWorkspaceDormant =Object{Type: "workspace_dormant",}// ResourceWorkspaceProxy// Valid Actions// - "ActionCreate" :: create a workspace proxy// - "ActionDelete" :: delete a workspace proxy// - "ActionRead" :: read and use a workspace proxy// - "ActionUpdate" :: update a workspace proxyResourceWorkspaceProxy =Object{Type: "workspace_proxy",})
Functions¶
funcAllActions¶
funcCanAssignRole¶
func CanAssignRole(subjectHasRolesExpandableRoles, assignedRoleRoleIdentifier)bool
CanAssignRole is a helper function that returns true if the user can assignthe specified role. This also can be used for removing a role.This is a simple implementation for now.
funcChangeRoleSet¶
func ChangeRoleSet(from []RoleIdentifier, to []RoleIdentifier) (added []RoleIdentifier, removed []RoleIdentifier)
ChangeRoleSet is a helper function that finds the difference of 2 sets ofroles. When setting a user's new roles, it is equivalent to adding andremoving roles. This set determines the changes, so that the appropriateRBAC checks can be applied using "ActionCreate" and "ActionDelete" for"added" and "removed" roles respectively.
funcConfigWithACL¶
func ConfigWithACL()regosql.ConvertConfig
ConfigWithACL is the basic configuration for converting rego to SQL whenthe object has group and user ACL fields.
funcConfigWithoutACL¶
func ConfigWithoutACL()regosql.ConvertConfig
ConfigWithoutACL is the basic configuration for converting rego to SQL whenthe object has no ACL fields.
funcConfigWorkspaces¶added inv2.8.0
func ConfigWorkspaces()regosql.ConvertConfig
funcFilter¶
func Filter[OObjecter](ctxcontext.Context, authAuthorizer, subjectSubject, actionpolicy.Action, objects []O) ([]O,error)
Filter takes in a list of objects, and will filter the list removing allthe elements the subject does not have permission for. All objects must beof the same type.
Ideally the 'CompileToSQL' is used instead for large sets. This cost scaleslinearly with the number of objects passed in.
funcIsUnauthorizedError¶
IsUnauthorizedError is a convenience function to check if err is UnauthorizedError.It is equivalent to errors.As(err, &UnauthorizedError{}).
funcReloadBuiltinRoles¶
func ReloadBuiltinRoles(opts *RoleOptions)
ReloadBuiltinRoles loads the static roles into the builtInRoles map.This can be called again with a different config to change the behavior.
TODO: @emyrk This would be great if it was instanced to a coderd ratherthan a global. But that is a much larger refactor right now.Essentially we did not foresee different deployments needing slightlydifferent role permissions.
funcReservedRoleName¶added inv2.13.0
ReservedRoleName exists because the database should only allow unique rolenames, but some roles are built in. So these names are reserved
funcRoleOrgAdmin¶
func RoleOrgAdmin()string
funcRoleOrgAuditor¶added inv2.14.0
func RoleOrgAuditor()string
funcRoleOrgMember¶
func RoleOrgMember()string
funcRoleOrgTemplateAdmin¶added inv2.14.0
func RoleOrgTemplateAdmin()string
funcRoleOrgUserAdmin¶added inv2.14.0
func RoleOrgUserAdmin()string
funcRoleOrgWorkspaceCreationBan¶added inv2.20.0
func RoleOrgWorkspaceCreationBan()string
Types¶
typeAuthorizeFilter¶
type AuthorizeFilter interface {SQLString()string}
AuthorizeFilter is a compiled partial query that can be converted to SQL.This allows enforcing the policy on the database side in a WHERE clause.
funcCompile¶
func Compile(cfgregosql.ConvertConfig, pa *PartialAuthorizer) (AuthorizeFilter,error)
typeAuthorizer¶
type Authorizer interface {// Authorize will authorize the given subject to perform the given action// on the given object. Authorize is pure and deterministic with respect to// its arguments and the surrounding object.Authorize(ctxcontext.Context, subjectSubject, actionpolicy.Action, objectObject)errorPrepare(ctxcontext.Context, subjectSubject, actionpolicy.Action, objectTypestring) (PreparedAuthorized,error)}
funcCacher¶
func Cacher(authzAuthorizer)Authorizer
Cacher returns an Authorizer that can use a cache to short circuit duplicatecalls to the Authorizer. This is useful when multiple calls are made to theAuthorizer for the same subject, action, and object.This is a GLOBAL cache shared between all requests.If no cache is found on the context, the Authorizer is called as normal.
Cacher is safe for multiple actors.
funcNewCachingAuthorizer¶
func NewCachingAuthorizer(registryprometheus.Registerer)Authorizer
NewCachingAuthorizer returns a new RegoAuthorizer that supports context basedcaching. To utilize the caching, the context passed to Authorize() must becreated with 'WithCacheCtx(ctx)'.
funcNewStrictCachingAuthorizer¶added inv2.12.0
func NewStrictCachingAuthorizer(registryprometheus.Registerer)Authorizer
NewStrictCachingAuthorizer is mainly just for testing.
funcRecorder¶added inv2.22.0
func Recorder(authzAuthorizer)Authorizer
Recorder returns an Authorizer that records any authorization checks madeon the Context provided for the authorization check.
Requires using the RecordAuthzChecks middleware.
typeAuthzCheckRecorder¶added inv2.22.0
type AuthzCheckRecorder struct {// contains filtered or unexported fields}
funcGetAuthzCheckRecorder¶added inv2.22.0
func GetAuthzCheckRecorder(ctxcontext.Context) (*AuthzCheckRecorder,bool)
func (*AuthzCheckRecorder)String¶added inv2.22.0
func (r *AuthzCheckRecorder) String()string
String serializes all of the checks recorded, using the following syntax:
typeExpandableRoles¶
type ExpandableRoles interface {Expand() ([]Role,error)// Names is for logging and tracing purposes, we want to know the human// names of the expanded roles.Names() []RoleIdentifier}
ExpandableRoles is any type that can be expanded into a []Role. This is implementedas an interface so we can have RoleIdentifiers for user defined roles, and implementcustom ExpandableRoles for system type users (eg autostart/autostop system role).We want a clear divide between the two types of roles so users have no codepathto interact or assign system roles.
Note: We may also want to do the same thing with scopes to allow custom scopesupport unavailable to the user. Eg: Scope to a single resource.
typeExpandableScope¶
type ExpandableScope interface {Expand() (Scope,error)// Name is for logging and tracing purposes, we want to know the human// name of the scope.Name()RoleIdentifier}
typeObject¶
type Object struct {// ID is the resource's uuidIDstring `json:"id"`Ownerstring `json:"owner"`// OrgID specifies which org the object is a part of.OrgIDstring `json:"org_owner"`// AnyOrgOwner will disregard the org_owner when checking for permissions// Use this to ask, "Can the actor do this action on any org?" when// the exact organization is not important or known.// E.g: The UI should show a "create template" button if the user// can create a template in any org.AnyOrgOwnerbool `json:"any_org"`// Type is "workspace", "project", "app", etcTypestring `json:"type"`ACLUserList map[string][]policy.Action ` json:"acl_user_list"`ACLGroupList map[string][]policy.Action ` json:"acl_group_list"`}
Object is used to create objects for authz checks when you have none inhand to run the check on.An example is if you want to list all workspaces, you can create a Objectthat represents the set of workspaces you are trying to get access too.Do not export this type, as it can be created from a resource type constant.
funcResourceUserObject¶
ResourceUserObject is a helper function to create a user object for authz checks.
func (Object)AnyOrganization¶added inv2.14.0
func (Object)AvailableActions¶added inv2.12.0
AvailableActions returns all available actions for a given object.Wildcard is omitted.
func (Object)RBACObject¶
func (Object)ValidAction¶added inv2.12.0
ValidAction checks if the action is valid for the given object type.
func (Object)WithACLUserList¶
WithACLUserList adds an ACL list to a given object
func (Object)WithIDString¶
typeObjecter¶
type Objecter interface {RBACObject()Object}
Objecter returns the RBAC object for itself.
funcAllResources¶
func AllResources() []Objecter
typePartialAuthorizer¶
type PartialAuthorizer struct {// contains filtered or unexported fields}
PartialAuthorizer is a prepared authorizer with the subject, action, andresource type fields already filled in. This speeds up authorizationwhen authorizing the same type of object numerous times.See rbac.Filter for example usage.
func (*PartialAuthorizer)Authorize¶
func (pa *PartialAuthorizer) Authorize(ctxcontext.Context, objectObject)error
func (*PartialAuthorizer)CompileToSQL¶
func (pa *PartialAuthorizer) CompileToSQL(ctxcontext.Context, cfgregosql.ConvertConfig) (string,error)
CompileToSQL converts the remaining rego queries into SQL WHERE clauses.
typePermission¶
type Permission struct {// Negate makes this a negative permissionNegatebool `json:"negate"`ResourceTypestring `json:"resource_type"`Actionpolicy.Action `json:"action"`}
Permission is the format passed into the rego.
funcPermissions¶
func Permissions(perms map[string][]policy.Action) []Permission
Permissions is just a helper function to make building roles that list out resourcesand actions a bit easier.
func (Permission)Valid¶added inv2.12.0
func (permPermission) Valid()error
typeRegoAuthorizer¶
type RegoAuthorizer struct {// contains filtered or unexported fields}
RegoAuthorizer will use a prepared rego query for performing authorize()
funcNewAuthorizer¶
func NewAuthorizer(registryprometheus.Registerer) *RegoAuthorizer
func (RegoAuthorizer)Authorize¶
func (aRegoAuthorizer) Authorize(ctxcontext.Context, subjectSubject, actionpolicy.Action, objectObject)error
Authorize is the intended function to be used outside this package.It returns `nil` if the subject is authorized to perform the action onthe object.If an error is returned, the authorization is denied.
func (RegoAuthorizer)Prepare¶
func (aRegoAuthorizer) Prepare(ctxcontext.Context, subjectSubject, actionpolicy.Action, objectTypestring) (PreparedAuthorized,error)
Prepare will partially execute the rego policy leaving the object fields unknown (except for the type).This will vastly speed up performance if batch authorization on the same type of objects is needed.
typeRole¶
type Role struct {IdentifierRoleIdentifier `json:"name"`// DisplayName is used for UI purposes. If the role has no display name,// that means the UI should never display it.DisplayNamestring `json:"display_name"`Site []Permission `json:"site"`// Org is a map of orgid to permissions. We represent orgid as a string.// We scope the organizations in the role so we can easily combine all the// roles.Org map[string][]Permission `json:"org"`User []Permission `json:"user"`// contains filtered or unexported fields}
Role is a set of permissions at multiple levels:- Site level permissions apply EVERYWHERE- Org level permissions apply to EVERYTHING in a given ORG- User level permissions are the lowestThis is the type passed into the rego as a json payload.Users of this package should instead **only** use the role names, andthis package will expand the role names into their json payloads.
funcOrganizationRoles¶
OrganizationRoles lists all roles that can be applied to an organization userin the given organization. This is the list of available roles,and specific to an organization.
This should be a list in a database, but until then we buildthe list from the builtins.
funcRoleByName¶
func RoleByName(nameRoleIdentifier) (Role,error)
RoleByName returns the permissions associated with a given role name.This allows just the role names to be stored and expanded when required.
This function is exported so that the Display name can be returned to theapi. We should maybe make an exported function that returns just thehuman-readable content of the Role struct (name + display name).
funcSiteBuiltInRoles¶added inv2.23.0
func SiteBuiltInRoles() []Role
SiteBuiltInRoles lists all roles that can be applied to a user.This is the list of available roles, and not specific to a user
This should be a list in a database, but until then we buildthe list from the builtins.
typeRoleIdentifier¶added inv2.13.0
type RoleIdentifier struct {Namestring// OrganizationID is uuid.Nil for unscoped roles (aka deployment wide)OrganizationIDuuid.UUID}
RoleIdentifier contains both the name of the role, and any organizational scope.Both fields are required to be globally unique and identifiable.
funcCustomOrganizationRole¶added inv2.13.0
func CustomOrganizationRole(orgIDuuid.UUID)RoleIdentifier
funcCustomSiteRole¶added inv2.12.0
func CustomSiteRole()RoleIdentifier
funcRoleAuditor¶added inv2.13.0
func RoleAuditor()RoleIdentifier
funcRoleMember¶
func RoleMember()RoleIdentifier
funcRoleNameFromString¶added inv2.13.0
func RoleNameFromString(inputstring) (RoleIdentifier,error)
RoleNameFromString takes a formatted string '<role_name>[:org_id]'.
funcRoleOwner¶
func RoleOwner()RoleIdentifier
funcRoleTemplateAdmin¶
func RoleTemplateAdmin()RoleIdentifier
funcRoleUserAdmin¶
func RoleUserAdmin()RoleIdentifier
funcScopedRoleOrgAdmin¶added inv2.13.0
func ScopedRoleOrgAdmin(organizationIDuuid.UUID)RoleIdentifier
ScopedRoleOrgAdmin is the org role with the organization ID
funcScopedRoleOrgAuditor¶added inv2.14.0
func ScopedRoleOrgAuditor(organizationIDuuid.UUID)RoleIdentifier
funcScopedRoleOrgMember¶added inv2.13.0
func ScopedRoleOrgMember(organizationIDuuid.UUID)RoleIdentifier
ScopedRoleOrgMember is the org role with the organization ID
funcScopedRoleOrgTemplateAdmin¶added inv2.14.0
func ScopedRoleOrgTemplateAdmin(organizationIDuuid.UUID)RoleIdentifier
funcScopedRoleOrgUserAdmin¶added inv2.14.0
func ScopedRoleOrgUserAdmin(organizationIDuuid.UUID)RoleIdentifier
funcScopedRoleOrgWorkspaceCreationBan¶added inv2.20.0
func ScopedRoleOrgWorkspaceCreationBan(organizationIDuuid.UUID)RoleIdentifier
func (RoleIdentifier)IsOrgRole¶added inv2.13.0
func (rRoleIdentifier) IsOrgRole()bool
func (*RoleIdentifier)MarshalJSON¶added inv2.13.0
func (r *RoleIdentifier) MarshalJSON() ([]byte,error)
func (RoleIdentifier)String¶added inv2.13.0
func (rRoleIdentifier) String()string
func (RoleIdentifier)UniqueName¶added inv2.13.0
func (rRoleIdentifier) UniqueName()string
func (*RoleIdentifier)UnmarshalJSON¶added inv2.13.0
func (r *RoleIdentifier) UnmarshalJSON(data []byte)error
typeRoleIdentifiers¶added inv2.13.0
type RoleIdentifiers []RoleIdentifier
RoleIdentifiers is a list of user assignable role names. The role names must bein the builtInRoles map. Any non-user assignable roles will generate anerror on Expand.
func (RoleIdentifiers)Expand¶added inv2.13.0
func (namesRoleIdentifiers) Expand() ([]Role,error)
func (RoleIdentifiers)Names¶added inv2.13.0
func (namesRoleIdentifiers) Names() []RoleIdentifier
typeRoleOptions¶
type RoleOptions struct {NoOwnerWorkspaceExecbool}
typeScope¶
Scope acts the exact same as a Role with the addition that is can alsoapply an AllowIDList. Any resource being checked against a Scope willreject any resource that is not in the AllowIDList.To not use an AllowIDList to reject authorization, use a wildcard for theAllowIDList. Eg: 'AllowIDList: []string{WildcardSymbol}'
funcExpandScope¶
funcWorkspaceAgentScope¶
func WorkspaceAgentScope(paramsWorkspaceAgentScopeParams)Scope
WorkspaceAgentScope returns a scope that is the same as ScopeAll but can onlyaffect resources in the allow list. Only a scope is returned as the rolesshould come from the workspace owner.
func (Scope)Name¶
func (sScope) Name()RoleIdentifier
typeSubject¶
type Subject struct {// FriendlyName is entirely optional and is used for logging and debugging// It is not used in any functional way.// It is usually the "username" of the user, but it can be the name of the// external workspace proxy or other service type actor.FriendlyNamestring// Email is entirely optional and is used for logging and debugging// It is not used in any functional way.Emailstring// Type indicates what kind of subject this is (user, system, provisioner, etc.)// It is not used in any functional way, only for logging.TypeSubjectTypeIDstringRolesExpandableRolesGroups []stringScopeExpandableScope// contains filtered or unexported fields}
Subject is a struct that contains all the elements of a subject in an rbacauthorize.
func (Subject)RegoValueOk¶added inv2.13.0
RegoValueOk is only used for unit testing. There is no easy wayto get the error for the unexported method, and this is intentional.Failed rego values can default to the backup json marshal method,so errors are not fatal. Unit tests should be aware when the customrego marshaller fails.
func (Subject)SafeRoleNames¶
func (sSubject) SafeRoleNames() []RoleIdentifier
SafeRoleNames prevent nil pointer dereference.
func (Subject)SafeScopeName¶
SafeScopeName prevent nil pointer dereference.
func (Subject)WithCachedASTValue¶
WithCachedASTValue can be called if the subject is static. This will computethe ast value once and cache it for future calls.
typeSubjectType¶added inv2.19.2
type SubjectTypestring
SubjectType represents the type of subject in the RBAC system.
const (SubjectTypeUserSubjectType = "user"SubjectTypeProvisionerdSubjectType = "provisionerd"SubjectTypeAutostartSubjectType = "autostart"SubjectTypeJobReaperSubjectType = "job_reaper"SubjectTypeResourceMonitorSubjectType = "resource_monitor"SubjectTypeCryptoKeyRotatorSubjectType = "crypto_key_rotator"SubjectTypeCryptoKeyReaderSubjectType = "crypto_key_reader"SubjectTypePrebuildsOrchestratorSubjectType = "prebuilds_orchestrator"SubjectTypeSystemReadProvisionerDaemonsSubjectType = "system_read_provisioner_daemons"SubjectTypeSystemRestrictedSubjectType = "system_restricted"SubjectTypeNotifierSubjectType = "notifier")
typeUnauthorizedError¶
type UnauthorizedError struct {// contains filtered or unexported fields}
UnauthorizedError is the error type for authorization errors
funcForbiddenWithInternal¶
func ForbiddenWithInternal(internalerror, subjectSubject, actionpolicy.Action, objectObject, outputrego.ResultSet) *UnauthorizedError
ForbiddenWithInternal creates a new error that will return a simple"forbidden" to the client, logging internally the more detailed messageprovided.
func (*UnauthorizedError)As¶
func (*UnauthorizedError) As(target interface{})bool
As implements the errors.As interface.
func (UnauthorizedError)Error¶
func (eUnauthorizedError) Error()string
Error implements the error interface.
func (*UnauthorizedError)Input¶
func (e *UnauthorizedError) Input() map[string]interface{}
func (*UnauthorizedError)Internal¶
func (e *UnauthorizedError) Internal()error
Internal allows the internal error message to be logged.
func (UnauthorizedError)IsUnauthorized¶added inv2.1.5
func (UnauthorizedError) IsUnauthorized()bool
IsUnauthorized implements the IsUnauthorized interface.
func (*UnauthorizedError)Output¶
func (e *UnauthorizedError) Output()rego.ResultSet
Output contains the results of the Rego query for debugging.
func (*UnauthorizedError)SetInternal¶
func (e *UnauthorizedError) SetInternal(errerror)
func (UnauthorizedError)Unwrap¶
func (eUnauthorizedError) Unwrap()error
Source Files¶
Directories¶
Path | Synopsis |
---|---|
Package regosql converts rego queries into SQL WHERE clauses. | Package regosql converts rego queries into SQL WHERE clauses. |
sqltypes Package sqltypes contains the types used to convert rego queries into SQL. | Package sqltypes contains the types used to convert rego queries into SQL. |