// prepChallengeForDisplay takes a core.Challenge and prepares it for display to
// the client by filling in its URL field and clearing its ID and URI fields.
551258
func (wfe *WebFrontEndImpl) prepChallengeForDisplay(request *http.Request, authz core.Authorization, challenge *core.Challenge) {
	// Update the challenge URL to be relative to the HTTP request Host
	if authz.V2 {
		challenge.URL = web.RelativeEndpoint(request, fmt.Sprintf("%sv2/%s/%s", challengePath, authz.ID, challenge.StringID()))
	} else {
		challenge.URL = web.RelativeEndpoint(request, fmt.Sprintf("%s%s/%d", challengePath, authz.ID, challenge.ID))
	}
	// Ensure the challenge URI and challenge ID aren't written by setting them to
	// values that the JSON omitempty tag considers empty
	challenge.URI = ""
	challenge.ID = 0

	// ACMEv2 never sends the KeyAuthorization back in a challenge object.
	challenge.ProvidedKeyAuthorization = ""

	// Historically the Type field of a problem was always prefixed with a static
	// error namespace. To support the V2 API and migrating to the correct IETF
	// namespace we now prefix the Type with the correct namespace at runtime when
	// we write the problem JSON to the user. We skip this process if the
	// challenge error type has already been prefixed with the V1ErrorNS.
	if challenge.Error != nil && !strings.HasPrefix(string(challenge.Error.Type), probs.V1ErrorNS) {
		challenge.Error.Type = probs.V2ErrorNS + challenge.Error.Type
	}

	// If the authz has been marked invalid, consider all challenges on that authz
	// to be invalid as well.
	if authz.Status == core.StatusInvalid {
		challenge.Status = authz.Status
	}
}
191313
func (s *InitiateAuthOutput) SetChallengeParameters(v map[string]*string) *InitiateAuthOutput {
	s.ChallengeParameters = v
	return s
}
509757
func (authz *Authorization) FindChallenge(challengeID int64) int {
	for i, c := range authz.Challenges {
		if c.ID == challengeID {
			return i
		}
	}
	return -1
}
365161
func (s *GetPlaybackConfigurationOutput) SetPlaybackEndpointPrefix(v string) *GetPlaybackConfigurationOutput {
	s.PlaybackEndpointPrefix = &v
	return s
}
1204748
func (resourcequotaStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object) {
	newResourcequota := obj.(*api.ResourceQuota)
	oldResourcequota := old.(*api.ResourceQuota)
	newResourcequota.Status = oldResourcequota.Status
	resourcequotautil.DropDisabledFields(&newResourcequota.Spec, &oldResourcequota.Spec)
}
882757
func (o *AcceptLoginRequestParams) WithLoginChallenge(loginChallenge string) *AcceptLoginRequestParams {
	o.SetLoginChallenge(loginChallenge)
	return o
}
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)
}
1138850
func (w *upgradeSeriesWorker) handlePrepareStarted() error {
	var err error
	if !w.leadersPinned {
		if err = w.pinLeaders(); err != nil {
			return errors.Trace(err)
		}
	}

	if w.preparedUnits, err = w.UnitsPrepared(); err != nil {
		return errors.Trace(err)
	}

	unitServices, allConfirmed, err := w.compareUnitAgentServices(w.preparedUnits)
	if err != nil {
		return errors.Trace(err)
	}
	if !allConfirmed {
		w.logger.Debugf(
			"waiting for units to complete series upgrade preparation; known unit agent services: %s",
			unitNames(unitServices),
		)
		return nil
	}

	return errors.Trace(w.transitionPrepareComplete(unitServices))
}
275092
func (s *PutPlaybackConfigurationOutput) SetPlaybackEndpointPrefix(v string) *PutPlaybackConfigurationOutput {
	s.PlaybackEndpointPrefix = &v
	return s
}
900650
func newChallenge(domain, keyAuth string, tlds map[string]string) (*challenge, error) {
	domain = dns01.UnFqdn(domain)
	parts := strings.Split(domain, ".")

	// Find the longest matching TLD.
	longest := -1
	for i := len(parts); i > 0; i-- {
		t := strings.Join(parts[i-1:], ".")
		if _, found := tlds[t]; found {
			longest = i - 1
		}
	}
	if longest < 1 {
		return nil, fmt.Errorf("invalid domain name %q", domain)
	}

	tld := strings.Join(parts[longest:], ".")
	sld := parts[longest-1]

	var host string
	if longest >= 1 {
		host = strings.Join(parts[:longest-1], ".")
	}

	fqdn, value := dns01.GetRecord(domain, keyAuth)

	return &challenge{
		domain:   domain,
		key:      "_acme-challenge." + host,
		keyFqdn:  fqdn,
		keyValue: value,
		tld:      tld,
		sld:      sld,
		host:     host,
	}, nil
}
1307033
func (s *LocalStore) RemoveHTTPChallengeToken(token, domain string) error {
	s.lock.Lock()
	defer s.lock.Unlock()

	if s.storedData.HTTPChallenges == nil {
		return nil
	}

	if _, ok := s.storedData.HTTPChallenges[token]; ok {
		delete(s.storedData.HTTPChallenges[token], domain)
		if len(s.storedData.HTTPChallenges[token]) == 0 {
			delete(s.storedData.HTTPChallenges, token)
		}
	}
	return nil
}
1111827
func (c *Client) Challenge(chalURI string) (Challenge, error) {
	var chal Challenge
	resp, err := c.client.Get(chalURI)
	if err != nil {
		return chal, err
	}
	defer resp.Body.Close()
	if err = checkHTTPError(resp, http.StatusAccepted); err != nil {
		return chal, err
	}

	if err := json.NewDecoder(resp.Body).Decode(&chal); err != nil {
		return chal, fmt.Errorf("decoding response body: %v", err)
	}
	return chal, nil
}
876188
func (authz *Authorization) FindChallengeByStringID(id string) int {
	for i, c := range authz.Challenges {
		if c.StringID() == id {
			return i
		}
	}
	return -1
}
427767
func (h *basicPasswordAuthHandler) AuthenticationChallenge(req *http.Request) (http.Header, error) {
	headers := http.Header{}

	if len(req.Header.Get(CSRFTokenHeader)) == 0 {
		headers.Add("Warning",
			fmt.Sprintf(
				`%s %s "A non-empty %s header is required to receive basic-auth challenges"`,
				oauthhandlers.WarningHeaderMiscCode,
				oauthhandlers.WarningHeaderOpenShiftSource,
				CSRFTokenHeader,
			),
		)
	} else {
		headers.Add("WWW-Authenticate", fmt.Sprintf(`Basic realm="%s"`, h.realm))
	}

	return headers, nil
}
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
}
703636
func (ra *RegistrationAuthorityImpl) authzValidChallengeEnabled(authz *core.Authorization) bool {
	for _, chall := range authz.Challenges {
		if chall.Status == core.StatusValid {
			return ra.PA.ChallengeTypeEnabled(chall.Type)
		}
	}
	return false
}
54618
func (podDisruptionBudgetStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object) {
	newPodDisruptionBudget := obj.(*policy.PodDisruptionBudget)
	oldPodDisruptionBudget := old.(*policy.PodDisruptionBudget)
	// Update is not allowed to set status
	newPodDisruptionBudget.Status = oldPodDisruptionBudget.Status

	// Any changes to the spec increment the generation number, any changes to the
	// status should reflect the generation number of the corresponding object.
	// See metav1.ObjectMeta description for more information on Generation.
	if !apiequality.Semantic.DeepEqual(oldPodDisruptionBudget.Spec, newPodDisruptionBudget.Spec) {
		newPodDisruptionBudget.Generation = oldPodDisruptionBudget.Generation + 1
	}
}