// ResolveCloudCredentialTag takes a string which is of either the format
// "<credential>" or "<user>/<credential>". If the string does not include
// a user, then the supplied user tag is implied.
517735
func ResolveCloudCredentialTag(user names.UserTag, cloud names.CloudTag, credentialName string) (names.CloudCredentialTag, error) {
	if i := strings.IndexRune(credentialName, '/'); i == -1 {
		credentialName = fmt.Sprintf("%s/%s", user.Id(), credentialName)
	}
	s := fmt.Sprintf("%s/%s", cloud.Id(), credentialName)
	if !names.IsValidCloudCredential(s) {
		return names.CloudCredentialTag{}, errors.NotValidf("cloud credential ID %q", s)
	}
	return names.NewCloudCredentialTag(s), nil
}
963554
func (c environProviderCredentials) FinalizeCredential(
	ctx environs.FinalizeCredentialContext,
	args environs.FinalizeCredentialParams,
) (*cloud.Credential, error) {
	switch authType := args.Credential.AuthType(); authType {
	case deviceCodeAuthType:
		subscriptionId := args.Credential.Attributes()[credAttrSubscriptionId]
		if subscriptionId != "" {
			// If a subscription ID was specified then fall
			// back to the interactive device login. attempt
			// to get subscription details from Azure CLI.
			graphResourceId := azureauth.TokenResource(args.CloudIdentityEndpoint)
			resourceManagerResourceId, err := azureauth.ResourceManagerResourceId(args.CloudStorageEndpoint)
			if err != nil {
				return nil, errors.Trace(err)
			}
			return c.deviceCodeCredential(ctx, args, azureauth.ServicePrincipalParams{
				GraphEndpoint:             args.CloudIdentityEndpoint,
				GraphResourceId:           graphResourceId,
				ResourceManagerEndpoint:   args.CloudEndpoint,
				ResourceManagerResourceId: resourceManagerResourceId,
				SubscriptionId:            subscriptionId,
			})
		}
		params, err := c.getServicePrincipalParams(args.CloudEndpoint)
		if err != nil {
			return nil, errors.Trace(err)
		}
		return c.azureCLICredential(ctx, args, params)
	case clientCredentialsAuthType:
		return &args.Credential, nil
	default:
		return nil, errors.NotSupportedf("%q auth-type", authType)
	}
}
864739
func (s cloudSpecAPI) GetCloudSpec(tag names.ModelTag) params.CloudSpecResult {
	var result params.CloudSpecResult
	spec, err := s.getCloudSpec(tag)
	if err != nil {
		result.Error = common.ServerError(err)
		return result
	}
	var paramsCloudCredential *params.CloudCredential
	if spec.Credential != nil && spec.Credential.AuthType() != "" {
		paramsCloudCredential = &params.CloudCredential{
			AuthType:   string(spec.Credential.AuthType()),
			Attributes: spec.Credential.Attributes(),
		}
	}
	result.Result = &params.CloudSpec{
		Type:             spec.Type,
		Name:             spec.Name,
		Region:           spec.Region,
		Endpoint:         spec.Endpoint,
		IdentityEndpoint: spec.IdentityEndpoint,
		StorageEndpoint:  spec.StorageEndpoint,
		Credential:       paramsCloudCredential,
		CACertificates:   spec.CACertificates,
	}
	return result
}
415349
func (f *Facade) ValidateCredentials(ctx datastore.Context, user userdomain.User) (bool, error) {
	defer ctx.Metrics().Stop(ctx.Metrics().Start("Facade.ValidateCredentials"))
	var err error
	logger := plog.WithField("userName", user.Name)
	logger.Debug("Started Facade.ValidateCredentials")
	defer logger.WithError(err).Debug("Finished Facade.ValidateCredentials")

	var storedUser userdomain.User
	storedUser, err = f.GetUser(ctx, user.Name)
	if err != nil {
		return false, err
	}

	// hash the passed in password
	hashedPassword := hashPassword(user.Password)

	// confirm the password
	if storedUser.Password != hashedPassword {
		return false, nil
	}

	// at this point we found the user and confirmed the password
	return true, 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
}
130833
func (p *PUPolicy) AddIdentityTag(k, v string) {
	p.Lock()
	defer p.Unlock()

	p.identity.AppendKeyValue(k, v)
}
1143791
func (st *State) InvalidateCloudCredential(tag names.CloudCredentialTag, reason string) error {
	buildTxn := func(attempt int) ([]txn.Op, error) {
		_, err := st.CloudCredential(tag)
		if err != nil {
			return nil, errors.Trace(err)
		}

		ops := []txn.Op{{
			C:      cloudCredentialsC,
			Id:     cloudCredentialDocID(tag),
			Assert: txn.DocExists,
			Update: bson.D{{"$set", bson.D{
				{"invalid", true},
				{"invalid-reason", reason},
			}}},
		}}
		return ops, nil
	}
	if err := st.db().Run(buildTxn); err != nil {
		return errors.Annotatef(err, "invalidating cloud credential %v", tag.Id())
	}
	return nil
}
712652
func tagUserCredentials(conf agent.Config) (string, string, error) {
	username := conf.Tag().String()
	var password string
	// TODO(perrito) we might need an accessor for the actual state password
	// just in case it ever changes from the same as api password.
	apiInfo, ok := conf.APIInfo()
	if ok {
		password = apiInfo.Password
	} else {
		// There seems to be no way to reach this inconsistence other than making a
		// backup on a machine where these fields are corrupted and even so I find
		// no reasonable way to reach this state, yet since APIInfo has it as a
		// possibility I prefer to handle it, we cannot recover from this since
		// it would mean that the agent.conf is corrupted.
		return "", "", errors.New("cannot obtain password to access the controller")
	}
	return username, password, nil
}
913787
func Credentials(user, pass string) Option {
	return func(c *clientConfig) error {
		if user == "" || pass == "" {
			return ErrInvalidCredentials
		}
		c.credentials = []byte(user + ":" + pass)
		return nil
	}
}
1318213
func (st *State) RemoveCloudAccess(cloud string, user names.UserTag) error {
	buildTxn := func(int) ([]txn.Op, error) {
		_, err := st.GetCloudAccess(cloud, user)
		if err != nil {
			return nil, err
		}
		ops := []txn.Op{removePermissionOp(cloudGlobalKey(cloud), userGlobalKey(userAccessID(user)))}
		return ops, nil
	}

	err := st.db().Run(buildTxn)
	return errors.Trace(err)
}
119861
func RegisterCredentials(provider environs.EnvironProvider, args RegisterCredentialsParams) (map[string]*cloud.CloudCredential, error) {
	if register, ok := provider.(environs.ProviderCredentialsRegister); ok {
		found, err := register.RegisterCredentials(args.Cloud)
		if err != nil {
			return nil, errors.Annotatef(
				err, "registering credentials for provider",
			)
		}
		logger.Tracef("provider registered credentials: %v", found)
		if len(found) == 0 {
			return nil, errors.NotFoundf("credentials for provider")
		}
		return found, errors.Trace(err)
	}
	return nil, nil
}
783700
func (c *MemStore) CredentialForCloud(cloudName string) (*cloud.CloudCredential, error) {
	c.mu.Lock()
	defer c.mu.Unlock()

	if result, ok := c.Credentials[cloudName]; ok {
		return &result, nil
	}
	return nil, errors.NotFoundf("credentials for cloud %s", cloudName)
}
1221118
func (c *bootstrapCommand) credentialsAndRegionName(
	ctx *cmd.Context,
	provider environs.EnvironProvider,
	cloud jujucloud.Cloud,
) (
	creds bootstrapCredentials,
	regionName string,
	err error,
) {

	store := c.ClientStore()

	// When looking for credentials, we should attempt to see if there are any
	// credentials that should be registered, before we get or detect them
	err = common.RegisterCredentials(ctx, store, provider, modelcmd.RegisterCredentialsParams{
		Cloud: cloud,
	})
	if err != nil {
		logger.Errorf("registering credentials errored %s", err)
	}

	var detected bool
	creds.credential, creds.name, regionName, detected, err = common.GetOrDetectCredential(
		ctx, store, provider, modelcmd.GetCredentialsParams{
			Cloud:          cloud,
			CloudRegion:    c.Region,
			CredentialName: c.CredentialName,
		},
	)
	switch errors.Cause(err) {
	case nil:
	case modelcmd.ErrMultipleCredentials:
		return bootstrapCredentials{}, "", ambiguousCredentialError
	case common.ErrMultipleDetectedCredentials:
		return bootstrapCredentials{}, "", ambiguousDetectedCredentialError
	default:
		return bootstrapCredentials{}, "", errors.Trace(err)
	}
	logger.Debugf(
		"authenticating with region %q and credential %q (%v)",
		regionName, creds.name, creds.credential.Label,
	)
	if detected {
		creds.detectedName = creds.name
		creds.name = ""
	}
	logger.Tracef("credential: %v", creds.credential)
	return creds, regionName, nil
}
351368
func (c *TagCache) ResolveTag(ctx context.Context, pkg, tag string) (pin common.Pin, err error) {
	if err = common.ValidatePackageName(pkg); err != nil {
		return
	}
	if err = common.ValidateInstanceTag(tag); err != nil {
		return
	}

	c.lock.Lock()
	defer c.lock.Unlock()

	// Already added with AddTag recently?
	if e := c.addedTags[makeTagKey(pkg, tag)]; e != nil {
		return common.Pin{
			PackageName: e.Package,
			InstanceID:  e.InstanceId,
		}, nil
	}

	if err = c.lazyLoadLocked(ctx); err != nil {
		return
	}

	// Most recently used tags are usually at the end, search in reverse as a
	// silly optimization.
	for i := len(c.cache.Entries) - 1; i >= 0; i-- {
		e := c.cache.Entries[i]
		if e.Package == pkg && e.Tag == tag {
			return common.Pin{
				PackageName: pkg,
				InstanceID:  e.InstanceId,
			}, nil
		}
	}

	return
}
682318
func (secretCredentialManager *SecretCredentialManager) GetCredential(server string) (*Credential, error) {
	err := secretCredentialManager.updateCredentialsMap()
	if err != nil {
		statusErr, ok := err.(*apierrors.StatusError)
		if (ok && statusErr.ErrStatus.Code != http.StatusNotFound) || !ok {
			return nil, err
		}
		// Handle secrets deletion by finding credentials from cache
		klog.Warningf("secret %q not found in namespace %q", secretCredentialManager.SecretName, secretCredentialManager.SecretNamespace)
	}

	credential, found := secretCredentialManager.Cache.GetCredential(server)
	if !found {
		klog.Errorf("credentials not found for server %q", server)
		return nil, ErrCredentialsNotFound
	}
	return &credential, nil
}
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
}
685241
func (_m *ClientInterface) ValidateCredentials(_a0 user.User) (bool, error) {
	ret := _m.Called(_a0)

	var r0 bool
	if rf, ok := ret.Get(0).(func(user.User) bool); ok {
		r0 = rf(_a0)
	} else {
		r0 = ret.Get(0).(bool)
	}

	var r1 error
	if rf, ok := ret.Get(1).(func(user.User) error); ok {
		r1 = rf(_a0)
	} else {
		r1 = ret.Error(1)
	}

	return r0, r1
}