// Retrieve returns the credentials value or error if no provider returned
// without error. If a provider is found it will be cached.
543786
func (c *ChainProvider) Retrieve() (Value, error) {
	var errs errorList
	for _, p := range c.Providers {
		value, err := p.Retrieve()
		if err == nil {
			c.active = p
			return value, nil
		}
		errs = append(errs, err)
	}
	c.active = nil

	err := ErrNoValidProvidersFoundInChain
	if len(errs) > 0 {
		err = errs
	}

	return Value{}, err
}
185005
func (e *EnvProvider) Retrieve() (Value, error) {
	e.retrieved = false

	token := os.Getenv(EnvCredentialsVarToken)
	if token == "" {
		return Value{ProviderName: EnvCredentialsProviderName},
			ErrEnvCredentialsTokenNotFound
	}

	e.retrieved = true
	value := Value{
		Token:        token,
		Account:      os.Getenv(EnvCredentialsVarAccount),
		ProviderName: EnvCredentialsProviderName,
	}

	return value, nil
}
570254
func (s *CacheOnStorage) Get(key interface{}) (interface{}, error) {
	if item, err := s.cache.Get(key); err != nil {
		return nil, err
	} else if item != nil {
		return item, nil
	}

	item, err := s.storage.Get(key)
	if err != nil {
		return nil, err
	}

	if err := s.cache.Set(item); err != nil {
		// XXX: Maybe make this a non error
		return nil, err
	}
	return item, nil
}
988485
func (self *PlanClient) Retrieve(id string) (*Plan, error) {
	plan := Plan{}
	path := "/v1/plans/" + url.QueryEscape(id)
	err := query("GET", path, nil, &plan)
	return &plan, err
}
977980
func (list *Validators) Get(id ID) (p Validator, err error) {
	list.RLock()
	defer list.RUnlock()
	var ok bool
	if p, ok = list.providers[id]; !ok {
		return nil, fmt.Errorf("provider %v doesn't exist", id)
	}
	return p, nil
}
1096917
func (e *Engine) RetrieveCredentials(ctx context.Context,
	notifier *observer.Notifier, cpath, cpathexp *string, teamIDs []identity.ID, skipDecryption bool) ([]PlaintextCredentialEnvelope, error) {
	if cpath != nil && cpathexp != nil {
		panic("cannot use both cpath and cpathexp")
	}
	if cpath == nil && cpathexp == nil {
		panic("cpath or cpathexp required")
	}

	var graphs []registry.CredentialGraph
	var err error
	if cpath != nil {
		graphs, err = e.client.CredentialGraph.List(ctx, *cpath, nil, e.session.AuthID(), teamIDs)
	} else if cpathexp != nil {
		graphs, err = e.client.CredentialGraph.Search(ctx, *cpathexp, e.session.AuthID(), teamIDs)
	}

	if err != nil {
		log.Printf("error retrieving credential graph: %s", err)
		return nil, err
	}

	cgs := newCredentialGraphSet()
	err = cgs.Add(graphs...)
	if err != nil {
		log.Printf("error creating credential graph set: %s", err)
		return nil, err
	}

	// Prune removes all unactive graphs (those without a head credential) and
	// unset credentials.
	activeGraphs, err := cgs.Prune()
	if err != nil {
		log.Printf("error encountered while pruning graph: %s", err)
		return nil, err
	}

	creds := []PlaintextCredentialEnvelope{}
	if len(activeGraphs) == 0 {
		log.Printf("no active graphs found")
		return creds, nil
	}

	var steps uint = 1
	for _, graph := range activeGraphs {
		steps += uint(len(graph.GetCredentials()))
	}

	n := notifier.Notifier(steps)
	n.Notify(observer.Progress, "Credentials retrieved", true)

	if skipDecryption {
		encrypted := []PlaintextCredentialEnvelope{}
		log.Printf("skipping decryption of credentials")
		for _, graph := range activeGraphs {
			for _, cred := range graph.GetCredentials() {
				// If we encounter a v1 credential then we have to decrypt it
				// to get the credential value.
				//
				// Very few v1 credentials exist so we can just decrypt
				// everything in those cases.
				if cred.GetVersion() == 1 {
					log.Printf("encountered a v1 credential; forcing decryption")
					goto Decryption
				}

				cValue := apitypes.NewUndecryptedCredentialValue()
				bv, err := json.Marshal(cValue)
				if err != nil {
					log.Printf("could not marshal undecrypted cvalue: %s", err)
					return nil, err
				}

				cv, err := strconv.Unquote(string(bv))
				if err != nil {
					return nil, err
				}
				encrypted = append(encrypted, packagePlaintextCred(cred, cv))
			}
		}

		return encrypted, nil
	}

Decryption:
	// Loop over the trees and unpack the credentials; later on we will
	// actually do real work and decrypt each of these credentials but for
	// now we just need ot return a list of them!
	idx := newCredentialGraphKeyIndex(*(e.session.AuthID()))
	idx.Add(activeGraphs...)

	// All graphs will belong to the same org
	orgID := activeGraphs[0].GetKeyring().OrgID()

	var fetchKeys sync.WaitGroup
	var kps *registry.Keypairs
	var claimtree *registry.ClaimTree
	var kpsErr, ctErr error
	fetchKeys.Add(2)

	// Fetch the user's keypairs for this specific organization
	go func() {
		kps, kpsErr = e.client.KeyPairs.List(ctx, orgID)
		fetchKeys.Done()
	}()

	// Fetch the org's claimtree which will include all public keys and their
	// claims for all users and machines inside the org
	go func() {
		claimtree, ctErr = e.client.ClaimTree.Get(ctx, orgID, nil)
		fetchKeys.Done()
	}()

	fetchKeys.Wait()
	if kpsErr != nil {
		log.Printf("Cannot fetch keypairs for org[%s]: %s", orgID, kpsErr)
		return nil, kpsErr
	}
	if ctErr != nil {
		log.Printf("Could not fetch claimtree for org[%s]: %s", orgID, ctErr)
		return nil, ctErr
	}

	// Cache the bundled crypto keypairs for reuse
	keypairs := make(map[identity.ID]*crypto.KeyPairs)
	for encryptingKeyID, graphs := range idx.GetIndex() {
		if len(graphs) == 0 {
			continue
		}

		kp, ok := keypairs[*orgID]
		if !ok {
			_, _, kp, err = fetchKeyPairs(kps, orgID)
			if err != nil {
				log.Printf("Error fetching keypairs: %s", err)
				return nil, err
			}
			keypairs[*orgID] = kp
		}

		encryptingKeySegment, err := claimtree.Find(&encryptingKeyID, false)
		if err != nil {
			log.Printf("Could not find encrypting key[%s]: %s", encryptingKeyID, err)
			return nil, err
		}

		encryptingKey := encryptingKeySegment.PublicKey.Body
		err = e.crypto.WithUnsealer(ctx, &kp.Encryption, *encryptingKey.Key.Value, func(unsealer crypto.Unsealer) error {
			for _, graph := range graphs {
				mekshare, err := graph.FindMEKByKeyID(&encryptingKeyID)
				if err != nil {
					log.Printf("Error finding keyring membership: %s %s", encryptingKeyID, err)
					return err
				}

				err = unsealer.WithUnboxer(ctx, *mekshare.Key.Value, *mekshare.Key.Nonce, func(u crypto.Unboxer) error {
					for _, cred := range graph.GetCredentials() {
						pt, err := u.Unbox(ctx, *cred.Credential().Value, *cred.Nonce(), *cred.Credential().Nonce)
						if err != nil {
							log.Printf("Error decrypting credential: %s", err)
							return err
						}

						// If this is a v1 credential, then we need to unmarshal the
						// plain text value to check whether or not we should return
						// the credentials.
						if cred.GetVersion() == 1 {
							cValue, err := extractCredentialValue(pt)
							if err != nil {
								log.Printf("could not unmarshal credential value from v1 cred: %s", err)
								return err
							}

							if cValue.IsUnset() {
								continue
							}
						}

						creds = append(creds, packagePlaintextCred(cred, string(pt)))
						n.Notify(observer.Progress, "Credential decrypted", true)
					}
					return nil
				})
				if err != nil {
					log.Printf("encountered an error while unboxing: %s", err)
					return err
				}
			}

			return nil
		})
		if err != nil {
			log.Printf("encountered an error while unsealing: %s", err)
			return nil, err
		}
	}

	return creds, nil
}
1111847
func (s *StaticProvider) Retrieve() (Value, error) {
	if s.Token == "" {
		return Value{ProviderName: StaticCredentialsProviderName},
			ErrStaticCredentialsEmpty
	}
	if len(s.Value.ProviderName) == 0 {
		s.Value.ProviderName = StaticCredentialsProviderName
	}
	return s.Value, nil
}
1162129
func (p *AssumeRoleProvider) Retrieve() (credentials.Value, error) {

	// Apply defaults where parameters are not set.
	if p.RoleSessionName == "" {
		// Try to work out a role name that will hopefully end up unique.
		p.RoleSessionName = fmt.Sprintf("%d", time.Now().UTC().UnixNano())
	}
	if p.Duration == 0 {
		// Expire as often as AWS permits.
		p.Duration = DefaultDuration
	}
	jitter := time.Duration(sdkrand.SeededRand.Float64() * p.MaxJitterFrac * float64(p.Duration))
	input := &sts.AssumeRoleInput{
		DurationSeconds: aws.Int64(int64((p.Duration - jitter) / time.Second)),
		RoleArn:         aws.String(p.RoleARN),
		RoleSessionName: aws.String(p.RoleSessionName),
		ExternalId:      p.ExternalID,
	}
	if p.Policy != nil {
		input.Policy = p.Policy
	}
	if p.SerialNumber != nil {
		if p.TokenCode != nil {
			input.SerialNumber = p.SerialNumber
			input.TokenCode = p.TokenCode
		} else if p.TokenProvider != nil {
			input.SerialNumber = p.SerialNumber
			code, err := p.TokenProvider()
			if err != nil {
				return credentials.Value{ProviderName: ProviderName}, err
			}
			input.TokenCode = aws.String(code)
		} else {
			return credentials.Value{ProviderName: ProviderName},
				awserr.New("AssumeRoleTokenNotAvailable",
					"assume role with MFA enabled, but neither TokenCode nor TokenProvider are set", nil)
		}
	}

	roleOutput, err := p.Client.AssumeRole(input)
	if err != nil {
		return credentials.Value{ProviderName: ProviderName}, err
	}

	// We will proactively generate new credentials before they expire.
	p.SetExpiration(*roleOutput.Credentials.Expiration, p.ExpiryWindow)

	return credentials.Value{
		AccessKeyID:     *roleOutput.Credentials.AccessKeyId,
		SecretAccessKey: *roleOutput.Credentials.SecretAccessKey,
		SessionToken:    *roleOutput.Credentials.SessionToken,
		ProviderName:    ProviderName,
	}, nil
}
598823
func (c *CertificateService) get(certURL string) ([]byte, string, error) {
	if len(certURL) == 0 {
		return nil, "", errors.New("certificate[get]: empty URL")
	}

	resp, err := c.core.postAsGet(certURL, nil)
	if err != nil {
		return nil, "", err
	}

	cert, err := ioutil.ReadAll(http.MaxBytesReader(nil, resp.Body, maxBodySize))
	if err != nil {
		return nil, "", err
	}

	// The issuer certificate link may be supplied via an "up" link
	// in the response headers of a new certificate.
	// See https://tools.ietf.org/html/draft-ietf-acme-acme-12#section-7.4.2
	up := getLink(resp.Header, "up")

	return cert, up, err
}
1357759
func (c *Client) Get(ctx context.Context, container, key string) (body io.ReadCloser, size int64, err error) {
	req := newReq(ctx, c.keyURL(container, key))
	c.Auth.SignRequest(req)
	res, err := c.transport().RoundTrip(req)
	if err != nil {
		return
	}
	switch res.StatusCode {
	case http.StatusOK:
		return res.Body, res.ContentLength, nil
	case http.StatusNotFound:
		res.Body.Close()
		return nil, 0, os.ErrNotExist
	default:
		res.Body.Close()
		return nil, 0, fmt.Errorf("azure HTTP error on GET: %d", res.StatusCode)
	}
}
222042
func (c *Cache) Get(key string) (resp []byte, ok bool) {
	item, err := c.Client.Get(cacheKey(key))
	if err != nil {
		return nil, false
	}
	return item.Value, true
}
397356
func (c *LRUExpireCache) Get(key interface{}) (interface{}, bool) {
	c.lock.Lock()
	defer c.lock.Unlock()
	e, ok := c.cache.Get(key)
	if !ok {
		return nil, false
	}
	if c.clock.Now().After(e.(*cacheEntry).expireTime) {
		c.cache.Remove(key)
		return nil, false
	}
	return e.(*cacheEntry).value, true
}
379667
func (self *TokenClient) Retrieve(id string) (*Token, error) {
	token := Token{}
	path := "/v1/tokens/" + url.QueryEscape(id)
	err := query("GET", path, nil, &token)
	return &token, err
}
568957
func Obtain(client RedisClient, key string, opts *Options) (*Locker, error) {
	locker := New(client, key, opts)
	if ok, err := locker.Lock(); err != nil {
		return nil, err
	} else if !ok {
		return nil, ErrLockNotObtained
	}
	return locker, nil
}
661044
func (self *CouponClient) Retrieve(id string) (*Coupon, error) {
	coupon := Coupon{}
	path := "/v1/coupons/" + url.QueryEscape(id)
	err := query("GET", path, nil, &coupon)
	return &coupon, err
}
647590
func (c *securityContextConstraints) Get(name string, options v1.GetOptions) (result *security.SecurityContextConstraints, err error) {
	result = &security.SecurityContextConstraints{}
	err = c.client.Get().
		Resource("securitycontextconstraints").
		Name(name).
		VersionedParams(&options, scheme.ParameterCodec).
		Do().
		Into(result)
	return
}
451216
func (e *EnvAWS) Retrieve() (Value, error) {
	e.retrieved = false

	id := os.Getenv("AWS_ACCESS_KEY_ID")
	if id == "" {
		id = os.Getenv("AWS_ACCESS_KEY")
	}

	secret := os.Getenv("AWS_SECRET_ACCESS_KEY")
	if secret == "" {
		secret = os.Getenv("AWS_SECRET_KEY")
	}

	signerType := SignatureV4
	if id == "" || secret == "" {
		signerType = SignatureAnonymous
	}

	e.retrieved = true
	return Value{
		AccessKeyID:     id,
		SecretAccessKey: secret,
		SessionToken:    os.Getenv("AWS_SESSION_TOKEN"),
		SignerType:      signerType,
	}, nil
}