github.com/tickoalcantara12/micro/v3@v3.0.0-20221007104245-9d75b9bcbab9/util/acme/certmagic/certmagic.go (about) 1 // Copyright 2020 Asim Aslam 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // https://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 // 15 // Original source: github.com/micro/go-micro/v3/api/server/acme/certmagic/certmagic.go 16 17 // Package certmagic is the ACME provider from github.com/caddyserver/certmagic 18 package certmagic 19 20 import ( 21 "crypto/tls" 22 "math/rand" 23 "net" 24 "time" 25 26 "github.com/caddyserver/certmagic" 27 "github.com/tickoalcantara12/micro/v3/service/logger" 28 "github.com/tickoalcantara12/micro/v3/util/acme" 29 ) 30 31 type certmagicProvider struct { 32 opts acme.Options 33 } 34 35 // TODO: set self-contained options 36 func (c *certmagicProvider) setup() { 37 certmagic.DefaultACME.CA = c.opts.CA 38 if c.opts.ChallengeProvider != nil { 39 // Enabling DNS Challenge disables the other challenges 40 certmagic.DefaultACME.DNSProvider = c.opts.ChallengeProvider 41 } 42 if c.opts.OnDemand { 43 certmagic.Default.OnDemand = new(certmagic.OnDemandConfig) 44 } 45 if c.opts.Cache != nil { 46 // already validated by new() 47 certmagic.Default.Storage = c.opts.Cache.(certmagic.Storage) 48 } 49 // If multiple instances of the provider are running, inject some 50 // randomness so they don't collide 51 // RenewalWindowRatio [0.33 - 0.50) 52 rand.Seed(time.Now().UnixNano()) 53 randomRatio := float64(rand.Intn(17)+33) * 0.01 54 certmagic.Default.RenewalWindowRatio = randomRatio 55 } 56 57 func (c *certmagicProvider) Listen(hosts ...string) (net.Listener, error) { 58 c.setup() 59 return certmagic.Listen(hosts) 60 } 61 62 func (c *certmagicProvider) TLSConfig(hosts ...string) (*tls.Config, error) { 63 c.setup() 64 return certmagic.TLS(hosts) 65 } 66 67 // NewProvider returns a certmagic provider 68 func NewProvider(options ...acme.Option) acme.Provider { 69 opts := acme.DefaultOptions() 70 71 for _, o := range options { 72 o(&opts) 73 } 74 75 if opts.Cache != nil { 76 if _, ok := opts.Cache.(certmagic.Storage); !ok { 77 logger.Fatal("ACME: cache provided doesn't implement certmagic's Storage interface") 78 } 79 } 80 81 return &certmagicProvider{ 82 opts: opts, 83 } 84 }