// connectToAuthService creates a valid client connection to the auth service
348672
func connectToAuthService(cfg *service.Config) (client auth.ClientI, err error) {
	// connect to the local auth server by default:
	cfg.Auth.Enabled = true
	if len(cfg.AuthServers) == 0 {
		cfg.AuthServers = []utils.NetAddr{
			*defaults.AuthConnectAddr(),
		}
	}
	// read the host SSH keys and use them to open an SSH connection to the auth service
	i, err := auth.ReadLocalIdentity(filepath.Join(cfg.DataDir, teleport.ComponentProcess), auth.IdentityID{Role: teleport.RoleAdmin, HostUUID: cfg.HostUUID})
	if err != nil {
		// the "admin" identity is not present? this means the tctl is running NOT on the auth server.
		if trace.IsNotFound(err) {
			return nil, trace.AccessDenied("tctl must be used on the auth server")
		}
		return nil, trace.Wrap(err)
	}
	tlsConfig, err := i.TLSConfig(cfg.CipherSuites)
	if err != nil {
		return nil, trace.Wrap(err)
	}
	client, err = auth.NewTLSClient(auth.ClientConfig{Addrs: cfg.AuthServers, TLS: tlsConfig})
	if err != nil {
		return nil, trace.Wrap(err)
	}

	// Check connectivity by calling something on the client.
	_, err = client.GetClusterName()
	if err != nil {
		utils.Consolef(os.Stderr, teleport.ComponentClient,
			"Cannot connect to the auth server: %v.\nIs the auth server running on %v?",
			err, cfg.AuthServers[0].Addr)
		os.Exit(1)
	}
	return client, nil
}
640172
func (a *saOAuthClientAdapter) getServiceAccountTokens(sa *corev1.ServiceAccount) ([]string, error) {
	allSecrets, err := a.secretClient.Secrets(sa.Namespace).List(metav1.ListOptions{})
	if err != nil {
		return nil, err
	}
	tokens := []string{}
	for i := range allSecrets.Items {
		secret := &allSecrets.Items[i]
		if IsServiceAccountToken(secret, sa) {
			tokens = append(tokens, string(secret.Data[corev1.ServiceAccountTokenKey]))
		}
	}
	return tokens, nil
}
571772
func (c *Client) TaskService() tasks.TasksClient {
	if c.taskService != nil {
		return c.taskService
	}
	c.connMu.Lock()
	defer c.connMu.Unlock()
	return tasks.NewTasksClient(c.conn)
}
334698
func (s *RequestHeaderAuthenticationOptions) ToAuthenticationRequestHeaderConfig() *authenticatorfactory.RequestHeaderConfig {
	if len(s.ClientCAFile) == 0 {
		return nil
	}

	return &authenticatorfactory.RequestHeaderConfig{
		UsernameHeaders:     s.UsernameHeaders,
		GroupHeaders:        s.GroupHeaders,
		ExtraHeaderPrefixes: s.ExtraHeaderPrefixes,
		ClientCA:            s.ClientCAFile,
		AllowedClientNames:  s.AllowedNames,
	}
}
1104560
func newAuthenticatedConnection(conn driver.Connection, auth httpAuthentication) (driver.Connection, error) {
	if conn == nil {
		return nil, driver.WithStack(driver.InvalidArgumentError{Message: "conn is nil"})
	}
	if auth == nil {
		return nil, driver.WithStack(driver.InvalidArgumentError{Message: "auth is nil"})
	}
	return &authenticatedConnection{
		conn: conn,
		auth: auth,
	}, nil
}
294403
func (r *Consumer) ConnectToNSQD(addr string) error {
	if atomic.LoadInt32(&r.stopFlag) == 1 {
		return errors.New("consumer stopped")
	}

	if atomic.LoadInt32(&r.runningHandlers) == 0 {
		return errors.New("no handlers")
	}

	atomic.StoreInt32(&r.connectedFlag, 1)

	logger, logLvl := r.getLogger()

	conn := NewConn(addr, &r.config, &consumerConnDelegate{r})
	conn.SetLogger(logger, logLvl,
		fmt.Sprintf("%3d [%s/%s] (%%s)", r.id, r.topic, r.channel))

	r.mtx.Lock()
	_, pendingOk := r.pendingConnections[addr]
	_, ok := r.connections[addr]
	if ok || pendingOk {
		r.mtx.Unlock()
		return ErrAlreadyConnected
	}
	r.pendingConnections[addr] = conn
	if idx := indexOf(addr, r.nsqdTCPAddrs); idx == -1 {
		r.nsqdTCPAddrs = append(r.nsqdTCPAddrs, addr)
	}
	r.mtx.Unlock()

	r.log(LogLevelInfo, "(%s) connecting to nsqd", addr)

	cleanupConnection := func() {
		r.mtx.Lock()
		delete(r.pendingConnections, addr)
		r.mtx.Unlock()
		conn.Close()
	}

	resp, err := conn.Connect()
	if err != nil {
		cleanupConnection()
		return err
	}

	if resp != nil {
		if resp.MaxRdyCount < int64(r.getMaxInFlight()) {
			r.log(LogLevelWarning,
				"(%s) max RDY count %d < consumer max in flight %d, truncation possible",
				conn.String(), resp.MaxRdyCount, r.getMaxInFlight())
		}
	}

	cmd := Subscribe(r.topic, r.channel)
	err = conn.WriteCommand(cmd)
	if err != nil {
		cleanupConnection()
		return fmt.Errorf("[%s] failed to subscribe to %s:%s - %s",
			conn, r.topic, r.channel, err.Error())
	}

	r.mtx.Lock()
	delete(r.pendingConnections, addr)
	r.connections[addr] = conn
	r.mtx.Unlock()

	// pre-emptive signal to existing connections to lower their RDY count
	for _, c := range r.conns() {
		r.maybeUpdateRDY(c)
	}

	return nil
}
320492
func (op *OpenIDProvider) AuthURL(c Client, state string) string {
	values := url.Values{"client_id": {c.ISS}, "state": {state}, "response_type": {"code"},
		"redirect_uri": {c.RedirectURI}, "scope": {"openid profile email"}}
	return fmt.Sprintf("%s?%s", op.Config.AuthorizationEndpoint, values.Encode())
}
258883
func (a *api) connectAgent(address string) (*agent.Client, error) {
	if a.agent == nil {
		var err error
		a.agent, err = agent.NewClient(address)
		if err != nil {
			return nil, fmt.Errorf("could not create a client to the agent: %s", err)
		}
		a.authenticateHost()
	}
	return a.agent, nil
}
629845
func (*denyAuthenticator) AuthenticateClient(client api.Client) (*authenticator.Response, bool, error) {
	return nil, false, nil
}
613942
func (client *Socket) ClientAuthPlain(username, password string) error {
	err := client.SetPlainUsername(username)
	if err == nil {
		err = client.SetPlainPassword(password)
	}
	return err
}
434295
func (c *client) awaitingAuth() bool {
	return !c.flags.isSet(connectReceived) && c.atmr != nil
}
314224
func (c *clusterConnection) SetAuthentication(auth driver.Authentication) (driver.Connection, error) {
	c.mutex.Lock()
	defer c.mutex.Unlock()

	// Configure underlying servers
	newServerConnections := make([]driver.Connection, len(c.servers))
	for i, s := range c.servers {
		authConn, err := s.SetAuthentication(auth)
		if err != nil {
			return nil, driver.WithStack(err)
		}
		newServerConnections[i] = authConn
	}

	// Save authentication
	c.auth = auth
	c.servers = newServerConnections

	return c, nil
}
1138790
func makeAuthenticatee(handler callback.Handler, factory transportFactory) (auth.Authenticatee, error) {

	ip := callback.NewInterprocess()
	if err := handler.Handle(ip); err != nil {
		return nil, err
	}
	config := &authenticateeConfig{
		client:    ip.Client(),
		handler:   handler,
		transport: factory.makeTransport(),
	}
	return auth.AuthenticateeFunc(func(ctx context.Context, handler callback.Handler) error {
		ctx, auth := newAuthenticatee(ctx, config)
		auth.authenticate(ctx, ip.Server())

		select {
		case <-ctx.Done():
			return auth.discard(ctx)
		case <-auth.done:
			return auth.err
		}
	}), nil
}
1328753
func (s *Service) withAuthService(c context.Context) context.Context {
	return serverAuth.Initialize(c, &serverAuth.Config{
		DBProvider: nil, // We don't need to store an auth DB.
		Signer:     nil, // We don't need to sign anything.
		AccessTokenProvider: func(ic context.Context, scopes []string) (*oauth2.Token, error) {
			// Create a new Authenticator for the supplied scopes.
			//
			// Pass our outer Context, since we don't want the cached Authenticator
			// instance to be permanently bound to the inner Context.
			a, err := s.authenticatorForScopes(c, scopes)
			scopesStr := strings.Join(scopes, " ")
			if err != nil {
				log.Fields{
					"scopes":     scopesStr,
					log.ErrorKey: err,
				}.Errorf(c, "Failed to create authenticator.")
				return nil, err
			}
			tok, err := a.GetAccessToken(minAuthTokenLifetime)
			if err != nil {
				log.Fields{
					"scopes":     scopesStr,
					log.ErrorKey: err,
				}.Errorf(c, "Failed to mint access token.")
			}
			return tok, err
		},
		AnonymousTransport: func(ic context.Context) http.RoundTripper {
			return s.unauthenticatedTransport()
		},
	})
}
896382
func (s *server) connectToPeer(addr *lnwire.NetAddress, errChan chan<- error) {
	conn, err := brontide.Dial(s.identityPriv, addr, cfg.net.Dial)
	if err != nil {
		srvrLog.Errorf("Unable to connect to %v: %v", addr, err)
		select {
		case errChan <- err:
		case <-s.quit:
		}
		return
	}

	close(errChan)

	s.OutboundPeerConnected(nil, conn)
}
225713
func (s *Store) ConnectServiceNodes(ws memdb.WatchSet, serviceName string) (uint64, structs.ServiceNodes, error) {
	return s.serviceNodes(ws, serviceName, true)
}
716839
func (pc *ProtoClient) ConnectTo(addr string) error {
	err := pc.Client.ConnectTo(addr)
	if err != nil {
		return err
	}

	if !pc.ready {
		err = pc.LoadServerInfo(addr)
		if err != nil {
			return err
		}
	}

	if pc.ready {
		go pc.waitForData()
	}
	return nil
}