// NewCredentialValidatorAPI creates a new CredentialValidator API endpoint on server-side.
336091
func NewCredentialValidatorAPI(ctx facade.Context) (*CredentialValidatorAPI, error) {
	return internalNewCredentialValidatorAPI(NewBackend(NewStateShim(ctx.State())), ctx.Resources(), ctx.Auth())
}
522976
func (c *Client) AddCredential(tag string, credential jujucloud.Credential) error {
	if bestVer := c.BestAPIVersion(); bestVer < 2 {
		return errors.NotImplementedf("AddCredential() (need v2+, have v%d)", bestVer)
	}
	var results params.ErrorResults
	cloudCredential := params.CloudCredential{
		AuthType:   string(credential.AuthType()),
		Attributes: credential.Attributes(),
	}
	args := params.TaggedCredentials{
		Credentials: []params.TaggedCredential{{
			Tag:        tag,
			Credential: cloudCredential,
		},
		}}
	if err := c.facade.FacadeCall("AddCredentials", args, &results); err != nil {
		return errors.Trace(err)
	}
	return results.OneError()
}
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
}
1040331
func (c *Core) newCredentialBackend(ctx context.Context, entry *MountEntry, sysView logical.SystemView, view logical.Storage) (logical.Backend, error) {
	t := entry.Type
	if alias, ok := credentialAliases[t]; ok {
		t = alias
	}

	f, ok := c.credentialBackends[t]
	if !ok {
		f = plugin.Factory
	}

	// Set up conf to pass in plugin_name
	conf := make(map[string]string, len(entry.Options)+1)
	for k, v := range entry.Options {
		conf[k] = v
	}

	switch {
	case entry.Type == "plugin":
		conf["plugin_name"] = entry.Config.PluginName
	default:
		conf["plugin_name"] = t
	}

	conf["plugin_type"] = consts.PluginTypeCredential.String()

	authLogger := c.baseLogger.Named(fmt.Sprintf("auth.%s.%s", t, entry.Accessor))
	c.AddLogger(authLogger)
	config := &logical.BackendConfig{
		StorageView: view,
		Logger:      authLogger,
		Config:      conf,
		System:      sysView,
		BackendUUID: entry.BackendAwareUUID,
	}

	b, err := f(ctx, config)
	if err != nil {
		return nil, err
	}

	return b, nil
}
1283433
func NewClientCredentialsConfig(clientID string, clientSecret string, tenantID string) ClientCredentialsConfig {
	return ClientCredentialsConfig{
		ClientID:     clientID,
		ClientSecret: clientSecret,
		TenantID:     tenantID,
		Resource:     azure.PublicCloud.ResourceManagerEndpoint,
		AADEndpoint:  azure.PublicCloud.ActiveDirectoryEndpoint,
	}
}
764289
func NewAPI(spec *loads.Document) *API {
	var an *analysis.Spec
	if spec != nil && spec.Spec() != nil {
		an = analysis.New(spec.Spec())
	}
	api := &API{
		spec:           spec,
		analyzer:       an,
		consumers:      make(map[string]runtime.Consumer, 10),
		producers:      make(map[string]runtime.Producer, 10),
		authenticators: make(map[string]runtime.Authenticator),
		operations:     make(map[string]map[string]runtime.OperationHandler),
		ServeError:     errors.ServeError,
		Models:         make(map[string]func() interface{}),
		formats:        strfmt.NewFormats(),
	}
	return api.WithJSONDefaults()
}
575986
func CredentialNotValidf(err error, message string) error {
	wrapped := errors.Wrapf(err, &credentialNotValid{err}, message)
	wrapped.(*errors.Err).SetLocation(1)
	return wrapped
}
373042
func NewFacade(apiCaller base.APICaller) (Facade, error) {
	facade := credentialvalidator.NewFacade(apiCaller)
	return facade, nil
}
311154
func CreateCredentials(accessKey, secretKey string) (cred Credentials, err error) {
	if !IsAccessKeyValid(accessKey) {
		return cred, ErrInvalidAccessKeyLength
	}
	if !IsSecretKeyValid(secretKey) {
		return cred, ErrInvalidSecretKeyLength
	}
	cred.AccessKey = accessKey
	cred.SecretKey = secretKey
	cred.Expiration = timeSentinel
	cred.Status = "enabled"
	return cred, nil
}
343580
func NewAPI(
	apiCaller base.APICaller,
	claimant names.MachineTag,
	entity names.Tag,
) (*API, error) {
	if !names.IsValidMachine(claimant.Id()) {
		return nil, errors.NotValidf("claimant tag")
	}
	switch entity.(type) {
	case names.ModelTag:
	case names.ControllerTag:
	case nil:
		return nil, errors.New("nil entity supplied")
	default:
		return nil, errors.Errorf(
			"invalid entity kind %q for singular API", entity.Kind(),
		)
	}
	facadeCaller := base.NewFacadeCaller(apiCaller, "Singular")
	return &API{
		facadeCaller: facadeCaller,
		claimant:     claimant,
		entity:       entity,
	}, 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)
}
546640
func NewAPIKeyAuthorizer(headers map[string]interface{}, queryParameters map[string]interface{}) *APIKeyAuthorizer {
	return &APIKeyAuthorizer{headers: headers, queryParameters: queryParameters}
}
1151461
func (api *CloudAPI) Credential(args params.Entities) (params.CloudCredentialResults, error) {
	results := params.CloudCredentialResults{
		Results: make([]params.CloudCredentialResult, len(args.Entities)),
	}
	authFunc, err := api.getCredentialsAuthFunc()
	if err != nil {
		return results, err
	}

	for i, arg := range args.Entities {
		credentialTag, err := names.ParseCloudCredentialTag(arg.Tag)
		if err != nil {
			results.Results[i].Error = common.ServerError(err)
			continue
		}
		if !authFunc(credentialTag.Owner()) {
			results.Results[i].Error = common.ServerError(common.ErrPerm)
			continue
		}

		// Helper to look up and cache credential schemas for clouds.
		schemaCache := make(map[string]map[cloud.AuthType]cloud.CredentialSchema)
		credentialSchemas := func() (map[cloud.AuthType]cloud.CredentialSchema, error) {
			cloudName := credentialTag.Cloud().Id()
			if s, ok := schemaCache[cloudName]; ok {
				return s, nil
			}
			aCloud, err := api.backend.Cloud(cloudName)
			if err != nil {
				return nil, err
			}
			provider, err := environs.Provider(aCloud.Type)
			if err != nil {
				return nil, err
			}
			schema := provider.CredentialSchemas()
			schemaCache[cloudName] = schema
			return schema, nil
		}
		cloudCredentials, err := api.backend.CloudCredentials(credentialTag.Owner(), credentialTag.Cloud().Id())
		if err != nil {
			results.Results[i].Error = common.ServerError(err)
			continue
		}

		cred, ok := cloudCredentials[credentialTag.Id()]
		if !ok {
			results.Results[i].Error = common.ServerError(errors.NotFoundf("credential %q", credentialTag.Name()))
			continue
		}

		schemas, err := credentialSchemas()
		if err != nil {
			results.Results[i].Error = common.ServerError(err)
			continue
		}

		attrs := cred.Attributes
		var redacted []string
		// Mask out the secrets.
		if s, ok := schemas[cloud.AuthType(cred.AuthType)]; ok {
			for _, attr := range s {
				if attr.Hidden {
					delete(attrs, attr.Name)
					redacted = append(redacted, attr.Name)
				}
			}
		}
		results.Results[i].Result = &params.CloudCredential{
			AuthType:   cred.AuthType,
			Attributes: attrs,
			Redacted:   redacted,
		}
	}
	return results, nil
}
26269
func OAuth2ClientCredentials(clientID, clientSecret, tokenURL string) registry.Option {
	return func(o *registry.Options) {
		c := clientcredentials.Config{
			ClientID:     clientID,
			ClientSecret: clientSecret,
			TokenURL:     tokenURL,
		}

		o.Context = context.WithValue(o.Context, contextHttpClient{}, newOAuthClient(c))
	}
}
1027813
func (p environProviderCredentials) FinalizeCredential(
	ctx environs.FinalizeCredentialContext,
	args environs.FinalizeCredentialParams,
) (*cloud.Credential, error) {
	switch authType := args.Credential.AuthType(); authType {
	case cloud.InteractiveAuthType:
		credAttrs := args.Credential.Attributes()
		// We don't care if the password is empty, just that it exists. Empty
		// passwords can be valid ones...
		if _, ok := credAttrs[credAttrTrustPassword]; ok {
			// check to see if the client cert, keys exist, if they do not,
			// generate them for the user.
			if _, ok := getClientCertificates(args.Credential); !ok {
				stderr := ctx.GetStderr()
				nopLogf := func(s string, args ...interface{}) {
					fmt.Fprintf(stderr, s+"\n", args...)
				}
				clientCert, clientKey, err := p.readOrGenerateCert(nopLogf)
				if err != nil {
					return nil, err
				}

				credAttrs[credAttrClientCert] = string(clientCert)
				credAttrs[credAttrClientKey] = string(clientKey)

				credential := cloud.NewCredential(cloud.CertificateAuthType, credAttrs)
				credential.Label = args.Credential.Label

				args.Credential = credential
			}
		}
		fallthrough
	case cloud.CertificateAuthType:
		return p.finalizeCredential(ctx, args)
	default:
		return &args.Credential, nil
	}
}
833081
func newLegacyServiceAccountAuthenticator(keyfiles []string, lookup bool, apiAudiences authenticator.Audiences, serviceAccountGetter serviceaccount.ServiceAccountTokenGetter) (authenticator.Token, error) {
	allPublicKeys := []interface{}{}
	for _, keyfile := range keyfiles {
		publicKeys, err := keyutil.PublicKeysFromFile(keyfile)
		if err != nil {
			return nil, err
		}
		allPublicKeys = append(allPublicKeys, publicKeys...)
	}

	tokenAuthenticator := serviceaccount.JWTTokenAuthenticator(serviceaccount.LegacyIssuer, allPublicKeys, apiAudiences, serviceaccount.NewLegacyValidator(lookup, serviceAccountGetter))
	return tokenAuthenticator, nil
}
564364
func (s *Server) ValidateCredentials(someUser user.User, valid *bool) error {
	result, err := s.f.ValidateCredentials(s.context(), someUser)
	if err != nil {
		return err
	}
	*valid = result
	return nil
}