forked from WICG/webpackage
-
Notifications
You must be signed in to change notification settings - Fork 0
/
signedexchange_test.go
446 lines (392 loc) · 14.8 KB
/
signedexchange_test.go
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
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
package signedexchange_test
import (
"bytes"
"io/ioutil"
"log"
"net/http"
"net/url"
"os"
"reflect"
"testing"
"time"
"github.com/WICG/webpackage/go/internal/signingalgorithm"
. "github.com/WICG/webpackage/go/signedexchange"
"github.com/WICG/webpackage/go/signedexchange/certurl"
"github.com/WICG/webpackage/go/signedexchange/version"
)
const (
requestUrl = "https://example.com/"
payload = `Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.`
pemCerts = `-----BEGIN CERTIFICATE-----
MIIBhjCCAS2gAwIBAgIJAOhR3xtYd5QsMAoGCCqGSM49BAMCMDIxFDASBgNVBAMM
C2V4YW1wbGUub3JnMQ0wCwYDVQQKDARUZXN0MQswCQYDVQQGEwJVUzAeFw0xODEx
MDUwOTA5MjJaFw0xOTEwMzEwOTA5MjJaMDIxFDASBgNVBAMMC2V4YW1wbGUub3Jn
MQ0wCwYDVQQKDARUZXN0MQswCQYDVQQGEwJVUzBZMBMGByqGSM49AgEGCCqGSM49
AwEHA0IABH1E6odXRm3+r7dMYmkJRmftx5IYHAsqgA7zjsFfCvPqL/fM4Uvi8EFu
JVQM/oKEZw3foCZ1KBjo/6Tenkoj/wCjLDAqMBAGCisGAQQB1nkCARYEAgUAMBYG
A1UdEQQPMA2CC2V4YW1wbGUub3JnMAoGCCqGSM49BAMCA0cAMEQCIEbxRKhlQYlw
Ja+O9h7misjLil82Q82nhOtl4j96awZgAiB6xrvRZIlMtWYKdi41BTb5fX22gL9M
L/twWg8eWpYeJA==
-----END CERTIFICATE-----
`
// Generated by `openssl ecparam -out priv.key -name prime256v1 -genkey`
pemPrivateKey = `-----BEGIN EC PRIVATE KEY-----
MHcCAQEEIEMac81NMjwO4pQ2IGKZ3UdymYtnFAXEjKdvAdEx4DQwoAoGCCqGSM49
AwEHoUQDQgAEfUTqh1dGbf6vt0xiaQlGZ+3HkhgcCyqADvOOwV8K8+ov98zhS+Lw
QW4lVAz+goRnDd+gJnUoGOj/pN6eSiP/AA==
-----END EC PRIVATE KEY-----`
)
// signatureDate corresponds to the expectedSignatureHeader's date value.
var signatureDate = time.Date(2018, 1, 31, 17, 13, 20, 0, time.UTC)
var nullLogger = log.New(ioutil.Discard, "", 0) // Use when some output is expected.
var stdoutLogger = log.New(os.Stdout, "ERROR: ", 0) // Use when no output is expected.
func mustReadFile(path string) []byte {
b, err := ioutil.ReadFile(path)
if err != nil {
panic(err)
}
return b
}
func testForEachVersion(t *testing.T, testFunc func(ver version.Version, t *testing.T)) {
for _, ver := range version.AllVersions {
t.Run(string(ver), func(t *testing.T) { testFunc(ver, t) })
}
}
func TestSignedExchange(t *testing.T) {
certs, err := signingalgorithm.ParseCertificates([]byte(pemCerts))
if err != nil {
t.Fatal(err)
}
privKey, err := signingalgorithm.ParsePrivateKey([]byte(pemPrivateKey))
if err != nil {
t.Fatal(err)
}
certUrl, _ := url.Parse("https://example.com/cert.msg")
validityUrl, _ := url.Parse("https://example.com/resource.validity")
expectedRespHeader := map[version.Version]http.Header{
version.Version1b1: http.Header{
"Content-Type": []string{"text/html; charset=utf-8"},
"Foo": []string{"Bar,Baz"},
"Content-Encoding": []string{"mi-sha256-draft2"},
"Mi-Draft2": []string{"mi-sha256-draft2=DRyBGPb7CAW2ukzb9sT1S1ialssthiv6QW7Ks-Trg4Y"},
},
version.Version1b2: http.Header{
"Content-Type": []string{"text/html; charset=utf-8"},
"Foo": []string{"Bar,Baz"},
"Content-Encoding": []string{"mi-sha256-03"},
"Digest": []string{"mi-sha256-03=DRyBGPb7CAW2ukzb9sT1S1ialssthiv6QW7Ks+Trg4Y="},
},
version.Version1b3: http.Header{
"Content-Type": []string{"text/html; charset=utf-8"},
"Foo": []string{"Bar,Baz"},
"Content-Encoding": []string{"mi-sha256-03"},
"Digest": []string{"mi-sha256-03=DRyBGPb7CAW2ukzb9sT1S1ialssthiv6QW7Ks+Trg4Y="},
},
}
expectedSignatureHeader := map[version.Version]string{
version.Version1b1: "label;cert-sha256=*eLWHusI0YcDcHSG5nkYbyZddE2sidVyhx6iSYoJ+SFc=*;cert-url=\"https://example.com/cert.msg\";date=1517418800;expires=1517422400;integrity=\"mi-draft2\";sig=*P+xY4Q8STWMxPzA8aAsyD+cS48e2kDkX0Zb87AkjP4I=*;validity-url=\"https://example.com/resource.validity\"",
version.Version1b2: "label;cert-sha256=*eLWHusI0YcDcHSG5nkYbyZddE2sidVyhx6iSYoJ+SFc=*;cert-url=\"https://example.com/cert.msg\";date=1517418800;expires=1517422400;integrity=\"digest/mi-sha256-03\";sig=*MuyacyYQQhivyQnoSAxjzyeYo3EaUuRd8H+WkpbEjio=*;validity-url=\"https://example.com/resource.validity\"",
version.Version1b3: "label;cert-sha256=*eLWHusI0YcDcHSG5nkYbyZddE2sidVyhx6iSYoJ+SFc=*;cert-url=\"https://example.com/cert.msg\";date=1517418800;expires=1517422400;integrity=\"digest/mi-sha256-03\";sig=*0xyLkp/b7AwNNfj6gWrRiQrvdITlVoWxXsQ4STLWv+Q=*;validity-url=\"https://example.com/resource.validity\"",
}
testForEachVersion(t, func(ver version.Version, t *testing.T) {
reqHeader := http.Header{}
reqHeader.Add("Accept", "*/*")
respHeader := http.Header{}
respHeader.Add("Content-Type", "text/html; charset=utf-8")
// Multiple values for the same header
respHeader.Add("Foo", "Bar")
respHeader.Add("Foo", "Baz")
e := NewExchange(ver, requestUrl, http.MethodGet, reqHeader, 200, respHeader, []byte(payload))
if err := e.MiEncodePayload(16); err != nil {
t.Fatal(err)
}
s := &Signer{
Date: signatureDate,
Expires: signatureDate.Add(1 * time.Hour),
Certs: certs,
CertUrl: certUrl,
ValidityUrl: validityUrl,
PrivKey: privKey,
Algorithm: &signingalgorithm.MockSigningAlgorithm{},
}
if err := e.AddSignatureHeader(s); err != nil {
t.Fatal(err)
}
var buf bytes.Buffer
if err := e.Write(&buf); err != nil {
t.Fatal(err)
}
got, err := ReadExchange(&buf)
if err != nil {
t.Fatal(err)
}
if got.Version != ver {
t.Errorf("Unexpected version: got %v, want %v", got.Version, ver)
}
if got.RequestURI != requestUrl {
t.Errorf("Unexpected request URL: %q", got.RequestURI)
}
if got.RequestMethod != http.MethodGet {
t.Errorf("Unexpected request method: %q", got.RequestMethod)
}
if ver == version.Version1b1 || ver == version.Version1b2 {
if !reflect.DeepEqual(got.RequestHeaders, reqHeader) {
t.Errorf("Unexpected request headers: %v", got.RequestHeaders)
}
} else {
emptyHeader := http.Header{}
if !reflect.DeepEqual(got.RequestHeaders, emptyHeader) {
t.Errorf("Unexpected request headers: %v", got.RequestHeaders)
}
}
if got.ResponseStatus != 200 {
t.Errorf("Unexpected response status: %v", got.ResponseStatus)
}
if !reflect.DeepEqual(got.ResponseHeaders, expectedRespHeader[ver]) {
t.Errorf("Unexpected response headers: %v", got.ResponseHeaders)
}
if got.SignatureHeaderValue != expectedSignatureHeader[ver] {
t.Errorf("Unexpected signature header: %q", got.SignatureHeaderValue)
}
wantPayload := mustReadFile("test-signedexchange-expected-payload-mi.bin")
if !bytes.Equal(got.Payload, wantPayload) {
t.Errorf("payload mismatch")
}
})
}
func TestSignedExchangeBannedCertUrlScheme(t *testing.T) {
testForEachVersion(t, func(ver version.Version, t *testing.T) {
e := NewExchange(ver, requestUrl, http.MethodGet, nil, 200, http.Header{}, []byte(payload))
if err := e.MiEncodePayload(16); err != nil {
t.Fatal(err)
}
certs, _ := signingalgorithm.ParseCertificates([]byte(pemCerts))
certUrl, _ := url.Parse("http://example.com/cert.msg")
validityUrl, _ := url.Parse("https://example.com/resource.validity")
privKey, _ := signingalgorithm.ParsePrivateKey([]byte(pemPrivateKey))
s := &Signer{
Date: signatureDate,
Expires: signatureDate.Add(1 * time.Hour),
Certs: certs,
CertUrl: certUrl,
ValidityUrl: validityUrl,
PrivKey: privKey,
}
if err := e.AddSignatureHeader(s); err == nil {
t.Errorf("non-{https,data} cert-url unexpectedly allowed in an exchange")
}
})
}
func createTestExchange(ver version.Version, t *testing.T) (e *Exchange, s *Signer, certBytes []byte) {
header := http.Header{}
header.Add("Content-Type", "text/html; charset=utf-8")
e = NewExchange(ver, requestUrl, http.MethodGet, nil, 200, header, []byte(payload))
if err := e.MiEncodePayload(16); err != nil {
t.Fatal(err)
}
certs, err := signingalgorithm.ParseCertificates([]byte(pemCerts))
if err != nil {
t.Fatal(err)
}
privKey, err := signingalgorithm.ParsePrivateKey([]byte(pemPrivateKey))
if err != nil {
t.Fatal(err)
}
certUrl, _ := url.Parse("https://example.com/cert.msg")
validityUrl, _ := url.Parse("https://example.com/resource.validity")
s = &Signer{
Date: signatureDate,
Expires: signatureDate.Add(1 * time.Hour),
Certs: certs,
CertUrl: certUrl,
ValidityUrl: validityUrl,
PrivKey: privKey,
}
certChain, err := certurl.NewCertChain(certs, []byte("dummy"), nil)
if err != nil {
t.Fatal(err)
}
var certCBOR bytes.Buffer
if err := certChain.Write(&certCBOR); err != nil {
t.Fatal(err)
}
certBytes = certCBOR.Bytes()
return
}
func verificationShouldSucceed(t *testing.T, e *Exchange, certBytes []byte, verificationTime time.Time) {
certFetcher := func(_ string) ([]byte, error) { return certBytes, nil }
if _, ok := e.Verify(verificationTime, certFetcher, stdoutLogger); !ok {
t.Errorf("Verification should succeed")
}
}
func verificationShouldFail(t *testing.T, e *Exchange, certBytes []byte, verificationTime time.Time) {
certFetcher := func(_ string) ([]byte, error) { return certBytes, nil }
if _, ok := e.Verify(verificationTime, certFetcher, nullLogger); ok {
t.Errorf("Verification should fail")
}
}
func TestVerify(t *testing.T) {
testForEachVersion(t, func(ver version.Version, t *testing.T) {
e, s, c := createTestExchange(ver, t)
if err := e.AddSignatureHeader(s); err != nil {
t.Fatal(err)
}
verificationShouldSucceed(t, e, c, signatureDate)
})
}
func TestVerifyNotYetValidExchange(t *testing.T) {
testForEachVersion(t, func(ver version.Version, t *testing.T) {
e, s, c := createTestExchange(ver, t)
if err := e.AddSignatureHeader(s); err != nil {
t.Fatal(err)
}
verificationTime := signatureDate.Add(-1 * time.Second)
verificationShouldFail(t, e, c, verificationTime)
})
}
func TestVerifyExpiredExchange(t *testing.T) {
testForEachVersion(t, func(ver version.Version, t *testing.T) {
e, s, c := createTestExchange(ver, t)
if err := e.AddSignatureHeader(s); err != nil {
t.Fatal(err)
}
verificationTime := signatureDate.Add(1 * time.Hour).Add(1 * time.Second)
verificationShouldFail(t, e, c, verificationTime)
})
}
func TestVerifyBadValidityUrl(t *testing.T) {
testForEachVersion(t, func(ver version.Version, t *testing.T) {
e, s, c := createTestExchange(ver, t)
s.ValidityUrl, _ = url.Parse("https://subdomain.example.com/resource.validity")
if err := e.AddSignatureHeader(s); err != nil {
t.Fatal(err)
}
verificationShouldFail(t, e, c, signatureDate)
})
}
func TestVerifyBadMethod(t *testing.T) {
testForEachVersion(t, func(ver version.Version, t *testing.T) {
// The test doesn't make sense in version >= b3, which doesn't have request method.
if ver != version.Version1b1 && ver != version.Version1b2 {
return
}
e, s, c := createTestExchange(ver, t)
e.RequestMethod = "POST"
if err := e.AddSignatureHeader(s); err != nil {
t.Fatal(err)
}
verificationShouldFail(t, e, c, signatureDate)
})
}
func TestVerifyStatefulRequestHeader(t *testing.T) {
testForEachVersion(t, func(ver version.Version, t *testing.T) {
e, s, c := createTestExchange(ver, t)
if e.RequestHeaders == nil {
e.RequestHeaders = http.Header{}
}
e.RequestHeaders.Set("Authorization", "Basic Zm9vOmJhcg==")
if err := e.AddSignatureHeader(s); err != nil {
t.Fatal(err)
}
verificationShouldFail(t, e, c, signatureDate)
})
}
func TestVerifyUncachedHeader(t *testing.T) {
testForEachVersion(t, func(ver version.Version, t *testing.T) {
e, s, c := createTestExchange(ver, t)
e.ResponseHeaders.Set("Set-Cookie", "foo=bar")
if err := e.AddSignatureHeader(s); err != nil {
t.Fatal(err)
}
verificationShouldFail(t, e, c, signatureDate)
})
}
func TestVerifyBadSignature(t *testing.T) {
testForEachVersion(t, func(ver version.Version, t *testing.T) {
e, s, c := createTestExchange(ver, t)
if err := e.AddSignatureHeader(s); err != nil {
t.Fatal(err)
}
e.ResponseHeaders.Add("Etag", "0123")
verificationShouldFail(t, e, c, signatureDate)
})
}
func TestVerifyNoContentType(t *testing.T) {
testForEachVersion(t, func(ver version.Version, t *testing.T) {
e, s, c := createTestExchange(ver, t)
e.ResponseHeaders.Del("Content-Type")
if err := e.AddSignatureHeader(s); err != nil {
t.Fatal(err)
}
// The requirement for Content-Type is only for version >= b3.
if ver == version.Version1b1 || ver == version.Version1b2 {
verificationShouldSucceed(t, e, c, signatureDate)
} else {
verificationShouldFail(t, e, c, signatureDate)
}
})
}
func TestVerifyNonCanonicalURL(t *testing.T) {
testForEachVersion(t, func(ver version.Version, t *testing.T) {
e, s, c := createTestExchange(ver, t)
// url.Parse() decodes "%73%78%67" to "sxg"
e.RequestURI = "https://example.com/%73%78%67"
if err := e.AddSignatureHeader(s); err != nil {
t.Fatal(err)
}
verificationShouldSucceed(t, e, c, signatureDate)
})
}
func TestVerifyNonCacheable(t *testing.T) {
testForEachVersion(t, func(ver version.Version, t *testing.T) {
e, s, c := createTestExchange(ver, t)
e.ResponseHeaders.Add("Cache-Control", "no-store")
if err := e.AddSignatureHeader(s); err != nil {
t.Fatal(err)
}
switch ver {
case version.Version1b1, version.Version1b2:
verificationShouldSucceed(t, e, c, signatureDate)
default:
verificationShouldFail(t, e, c, signatureDate)
}
})
}
func TestIsCacheable(t *testing.T) {
testForEachVersion(t, func(ver version.Version, t *testing.T) {
if ver == version.Version1b1 || ver == version.Version1b2 {
return
}
e, _, _ := createTestExchange(ver, t)
if !e.IsCacheable(stdoutLogger) {
t.Errorf("Response should be cacheable")
}
e, _, _ = createTestExchange(ver, t)
e.ResponseHeaders.Add("cache-control", "no-store")
if e.IsCacheable(nullLogger) {
t.Errorf("Response with \"no-store\" cache directive shouldn't be cacheable")
}
e, _, _ = createTestExchange(ver, t)
e.ResponseHeaders.Add("cache-control", "max-age=300, private")
if e.IsCacheable(nullLogger) {
t.Errorf("Response with \"private\" cache directive shouldn't be cacheable")
}
e, _, _ = createTestExchange(ver, t)
e.ResponseStatus = 201
if e.IsCacheable(nullLogger) {
t.Errorf("Response with status code 201 shouldn't be cacheable by default")
}
e, _, _ = createTestExchange(ver, t)
e.ResponseStatus = 201
e.ResponseHeaders.Add("cache-control", "max-age=300")
if !e.IsCacheable(stdoutLogger) {
t.Errorf("Response with \"max-age\" cache directive should be cacheable")
}
e, _, _ = createTestExchange(ver, t)
e.ResponseStatus = 201
e.ResponseHeaders.Add("expires", "Mon, 07 Jan 2019 07:29:39 GMT")
if !e.IsCacheable(stdoutLogger) {
t.Errorf("Response with \"Expires\" header should be cacheable")
}
})
}