// Present presents a challenge to obtain new ACME certificate.
186844
func (c *challengeHTTP) Present(domain, token, keyAuth string) error {
	return c.Store.SetHTTPChallengeToken(token, domain, []byte(keyAuth))
}
161956
func (d *DNSProvider) Present(domain, token, keyAuth string) error {
	if d.config.Mode == "RAW" {
		msg := &messageRaw{
			Domain:  domain,
			Token:   token,
			KeyAuth: keyAuth,
		}

		err := d.doPost("/present", msg)
		if err != nil {
			return fmt.Errorf("httpreq: %v", err)
		}
		return nil
	}

	fqdn, value := dns01.GetRecord(domain, keyAuth)
	msg := &message{
		FQDN:  fqdn,
		Value: value,
	}

	err := d.doPost("/present", msg)
	if err != nil {
		return fmt.Errorf("httpreq: %v", err)
	}
	return nil
}
1082686
func (d *DNSProvider) Present(domain, token, keyAuth string) error {
	fqdn, value := dns01.GetRecord(domain, keyAuth)

	// find authZone
	authZone, err := dns01.FindZoneByFqdn(fqdn)
	if err != nil {
		return fmt.Errorf("glesys: findZoneByFqdn failure: %v", err)
	}

	// determine name of TXT record
	if !strings.HasSuffix(
		strings.ToLower(fqdn), strings.ToLower("."+authZone)) {
		return fmt.Errorf("glesys: unexpected authZone %s for fqdn %s", authZone, fqdn)
	}
	name := fqdn[:len(fqdn)-len("."+authZone)]

	// acquire lock and check there is not a challenge already in
	// progress for this value of authZone
	d.inProgressMu.Lock()
	defer d.inProgressMu.Unlock()

	// add TXT record into authZone
	recordID, err := d.addTXTRecord(domain, dns01.UnFqdn(authZone), name, value, d.config.TTL)
	if err != nil {
		return err
	}

	// save data necessary for CleanUp
	d.activeRecords[fqdn] = recordID
	return nil
}
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)
}
728462
func (p *ecrProvider) Provide(image string) credentialprovider.DockerConfig {
	parsed, err := parseRepoURL(image)
	if err != nil {
		klog.V(3).Info(err)
		return credentialprovider.DockerConfig{}
	}

	if cfg, exists := p.getFromCache(parsed); exists {
		klog.V(6).Infof("Got ECR credentials from cache for %s", parsed.registry)
		return cfg
	}
	klog.V(3).Info("unable to get ECR credentials from cache, checking ECR API")

	cfg, err := p.getFromECR(parsed)
	if err != nil {
		klog.Errorf("error getting credentials from ECR for %s %v", parsed.registry, err)
		return credentialprovider.DockerConfig{}
	}
	klog.V(3).Infof("Got ECR credentials from ECR API for %s", parsed.registry)
	return cfg
}
331989
func (c *ACM) WaitUntilCertificateValidated(input *DescribeCertificateInput) error {
	return c.WaitUntilCertificateValidatedWithContext(aws.BackgroundContext(), input)
}
683246
func (d *DNSProvider) Present(domain, token, keyAuth string) error {
	ctx := context.Background()
	fqdn, value := dns01.GetRecord(domain, keyAuth)

	zone, err := d.getHostedZoneID(ctx, fqdn)
	if err != nil {
		return fmt.Errorf("azure: %v", err)
	}

	rsc := dns.NewRecordSetsClient(d.config.SubscriptionID)
	rsc.Authorizer = d.authorizer

	relative := toRelativeRecord(fqdn, dns01.ToFqdn(zone))

	// Get existing record set
	rset, err := rsc.Get(ctx, d.config.ResourceGroup, zone, relative, dns.TXT)
	if err != nil {
		detailedError, ok := err.(autorest.DetailedError)
		if !ok || detailedError.StatusCode != http.StatusNotFound {
			return fmt.Errorf("azure: %v", err)
		}
	}

	// Construct unique TXT records using map
	uniqRecords := map[string]struct{}{value: {}}
	if rset.RecordSetProperties != nil && rset.TxtRecords != nil {
		for _, txtRecord := range *rset.TxtRecords {
			// Assume Value doesn't contain multiple strings
			if txtRecord.Value != nil && len(*txtRecord.Value) > 0 {
				uniqRecords[(*txtRecord.Value)[0]] = struct{}{}
			}
		}
	}

	var txtRecords []dns.TxtRecord
	for txt := range uniqRecords {
		txtRecords = append(txtRecords, dns.TxtRecord{Value: &[]string{txt}})
	}

	rec := dns.RecordSet{
		Name: &relative,
		RecordSetProperties: &dns.RecordSetProperties{
			TTL:        to.Int64Ptr(int64(d.config.TTL)),
			TxtRecords: &txtRecords,
		},
	}

	_, err = rsc.CreateOrUpdate(ctx, d.config.ResourceGroup, zone, relative, dns.TXT, rec, "", "")
	if err != nil {
		return fmt.Errorf("azure: %v", err)
	}
	return nil
}
1239089
func (c *OpenidConfigurationController) Show(ctx *app.ShowOpenidConfigurationContext) error {

	issuer := rest.AbsoluteURL(ctx.RequestData, "", nil)
	authorizationEndpoint := rest.AbsoluteURL(ctx.RequestData, client.AuthorizeAuthorizePath(), nil)
	tokenEndpoint := rest.AbsoluteURL(ctx.RequestData, client.ExchangeTokenPath(), nil)
	userinfoEndpoint := rest.AbsoluteURL(ctx.RequestData, client.ShowUserinfoPath(), nil)
	logoutEndpoint := rest.AbsoluteURL(ctx.RequestData, client.LogoutLogoutPath(), nil)
	jwksURI := rest.AbsoluteURL(ctx.RequestData, client.KeysTokenPath(), nil)

	authOpenIDConfiguration := &app.OpenIDConfiguration{
		// REQUIRED properties
		Issuer:                 &issuer,
		AuthorizationEndpoint:  &authorizationEndpoint,
		TokenEndpoint:          &tokenEndpoint,
		EndSessionEndpoint:     &logoutEndpoint,
		ResponseTypesSupported: []string{"code"},
		JwksURI:                &jwksURI,

		// subject_types_supported REQUIRED. JSON array containing a list of the Subject Identifier types that this OP supports. Valid types include pairwise and public.
		// A Subject Identifier is a locally unique and never reassigned identifier within the Issuer for the End-User, which is intended to be consumed by the Client.
		// http://openid.net/specs/openid-connect-core-1_0.html#SubjectIDTypes
		// subject ==  identity
		SubjectTypesSupported: []string{"public"},
		// id_token_signing_alg_values_supported REQUIRED. JSON array containing a list of the JWS signing algorithms (alg values) supported by the OP for the ID Token to encode the Claims in a JWT [JWT].
		// The algorithm RS256 MUST be included. The value none MAY be supported, but MUST NOT be used unless the Response Type used returns no ID Token from the Authorization Endpoint (such as when using the Authorization Code Flow).
		IDTokenSigningAlgValuesSupported: []string{"RS256"},

		// RECOMMENDED properties
		UserinfoEndpoint: &userinfoEndpoint,
		ScopesSupported:  []string{"openid", "offline_access"},
		ClaimsSupported:  []string{"sub", "iss", "auth_time", "name", "given_name", "family_name", "preferred_username", "email"},

		// OPTIONAL properties
		GrantTypesSupported: []string{"authorization_code", "refresh_token", "client_credentials"},
		// client_secret_post for client_credentials grant_type
		// client_secre_jwt for authorizatoin_code grant_type
		TokenEndpointAuthMethodsSupported: []string{"client_secret_post", "client_secret_jwt"},
		// response_modes_supported
	}

	return ctx.OK(authOpenIDConfiguration)
}
650317
func (c *IterationController) Show(ctx *app.ShowIterationContext) error {
	id, err := uuid.FromString(ctx.IterationID)
	if err != nil {
		return jsonapi.JSONErrorResponse(ctx, goa.ErrNotFound(err.Error()))
	}
	var itr *iteration.Iteration
	err = application.Transactional(c.db, func(appl application.Application) error {
		itr, err = appl.Iterations().Load(ctx, id)
		return err
	})
	if err != nil {
		return jsonapi.JSONErrorResponse(ctx, err)
	}
	return ctx.ConditionalRequest(*itr, c.config.GetCacheControlIteration, func() error {
		var wiCounts map[string]workitem.WICountsPerIteration
		var parentItrs []iteration.Iteration
		err := application.Transactional(c.db, func(appl application.Application) error {
			var err error
			wiCounts, err = appl.WorkItems().GetCountsForIteration(ctx, itr)
			if err != nil {
				return err
			}
			parentItrs, err = appl.Iterations().LoadMultiple(ctx, itr.Path)
			return err
		})
		if err != nil {
			return jsonapi.JSONErrorResponse(ctx, err)
		}
		itrMap := make(iterationIDMap)
		for _, itr := range parentItrs {
			itrMap[itr.ID] = itr
		}
		return ctx.OK(&app.IterationSingle{
			Data: ConvertIteration(ctx.Request, *itr, parentPathResolver(itrMap), updateIterationsWithCounts(wiCounts)),
		})
	})
}
693784
func (i *CredentialIter) Current() (*Credential, error) {
	if i.err != nil {
		return nil, i.err
	}
	return &i.page[i.i], nil
}
1260395
func (d *DNSProvider) Present(domain, token, keyAuth string) error {
	fqdn, value := dns01.GetRecord(domain, keyAuth)

	zone, err := d.client.GetZone(fqdn)
	if err != nil {
		return fmt.Errorf("ClouDNS: %v", err)
	}

	err = d.client.AddTxtRecord(zone.Name, fqdn, value, d.config.TTL)
	if err != nil {
		return fmt.Errorf("ClouDNS: %v", err)
	}

	return nil
}
88879
func (ctx *Ctx) CurrentDevice() (device Device, err error) {
	return ctx.device, nil
}
323826
func (ca *MockCA) IssueCertificate(ctx context.Context, _ *caPB.IssueCertificateRequest) (core.Certificate, error) {
	if ca.PEM == nil {
		return core.Certificate{}, fmt.Errorf("MockCA's PEM field must be set before calling IssueCertificate")
	}
	block, _ := pem.Decode(ca.PEM)
	cert, err := x509.ParseCertificate(block.Bytes)
	if err != nil {
		return core.Certificate{}, err
	}
	return core.Certificate{
		DER: cert.Raw,
	}, nil
}
1302186
func (s *DirectMessageService) Show(id int64) (*DirectMessage, *http.Response, error) {
	params := &directMessageShowParams{ID: id}
	dm := new(DirectMessage)
	apiError := new(APIError)
	resp, err := s.sling.New().Get("show.json").QueryStruct(params).Receive(dm, apiError)
	return dm, resp, relevantError(err, *apiError)
}
1189298
func (d *DNSProvider) Present(domain, token, keyAuth string) error {
	fqdn, value := dns01.GetRecord(domain, keyAuth)

	zone, err := d.getHostedZone(fqdn)
	if err != nil {
		return fmt.Errorf("googlecloud: %v", err)
	}

	// Look for existing records.
	existingRrSet, err := d.findTxtRecords(zone, fqdn)
	if err != nil {
		return fmt.Errorf("googlecloud: %v", err)
	}

	for _, rrSet := range existingRrSet {
		var rrd []string
		for _, rr := range rrSet.Rrdatas {
			data := mustUnquote(rr)
			rrd = append(rrd, data)

			if data == value {
				log.Printf("skip: the record already exists: %s", value)
				return nil
			}
		}
		rrSet.Rrdatas = rrd
	}

	// Attempt to delete the existing records before adding the new one.
	if len(existingRrSet) > 0 {
		if err = d.applyChanges(zone, &dns.Change{Deletions: existingRrSet}); err != nil {
			return fmt.Errorf("googlecloud: %v", err)
		}
	}

	rec := &dns.ResourceRecordSet{
		Name:    fqdn,
		Rrdatas: []string{value},
		Ttl:     int64(d.config.TTL),
		Type:    "TXT",
	}

	// Append existing TXT record data to the new TXT record data
	for _, rrSet := range existingRrSet {
		for _, rr := range rrSet.Rrdatas {
			if rr != value {
				rec.Rrdatas = append(rec.Rrdatas, rr)
			}
		}
	}

	change := &dns.Change{
		Additions: []*dns.ResourceRecordSet{rec},
	}

	if err = d.applyChanges(zone, change); err != nil {
		return fmt.Errorf("googlecloud: %v", err)
	}

	return nil
}
218679
func (d *DNSProvider) Present(domain, token, keyAuth string) error {
	fqdn, value := dns01.GetRecord(domain, keyAuth)

	authZone, err := dns01.FindZoneByFqdn(fqdn)
	if err != nil {
		return fmt.Errorf("cloudflare: %v", err)
	}

	zoneID, err := d.client.ZoneIDByName(dns01.UnFqdn(authZone))
	if err != nil {
		return fmt.Errorf("cloudflare: failed to find zone %s: %v", authZone, err)
	}

	dnsRecord := cloudflare.DNSRecord{
		Type:    "TXT",
		Name:    dns01.UnFqdn(fqdn),
		Content: value,
		TTL:     d.config.TTL,
	}

	response, err := d.client.CreateDNSRecord(zoneID, dnsRecord)
	if err != nil {
		return fmt.Errorf("cloudflare: failed to create TXT record: %v", err)
	}

	if !response.Success {
		return fmt.Errorf("cloudflare: failed to create TXT record: %+v %+v", response.Errors, response.Messages)
	}

	log.Infof("cloudflare: new record for %s, ID %s", domain, response.Result.ID)

	return nil
}
576568
func (w *HTTPProvider) Present(domain, token, keyAuth string) error {
	var err error

	challengeFilePath := filepath.Join(w.path, http01.ChallengePath(token))
	err = os.MkdirAll(filepath.Dir(challengeFilePath), 0755)
	if err != nil {
		return fmt.Errorf("could not create required directories in webroot for HTTP challenge -> %v", err)
	}

	err = ioutil.WriteFile(challengeFilePath, []byte(keyAuth), 0644)
	if err != nil {
		return fmt.Errorf("could not write file in webroot for HTTP challenge -> %v", err)
	}

	return nil
}