// ValidateExistingModelCredential checks if the cloud credential that a given model uses is valid for it.
11598
func ValidateExistingModelCredential(backend PersistentBackend, callCtx context.ProviderCallContext) (params.ErrorResults, error) {
	model, err := backend.Model()
	if err != nil {
		return params.ErrorResults{}, errors.Trace(err)
	}

	credentialTag, isSet := model.CloudCredential()
	if !isSet {
		return params.ErrorResults{}, nil
	}

	storedCredential, err := backend.CloudCredential(credentialTag)
	if err != nil {
		return params.ErrorResults{}, errors.Trace(err)
	}

	if !storedCredential.IsValid() {
		return params.ErrorResults{}, errors.NotValidf("credential %q", storedCredential.Name)
	}
	credential := cloud.NewCredential(cloud.AuthType(storedCredential.AuthType), storedCredential.Attributes)
	return ValidateNewModelCredential(backend, callCtx, credentialTag, &credential)
}
1258229
func (arc *ConfigFactory) IsKeyExist(key string) bool {
	if arc.initSuccess == false {
		return false
	}

	return arc.configMgr.IsKeyExist(key)
}
710070
func (a *UnitAgent) validateMigration(apiCaller base.APICaller) error {
	// TODO(mjs) - more extensive checks to come.
	unitTag := names.NewUnitTag(a.UnitName)
	facade := uniter.NewState(apiCaller, unitTag)
	_, err := facade.Unit(unitTag)
	if err != nil {
		return errors.Trace(err)
	}
	model, err := facade.Model()
	if err != nil {
		return errors.Trace(err)
	}
	curModelUUID := a.CurrentConfig().Model().Id()
	newModelUUID := model.UUID
	if newModelUUID != curModelUUID {
		return errors.Errorf("model mismatch when validating: got %q, expected %q",
			newModelUUID, curModelUUID)
	}
	return nil
}
254727
func MaybeHandleCredentialError(isAuthError func(error) bool, err error, ctx context.ProviderCallContext) bool {
	denied := isAuthError(errors.Cause(err))
	if ctx != nil && denied {
		invalidateErr := ctx.InvalidateCredential("cloud denied access")
		if invalidateErr != nil {
			logger.Warningf("could not invalidate stored cloud credential on the controller: %v", invalidateErr)
		}
	}
	return denied
}
268702
func IsModelMigratedError(err error) bool {
	_, ok := errors.Cause(err).(modelMigratedError)
	return ok
}
495915
func (st *State) CredentialModelsAndOwnerAccess(tag names.CloudCredentialTag) ([]CredentialOwnerModelAccess, error) {
	models, err := st.CredentialModels(tag)
	if err != nil {
		return nil, errors.Trace(err)
	}

	var results []CredentialOwnerModelAccess
	for uuid, name := range models {
		ownerAccess, err := st.UserAccess(tag.Owner(), names.NewModelTag(uuid))
		if err != nil {
			if errors.IsNotFound(err) {
				results = append(results, CredentialOwnerModelAccess{ModelName: name, ModelUUID: uuid, OwnerAccess: permission.NoAccess})
				continue
			}
			results = append(results, CredentialOwnerModelAccess{ModelName: name, ModelUUID: uuid, Error: errors.Trace(err)})
			continue
		}
		results = append(results, CredentialOwnerModelAccess{ModelName: name, ModelUUID: uuid, OwnerAccess: ownerAccess.Access})
	}
	return results, nil
}
72095
func (a *authenticator) validateCredentials(credentials *credentials) (string, int, error) {
	user, err := a.userDb.GetUser(credentials.Username)
	if err != nil {
		return "", http.StatusUnauthorized, errors.Errorf("401 unauthorized: user name or password is incorrect")
	}
	if err := bcrypt.CompareHashAndPassword([]byte(user.PasswordHash), []byte(credentials.Password)); err != nil {
		return credentials.Username, http.StatusUnauthorized, fmt.Errorf("401 unauthorized: user name or password is incorrect")
	}
	return credentials.Username, 0, nil
}
279210
func (st *State) ModelExists(uuid string) (bool, error) {
	models, closer := st.db().GetCollection(modelsC)
	defer closer()

	count, err := models.FindId(uuid).Count()
	if err != nil {
		return false, errors.Annotate(err, "querying model")
	}
	return count > 0, nil
}
622001
func (d *DNSProvider) FindExistingRecordID(zone, recordName string) (int64, error) {
	ctx := context.Background()
	records, err := d.client.GetRecords(ctx, zone)
	if err != nil {
		return -1, errors.New("Error while retrievening DNS records: " + err.Error())
	}
	for _, record := range records {
		if record.Name == recordName {
			return record.ID, nil
		}
	}
	return 0, nil
}
540592
func checkModelEntityRefsNoPersistentStorage(
	db Database, doc *modelEntityRefsDoc,
) ([]txn.Op, error) {
	for _, volumeId := range doc.Volumes {
		volumeTag := names.NewVolumeTag(volumeId)
		detachable, err := isDetachableVolumeTag(db, volumeTag)
		if err != nil {
			return nil, errors.Trace(err)
		}
		if detachable {
			return nil, hasPersistentStorageError{}
		}
	}
	for _, filesystemId := range doc.Filesystems {
		filesystemTag := names.NewFilesystemTag(filesystemId)
		detachable, err := isDetachableFilesystemTag(db, filesystemTag)
		if err != nil {
			return nil, errors.Trace(err)
		}
		if detachable {
			return nil, hasPersistentStorageError{}
		}
	}
	return noNewStorageModelEntityRefs(doc), nil
}
1274156
func MaybeInvalidateCredential(err error, ctx context.ProviderCallContext) bool {
	if ctx == nil {
		return false
	}
	if !hasDenialStatusCode(err) {
		return false
	}

	invalidateErr := ctx.InvalidateCredential("azure cloud denied access")
	if invalidateErr != nil {
		logger.Warningf("could not invalidate stored azure cloud credential on the controller: %v", invalidateErr)
	}
	return true
}
212722
func (b *backend) WatchModelCredential() (state.NotifyWatcher, error) {
	m, err := b.Model()
	if err != nil {
		return nil, errors.Trace(err)
	}
	return m.WatchModelCredential(), nil
}
823103
func (m *GormIdentityRepository) IsValid(ctx context.Context, id uuid.UUID) bool {
	return m.CheckExists(ctx, id) == nil
}
1326485
func (p environProviderCredentials) ShouldFinalizeCredential(cred cloud.Credential) bool {
	// The credential is fully formed, so we assume the client
	// certificate is uploaded to the server already.
	credAttrs := cred.Attributes()
	_, ok := credAttrs[credAttrServerCert]
	return !ok
}
224246
func (c *Cloud) InstanceExistsByProviderID(ctx context.Context, providerID string) (bool, error) {
	instanceID, err := KubernetesInstanceID(providerID).MapToAWSInstanceID()
	if err != nil {
		return false, err
	}

	request := &ec2.DescribeInstancesInput{
		InstanceIds: []*string{instanceID.awsString()},
	}

	instances, err := c.ec2.DescribeInstances(request)
	if err != nil {
		return false, err
	}
	if len(instances) == 0 {
		return false, nil
	}
	if len(instances) > 1 {
		return false, fmt.Errorf("multiple instances found for instance: %s", instanceID)
	}

	state := instances[0].State.Name
	if *state == ec2.InstanceStateNameTerminated {
		klog.Warningf("the instance %s is terminated", instanceID)
		return false, nil
	}

	return true, nil
}
381743
func (api *CloudAPIV2) RevokeCredentials(args params.Entities) (params.ErrorResults, error) {
	results := params.ErrorResults{
		Results: make([]params.ErrorResult, len(args.Entities)),
	}
	authFunc, err := api.getCredentialsAuthFunc()
	if err != nil {
		return results, err
	}
	for i, arg := range args.Entities {
		tag, err := names.ParseCloudCredentialTag(arg.Tag)
		if err != nil {
			results.Results[i].Error = common.ServerError(err)
			continue
		}
		// NOTE(axw) if we add ACLs for cloud credentials, we'll need
		// to change this auth check.
		if !authFunc(tag.Owner()) {
			results.Results[i].Error = common.ServerError(common.ErrPerm)
			continue
		}

		models, err := api.credentialModels(tag)
		if err != nil {
			logger.Warningf("could not get models that use credential %v: %v", tag, err)
		}
		if len(models) > 0 {
			// For backward compatibility, we must proceed here regardless of whether the credential is used by any models,
			// but, at least, let's log it.
			logger.Warningf("credential %v will be deleted but it is still used by model%v", tag, modelsPretty(models))
		}

		if err := api.backend.RemoveCloudCredential(tag); err != nil {
			results.Results[i].Error = common.ServerError(err)
		}
	}
	return results, nil
}
101496
func ValidateModelName(name string) error {
	modelName, _, err := SplitModelName(name)
	if err != nil {
		return errors.Annotatef(err, "validating model name %q", name)
	}
	if !names.IsValidModelName(modelName) {
		return errors.NotValidf("model name %q", name)
	}
	return nil
}