// begin next 3 methods borrowed from go-dockerclient
// NewAuthConfigurations finishes creating the auth config array s2i pulls from
// any auth config file it is pointed to when started from the command line
779320
func NewAuthConfigurations(r io.Reader) (*AuthConfigurations, error) {
	var auth *AuthConfigurations
	confs, err := parseDockerConfig(r)
	if err != nil {
		return nil, err
	}
	auth, err = authConfigs(confs)
	if err != nil {
		return nil, err
	}
	return auth, nil
}
850267
func NewCmdConfigSetAuthInfo(out io.Writer, configAccess clientcmd.ConfigAccess) *cobra.Command {
	options := &createAuthInfoOptions{configAccess: configAccess}
	return newCmdConfigSetAuthInfo(out, options)
}
182680
func (c *TokensClient) CreateAuth(ctx context.Context, authorization string, authTokenRequest *AuthTokenRequest) (*AuthToken, error) {
	p := "/tokens/auth"

	req, err := c.backend.NewRequest(http.MethodPost, p, nil, authTokenRequest)
	if err != nil {
		return nil, err
	}

	req.Header.Set("authorization", authorization)

	var resp AuthToken
	_, err = c.backend.Do(ctx, req, &resp, func(code int) error {
		return &Error{}
	})
	if err != nil {
		return nil, err
	}

	return &resp, nil
}
1248447
func (d *Driver) newDockerClient(timeout time.Duration) (*docker.Client, error) {
	var err error
	var merr multierror.Error
	var newClient *docker.Client

	// Default to using whatever is configured in docker.endpoint. If this is
	// not specified we'll fall back on NewClientFromEnv which reads config from
	// the DOCKER_* environment variables DOCKER_HOST, DOCKER_TLS_VERIFY, and
	// DOCKER_CERT_PATH. This allows us to lock down the config in production
	// but also accept the standard ENV configs for dev and test.
	dockerEndpoint := d.config.Endpoint
	if dockerEndpoint != "" {
		cert := d.config.TLS.Cert
		key := d.config.TLS.Key
		ca := d.config.TLS.CA

		if cert+key+ca != "" {
			d.logger.Debug("using TLS client connection", "endpoint", dockerEndpoint)
			newClient, err = docker.NewTLSClient(dockerEndpoint, cert, key, ca)
			if err != nil {
				merr.Errors = append(merr.Errors, err)
			}
		} else {
			d.logger.Debug("using standard client connection", "endpoint", dockerEndpoint)
			newClient, err = docker.NewClient(dockerEndpoint)
			if err != nil {
				merr.Errors = append(merr.Errors, err)
			}
		}
	} else {
		d.logger.Debug("using client connection initialized from environment")
		newClient, err = docker.NewClientFromEnv()
		if err != nil {
			merr.Errors = append(merr.Errors, err)
		}
	}

	if timeout != 0 && newClient != nil {
		newClient.SetTimeout(timeout)
	}
	return newClient, merr.ErrorOrNil()
}
1343256
func NewAuth(auth types.AuthConfig) Auth {
	// TODO 这里可以组装其他的方法
	return simple.NewBasicAuth(auth.Username, auth.Password)
}
851695
func authFromTaskConfig(driverConfig *TaskConfig) authBackend {
	return func(string) (*docker.AuthConfiguration, error) {
		// If all auth fields are empty, return
		if len(driverConfig.Auth.Username) == 0 && len(driverConfig.Auth.Password) == 0 && len(driverConfig.Auth.Email) == 0 && len(driverConfig.Auth.ServerAddr) == 0 {
			return nil, nil
		}
		return &docker.AuthConfiguration{
			Username:      driverConfig.Auth.Username,
			Password:      driverConfig.Auth.Password,
			Email:         driverConfig.Auth.Email,
			ServerAddress: driverConfig.Auth.ServerAddr,
		}, nil
	}
}
33557
func NewClient(addr string, authConfig types.AuthConfig) *Client {
	conn := connect(addr, authConfig)
	return &Client{addr: addr, conn: conn}
}
857190
func (auth *Auth) CreateAuthURI(ctx context.Context, providerID string, continueURI string, sessionID string) (string, error) {
	resp, err := auth.client.CreateAuthUri(&identitytoolkit.IdentitytoolkitRelyingpartyCreateAuthUriRequest{
		ProviderId:   providerID,
		ContinueUri:  continueURI,
		AuthFlowType: "CODE_FLOW",
		SessionId:    sessionID,
	}).Context(ctx).Do()
	if err != nil {
		return "", err
	}
	return resp.AuthUri, nil
}
224784
func NewGoogleClient(conf *cloudstorage.Config) (client GoogleOAuthClient, err error) {

	switch conf.AuthMethod {
	case AuthGCEDefaultOAuthToken:
		// This token method uses the default OAuth token with GCS created by tools like gsutils, gcloud, etc...
		// See github.com/lytics/lio/src/ext_svcs/google/google_transporter.go : BuildDefaultGoogleTransporter
		client, err = BuildDefaultGoogleTransporter("")
		if err != nil {
			return nil, err
		}
	case AuthGCEMetaKeySource:
		client, err = BuildGCEMetadatTransporter("")
		if err != nil {
			return nil, err
		}
	case AuthJWTKeySource:
		if conf.JwtConf == nil {
			return nil, fmt.Errorf("invalid config: missing jwt config struct")
		}
		// used if you are providing string of json
		client, err = BuildGoogleJWTTransporter(conf.JwtConf)
		if err != nil {
			return nil, err
		}
	case AuthGoogleJWTKeySource:
		switch conf.Scope {
		case "":
			// See the list here: https://github.com/GoogleCloudPlatform/google-cloud-go/blob/master/storage/storage.go#L58-L68
			return nil, fmt.Errorf("invalid config: missing devstorage scope")
		}
		client, err = BuildGoogleFileJWTTransporter(conf.JwtFile, conf.Scope)
		if err != nil {
			return nil, err
		}
	default:
		return nil, fmt.Errorf("bad AuthMethod: %v", conf.AuthMethod)
	}

	return client, err
}
416119
func (c *commonFlags) Init(authOpts auth.Options) {
	c.defaultFlags.Init(&c.Flags)
	c.authFlags.Register(&c.Flags, authOpts)
	c.Flags.StringVar(&c.serverURL, "server", os.Getenv("SWARMING_SERVER"), "Server URL; required. Set $SWARMING_SERVER to set a default.")
	c.Flags.IntVar(&c.worker, "worker", 8, "Number of workers used to download isolated files.")
}
108317
func authFromDockerConfig(file string) authBackend {
	return func(repo string) (*docker.AuthConfiguration, error) {
		if file == "" {
			return nil, nil
		}
		repoInfo, err := parseRepositoryInfo(repo)
		if err != nil {
			return nil, err
		}

		cfile, err := loadDockerConfig(file)
		if err != nil {
			return nil, err
		}

		return firstValidAuth(repo, []authBackend{
			func(string) (*docker.AuthConfiguration, error) {
				dockerAuthConfig := registry.ResolveAuthConfig(cfile.AuthConfigs, repoInfo.Index)
				auth := &docker.AuthConfiguration{
					Username:      dockerAuthConfig.Username,
					Password:      dockerAuthConfig.Password,
					Email:         dockerAuthConfig.Email,
					ServerAddress: dockerAuthConfig.ServerAddress,
				}
				if authIsEmpty(auth) {
					return nil, nil
				}
				return auth, nil
			},
			authFromHelper(cfile.CredentialHelpers[registry.GetAuthConfigKey(repoInfo.Index)]),
			authFromHelper(cfile.CredentialsStore),
		})
	}
}
1212015
func init() {
	tr := utilnet.SetTransportDefaults(&http.Transport{})
	metadataHTTPClientTimeout := time.Second * 10
	httpClient := &http.Client{
		Transport: tr,
		Timeout:   metadataHTTPClientTimeout,
	}
	credentialprovider.RegisterCredentialProvider("google-dockercfg",
		&credentialprovider.CachingDockerConfigProvider{
			Provider: &dockerConfigKeyProvider{
				metadataProvider{Client: httpClient},
			},
			Lifetime: 60 * time.Second,
		})

	credentialprovider.RegisterCredentialProvider("google-dockercfg-url",
		&credentialprovider.CachingDockerConfigProvider{
			Provider: &dockerConfigUrlKeyProvider{
				metadataProvider{Client: httpClient},
			},
			Lifetime: 60 * time.Second,
		})

	credentialprovider.RegisterCredentialProvider("google-container-registry",
		// Never cache this.  The access token is already
		// cached by the metadata service.
		&containerRegistryProvider{
			metadataProvider{Client: httpClient},
		})
}
100066
func LoadImageRegistryAuth(dockerCfg io.Reader) *AuthConfigurations {
	auths, err := NewAuthConfigurations(dockerCfg)
	if err != nil {
		glog.V(0).Infof("error: Unable to load docker config: %v", err)
		return nil
	}
	return auths
}
1336438
func newDockerClient(c *Context) (*dockerutil.Client, error) {
	host := c.String(FlagDockerHost)
	certPath := c.String(FlagDockerCert)
	authProvider, err := newAuthProvider(c)
	if err != nil {
		return nil, err
	}

	return dockerutil.NewClient(authProvider, host, certPath)
}
572075
func AuthStart() (err error) {
	if auth_init {
		if auth_verbose {
			log.Println("AUTH: Already running")
		}
		return errors.New("Auth is already running")
	}

	auth_handler, err = NewSocket(REP)
	if err != nil {
		return
	}
	auth_handler.SetLinger(0)
	err = auth_handler.Bind("inproc://zeromq.zap.01")
	if err != nil {
		auth_handler.Close()
		return
	}

	auth_quit, err = NewSocket(REQ)
	if err != nil {
		auth_handler.Close()
		return
	}
	auth_quit.SetLinger(0)
	err = auth_quit.Connect("inproc://zeromq.zap.01")
	if err != nil {
		auth_handler.Close()
		auth_quit.Close()
		return
	}

	go auth_do_handler()

	if auth_verbose {
		log.Println("AUTH: Starting")
	}

	auth_init = true

	return
}
901239
func NewCmdCreateSecretDockerRegistry(f cmdutil.Factory, ioStreams genericclioptions.IOStreams) *cobra.Command {
	options := &SecretDockerRegistryOpts{
		CreateSubcommandOptions: NewCreateSubcommandOptions(ioStreams),
	}

	cmd := &cobra.Command{
		Use:                   "docker-registry NAME --docker-username=user --docker-password=password --docker-email=email [--docker-server=string] [--from-literal=key1=value1] [--dry-run]",
		DisableFlagsInUseLine: true,
		Short:                 i18n.T("Create a secret for use with a Docker registry"),
		Long:                  secretForDockerRegistryLong,
		Example:               secretForDockerRegistryExample,
		Run: func(cmd *cobra.Command, args []string) {
			cmdutil.CheckErr(options.Complete(f, cmd, args))
			cmdutil.CheckErr(options.Run())
		},
	}

	options.CreateSubcommandOptions.PrintFlags.AddFlags(cmd)

	cmdutil.AddApplyAnnotationFlags(cmd)
	cmdutil.AddValidateFlags(cmd)
	cmdutil.AddGeneratorFlags(cmd, generateversioned.SecretForDockerRegistryV1GeneratorName)
	cmd.Flags().String("docker-username", "", i18n.T("Username for Docker registry authentication"))
	cmd.MarkFlagRequired("docker-username")
	cmd.Flags().String("docker-password", "", i18n.T("Password for Docker registry authentication"))
	cmd.MarkFlagRequired("docker-password")
	cmd.Flags().String("docker-email", "", i18n.T("Email for Docker registry"))
	cmd.Flags().String("docker-server", "https://index.docker.io/v1/", i18n.T("Server location for Docker registry"))
	cmd.Flags().Bool("append-hash", false, "Append a hash of the secret to its name.")
	cmd.Flags().StringSlice("from-file", []string{}, "Key files can be specified using their file path, in which case a default name will be given to them, or optionally with a name and file path, in which case the given name will be used.  Specifying a directory will iterate each named file in the directory that is a valid secret key.")

	return cmd
}
253354
func Init() {
	if *ldapAuthConfigFile == "" && *ldapAuthConfigString == "" {
		log.Infof("Not configuring AuthServerLdap because mysql_ldap_auth_config_file and mysql_ldap_auth_config_string are empty")
		return
	}
	if *ldapAuthConfigFile != "" && *ldapAuthConfigString != "" {
		log.Infof("Both mysql_ldap_auth_config_file and mysql_ldap_auth_config_string are non-empty, can only use one.")
		return
	}
	if *ldapAuthMethod != mysql.MysqlClearPassword && *ldapAuthMethod != mysql.MysqlDialog {
		log.Exitf("Invalid mysql_ldap_auth_method value: only support mysql_clear_password or dialog")
	}
	ldapAuthServer := &AuthServerLdap{
		Client:       &ClientImpl{},
		ServerConfig: ServerConfig{},
		Method:       *ldapAuthMethod,
	}

	data := []byte(*ldapAuthConfigString)
	if *ldapAuthConfigFile != "" {
		var err error
		data, err = ioutil.ReadFile(*ldapAuthConfigFile)
		if err != nil {
			log.Exitf("Failed to read mysql_ldap_auth_config_file: %v", err)
		}
	}
	if err := json.Unmarshal(data, ldapAuthServer); err != nil {
		log.Exitf("Error parsing AuthServerLdap config: %v", err)
	}
	mysql.RegisterAuthServerImpl("ldap", ldapAuthServer)
}