about summary refs log tree commit diff stats
path: root/internal/server/tls.go
blob: 84dae744c0f478340f7b47082e2e7fcff541143b (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
package server

import (
	"context"
	"crypto/x509"
	"website/internal/log"

	"github.com/ardanlabs/conf/v3"
	"github.com/caddyserver/caddy/v2"
	"github.com/caddyserver/certmagic"
	certmagic_redis "github.com/pberkel/caddy-storage-redis"
	"github.com/pkg/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"`
}

func (s *Server) serveTLS() (err error) {
	if s.runtimeConfig.Development {
		ca := s.runtimeConfig.ACMECACert
		if ca == "" {
			return errors.New("Need ACME_CA_CERT to enable TLS in development")
		}

		cp := x509.NewCertPool()
		cp.AppendCertsFromPEM([]byte(ca))

		cfg := certmagic.NewDefault()
		issuer := certmagic.NewACMEIssuer(cfg, certmagic.ACMEIssuer{
			CA:                      "https://localhost/acme/local/directory",
			TrustedRoots:            cp,
			DisableTLSALPNChallenge: true,
			AltHTTPPort:             s.runtimeConfig.Port,
		})

		certmagic.DefaultACME = *issuer
	} else {
		rc := &redisConfig{}
		_, err = conf.Parse("REDIS", rc)
		if err != nil {
			return errors.Wrap(err, "could not parse redis config")
		}

		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

		certmagic.Default.Storage = rs
		err = rs.Provision(caddy.Context{
			Context: context.Background(),
		})
		if err != nil {
			return errors.Wrap(err, "could not provision redis storage")
		}
	}

	certmagic.DefaultACME.Agreed = true
	certmagic.DefaultACME.Email = s.config.Email
	certmagic.Default.DefaultServerName = s.config.Domains[0]
	certmagic.HTTPPort = s.runtimeConfig.Port
	certmagic.HTTPSPort = s.runtimeConfig.TLSPort

	log.Debug(
		"starting certmagic",
		"http_port",
		certmagic.HTTPPort,
		"https_port",
		certmagic.HTTPSPort,
	)

	return certmagic.HTTPS(s.config.Domains, s.Server.Handler)
}