// GetCloudUsers gets the access permissions on a cloud.
162498
func (st *State) GetCloudUsers(cloud string) (map[string]permission.Access, error) {
	perms, err := st.usersPermissions(cloudGlobalKey(cloud))
	if err != nil {
		return nil, errors.Trace(err)
	}
	result := make(map[string]permission.Access)
	for _, p := range perms {
		result[userIDFromGlobalKey(p.doc.SubjectGlobalKey)] = p.access()
	}
	return result, nil
}
531249
func (a *AuthMiddleware) GetUser(r *http.Request) (interface{}, error) {
	peers := r.TLS.PeerCertificates
	if len(peers) > 1 {
		// when turning intermediaries on, don't forget to verify
		// https://github.com/kubernetes/kubernetes/pull/34524/files#diff-2b283dde198c92424df5355f39544aa4R59
		return nil, trace.AccessDenied("access denied: intermediaries are not supported")
	}
	localClusterName, err := a.AccessPoint.GetClusterName()
	if err != nil {
		return nil, trace.Wrap(err)
	}
	// with no client authentication in place, middleware
	// assumes not-privileged Nop role.
	// it theoretically possible to use bearer token auth even
	// for connections without auth, but this is not active use-case
	// therefore it is not allowed to reduce scope
	if len(peers) == 0 {
		return BuiltinRole{
			GetClusterConfig: a.AccessPoint.GetClusterConfig,
			Role:             teleport.RoleNop,
			Username:         string(teleport.RoleNop),
			ClusterName:      localClusterName.GetClusterName(),
		}, nil
	}
	clientCert := peers[0]
	certClusterName, err := tlsca.ClusterName(clientCert.Issuer)
	if err != nil {
		log.Warnf("Failed to parse client certificate %v.", err)
		return nil, trace.AccessDenied("access denied: invalid client certificate")
	}

	identity, err := tlsca.FromSubject(clientCert.Subject)
	if err != nil {
		return nil, trace.Wrap(err)
	}
	// If there is any restriction on the certificate usage
	// reject the API server request. This is done so some classes
	// of certificates issued for kubernetes usage by proxy, can not be used
	// against auth server. Later on we can extend more
	// advanced cert usage, but for now this is the safest option.
	if len(identity.Usage) != 0 && !utils.StringSlicesEqual(a.AcceptedUsage, identity.Usage) {
		log.Warningf("Restricted certificate of user %q with usage %v rejected while accessing the auth endpoint with acceptable usage %v.",
			identity.Username, identity.Usage, a.AcceptedUsage)
		return nil, trace.AccessDenied("access denied: invalid client certificate")
	}

	// this block assumes interactive user from remote cluster
	// based on the remote certificate authority cluster name encoded in
	// x509 organization name. This is a safe check because:
	// 1. Trust and verification is established during TLS handshake
	// by creating a cert pool constructed of trusted certificate authorities
	// 2. Remote CAs are not allowed to have the same cluster name
	// as the local certificate authority
	if certClusterName != localClusterName.GetClusterName() {
		// make sure that this user does not have system role
		// the local auth server can not truste remote servers
		// to issue certificates with system roles (e.g. Admin),
		// to get unrestricted access to the local cluster
		systemRole := findSystemRole(identity.Groups)
		if systemRole != nil {
			return RemoteBuiltinRole{
				Role:        *systemRole,
				Username:    identity.Username,
				ClusterName: certClusterName,
			}, nil
		}
		return RemoteUser{
			ClusterName:      certClusterName,
			Username:         identity.Username,
			Principals:       identity.Principals,
			KubernetesGroups: identity.KubernetesGroups,
			RemoteRoles:      identity.Groups,
		}, nil
	}
	// code below expects user or service from local cluster, to distinguish between
	// interactive users and services (e.g. proxies), the code below
	// checks for presence of system roles issued in certificate identity
	systemRole := findSystemRole(identity.Groups)
	// in case if the system role is present, assume this is a service
	// agent, e.g. Proxy, connecting to the cluster
	if systemRole != nil {
		return BuiltinRole{
			GetClusterConfig: a.AccessPoint.GetClusterConfig,
			Role:             *systemRole,
			Username:         identity.Username,
			ClusterName:      localClusterName.GetClusterName(),
		}, nil
	}
	// otherwise assume that is a local role, no need to pass the roles
	// as it will be fetched from the local database
	return LocalUser{
		Username: identity.Username,
	}, nil
}
252604
func (l *Client) GetAccounts() ([]*Account, error) {
	res := ApiResp{}
	var data []*Account

	// make the request
	err := l.Get(accountListEndpoint, nil, nil, &res, &data)
	if err != nil {
		return data, err
	}

	return data, nil
}
566010
func (api *CloudAPI) UpdateCloud(cloudArgs params.UpdateCloudArgs) (params.ErrorResults, error) {
	results := params.ErrorResults{
		Results: make([]params.ErrorResult, len(cloudArgs.Clouds)),
	}
	isAdmin, err := api.authorizer.HasPermission(permission.SuperuserAccess, api.ctlrBackend.ControllerTag())
	if err != nil && !errors.IsNotFound(err) {
		return results, errors.Trace(err)
	} else if !isAdmin {
		return results, common.ServerError(common.ErrPerm)
	}
	for i, cloud := range cloudArgs.Clouds {
		err := api.backend.UpdateCloud(common.CloudFromParams(cloud.Name, cloud.Cloud))
		results.Results[i].Error = common.ServerError(err)
	}
	return results, nil
}
96091
func (s *boshDirector) GetCloudControllerVMSet(name string) (io.ReadCloser, error) {
	endpoint := fmt.Sprintf("%s:%d/deployments/%s/vms", s.ip, s.port, name)
	return s.get(endpoint)
}
391045
func (api *CloudAPI) RemoveClouds(args params.Entities) (params.ErrorResults, error) {
	result := params.ErrorResults{
		Results: make([]params.ErrorResult, len(args.Entities)),
	}
	isAdmin, err := api.authorizer.HasPermission(permission.SuperuserAccess, api.ctlrBackend.ControllerTag())
	if err != nil && !errors.IsNotFound(err) {
		return result, errors.Trace(err)
	}
	for i, entity := range args.Entities {
		tag, err := names.ParseCloudTag(entity.Tag)
		if err != nil {
			result.Results[i].Error = common.ServerError(err)
			continue
		}
		// Ensure user has permission to remove the cloud.
		if !isAdmin {
			canAccess, err := api.canAccessCloud(tag.Id(), api.apiUser, permission.AdminAccess)
			if err != nil {
				result.Results[i].Error = common.ServerError(err)
				continue
			}
			if !canAccess {
				result.Results[i].Error = common.ServerError(common.ErrPerm)
				continue
			}
		}
		err = api.backend.RemoveCloud(tag.Id())
		result.Results[i].Error = common.ServerError(err)
	}
	return result, nil
}
721799
func (c *Client) ListUsers() (rec []UserInfo, err error) {
	req, err := newGETRequest(c, "users/")
	if err != nil {
		return []UserInfo{}, err
	}

	if err = executeAndParseRequest(c, req, &rec); err != nil {
		return []UserInfo{}, err
	}

	return rec, nil
}
704115
func (c *Cache) GetUsers() (users []services.User, err error) {
	return c.usersCache.GetUsers()
}
462706
func (c *Crowd) GetGroups(user string, donested bool) ([]*Group, error) {
	groupList := listGroups{}

	v := url.Values{}
	v.Set("username", user)
	var endpoint string

	if donested {
		endpoint = "nested"
	} else {
		endpoint = "direct"
	}

	url := c.url + "rest/usermanagement/1/user/group/" + endpoint + "?" + v.Encode()
	c.Client.Jar = c.cookies
	req, err := http.NewRequest("GET", url, nil)
	if err != nil {
		return groupList.Groups, err
	}
	req.SetBasicAuth(c.user, c.passwd)
	req.Header.Set("Accept", "application/json")
	resp, err := c.Client.Do(req)
	if err != nil {
		return groupList.Groups, err
	}
	defer resp.Body.Close()

	switch resp.StatusCode {
	case 404:
		return groupList.Groups, fmt.Errorf("user not found")
	case 200:
		// fall through switch without returning
	default:
		return groupList.Groups, fmt.Errorf("request failed: %s", resp.Status)
	}

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return groupList.Groups, err
	}

	err = json.Unmarshal(body, &groupList)
	if err != nil {
		return groupList.Groups, err
	}

	return groupList.Groups, nil
}
498233
func (m *Model) Users() ([]permission.UserAccess, error) {
	coll, closer := m.st.db().GetCollection(modelUsersC)
	defer closer()

	var userDocs []userAccessDoc
	err := coll.Find(nil).All(&userDocs)
	if err != nil {
		return nil, errors.Trace(err)
	}

	var modelUsers []permission.UserAccess
	for _, doc := range userDocs {
		// check if the User belonging to this model user has
		// been deleted, in this case we should not return it.
		userTag := names.NewUserTag(doc.UserName)
		if userTag.IsLocal() {
			_, err := m.st.User(userTag)
			if err != nil {
				if _, ok := err.(DeletedUserError); !ok {
					// We ignore deleted users for now. So if it is not a
					// DeletedUserError we return the error.
					return nil, errors.Trace(err)
				}
				continue
			}
		}
		mu, err := NewModelUserAccess(m.st, doc)
		if err != nil {
			return nil, errors.Trace(err)
		}
		modelUsers = append(modelUsers, mu)
	}

	return modelUsers, nil
}
771445
func (sys *IAMSys) GetUser(accessKey string) (cred auth.Credentials, ok bool) {
	sys.RLock()
	defer sys.RUnlock()

	cred, ok = sys.iamUsersMap[accessKey]
	return cred, ok && cred.IsValid()
}
384017
func (api *CloudAPI) AddCloud(cloudArgs params.AddCloudArgs) error {
	isAdmin, err := api.authorizer.HasPermission(permission.SuperuserAccess, api.ctlrBackend.ControllerTag())
	if err != nil && !errors.IsNotFound(err) {
		return errors.Trace(err)
	} else if !isAdmin {
		return common.ServerError(common.ErrPerm)
	}
	err = api.backend.AddCloud(common.CloudFromParams(cloudArgs.Name, cloudArgs.Cloud), api.apiUser.Name())
	return errors.Trace(err)
}
1277070
func (c *Crowd) GetUser(user string) (User, error) {
	u := User{}

	v := url.Values{}
	v.Set("username", user)
	url := c.url + "rest/usermanagement/1/user?" + v.Encode()
	c.Client.Jar = c.cookies
	req, err := http.NewRequest("GET", url, nil)
	if err != nil {
		return u, err
	}
	req.SetBasicAuth(c.user, c.passwd)
	req.Header.Set("Accept", "application/xml")
	req.Header.Set("Content-Type", "application/xml")
	resp, err := c.Client.Do(req)
	if err != nil {
		return u, err
	}
	defer resp.Body.Close()

	switch resp.StatusCode {
	case 404:
		return u, fmt.Errorf("user not found")
	case 200:
		// fall through switch without returning
	default:
		return u, fmt.Errorf("request failed: %s", resp.Status)
	}

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return u, err
	}

	err = xml.Unmarshal(body, &u)
	if err != nil {
		return u, err
	}

	return u, nil
}
426090
func (api *CloudAPI) UserCredentials(args params.UserClouds) (params.StringsResults, error) {
	results := params.StringsResults{
		Results: make([]params.StringsResult, len(args.UserClouds)),
	}
	authFunc, err := api.getCredentialsAuthFunc()
	if err != nil {
		return results, err
	}
	for i, arg := range args.UserClouds {
		userTag, err := names.ParseUserTag(arg.UserTag)
		if err != nil {
			results.Results[i].Error = common.ServerError(err)
			continue
		}
		if !authFunc(userTag) {
			results.Results[i].Error = common.ServerError(common.ErrPerm)
			continue
		}
		cloudTag, err := names.ParseCloudTag(arg.CloudTag)
		if err != nil {
			results.Results[i].Error = common.ServerError(err)
			continue
		}
		cloudCredentials, err := api.backend.CloudCredentials(userTag, cloudTag.Id())
		if err != nil {
			results.Results[i].Error = common.ServerError(err)
			continue
		}
		out := make([]string, 0, len(cloudCredentials))
		for tagId := range cloudCredentials {
			if !names.IsValidCloudCredential(tagId) {
				results.Results[i].Error = common.ServerError(errors.NotValidf("cloud credential ID %q", tagId))
				continue
			}
			out = append(out, names.NewCloudCredentialTag(tagId).String())
		}
		results.Results[i].Result = out
	}
	return results, nil
}
1344378
func (api OrganizationsAPI) GetUserGrants(w http.ResponseWriter, r *http.Request) {
	globalID := mux.Vars(r)["globalid"]
	userIdentifier := mux.Vars(r)["username"]

	userObj, err := SearchUser(r, userIdentifier)
	if err != nil && !db.IsNotFound(err) {
		log.Error("Failed to look up user identifier: ", err)
		http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
		return
	}
	if err != nil {
		log.Debug("If the user doesn't exist he also can't have an authorization")
		// No user found for this identifier, return an empty list of grants
		w.WriteHeader(http.StatusForbidden)
		return
	}

	hasAuth, err := hasAuthorization(r, userObj.Username, globalID)
	if handleServerError(w, "checking if user has an authorization for the organization", err) {
		return
	}
	if !hasAuth {
		log.Debug("Refusing to list grants for user without authorization")
		w.WriteHeader(http.StatusForbidden)
		w.Write([]byte("User does not have an authorization for this organzation"))
		return
	}

	grantMgr := grants.NewManager(r)
	grantObj, err := grantMgr.GetGrantsForUser(userObj.Username, globalID)
	if err != nil && !db.IsNotFound(err) {
		log.Error("Failed to look up user grants: ", err)
		http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
		return
	}
	if db.IsNotFound(err) {
		grantObj = &grants.SavedGrants{Grants: []grants.Grant{}}
	}

	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(http.StatusOK)
	json.NewEncoder(w).Encode(grantObj.Grants)
}
8473
func (c *VSphereCloud) GetCloudGroups(cluster *kops.Cluster, instancegroups []*kops.InstanceGroup, warnUnmatched bool, nodes []v1.Node) (map[string]*cloudinstances.CloudInstanceGroup, error) {
	glog.V(8).Infof("vSphere cloud provider GetCloudGroups not implemented yet")
	return nil, fmt.Errorf("vSphere cloud provider does not support getting cloud groups at this time")
}
113955
func (api *Client) GetUserGroupMembers(userGroup string) ([]string, error) {
	return api.GetUserGroupMembersContext(context.Background(), userGroup)
}