// -- X-Pack Security --
// XPackSecurityGetRoleMapping gets a role mapping.
550196
func (c *Client) XPackSecurityGetRoleMapping(roleMappingName string) *XPackSecurityGetRoleMappingService {
	return NewXPackSecurityGetRoleMappingService(c).Name(roleMappingName)
}
321072
func (v *vaultClient) getRole() string {
	if v.config.Role != "" {
		return v.config.Role
	}

	return v.tokenData.Role
}
1184248
func (c *ClientConn) LoadECDSAPrivateKey(key *ecdsa.PrivateKey) error {
	mk, err := x509.MarshalECPrivateKey(key)

	if err != nil {
		return err
	}

	var pemData = pem.EncodeToMemory(&pem.Block{
		Type:  "ECDSA PRIVATE KEY",
		Bytes: mk,
	})

	return c.loadPrivateKey("ECDSA", string(pemData))
}
941862
func (b *backend) pathRoleRead(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) {
	roleName := data.Get("role_name").(string)
	if roleName == "" {
		return logical.ErrorResponse("missing role_name"), nil
	}

	lock := b.roleLock(roleName)
	lock.RLock()
	lockRelease := lock.RUnlock

	role, err := b.roleEntry(ctx, req.Storage, roleName)
	if err != nil {
		lockRelease()
		return nil, err
	}

	if role == nil {
		lockRelease()
		return nil, nil
	}

	respData := map[string]interface{}{
		"bind_secret_id": role.BindSecretID,
		// TODO - remove this deprecated field in future versions,
		// and its associated warning below.
		"bound_cidr_list":       role.SecretIDBoundCIDRs,
		"secret_id_bound_cidrs": role.SecretIDBoundCIDRs,
		"token_bound_cidrs":     role.TokenBoundCIDRs,
		"period":                role.Period / time.Second,
		"policies":              role.Policies,
		"secret_id_num_uses":    role.SecretIDNumUses,
		"secret_id_ttl":         role.SecretIDTTL / time.Second,
		"token_max_ttl":         role.TokenMaxTTL / time.Second,
		"token_num_uses":        role.TokenNumUses,
		"token_ttl":             role.TokenTTL / time.Second,
		"local_secret_ids":      false,
		"token_type":            role.TokenType,
	}

	if role.SecretIDPrefix == secretIDLocalPrefix {
		respData["local_secret_ids"] = true
	}

	resp := &logical.Response{
		Data: respData,
	}

	if err := validateRoleConstraints(role); err != nil {
		resp.AddWarning("Role does not have any constraints set on it. Updates to this role will require a constraint to be set")
	}
	resp.AddWarning(`The "bound_cidr_list" parameter is deprecated and will be removed in favor of "secret_id_bound_cidrs".`)

	// For sanity, verify that the index still exists. If the index is missing,
	// add one and return a warning so it can be reported.
	roleIDIndex, err := b.roleIDEntry(ctx, req.Storage, role.RoleID)
	if err != nil {
		lockRelease()
		return nil, err
	}

	if roleIDIndex == nil {
		// Switch to a write lock
		lock.RUnlock()
		lock.Lock()
		lockRelease = lock.Unlock

		// Check again if the index is missing
		roleIDIndex, err = b.roleIDEntry(ctx, req.Storage, role.RoleID)
		if err != nil {
			lockRelease()
			return nil, err
		}

		if roleIDIndex == nil {
			// Create a new index
			err = b.setRoleIDEntry(ctx, req.Storage, role.RoleID, &roleIDStorageEntry{
				Name: role.name,
			})
			if err != nil {
				lockRelease()
				return nil, errwrap.Wrapf(fmt.Sprintf("failed to create secondary index for role_id %q: {{err}}", role.RoleID), err)
			}
			resp.AddWarning("Role identifier was missing an index back to role name. A new index has been added. Please report this observation.")
		}
	}

	lockRelease()

	return resp, nil
}
1005377
func Convert_v1beta1_RoleRef_To_rbac_RoleRef(in *v1beta1.RoleRef, out *rbac.RoleRef, s conversion.Scope) error {
	return autoConvert_v1beta1_RoleRef_To_rbac_RoleRef(in, out, s)
}
249780
func (c *Client) XPackSecurityDeleteRole(roleName string) *XPackSecurityDeleteRoleService {
	return NewXPackSecurityDeleteRoleService(c).Name(roleName)
}
395324
func (set RoleSet) CertificateFormat() string {
	var formats []string

	for _, role := range set {
		// get the certificate format for each individual role. if a role does not
		// have a certificate format (like implicit roles) skip over it
		certificateFormat := role.GetOptions().CertificateFormat
		if certificateFormat == "" {
			continue
		}

		formats = append(formats, certificateFormat)
	}

	// if no formats were found, return standard
	if len(formats) == 0 {
		return teleport.CertificateFormatStandard
	}

	// sort the slice so the most permissive is the first element
	sort.Slice(formats, func(i, j int) bool {
		return certificatePriority(formats[i]) < certificatePriority(formats[j])
	})

	return formats[0]
}
1188626
func LoadCommonRSAKeyPairPEM(headers map[string]string) (public []byte, private []byte, err error) {
	keyfile := filepath.Join(config.GetOptions().EtcPath, CommonKeyFilename)
	publicKey, privateKey, err := LoadKeyPairFromFile(keyfile)
	if err != nil {
		return nil, nil, err
	}
	if private, err = PEMFromRSAPrivateKey(privateKey, headers); err != nil {
		log.Errorf("Error loading private key: %+v\n", err)
		return nil, nil, err
	}
	if public, err = PEMFromRSAPublicKey(publicKey, headers); err != nil {
		log.Errorf("Error loading public key: %+v\n", err)
		return nil, nil, err
	}
	return public, private, nil
}
719641
func (i *Invitation) GetRole() string {
	if i == nil || i.Role == nil {
		return ""
	}
	return *i.Role
}
1107129
func FindRoleIndex(rs []*data.Role, name data.RoleName) int {
	for i, r := range rs {
		if r.Name == name {
			return i
		}
	}
	return -1
}
971792
func (ca *CertAuthorityV2) CombinedMapping() RoleMap {
	if len(ca.Spec.Roles) != 0 {
		return RoleMap([]RoleMapping{{Remote: Wildcard, Local: ca.Spec.Roles}})
	}
	return RoleMap(ca.Spec.RoleMap)
}
972455
func (s *SecretService) loadSecrets(ctx context.Context, orgID platform.ID) (map[string]string, int, error) {
	// TODO(desa): update url construction
	sec, err := s.Client.Logical().Read(fmt.Sprintf("/secret/data/%s", orgID))
	if err != nil {
		return nil, -1, err
	}

	m := map[string]string{}
	if sec == nil {
		return m, 0, nil
	}

	data, ok := sec.Data["data"].(map[string]interface{})
	if !ok {
		return nil, -1, fmt.Errorf("value found in secret data is not map[string]interface{}")
	}

	for k, v := range data {
		val, ok := v.(string)
		if !ok {
			continue
		}
		m[k] = val
	}

	metadata, ok := sec.Data["metadata"].(map[string]interface{})
	if !ok {
		return nil, -1, fmt.Errorf("value found in secret metadata is not map[string]interface{}")
	}

	var version int
	switch v := metadata["version"].(type) {
	case json.Number:
		ver, err := v.Int64()
		if err != nil {
			return nil, -1, err
		}
		version = int(ver)
	case string:
		ver, err := strconv.Atoi(v)
		if err != nil {
			return nil, -1, fmt.Errorf("version provided is not a valid integer: %v", err)
		}
		version = ver
	case int:
		version = v
	default:
		return nil, -1, fmt.Errorf("version provided is %T not a string or int", v)
	}

	return m, version, nil
}
717575
func (b *backend) pathRoleDelete(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) {
	roleName := data.Get("role_name").(string)
	if roleName == "" {
		return logical.ErrorResponse("missing role_name"), nil
	}

	lock := b.roleLock(roleName)
	lock.Lock()
	defer lock.Unlock()

	role, err := b.roleEntry(ctx, req.Storage, roleName)
	if err != nil {
		return nil, err
	}
	if role == nil {
		return nil, nil
	}

	// Just before the role is deleted, remove all the SecretIDs issued as part of the role.
	if err = b.flushRoleSecrets(ctx, req.Storage, role.name, role.HMACKey, role.SecretIDPrefix); err != nil {
		return nil, errwrap.Wrapf(fmt.Sprintf("failed to invalidate the secrets belonging to role %q: {{err}}", role.name), err)
	}

	// Delete the reverse mapping from RoleID to the role
	if err = b.roleIDEntryDelete(ctx, req.Storage, role.RoleID); err != nil {
		return nil, errwrap.Wrapf(fmt.Sprintf("failed to delete the mapping from RoleID to role %q: {{err}}", role.name), err)
	}

	// After deleting the SecretIDs and the RoleID, delete the role itself
	if err = req.Storage.Delete(ctx, "role/"+strings.ToLower(role.name)); err != nil {
		return nil, err
	}

	return nil, nil
}
707652
func (t *SignedTargets) BuildDelegationRole(roleName RoleName) (DelegationRole, error) {
	for _, role := range t.Signed.Delegations.Roles {
		if role.Name == roleName {
			pubKeys := make(map[string]PublicKey)
			for _, keyID := range role.KeyIDs {
				pubKey, ok := t.Signed.Delegations.Keys[keyID]
				if !ok {
					// Couldn't retrieve all keys, so stop walking and return invalid role
					return DelegationRole{}, ErrInvalidRole{
						Role:   roleName,
						Reason: "role lists unknown key " + keyID + " as a signing key",
					}
				}
				pubKeys[keyID] = pubKey
			}
			return DelegationRole{
				BaseRole: BaseRole{
					Name:      role.Name,
					Keys:      pubKeys,
					Threshold: role.Threshold,
				},
				Paths: role.Paths,
			}, nil
		}
	}
	return DelegationRole{}, ErrNoSuchRole{Role: roleName}
}
1029651
func (e *SyncedEnforcer) GetRolesForUser(name string) []string {
	e.m.Lock()
	defer e.m.Unlock()
	return e.Enforcer.GetRolesForUser(name)
}
452737
func getRoleMaskFromIdemixRoles(roles []Role) int {
	mask := 0
	for _, role := range roles {
		mask = mask | role.getValue()
	}
	return mask
}
671846
func (c *TrustedClusterV2) CombinedMapping() RoleMap {
	if len(c.Spec.Roles) != 0 {
		return []RoleMapping{{Remote: Wildcard, Local: c.Spec.Roles}}
	}
	return c.Spec.RoleMap
}