github.com/gravitational/teleport/api@v0.0.0-20240507183017-3110591cbafc/types/user.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  	"fmt"
    21  	"time"
    22  
    23  	"github.com/gravitational/trace"
    24  
    25  	"github.com/gravitational/teleport/api/constants"
    26  	"github.com/gravitational/teleport/api/utils"
    27  )
    28  
    29  // UserType is the user's types that indicates where it was created.
    30  type UserType string
    31  
    32  const (
    33  	// UserTypeSSO identifies a user that was created from an SSO provider.
    34  	UserTypeSSO UserType = "sso"
    35  	// UserTypeLocal identifies a user that was created in Teleport itself and has no connection to an external identity.
    36  	UserTypeLocal UserType = "local"
    37  )
    38  
    39  // Match checks if the given user matches this filter.
    40  func (f *UserFilter) Match(user *UserV2) bool {
    41  	if len(f.SearchKeywords) != 0 {
    42  		if !user.MatchSearch(f.SearchKeywords) {
    43  			return false
    44  		}
    45  	}
    46  
    47  	return true
    48  }
    49  
    50  // User represents teleport embedded user or external user.
    51  type User interface {
    52  	// ResourceWithSecrets provides common resource properties
    53  	ResourceWithSecrets
    54  	ResourceWithOrigin
    55  	ResourceWithLabels
    56  	// SetMetadata sets object metadata
    57  	SetMetadata(meta Metadata)
    58  	// GetOIDCIdentities returns a list of connected OIDC identities
    59  	GetOIDCIdentities() []ExternalIdentity
    60  	// GetSAMLIdentities returns a list of connected SAML identities
    61  	GetSAMLIdentities() []ExternalIdentity
    62  	// GetGithubIdentities returns a list of connected Github identities
    63  	GetGithubIdentities() []ExternalIdentity
    64  	// Get local authentication secrets (may be nil).
    65  	GetLocalAuth() *LocalAuthSecrets
    66  	// Set local authentication secrets (use nil to delete).
    67  	SetLocalAuth(auth *LocalAuthSecrets)
    68  	// GetRoles returns a list of roles assigned to user
    69  	GetRoles() []string
    70  	// GetLogins gets the list of server logins/principals for the user
    71  	GetLogins() []string
    72  	// GetDatabaseUsers gets the list of Database Users for the user
    73  	GetDatabaseUsers() []string
    74  	// GetDatabaseNames gets the list of Database Names for the user
    75  	GetDatabaseNames() []string
    76  	// GetKubeUsers gets the list of Kubernetes Users for the user
    77  	GetKubeUsers() []string
    78  	// GetKubeGroups gets the list of Kubernetes Groups for the user
    79  	GetKubeGroups() []string
    80  	// GetWindowsLogins gets the list of Windows Logins for the user
    81  	GetWindowsLogins() []string
    82  	// GetAWSRoleARNs gets the list of AWS role ARNs for the user
    83  	GetAWSRoleARNs() []string
    84  	// GetAzureIdentities gets a list of Azure identities for the user
    85  	GetAzureIdentities() []string
    86  	// GetGCPServiceAccounts gets a list of GCP service accounts for the user
    87  	GetGCPServiceAccounts() []string
    88  	// String returns user
    89  	String() string
    90  	// GetStatus return user login status
    91  	GetStatus() LoginStatus
    92  	// SetLocked sets login status to locked
    93  	SetLocked(until time.Time, reason string)
    94  	// ResetLocks resets lock related fields to empty values.
    95  	ResetLocks()
    96  	// SetRoles sets user roles
    97  	SetRoles(roles []string)
    98  	// AddRole adds role to the users' role list
    99  	AddRole(name string)
   100  	// SetLogins sets a list of server logins/principals for user
   101  	SetLogins(logins []string)
   102  	// SetDatabaseUsers sets a list of Database Users for user
   103  	SetDatabaseUsers(databaseUsers []string)
   104  	// SetDatabaseNames sets a list of Database Names for user
   105  	SetDatabaseNames(databaseNames []string)
   106  	// SetDatabaseRoles sets a list of Database roles for user
   107  	SetDatabaseRoles(databaseRoles []string)
   108  	// SetKubeUsers sets a list of Kubernetes Users for user
   109  	SetKubeUsers(kubeUsers []string)
   110  	// SetKubeGroups sets a list of Kubernetes Groups for user
   111  	SetKubeGroups(kubeGroups []string)
   112  	// SetWindowsLogins sets a list of Windows Logins for user
   113  	SetWindowsLogins(logins []string)
   114  	// SetAWSRoleARNs sets a list of AWS role ARNs for user
   115  	SetAWSRoleARNs(awsRoleARNs []string)
   116  	// SetAzureIdentities sets a list of Azure identities for the user
   117  	SetAzureIdentities(azureIdentities []string)
   118  	// SetGCPServiceAccounts sets a list of GCP service accounts for the user
   119  	SetGCPServiceAccounts(accounts []string)
   120  	// SetHostUserUID sets the UID for host users
   121  	SetHostUserUID(uid string)
   122  	// SetHostUserGID sets the GID for host users
   123  	SetHostUserGID(gid string)
   124  	// GetCreatedBy returns information about user
   125  	GetCreatedBy() CreatedBy
   126  	// SetCreatedBy sets created by information
   127  	SetCreatedBy(CreatedBy)
   128  	// GetUserType indicates if the User was created by an SSO Provider or locally.
   129  	GetUserType() UserType
   130  	// GetTraits gets the trait map for this user used to populate role variables.
   131  	GetTraits() map[string][]string
   132  	// SetTraits sets the trait map for this user used to populate role variables.
   133  	SetTraits(map[string][]string)
   134  	// GetTrustedDeviceIDs returns the IDs of the user's trusted devices.
   135  	GetTrustedDeviceIDs() []string
   136  	// SetTrustedDeviceIDs assigns the IDs of the user's trusted devices.
   137  	SetTrustedDeviceIDs(ids []string)
   138  	// IsBot returns true if the user is a bot.
   139  	IsBot() bool
   140  	// BotGenerationLabel returns the bot generation label.
   141  	BotGenerationLabel() string
   142  	// GetPasswordState reflects what the system knows about the user's password.
   143  	// Note that this is a "best effort" property, in that it can be UNSPECIFIED
   144  	// for users who were created before this property was introduced and didn't
   145  	// perform any password-related activity since then. See RFD 0159 for details.
   146  	// Do NOT use this value for authentication purposes!
   147  	GetPasswordState() PasswordState
   148  	// SetPasswordState updates the information about user's password. Note that
   149  	// this is a "best effort" property, in that it can be UNSPECIFIED for users
   150  	// who were created before this property was introduced and didn't perform any
   151  	// password-related activity since then. See RFD 0159 for details.
   152  	SetPasswordState(PasswordState)
   153  }
   154  
   155  // NewUser creates new empty user
   156  func NewUser(name string) (User, error) {
   157  	u := &UserV2{
   158  		Metadata: Metadata{
   159  			Name: name,
   160  		},
   161  	}
   162  	if err := u.CheckAndSetDefaults(); err != nil {
   163  		return nil, trace.Wrap(err)
   164  	}
   165  	return u, nil
   166  }
   167  
   168  // IsSameProvider returns true if the provided connector has the
   169  // same ID/type as this one
   170  func (r *ConnectorRef) IsSameProvider(other *ConnectorRef) bool {
   171  	return other != nil && other.Type == r.Type && other.ID == r.ID
   172  }
   173  
   174  // GetVersion returns resource version
   175  func (u *UserV2) GetVersion() string {
   176  	return u.Version
   177  }
   178  
   179  // GetKind returns resource kind
   180  func (u *UserV2) GetKind() string {
   181  	return u.Kind
   182  }
   183  
   184  // GetSubKind returns resource sub kind
   185  func (u *UserV2) GetSubKind() string {
   186  	return u.SubKind
   187  }
   188  
   189  // SetSubKind sets resource subkind
   190  func (u *UserV2) SetSubKind(s string) {
   191  	u.SubKind = s
   192  }
   193  
   194  // GetResourceID returns resource ID
   195  func (u *UserV2) GetResourceID() int64 {
   196  	return u.Metadata.ID
   197  }
   198  
   199  // SetResourceID sets resource ID
   200  func (u *UserV2) SetResourceID(id int64) {
   201  	u.Metadata.ID = id
   202  }
   203  
   204  // GetRevision returns the revision
   205  func (u *UserV2) GetRevision() string {
   206  	return u.Metadata.GetRevision()
   207  }
   208  
   209  // SetRevision sets the revision
   210  func (u *UserV2) SetRevision(rev string) {
   211  	u.Metadata.SetRevision(rev)
   212  }
   213  
   214  // GetMetadata returns object metadata
   215  func (u *UserV2) GetMetadata() Metadata {
   216  	return u.Metadata
   217  }
   218  
   219  // Origin returns the origin value of the resource.
   220  func (u *UserV2) Origin() string {
   221  	return u.Metadata.Origin()
   222  }
   223  
   224  // SetOrigin sets the origin value of the resource.
   225  func (u *UserV2) SetOrigin(origin string) {
   226  	u.Metadata.SetOrigin(origin)
   227  }
   228  
   229  // GetLabel fetches the given user label, with the same semantics
   230  // as a map read
   231  func (u *UserV2) GetLabel(key string) (value string, ok bool) {
   232  	value, ok = u.Metadata.Labels[key]
   233  	return
   234  }
   235  
   236  // GetAllLabels fetches all the user labels.
   237  func (u *UserV2) GetAllLabels() map[string]string {
   238  	return u.Metadata.Labels
   239  }
   240  
   241  // GetStaticLabels fetches all the user labels.
   242  func (u *UserV2) GetStaticLabels() map[string]string {
   243  	return u.Metadata.Labels
   244  }
   245  
   246  // SetStaticLabels sets the entire label set for the user.
   247  func (u *UserV2) SetStaticLabels(sl map[string]string) {
   248  	u.Metadata.Labels = sl
   249  }
   250  
   251  // MatchSearch goes through select field values and tries to
   252  // match against the list of search values.
   253  func (u *UserV2) MatchSearch(values []string) bool {
   254  	fieldVals := append(utils.MapToStrings(u.Metadata.Labels), u.GetName())
   255  	return MatchSearch(fieldVals, values, nil)
   256  }
   257  
   258  // SetMetadata sets object metadata
   259  func (u *UserV2) SetMetadata(meta Metadata) {
   260  	u.Metadata = meta
   261  }
   262  
   263  // SetExpiry sets expiry time for the object
   264  func (u *UserV2) SetExpiry(expires time.Time) {
   265  	u.Metadata.SetExpiry(expires)
   266  }
   267  
   268  // GetName returns the name of the User
   269  func (u *UserV2) GetName() string {
   270  	return u.Metadata.Name
   271  }
   272  
   273  // SetName sets the name of the User
   274  func (u *UserV2) SetName(e string) {
   275  	u.Metadata.Name = e
   276  }
   277  
   278  // WithoutSecrets returns an instance of resource without secrets.
   279  func (u *UserV2) WithoutSecrets() Resource {
   280  	if u.Spec.LocalAuth == nil {
   281  		return u
   282  	}
   283  	u2 := *u
   284  	u2.Spec.LocalAuth = nil
   285  	return &u2
   286  }
   287  
   288  // GetTraits gets the trait map for this user used to populate role variables.
   289  func (u *UserV2) GetTraits() map[string][]string {
   290  	return u.Spec.Traits
   291  }
   292  
   293  // SetTraits sets the trait map for this user used to populate role variables.
   294  func (u *UserV2) SetTraits(traits map[string][]string) {
   295  	u.Spec.Traits = traits
   296  }
   297  
   298  // GetTrustedDeviceIDs returns the IDs of the user's trusted devices.
   299  func (u *UserV2) GetTrustedDeviceIDs() []string {
   300  	return u.Spec.TrustedDeviceIDs
   301  }
   302  
   303  // SetTrustedDeviceIDs assigns the IDs of the user's trusted devices.
   304  func (u *UserV2) SetTrustedDeviceIDs(ids []string) {
   305  	u.Spec.TrustedDeviceIDs = ids
   306  }
   307  
   308  // setStaticFields sets static resource header and metadata fields.
   309  func (u *UserV2) setStaticFields() {
   310  	u.Kind = KindUser
   311  	u.Version = V2
   312  }
   313  
   314  // CheckAndSetDefaults checks and set default values for any missing fields.
   315  func (u *UserV2) CheckAndSetDefaults() error {
   316  	u.setStaticFields()
   317  	if err := u.Metadata.CheckAndSetDefaults(); err != nil {
   318  		return trace.Wrap(err)
   319  	}
   320  
   321  	for _, id := range u.Spec.OIDCIdentities {
   322  		if err := id.Check(); err != nil {
   323  			return trace.Wrap(err)
   324  		}
   325  	}
   326  
   327  	return nil
   328  }
   329  
   330  // SetCreatedBy sets created by information
   331  func (u *UserV2) SetCreatedBy(b CreatedBy) {
   332  	u.Spec.CreatedBy = b
   333  }
   334  
   335  // GetCreatedBy returns information about who created user
   336  func (u *UserV2) GetCreatedBy() CreatedBy {
   337  	return u.Spec.CreatedBy
   338  }
   339  
   340  // Expiry returns expiry time for temporary users. Prefer expires from
   341  // metadata, if it does not exist, fall back to expires in spec.
   342  func (u *UserV2) Expiry() time.Time {
   343  	if u.Metadata.Expires != nil && !u.Metadata.Expires.IsZero() {
   344  		return *u.Metadata.Expires
   345  	}
   346  	return u.Spec.Expires
   347  }
   348  
   349  // SetRoles sets a list of roles for user
   350  func (u *UserV2) SetRoles(roles []string) {
   351  	u.Spec.Roles = utils.Deduplicate(roles)
   352  }
   353  
   354  func (u *UserV2) setTrait(trait string, list []string) {
   355  	if u.Spec.Traits == nil {
   356  		u.Spec.Traits = make(map[string][]string)
   357  	}
   358  	u.Spec.Traits[trait] = utils.Deduplicate(list)
   359  }
   360  
   361  // SetLogins sets the Logins trait for the user
   362  func (u *UserV2) SetLogins(logins []string) {
   363  	u.setTrait(constants.TraitLogins, logins)
   364  }
   365  
   366  // SetDatabaseUsers sets the DatabaseUsers trait for the user
   367  func (u *UserV2) SetDatabaseUsers(databaseUsers []string) {
   368  	u.setTrait(constants.TraitDBUsers, databaseUsers)
   369  }
   370  
   371  // SetDatabaseNames sets the DatabaseNames trait for the user
   372  func (u *UserV2) SetDatabaseNames(databaseNames []string) {
   373  	u.setTrait(constants.TraitDBNames, databaseNames)
   374  }
   375  
   376  // SetDatabaseRoles sets the DatabaseRoles trait for the user
   377  func (u *UserV2) SetDatabaseRoles(databaseRoles []string) {
   378  	u.setTrait(constants.TraitDBRoles, databaseRoles)
   379  }
   380  
   381  // SetKubeUsers sets the KubeUsers trait for the user
   382  func (u *UserV2) SetKubeUsers(kubeUsers []string) {
   383  	u.setTrait(constants.TraitKubeUsers, kubeUsers)
   384  }
   385  
   386  // SetKubeGroups sets the KubeGroups trait for the user
   387  func (u *UserV2) SetKubeGroups(kubeGroups []string) {
   388  	u.setTrait(constants.TraitKubeGroups, kubeGroups)
   389  }
   390  
   391  // SetWindowsLogins sets the WindowsLogins trait for the user
   392  func (u *UserV2) SetWindowsLogins(logins []string) {
   393  	u.setTrait(constants.TraitWindowsLogins, logins)
   394  }
   395  
   396  // SetAWSRoleARNs sets the AWSRoleARNs trait for the user
   397  func (u *UserV2) SetAWSRoleARNs(awsRoleARNs []string) {
   398  	u.setTrait(constants.TraitAWSRoleARNs, awsRoleARNs)
   399  }
   400  
   401  // SetAzureIdentities sets a list of Azure identities for the user
   402  func (u *UserV2) SetAzureIdentities(identities []string) {
   403  	u.setTrait(constants.TraitAzureIdentities, identities)
   404  }
   405  
   406  // SetGCPServiceAccounts sets a list of GCP service accounts for the user
   407  func (u *UserV2) SetGCPServiceAccounts(accounts []string) {
   408  	u.setTrait(constants.TraitGCPServiceAccounts, accounts)
   409  }
   410  
   411  // SetHostUserUID sets the host user UID
   412  func (u *UserV2) SetHostUserUID(uid string) {
   413  	u.setTrait(constants.TraitHostUserUID, []string{uid})
   414  }
   415  
   416  // SetHostUserGID sets the host user GID
   417  func (u *UserV2) SetHostUserGID(uid string) {
   418  	u.setTrait(constants.TraitHostUserGID, []string{uid})
   419  }
   420  
   421  // GetStatus returns login status of the user
   422  func (u *UserV2) GetStatus() LoginStatus {
   423  	return u.Spec.Status
   424  }
   425  
   426  // GetOIDCIdentities returns a list of connected OIDC identities
   427  func (u *UserV2) GetOIDCIdentities() []ExternalIdentity {
   428  	return u.Spec.OIDCIdentities
   429  }
   430  
   431  // GetSAMLIdentities returns a list of connected SAML identities
   432  func (u *UserV2) GetSAMLIdentities() []ExternalIdentity {
   433  	return u.Spec.SAMLIdentities
   434  }
   435  
   436  // GetGithubIdentities returns a list of connected Github identities
   437  func (u *UserV2) GetGithubIdentities() []ExternalIdentity {
   438  	return u.Spec.GithubIdentities
   439  }
   440  
   441  // GetLocalAuth gets local authentication secrets (may be nil).
   442  func (u *UserV2) GetLocalAuth() *LocalAuthSecrets {
   443  	return u.Spec.LocalAuth
   444  }
   445  
   446  // SetLocalAuth sets local authentication secrets (use nil to delete).
   447  func (u *UserV2) SetLocalAuth(auth *LocalAuthSecrets) {
   448  	u.Spec.LocalAuth = auth
   449  }
   450  
   451  // GetRoles returns a list of roles assigned to user
   452  func (u *UserV2) GetRoles() []string {
   453  	return u.Spec.Roles
   454  }
   455  
   456  // AddRole adds a role to user's role list
   457  func (u *UserV2) AddRole(name string) {
   458  	for _, r := range u.Spec.Roles {
   459  		if r == name {
   460  			return
   461  		}
   462  	}
   463  	u.Spec.Roles = append(u.Spec.Roles, name)
   464  }
   465  
   466  func (u UserV2) getTrait(trait string) []string {
   467  	if u.Spec.Traits == nil {
   468  		return []string{}
   469  	}
   470  	return u.Spec.Traits[trait]
   471  }
   472  
   473  // GetLogins gets the list of server logins/principals for the user
   474  func (u UserV2) GetLogins() []string {
   475  	return u.getTrait(constants.TraitLogins)
   476  }
   477  
   478  // GetDatabaseUsers gets the list of DB Users for the user
   479  func (u UserV2) GetDatabaseUsers() []string {
   480  	return u.getTrait(constants.TraitDBUsers)
   481  }
   482  
   483  // GetDatabaseNames gets the list of DB Names for the user
   484  func (u UserV2) GetDatabaseNames() []string {
   485  	return u.getTrait(constants.TraitDBNames)
   486  }
   487  
   488  // GetKubeUsers gets the list of Kubernetes Users for the user
   489  func (u UserV2) GetKubeUsers() []string {
   490  	return u.getTrait(constants.TraitKubeUsers)
   491  }
   492  
   493  // GetKubeGroups gets the list of Kubernetes Groups for the user
   494  func (u UserV2) GetKubeGroups() []string {
   495  	return u.getTrait(constants.TraitKubeGroups)
   496  }
   497  
   498  // GetWindowsLogins gets the list of Windows Logins for the user
   499  func (u UserV2) GetWindowsLogins() []string {
   500  	return u.getTrait(constants.TraitWindowsLogins)
   501  }
   502  
   503  // GetAWSRoleARNs gets the list of AWS role ARNs for the user
   504  func (u UserV2) GetAWSRoleARNs() []string {
   505  	return u.getTrait(constants.TraitAWSRoleARNs)
   506  }
   507  
   508  // GetAzureIdentities gets a list of Azure identities for the user
   509  func (u UserV2) GetAzureIdentities() []string {
   510  	return u.getTrait(constants.TraitAzureIdentities)
   511  }
   512  
   513  // GetGCPServiceAccounts gets a list of GCP service accounts for the user
   514  func (u UserV2) GetGCPServiceAccounts() []string {
   515  	return u.getTrait(constants.TraitGCPServiceAccounts)
   516  }
   517  
   518  // GetUserType indicates if the User was created by an SSO Provider or locally.
   519  func (u UserV2) GetUserType() UserType {
   520  	if u.GetCreatedBy().Connector == nil {
   521  		return UserTypeLocal
   522  	}
   523  
   524  	return UserTypeSSO
   525  }
   526  
   527  // IsBot returns true if the user is a bot.
   528  func (u UserV2) IsBot() bool {
   529  	_, ok := u.GetMetadata().Labels[BotLabel]
   530  	return ok
   531  }
   532  
   533  // BotGenerationLabel returns the bot generation label.
   534  func (u UserV2) BotGenerationLabel() string {
   535  	return u.GetMetadata().Labels[BotGenerationLabel]
   536  }
   537  
   538  func (u *UserV2) String() string {
   539  	return fmt.Sprintf("User(name=%v, roles=%v, identities=%v)", u.Metadata.Name, u.Spec.Roles, u.Spec.OIDCIdentities)
   540  }
   541  
   542  // SetLocked marks the user as locked
   543  func (u *UserV2) SetLocked(until time.Time, reason string) {
   544  	u.Spec.Status.IsLocked = true
   545  	u.Spec.Status.LockExpires = until
   546  	u.Spec.Status.LockedMessage = reason
   547  	u.Spec.Status.LockedTime = time.Now().UTC()
   548  }
   549  
   550  // ResetLocks resets lock related fields to empty values.
   551  func (u *UserV2) ResetLocks() {
   552  	u.Spec.Status.IsLocked = false
   553  	u.Spec.Status.LockedMessage = ""
   554  	u.Spec.Status.LockExpires = time.Time{}
   555  }
   556  
   557  // DeepCopy creates a clone of this user value.
   558  func (u *UserV2) DeepCopy() User {
   559  	return utils.CloneProtoMsg(u)
   560  }
   561  
   562  func (u *UserV2) GetPasswordState() PasswordState {
   563  	return u.Status.PasswordState
   564  }
   565  
   566  func (u *UserV2) SetPasswordState(state PasswordState) {
   567  	u.Status.PasswordState = state
   568  }
   569  
   570  // IsEmpty returns true if there's no info about who created this user
   571  func (c CreatedBy) IsEmpty() bool {
   572  	return c.User.Name == ""
   573  }
   574  
   575  // String returns human readable information about the user
   576  func (c CreatedBy) String() string {
   577  	if c.User.Name == "" {
   578  		return "system"
   579  	}
   580  	if c.Connector != nil {
   581  		return fmt.Sprintf("%v connector %v for user %v at %v",
   582  			c.Connector.Type, c.Connector.ID, c.Connector.Identity, utils.HumanTimeFormat(c.Time))
   583  	}
   584  	return fmt.Sprintf("%v at %v", c.User.Name, c.Time)
   585  }
   586  
   587  // String returns debug friendly representation of this identity
   588  func (i *ExternalIdentity) String() string {
   589  	return fmt.Sprintf("OIDCIdentity(connectorID=%v, username=%v)", i.ConnectorID, i.Username)
   590  }
   591  
   592  // Check returns nil if all parameters are great, err otherwise
   593  func (i *ExternalIdentity) Check() error {
   594  	if i.ConnectorID == "" {
   595  		return trace.BadParameter("ConnectorID: missing value")
   596  	}
   597  	if i.Username == "" {
   598  		return trace.BadParameter("Username: missing username")
   599  	}
   600  	return nil
   601  }