github.com/gravitational/teleport/api@v0.0.0-20240507183017-3110591cbafc/types/role.go (about)

     1  /*
     2  Copyright 2020 Gravitational, Inc.
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8      http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package types
    18  
    19  import (
    20  	"encoding/json"
    21  	"fmt"
    22  	"net"
    23  	"path"
    24  	"slices"
    25  	"strings"
    26  	"time"
    27  
    28  	"github.com/gogo/protobuf/proto"
    29  	"github.com/gravitational/trace"
    30  
    31  	"github.com/gravitational/teleport/api/constants"
    32  	"github.com/gravitational/teleport/api/defaults"
    33  	"github.com/gravitational/teleport/api/types/wrappers"
    34  	"github.com/gravitational/teleport/api/utils"
    35  	"github.com/gravitational/teleport/api/utils/keys"
    36  )
    37  
    38  type OnSessionLeaveAction string
    39  
    40  const (
    41  	// OnSessionLeaveTerminate is a moderated sessions policy constant that terminates
    42  	// a session once the require policy is no longer fulfilled.
    43  	OnSessionLeaveTerminate OnSessionLeaveAction = "terminate"
    44  
    45  	// OnSessionLeaveTerminate is a moderated sessions policy constant that pauses
    46  	// a session once the require policies is no longer fulfilled. It is resumed
    47  	// once the requirements are fulfilled again.
    48  	OnSessionLeavePause OnSessionLeaveAction = "pause"
    49  )
    50  
    51  // Match checks if the given role matches this filter.
    52  func (f *RoleFilter) Match(role *RoleV6) bool {
    53  	if f.SkipSystemRoles && IsSystemResource(role) {
    54  		return false
    55  	}
    56  
    57  	if len(f.SearchKeywords) != 0 {
    58  		if !role.MatchSearch(f.SearchKeywords) {
    59  			return false
    60  		}
    61  	}
    62  
    63  	return true
    64  }
    65  
    66  // Role contains a set of permissions or settings
    67  type Role interface {
    68  	// Resource provides common resource methods.
    69  	ResourceWithLabels
    70  
    71  	// SetMetadata sets role metadata
    72  	SetMetadata(meta Metadata)
    73  
    74  	// GetOptions gets role options.
    75  	GetOptions() RoleOptions
    76  	// SetOptions sets role options
    77  	SetOptions(opt RoleOptions)
    78  
    79  	// GetCreateDatabaseUserMode gets the create database user mode option.
    80  	GetCreateDatabaseUserMode() CreateDatabaseUserMode
    81  
    82  	// GetLogins gets *nix system logins for allow or deny condition.
    83  	GetLogins(RoleConditionType) []string
    84  	// SetLogins sets *nix system logins for allow or deny condition.
    85  	SetLogins(RoleConditionType, []string)
    86  
    87  	// GetNamespaces gets a list of namespaces this role is allowed or denied access to.
    88  	GetNamespaces(RoleConditionType) []string
    89  	// SetNamespaces sets a list of namespaces this role is allowed or denied access to.
    90  	SetNamespaces(RoleConditionType, []string)
    91  
    92  	// GetLabelMatchers gets the LabelMatchers that match labels of resources of
    93  	// type [kind] this role is allowed or denied access to.
    94  	GetLabelMatchers(rct RoleConditionType, kind string) (LabelMatchers, error)
    95  	// SetLabelMatchers sets the LabelMatchers that match labels of resources of
    96  	// type [kind] this role is allowed or denied access to.
    97  	SetLabelMatchers(rct RoleConditionType, kind string, labelMatchers LabelMatchers) error
    98  
    99  	// GetNodeLabels gets the map of node labels this role is allowed or denied access to.
   100  	GetNodeLabels(RoleConditionType) Labels
   101  	// SetNodeLabels sets the map of node labels this role is allowed or denied access to.
   102  	SetNodeLabels(RoleConditionType, Labels)
   103  
   104  	// GetAppLabels gets the map of app labels this role is allowed or denied access to.
   105  	GetAppLabels(RoleConditionType) Labels
   106  	// SetAppLabels sets the map of app labels this role is allowed or denied access to.
   107  	SetAppLabels(RoleConditionType, Labels)
   108  
   109  	// GetClusterLabels gets the map of cluster labels this role is allowed or denied access to.
   110  	GetClusterLabels(RoleConditionType) Labels
   111  	// SetClusterLabels sets the map of cluster labels this role is allowed or denied access to.
   112  	SetClusterLabels(RoleConditionType, Labels)
   113  
   114  	// GetKubernetesLabels gets the map of kubernetes labels this role is
   115  	// allowed or denied access to.
   116  	GetKubernetesLabels(RoleConditionType) Labels
   117  	// SetKubernetesLabels sets the map of kubernetes labels this role is
   118  	// allowed or denied access to.
   119  	SetKubernetesLabels(RoleConditionType, Labels)
   120  
   121  	// GetRules gets all allow or deny rules.
   122  	GetRules(rct RoleConditionType) []Rule
   123  	// SetRules sets an allow or deny rule.
   124  	SetRules(rct RoleConditionType, rules []Rule)
   125  
   126  	// GetKubeGroups returns kubernetes groups
   127  	GetKubeGroups(RoleConditionType) []string
   128  	// SetKubeGroups sets kubernetes groups for allow or deny condition.
   129  	SetKubeGroups(RoleConditionType, []string)
   130  
   131  	// GetKubeUsers returns kubernetes users to impersonate
   132  	GetKubeUsers(RoleConditionType) []string
   133  	// SetKubeUsers sets kubernetes users to impersonate for allow or deny condition.
   134  	SetKubeUsers(RoleConditionType, []string)
   135  
   136  	// GetKubeResources returns the Kubernetes Resources this role grants
   137  	// access to.
   138  	GetKubeResources(rct RoleConditionType) []KubernetesResource
   139  	// SetKubeResources configures the Kubernetes Resources for the RoleConditionType.
   140  	SetKubeResources(rct RoleConditionType, pods []KubernetesResource)
   141  
   142  	// GetAccessRequestConditions gets allow/deny conditions for access requests.
   143  	GetAccessRequestConditions(RoleConditionType) AccessRequestConditions
   144  	// SetAccessRequestConditions sets allow/deny conditions for access requests.
   145  	SetAccessRequestConditions(RoleConditionType, AccessRequestConditions)
   146  
   147  	// GetAccessReviewConditions gets allow/deny conditions for access review.
   148  	GetAccessReviewConditions(RoleConditionType) AccessReviewConditions
   149  	// SetAccessReviewConditions sets allow/deny conditions for access review.
   150  	SetAccessReviewConditions(RoleConditionType, AccessReviewConditions)
   151  
   152  	// GetDatabaseLabels gets the map of db labels this role is allowed or denied access to.
   153  	GetDatabaseLabels(RoleConditionType) Labels
   154  	// SetDatabaseLabels sets the map of db labels this role is allowed or denied access to.
   155  	SetDatabaseLabels(RoleConditionType, Labels)
   156  
   157  	// GetDatabaseNames gets a list of database names this role is allowed or denied access to.
   158  	GetDatabaseNames(RoleConditionType) []string
   159  	// SetDatabaseNames sets a list of database names this role is allowed or denied access to.
   160  	SetDatabaseNames(RoleConditionType, []string)
   161  
   162  	// GetDatabaseUsers gets a list of database users this role is allowed or denied access to.
   163  	GetDatabaseUsers(RoleConditionType) []string
   164  	// SetDatabaseUsers sets a list of database users this role is allowed or denied access to.
   165  	SetDatabaseUsers(RoleConditionType, []string)
   166  
   167  	// GetDatabaseRoles gets a list of database roles for auto-provisioned users.
   168  	GetDatabaseRoles(RoleConditionType) []string
   169  	// SetDatabaseRoles sets a list of database roles for auto-provisioned users.
   170  	SetDatabaseRoles(RoleConditionType, []string)
   171  
   172  	// GetDatabasePermissions gets database permissions for auto-provisioned users.
   173  	GetDatabasePermissions(rct RoleConditionType) DatabasePermissions
   174  	// SetDatabasePermissions sets database permissions for auto-provisioned users.
   175  	SetDatabasePermissions(RoleConditionType, DatabasePermissions)
   176  
   177  	// GetImpersonateConditions returns conditions this role is allowed or denied to impersonate.
   178  	GetImpersonateConditions(rct RoleConditionType) ImpersonateConditions
   179  	// SetImpersonateConditions sets conditions this role is allowed or denied to impersonate.
   180  	SetImpersonateConditions(rct RoleConditionType, cond ImpersonateConditions)
   181  
   182  	// GetAWSRoleARNs returns a list of AWS role ARNs this role is allowed to assume.
   183  	GetAWSRoleARNs(RoleConditionType) []string
   184  	// SetAWSRoleARNs sets a list of AWS role ARNs this role is allowed to assume.
   185  	SetAWSRoleARNs(RoleConditionType, []string)
   186  
   187  	// GetAzureIdentities returns a list of Azure identities this role is allowed to assume.
   188  	GetAzureIdentities(RoleConditionType) []string
   189  	// SetAzureIdentities sets a list of Azure identities this role is allowed to assume.
   190  	SetAzureIdentities(RoleConditionType, []string)
   191  
   192  	// GetGCPServiceAccounts returns a list of GCP service accounts this role is allowed to assume.
   193  	GetGCPServiceAccounts(RoleConditionType) []string
   194  	// SetGCPServiceAccounts sets a list of GCP service accounts this role is allowed to assume.
   195  	SetGCPServiceAccounts(RoleConditionType, []string)
   196  
   197  	// GetWindowsDesktopLabels gets the Windows desktop labels this role
   198  	// is allowed or denied access to.
   199  	GetWindowsDesktopLabels(RoleConditionType) Labels
   200  	// SetWindowsDesktopLabels sets the Windows desktop labels this role
   201  	// is allowed or denied access to.
   202  	SetWindowsDesktopLabels(RoleConditionType, Labels)
   203  	// GetWindowsLogins gets Windows desktop logins for allow or deny condition.
   204  	GetWindowsLogins(RoleConditionType) []string
   205  	// SetWindowsLogins sets Windows desktop logins for allow or deny condition.
   206  	SetWindowsLogins(RoleConditionType, []string)
   207  
   208  	// GetSessionRequirePolicies returns the RBAC required policies for a session.
   209  	GetSessionRequirePolicies() []*SessionRequirePolicy
   210  	// SetSessionRequirePolicies sets the RBAC required policies for a session.
   211  	SetSessionRequirePolicies([]*SessionRequirePolicy)
   212  	// GetSessionJoinPolicies returns the RBAC join policies for a session.
   213  	GetSessionJoinPolicies() []*SessionJoinPolicy
   214  	// SetSessionJoinPolicies sets the RBAC join policies for a session.
   215  	SetSessionJoinPolicies([]*SessionJoinPolicy)
   216  	// GetSessionPolicySet returns the RBAC policy set for a role.
   217  	GetSessionPolicySet() SessionTrackerPolicySet
   218  
   219  	// GetSearchAsRoles returns the list of extra roles which should apply to a
   220  	// user while they are searching for resources as part of a Resource Access
   221  	// Request, and defines the underlying roles which will be requested as part
   222  	// of any Resource Access Request.
   223  	GetSearchAsRoles(RoleConditionType) []string
   224  	// SetSearchAsRoles sets the list of extra roles which should apply to a
   225  	// user while they are searching for resources as part of a Resource Access
   226  	// Request, and defines the underlying roles which will be requested as part
   227  	// of any Resource Access Request.
   228  	SetSearchAsRoles(RoleConditionType, []string)
   229  
   230  	// GetPreviewAsRoles returns the list of extra roles which should apply to a
   231  	// reviewer while they are viewing a Resource Access Request for the
   232  	// purposes of viewing details such as the hostname and labels of requested
   233  	// resources.
   234  	GetPreviewAsRoles(RoleConditionType) []string
   235  	// SetPreviewAsRoles sets the list of extra roles which should apply to a
   236  	// reviewer while they are viewing a Resource Access Request for the
   237  	// purposes of viewing details such as the hostname and labels of requested
   238  	// resources.
   239  	SetPreviewAsRoles(RoleConditionType, []string)
   240  
   241  	// GetHostGroups gets the list of groups this role is put in when users are provisioned
   242  	GetHostGroups(RoleConditionType) []string
   243  	// SetHostGroups sets the list of groups this role is put in when users are provisioned
   244  	SetHostGroups(RoleConditionType, []string)
   245  
   246  	// GetDesktopGroups gets the list of groups this role is put in when desktop users are provisioned
   247  	GetDesktopGroups(RoleConditionType) []string
   248  	// SetDesktopGroups sets the list of groups this role is put in when desktop users are provisioned
   249  	SetDesktopGroups(RoleConditionType, []string)
   250  
   251  	// GetHostSudoers gets the list of sudoers entries for the role
   252  	GetHostSudoers(RoleConditionType) []string
   253  	// SetHostSudoers sets the list of sudoers entries for the role
   254  	SetHostSudoers(RoleConditionType, []string)
   255  
   256  	// GetPrivateKeyPolicy returns the private key policy enforced for this role.
   257  	GetPrivateKeyPolicy() keys.PrivateKeyPolicy
   258  
   259  	// GetDatabaseServiceLabels gets the map of db service labels this role is allowed or denied access to.
   260  	GetDatabaseServiceLabels(RoleConditionType) Labels
   261  	// SetDatabaseServiceLabels sets the map of db service labels this role is allowed or denied access to.
   262  	SetDatabaseServiceLabels(RoleConditionType, Labels)
   263  
   264  	// GetGroupLabels gets the map of group labels this role is allowed or denied access to.
   265  	GetGroupLabels(RoleConditionType) Labels
   266  	// SetGroupLabels sets the map of group labels this role is allowed or denied access to.
   267  	SetGroupLabels(RoleConditionType, Labels)
   268  
   269  	// GetSPIFFEConditions returns the allow or deny SPIFFERoleCondition.
   270  	GetSPIFFEConditions(rct RoleConditionType) []*SPIFFERoleCondition
   271  	// SetSPIFFEConditions sets the allow or deny SPIFFERoleCondition.
   272  	SetSPIFFEConditions(rct RoleConditionType, cond []*SPIFFERoleCondition)
   273  }
   274  
   275  // NewRole constructs new standard V7 role.
   276  // This creates a V7 role with V4+ RBAC semantics.
   277  func NewRole(name string, spec RoleSpecV6) (Role, error) {
   278  	// When incrementing the role version, make sure to update the
   279  	// role version in the asset file used by the UI.
   280  	// See: web/packages/teleport/src/Roles/templates/role.yaml
   281  	role, err := NewRoleWithVersion(name, V7, spec)
   282  	return role, trace.Wrap(err)
   283  }
   284  
   285  // NewRoleWithVersion constructs new standard role with the version specified.
   286  func NewRoleWithVersion(name string, version string, spec RoleSpecV6) (Role, error) {
   287  	role := RoleV6{
   288  		Version: version,
   289  		Metadata: Metadata{
   290  			Name: name,
   291  		},
   292  		Spec: spec,
   293  	}
   294  	if err := role.CheckAndSetDefaults(); err != nil {
   295  		return nil, trace.Wrap(err)
   296  	}
   297  	return &role, nil
   298  }
   299  
   300  // RoleConditionType specifies if it's an allow rule (true) or deny rule (false).
   301  type RoleConditionType bool
   302  
   303  const (
   304  	// Allow is the set of conditions that allow access.
   305  	Allow RoleConditionType = true
   306  	// Deny is the set of conditions that prevent access.
   307  	Deny RoleConditionType = false
   308  )
   309  
   310  // GetVersion returns resource version
   311  func (r *RoleV6) GetVersion() string {
   312  	return r.Version
   313  }
   314  
   315  // GetKind returns resource kind
   316  func (r *RoleV6) GetKind() string {
   317  	return r.Kind
   318  }
   319  
   320  // GetSubKind returns resource sub kind
   321  func (r *RoleV6) GetSubKind() string {
   322  	return r.SubKind
   323  }
   324  
   325  // SetSubKind sets resource subkind
   326  func (r *RoleV6) SetSubKind(s string) {
   327  	r.SubKind = s
   328  }
   329  
   330  // GetResourceID returns resource ID
   331  func (r *RoleV6) GetResourceID() int64 {
   332  	return r.Metadata.ID
   333  }
   334  
   335  // SetResourceID sets resource ID
   336  func (r *RoleV6) SetResourceID(id int64) {
   337  	r.Metadata.ID = id
   338  }
   339  
   340  // GetRevision returns the revision
   341  func (r *RoleV6) GetRevision() string {
   342  	return r.Metadata.GetRevision()
   343  }
   344  
   345  // SetRevision sets the revision
   346  func (r *RoleV6) SetRevision(rev string) {
   347  	r.Metadata.SetRevision(rev)
   348  }
   349  
   350  // SetExpiry sets expiry time for the object.
   351  func (r *RoleV6) SetExpiry(expires time.Time) {
   352  	r.Metadata.SetExpiry(expires)
   353  }
   354  
   355  // Expiry returns the expiry time for the object.
   356  func (r *RoleV6) Expiry() time.Time {
   357  	return r.Metadata.Expiry()
   358  }
   359  
   360  // SetName sets the role name and is a shortcut for SetMetadata().Name.
   361  func (r *RoleV6) SetName(s string) {
   362  	r.Metadata.Name = s
   363  }
   364  
   365  // GetName gets the role name and is a shortcut for GetMetadata().Name.
   366  func (r *RoleV6) GetName() string {
   367  	return r.Metadata.Name
   368  }
   369  
   370  // GetMetadata returns role metadata.
   371  func (r *RoleV6) GetMetadata() Metadata {
   372  	return r.Metadata
   373  }
   374  
   375  // SetMetadata sets role metadata
   376  func (r *RoleV6) SetMetadata(meta Metadata) {
   377  	r.Metadata = meta
   378  }
   379  
   380  // GetOptions gets role options.
   381  func (r *RoleV6) GetOptions() RoleOptions {
   382  	return r.Spec.Options
   383  }
   384  
   385  // SetOptions sets role options.
   386  func (r *RoleV6) SetOptions(options RoleOptions) {
   387  	r.Spec.Options = options
   388  }
   389  
   390  // GetCreateDatabaseUserMode gets the create database user mode option.
   391  func (r *RoleV6) GetCreateDatabaseUserMode() CreateDatabaseUserMode {
   392  	if r.Spec.Options.CreateDatabaseUserMode != CreateDatabaseUserMode_DB_USER_MODE_UNSPECIFIED {
   393  		return r.Spec.Options.CreateDatabaseUserMode
   394  	}
   395  	// To keep backwards compatibility, look at the create database user option.
   396  	if r.Spec.Options.CreateDatabaseUser != nil && r.Spec.Options.CreateDatabaseUser.Value {
   397  		return CreateDatabaseUserMode_DB_USER_MODE_KEEP
   398  	}
   399  	return CreateDatabaseUserMode_DB_USER_MODE_OFF
   400  }
   401  
   402  // GetLogins gets system logins for allow or deny condition.
   403  func (r *RoleV6) GetLogins(rct RoleConditionType) []string {
   404  	if rct == Allow {
   405  		return r.Spec.Allow.Logins
   406  	}
   407  	return r.Spec.Deny.Logins
   408  }
   409  
   410  // SetLogins sets system logins for allow or deny condition.
   411  func (r *RoleV6) SetLogins(rct RoleConditionType, logins []string) {
   412  	lcopy := utils.CopyStrings(logins)
   413  
   414  	if rct == Allow {
   415  		r.Spec.Allow.Logins = lcopy
   416  	} else {
   417  		r.Spec.Deny.Logins = lcopy
   418  	}
   419  }
   420  
   421  // GetKubeGroups returns kubernetes groups
   422  func (r *RoleV6) GetKubeGroups(rct RoleConditionType) []string {
   423  	if rct == Allow {
   424  		return r.Spec.Allow.KubeGroups
   425  	}
   426  	return r.Spec.Deny.KubeGroups
   427  }
   428  
   429  // SetKubeGroups sets kubernetes groups for allow or deny condition.
   430  func (r *RoleV6) SetKubeGroups(rct RoleConditionType, groups []string) {
   431  	lcopy := utils.CopyStrings(groups)
   432  
   433  	if rct == Allow {
   434  		r.Spec.Allow.KubeGroups = lcopy
   435  	} else {
   436  		r.Spec.Deny.KubeGroups = lcopy
   437  	}
   438  }
   439  
   440  // GetKubeResources returns the Kubernetes Resources this role grants
   441  // access to.
   442  func (r *RoleV6) GetKubeResources(rct RoleConditionType) []KubernetesResource {
   443  	if rct == Allow {
   444  		return r.convertKubernetesResourcesBetweenRoleVersions(r.Spec.Allow.KubernetesResources)
   445  	}
   446  	return r.Spec.Deny.KubernetesResources
   447  }
   448  
   449  // convertKubeResourcesBetweenRoleVersions converts Kubernetes resources between role versions.
   450  // This is required to keep compatibility between role versions to avoid breaking changes
   451  // when upgrading Teleport.
   452  // For roles v7, it returns the list as it is.
   453  // For older roles <v7, if the kind is pod and name and namespace are wildcards,
   454  // then return a wildcard resource since RoleV6 and below do not restrict access
   455  // to other resources. This is a simple optimization to reduce the number of resources.
   456  // Finally, if the older role version is not a wildcard, then it returns the pod resources as is
   457  // and append the other supported resources - KubernetesResourcesKinds - for Role v7.
   458  func (r *RoleV6) convertKubernetesResourcesBetweenRoleVersions(resources []KubernetesResource) []KubernetesResource {
   459  	switch r.Version {
   460  	case V7:
   461  		return resources
   462  	// Teleport does not support role versions < v3.
   463  	case V6, V5, V4, V3:
   464  		switch {
   465  		// If role does not have kube labels, return empty list since it won't match
   466  		// any kubernetes cluster.
   467  		case !r.HasLabelMatchers(Allow, KindKubernetesCluster):
   468  			return nil
   469  			// If role is not V7 and resources is wildcard, return wildcard for kind as well.
   470  			// This is an optimization to avoid appending multiple resources.
   471  			// This check ignores the Kind field because `validateKubeResources` ensures
   472  			// that for older roles, the Kind field can only be pod.
   473  		case len(resources) == 1 && resources[0].Name == Wildcard && resources[0].Namespace == Wildcard:
   474  			return []KubernetesResource{{Kind: Wildcard, Name: Wildcard, Namespace: Wildcard, Verbs: []string{Wildcard}}}
   475  		default:
   476  			for _, resource := range KubernetesResourcesKinds {
   477  				// Ignore Pod resources for older roles because Pods were already supported
   478  				// so we don't need to keep backwards compatibility for them.
   479  				// Also ignore Namespace resources because it grants access to all resources
   480  				// in the namespace.
   481  				if resource == KindKubePod || resource == KindNamespace {
   482  					continue
   483  				}
   484  				resources = append(resources, KubernetesResource{Kind: resource, Name: Wildcard, Namespace: Wildcard, Verbs: []string{Wildcard}})
   485  			}
   486  			return resources
   487  		}
   488  	default:
   489  		return nil
   490  	}
   491  }
   492  
   493  // SetKubeResources configures the Kubernetes Resources for the RoleConditionType.
   494  func (r *RoleV6) SetKubeResources(rct RoleConditionType, pods []KubernetesResource) {
   495  	if rct == Allow {
   496  		r.Spec.Allow.KubernetesResources = pods
   497  	} else {
   498  		r.Spec.Deny.KubernetesResources = pods
   499  	}
   500  }
   501  
   502  // GetKubeUsers returns kubernetes users
   503  func (r *RoleV6) GetKubeUsers(rct RoleConditionType) []string {
   504  	if rct == Allow {
   505  		return r.Spec.Allow.KubeUsers
   506  	}
   507  	return r.Spec.Deny.KubeUsers
   508  }
   509  
   510  // SetKubeUsers sets kubernetes user for allow or deny condition.
   511  func (r *RoleV6) SetKubeUsers(rct RoleConditionType, users []string) {
   512  	lcopy := utils.CopyStrings(users)
   513  
   514  	if rct == Allow {
   515  		r.Spec.Allow.KubeUsers = lcopy
   516  	} else {
   517  		r.Spec.Deny.KubeUsers = lcopy
   518  	}
   519  }
   520  
   521  // GetAccessRequestConditions gets conditions for access requests.
   522  func (r *RoleV6) GetAccessRequestConditions(rct RoleConditionType) AccessRequestConditions {
   523  	cond := r.Spec.Deny.Request
   524  	if rct == Allow {
   525  		cond = r.Spec.Allow.Request
   526  	}
   527  	if cond == nil {
   528  		return AccessRequestConditions{}
   529  	}
   530  	return *cond
   531  }
   532  
   533  // SetAccessRequestConditions sets allow/deny conditions for access requests.
   534  func (r *RoleV6) SetAccessRequestConditions(rct RoleConditionType, cond AccessRequestConditions) {
   535  	if rct == Allow {
   536  		r.Spec.Allow.Request = &cond
   537  	} else {
   538  		r.Spec.Deny.Request = &cond
   539  	}
   540  }
   541  
   542  // GetAccessReviewConditions gets conditions for access reviews.
   543  func (r *RoleV6) GetAccessReviewConditions(rct RoleConditionType) AccessReviewConditions {
   544  	cond := r.Spec.Deny.ReviewRequests
   545  	if rct == Allow {
   546  		cond = r.Spec.Allow.ReviewRequests
   547  	}
   548  	if cond == nil {
   549  		return AccessReviewConditions{}
   550  	}
   551  	return *cond
   552  }
   553  
   554  // SetAccessReviewConditions sets allow/deny conditions for access reviews.
   555  func (r *RoleV6) SetAccessReviewConditions(rct RoleConditionType, cond AccessReviewConditions) {
   556  	if rct == Allow {
   557  		r.Spec.Allow.ReviewRequests = &cond
   558  	} else {
   559  		r.Spec.Deny.ReviewRequests = &cond
   560  	}
   561  }
   562  
   563  // GetNamespaces gets a list of namespaces this role is allowed or denied access to.
   564  func (r *RoleV6) GetNamespaces(rct RoleConditionType) []string {
   565  	if rct == Allow {
   566  		return r.Spec.Allow.Namespaces
   567  	}
   568  	return r.Spec.Deny.Namespaces
   569  }
   570  
   571  // SetNamespaces sets a list of namespaces this role is allowed or denied access to.
   572  func (r *RoleV6) SetNamespaces(rct RoleConditionType, namespaces []string) {
   573  	ncopy := utils.CopyStrings(namespaces)
   574  
   575  	if rct == Allow {
   576  		r.Spec.Allow.Namespaces = ncopy
   577  	} else {
   578  		r.Spec.Deny.Namespaces = ncopy
   579  	}
   580  }
   581  
   582  // GetNodeLabels gets the map of node labels this role is allowed or denied access to.
   583  func (r *RoleV6) GetNodeLabels(rct RoleConditionType) Labels {
   584  	if rct == Allow {
   585  		return r.Spec.Allow.NodeLabels
   586  	}
   587  	return r.Spec.Deny.NodeLabels
   588  }
   589  
   590  // SetNodeLabels sets the map of node labels this role is allowed or denied access to.
   591  func (r *RoleV6) SetNodeLabels(rct RoleConditionType, labels Labels) {
   592  	if rct == Allow {
   593  		r.Spec.Allow.NodeLabels = labels.Clone()
   594  	} else {
   595  		r.Spec.Deny.NodeLabels = labels.Clone()
   596  	}
   597  }
   598  
   599  // GetAppLabels gets the map of app labels this role is allowed or denied access to.
   600  func (r *RoleV6) GetAppLabels(rct RoleConditionType) Labels {
   601  	if rct == Allow {
   602  		return r.Spec.Allow.AppLabels
   603  	}
   604  	return r.Spec.Deny.AppLabels
   605  }
   606  
   607  // SetAppLabels sets the map of node labels this role is allowed or denied access to.
   608  func (r *RoleV6) SetAppLabels(rct RoleConditionType, labels Labels) {
   609  	if rct == Allow {
   610  		r.Spec.Allow.AppLabels = labels.Clone()
   611  	} else {
   612  		r.Spec.Deny.AppLabels = labels.Clone()
   613  	}
   614  }
   615  
   616  // GetClusterLabels gets the map of cluster labels this role is allowed or denied access to.
   617  func (r *RoleV6) GetClusterLabels(rct RoleConditionType) Labels {
   618  	if rct == Allow {
   619  		return r.Spec.Allow.ClusterLabels
   620  	}
   621  	return r.Spec.Deny.ClusterLabels
   622  }
   623  
   624  // SetClusterLabels sets the map of cluster labels this role is allowed or denied access to.
   625  func (r *RoleV6) SetClusterLabels(rct RoleConditionType, labels Labels) {
   626  	if rct == Allow {
   627  		r.Spec.Allow.ClusterLabels = labels.Clone()
   628  	} else {
   629  		r.Spec.Deny.ClusterLabels = labels.Clone()
   630  	}
   631  }
   632  
   633  // GetKubernetesLabels gets the map of app labels this role is allowed or denied access to.
   634  func (r *RoleV6) GetKubernetesLabels(rct RoleConditionType) Labels {
   635  	if rct == Allow {
   636  		return r.Spec.Allow.KubernetesLabels
   637  	}
   638  	return r.Spec.Deny.KubernetesLabels
   639  }
   640  
   641  // SetKubernetesLabels sets the map of node labels this role is allowed or denied access to.
   642  func (r *RoleV6) SetKubernetesLabels(rct RoleConditionType, labels Labels) {
   643  	if rct == Allow {
   644  		r.Spec.Allow.KubernetesLabels = labels.Clone()
   645  	} else {
   646  		r.Spec.Deny.KubernetesLabels = labels.Clone()
   647  	}
   648  }
   649  
   650  // GetDatabaseServiceLabels gets the map of db service labels this role is allowed or denied access to.
   651  func (r *RoleV6) GetDatabaseServiceLabels(rct RoleConditionType) Labels {
   652  	if rct == Allow {
   653  		return r.Spec.Allow.DatabaseServiceLabels
   654  	}
   655  	return r.Spec.Deny.DatabaseServiceLabels
   656  }
   657  
   658  // SetDatabaseServiceLabels sets the map of db service labels this role is allowed or denied access to.
   659  func (r *RoleV6) SetDatabaseServiceLabels(rct RoleConditionType, labels Labels) {
   660  	if rct == Allow {
   661  		r.Spec.Allow.DatabaseServiceLabels = labels.Clone()
   662  	} else {
   663  		r.Spec.Deny.DatabaseServiceLabels = labels.Clone()
   664  	}
   665  }
   666  
   667  // GetDatabaseLabels gets the map of db labels this role is allowed or denied access to.
   668  func (r *RoleV6) GetDatabaseLabels(rct RoleConditionType) Labels {
   669  	if rct == Allow {
   670  		return r.Spec.Allow.DatabaseLabels
   671  	}
   672  	return r.Spec.Deny.DatabaseLabels
   673  }
   674  
   675  // SetDatabaseLabels sets the map of db labels this role is allowed or denied access to.
   676  func (r *RoleV6) SetDatabaseLabels(rct RoleConditionType, labels Labels) {
   677  	if rct == Allow {
   678  		r.Spec.Allow.DatabaseLabels = labels.Clone()
   679  	} else {
   680  		r.Spec.Deny.DatabaseLabels = labels.Clone()
   681  	}
   682  }
   683  
   684  // GetDatabaseNames gets a list of database names this role is allowed or denied access to.
   685  func (r *RoleV6) GetDatabaseNames(rct RoleConditionType) []string {
   686  	if rct == Allow {
   687  		return r.Spec.Allow.DatabaseNames
   688  	}
   689  	return r.Spec.Deny.DatabaseNames
   690  }
   691  
   692  // SetDatabaseNames sets a list of database names this role is allowed or denied access to.
   693  func (r *RoleV6) SetDatabaseNames(rct RoleConditionType, values []string) {
   694  	if rct == Allow {
   695  		r.Spec.Allow.DatabaseNames = values
   696  	} else {
   697  		r.Spec.Deny.DatabaseNames = values
   698  	}
   699  }
   700  
   701  // GetDatabaseUsers gets a list of database users this role is allowed or denied access to.
   702  func (r *RoleV6) GetDatabaseUsers(rct RoleConditionType) []string {
   703  	if rct == Allow {
   704  		return r.Spec.Allow.DatabaseUsers
   705  	}
   706  	return r.Spec.Deny.DatabaseUsers
   707  }
   708  
   709  // SetDatabaseUsers sets a list of database users this role is allowed or denied access to.
   710  func (r *RoleV6) SetDatabaseUsers(rct RoleConditionType, values []string) {
   711  	if rct == Allow {
   712  		r.Spec.Allow.DatabaseUsers = values
   713  	} else {
   714  		r.Spec.Deny.DatabaseUsers = values
   715  	}
   716  }
   717  
   718  // GetDatabaseRoles gets a list of database roles for auto-provisioned users.
   719  func (r *RoleV6) GetDatabaseRoles(rct RoleConditionType) []string {
   720  	if rct == Allow {
   721  		return r.Spec.Allow.DatabaseRoles
   722  	}
   723  	return r.Spec.Deny.DatabaseRoles
   724  }
   725  
   726  // SetDatabaseRoles sets a list of database roles for auto-provisioned users.
   727  func (r *RoleV6) SetDatabaseRoles(rct RoleConditionType, values []string) {
   728  	if rct == Allow {
   729  		r.Spec.Allow.DatabaseRoles = values
   730  	} else {
   731  		r.Spec.Deny.DatabaseRoles = values
   732  	}
   733  }
   734  
   735  // GetDatabasePermissions gets a list of database permissions for auto-provisioned users.
   736  func (r *RoleV6) GetDatabasePermissions(rct RoleConditionType) DatabasePermissions {
   737  	if rct == Allow {
   738  		return r.Spec.Allow.DatabasePermissions
   739  	}
   740  	return r.Spec.Deny.DatabasePermissions
   741  }
   742  
   743  // SetDatabasePermissions sets a list of database permissions for auto-provisioned users.
   744  func (r *RoleV6) SetDatabasePermissions(rct RoleConditionType, values DatabasePermissions) {
   745  	if rct == Allow {
   746  		r.Spec.Allow.DatabasePermissions = values
   747  	} else {
   748  		r.Spec.Deny.DatabasePermissions = values
   749  	}
   750  }
   751  
   752  // GetImpersonateConditions returns conditions this role is allowed or denied to impersonate.
   753  func (r *RoleV6) GetImpersonateConditions(rct RoleConditionType) ImpersonateConditions {
   754  	cond := r.Spec.Deny.Impersonate
   755  	if rct == Allow {
   756  		cond = r.Spec.Allow.Impersonate
   757  	}
   758  	if cond == nil {
   759  		return ImpersonateConditions{}
   760  	}
   761  	return *cond
   762  }
   763  
   764  // SetImpersonateConditions sets conditions this role is allowed or denied to impersonate.
   765  func (r *RoleV6) SetImpersonateConditions(rct RoleConditionType, cond ImpersonateConditions) {
   766  	if rct == Allow {
   767  		r.Spec.Allow.Impersonate = &cond
   768  	} else {
   769  		r.Spec.Deny.Impersonate = &cond
   770  	}
   771  }
   772  
   773  // GetAWSRoleARNs returns a list of AWS role ARNs this role is allowed to impersonate.
   774  func (r *RoleV6) GetAWSRoleARNs(rct RoleConditionType) []string {
   775  	if rct == Allow {
   776  		return r.Spec.Allow.AWSRoleARNs
   777  	}
   778  	return r.Spec.Deny.AWSRoleARNs
   779  }
   780  
   781  // SetAWSRoleARNs sets a list of AWS role ARNs this role is allowed to impersonate.
   782  func (r *RoleV6) SetAWSRoleARNs(rct RoleConditionType, arns []string) {
   783  	if rct == Allow {
   784  		r.Spec.Allow.AWSRoleARNs = arns
   785  	} else {
   786  		r.Spec.Deny.AWSRoleARNs = arns
   787  	}
   788  }
   789  
   790  // GetAzureIdentities returns a list of Azure identities this role is allowed to assume.
   791  func (r *RoleV6) GetAzureIdentities(rct RoleConditionType) []string {
   792  	if rct == Allow {
   793  		return r.Spec.Allow.AzureIdentities
   794  	}
   795  	return r.Spec.Deny.AzureIdentities
   796  }
   797  
   798  // SetAzureIdentities sets a list of Azure identities this role is allowed to assume.
   799  func (r *RoleV6) SetAzureIdentities(rct RoleConditionType, identities []string) {
   800  	if rct == Allow {
   801  		r.Spec.Allow.AzureIdentities = identities
   802  	} else {
   803  		r.Spec.Deny.AzureIdentities = identities
   804  	}
   805  }
   806  
   807  // GetGCPServiceAccounts returns a list of GCP service accounts this role is allowed to assume.
   808  func (r *RoleV6) GetGCPServiceAccounts(rct RoleConditionType) []string {
   809  	if rct == Allow {
   810  		return r.Spec.Allow.GCPServiceAccounts
   811  	}
   812  	return r.Spec.Deny.GCPServiceAccounts
   813  }
   814  
   815  // SetGCPServiceAccounts sets a list of GCP service accounts this role is allowed to assume.
   816  func (r *RoleV6) SetGCPServiceAccounts(rct RoleConditionType, accounts []string) {
   817  	if rct == Allow {
   818  		r.Spec.Allow.GCPServiceAccounts = accounts
   819  	} else {
   820  		r.Spec.Deny.GCPServiceAccounts = accounts
   821  	}
   822  }
   823  
   824  // GetWindowsDesktopLabels gets the desktop labels this role is allowed or denied access to.
   825  func (r *RoleV6) GetWindowsDesktopLabels(rct RoleConditionType) Labels {
   826  	if rct == Allow {
   827  		return r.Spec.Allow.WindowsDesktopLabels
   828  	}
   829  	return r.Spec.Deny.WindowsDesktopLabels
   830  }
   831  
   832  // SetWindowsDesktopLabels sets the desktop labels this role is allowed or denied access to.
   833  func (r *RoleV6) SetWindowsDesktopLabels(rct RoleConditionType, labels Labels) {
   834  	if rct == Allow {
   835  		r.Spec.Allow.WindowsDesktopLabels = labels.Clone()
   836  	} else {
   837  		r.Spec.Deny.WindowsDesktopLabels = labels.Clone()
   838  	}
   839  }
   840  
   841  // GetWindowsLogins gets Windows desktop logins for the role's allow or deny condition.
   842  func (r *RoleV6) GetWindowsLogins(rct RoleConditionType) []string {
   843  	if rct == Allow {
   844  		return r.Spec.Allow.WindowsDesktopLogins
   845  	}
   846  	return r.Spec.Deny.WindowsDesktopLogins
   847  }
   848  
   849  // SetWindowsLogins sets Windows desktop logins for the role's allow or deny condition.
   850  func (r *RoleV6) SetWindowsLogins(rct RoleConditionType, logins []string) {
   851  	lcopy := utils.CopyStrings(logins)
   852  
   853  	if rct == Allow {
   854  		r.Spec.Allow.WindowsDesktopLogins = lcopy
   855  	} else {
   856  		r.Spec.Deny.WindowsDesktopLogins = lcopy
   857  	}
   858  }
   859  
   860  // GetRules gets all allow or deny rules.
   861  func (r *RoleV6) GetRules(rct RoleConditionType) []Rule {
   862  	if rct == Allow {
   863  		return r.Spec.Allow.Rules
   864  	}
   865  	return r.Spec.Deny.Rules
   866  }
   867  
   868  // SetRules sets an allow or deny rule.
   869  func (r *RoleV6) SetRules(rct RoleConditionType, in []Rule) {
   870  	rcopy := CopyRulesSlice(in)
   871  
   872  	if rct == Allow {
   873  		r.Spec.Allow.Rules = rcopy
   874  	} else {
   875  		r.Spec.Deny.Rules = rcopy
   876  	}
   877  }
   878  
   879  // GetHostGroups gets all groups for provisioned user
   880  func (r *RoleV6) GetHostGroups(rct RoleConditionType) []string {
   881  	if rct == Allow {
   882  		return r.Spec.Allow.HostGroups
   883  	}
   884  	return r.Spec.Deny.HostGroups
   885  }
   886  
   887  // SetHostGroups sets all groups for provisioned user
   888  func (r *RoleV6) SetHostGroups(rct RoleConditionType, groups []string) {
   889  	ncopy := utils.CopyStrings(groups)
   890  	if rct == Allow {
   891  		r.Spec.Allow.HostGroups = ncopy
   892  	} else {
   893  		r.Spec.Deny.HostGroups = ncopy
   894  	}
   895  }
   896  
   897  // GetDesktopGroups gets all groups for provisioned user
   898  func (r *RoleV6) GetDesktopGroups(rct RoleConditionType) []string {
   899  	if rct == Allow {
   900  		return r.Spec.Allow.DesktopGroups
   901  	}
   902  	return r.Spec.Deny.DesktopGroups
   903  }
   904  
   905  // SetDesktopGroups sets all groups for provisioned user
   906  func (r *RoleV6) SetDesktopGroups(rct RoleConditionType, groups []string) {
   907  	ncopy := utils.CopyStrings(groups)
   908  	if rct == Allow {
   909  		r.Spec.Allow.DesktopGroups = ncopy
   910  	} else {
   911  		r.Spec.Deny.DesktopGroups = ncopy
   912  	}
   913  }
   914  
   915  // GetHostSudoers gets the list of sudoers entries for the role
   916  func (r *RoleV6) GetHostSudoers(rct RoleConditionType) []string {
   917  	if rct == Allow {
   918  		return r.Spec.Allow.HostSudoers
   919  	}
   920  	return r.Spec.Deny.HostSudoers
   921  }
   922  
   923  // GetHostSudoers sets the list of sudoers entries for the role
   924  func (r *RoleV6) SetHostSudoers(rct RoleConditionType, sudoers []string) {
   925  	ncopy := utils.CopyStrings(sudoers)
   926  	if rct == Allow {
   927  		r.Spec.Allow.HostSudoers = ncopy
   928  	} else {
   929  		r.Spec.Deny.HostSudoers = ncopy
   930  	}
   931  }
   932  
   933  // GetSPIFFEConditions returns the allow or deny SPIFFERoleCondition.
   934  func (r *RoleV6) GetSPIFFEConditions(rct RoleConditionType) []*SPIFFERoleCondition {
   935  	if rct == Allow {
   936  		return r.Spec.Allow.SPIFFE
   937  	}
   938  	return r.Spec.Deny.SPIFFE
   939  }
   940  
   941  // SetSPIFFEConditions sets the allow or deny SPIFFERoleCondition.
   942  func (r *RoleV6) SetSPIFFEConditions(rct RoleConditionType, cond []*SPIFFERoleCondition) {
   943  	if rct == Allow {
   944  		r.Spec.Allow.SPIFFE = cond
   945  	} else {
   946  		r.Spec.Deny.SPIFFE = cond
   947  	}
   948  }
   949  
   950  // GetPrivateKeyPolicy returns the private key policy enforced for this role.
   951  func (r *RoleV6) GetPrivateKeyPolicy() keys.PrivateKeyPolicy {
   952  	switch r.Spec.Options.RequireMFAType {
   953  	case RequireMFAType_SESSION_AND_HARDWARE_KEY:
   954  		return keys.PrivateKeyPolicyHardwareKey
   955  	case RequireMFAType_HARDWARE_KEY_TOUCH:
   956  		return keys.PrivateKeyPolicyHardwareKeyTouch
   957  	case RequireMFAType_HARDWARE_KEY_PIN:
   958  		return keys.PrivateKeyPolicyHardwareKeyPIN
   959  	case RequireMFAType_HARDWARE_KEY_TOUCH_AND_PIN:
   960  		return keys.PrivateKeyPolicyHardwareKeyTouchAndPIN
   961  	default:
   962  		return keys.PrivateKeyPolicyNone
   963  	}
   964  }
   965  
   966  // setStaticFields sets static resource header and metadata fields.
   967  func (r *RoleV6) setStaticFields() {
   968  	r.Kind = KindRole
   969  	if r.Version != V3 && r.Version != V4 && r.Version != V5 && r.Version != V6 {
   970  		// When incrementing the role version, make sure to update the
   971  		// role version in the asset file used by the UI.
   972  		// See: web/packages/teleport/src/Roles/templates/role.yaml
   973  		r.Version = V7
   974  	}
   975  }
   976  
   977  // GetGroupLabels gets the map of group labels this role is allowed or denied access to.
   978  func (r *RoleV6) GetGroupLabels(rct RoleConditionType) Labels {
   979  	if rct == Allow {
   980  		return r.Spec.Allow.GroupLabels
   981  	}
   982  	return r.Spec.Deny.GroupLabels
   983  }
   984  
   985  // SetGroupLabels sets the map of group labels this role is allowed or denied access to.
   986  func (r *RoleV6) SetGroupLabels(rct RoleConditionType, labels Labels) {
   987  	if rct == Allow {
   988  		r.Spec.Allow.GroupLabels = labels.Clone()
   989  	} else {
   990  		r.Spec.Deny.GroupLabels = labels.Clone()
   991  	}
   992  }
   993  
   994  // CheckAndSetDefaults checks validity of all fields and sets defaults
   995  func (c *SPIFFERoleCondition) CheckAndSetDefaults() error {
   996  	if c.Path == "" {
   997  		return trace.BadParameter("path: should be non-empty")
   998  	}
   999  	isRegex := strings.HasPrefix(c.Path, "^") && strings.HasSuffix(c.Path, "$")
  1000  	if !(strings.HasPrefix(c.Path, "/") || isRegex) {
  1001  		return trace.BadParameter(
  1002  			"path: should start with / or be a regex expression starting with ^ and ending with $",
  1003  		)
  1004  	}
  1005  	for i, str := range c.IPSANs {
  1006  		if _, _, err := net.ParseCIDR(str); err != nil {
  1007  			return trace.BadParameter(
  1008  				"validating ip_sans[%d]: %s", i, err.Error(),
  1009  			)
  1010  		}
  1011  	}
  1012  	return nil
  1013  }
  1014  
  1015  // CheckAndSetDefaults checks validity of all parameters and sets defaults
  1016  func (r *RoleV6) CheckAndSetDefaults() error {
  1017  	r.setStaticFields()
  1018  	if err := r.Metadata.CheckAndSetDefaults(); err != nil {
  1019  		return trace.Wrap(err)
  1020  	}
  1021  
  1022  	// Make sure all fields have defaults.
  1023  	if r.Spec.Options.CertificateFormat == "" {
  1024  		r.Spec.Options.CertificateFormat = constants.CertificateFormatStandard
  1025  	}
  1026  	if r.Spec.Options.MaxSessionTTL.Value() == 0 {
  1027  		r.Spec.Options.MaxSessionTTL = NewDuration(defaults.MaxCertDuration)
  1028  	}
  1029  	if r.Spec.Options.PortForwarding == nil {
  1030  		r.Spec.Options.PortForwarding = NewBoolOption(true)
  1031  	}
  1032  	if len(r.Spec.Options.BPF) == 0 {
  1033  		r.Spec.Options.BPF = defaults.EnhancedEvents()
  1034  	}
  1035  	if r.Spec.Allow.Namespaces == nil {
  1036  		r.Spec.Allow.Namespaces = []string{defaults.Namespace}
  1037  	}
  1038  	if r.Spec.Options.RecordSession == nil {
  1039  		r.Spec.Options.RecordSession = &RecordSession{
  1040  			Desktop: NewBoolOption(true),
  1041  			Default: constants.SessionRecordingModeBestEffort,
  1042  		}
  1043  	}
  1044  	if r.Spec.Options.DesktopClipboard == nil {
  1045  		r.Spec.Options.DesktopClipboard = NewBoolOption(true)
  1046  	}
  1047  	if r.Spec.Options.DesktopDirectorySharing == nil {
  1048  		r.Spec.Options.DesktopDirectorySharing = NewBoolOption(true)
  1049  	}
  1050  	if r.Spec.Options.CreateDesktopUser == nil {
  1051  		r.Spec.Options.CreateDesktopUser = NewBoolOption(false)
  1052  	}
  1053  	if r.Spec.Options.CreateDatabaseUser == nil {
  1054  		r.Spec.Options.CreateDatabaseUser = NewBoolOption(false)
  1055  	}
  1056  	if r.Spec.Options.SSHFileCopy == nil {
  1057  		r.Spec.Options.SSHFileCopy = NewBoolOption(true)
  1058  	}
  1059  	if r.Spec.Options.IDP == nil {
  1060  		// By default, allow users to access the IdP.
  1061  		r.Spec.Options.IDP = &IdPOptions{
  1062  			SAML: &IdPSAMLOptions{
  1063  				Enabled: NewBoolOption(true),
  1064  			},
  1065  		}
  1066  	}
  1067  
  1068  	if _, ok := CreateHostUserMode_name[int32(r.Spec.Options.CreateHostUserMode)]; !ok {
  1069  		return trace.BadParameter("invalid host user mode %q, expected one of off, drop or keep", r.Spec.Options.CreateHostUserMode)
  1070  	}
  1071  
  1072  	switch r.Version {
  1073  	case V3:
  1074  		if r.Spec.Allow.NodeLabels == nil {
  1075  			if len(r.Spec.Allow.Logins) == 0 {
  1076  				// no logins implies no node access
  1077  				r.Spec.Allow.NodeLabels = Labels{}
  1078  			} else {
  1079  				r.Spec.Allow.NodeLabels = Labels{Wildcard: []string{Wildcard}}
  1080  			}
  1081  		}
  1082  
  1083  		if r.Spec.Allow.AppLabels == nil {
  1084  			r.Spec.Allow.AppLabels = Labels{Wildcard: []string{Wildcard}}
  1085  		}
  1086  
  1087  		if r.Spec.Allow.KubernetesLabels == nil {
  1088  			r.Spec.Allow.KubernetesLabels = Labels{Wildcard: []string{Wildcard}}
  1089  		}
  1090  
  1091  		if r.Spec.Allow.DatabaseLabels == nil {
  1092  			r.Spec.Allow.DatabaseLabels = Labels{Wildcard: []string{Wildcard}}
  1093  		}
  1094  
  1095  		fallthrough
  1096  	case V4, V5:
  1097  		// Labels default to nil/empty for v4+ roles
  1098  		// Allow unrestricted access to all pods.
  1099  		if len(r.Spec.Allow.KubernetesResources) == 0 && r.HasLabelMatchers(Allow, KindKubernetesCluster) {
  1100  			r.Spec.Allow.KubernetesResources = []KubernetesResource{
  1101  				{
  1102  					Kind:      KindKubePod,
  1103  					Namespace: Wildcard,
  1104  					Name:      Wildcard,
  1105  				},
  1106  			}
  1107  		}
  1108  
  1109  		setDefaultKubernetesVerbs(&r.Spec)
  1110  		if err := validateRoleSpecKubeResources(r.Version, r.Spec); err != nil {
  1111  			return trace.Wrap(err)
  1112  		}
  1113  
  1114  	case V6:
  1115  		setDefaultKubernetesVerbs(&r.Spec)
  1116  		if err := validateRoleSpecKubeResources(r.Version, r.Spec); err != nil {
  1117  			return trace.Wrap(err)
  1118  		}
  1119  	case V7:
  1120  		// Kubernetes resources default to {kind:*, name:*, namespace:*} for v7 roles.
  1121  		if len(r.Spec.Allow.KubernetesResources) == 0 && r.HasLabelMatchers(Allow, KindKubernetesCluster) {
  1122  			r.Spec.Allow.KubernetesResources = []KubernetesResource{
  1123  				{
  1124  					Kind:      Wildcard,
  1125  					Namespace: Wildcard,
  1126  					Name:      Wildcard,
  1127  					Verbs:     []string{Wildcard},
  1128  				},
  1129  			}
  1130  		}
  1131  
  1132  		if err := validateRoleSpecKubeResources(r.Version, r.Spec); err != nil {
  1133  			return trace.Wrap(err)
  1134  		}
  1135  	default:
  1136  		return trace.BadParameter("unrecognized role version: %v", r.Version)
  1137  	}
  1138  
  1139  	if r.Spec.Deny.Namespaces == nil {
  1140  		r.Spec.Deny.Namespaces = []string{defaults.Namespace}
  1141  	}
  1142  
  1143  	// Validate that enhanced recording options are all valid.
  1144  	for _, opt := range r.Spec.Options.BPF {
  1145  		if opt == constants.EnhancedRecordingCommand ||
  1146  			opt == constants.EnhancedRecordingDisk ||
  1147  			opt == constants.EnhancedRecordingNetwork {
  1148  			continue
  1149  		}
  1150  		return trace.BadParameter("invalid value for role option enhanced_recording: %v", opt)
  1151  	}
  1152  
  1153  	// Validate locking mode.
  1154  	switch r.Spec.Options.Lock {
  1155  	case "":
  1156  		// Missing locking mode implies the cluster-wide default should be used.
  1157  	case constants.LockingModeBestEffort, constants.LockingModeStrict:
  1158  	default:
  1159  		return trace.BadParameter("invalid value for role option lock: %v", r.Spec.Options.Lock)
  1160  	}
  1161  
  1162  	// check and correct the session ttl
  1163  	if r.Spec.Options.MaxSessionTTL.Value() <= 0 {
  1164  		r.Spec.Options.MaxSessionTTL = NewDuration(defaults.MaxCertDuration)
  1165  	}
  1166  
  1167  	// restrict wildcards
  1168  	for _, login := range r.Spec.Allow.Logins {
  1169  		if login == Wildcard {
  1170  			return trace.BadParameter("wildcard matcher is not allowed in logins")
  1171  		}
  1172  	}
  1173  	for _, arn := range r.Spec.Allow.AWSRoleARNs {
  1174  		if arn == Wildcard {
  1175  			return trace.BadParameter("wildcard matcher is not allowed in aws_role_arns")
  1176  		}
  1177  	}
  1178  	for _, identity := range r.Spec.Allow.AzureIdentities {
  1179  		if identity == Wildcard {
  1180  			return trace.BadParameter("wildcard matcher is not allowed in allow.azure_identities")
  1181  		}
  1182  	}
  1183  	for _, identity := range r.Spec.Allow.GCPServiceAccounts {
  1184  		if identity == Wildcard {
  1185  			return trace.BadParameter("wildcard matcher is not allowed in allow.gcp_service_accounts")
  1186  		}
  1187  	}
  1188  	for _, role := range r.Spec.Allow.DatabaseRoles {
  1189  		if role == Wildcard {
  1190  			return trace.BadParameter("wildcard is not allowed in allow.database_roles")
  1191  		}
  1192  	}
  1193  	checkWildcardSelector := func(labels Labels) error {
  1194  		for key, val := range labels {
  1195  			if key == Wildcard && !(len(val) == 1 && val[0] == Wildcard) {
  1196  				return trace.BadParameter("selector *:<val> is not supported")
  1197  			}
  1198  		}
  1199  		return nil
  1200  	}
  1201  	for _, labels := range []Labels{
  1202  		r.Spec.Allow.NodeLabels,
  1203  		r.Spec.Allow.AppLabels,
  1204  		r.Spec.Allow.KubernetesLabels,
  1205  		r.Spec.Allow.DatabaseLabels,
  1206  		r.Spec.Allow.WindowsDesktopLabels,
  1207  		r.Spec.Allow.GroupLabels,
  1208  	} {
  1209  		if err := checkWildcardSelector(labels); err != nil {
  1210  			return trace.Wrap(err)
  1211  		}
  1212  	}
  1213  
  1214  	for i, perm := range r.Spec.Allow.DatabasePermissions {
  1215  		if err := perm.CheckAndSetDefaults(); err != nil {
  1216  			return trace.BadParameter("failed to process 'allow' db_permission #%v: %v", i+1, err)
  1217  		}
  1218  		// Wildcards permissions are disallowed. Even though this should never pass the db-specific driver,
  1219  		// it doesn't hurt to check it here. Wildcards *are* allowed on deny side,
  1220  		// which is why this check is here and not in CheckAndSetDefaults().
  1221  		for _, permission := range perm.Permissions {
  1222  			if permission == Wildcard {
  1223  				return trace.BadParameter("individual database permissions cannot be wildcards strings")
  1224  			}
  1225  		}
  1226  	}
  1227  	for i, perm := range r.Spec.Deny.DatabasePermissions {
  1228  		if err := perm.CheckAndSetDefaults(); err != nil {
  1229  			return trace.BadParameter("failed to process 'deny' db_permission #%v: %v", i+1, err)
  1230  		}
  1231  	}
  1232  	for i := range r.Spec.Allow.SPIFFE {
  1233  		err := r.Spec.Allow.SPIFFE[i].CheckAndSetDefaults()
  1234  		if err != nil {
  1235  			return trace.Wrap(err, "validating spec.allow.spiffe[%d]", i)
  1236  		}
  1237  	}
  1238  	for i := range r.Spec.Deny.SPIFFE {
  1239  		err := r.Spec.Deny.SPIFFE[i].CheckAndSetDefaults()
  1240  		if err != nil {
  1241  			return trace.Wrap(err, "validating spec.deny.spiffe[%d]", i)
  1242  		}
  1243  	}
  1244  
  1245  	for i := range r.Spec.Allow.Rules {
  1246  		err := r.Spec.Allow.Rules[i].CheckAndSetDefaults()
  1247  		if err != nil {
  1248  			return trace.BadParameter("failed to process 'allow' rule %v: %v", i, err)
  1249  		}
  1250  	}
  1251  	for i := range r.Spec.Deny.Rules {
  1252  		err := r.Spec.Deny.Rules[i].CheckAndSetDefaults()
  1253  		if err != nil {
  1254  			return trace.BadParameter("failed to process 'deny' rule %v: %v", i, err)
  1255  		}
  1256  	}
  1257  	if r.Spec.Allow.Impersonate != nil {
  1258  		if err := r.Spec.Allow.Impersonate.CheckAndSetDefaults(); err != nil {
  1259  			return trace.Wrap(err)
  1260  		}
  1261  	}
  1262  	if r.Spec.Deny.Impersonate != nil {
  1263  		if r.Spec.Deny.Impersonate.Where != "" {
  1264  			return trace.BadParameter("'where' is not supported in deny.impersonate conditions")
  1265  		}
  1266  		if err := r.Spec.Deny.Impersonate.CheckAndSetDefaults(); err != nil {
  1267  			return trace.Wrap(err)
  1268  		}
  1269  	}
  1270  
  1271  	return nil
  1272  }
  1273  
  1274  // String returns the human readable representation of a role.
  1275  func (r *RoleV6) String() string {
  1276  	options, _ := json.Marshal(r.Spec.Options)
  1277  	return fmt.Sprintf("Role(Name=%v,Options=%q,Allow=%+v,Deny=%+v)",
  1278  		r.GetName(), string(options), r.Spec.Allow, r.Spec.Deny)
  1279  }
  1280  
  1281  // IsEmpty returns true if conditions are unspecified
  1282  func (i ImpersonateConditions) IsEmpty() bool {
  1283  	return len(i.Users) == 0 || len(i.Roles) == 0
  1284  }
  1285  
  1286  // CheckAndSetDefaults checks and sets default values
  1287  func (i ImpersonateConditions) CheckAndSetDefaults() error {
  1288  	if len(i.Users) != 0 && len(i.Roles) == 0 {
  1289  		// Role-only impersonation note: the phrasing of this error message
  1290  		// assumes the user is attempting user (rather than role)
  1291  		// impersonation, but this seems like a safe assumption when a user has
  1292  		// already been specified.
  1293  		return trace.BadParameter("please set both impersonate.users and impersonate.roles for user impersonation")
  1294  	}
  1295  	return nil
  1296  }
  1297  
  1298  // NewRule creates a rule based on a resource name and a list of verbs
  1299  func NewRule(resource string, verbs []string) Rule {
  1300  	return Rule{
  1301  		Resources: []string{resource},
  1302  		Verbs:     verbs,
  1303  	}
  1304  }
  1305  
  1306  // CheckAndSetDefaults checks and sets defaults for this rule
  1307  func (r *Rule) CheckAndSetDefaults() error {
  1308  	if len(r.Resources) == 0 {
  1309  		return trace.BadParameter("missing resources to match")
  1310  	}
  1311  	if len(r.Verbs) == 0 {
  1312  		return trace.BadParameter("missing verbs")
  1313  	}
  1314  	return nil
  1315  }
  1316  
  1317  // HasResource returns true if the rule has the specified resource.
  1318  func (r *Rule) HasResource(resource string) bool {
  1319  	for _, r := range r.Resources {
  1320  		if r == resource {
  1321  			return true
  1322  		}
  1323  	}
  1324  	return false
  1325  }
  1326  
  1327  // HasVerb returns true if the rule has the specified verb.
  1328  func (r *Rule) HasVerb(verb string) bool {
  1329  	for _, v := range r.Verbs {
  1330  		// readnosecrets can be satisfied by having readnosecrets or read
  1331  		if verb == VerbReadNoSecrets {
  1332  			if v == VerbReadNoSecrets || v == VerbRead {
  1333  				return true
  1334  			}
  1335  			continue
  1336  		}
  1337  		if v == verb {
  1338  			return true
  1339  		}
  1340  	}
  1341  	return false
  1342  }
  1343  
  1344  // CopyRulesSlice copies input slice of Rules and returns the copy
  1345  func CopyRulesSlice(in []Rule) []Rule {
  1346  	out := make([]Rule, len(in))
  1347  	copy(out, in)
  1348  	return out
  1349  }
  1350  
  1351  // Labels is a wrapper around map
  1352  // that can marshal and unmarshal itself
  1353  // from scalar and list values
  1354  type Labels map[string]utils.Strings
  1355  
  1356  // ToProto returns a protobuf-compatible representation of Labels.
  1357  func (l Labels) ToProto() *wrappers.LabelValues {
  1358  	v := &wrappers.LabelValues{
  1359  		Values: make(map[string]wrappers.StringValues, len(l)),
  1360  	}
  1361  	for key, vals := range l {
  1362  		stringValues := wrappers.StringValues{
  1363  			Values: make([]string, len(vals)),
  1364  		}
  1365  		copy(stringValues.Values, vals)
  1366  		v.Values[key] = stringValues
  1367  	}
  1368  	return v
  1369  }
  1370  
  1371  // Marshal marshals value into protobuf representation
  1372  func (l Labels) Marshal() ([]byte, error) {
  1373  	return proto.Marshal(l.ToProto())
  1374  }
  1375  
  1376  // MarshalTo marshals value to the array
  1377  func (l Labels) MarshalTo(data []byte) (int, error) {
  1378  	return l.ToProto().MarshalTo(data)
  1379  }
  1380  
  1381  // Unmarshal unmarshals value from protobuf
  1382  func (l *Labels) Unmarshal(data []byte) error {
  1383  	protoValues := &wrappers.LabelValues{}
  1384  	err := proto.Unmarshal(data, protoValues)
  1385  	if err != nil {
  1386  		return err
  1387  	}
  1388  	if protoValues.Values == nil {
  1389  		return nil
  1390  	}
  1391  	*l = make(map[string]utils.Strings, len(protoValues.Values))
  1392  	for key := range protoValues.Values {
  1393  		(*l)[key] = protoValues.Values[key].Values
  1394  	}
  1395  	return nil
  1396  }
  1397  
  1398  // Size returns protobuf size
  1399  func (l Labels) Size() int {
  1400  	return l.ToProto().Size()
  1401  }
  1402  
  1403  // Clone returns non-shallow copy of the labels set
  1404  func (l Labels) Clone() Labels {
  1405  	if l == nil {
  1406  		return nil
  1407  	}
  1408  	out := make(Labels, len(l))
  1409  	for key, vals := range l {
  1410  		cvals := make([]string, len(vals))
  1411  		copy(cvals, vals)
  1412  		out[key] = cvals
  1413  	}
  1414  	return out
  1415  }
  1416  
  1417  // NewBool returns Bool struct based on bool value
  1418  func NewBool(b bool) Bool {
  1419  	return Bool(b)
  1420  }
  1421  
  1422  // NewBoolP returns Bool pointer
  1423  func NewBoolP(b bool) *Bool {
  1424  	val := NewBool(b)
  1425  	return &val
  1426  }
  1427  
  1428  // Bool is a wrapper around boolean values
  1429  type Bool bool
  1430  
  1431  // Value returns boolean value of the wrapper
  1432  func (b Bool) Value() bool {
  1433  	return bool(b)
  1434  }
  1435  
  1436  // MarshalJSON marshals boolean value.
  1437  func (b Bool) MarshalJSON() ([]byte, error) {
  1438  	return json.Marshal(b.Value())
  1439  }
  1440  
  1441  // UnmarshalJSON unmarshals JSON from string or bool,
  1442  // in case if value is missing or not recognized, defaults to false
  1443  func (b *Bool) UnmarshalJSON(data []byte) error {
  1444  	if len(data) == 0 {
  1445  		return nil
  1446  	}
  1447  	var boolVal bool
  1448  	// check if it's a bool variable
  1449  	if err := json.Unmarshal(data, &boolVal); err == nil {
  1450  		*b = Bool(boolVal)
  1451  		return nil
  1452  	}
  1453  	// also support string variables
  1454  	var stringVar string
  1455  	if err := json.Unmarshal(data, &stringVar); err != nil {
  1456  		return trace.Wrap(err)
  1457  	}
  1458  	v, err := utils.ParseBool(stringVar)
  1459  	if err != nil {
  1460  		*b = false
  1461  		return nil
  1462  	}
  1463  	*b = Bool(v)
  1464  	return nil
  1465  }
  1466  
  1467  // MarshalYAML marshals bool into yaml value
  1468  func (b Bool) MarshalYAML() (interface{}, error) {
  1469  	return bool(b), nil
  1470  }
  1471  
  1472  // UnmarshalYAML unmarshals bool value from yaml
  1473  func (b *Bool) UnmarshalYAML(unmarshal func(interface{}) error) error {
  1474  	var boolVar bool
  1475  	if err := unmarshal(&boolVar); err == nil {
  1476  		*b = Bool(boolVar)
  1477  		return nil
  1478  	}
  1479  	var stringVar string
  1480  	if err := unmarshal(&stringVar); err != nil {
  1481  		return trace.Wrap(err)
  1482  	}
  1483  	v, err := utils.ParseBool(stringVar)
  1484  	if err != nil {
  1485  		*b = Bool(v)
  1486  		return nil
  1487  	}
  1488  	*b = Bool(v)
  1489  	return nil
  1490  }
  1491  
  1492  // BoolOption is a wrapper around bool
  1493  // that can take multiple values:
  1494  // * true, false and non-set (when pointer is nil)
  1495  // and can marshal itself to protobuf equivalent BoolValue
  1496  type BoolOption struct {
  1497  	// Value is a value of the option
  1498  	Value bool
  1499  }
  1500  
  1501  // NewBoolOption returns Bool struct based on bool value
  1502  func NewBoolOption(b bool) *BoolOption {
  1503  	v := BoolOption{Value: b}
  1504  	return &v
  1505  }
  1506  
  1507  // BoolDefaultTrue returns true if v is not set (pointer is nil)
  1508  // otherwise returns real boolean value
  1509  func BoolDefaultTrue(v *BoolOption) bool {
  1510  	if v == nil {
  1511  		return true
  1512  	}
  1513  	return v.Value
  1514  }
  1515  
  1516  func (b *BoolOption) protoType() *BoolValue {
  1517  	return &BoolValue{
  1518  		Value: b.Value,
  1519  	}
  1520  }
  1521  
  1522  // MarshalTo marshals value to the slice
  1523  func (b BoolOption) MarshalTo(data []byte) (int, error) {
  1524  	return b.protoType().MarshalTo(data)
  1525  }
  1526  
  1527  // MarshalToSizedBuffer marshals value to the slice
  1528  func (b BoolOption) MarshalToSizedBuffer(data []byte) (int, error) {
  1529  	return b.protoType().MarshalToSizedBuffer(data)
  1530  }
  1531  
  1532  // Marshal marshals value into protobuf representation
  1533  func (b BoolOption) Marshal() ([]byte, error) {
  1534  	return proto.Marshal(b.protoType())
  1535  }
  1536  
  1537  // Unmarshal unmarshals value from protobuf
  1538  func (b *BoolOption) Unmarshal(data []byte) error {
  1539  	protoValue := &BoolValue{}
  1540  	err := proto.Unmarshal(data, protoValue)
  1541  	if err != nil {
  1542  		return err
  1543  	}
  1544  	b.Value = protoValue.Value
  1545  	return nil
  1546  }
  1547  
  1548  // Size returns protobuf size
  1549  func (b BoolOption) Size() int {
  1550  	return b.protoType().Size()
  1551  }
  1552  
  1553  // MarshalJSON marshals boolean value.
  1554  func (b BoolOption) MarshalJSON() ([]byte, error) {
  1555  	return json.Marshal(b.Value)
  1556  }
  1557  
  1558  // UnmarshalJSON unmarshals JSON from string or bool,
  1559  // in case if value is missing or not recognized, defaults to false
  1560  func (b *BoolOption) UnmarshalJSON(data []byte) error {
  1561  	var val Bool
  1562  	if err := val.UnmarshalJSON(data); err != nil {
  1563  		return err
  1564  	}
  1565  	b.Value = val.Value()
  1566  	return nil
  1567  }
  1568  
  1569  // MarshalYAML marshals BoolOption into yaml value
  1570  func (b *BoolOption) MarshalYAML() (interface{}, error) {
  1571  	return b.Value, nil
  1572  }
  1573  
  1574  // UnmarshalYAML unmarshals BoolOption to YAML
  1575  func (b *BoolOption) UnmarshalYAML(unmarshal func(interface{}) error) error {
  1576  	var val Bool
  1577  	if err := val.UnmarshalYAML(unmarshal); err != nil {
  1578  		return err
  1579  	}
  1580  	b.Value = val.Value()
  1581  	return nil
  1582  }
  1583  
  1584  // ProcessNamespace returns the default namespace in case the namespace is empty.
  1585  func ProcessNamespace(namespace string) string {
  1586  	if namespace == "" {
  1587  		return defaults.Namespace
  1588  	}
  1589  	return namespace
  1590  }
  1591  
  1592  // WhereExpr is a tree like structure representing a `where` (sub-)expression.
  1593  type WhereExpr struct {
  1594  	Field            string
  1595  	Literal          interface{}
  1596  	And, Or          WhereExpr2
  1597  	Not              *WhereExpr
  1598  	Equals, Contains WhereExpr2
  1599  }
  1600  
  1601  // WhereExpr2 is a pair of `where` (sub-)expressions.
  1602  type WhereExpr2 struct {
  1603  	L, R *WhereExpr
  1604  }
  1605  
  1606  // String returns a human readable representation of WhereExpr.
  1607  func (e WhereExpr) String() string {
  1608  	if e.Field != "" {
  1609  		return e.Field
  1610  	}
  1611  	if e.Literal != nil {
  1612  		return fmt.Sprintf("%q", e.Literal)
  1613  	}
  1614  	if e.And.L != nil && e.And.R != nil {
  1615  		return fmt.Sprintf("(%s && %s)", e.And.L, e.And.R)
  1616  	}
  1617  	if e.Or.L != nil && e.Or.R != nil {
  1618  		return fmt.Sprintf("(%s || %s)", e.Or.L, e.Or.R)
  1619  	}
  1620  	if e.Not != nil {
  1621  		return fmt.Sprintf("!%s", e.Not)
  1622  	}
  1623  	if e.Equals.L != nil && e.Equals.R != nil {
  1624  		return fmt.Sprintf("equals(%s, %s)", e.Equals.L, e.Equals.R)
  1625  	}
  1626  	if e.Contains.L != nil && e.Contains.R != nil {
  1627  		return fmt.Sprintf("contains(%s, %s)", e.Contains.L, e.Contains.R)
  1628  	}
  1629  	return ""
  1630  }
  1631  
  1632  // GetSessionRequirePolicies returns the RBAC required policies for a role.
  1633  func (r *RoleV6) GetSessionRequirePolicies() []*SessionRequirePolicy {
  1634  	return r.Spec.Allow.RequireSessionJoin
  1635  }
  1636  
  1637  // GetSessionPolicySet returns the RBAC policy set for a session.
  1638  func (r *RoleV6) GetSessionPolicySet() SessionTrackerPolicySet {
  1639  	return SessionTrackerPolicySet{
  1640  		Name:               r.Metadata.Name,
  1641  		Version:            r.Version,
  1642  		RequireSessionJoin: r.Spec.Allow.RequireSessionJoin,
  1643  	}
  1644  }
  1645  
  1646  // SetSessionRequirePolicies sets the RBAC required policies for a role.
  1647  func (r *RoleV6) SetSessionRequirePolicies(policies []*SessionRequirePolicy) {
  1648  	r.Spec.Allow.RequireSessionJoin = policies
  1649  }
  1650  
  1651  // SetSessionJoinPolicies returns the RBAC join policies for a role.
  1652  func (r *RoleV6) GetSessionJoinPolicies() []*SessionJoinPolicy {
  1653  	return r.Spec.Allow.JoinSessions
  1654  }
  1655  
  1656  // SetSessionJoinPolicies sets the RBAC join policies for a role.
  1657  func (r *RoleV6) SetSessionJoinPolicies(policies []*SessionJoinPolicy) {
  1658  	r.Spec.Allow.JoinSessions = policies
  1659  }
  1660  
  1661  // GetSearchAsRoles returns the list of extra roles which should apply to a
  1662  // user while they are searching for resources as part of a Resource Access
  1663  // Request, and defines the underlying roles which will be requested as part
  1664  // of any Resource Access Request.
  1665  func (r *RoleV6) GetSearchAsRoles(rct RoleConditionType) []string {
  1666  	roleConditions := &r.Spec.Allow
  1667  	if rct == Deny {
  1668  		roleConditions = &r.Spec.Deny
  1669  	}
  1670  	if roleConditions.Request == nil {
  1671  		return nil
  1672  	}
  1673  	return roleConditions.Request.SearchAsRoles
  1674  }
  1675  
  1676  // SetSearchAsRoles sets the list of extra roles which should apply to a
  1677  // user while they are searching for resources as part of a Resource Access
  1678  // Request, and defines the underlying roles which will be requested as part
  1679  // of any Resource Access Request.
  1680  func (r *RoleV6) SetSearchAsRoles(rct RoleConditionType, roles []string) {
  1681  	roleConditions := &r.Spec.Allow
  1682  	if rct == Deny {
  1683  		roleConditions = &r.Spec.Deny
  1684  	}
  1685  	if roleConditions.Request == nil {
  1686  		roleConditions.Request = &AccessRequestConditions{}
  1687  	}
  1688  	roleConditions.Request.SearchAsRoles = roles
  1689  }
  1690  
  1691  // GetPreviewAsRoles returns the list of extra roles which should apply to a
  1692  // reviewer while they are viewing a Resource Access Request for the
  1693  // purposes of viewing details such as the hostname and labels of requested
  1694  // resources.
  1695  func (r *RoleV6) GetPreviewAsRoles(rct RoleConditionType) []string {
  1696  	roleConditions := &r.Spec.Allow
  1697  	if rct == Deny {
  1698  		roleConditions = &r.Spec.Deny
  1699  	}
  1700  	if roleConditions.ReviewRequests == nil {
  1701  		return nil
  1702  	}
  1703  	return roleConditions.ReviewRequests.PreviewAsRoles
  1704  }
  1705  
  1706  // SetPreviewAsRoles sets the list of extra roles which should apply to a
  1707  // reviewer while they are viewing a Resource Access Request for the
  1708  // purposes of viewing details such as the hostname and labels of requested
  1709  // resources.
  1710  func (r *RoleV6) SetPreviewAsRoles(rct RoleConditionType, roles []string) {
  1711  	roleConditions := &r.Spec.Allow
  1712  	if rct == Deny {
  1713  		roleConditions = &r.Spec.Deny
  1714  	}
  1715  	if roleConditions.ReviewRequests == nil {
  1716  		roleConditions.ReviewRequests = &AccessReviewConditions{}
  1717  	}
  1718  	roleConditions.ReviewRequests.PreviewAsRoles = roles
  1719  }
  1720  
  1721  // validateRoleSpecKubeResources validates the Allow/Deny Kubernetes Resources
  1722  // entries.
  1723  func validateRoleSpecKubeResources(version string, spec RoleSpecV6) error {
  1724  	if err := validateKubeResources(version, spec.Allow.KubernetesResources); err != nil {
  1725  		return trace.Wrap(err)
  1726  	}
  1727  	if err := validateKubeResources(version, spec.Deny.KubernetesResources); err != nil {
  1728  		return trace.Wrap(err)
  1729  	}
  1730  	return nil
  1731  }
  1732  
  1733  // setDefaultKubernetesVerbs sets the default verbs for each KubernetesResource
  1734  // entry if none are specified. This is necessary for backwards compatibility
  1735  // with older versions of Role: V3, V4, V5, and v6.
  1736  func setDefaultKubernetesVerbs(spec *RoleSpecV6) {
  1737  	for _, kubeResources := range [][]KubernetesResource{spec.Allow.KubernetesResources, spec.Deny.KubernetesResources} {
  1738  		for i := range kubeResources {
  1739  			if len(kubeResources[i].Verbs) == 0 {
  1740  				kubeResources[i].Verbs = []string{Wildcard}
  1741  			}
  1742  		}
  1743  	}
  1744  }
  1745  
  1746  // validateKubeResources validates the following rules for each kubeResources entry:
  1747  // - Kind belongs to KubernetesResourcesKinds
  1748  // - Name is not empty
  1749  // - Namespace is not empty
  1750  func validateKubeResources(roleVersion string, kubeResources []KubernetesResource) error {
  1751  	for _, kubeResource := range kubeResources {
  1752  		if !slices.Contains(KubernetesResourcesKinds, kubeResource.Kind) && kubeResource.Kind != Wildcard {
  1753  			return trace.BadParameter("KubernetesResource kind %q is invalid or unsupported; Supported: %v", kubeResource.Kind, append([]string{Wildcard}, KubernetesResourcesKinds...))
  1754  		}
  1755  
  1756  		for _, verb := range kubeResource.Verbs {
  1757  			if !slices.Contains(KubernetesVerbs, verb) && verb != Wildcard {
  1758  				return trace.BadParameter("KubernetesResource verb %q is invalid or unsupported; Supported: %v", verb, KubernetesVerbs)
  1759  			}
  1760  			if verb == Wildcard && len(kubeResource.Verbs) > 1 {
  1761  				return trace.BadParameter("KubernetesResource verb %q cannot be used with other verbs", verb)
  1762  			}
  1763  		}
  1764  
  1765  		// Only Pod resources are supported in role version <=V6.
  1766  		// This is mandatory because we must append the other resources to the
  1767  		// kubernetes resources.
  1768  		switch roleVersion {
  1769  		// Teleport does not support role versions < v3.
  1770  		case V6, V5, V4, V3:
  1771  			if kubeResource.Kind != KindKubePod {
  1772  				return trace.BadParameter("KubernetesResource %q is not supported in role version %q. Upgrade the role version to %q", kubeResource.Kind, roleVersion, V7)
  1773  			}
  1774  			if len(kubeResource.Verbs) != 1 || kubeResource.Verbs[0] != Wildcard {
  1775  				return trace.BadParameter("Role version %q only supports %q verb. Upgrade the role version to %q", roleVersion, Wildcard, V7)
  1776  			}
  1777  		}
  1778  
  1779  		if len(kubeResource.Namespace) == 0 && !slices.Contains(KubernetesClusterWideResourceKinds, kubeResource.Kind) {
  1780  			return trace.BadParameter("KubernetesResource must include Namespace")
  1781  		}
  1782  		if len(kubeResource.Name) == 0 {
  1783  			return trace.BadParameter("KubernetesResource must include Name")
  1784  		}
  1785  	}
  1786  	return nil
  1787  }
  1788  
  1789  // ClusterResource returns the resource name in the following format
  1790  // <namespace>/<name>.
  1791  func (k *KubernetesResource) ClusterResource() string {
  1792  	return path.Join(k.Namespace, k.Name)
  1793  }
  1794  
  1795  // IsEmpty will return true if the condition is empty.
  1796  func (a AccessRequestConditions) IsEmpty() bool {
  1797  	return len(a.Annotations) == 0 &&
  1798  		len(a.ClaimsToRoles) == 0 &&
  1799  		len(a.Roles) == 0 &&
  1800  		len(a.SearchAsRoles) == 0 &&
  1801  		len(a.SuggestedReviewers) == 0 &&
  1802  		len(a.Thresholds) == 0
  1803  }
  1804  
  1805  // IsEmpty will return true if the condition is empty.
  1806  func (a AccessReviewConditions) IsEmpty() bool {
  1807  	return len(a.ClaimsToRoles) == 0 &&
  1808  		len(a.PreviewAsRoles) == 0 &&
  1809  		len(a.Roles) == 0 &&
  1810  		len(a.Where) == 0
  1811  }
  1812  
  1813  // LabelMatchers holds the role label matchers and label expression that are
  1814  // used to match resource labels of a specific resource kind and condition
  1815  // (allow/deny).
  1816  type LabelMatchers struct {
  1817  	Labels     Labels
  1818  	Expression string
  1819  }
  1820  
  1821  // Empty returns true if all elements of the LabelMatchers are empty/unset.
  1822  func (l LabelMatchers) Empty() bool {
  1823  	return len(l.Labels) == 0 && len(l.Expression) == 0
  1824  }
  1825  
  1826  // GetLabelMatchers gets the LabelMatchers that match labels of resources of
  1827  // type [kind] this role is allowed or denied access to.
  1828  func (r *RoleV6) GetLabelMatchers(rct RoleConditionType, kind string) (LabelMatchers, error) {
  1829  	var cond *RoleConditions
  1830  	if rct == Allow {
  1831  		cond = &r.Spec.Allow
  1832  	} else {
  1833  		cond = &r.Spec.Deny
  1834  	}
  1835  	switch kind {
  1836  	case KindRemoteCluster:
  1837  		return LabelMatchers{cond.ClusterLabels, cond.ClusterLabelsExpression}, nil
  1838  	case KindNode:
  1839  		return LabelMatchers{cond.NodeLabels, cond.NodeLabelsExpression}, nil
  1840  	case KindKubernetesCluster:
  1841  		return LabelMatchers{cond.KubernetesLabels, cond.KubernetesLabelsExpression}, nil
  1842  	case KindApp:
  1843  		return LabelMatchers{cond.AppLabels, cond.AppLabelsExpression}, nil
  1844  	case KindDatabase:
  1845  		return LabelMatchers{cond.DatabaseLabels, cond.DatabaseLabelsExpression}, nil
  1846  	case KindDatabaseService:
  1847  		return LabelMatchers{cond.DatabaseServiceLabels, cond.DatabaseServiceLabelsExpression}, nil
  1848  	case KindWindowsDesktop:
  1849  		return LabelMatchers{cond.WindowsDesktopLabels, cond.WindowsDesktopLabelsExpression}, nil
  1850  	case KindWindowsDesktopService:
  1851  		return LabelMatchers{cond.WindowsDesktopLabels, cond.WindowsDesktopLabelsExpression}, nil
  1852  	case KindUserGroup:
  1853  		return LabelMatchers{cond.GroupLabels, cond.GroupLabelsExpression}, nil
  1854  	}
  1855  	return LabelMatchers{}, trace.BadParameter("can't get label matchers for resource kind %q", kind)
  1856  }
  1857  
  1858  // SetLabelMatchers sets the LabelMatchers that match labels of resources of
  1859  // type [kind] this role is allowed or denied access to.
  1860  func (r *RoleV6) SetLabelMatchers(rct RoleConditionType, kind string, labelMatchers LabelMatchers) error {
  1861  	var cond *RoleConditions
  1862  	if rct == Allow {
  1863  		cond = &r.Spec.Allow
  1864  	} else {
  1865  		cond = &r.Spec.Deny
  1866  	}
  1867  	switch kind {
  1868  	case KindRemoteCluster:
  1869  		cond.ClusterLabels = labelMatchers.Labels
  1870  		cond.ClusterLabelsExpression = labelMatchers.Expression
  1871  		return nil
  1872  	case KindNode:
  1873  		cond.NodeLabels = labelMatchers.Labels
  1874  		cond.NodeLabelsExpression = labelMatchers.Expression
  1875  		return nil
  1876  	case KindKubernetesCluster:
  1877  		cond.KubernetesLabels = labelMatchers.Labels
  1878  		cond.KubernetesLabelsExpression = labelMatchers.Expression
  1879  		return nil
  1880  	case KindApp:
  1881  		cond.AppLabels = labelMatchers.Labels
  1882  		cond.AppLabelsExpression = labelMatchers.Expression
  1883  		return nil
  1884  	case KindDatabase:
  1885  		cond.DatabaseLabels = labelMatchers.Labels
  1886  		cond.DatabaseLabelsExpression = labelMatchers.Expression
  1887  		return nil
  1888  	case KindDatabaseService:
  1889  		cond.DatabaseServiceLabels = labelMatchers.Labels
  1890  		cond.DatabaseServiceLabelsExpression = labelMatchers.Expression
  1891  		return nil
  1892  	case KindWindowsDesktop:
  1893  		cond.WindowsDesktopLabels = labelMatchers.Labels
  1894  		cond.WindowsDesktopLabelsExpression = labelMatchers.Expression
  1895  		return nil
  1896  	case KindWindowsDesktopService:
  1897  		cond.WindowsDesktopLabels = labelMatchers.Labels
  1898  		cond.WindowsDesktopLabelsExpression = labelMatchers.Expression
  1899  		return nil
  1900  	case KindUserGroup:
  1901  		cond.GroupLabels = labelMatchers.Labels
  1902  		cond.GroupLabelsExpression = labelMatchers.Expression
  1903  		return nil
  1904  	}
  1905  	return trace.BadParameter("can't set label matchers for resource kind %q", kind)
  1906  }
  1907  
  1908  // HasLabelMatchers returns true if the role has label matchers for the
  1909  // specified resource kind and condition (allow/deny).
  1910  // If the kind is not supported, false is returned.
  1911  func (r *RoleV6) HasLabelMatchers(rct RoleConditionType, kind string) bool {
  1912  	lm, err := r.GetLabelMatchers(rct, kind)
  1913  	return err == nil && !lm.Empty()
  1914  }
  1915  
  1916  // GetLabel retrieves the label with the provided key.
  1917  func (r *RoleV6) GetLabel(key string) (value string, ok bool) {
  1918  	v, ok := r.Metadata.Labels[key]
  1919  	return v, ok
  1920  }
  1921  
  1922  // GetAllLabels returns all resource's labels.
  1923  func (r *RoleV6) GetAllLabels() map[string]string {
  1924  	return r.Metadata.Labels
  1925  }
  1926  
  1927  // GetStaticLabels returns the resource's static labels.
  1928  func (r *RoleV6) GetStaticLabels() map[string]string {
  1929  	return r.Metadata.Labels
  1930  }
  1931  
  1932  // SetStaticLabels sets the resource's static labels.
  1933  func (r *RoleV6) SetStaticLabels(labels map[string]string) {
  1934  	r.Metadata.Labels = labels
  1935  }
  1936  
  1937  // Origin returns the origin value of the resource.
  1938  func (r *RoleV6) Origin() string {
  1939  	return r.Metadata.Origin()
  1940  }
  1941  
  1942  // SetOrigin sets the origin value of the resource.
  1943  func (r *RoleV6) SetOrigin(origin string) {
  1944  	r.Metadata.SetOrigin(origin)
  1945  }
  1946  
  1947  // MatchSearch goes through select field values of a resource
  1948  // and tries to match against the list of search values.
  1949  func (r *RoleV6) MatchSearch(values []string) bool {
  1950  	fieldVals := append(utils.MapToStrings(r.GetAllLabels()), r.GetName())
  1951  	return MatchSearch(fieldVals, values, nil)
  1952  }
  1953  
  1954  // LabelMatcherKinds is the complete list of resource kinds that support label
  1955  // matchers.
  1956  var LabelMatcherKinds = []string{
  1957  	KindRemoteCluster,
  1958  	KindNode,
  1959  	KindKubernetesCluster,
  1960  	KindApp,
  1961  	KindDatabase,
  1962  	KindDatabaseService,
  1963  	KindWindowsDesktop,
  1964  	KindWindowsDesktopService,
  1965  	KindUserGroup,
  1966  }
  1967  
  1968  const (
  1969  	createHostUserModeOffString          = "off"
  1970  	createHostUserModeDropString         = "drop"
  1971  	createHostUserModeKeepString         = "keep"
  1972  	createHostUserModeInsecureDropString = "insecure-drop"
  1973  )
  1974  
  1975  func (h CreateHostUserMode) encode() (string, error) {
  1976  	switch h {
  1977  	case CreateHostUserMode_HOST_USER_MODE_UNSPECIFIED:
  1978  		return "", nil
  1979  	case CreateHostUserMode_HOST_USER_MODE_OFF:
  1980  		return createHostUserModeOffString, nil
  1981  	case CreateHostUserMode_HOST_USER_MODE_DROP:
  1982  		return createHostUserModeDropString, nil
  1983  	case CreateHostUserMode_HOST_USER_MODE_KEEP:
  1984  		return createHostUserModeKeepString, nil
  1985  	case CreateHostUserMode_HOST_USER_MODE_INSECURE_DROP:
  1986  		return createHostUserModeInsecureDropString, nil
  1987  	}
  1988  	return "", trace.BadParameter("invalid host user mode %v", h)
  1989  }
  1990  
  1991  func (h *CreateHostUserMode) decode(val any) error {
  1992  	var valS string
  1993  	switch val := val.(type) {
  1994  	case int32:
  1995  		return trace.Wrap(h.setFromEnum(val))
  1996  	case int64:
  1997  		return trace.Wrap(h.setFromEnum(int32(val)))
  1998  	case int:
  1999  		return trace.Wrap(h.setFromEnum(int32(val)))
  2000  	case float64:
  2001  		return trace.Wrap(h.setFromEnum(int32(val)))
  2002  	case float32:
  2003  		return trace.Wrap(h.setFromEnum(int32(val)))
  2004  	case string:
  2005  		valS = val
  2006  	case bool:
  2007  		if val {
  2008  			return trace.BadParameter("create_host_user_mode cannot be true, got %v", val)
  2009  		}
  2010  		valS = createHostUserModeOffString
  2011  	default:
  2012  		return trace.BadParameter("bad value type %T, expected string or int", val)
  2013  	}
  2014  
  2015  	switch valS {
  2016  	case "":
  2017  		*h = CreateHostUserMode_HOST_USER_MODE_UNSPECIFIED
  2018  	case createHostUserModeOffString:
  2019  		*h = CreateHostUserMode_HOST_USER_MODE_OFF
  2020  	case createHostUserModeKeepString:
  2021  		*h = CreateHostUserMode_HOST_USER_MODE_KEEP
  2022  	case createHostUserModeInsecureDropString, createHostUserModeDropString:
  2023  		*h = CreateHostUserMode_HOST_USER_MODE_INSECURE_DROP
  2024  	default:
  2025  		return trace.BadParameter("invalid host user mode %v", val)
  2026  	}
  2027  	return nil
  2028  }
  2029  
  2030  // setFromEnum sets the value from enum value as int32.
  2031  func (h *CreateHostUserMode) setFromEnum(val int32) error {
  2032  	// Map drop to insecure-drop
  2033  	if val == int32(CreateHostUserMode_HOST_USER_MODE_DROP) {
  2034  		val = int32(CreateHostUserMode_HOST_USER_MODE_INSECURE_DROP)
  2035  	}
  2036  	if _, ok := CreateHostUserMode_name[val]; !ok {
  2037  		return trace.BadParameter("invalid host user mode %v", val)
  2038  	}
  2039  	*h = CreateHostUserMode(val)
  2040  	return nil
  2041  }
  2042  
  2043  // UnmarshalYAML supports parsing CreateHostUserMode from string.
  2044  func (h *CreateHostUserMode) UnmarshalYAML(unmarshal func(interface{}) error) error {
  2045  	var val interface{}
  2046  	err := unmarshal(&val)
  2047  	if err != nil {
  2048  		return trace.Wrap(err)
  2049  	}
  2050  
  2051  	err = h.decode(val)
  2052  	return trace.Wrap(err)
  2053  }
  2054  
  2055  // MarshalYAML marshals CreateHostUserMode to yaml.
  2056  func (h *CreateHostUserMode) MarshalYAML() (interface{}, error) {
  2057  	val, err := h.encode()
  2058  	if err != nil {
  2059  		return nil, trace.Wrap(err)
  2060  	}
  2061  	return val, nil
  2062  }
  2063  
  2064  // MarshalJSON marshals CreateHostUserMode to json bytes.
  2065  func (h *CreateHostUserMode) MarshalJSON() ([]byte, error) {
  2066  	val, err := h.encode()
  2067  	if err != nil {
  2068  		return nil, trace.Wrap(err)
  2069  	}
  2070  	out, err := json.Marshal(val)
  2071  	return out, trace.Wrap(err)
  2072  }
  2073  
  2074  // UnmarshalJSON supports parsing CreateHostUserMode from string.
  2075  func (h *CreateHostUserMode) UnmarshalJSON(data []byte) error {
  2076  	var val interface{}
  2077  	err := json.Unmarshal(data, &val)
  2078  	if err != nil {
  2079  		return trace.Wrap(err)
  2080  	}
  2081  
  2082  	err = h.decode(val)
  2083  	return trace.Wrap(err)
  2084  }
  2085  
  2086  const (
  2087  	createDatabaseUserModeOffString            = "off"
  2088  	createDatabaseUserModeKeepString           = "keep"
  2089  	createDatabaseUserModeBestEffortDropString = "best_effort_drop"
  2090  )
  2091  
  2092  func (h CreateDatabaseUserMode) encode() (string, error) {
  2093  	switch h {
  2094  	case CreateDatabaseUserMode_DB_USER_MODE_UNSPECIFIED:
  2095  		return "", nil
  2096  	case CreateDatabaseUserMode_DB_USER_MODE_OFF:
  2097  		return createDatabaseUserModeOffString, nil
  2098  	case CreateDatabaseUserMode_DB_USER_MODE_KEEP:
  2099  		return createDatabaseUserModeKeepString, nil
  2100  	case CreateDatabaseUserMode_DB_USER_MODE_BEST_EFFORT_DROP:
  2101  		return createDatabaseUserModeBestEffortDropString, nil
  2102  	}
  2103  
  2104  	return "", trace.BadParameter("invalid database user mode %v", h)
  2105  }
  2106  
  2107  func (h *CreateDatabaseUserMode) decode(val any) error {
  2108  	var str string
  2109  	switch val := val.(type) {
  2110  	case string:
  2111  		str = val
  2112  	default:
  2113  		return trace.BadParameter("bad value type %T, expected string", val)
  2114  	}
  2115  
  2116  	switch str {
  2117  	case "":
  2118  		*h = CreateDatabaseUserMode_DB_USER_MODE_UNSPECIFIED
  2119  	case createDatabaseUserModeOffString:
  2120  		*h = CreateDatabaseUserMode_DB_USER_MODE_OFF
  2121  	case createDatabaseUserModeKeepString:
  2122  		*h = CreateDatabaseUserMode_DB_USER_MODE_KEEP
  2123  	case createDatabaseUserModeBestEffortDropString:
  2124  		*h = CreateDatabaseUserMode_DB_USER_MODE_BEST_EFFORT_DROP
  2125  	default:
  2126  		return trace.BadParameter("invalid database user mode %v", val)
  2127  	}
  2128  
  2129  	return nil
  2130  }
  2131  
  2132  // UnmarshalYAML supports parsing CreateDatabaseUserMode from string.
  2133  func (h *CreateDatabaseUserMode) UnmarshalYAML(unmarshal func(interface{}) error) error {
  2134  	var val interface{}
  2135  	err := unmarshal(&val)
  2136  	if err != nil {
  2137  		return trace.Wrap(err)
  2138  	}
  2139  
  2140  	err = h.decode(val)
  2141  	return trace.Wrap(err)
  2142  }
  2143  
  2144  // MarshalYAML marshals CreateDatabaseUserMode to yaml.
  2145  func (h *CreateDatabaseUserMode) MarshalYAML() (interface{}, error) {
  2146  	val, err := h.encode()
  2147  	if err != nil {
  2148  		return nil, trace.Wrap(err)
  2149  	}
  2150  	return val, nil
  2151  }
  2152  
  2153  // MarshalJSON marshals CreateDatabaseUserMode to json bytes.
  2154  func (h *CreateDatabaseUserMode) MarshalJSON() ([]byte, error) {
  2155  	val, err := h.encode()
  2156  	if err != nil {
  2157  		return nil, trace.Wrap(err)
  2158  	}
  2159  	out, err := json.Marshal(val)
  2160  	return out, trace.Wrap(err)
  2161  }
  2162  
  2163  // UnmarshalJSON supports parsing CreateDatabaseUserMode from string.
  2164  func (h *CreateDatabaseUserMode) UnmarshalJSON(data []byte) error {
  2165  	var val interface{}
  2166  	err := json.Unmarshal(data, &val)
  2167  	if err != nil {
  2168  		return trace.Wrap(err)
  2169  	}
  2170  
  2171  	err = h.decode(val)
  2172  	return trace.Wrap(err)
  2173  }
  2174  
  2175  // IsEnabled returns true if database automatic user provisioning is enabled.
  2176  func (m CreateDatabaseUserMode) IsEnabled() bool {
  2177  	return m != CreateDatabaseUserMode_DB_USER_MODE_UNSPECIFIED && m != CreateDatabaseUserMode_DB_USER_MODE_OFF
  2178  }