-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathhandler_test.go
More file actions
376 lines (347 loc) · 11.6 KB
/
Copy pathhandler_test.go
File metadata and controls
376 lines (347 loc) · 11.6 KB
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
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
package acme
import (
"bytes"
"context"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/x509"
"crypto/x509/pkix"
"encoding/base64"
"encoding/json"
"encoding/pem"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/go-jose/go-jose/v4"
"github.com/letsencrypt/cactus/ca"
"github.com/letsencrypt/cactus/cert"
cactuslog "github.com/letsencrypt/cactus/log"
"github.com/letsencrypt/cactus/signer"
"github.com/letsencrypt/cactus/storage"
)
func newTestStack(t *testing.T) (*httptest.Server, *Server) {
t.Helper()
dir := t.TempDir()
fs, err := storage.New(dir)
if err != nil {
t.Fatal(err)
}
seed := bytes.Repeat([]byte{0x91}, signer.SeedSize)
s, _ := signer.FromSeed(signer.AlgMLDSA44, seed)
l, err := cactuslog.New(context.Background(), cactuslog.Config{
LogID: cert.TrustAnchorID("32473.1"),
CosignerID: cert.TrustAnchorID("32473.1"),
Signer: s,
FS: fs,
FlushPeriod: 25 * time.Millisecond,
})
if err != nil {
t.Fatal(err)
}
t.Cleanup(l.Stop)
issuer, err := ca.New(l, "32473.1", 1)
if err != nil {
t.Fatal(err)
}
srv, err := New(Config{
ExternalURL: "", // will be set after httptest.NewServer
Issuer: issuer,
ChallengeMode: ChallengeAutoPass,
})
if err != nil {
t.Fatal(err)
}
hsrv := httptest.NewServer(srv.Handler())
srv.SetExternalURL(hsrv.URL)
t.Cleanup(hsrv.Close)
return hsrv, srv
}
// jwsSign builds a JWS over payload, with the given protected headers.
func jwsSign(t *testing.T, key *ecdsa.PrivateKey, jwk *jose.JSONWebKey, kid, nonce, url string, payload []byte) string {
t.Helper()
signerOpts := jose.SignerOptions{
ExtraHeaders: map[jose.HeaderKey]interface{}{
"nonce": nonce,
jose.HeaderKey("url"): url,
},
}
signingKey := jose.SigningKey{Algorithm: jose.ES256, Key: key}
if jwk != nil {
signerOpts.EmbedJWK = true
} else {
signerOpts.ExtraHeaders[jose.HeaderKey("kid")] = kid
}
sgn, err := jose.NewSigner(signingKey, &signerOpts)
if err != nil {
t.Fatal(err)
}
jws, err := sgn.Sign(payload)
if err != nil {
t.Fatal(err)
}
out, err := jws.CompactSerialize()
if err != nil {
t.Fatal(err)
}
return out
}
// nonceFor fetches a nonce from /new-nonce.
func nonceFor(t *testing.T, base string) string {
t.Helper()
resp, err := http.Head(base + "/new-nonce")
if err != nil {
t.Fatal(err)
}
resp.Body.Close()
n := resp.Header.Get("Replay-Nonce")
if n == "" {
t.Fatal("no nonce")
}
return n
}
// post posts a JWS to base+path and returns response, body, new nonce.
func post(t *testing.T, base, path, body string) (*http.Response, []byte) {
t.Helper()
req, err := http.NewRequest("POST", base+path, strings.NewReader(body))
if err != nil {
t.Fatal(err)
}
req.Header.Set("Content-Type", "application/jose+json")
resp, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatal(err)
}
b, _ := io.ReadAll(resp.Body)
resp.Body.Close()
return resp, b
}
// postAsGet performs the RFC 8555 §6.3 POST-as-GET pattern against url:
// signs an empty payload with acctKey/kid using a fresh nonce, posts
// to url, and returns the response + body.
func postAsGet(t *testing.T, base, url string, acctKey *ecdsa.PrivateKey, kid string, accept string) (*http.Response, []byte) {
t.Helper()
nonce := nonceFor(t, base)
jws := jwsSign(t, acctKey, nil, kid, nonce, url, []byte{})
req, err := http.NewRequest("POST", url, strings.NewReader(jws))
if err != nil {
t.Fatal(err)
}
req.Header.Set("Content-Type", "application/jose+json")
if accept != "" {
req.Header.Set("Accept", accept)
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatal(err)
}
b, _ := io.ReadAll(resp.Body)
resp.Body.Close()
return resp, b
}
func TestDirectoryEndpoint(t *testing.T) {
hsrv, _ := newTestStack(t)
resp, err := http.Get(hsrv.URL + "/directory")
if err != nil {
t.Fatal(err)
}
defer resp.Body.Close()
var d Directory
if err := json.NewDecoder(resp.Body).Decode(&d); err != nil {
t.Fatalf("decode directory: %v", err)
}
if d.NewAccount == "" || d.NewOrder == "" || d.NewNonce == "" {
t.Errorf("directory missing fields: %+v", d)
}
}
func TestNewNonceEndpoint(t *testing.T) {
hsrv, _ := newTestStack(t)
resp, err := http.Head(hsrv.URL + "/new-nonce")
if err != nil {
t.Fatal(err)
}
resp.Body.Close()
if resp.Header.Get("Replay-Nonce") == "" {
t.Error("missing Replay-Nonce")
}
}
func TestEndToEndIssuance(t *testing.T) {
hsrv, _ := newTestStack(t)
base := hsrv.URL
// 1. Account key.
acctKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
t.Fatal(err)
}
acctJWK := &jose.JSONWebKey{Key: acctKey.Public(), Algorithm: "ES256"}
// 2. new-account.
nonce := nonceFor(t, base)
accountReq, _ := json.Marshal(NewAccountReq{TermsOfServiceAgreed: true})
jws := jwsSign(t, acctKey, acctJWK, "", nonce, base+"/new-account", accountReq)
resp, body := post(t, base, "/new-account", jws)
if resp.StatusCode != http.StatusCreated && resp.StatusCode != http.StatusOK {
t.Fatalf("new-account status=%d body=%s", resp.StatusCode, body)
}
kid := resp.Header.Get("Location")
if kid == "" {
t.Fatal("missing Location")
}
// 3. new-order.
nonce = resp.Header.Get("Replay-Nonce")
orderPayload, _ := json.Marshal(NewOrderReq{
Identifiers: []Identifier{{Type: "dns", Value: "example.test"}},
})
jws = jwsSign(t, acctKey, nil, kid, nonce, base+"/new-order", orderPayload)
resp, body = post(t, base, "/new-order", jws)
if resp.StatusCode != http.StatusCreated {
t.Fatalf("new-order status=%d body=%s", resp.StatusCode, body)
}
var ord OrderResp
if err := json.Unmarshal(body, &ord); err != nil {
t.Fatalf("unmarshal order: %v", err)
}
orderURL := resp.Header.Get("Location")
if ord.Status != "ready" {
t.Errorf("order status = %q, want ready (auto-pass)", ord.Status)
}
// 4. Generate CSR.
csrKey, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
csrTmpl := &x509.CertificateRequest{
Subject: pkix.Name{CommonName: "example.test"},
DNSNames: []string{"example.test"},
}
csrDER, err := x509.CreateCertificateRequest(rand.Reader, csrTmpl, csrKey)
if err != nil {
t.Fatal(err)
}
finPayload, _ := json.Marshal(FinalizeReq{
CSR: base64.RawURLEncoding.EncodeToString(csrDER),
})
// 5. finalize.
nonce = resp.Header.Get("Replay-Nonce")
finalizeURL := ord.Finalize
jws = jwsSign(t, acctKey, nil, kid, nonce, finalizeURL, finPayload)
resp, body = post(t, base, strings.TrimPrefix(finalizeURL, base), jws)
if resp.StatusCode != http.StatusOK {
t.Fatalf("finalize status=%d body=%s", resp.StatusCode, body)
}
var ord2 OrderResp
if err := json.Unmarshal(body, &ord2); err != nil {
t.Fatalf("unmarshal body: %v", err)
}
if ord2.Status != "valid" {
t.Errorf("order status after finalize = %q", ord2.Status)
}
if ord2.Certificate == "" {
t.Fatal("missing certificate URL")
}
// 6. Download cert via POST-as-GET (RFC 8555 §6.3).
resp, pemBytes := postAsGet(t, base, ord2.Certificate, acctKey, kid, "")
if resp.StatusCode != 200 {
t.Fatalf("cert status = %d body=%s", resp.StatusCode, pemBytes)
}
block, _ := pem.Decode(pemBytes)
if block == nil || block.Type != "CERTIFICATE" {
t.Fatalf("not a PEM CERTIFICATE: %q", string(pemBytes))
}
// 7. Verify the cert structure: serialNumber > 0, issuer DN matches log ID DN.
if len(block.Bytes) < 100 {
t.Errorf("suspiciously short cert: %d bytes", len(block.Bytes))
}
_ = orderURL
_ = ord
}
func lastSegment(u string) string {
if i := strings.LastIndex(u, "/"); i >= 0 {
return u[i+1:]
}
return u
}
// TestNewAccountRequiresNonce confirms the nonce-required behaviour.
func TestNewAccountRequiresNonce(t *testing.T) {
hsrv, _ := newTestStack(t)
acctKey, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
acctJWK := &jose.JSONWebKey{Key: acctKey.Public(), Algorithm: "ES256"}
jws := jwsSign(t, acctKey, acctJWK, "", "definitely-not-a-real-nonce",
hsrv.URL+"/new-account", []byte("{}"))
resp, _ := post(t, hsrv.URL, "/new-account", jws)
if resp.StatusCode == http.StatusCreated || resp.StatusCode == http.StatusOK {
t.Errorf("expected nonce-error status, got %d", resp.StatusCode)
}
}
// newAccountAndOrder registers a fresh account and one dns order, returning
// the account key, kid, and the order object. Helper for cross-account tests.
func newAccountAndOrder(t *testing.T, base, dnsName string) (*ecdsa.PrivateKey, string, OrderResp, string) {
t.Helper()
acctKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
t.Fatal(err)
}
acctJWK := &jose.JSONWebKey{Key: acctKey.Public(), Algorithm: "ES256"}
nonce := nonceFor(t, base)
accountReq, _ := json.Marshal(NewAccountReq{TermsOfServiceAgreed: true})
jws := jwsSign(t, acctKey, acctJWK, "", nonce, base+"/new-account", accountReq)
resp, body := post(t, base, "/new-account", jws)
if resp.StatusCode != http.StatusCreated && resp.StatusCode != http.StatusOK {
t.Fatalf("new-account: %d %s", resp.StatusCode, body)
}
kid := resp.Header.Get("Location")
nonce = resp.Header.Get("Replay-Nonce")
orderPayload, _ := json.Marshal(NewOrderReq{Identifiers: []Identifier{{Type: "dns", Value: dnsName}}})
jws = jwsSign(t, acctKey, nil, kid, nonce, base+"/new-order", orderPayload)
resp, body = post(t, base, "/new-order", jws)
if resp.StatusCode != http.StatusCreated {
t.Fatalf("new-order: %d %s", resp.StatusCode, body)
}
var ord OrderResp
if err := json.Unmarshal(body, &ord); err != nil {
t.Fatalf("unmarshal body: %v", err)
}
return acctKey, kid, ord, resp.Header.Get("Location")
}
// TestCrossAccountAccessDenied confirms RFC 8555 §6.3 access control: a
// second account cannot read or finalize the first account's order.
func TestCrossAccountAccessDenied(t *testing.T) {
hsrv, _ := newTestStack(t)
base := hsrv.URL
_, _, victimOrder, victimOrderURL := newAccountAndOrder(t, base, "victim.test")
attackerKey, attackerKID, _, _ := newAccountAndOrder(t, base, "attacker.test")
// Attacker POST-as-GETs the victim's order URL.
resp, body := postAsGet(t, base, victimOrderURL, attackerKey, attackerKID, "")
if resp.StatusCode != http.StatusNotFound {
t.Errorf("cross-account order read: status=%d body=%s, want 404", resp.StatusCode, body)
}
// Attacker tries to finalize the victim's order with its own CSR.
csrKey, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
csrDER, _ := x509.CreateCertificateRequest(rand.Reader, &x509.CertificateRequest{
DNSNames: []string{"victim.test"},
}, csrKey)
finPayload, _ := json.Marshal(FinalizeReq{CSR: base64.RawURLEncoding.EncodeToString(csrDER)})
nonce := nonceFor(t, base)
jws := jwsSign(t, attackerKey, nil, attackerKID, nonce, victimOrder.Finalize, finPayload)
resp, body = post(t, base, strings.TrimPrefix(victimOrder.Finalize, base), jws)
if resp.StatusCode != http.StatusNotFound {
t.Errorf("cross-account finalize: status=%d body=%s, want 404", resp.StatusCode, body)
}
}
// TestFinalizeRejectsAccountKeyCSR confirms RFC 8555 §11.1: a CSR whose
// public key equals the account key is rejected.
func TestFinalizeRejectsAccountKeyCSR(t *testing.T) {
hsrv, _ := newTestStack(t)
base := hsrv.URL
acctKey, kid, ord, _ := newAccountAndOrder(t, base, "example.test")
// CSR signed with (and carrying) the account key.
csrDER, _ := x509.CreateCertificateRequest(rand.Reader, &x509.CertificateRequest{
DNSNames: []string{"example.test"},
}, acctKey)
finPayload, _ := json.Marshal(FinalizeReq{CSR: base64.RawURLEncoding.EncodeToString(csrDER)})
nonce := nonceFor(t, base)
jws := jwsSign(t, acctKey, nil, kid, nonce, ord.Finalize, finPayload)
resp, body := post(t, base, strings.TrimPrefix(ord.Finalize, base), jws)
if resp.StatusCode != http.StatusBadRequest {
t.Errorf("account-key CSR finalize: status=%d body=%s, want 400 badCSR", resp.StatusCode, body)
}
}