package cfg import ( "context" "crypto/tls" "crypto/x509" "encoding/pem" "io/ioutil" "net/http" "os" "path/filepath" "github.com/caddyserver/certmagic" "github.com/xlgmokha/x/pkg/x" "go.uber.org/zap" ) func WithSelfSigned(cert, key string) Option { certificate := x.Must(tls.LoadX509KeyPair(cert, key)) return func(config *Config) { config.TLS = &tls.Config{ MinVersion: tls.VersionTLS13, Certificates: []tls.Certificate{certificate}, } } } func WithTLS(domainNames []string) Option { directoryURL := "https://localhost:8081/acme/acme/directory" storage := &certmagic.FileStorage{ Path: filepath.Join(x.Must(os.Getwd()), "/tmp/cache"), } var cache *certmagic.Cache cache = certmagic.NewCache(certmagic.CacheOptions{ GetConfigForCert: func(cert certmagic.Certificate) (*certmagic.Config, error) { return certmagic.New(cache, certmagic.Config{ Logger: x.Must(zap.NewProduction()), OnDemand: new(certmagic.OnDemandConfig), Storage: storage, }), nil }, }) roots := x.Must(x509.SystemCertPool()) roots.AddCert(func() *x509.Certificate { block, _ := pem.Decode(x.Must(ioutil.ReadFile( filepath.Join(x.Must(os.Getwd()), "/tmp/step/certs/root_ca.crt"), ))) return x.Must(x509.ParseCertificate(block.Bytes)) }()) magic := certmagic.New(cache, certmagic.Config{ Logger: x.Must(zap.NewProduction()), OnDemand: new(certmagic.OnDemandConfig), Storage: storage, }) issuer := certmagic.NewACMEIssuer(magic, certmagic.ACMEIssuer{ Agreed: true, Email: "email@example.com", CA: directoryURL, TestCA: directoryURL, TrustedRoots: roots, }) magic.Issuers = []certmagic.Issuer{issuer} if err := http.ListenAndServe(":80", issuer.HTTPChallengeHandler(http.DefaultServeMux)); err != nil { return func(*Config) {} } x.Check(magic.ManageSync(context.Background(), domainNames)) return func(config *Config) { config.TLS = magic.TLSConfig() config.TLS.NextProtos = append([]string{"h2", "http/1.1"}, config.TLS.NextProtos...) } }