github.com/btccom/go-micro/v2@v2.9.3/api/server/acme/certmagic/certmagic.go (about)

     1  // Package certmagic is the ACME provider from github.com/caddyserver/certmagic
     2  package certmagic
     3  
     4  import (
     5  	"crypto/tls"
     6  	"math/rand"
     7  	"net"
     8  	"time"
     9  
    10  	"github.com/caddyserver/certmagic"
    11  	"github.com/btccom/go-micro/v2/api/server/acme"
    12  	"github.com/btccom/go-micro/v2/logger"
    13  )
    14  
    15  type certmagicProvider struct {
    16  	opts acme.Options
    17  }
    18  
    19  // TODO: set self-contained options
    20  func (c *certmagicProvider) setup() {
    21  	certmagic.DefaultACME.CA = c.opts.CA
    22  	if c.opts.ChallengeProvider != nil {
    23  		// Enabling DNS Challenge disables the other challenges
    24  		certmagic.DefaultACME.DNSProvider = c.opts.ChallengeProvider
    25  	}
    26  	if c.opts.OnDemand {
    27  		certmagic.Default.OnDemand = new(certmagic.OnDemandConfig)
    28  	}
    29  	if c.opts.Cache != nil {
    30  		// already validated by new()
    31  		certmagic.Default.Storage = c.opts.Cache.(certmagic.Storage)
    32  	}
    33  	// If multiple instances of the provider are running, inject some
    34  	// randomness so they don't collide
    35  	// RenewalWindowRatio [0.33 - 0.50)
    36  	rand.Seed(time.Now().UnixNano())
    37  	randomRatio := float64(rand.Intn(17)+33) * 0.01
    38  	certmagic.Default.RenewalWindowRatio = randomRatio
    39  }
    40  
    41  func (c *certmagicProvider) Listen(hosts ...string) (net.Listener, error) {
    42  	c.setup()
    43  	return certmagic.Listen(hosts)
    44  }
    45  
    46  func (c *certmagicProvider) TLSConfig(hosts ...string) (*tls.Config, error) {
    47  	c.setup()
    48  	return certmagic.TLS(hosts)
    49  }
    50  
    51  // NewProvider returns a certmagic provider
    52  func NewProvider(options ...acme.Option) acme.Provider {
    53  	opts := acme.DefaultOptions()
    54  
    55  	for _, o := range options {
    56  		o(&opts)
    57  	}
    58  
    59  	if opts.Cache != nil {
    60  		if _, ok := opts.Cache.(certmagic.Storage); !ok {
    61  			logger.Fatal("ACME: cache provided doesn't implement certmagic's Storage interface")
    62  		}
    63  	}
    64  
    65  	return &certmagicProvider{
    66  		opts: opts,
    67  	}
    68  }