// DetectCredentials implements environs.ProviderCredentials.
// Configuration options for the OCI SDK are detailed here:
// https://docs.us-phoenix-1.oraclecloud.com/Content/API/Concepts/sdkconfig.htm
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
}
836779
func (c Credentials) DetectCredentials() (*cloud.CloudCredential, error) {
	result, err := c.OpenstackCredentials.DetectCredentials()
	if err != nil {
		return nil, err
	}

	delete(result.AuthCredentials, string(cloud.AccessKeyAuthType))

	// delete domain name from creds, since rackspace doesn't use it, and it
	// confuses our code.
	for k, v := range result.AuthCredentials {
		attr := v.Attributes()
		delete(attr, openstack.CredAttrDomainName)
		result.AuthCredentials[k] = cloud.NewCredential(v.AuthType(), attr)
	}
	return result, nil
}
222384
func NewCredentials(c client.ConfigProvider, options ...func(*EC2RoleProvider)) *credentials.Credentials {
	p := &EC2RoleProvider{
		Client: ec2metadata.New(c),
	}

	for _, option := range options {
		option(p)
	}

	return credentials.NewCredentials(p)
}
914091
func (e EnvironProvider) validateCloudSpec(spec environs.CloudSpec) error {
	if err := spec.Validate(); err != nil {
		return errors.Trace(err)
	}
	if spec.Credential == nil {
		return errors.NotValidf("missing credentials")
	}

	// validate the authentication type
	if authType := spec.Credential.AuthType(); authType != cloud.UserPassAuthType {
		return errors.NotSupportedf("%q auth-type ", authType)
	}

	if _, ok := spec.Credential.Attributes()["identity-domain"]; !ok {
		return errors.NotFoundf("identity-domain in the credentials")
	}

	return nil
}
1143000
func (environProviderCredentials) CredentialSchemas() map[cloud.AuthType]cloud.CredentialSchema {
	return map[cloud.AuthType]cloud.CredentialSchema{
		cloud.CertificateAuthType: {
			{
				Name: credAttrServerCert,
				CredentialAttr: cloud.CredentialAttr{
					Description:    "the path to the PEM-encoded LXD server certificate file",
					ExpandFilePath: true,
				},
			}, {
				Name: credAttrClientCert,
				CredentialAttr: cloud.CredentialAttr{
					Description:    "the path to the PEM-encoded LXD client certificate file",
					ExpandFilePath: true,
				},
			}, {
				Name: credAttrClientKey,
				CredentialAttr: cloud.CredentialAttr{
					Description:    "the path to the PEM-encoded LXD client key file",
					ExpandFilePath: true,
				},
			},
		},
		cloud.InteractiveAuthType: {
			{
				Name: credAttrTrustPassword,
				CredentialAttr: cloud.CredentialAttr{
					Description: "the LXD server trust password",
					Hidden:      true,
				},
			},
		},
	}
}
747592
func (c *Client) Credentials(tags ...names.CloudCredentialTag) ([]params.CloudCredentialResult, error) {
	if len(tags) == 0 {
		return []params.CloudCredentialResult{}, nil
	}
	var results params.CloudCredentialResults
	args := params.Entities{
		Entities: make([]params.Entity, len(tags)),
	}
	for i, tag := range tags {
		args.Entities[i].Tag = tag.String()
	}
	if err := c.facade.FacadeCall("Credential", args, &results); err != nil {
		return nil, errors.Trace(err)
	}
	return results.Results, nil
}
326555
func (EnvironProvider) DetectRegions() ([]cloud.Region, error) {
	// If OS_REGION_NAME and OS_AUTH_URL are both set,
	// return return a region using them.
	creds, err := identity.CredentialsFromEnv()
	if err != nil {
		return nil, errors.Errorf("failed to retrive cred from env : %v", err)
	}
	if creds.Region == "" {
		return nil, errors.NewNotFound(nil, "OS_REGION_NAME environment variable not set")
	}
	if creds.URL == "" {
		return nil, errors.NewNotFound(nil, "OS_AUTH_URL environment variable not set")
	}
	return []cloud.Region{{
		Name:     creds.Region,
		Endpoint: creds.URL,
	}}, nil
}
492925
func (environProviderCredentials) DetectCredentials() (*cloud.CloudCredential, error) {
	// MAAS stores credentials in a json file: ~/.maasrc
	// {"Server": "http://<ip>/MAAS", "OAuth": "<key>"}
	maasrc := filepath.Join(utils.Home(), ".maasrc")
	fileBytes, err := ioutil.ReadFile(maasrc)
	if os.IsNotExist(err) {
		return nil, errors.NotFoundf("maas credentials")
	}
	if err != nil {
		return nil, errors.Trace(err)
	}

	details := make(map[string]interface{})
	err = json.Unmarshal(fileBytes, &details)
	if err != nil {
		return nil, errors.Trace(err)
	}
	oauthKey := details["OAuth"]
	if oauthKey == "" {
		return nil, errors.New("MAAS credentials require a value for OAuth token")
	}
	cred := cloud.NewCredential(cloud.OAuth1AuthType, map[string]string{
		credAttrMAASOAuth: fmt.Sprintf("%v", oauthKey),
	})
	server, ok := details["Server"]
	if server == "" || !ok {
		server = "unspecified server"
	}
	cred.Label = fmt.Sprintf("MAAS credential for %s", server)

	return &cloud.CloudCredential{
		AuthCredentials: map[string]cloud.Credential{
			"default": cred,
		},
	}, nil
}
474027
func (p *environProvider) DetectClouds() ([]cloud.Cloud, error) {
	configPath := filepath.Join(utils.Home(), ".config", "lxc", "config.yml")
	config, err := p.lxcConfigReader.ReadConfig(configPath)
	if err != nil {
		logger.Errorf("unable to read/parse LXC config file: %s", err)
	}

	clouds := []cloud.Cloud{localhostCloud}
	for name, remote := range config.Remotes {
		if remote.Protocol == lxdnames.ProviderType {
			clouds = append(clouds, cloud.Cloud{
				Name:        name,
				Type:        lxdnames.ProviderType,
				Endpoint:    remote.Addr,
				Description: "LXD Cluster",
				AuthTypes: []cloud.AuthType{
					cloud.CertificateAuthType,
				},
				Regions: []cloud.Region{{
					Name:     lxdnames.DefaultRemoteRegion,
					Endpoint: remote.Addr,
				}},
			})
		}
	}

	return clouds, nil
}
99244
func (c *Client) UserCredentials(user names.UserTag, cloud names.CloudTag) ([]names.CloudCredentialTag, error) {
	var results params.StringsResults
	args := params.UserClouds{[]params.UserCloud{
		{UserTag: user.String(), CloudTag: cloud.String()},
	}}
	if err := c.facade.FacadeCall("UserCredentials", args, &results); err != nil {
		return nil, errors.Trace(err)
	}
	if len(results.Results) != 1 {
		return nil, errors.Errorf("expected 1 result, got %d", len(results.Results))
	}
	if results.Results[0].Error != nil {
		return nil, results.Results[0].Error
	}
	tags := make([]names.CloudCredentialTag, len(results.Results[0].Result))
	for i, s := range results.Results[0].Result {
		tag, err := names.ParseCloudCredentialTag(s)
		if err != nil {
			return nil, errors.Trace(err)
		}
		tags[i] = tag
	}
	return tags, 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
}
540683
func DetectDefaultStore(store string) string {
	platformDefault := defaultCredentialsStore()

	// user defined or no default for platform
	if store != "" || platformDefault == "" {
		return store
	}

	if _, err := exec.LookPath(remoteCredentialsPrefix + platformDefault); err == nil {
		return platformDefault
	}
	return ""
}
913787
func Credentials(user, pass string) Option {
	return func(c *clientConfig) error {
		if user == "" || pass == "" {
			return ErrInvalidCredentials
		}
		c.credentials = []byte(user + ":" + pass)
		return nil
	}
}
171863
func NewCredentialsClient(cfg aws.Config, handlers request.Handlers, endpoint string, options ...func(*Provider)) *credentials.Credentials {
	return credentials.NewCredentials(NewProviderClient(cfg, handlers, endpoint, options...))
}
393750
func getCredentials(client *http.Client, endpoint string) (ec2RoleCredRespBody, error) {

	// http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html
	u, err := getIAMRoleURL(endpoint)
	if err != nil {
		return ec2RoleCredRespBody{}, err
	}

	// http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html
	roleNames, err := listRoleNames(client, u)
	if err != nil {
		return ec2RoleCredRespBody{}, err
	}

	if len(roleNames) == 0 {
		return ec2RoleCredRespBody{}, errors.New("No IAM roles attached to this EC2 service")
	}

	// http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html
	// - An instance profile can contain only one IAM role. This limit cannot be increased.
	roleName := roleNames[0]

	// http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html
	// The following command retrieves the security credentials for an
	// IAM role named `s3access`.
	//
	//    $ curl http://169.254.169.254/latest/meta-data/iam/security-credentials/s3access
	//
	u.Path = path.Join(u.Path, roleName)
	req, err := http.NewRequest("GET", u.String(), nil)
	if err != nil {
		return ec2RoleCredRespBody{}, err
	}

	resp, err := client.Do(req)
	if err != nil {
		return ec2RoleCredRespBody{}, err
	}
	defer resp.Body.Close()
	if resp.StatusCode != http.StatusOK {
		return ec2RoleCredRespBody{}, errors.New(resp.Status)
	}

	respCreds := ec2RoleCredRespBody{}
	if err := json.NewDecoder(resp.Body).Decode(&respCreds); err != nil {
		return ec2RoleCredRespBody{}, err
	}

	if respCreds.Code != "Success" {
		// If an error code was returned something failed requesting the role.
		return ec2RoleCredRespBody{}, errors.New(respCreds.Message)
	}

	return respCreds, nil
}
848281
func GetCredentials() (string, string) {
	username := os.Getenv("CF_INT_USERNAME")
	if username == "" {
		username = "admin"
	}
	password := os.Getenv("CF_INT_PASSWORD")
	if password == "" {
		password = "admin"
	}
	return username, password
}
803887
func (st *State) CloudCredentials(user names.UserTag, cloudName string) (map[string]Credential, error) {
	coll, cleanup := st.db().GetCollection(cloudCredentialsC)
	defer cleanup()

	credentials := make(map[string]Credential)
	iter := coll.Find(bson.D{
		{"owner", user.Id()},
		{"cloud", cloudName},
	}).Iter()
	defer iter.Close()

	var doc cloudCredentialDoc
	for iter.Next(&doc) {
		tag, err := doc.cloudCredentialTag()
		if err != nil {
			return nil, errors.Trace(err)
		}
		credentials[tag.Id()] = Credential{doc}
	}
	if err := iter.Close(); err != nil {
		return nil, errors.Annotatef(
			err, "cannot get cloud credentials for user %q, cloud %q",
			user.Id(), cloudName,
		)
	}
	return credentials, nil
}