// ValidateDiscoveryTokenAPIServer validates discovery token for API server
192415
func ValidateDiscoveryTokenAPIServer(apiServer string, fldPath *field.Path) field.ErrorList {
	allErrs := field.ErrorList{}
	_, _, err := net.SplitHostPort(apiServer)
	if err != nil {
		allErrs = append(allErrs, field.Invalid(fldPath, apiServer, err.Error()))
	}
	return allErrs
}
421732
func (c *Client) consulDiscovery() {
	for {
		select {
		case <-c.triggerDiscoveryCh:
			if err := c.consulDiscoveryImpl(); err != nil {
				c.logger.Error("error discovering nomad servers", "error", err)
			}
		case <-c.shutdownCh:
			return
		}
	}
}
1081430
func (m *DiscoveryResponse) Validate() error {
	if m == nil {
		return nil
	}

	// no validation rules for VersionInfo

	for idx, item := range m.GetResources() {
		_, _ = idx, item

		{
			tmp := item

			if v, ok := interface{}(&tmp).(interface{ Validate() error }); ok {

				if err := v.Validate(); err != nil {
					return DiscoveryResponseValidationError{
						field:  fmt.Sprintf("Resources[%v]", idx),
						reason: "embedded message failed validation",
						cause:  err,
					}
				}
			}
		}

	}

	// no validation rules for Canary

	// no validation rules for TypeUrl

	// no validation rules for Nonce

	{
		tmp := m.GetControlPlane()

		if v, ok := interface{}(tmp).(interface{ Validate() error }); ok {

			if err := v.Validate(); err != nil {
				return DiscoveryResponseValidationError{
					field:  "ControlPlane",
					reason: "embedded message failed validation",
					cause:  err,
				}
			}
		}
	}

	return nil
}
604854
func (nc *Conn) SetDiscoveredServersHandler(dscb ConnHandler) {
	if nc == nil {
		return
	}
	nc.mu.Lock()
	defer nc.mu.Unlock()
	nc.Opts.DiscoveredServersCB = dscb
}
1144052
func (p *Client) DiscoverServices(filter []ble.UUID) ([]*ble.Service, error) {
	p.Lock()
	defer p.Unlock()
	if p.profile == nil {
		p.profile = &ble.Profile{}
	}
	start := uint16(0x0001)
	for {
		length, b, err := p.ac.ReadByGroupType(start, 0xFFFF, ble.PrimaryServiceUUID)
		if err == ble.ErrAttrNotFound {
			return p.profile.Services, nil
		}
		if err != nil {
			return nil, err
		}
		for len(b) != 0 {
			h := binary.LittleEndian.Uint16(b[:2])
			endh := binary.LittleEndian.Uint16(b[2:4])
			u := ble.UUID(b[4:length])
			if filter == nil || ble.Contains(filter, u) {
				s := &ble.Service{
					UUID:      u,
					Handle:    h,
					EndHandle: endh,
				}
				p.profile.Services = append(p.profile.Services, s)
			}
			if endh == 0xFFFF {
				return p.profile.Services, nil
			}
			start = endh + 1
			b = b[length:]
		}
	}
}
136440
func (proxy *ProxyClient) FindServersByLabels(ctx context.Context, namespace string, labels map[string]string) ([]services.Server, error) {
	if namespace == "" {
		return nil, trace.BadParameter(auth.MissingNamespaceError)
	}
	nodes := make([]services.Server, 0)
	site, err := proxy.CurrentClusterAccessPoint(ctx, false)
	if err != nil {
		return nil, trace.Wrap(err)
	}

	siteNodes, err := site.GetNodes(namespace, services.SkipValidation())
	if err != nil {
		return nil, trace.Wrap(err)
	}

	// look at every node on this site and see which ones match:
	for _, node := range siteNodes {
		if node.MatchAgainst(labels) {
			nodes = append(nodes, node)
		}
	}
	return nodes, nil
}
1063208
func (sa *discoverySecurityAdapter) ValidateAliveMsg(m *proto.SignedGossipMessage) bool {
	am := m.GetAliveMsg()
	if am == nil || am.Membership == nil || am.Membership.PkiId == nil || !m.IsSigned() {
		sa.logger.Warning("Invalid alive message:", m)
		return false
	}

	var identity api.PeerIdentityType

	// If identity is included inside AliveMessage
	if am.Identity != nil {
		identity = api.PeerIdentityType(am.Identity)
		claimedPKIID := am.Membership.PkiId
		err := sa.idMapper.Put(claimedPKIID, identity)
		if err != nil {
			sa.logger.Debugf("Failed validating identity of %v reason: %+v", am, errors.WithStack(err))
			return false
		}
	} else {
		identity, _ = sa.idMapper.Get(am.Membership.PkiId)
		if identity != nil {
			sa.logger.Debug("Fetched identity of", am.Membership.PkiId, "from identity store")
		}
	}

	if identity == nil {
		sa.logger.Debug("Don't have certificate for", am)
		return false
	}

	return sa.validateAliveMsgSignature(m, identity)
}
83359
func NewRedisDiscovery(client *redis.Client) Discovery {
	return &discovery{
		services:          announcement.NewRedisAnnouncementStore(client, "discovery"),
		masterAuthServers: make(map[string]struct{}),
	}
}
878795
func (c *Config) WithEndpointDiscovery(t bool) *Config {
	c.EnableEndpointDiscovery = &t
	return c
}
896923
func discoverTypes(protoPath string) {
	fileset := token.NewFileSet()
	packageMap, err := parser.ParseDir(fileset, protoPath, nil, 0)
	if err != nil {
		panic(err)
	}

	// Iterate over packages
	for _, p := range packageMap {
		// Iterate over files
		for _, f := range p.Files {
			// Iterate over declarations
			for _, d := range f.Decls {
				switch t := d.(type) {
				case *ast.GenDecl:
					// Iterate over specifications
					for _, s := range t.Specs {
						// Handle type and value specs
						switch t := s.(type) {
						case *ast.TypeSpec:
							// Type specs contain types such as CDemoPacket. Extract the type
							// name and mark it as found in the corresponding message type.
							typeName := t.Name.String()
							//if _, ok := findMessageByTypeName(typeName); ok {
							messageTypeNames[typeName] = true
							//}

						case *ast.ValueSpec:
							// Value specs contain enum values such as EDemoCommands_DEM_Packet.
							// Extract the enum name (ex. EDemoCommands), value name
							// (ex. EDemoCommands_DEM_Packet) and real value (ex. 7) and
							// store them with the matching enum type.
							valueName := nameOfValue(t)
							if enumName := typeOfValue(t); enumName != "" {
								if mt, ok := findMessageByEnumName(enumName); ok {
									mt.enumValues[valueName] = valueOfValue(t)
								}
							}
						}
					}
				}
			}
		}
	}
}
217534
func isValidPeer(host *HostInfo) bool {
	return !(len(host.RPCAddress()) == 0 ||
		host.hostId == "" ||
		host.dataCenter == "" ||
		host.rack == "" ||
		len(host.tokens) == 0)
}
925837
func (m *DefaultRESTMapper) ResourceIsValid(resource string) bool {
	_, err := m.KindFor(resource)
	return err == nil
}
1204102
func (r *RPCJob) ServerDiscovery(
	route string,
	rpcMetadata map[string]interface{},
) (serverID string, err error) {
	return "", nil
}
895185
func NewEtcdServiceDiscovery(
	config *config.Config,
	server *Server,
	appDieChan chan bool,
	cli ...*clientv3.Client,
) (ServiceDiscovery, error) {
	var client *clientv3.Client
	if len(cli) > 0 {
		client = cli[0]
	}
	sd := &etcdServiceDiscovery{
		config:          config,
		running:         false,
		server:          server,
		serverMapByType: make(map[string]map[string]*Server),
		listeners:       make([]SDListener, 0),
		stopChan:        make(chan bool),
		stopLeaseChan:   make(chan bool),
		appDieChan:      appDieChan,
		cli:             client,
	}

	sd.configure()

	return sd, nil
}
922441
func (s *MockDiscoveryServer) Discover(ctx context.Context, request *discovery.SignedRequest) (*discovery.Response, error) {
	if request == nil {
		return nil, errors.New("nil request")
	}

	req := &discovery.Request{}
	err := proto.Unmarshal(request.Payload, req)
	if err != nil {
		return nil, errors.Wrap(err, "failed parsing request")
	}
	if req.Authentication == nil {
		return nil, errors.New("access denied, no authentication info in request")
	}
	if len(req.Authentication.ClientIdentity) == 0 {
		return nil, errors.New("access denied, client identity wasn't supplied")
	}

	var results []*discovery.QueryResult
	for _, q := range req.Queries {
		result := s.processQuery(q)
		if result != nil {
			results = append(results, result)
		}
	}
	return &discovery.Response{
		Results: results,
	}, nil
}
972002
func handleAuthorizationCode(c context.Context, cfg *Settings, code string) (uid string, u *auth.User, err error) {
	if cfg.ClientID == "" || cfg.ClientSecret == "" || cfg.RedirectURI == "" {
		return "", nil, ErrNotConfigured
	}

	// Validate the discover doc has necessary fields to proceed.
	discovery, err := fetchDiscoveryDoc(c, cfg.DiscoveryURL)
	switch {
	case err != nil:
		return "", nil, err
	case discovery.TokenEndpoint == "":
		return "", nil, errors.New("openid: bad discovery doc, empty token_endpoint")
	}

	// Prepare a request to exchange authorization code for the ID token.
	v := url.Values{}
	v.Set("code", code)
	v.Set("client_id", cfg.ClientID)
	v.Set("client_secret", cfg.ClientSecret)
	v.Set("redirect_uri", cfg.RedirectURI)
	v.Set("grant_type", "authorization_code")
	payload := v.Encode()

	// Send POST to the token endpoint with URL-encoded parameters to get back the
	// ID token. There's more stuff in the reply, we don't need it.
	var token struct {
		IDToken string `json:"id_token"`
	}
	req := internal.Request{
		Method: "POST",
		URL:    discovery.TokenEndpoint,
		Body:   []byte(payload),
		Headers: map[string]string{
			"Content-Type": "application/x-www-form-urlencoded",
		},
		Out: &token,
	}
	if err := req.Do(c); err != nil {
		return "", nil, err
	}

	// Unpack the ID token to grab the user information from it.
	return userFromIDToken(c, token.IDToken, cfg, discovery)
}
1318811
func userFromIDToken(c context.Context, token string, cfg *Settings, discovery *discoveryDoc) (uid string, u *auth.User, err error) {
	// Validate the discovery doc has necessary fields to proceed.
	switch {
	case discovery.Issuer == "":
		return "", nil, errors.New("openid: bad discovery doc, empty issuer")
	case discovery.JwksURI == "":
		return "", nil, errors.New("openid: bad discovery doc, empty jwks_uri")
	}

	// Grab the signing keys needed to verify the token. This is almost always
	// hitting the local process cache and thus must be fast.
	signingKeys, err := discovery.signingKeys(c)
	if err != nil {
		return "", nil, err
	}

	// Unpack the ID token to grab the user information from it.
	verifiedToken, err := VerifyIDToken(c, token, signingKeys, discovery.Issuer, cfg.ClientID)
	if err != nil {
		return "", nil, err
	}

	// Ignore non https:// URLs for pictures. We serve all pages over HTTPS and
	// don't want to break this rule just for a pretty picture.
	picture := verifiedToken.Picture
	if picture != "" && !strings.HasPrefix(picture, "https://") {
		picture = ""
	}

	// Build the identity string from the email. This essentially validates it.
	id, err := identity.MakeIdentity("user:" + verifiedToken.Email)
	if err != nil {
		return "", nil, err
	}

	return verifiedToken.Sub, &auth.User{
		Identity: id,
		Email:    verifiedToken.Email,
		Name:     verifiedToken.Name,
		Picture:  picture,
	}, nil
}