1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
|
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...)
}
}
|