// RevokeCredentialsCheckModels revokes a set of cloud credentials.
// If the credentials are used by any of the models, the credential deletion will be aborted.
// If credential-in-use needs to be revoked nonetheless, this method allows the use of force.
186713
func (api *CloudAPI) RevokeCredentialsCheckModels(args params.RevokeCredentialArgs) (params.ErrorResults, error) {
	// TODO (anastasiamac 2018-11-13) the behavior here needs to be changed to performed promised models checks and authorise use of force.
	results := params.ErrorResults{
		Results: make([]params.ErrorResult, len(args.Credentials)),
	}
	authFunc, err := api.getCredentialsAuthFunc()
	if err != nil {
		return results, err
	}

	opMessage := func(force bool) string {
		if force {
			return "will be deleted but"
		}
		return "cannot be deleted as"
	}

	for i, arg := range args.Credentials {
		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 {
			if !arg.Force {
				// Could not determine if credential has models - do not continue updating this credential...
				results.Results[i].Error = common.ServerError(err)
				continue
			}
			logger.Warningf("could not get models that use credential %v: %v", tag, err)
		}
		if len(models) != 0 {
			logger.Warningf("credential %v %v it is used by model%v",
				tag,
				opMessage(arg.Force),
				modelsPretty(models),
			)
			if !arg.Force {
				// Some models still use this credential - do not delete this credential...
				results.Results[i].Error = common.ServerError(errors.Errorf("cannot delete credential %v: it is still used by %d model%v", tag, len(models), plural(len(models))))
				continue
			}
		}

		if err := api.backend.RemoveCloudCredential(tag); err != nil {
			results.Results[i].Error = common.ServerError(err)
		}
	}
	return results, nil
}
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
}
403791
func (cert *Certificate) Revoke(tx *sql.Tx, mechanism, reason string, when int64) error {
	if err := cert.Select(tx); err != nil {
		return err
	}

	rev := &Revocation{
		SKI:       cert.SKI,
		RevokedAt: when,
		Mechanism: mechanism,
		Reason:    reason,
	}

	// We ignore the inserted value because if it returns false, that means
	// the certificate has already been revoked.
	_, err := Ensure(rev, tx)
	return err
}
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
}
1222765
func (api *API) CheckMachines(args params.ModelArgs) (params.ErrorResults, error) {
	tag, err := names.ParseModelTag(args.ModelTag)
	if err != nil {
		return params.ErrorResults{}, errors.Trace(err)
	}
	st, err := api.pool.Get(tag.Id())
	if err != nil {
		return params.ErrorResults{}, errors.Trace(err)
	}
	defer st.Release()

	return credentialcommon.ValidateExistingModelCredential(
		credentialcommon.NewPersistentBackend(st.State),
		api.callContext,
	)
}
1153115
func (c *fabricCAAdapter) Revoke(key core.Key, cert []byte, request *api.RevocationRequest) (*api.RevocationResponse, error) {
	// Create revocation request
	var req = caapi.RevocationRequest{
		CAName: request.CAName,
		Name:   request.Name,
		Serial: request.Serial,
		AKI:    request.AKI,
		Reason: request.Reason,
	}

	registrar, err := c.newIdentity(key, cert)
	if err != nil {
		return nil, errors.Wrap(err, "failed to create CA signing identity")
	}

	resp, err := registrar.Revoke(&req)
	if err != nil {
		return nil, errors.Wrap(err, "failed to revoke")
	}
	var revokedCerts []api.RevokedCert
	for i := range resp.RevokedCerts {
		revokedCerts = append(
			revokedCerts,
			api.RevokedCert{
				Serial: resp.RevokedCerts[i].Serial,
				AKI:    resp.RevokedCerts[i].AKI,
			})
	}

	return &api.RevocationResponse{
		RevokedCerts: revokedCerts,
		CRL:          resp.CRL,
	}, nil
}
345349
func (u *user) RevokeAccess(ctx context.Context, db Database) error {
	if err := u.SetDatabaseAccess(ctx, db, GrantNone); err != nil {
		return WithStack(err)
	}
	return nil
}
1266728
func (c *Facade) WatchModelCredential() (watcher.NotifyWatcher, error) {
	if v := c.facade.BestAPIVersion(); v < 2 {
		return nil, errors.NotSupportedf("WatchModelCredential on CredentialValidator v%v", v)
	}
	var result params.NotifyWatchResult
	err := c.facade.FacadeCall("WatchModelCredential", nil, &result)
	if err != nil {
		return nil, errors.Trace(err)
	}

	if err := result.Error; err != nil {
		return nil, errors.Trace(err)
	}
	w := apiwatcher.NewNotifyWatcher(c.facade.RawAPICaller(), result)
	return w, nil
}
481005
func (s *service) AskUserServiceToCheckCredentials(username string, password string, method string) (rest.ResponseDTOUserInfo, *apihelper.ApiErrors) {

	requestBody := rest.RequestDTOUserCredentials{
		Username: username,
		Password: password,
		Method:   method,
	}

	b := new(bytes.Buffer)
	json.NewEncoder(b).Encode(requestBody)

	// call api
	req, err := http.NewRequest("POST", privateBaseUrl+"/user/check-credentials", b)
	req.Header.Set("Authorization", "Bearer YYY")

	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		panic(err)
	}
	defer resp.Body.Close()

	// read response
	body, _ := ioutil.ReadAll(resp.Body)

	userInfo := rest.ResponseDTOUserInfo{}
	apiErrors := apihelper.ApiErrors{}
	json.Unmarshal(body, &userInfo)
	json.Unmarshal(body, &apiErrors)

	if len(apiErrors.Errors) == 0 {
		return userInfo, nil
	}
	return rest.ResponseDTOUserInfo{}, &apiErrors
}
1304370
func (m *ModelManagerAPI) ChangeModelCredential(args params.ChangeModelCredentialsParams) (params.ErrorResults, error) {
	if err := m.check.ChangeAllowed(); err != nil {
		return params.ErrorResults{}, errors.Trace(err)
	}

	controllerAdmin, err := m.authorizer.HasPermission(permission.SuperuserAccess, m.state.ControllerTag())
	if err != nil {
		return params.ErrorResults{}, errors.Trace(err)
	}
	// Only controller or model admin can change cloud credential on a model.
	checkModelAccess := func(tag names.ModelTag) error {
		if controllerAdmin {
			return nil
		}
		modelAdmin, err := m.authorizer.HasPermission(permission.AdminAccess, tag)
		if err != nil {
			return errors.Trace(err)
		}
		if modelAdmin {
			return nil
		}
		return common.ErrPerm
	}

	replaceModelCredential := func(arg params.ChangeModelCredentialParams) error {
		modelTag, err := names.ParseModelTag(arg.ModelTag)
		if err != nil {
			return errors.Trace(err)
		}
		if err := checkModelAccess(modelTag); err != nil {
			return errors.Trace(err)
		}
		credentialTag, err := names.ParseCloudCredentialTag(arg.CloudCredentialTag)
		if err != nil {
			return errors.Trace(err)
		}
		model, releaser, err := m.state.GetModel(modelTag.Id())
		if err != nil {
			return errors.Trace(err)
		}
		defer releaser()

		updated, err := model.SetCloudCredential(credentialTag)
		if err != nil {
			return errors.Trace(err)
		}
		if !updated {
			return errors.Errorf("model %v already uses credential %v", modelTag.Id(), credentialTag.Id())
		}
		return nil
	}

	results := make([]params.ErrorResult, len(args.Models))
	for i, arg := range args.Models {
		if err := replaceModelCredential(arg); err != nil {
			results[i].Error = common.ServerError(err)
		}
	}
	return params.ErrorResults{results}, nil
}
962542
func (m *Model) ValidateCloudCredential(tag names.CloudCredentialTag, credential cloud.Credential) error {
	cloud, err := m.st.Cloud(m.Cloud())
	if err != nil {
		return errors.Annotatef(err, "getting cloud %q", m.Cloud())
	}

	err = validateCredentialForCloud(cloud, tag, convertCloudCredentialToState(tag, credential))
	if err != nil {
		return errors.Annotatef(err, "validating credential %q for cloud %q", tag.Id(), cloud.Name)
	}
	return nil
}
692133
func (client *Client) RevokeSecurityGroup(args *RevokeSecurityGroupArgs) error {
	response := RevokeSecurityGroupResponse{}
	err := client.Invoke("RevokeSecurityGroup", args, &response)
	return err
}
1072383
func OutputUpdateCredentialModelResult(ctx *cmd.Context, models []params.UpdateCredentialModelResult, showValid bool) {
	var valid []string
	invalid := map[string][]error{}
	for _, m := range models {
		if len(m.Errors) == 0 {
			valid = append(valid, m.ModelName)
			continue
		} else {
			var mError []error
			for _, anErr := range m.Errors {
				mError = append(mError, errors.Trace(anErr.Error))
			}
			invalid[m.ModelName] = mError
		}
	}

	if showValid && len(valid) > 0 {
		ctx.Infof("Credential valid for:")
		for _, v := range valid {
			ctx.Infof("  %v", v)
		}
	}
	if len(invalid) > 0 {
		// ensure we sort the valid, invalid slices so that the output is consistent
		i := 0
		names := make([]string, len(invalid))
		for k := range invalid {
			names[i] = k
			i++
		}
		sort.Strings(names)

		ctx.Infof("Credential invalid for:")
		for _, v := range names {
			ctx.Infof("  %v:", v)
			for _, e := range invalid[v] {
				ctx.Infof("    %v", e)
			}
		}
	}
}
641129
func (c *Client) UpdateCredentialsCheckModels(tag names.CloudCredentialTag, credential jujucloud.Credential) ([]params.UpdateCredentialModelResult, error) {
	in := params.UpdateCredentialArgs{
		Credentials: []params.TaggedCredential{{
			Tag: tag.String(),
			Credential: params.CloudCredential{
				AuthType:   string(credential.AuthType()),
				Attributes: credential.Attributes(),
			},
		}},
	}

	if c.facade.BestAPIVersion() < 3 {
		var out params.ErrorResults
		if err := c.facade.FacadeCall("UpdateCredentials", in, &out); err != nil {
			return nil, errors.Trace(err)
		}
		if len(out.Results) != 1 {
			return nil, errors.Errorf("expected 1 result for when updating credential %q, got %d", tag.Name(), len(out.Results))
		}
		if out.Results[0].Error != nil {
			return nil, errors.Trace(out.Results[0].Error)
		}
		return nil, nil
	}

	var out params.UpdateCredentialResults
	if err := c.facade.FacadeCall("UpdateCredentialsCheckModels", in, &out); err != nil {
		return nil, errors.Trace(err)
	}
	if len(out.Results) != 1 {
		return nil, errors.Errorf("expected 1 result for when updating credential %q, got %d", tag.Name(), len(out.Results))
	}
	if out.Results[0].Error != nil {
		// Unlike many other places, we want to return something valid here to provide more details.
		return out.Results[0].Models, errors.Trace(out.Results[0].Error)
	}
	return out.Results[0].Models, nil
}
420833
func (c *Client) RevokeModel(user, access string, modelUUIDs ...string) error {
	return c.modifyModelUser(params.RevokeModelAccess, user, access, modelUUIDs)
}
512346
func (c *Collection) checkModelType(model Model) error {
	return c.spec.checkModelType(model)
}
932408
func (c *Client) ChangeModelCredential(model names.ModelTag, credential names.CloudCredentialTag) error {
	if bestVer := c.BestAPIVersion(); bestVer < 5 {
		return errors.NotImplementedf("ChangeModelCredential in version %v", bestVer)
	}

	var out params.ErrorResults
	in := params.ChangeModelCredentialsParams{
		[]params.ChangeModelCredentialParams{
			{ModelTag: model.String(), CloudCredentialTag: credential.String()},
		},
	}

	err := c.facade.FacadeCall("ChangeModelCredential", in, &out)
	if err != nil {
		return errors.Trace(err)
	}
	return out.OneError()
}