From 4d27620bf502549008290bf2034fc8b09e1a677a Mon Sep 17 00:00:00 2001 From: mo khan Date: Mon, 7 Apr 2025 14:30:30 -0600 Subject: chore: add tls config --- pkg/cfg/tls.go | 57 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) (limited to 'pkg/cfg') diff --git a/pkg/cfg/tls.go b/pkg/cfg/tls.go index 6441df8..bce6e18 100644 --- a/pkg/cfg/tls.go +++ b/pkg/cfg/tls.go @@ -1,9 +1,18 @@ 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 { @@ -16,3 +25,51 @@ func WithSelfSigned(cert, key string) Option { } } } + +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...) + } +} -- cgit v1.2.3