// getConfiguredCredentialStore returns the credential helper configured for the
// given registry, the default credsStore, or the empty string if neither are
// configured.
487482
func getConfiguredCredentialStore(c *ConfigFile, registryHostname string) string {
	if c.CredentialHelpers != nil && registryHostname != "" {
		if helper, exists := c.CredentialHelpers[registryHostname]; exists {
			return helper
		}
	}
	return c.CredentialsStore
}
1280044
func (c *Config) WithCredentials(creds *credentials.Credentials) *Config {
	c.Credentials = creds
	return c
}
910542
func (c *nativeStore) getCredentialsFromStore(serverAddress string) (types.AuthConfig, error) {
	var ret types.AuthConfig

	creds, err := client.Get(c.programFunc, serverAddress)
	if err != nil {
		if credentials.IsErrCredentialsNotFound(err) {
			// do not return an error if the credentials are not
			// in the keychain. Let docker ask for new credentials.
			return ret, nil
		}
		return ret, err
	}

	if creds.Username == tokenUsername {
		ret.IdentityToken = creds.Secret
	} else {
		ret.Password = creds.Secret
		ret.Username = creds.Username
	}

	ret.ServerAddress = serverAddress
	return ret, nil
}
186423
func (e EnvironProvider) DetectCredentials() (*cloud.CloudCredential, error) {
	result := cloud.CloudCredential{
		AuthCredentials: make(map[string]cloud.Credential),
	}
	cfg_file, err := ociConfigFile()
	if err != nil {
		if os.IsNotExist(errors.Cause(err)) {
			return &result, nil
		}
		return nil, errors.Trace(err)
	}

	cfg, err := ini.LooseLoad(cfg_file)
	if err != nil {
		return nil, errors.Trace(err)
	}
	cfg.NameMapper = ini.TitleUnderscore

	var defaultRegion string

	for _, val := range cfg.SectionStrings() {
		values := new(credentialSection)
		if err := cfg.Section(val).MapTo(values); err != nil {
			logger.Warningf("invalid value in section %s: %s", val, err)
			continue
		}
		missingFields := []string{}
		if values.User == "" {
			missingFields = append(missingFields, "user")
		}

		if values.Tenancy == "" {
			missingFields = append(missingFields, "tenancy")
		}

		if values.KeyFile == "" {
			missingFields = append(missingFields, "key_file")
		}

		if values.Fingerprint == "" {
			missingFields = append(missingFields, "fingerprint")
		}
		if values.Region == "" {
			missingFields = append(missingFields, "region")
		}

		if len(missingFields) > 0 {
			logger.Warningf("missing required field(s) in section %s: %s", val, strings.Join(missingFields, ", "))
			continue
		}

		pemFileContent, err := ioutil.ReadFile(values.KeyFile)
		if err != nil {
			return nil, errors.Trace(err)
		}
		if err := common.ValidateKey(pemFileContent, values.PassPhrase); err != nil {
			logger.Warningf("failed to decrypt PEM %s using the configured pass phrase", values.KeyFile)
			continue
		}

		if val == "DEFAULT" {
			defaultRegion = values.Region
		}
		httpSigCreds := cloud.NewCredential(
			cloud.HTTPSigAuthType,
			map[string]string{
				"user":        values.User,
				"tenancy":     values.Tenancy,
				"key":         string(pemFileContent),
				"pass-phrase": values.PassPhrase,
				"fingerprint": values.Fingerprint,
				"region":      values.Region,
			},
		)
		httpSigCreds.Label = fmt.Sprintf("OCI credential %q", val)
		result.AuthCredentials[val] = httpSigCreds
	}
	if len(result.AuthCredentials) == 0 {
		return nil, errors.NotFoundf("OCI credentials")
	}
	result.DefaultRegion = defaultRegion
	return &result, nil
}
253919
func readCredentialSpecRegistry(id, name string) (string, error) {
	key, err := registryOpenKeyFunc(registry.LOCAL_MACHINE, credentialSpecRegistryLocation, registry.QUERY_VALUE)
	if err != nil {
		return "", errors.Wrapf(err, "failed handling spec %q for container %s - registry key %s could not be opened", name, id, credentialSpecRegistryLocation)
	}
	defer key.Close()

	value, _, err := key.GetStringValue(name)
	if err != nil {
		if err == registry.ErrNotExist {
			return "", fmt.Errorf("registry credential spec %q for container %s was not found", name, id)
		}
		return "", errors.Wrapf(err, "error reading credential spec %q from registry for container %s", name, id)
	}

	return value, nil
}
991579
func getRedactedConfig(s *service) config.Configuration {
	rawConf := s.cfg.RawCopy()
	rawConf.GUI.APIKey = "REDACTED"
	if rawConf.GUI.Password != "" {
		rawConf.GUI.Password = "REDACTED"
	}
	if rawConf.GUI.User != "" {
		rawConf.GUI.User = "REDACTED"
	}
	return rawConf
}
224094
func GetAuthConfig(username, password, registry string) (types.AuthConfig, error) {
	if username != "" && password != "" && registry != "" {
		return types.AuthConfig{
			Username:      username,
			Password:      password,
			ServerAddress: registry,
		}, nil
	}

	dcfg, err := config.Load(config.Dir())
	if err != nil {
		return types.AuthConfig{}, fmt.Errorf("loading config file failed: %v", err)
	}

	// return error early if there are no auths saved
	if !dcfg.ContainsAuth() {
		// If we were passed a registry, just use that.
		if registry != "" {
			return setDefaultRegistry(types.AuthConfig{
				ServerAddress: registry,
			}), nil
		}

		// Otherwise, just use an empty auth config.
		return types.AuthConfig{}, nil
	}

	authConfigs, err := dcfg.GetAllCredentials()
	if err != nil {
		return types.AuthConfig{}, fmt.Errorf("getting credentials failed: %v", err)
	}

	// if they passed a specific registry, return those creds _if_ they exist
	if registry != "" {
		// try with the user input
		if creds, ok := authConfigs[registry]; ok {
			fixAuthConfig(&creds, registry)
			return creds, nil
		}

		// remove https:// from user input and try again
		if strings.HasPrefix(registry, "https://") {
			registryCleaned := strings.TrimPrefix(registry, "https://")
			if creds, ok := authConfigs[registryCleaned]; ok {
				fixAuthConfig(&creds, registryCleaned)
				return creds, nil
			}
		}

		// remove http:// from user input and try again
		if strings.HasPrefix(registry, "http://") {
			registryCleaned := strings.TrimPrefix(registry, "http://")
			if creds, ok := authConfigs[registryCleaned]; ok {
				fixAuthConfig(&creds, registryCleaned)
				return creds, nil
			}
		}

		// add https:// to user input and try again
		// see https://github.com/genuinetools/reg/issues/32
		if !strings.HasPrefix(registry, "https://") && !strings.HasPrefix(registry, "http://") {
			registryCleaned := "https://" + registry
			if creds, ok := authConfigs[registryCleaned]; ok {
				fixAuthConfig(&creds, registryCleaned)
				return creds, nil
			}
		}

		logrus.Debugf("Using registry %q with no authentication", registry)

		// Otherwise just use the registry with no auth.
		return setDefaultRegistry(types.AuthConfig{
			ServerAddress: registry,
		}), nil
	}

	// Just set the auth config as the first registryURL, username and password
	// found in the auth config.
	for _, creds := range authConfigs {
		fmt.Printf("No registry passed. Using registry %q\n", creds.ServerAddress)
		return creds, nil
	}

	// Don't use any authentication.
	// We should never get here.
	fmt.Println("Not using any authentication")
	return types.AuthConfig{}, nil
}
317089
func (s *store) AllCredentials() (map[string]cloud.CloudCredential, error) {
	cloudCredentials, err := ReadCredentialsFile(JujuCredentialsPath())
	if err != nil {
		return nil, errors.Trace(err)
	}
	return cloudCredentials, nil
}
875535
func getCertificate(clientHello *tls.ClientHelloInfo) (*tls.Certificate, error) {
	if len(cfgCerts.Certificates) == 0 {
		return nil, fmt.Errorf("tls: no certificates configured")
	}

	if len(cfgCerts.Certificates) == 1 || cfgCerts.NameToCertificate == nil {
		// There's only one choice, so no point doing any work.
		return &cfgCerts.Certificates[0], nil
	}

	name := strings.ToLower(clientHello.ServerName)
	for len(name) > 0 && name[len(name)-1] == '.' {
		name = name[:len(name)-1]
	}

	if cert, ok := cfgCerts.NameToCertificate[name]; ok {
		return cert, nil
	}

	// try replacing labels in the name with wildcards until we get a
	// match.
	labels := strings.Split(name, ".")
	for i := range labels {
		labels[i] = "*"
		candidate := strings.Join(labels, ".")
		if cert, ok := cfgCerts.NameToCertificate[candidate]; ok {
			return cert, nil
		}
	}

	// If nothing matches, return the first certificate.
	return &cfgCerts.Certificates[0], nil
}
295519
func (s *AESEncryptedStorage) readEncryptedStorage() (map[string]storedCredential, error) {
	creds := make(map[string]storedCredential)
	raw, err := ioutil.ReadFile(s.filename)

	if err != nil {
		if os.IsNotExist(err) {
			// Doesn't exist yet
			return creds, nil
		}
		log.Warn("Failed to read encrypted storage", "err", err, "file", s.filename)
	}
	if err = json.Unmarshal(raw, &creds); err != nil {
		log.Warn("Failed to unmarshal encrypted storage", "err", err, "file", s.filename)
		return nil, err
	}
	return creds, nil
}
1224588
func (configFile *ConfigFile) GetAllCredentials() (map[string]types.AuthConfig, error) {
	auths := make(map[string]types.AuthConfig)
	addAll := func(from map[string]types.AuthConfig) {
		for reg, ac := range from {
			auths[reg] = ac
		}
	}

	defaultStore := configFile.GetCredentialsStore("")
	newAuths, err := defaultStore.GetAll()
	if err != nil {
		return nil, err
	}
	addAll(newAuths)

	// Auth configs from a registry-specific helper should override those from the default store.
	for registryHostname := range configFile.CredentialHelpers {
		newAuth, err := configFile.GetAuthConfig(registryHostname)
		if err != nil {
			return nil, err
		}
		auths[registryHostname] = newAuth
	}
	return auths, nil
}
619023
func GetAWSSDKCredentialProvider() (func() (key, secret, token string, err error), func() bool) {
	return myCredProvider.Retrieve, myCredProvider.IsExpired
}
782189
func (p environProviderCredentials) RegisterCredentials(cld cloud.Cloud) (map[string]*cloud.CloudCredential, error) {
	cloudName := cld.Name
	if cloudName != caas.K8sCloudMicrok8s {
		return make(map[string]*cloud.CloudCredential), nil
	}
	_, cred, _, err := p.builtinCloudGetter(p.cmdRunner)

	if err != nil {
		return nil, errors.Trace(err)
	}

	return map[string]*cloud.CloudCredential{
		cloudName: {
			DefaultCredential: cloudName,
			AuthCredentials: map[string]cloud.Credential{
				cloudName: cred,
			},
		},
	}, nil
}
318100
func (configFile *ConfigFile) GetAuthConfig(registryHostname string) (types.AuthConfig, error) {
	return configFile.GetCredentialsStore(registryHostname).Get(registryHostname)
}
126298
func GetCertificate(d Depot, name string) (crt *pkix.Certificate, err error) {
	b, err := d.Get(CrtTag(name))
	if err != nil {
		return nil, err
	}
	return pkix.NewCertificateFromPEM(b)
}
947991
func (c *ChartDownloader) getRepoCredentials(r *repo.ChartRepository) (username, password string) {
	username = c.Username
	password = c.Password
	if r != nil && r.Config != nil {
		if username == "" {
			username = r.Config.Username
		}
		if password == "" {
			password = r.Config.Password
		}
	}
	return
}
706504
func (c LoginClient) GetConfiguredAccounts(ctx context.Context, sessionID int) (res []ConfiguredAccount, err error) {
	__arg := GetConfiguredAccountsArg{SessionID: sessionID}
	err = c.Cli.Call(ctx, "keybase.1.login.getConfiguredAccounts", []interface{}{__arg}, &res)
	return
}