aboutsummaryrefslogtreecommitdiff
path: root/clients/autocert/autocert_wrapper.go
blob: b174a621e3f24f6f5316c2136c39b2c6a3a01350 (plain)
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package autocert

import (
	"context"
	"crypto/tls"
	"sync"

	"code.crute.us/mcrute/golib/clients/dns"
	glautocert "code.crute.us/mcrute/golib/crypto/acme/autocert"
	fautocert "code.crute.us/mcrute/golib/crypto/acme/autocert/fork"
	"code.crute.us/mcrute/golib/log"
	"code.crute.us/mcrute/golib/service"
)

type AutocertConfig struct {
	ApiKey   string
	Hosts    []string
	Email    string
	CertHost string
}

type AutocertWrapper struct {
	*fautocert.Manager
	hostList      *glautocert.ACMEHostList
	primingNotify chan string
	primaryHost   string
}

func MustNewAutocertWrapper(ctx context.Context, c AutocertConfig) *AutocertWrapper {
	w, err := NewAutocertWrapper(ctx, c)
	if err != nil {
		panic(err)
	}
	return w
}

func NewAutocertWrapper(ctx context.Context, c AutocertConfig) (*AutocertWrapper, error) {
	hostList := glautocert.NewACMEHostList(c.Hosts...)
	return &AutocertWrapper{
		hostList:      hostList,
		primingNotify: make(chan string, 10),
		primaryHost:   c.Hosts[0],
		Manager: &fautocert.Manager{
			Cache:      fautocert.DirCache("ssl/"),
			Prompt:     fautocert.AcceptTOS,
			HostPolicy: hostList.HostPolicy,
			Email:      c.Email,
			StapleOCSP: true,
			DNSManager: &dns.AcmeDNSServiceClient{
				URL:    c.CertHost,
				ApiKey: c.ApiKey,
			},
		},
	}, nil
}

func (w *AutocertWrapper) GetCertificate(hello *tls.ClientHelloInfo) (*tls.Certificate, error) {
	h := *hello

	// Override a blank SNI ServerName with the first host in the allowed
	// host list rather than erroring out. This allows users to hit the
	// server by IP and use a Host header while still getting content and
	// is consistent with nginx behavior.
	if h.ServerName == "" {
		h.ServerName = w.primaryHost
	}

	return w.Manager.GetCertificate(&h)
}

func (w *AutocertWrapper) PrimeCache() error {
	return w.hostList.PrimeCache(w.Manager, w.primingNotify)
}

func (w *AutocertWrapper) PrimingReporter(l log.LeveledLogger) service.RunnerFunc {
	return func(c context.Context, wg *sync.WaitGroup) error {
		wg.Add(1)
		defer wg.Done()

		select {
		case m := <-w.primingNotify:
			l.Info(m)
		case <-c.Done():
			return nil
		}

		return nil
	}
}

var _ glautocert.PrimingCertProvider = (*AutocertWrapper)(nil)