aboutsummaryrefslogtreecommitdiffhomepage
path: root/caddytest/integration/acme_test.go
blob: ceacd1db0faa035db14a5c0c6c0d00263b6cd48d (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
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
package integration

import (
	"context"
	"crypto/ecdsa"
	"crypto/elliptic"
	"crypto/rand"
	"fmt"
	"net"
	"net/http"
	"strings"
	"testing"

	"github.com/caddyserver/caddy/v2"
	"github.com/caddyserver/caddy/v2/caddytest"
	"github.com/mholt/acmez/v2"
	"github.com/mholt/acmez/v2/acme"
	smallstepacme "github.com/smallstep/certificates/acme"
	"go.uber.org/zap"
)

const acmeChallengePort = 9081

// Test the basic functionality of Caddy's ACME server
func TestACMEServerWithDefaults(t *testing.T) {
	ctx := context.Background()
	logger, err := zap.NewDevelopment()
	if err != nil {
		t.Error(err)
		return
	}

	tester := caddytest.NewTester(t)
	tester.InitServer(`
	{
		skip_install_trust
		admin localhost:2999
		http_port     9080
		https_port    9443
		local_certs
	}
	acme.localhost {
		acme_server
	}
  `, "caddyfile")

	client := acmez.Client{
		Client: &acme.Client{
			Directory:  "https://acme.localhost:9443/acme/local/directory",
			HTTPClient: tester.Client,
			Logger:     logger,
		},
		ChallengeSolvers: map[string]acmez.Solver{
			acme.ChallengeTypeHTTP01: &naiveHTTPSolver{logger: logger},
		},
	}

	accountPrivateKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
	if err != nil {
		t.Errorf("generating account key: %v", err)
	}
	account := acme.Account{
		Contact:              []string{"mailto:you@example.com"},
		TermsOfServiceAgreed: true,
		PrivateKey:           accountPrivateKey,
	}
	account, err = client.NewAccount(ctx, account)
	if err != nil {
		t.Errorf("new account: %v", err)
		return
	}

	// Every certificate needs a key.
	certPrivateKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
	if err != nil {
		t.Errorf("generating certificate key: %v", err)
		return
	}

	certs, err := client.ObtainCertificateForSANs(ctx, account, certPrivateKey, []string{"localhost"})
	if err != nil {
		t.Errorf("obtaining certificate: %v", err)
		return
	}

	// ACME servers should usually give you the entire certificate chain
	// in PEM format, and sometimes even alternate chains! It's up to you
	// which one(s) to store and use, but whatever you do, be sure to
	// store the certificate and key somewhere safe and secure, i.e. don't
	// lose them!
	for _, cert := range certs {
		t.Logf("Certificate %q:\n%s\n\n", cert.URL, cert.ChainPEM)
	}
}

func TestACMEServerWithMismatchedChallenges(t *testing.T) {
	ctx := context.Background()
	logger := caddy.Log().Named("acmez")

	tester := caddytest.NewTester(t)
	tester.InitServer(`
	{
		skip_install_trust
		admin localhost:2999
		http_port     9080
		https_port    9443
		local_certs
	}
	acme.localhost {
		acme_server {
			challenges tls-alpn-01
		}
	}
  `, "caddyfile")

	client := acmez.Client{
		Client: &acme.Client{
			Directory:  "https://acme.localhost:9443/acme/local/directory",
			HTTPClient: tester.Client,
			Logger:     logger,
		},
		ChallengeSolvers: map[string]acmez.Solver{
			acme.ChallengeTypeHTTP01: &naiveHTTPSolver{logger: logger},
		},
	}

	accountPrivateKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
	if err != nil {
		t.Errorf("generating account key: %v", err)
	}
	account := acme.Account{
		Contact:              []string{"mailto:you@example.com"},
		TermsOfServiceAgreed: true,
		PrivateKey:           accountPrivateKey,
	}
	account, err = client.NewAccount(ctx, account)
	if err != nil {
		t.Errorf("new account: %v", err)
		return
	}

	// Every certificate needs a key.
	certPrivateKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
	if err != nil {
		t.Errorf("generating certificate key: %v", err)
		return
	}

	certs, err := client.ObtainCertificateForSANs(ctx, account, certPrivateKey, []string{"localhost"})
	if len(certs) > 0 {
		t.Errorf("expected '0' certificates, but received '%d'", len(certs))
	}
	if err == nil {
		t.Error("expected errors, but received none")
	}
	const expectedErrMsg = "no solvers available for remaining challenges (configured=[http-01] offered=[tls-alpn-01] remaining=[tls-alpn-01])"
	if !strings.Contains(err.Error(), expectedErrMsg) {
		t.Errorf(`received error message does not match expectation: expected="%s" received="%s"`, expectedErrMsg, err.Error())
	}
}

// naiveHTTPSolver is a no-op acmez.Solver for example purposes only.
type naiveHTTPSolver struct {
	srv    *http.Server
	logger *zap.Logger
}

func (s *naiveHTTPSolver) Present(ctx context.Context, challenge acme.Challenge) error {
	smallstepacme.InsecurePortHTTP01 = acmeChallengePort
	s.srv = &http.Server{
		Addr: fmt.Sprintf(":%d", acmeChallengePort),
		Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			host, _, err := net.SplitHostPort(r.Host)
			if err != nil {
				host = r.Host
			}
			s.logger.Info("received request on challenge server", zap.String("path", r.URL.Path))
			if r.Method == "GET" && r.URL.Path == challenge.HTTP01ResourcePath() && strings.EqualFold(host, challenge.Identifier.Value) {
				w.Header().Add("Content-Type", "text/plain")
				w.Write([]byte(challenge.KeyAuthorization))
				r.Close = true
				s.logger.Info("served key authentication",
					zap.String("identifier", challenge.Identifier.Value),
					zap.String("challenge", "http-01"),
					zap.String("remote", r.RemoteAddr),
				)
			}
		}),
	}
	l, err := net.Listen("tcp", fmt.Sprintf(":%d", acmeChallengePort))
	if err != nil {
		return err
	}
	s.logger.Info("present challenge", zap.Any("challenge", challenge))
	go s.srv.Serve(l)
	return nil
}

func (s naiveHTTPSolver) CleanUp(ctx context.Context, challenge acme.Challenge) error {
	smallstepacme.InsecurePortHTTP01 = 0
	s.logger.Info("cleanup", zap.Any("challenge", challenge))
	if s.srv != nil {
		s.srv.Close()
	}
	return nil
}