about summary refs log tree commit diff stats
path: root/internal/server/tls.go
blob: b299b0b2a3eb252d8b3543a3ce59c8843b7351d5 (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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
package server

import (
	"context"
	"crypto/x509"
	"net"
	"net/http"
	"slices"
	"strconv"

	"go.alanpearce.eu/x/listenfd"

	certmagic_redis "github.com/alanpearce/certmagic-storage-redis"
	"github.com/ardanlabs/conf/v3"
	"github.com/caddyserver/certmagic"
	"github.com/libdns/powerdns"
	"gitlab.com/tozd/go/errors"
)

type redisConfig struct {
	Address       string `conf:"required"`
	Username      string `conf:"default:default"`
	Password      string `conf:"required"`
	EncryptionKey string `conf:"required"`
	KeyPrefix     string `conf:"default:certmagic"`
	TLSEnabled    bool   `conf:"default:false,env:TLS_ENABLED"`
	TLSInsecure   bool   `conf:"default:false,env:TLS_INSECURE"`
}

func (s *Server) serveTLS() (err error) {
	log := s.log.Named("tls")

	wildcardDomain := "*." + s.config.WildcardDomain
	certificateDomains := slices.Clone(s.config.Domains)

	// setting cfg.Logger is too late somehow
	certmagic.Default.Logger = log.GetLogger().Named("certmagic")
	certmagic.DefaultACME.Agreed = true
	certmagic.DefaultACME.Email = s.config.Email
	certmagic.DefaultACME.ListenHost = s.runtimeConfig.ListenAddress
	certmagic.DefaultACME.AltHTTPPort = s.runtimeConfig.Port
	certmagic.DefaultACME.AltTLSALPNPort = s.runtimeConfig.TLSPort

	if s.runtimeConfig.Development {
		ca := s.runtimeConfig.ACMECA
		if ca == "" {
			return errors.New("can't enable tls in development without an ACME_CA")
		}

		cp, err := x509.SystemCertPool()
		if err != nil {
			log.Warn("could not get system certificate pool", "error", err)
			cp = x509.NewCertPool()
		}

		if cacert := s.runtimeConfig.ACMECACert; cacert != "" {
			cp.AppendCertsFromPEM([]byte(cacert))
		}

		// caddy's ACME server (step-ca) doesn't specify an OCSP server
		certmagic.Default.OCSP.DisableStapling = true

		certmagic.DefaultACME.CA = s.runtimeConfig.ACMECA
		certmagic.DefaultACME.TrustedRoots = cp
		certmagic.DefaultACME.DisableTLSALPNChallenge = true
	} else {
		rc := &redisConfig{}
		_, err = conf.Parse("REDIS", rc)
		if err != nil {
			return errors.WithMessage(err, "could not parse redis config")
		}

		pdns := &powerdns.Provider{}
		_, err = conf.Parse("POWERDNS", pdns)
		if err != nil {
			return errors.WithMessage(err, "could not parse PowerDNS ACME config")
		}

		certmagic.DefaultACME.CA = certmagic.LetsEncryptProductionCA
		certmagic.DefaultACME.DNS01Solver = &certmagic.DNS01Solver{
			DNSManager: certmagic.DNSManager{
				DNSProvider: pdns,
				Logger:      certmagic.Default.Logger,
			},
		}

		certificateDomains = append(slices.Clone(s.config.Domains), wildcardDomain)

		rs := certmagic_redis.New()
		rs.Address = []string{rc.Address}
		rs.Username = rc.Username
		rs.Password = rc.Password
		rs.EncryptionKey = rc.EncryptionKey
		rs.KeyPrefix = rc.KeyPrefix
		rs.TlsEnabled = rc.TLSEnabled
		rs.TlsInsecure = rc.TLSInsecure

		certmagic.Default.Storage = rs
		err = rs.ProvisionCertMagic(context.TODO(), log.GetLogger())
		if err != nil {
			return errors.WithMessage(err, "could not provision redis storage")
		}
	}

	ln, err := listenfd.GetListener(
		1,
		net.JoinHostPort(s.runtimeConfig.ListenAddress, strconv.Itoa(s.runtimeConfig.Port)),
		log.Named("listenfd"),
	)
	if err != nil {
		return errors.WithMessage(err, "could not bind plain socket")
	}

	go func(ln net.Listener, srv *http.Server) {
		httpMux := http.NewServeMux()
		httpMux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
			if certmagic.LooksLikeHTTPChallenge(r) &&
				certmagic.DefaultACME.HandleHTTPChallenge(w, r) {
				return
			}
			url := r.URL
			url.Scheme = "https"
			port := s.config.BaseURL.Port()
			if port == "" {
				url.Host = r.Host
			} else {
				host, _, err := net.SplitHostPort(r.Host)
				if err != nil {
					log.Warn("error splitting host and port", "error", err)
					host = r.Host
				}
				url.Host = net.JoinHostPort(host, s.config.BaseURL.Port())
			}
			http.Redirect(w, r, url.String(), http.StatusMovedPermanently)
		})
		srv.Handler = httpMux

		if err := srv.Serve(ln); err != nil && !errors.Is(err, http.ErrServerClosed) {
			log.Error("error in http handler", "error", err)
		}
	}(ln, &http.Server{
		ReadHeaderTimeout: s.ReadHeaderTimeout,
		ReadTimeout:       s.ReadTimeout,
		WriteTimeout:      s.WriteTimeout,
		IdleTimeout:       s.IdleTimeout,
	})

	log.Debug(
		"starting certmagic",
		"http_port",
		s.runtimeConfig.Port,
		"https_port",
		s.runtimeConfig.TLSPort,
	)
	err = certmagic.ManageAsync(context.TODO(), certificateDomains)
	if err != nil {
		return errors.WithMessage(err, "could not enable TLS")
	}
	tlsConfig := certmagic.NewDefault().TLSConfig()
	tlsConfig.NextProtos = append([]string{"h2", "http/1.1"}, tlsConfig.NextProtos...)

	sln, err := listenfd.GetListenerTLS(
		0,
		net.JoinHostPort(s.runtimeConfig.ListenAddress, strconv.Itoa(s.runtimeConfig.TLSPort)),
		tlsConfig,
		log.Named("listenfd"),
	)
	if err != nil {
		return errors.WithMessage(err, "could not bind tls socket")
	}

	return s.Serve(sln)
}