// executeCredentialProcess starts the credential process on the OS and
// returns the results or an error.
966638
func (p *ProcessProvider) executeCredentialProcess() ([]byte, error) {

	if err := p.prepareCommand(); err != nil {
		return nil, err
	}

	// Setup the pipes
	outReadPipe, outWritePipe, err := os.Pipe()
	if err != nil {
		return nil, awserr.New(
			ErrCodeProcessProviderExecution,
			errMsgProcessProviderPipe,
			err)
	}

	p.command.Stderr = os.Stderr    // display stderr on console for MFA
	p.command.Stdout = outWritePipe // get creds json on process's stdout
	p.command.Stdin = os.Stdin      // enable stdin for MFA

	output := bytes.NewBuffer(make([]byte, 0, p.MaxBufSize))

	stdoutCh := make(chan error, 1)
	go readInput(
		io.LimitReader(outReadPipe, int64(p.MaxBufSize)),
		output,
		stdoutCh)

	execCh := make(chan error, 1)
	go executeCommand(*p.command, execCh)

	finished := false
	var errors []error
	for !finished {
		select {
		case readError := <-stdoutCh:
			errors = appendError(errors, readError)
			finished = true
		case execError := <-execCh:
			err := outWritePipe.Close()
			errors = appendError(errors, err)
			errors = appendError(errors, execError)
			if errors != nil {
				return output.Bytes(), awserr.NewBatchError(
					ErrCodeProcessProviderExecution,
					errMsgProcessProviderProcess,
					errors)
			}
		case <-time.After(p.Timeout):
			finished = true
			return output.Bytes(), awserr.NewBatchError(
				ErrCodeProcessProviderExecution,
				errMsgProcessProviderTimeout,
				errors) // errors can be nil
		}
	}

	out := output.Bytes()

	if runtime.GOOS == "windows" {
		// windows adds slashes to quotes
		out = []byte(strings.Replace(string(out), `\"`, `"`, -1))
	}

	return out, nil
}
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
}
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)
	}
}
1154194
func (a *Authenticator) PurgeCredentialsCache() error {
	a.lock.Lock()
	defer a.lock.Unlock()
	if err := a.ensureInitialized(); err != nil {
		return err
	}
	return a.purgeCredentialsCacheLocked()
}
1255995
func NewCredentialsTimeout(command string, timeout time.Duration) *credentials.Credentials {
	p := NewCredentials(command, func(opt *ProcessProvider) {
		opt.Timeout = timeout
	})

	return p
}
1214022
func (c *Gcd) StartProcess(exePath, userDir, port string) error {
	c.port = port
	c.addr = fmt.Sprintf("%s:%s", c.host, c.port)
	c.profileDir = userDir
	c.apiEndpoint = fmt.Sprintf("http://%s/json", c.addr)
	// profile directory
	c.flags = append(c.flags, fmt.Sprintf("--user-data-dir=%s", c.profileDir))
	// debug port to use
	c.flags = append(c.flags, fmt.Sprintf("--remote-debugging-port=%s", port))
	// bypass first run check
	c.flags = append(c.flags, "--no-first-run")
	// bypass default browser check
	c.flags = append(c.flags, "--no-default-browser-check")

	c.chromeCmd = exec.Command(exePath, c.flags...)
	// add custom environment variables.
	c.chromeCmd.Env = os.Environ()
	c.chromeCmd.Env = append(c.chromeCmd.Env, c.env...)

	return c.startProcess()
}
448159
func (c *Client) ValidateCredentials(user user.User) (bool, error) {
	result := false
	err := c.call("ValidateCredentials", user, &result)
	return result, err
}
610333
func (s *RegistryCredential) SetCredential(v string) *RegistryCredential {
	s.Credential = &v
	return s
}
898294
func (c *SSHCommand) generateCredential(username, ip string) (*api.Secret, *SSHCredentialResp, error) {
	sshClient := c.client.SSHWithMountPoint(c.flagMountPoint)

	// Attempt to generate the credential.
	secret, err := sshClient.Credential(c.flagRole, map[string]interface{}{
		"username": username,
		"ip":       ip,
	})
	if err != nil {
		return nil, nil, errors.Wrap(err, "failed to get credentials")
	}
	if secret == nil || secret.Data == nil {
		return nil, nil, fmt.Errorf("vault returned empty credentials")
	}

	// Port comes back as a json.Number which mapstructure doesn't like, so
	// convert it
	if d, ok := secret.Data["port"].(json.Number); ok {
		secret.Data["port"] = d.String()
	}

	// Use mapstructure to decode the response
	var resp SSHCredentialResp
	if err := mapstructure.Decode(secret.Data, &resp); err != nil {
		return nil, nil, errors.Wrap(err, "failed to decode credential")
	}

	// Check for an empty key response
	if len(resp.Key) == 0 {
		return nil, nil, fmt.Errorf("vault returned an invalid key")
	}

	return secret, &resp, nil
}
286661
func KillProcess(pid int) {
	p, err := os.FindProcess(pid)
	if err == nil {
		p.Kill()
	}
}
726830
func StartProcess(label string, dir string, execPath string, args []string, inFile io.Reader, outFile io.WriteCloser) (*Process, error) {
	cmd := exec.Command(execPath, args...)
	cmd.Dir = dir
	cmd.Stdout = outFile
	cmd.Stderr = outFile
	cmd.Stdin = inFile
	if err := cmd.Start(); err != nil {
		return nil, err
	}
	proc := &Process{
		Label:      label,
		ExecPath:   execPath,
		Args:       args,
		Pid:        cmd.Process.Pid,
		StartTime:  time.Now(),
		Cmd:        cmd,
		ExitState:  nil,
		InputFile:  inFile,
		OutputFile: outFile,
		WaitCh:     make(chan struct{}),
	}
	go func() {
		err := proc.Cmd.Wait()
		if err != nil {
			// fmt.Printf("Process exit: %v\n", err)
			if exitError, ok := err.(*exec.ExitError); ok {
				proc.ExitState = exitError.ProcessState
			}
		}
		proc.ExitState = proc.Cmd.ProcessState
		proc.EndTime = time.Now() // TODO make this goroutine-safe
		err = proc.OutputFile.Close()
		if err != nil {
			fmt.Printf("Error closing output file for %v: %v\n", proc.Label, err)
		}
		close(proc.WaitCh)
	}()
	return proc, nil
}
742988
func (m *nativeGitClient) runCredentialedCmd(command string, args ...string) (string, error) {
	cmd := exec.Command(command, args...)
	if auth, ok := m.auth.(*http.BasicAuth); ok {
		cmd.Env = append(cmd.Env, fmt.Sprintf("GIT_ASKPASS=git-ask-pass.sh"))
		cmd.Env = append(cmd.Env, fmt.Sprintf("GIT_USERNAME=%s", auth.Username))
		cmd.Env = append(cmd.Env, fmt.Sprintf("GIT_PASSWORD=%s", auth.Password))
	}
	return m.runCmdOutput(cmd)
}
1302288
func Convert_v1alpha1_ExecCredentialSpec_To_clientauthentication_ExecCredentialSpec(in *ExecCredentialSpec, out *clientauthentication.ExecCredentialSpec, s conversion.Scope) error {
	return autoConvert_v1alpha1_ExecCredentialSpec_To_clientauthentication_ExecCredentialSpec(in, out, s)
}
718072
func AuthenticateExecution(c context.Context, auth *dm.Execution_Auth) (a *Attempt, e *Execution, err error) {
	a, e, err = verifyExecutionAndCheckExTok(c, auth)
	if err != nil {
		logging.Fields{ek: err, "eid": auth.Id}.Errorf(c, "failed to verify execution")
		err = makeError(err, "requires execution Auth")
	}
	return a, e, err
}
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
}
190724
func NewCredential(auth types.AuthConfig) Credential {
	// TODO 这里可以组装其他的方法
	return simple.NewBasicCredential(auth.Username, auth.Password)
}
1273285
func (v *Validator) CheckProcess() (errs error) {
	logrus.Debugf("check process")

	if v.spec.Process == nil {
		return
	}

	process := v.spec.Process
	if !osFilepath.IsAbs(v.platform, process.Cwd) {
		errs = multierror.Append(errs,
			specerror.NewError(
				specerror.ProcCwdAbs,
				fmt.Errorf("cwd %q is not an absolute path", process.Cwd),
				rspec.Version))
	}

	for _, env := range process.Env {
		if !envValid(env) {
			errs = multierror.Append(errs, fmt.Errorf("env %q should be in the form of 'key=value'. The left hand side must consist solely of letters, digits, and underscores '_'", env))
		}
	}

	if len(process.Args) == 0 {
		errs = multierror.Append(errs,
			specerror.NewError(
				specerror.ProcArgsOneEntryRequired,
				fmt.Errorf("args must not be empty"),
				rspec.Version))
	} else {
		if filepath.IsAbs(process.Args[0]) && v.spec.Root != nil {
			var rootfsPath string
			if filepath.IsAbs(v.spec.Root.Path) {
				rootfsPath = v.spec.Root.Path
			} else {
				rootfsPath = filepath.Join(v.bundlePath, v.spec.Root.Path)
			}
			absPath := filepath.Join(rootfsPath, process.Args[0])
			fileinfo, err := os.Stat(absPath)
			if os.IsNotExist(err) {
				logrus.Warnf("executable %q is not available in rootfs currently", process.Args[0])
			} else if err != nil {
				errs = multierror.Append(errs, err)
			} else {
				m := fileinfo.Mode()
				if m.IsDir() || m&0111 == 0 {
					errs = multierror.Append(errs, fmt.Errorf("arg %q is not executable", process.Args[0]))
				}
			}
		}
	}

	if v.platform == "linux" || v.platform == "solaris" {
		errs = multierror.Append(errs, v.CheckRlimits())
	}

	if v.platform == "linux" {
		if v.spec.Process.Capabilities != nil {
			errs = multierror.Append(errs, v.CheckCapabilities())
		}

		if len(process.ApparmorProfile) > 0 {
			profilePath := filepath.Join(v.bundlePath, v.spec.Root.Path, "/etc/apparmor.d", process.ApparmorProfile)
			_, err := os.Stat(profilePath)
			if err != nil {
				errs = multierror.Append(errs, err)
			}
		}
	}

	return
}