// FindChallenge will look for the given challenge inside this authorization. If
// found, it will return the index of that challenge within the Authorization's
// Challenges array. Otherwise it will return -1.
509757
func (authz *Authorization) FindChallenge(challengeID int64) int {
	for i, c := range authz.Challenges {
		if c.ID == challengeID {
			return i
		}
	}
	return -1
}
191313
func (s *InitiateAuthOutput) SetChallengeParameters(v map[string]*string) *InitiateAuthOutput {
	s.ChallengeParameters = v
	return s
}
9766
func (t *LaunchTemplate) Find(c *fi.Context) (*LaunchTemplate, error) {
	cloud, ok := c.Cloud.(awsup.AWSCloud)
	if !ok {
		return nil, fmt.Errorf("invalid cloud provider: %v, expected: %s", c.Cloud, "awsup.AWSCloud")
	}

	// @step: get the latest launch template version
	lt, err := t.findLatestLaunchTemplate(c)
	if err != nil {
		return nil, err
	}
	if lt == nil {
		return nil, nil
	}

	glog.V(3).Infof("found existing LaunchTemplate: %s", fi.StringValue(lt.LaunchTemplateName))

	actual := &LaunchTemplate{
		AssociatePublicIP:      fi.Bool(false),
		ID:                     lt.LaunchTemplateName,
		ImageID:                lt.LaunchTemplateData.ImageId,
		InstanceMonitoring:     fi.Bool(false),
		InstanceType:           lt.LaunchTemplateData.InstanceType,
		Lifecycle:              t.Lifecycle,
		Name:                   t.Name,
		RootVolumeOptimization: lt.LaunchTemplateData.EbsOptimized,
	}

	// @step: check if any of the interfaces are public facing
	for _, x := range lt.LaunchTemplateData.NetworkInterfaces {
		if aws.BoolValue(x.AssociatePublicIpAddress) {
			actual.AssociatePublicIP = fi.Bool(true)
			// @note: not sure i like this https://github.com/hashicorp/terraform/issues/2998
			for _, id := range x.Groups {
				actual.SecurityGroups = append(actual.SecurityGroups, &SecurityGroup{ID: id})
			}
		}
	}
	// @step: add at the security groups
	for _, id := range lt.LaunchTemplateData.SecurityGroupIds {
		actual.SecurityGroups = append(actual.SecurityGroups, &SecurityGroup{ID: id})
	}
	sort.Sort(OrderSecurityGroupsById(actual.SecurityGroups))

	// @step: check if monitoring it enabled
	if lt.LaunchTemplateData.Monitoring != nil {
		actual.InstanceMonitoring = lt.LaunchTemplateData.Monitoring.Enabled
	}
	// @step: add the tenancy
	if lt.LaunchTemplateData.Placement != nil {
		actual.Tenancy = lt.LaunchTemplateData.Placement.Tenancy
	}
	// @step: add the ssh if there is one
	if lt.LaunchTemplateData.KeyName != nil {
		actual.SSHKey = &SSHKey{Name: lt.LaunchTemplateData.KeyName}
	}
	// @step: add a instance if there is one
	if lt.LaunchTemplateData.IamInstanceProfile != nil {
		actual.IAMInstanceProfile = &IAMInstanceProfile{Name: lt.LaunchTemplateData.IamInstanceProfile.Name}
	}

	// @step: get the image is order to find out the root device name as using the index
	// is not vaiable, under conditions they move
	image, err := cloud.ResolveImage(fi.StringValue(t.ImageID))
	if err != nil {
		return nil, err
	}

	// @step: find the root volume
	for _, b := range lt.LaunchTemplateData.BlockDeviceMappings {
		if b.Ebs == nil {
			continue
		}
		if b.DeviceName != nil && fi.StringValue(b.DeviceName) == fi.StringValue(image.RootDeviceName) {
			actual.RootVolumeSize = b.Ebs.VolumeSize
			actual.RootVolumeType = b.Ebs.VolumeType
			actual.RootVolumeIops = b.Ebs.Iops
		} else {
			_, d := BlockDeviceMappingFromLaunchTemplateBootDeviceRequest(b)
			actual.BlockDeviceMappings = append(actual.BlockDeviceMappings, d)
		}
	}

	if lt.LaunchTemplateData.UserData != nil {
		ud, err := base64.StdEncoding.DecodeString(aws.StringValue(lt.LaunchTemplateData.UserData))
		if err != nil {
			return nil, fmt.Errorf("error decoding userdata: %s", err)
		}
		actual.UserData = fi.WrapResource(fi.NewStringResource(string(ud)))
	}

	// @step: to avoid spurious changes on ImageId
	if t.ImageID != nil && actual.ImageID != nil && *actual.ImageID != *t.ImageID {
		image, err := cloud.ResolveImage(*t.ImageID)
		if err != nil {
			glog.Warningf("unable to resolve image: %q: %v", *t.ImageID, err)
		} else if image == nil {
			glog.Warningf("unable to resolve image: %q: not found", *t.ImageID)
		} else if aws.StringValue(image.ImageId) == *actual.ImageID {
			glog.V(4).Infof("Returning matching ImageId as expected name: %q -> %q", *actual.ImageID, *t.ImageID)
			actual.ImageID = t.ImageID
		}
	}

	if t.ID == nil {
		t.ID = actual.ID
	}

	return actual, nil
}
427804
func (contracts *Contracts) FindContract(id string) (*Contract, error) {
	var contract *Contract
	var contractFound bool
	for _, contract = range contracts.Contracts.Items {
		if contract.ContractID == id {
			contractFound = true
			break
		}
	}

	if !contractFound {
		return nil, fmt.Errorf("Unable to find contract: \"%s\"", id)
	}

	return contract, nil
}
1283802
func (s *AuthorizationService) FindAuthorizations(ctx context.Context, filter platform.AuthorizationFilter, opt ...platform.FindOptions) (as []*platform.Authorization, i int, err error) {
	defer func() {
		if err != nil {
			s.Logger.Info("error finding authorizations", zap.Error(err))
		}
	}()

	return s.AuthorizationService.FindAuthorizations(ctx, filter, opt...)
}
1241446
func parseAuthChallenge(header string) (string, map[string]string) {
	sections := strings.SplitN(header, " ", 2)
	if len(sections) == 1 {
		sections = append(sections, "")
	}
	challenge := sections[1]
	keys := make(map[string]string)
	for _, s := range strings.Split(challenge, ",") {
		pair := strings.SplitN(strings.TrimSpace(s), "=", 2)
		if len(pair) == 1 {
			keys[pair[0]] = ""
			continue
		}
		keys[pair[0]] = strings.Trim(pair[1], "\"")
	}
	return sections[0], keys
}
707199
func (r *redirector) AuthenticationChallenge(req *http.Request) (http.Header, error) {
	redirectURL, err := buildRedirectURL(r.RedirectURL, r.BaseRequestURL, req.URL)
	if err != nil {
		return nil, err
	}
	headers := http.Header{}
	headers.Add("Location", redirectURL.String())
	return headers, nil
}
1225432
func IsValidChallenge(challenge string) bool {
	if len(challenge) != ChallengeLengthString {
		return false
	}
	if _, err := hex.DecodeString(challenge); err != nil {
		return false
	}
	return true
}
516270
func (s *ProbesService) Find(k ProbeKey) (ProbeInfoDTO, *http.Response, error) {
	var t ProbeInfoDTO
	res, err := s.client.get(k.URI(), &t)
	return t, res, err
}
876188
func (authz *Authorization) FindChallengeByStringID(id string) int {
	for i, c := range authz.Challenges {
		if c.StringID() == id {
			return i
		}
	}
	return -1
}
250723
func (ch Challenge) CheckConsistencyForValidation() error {
	if err := ch.checkConsistency(); err != nil {
		return err
	}

	// If the challenge is completed, then there should be a key authorization
	return looksLikeKeyAuthorization(ch.ProvidedKeyAuthorization)
}
477384
func (c *CredentialsClient) Search(ctx context.Context, pathexp string, teamIDs []identity.ID, p ProgressFunc) ([]apitypes.CredentialEnvelope, error) {
	v := &url.Values{}
	v.Set("pathexp", pathexp)
	v.Set("skip-decryption", "true")

	for _, id := range teamIDs {
		v.Add("team_id", id.String())
	}

	return c.listWorker(ctx, v, p)
}
158027
func (s *AuthorizationService) FindAuthorizations(ctx context.Context, filter platform.AuthorizationFilter, opt ...platform.FindOptions) (as []*platform.Authorization, i int, err error) {
	defer func(start time.Time) {
		labels := prometheus.Labels{
			"method": "FindAuthorizations",
			"error":  fmt.Sprint(err != nil),
		}
		s.requestCount.With(labels).Add(1)
		s.requestDuration.With(labels).Observe(time.Since(start).Seconds())
	}(time.Now())

	return s.AuthorizationService.FindAuthorizations(ctx, filter, opt...)
}
877317
func (ra *RegistrationAuthorityImpl) PerformValidation(
	ctx context.Context,
	req *rapb.PerformValidationRequest) (*corepb.Authorization, error) {
	base, err := bgrpc.PBToAuthz(req.Authz)
	if err != nil {
		return nil, err
	}

	// Refuse to update expired authorizations
	if base.Expires == nil || base.Expires.Before(ra.clk.Now()) {
		return nil, berrors.MalformedError("expired authorization")
	}

	authz := base
	challIndex := int(*req.ChallengeIndex)
	if challIndex >= len(authz.Challenges) {
		return nil,
			berrors.MalformedError("invalid challenge index '%d'", challIndex)
	}

	ch := &authz.Challenges[challIndex]

	// This challenge type may have been disabled since the challenge was created.
	if !ra.PA.ChallengeTypeEnabled(ch.Type) {
		return nil, berrors.MalformedError("challenge type %q no longer allowed", ch.Type)
	}

	// When configured with `reuseValidAuthz` we can expect some clients to try
	// and update a challenge for an authorization that is already valid. In this
	// case we don't need to process the challenge update. It wouldn't be helpful,
	// the overall authorization is already good! We increment a stat for this
	// case and return early.
	if ra.reuseValidAuthz && authz.Status == core.StatusValid {
		ra.stats.Inc("ReusedValidAuthzChallenge", 1)
		return req.Authz, nil
	}

	if authz.Status != core.StatusPending {
		return nil, berrors.WrongAuthorizationStateError("authorization must be pending")
	}

	// Look up the account key for this authorization
	reg, err := ra.SA.GetRegistration(ctx, authz.RegistrationID)
	if err != nil {
		return nil, berrors.InternalServerError(err.Error())
	}

	// Compute the key authorization field based on the registration key
	expectedKeyAuthorization, err := ch.ExpectedKeyAuthorization(reg.Key)
	if err != nil {
		return nil, berrors.InternalServerError("could not compute expected key authorization value")
	}

	// Populate the ProvidedKeyAuthorization such that the VA can confirm the
	// expected vs actual without needing the registration key. Historically this
	// was done with the value from the challenge response and so the field name
	// is called "ProvidedKeyAuthorization", in reality this is just
	// "KeyAuthorization".
	// TODO(@cpu): Rename ProvidedKeyAuthorization to KeyAuthorization
	ch.ProvidedKeyAuthorization = expectedKeyAuthorization

	// Double check before sending to VA
	if cErr := ch.CheckConsistencyForValidation(); cErr != nil {
		return nil, berrors.MalformedError(cErr.Error())
	}

	ra.stats.Inc("NewPendingAuthorizations", 1)

	// Dispatch to the VA for service
	vaCtx := context.Background()
	go func(authz core.Authorization) {
		// We will mutate challenges later in this goroutine to change status and
		// add error, but we also return a copy of authz immediately. To avoid a
		// data race, make a copy of the challenges slice here for mutation.
		challenges := make([]core.Challenge, len(authz.Challenges))
		copy(challenges, authz.Challenges)
		authz.Challenges = challenges

		records, err := ra.VA.PerformValidation(vaCtx, authz.Identifier.Value, authz.Challenges[challIndex], authz)
		var prob *probs.ProblemDetails
		if p, ok := err.(*probs.ProblemDetails); ok {
			prob = p
		} else if err != nil {
			prob = probs.ServerInternal("Could not communicate with VA")
			ra.log.AuditErrf("Could not communicate with VA: %s", err)
		}

		// Save the updated records
		challenge := &authz.Challenges[challIndex]
		challenge.ValidationRecord = records

		if !challenge.RecordsSane() && prob == nil {
			prob = probs.ServerInternal("Records for validation failed sanity check")
		}

		if prob != nil {
			challenge.Status = core.StatusInvalid
			challenge.Error = prob
		} else {
			challenge.Status = core.StatusValid
		}
		authz.Challenges[challIndex] = *challenge

		err = ra.onValidationUpdate(vaCtx, authz)
		if err != nil {
			ra.log.AuditErrf("Could not record updated validation: err=[%s] regID=[%d] authzID=[%s]",
				err, authz.RegistrationID, authz.ID)
		}
	}(authz)
	ra.stats.Inc("UpdatedPendingAuthorizations", 1)
	return bgrpc.AuthzToPB(authz)
}
447617
func (p *DB) findGE(key []byte, prev bool) (int, bool) {
	node := 0
	h := p.maxHeight - 1
	for {
		next := p.nodeData[node+nNext+h]
		cmp := 1
		if next != 0 {
			o := p.nodeData[next]
			cmp = p.cmp.Compare(p.kvData[o:o+p.nodeData[next+nKey]], key)
		}
		if cmp < 0 {
			// Keep searching in this list
			node = next
		} else {
			if prev {
				p.prevNode[h] = node
			} else if cmp == 0 {
				return next, true
			}
			if h == 0 {
				return next, cmp == 0
			}
			h--
		}
	}
}
900018
func (c placeholderChallenger) AuthenticationChallenge(req *http.Request) (http.Header, error) {
	headers := http.Header{}
	headers.Add("Warning",
		fmt.Sprintf(
			`%s %s "You must obtain an API token by visiting %s"`,
			oauthhandlers.WarningHeaderMiscCode,
			oauthhandlers.WarningHeaderOpenShiftSource,
			c.tokenRequestURL,
		),
	)
	headers.Add("Link", fmt.Sprintf(`<%s>; rel="related"`, c.tokenRequestURL))

	return headers, nil
}
380451
func (s *AdminRespondToAuthChallengeOutput) SetChallengeParameters(v map[string]*string) *AdminRespondToAuthChallengeOutput {
	s.ChallengeParameters = v
	return s
}