Repository navigation
Expand file tree
/
Copy pathverify_test.go
More file actions
401 lines (347 loc) · 12.8 KB
/
Copy pathverify_test.go
File metadata and controls
401 lines (347 loc) · 12.8 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
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
package pdfsign_test
import (
"bytes"
"context"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/x509"
"crypto/x509/pkix"
"encoding/asn1"
"math/big"
"net/http"
"net/http/httptest"
"sync"
"testing"
"time"
"github.com/digitorus/pdfsign"
"github.com/digitorus/pdfsign/internal/testpki"
"github.com/digitorus/pdfsign/revocation"
)
func TestVerify_Execute_NoFile(t *testing.T) {
// Test behavior when document has no reader (dummy doc)
doc := &pdfsign.Document{} // initialized without OpenFile
result := doc.Verify()
if result.Err() == nil {
t.Error("Expected error when verifying uninitialized document")
}
}
// TestVerify_TrustedRoots proves TrustedRoots() actually gates chain trust
// instead of being a no-op: the exact same signed document must verify as
// trusted against its real issuing root, and as untrusted against an
// unrelated root, with TrustSelfSigned left at its secure default (false).
func TestVerify_TrustedRoots(t *testing.T) {
pki := testpki.NewTestPKI(t)
pki.StartCRLServer()
defer pki.Close()
key, cert := pki.IssueLeaf("Trusted Roots Tester")
doc, err := pdfsign.OpenFile("testfiles/testfile_form.pdf")
if err != nil {
t.Fatalf("OpenFile: %v", err)
}
doc.Sign(key, cert, pki.Chain()...).Reason("TrustedRoots test")
var signed bytes.Buffer
if _, err := doc.Write(&signed); err != nil {
t.Fatalf("Write: %v", err)
}
t.Run("correct root is trusted", func(t *testing.T) {
verifyDoc, err := pdfsign.Open(bytes.NewReader(signed.Bytes()), int64(signed.Len()))
if err != nil {
t.Fatalf("Open: %v", err)
}
result := verifyDoc.Verify().TrustedRoots(pki.RootPool())
if err := result.Err(); err != nil {
t.Fatalf("verify: %v", err)
}
if !result.Valid() {
t.Fatalf("expected Valid() with the correct root pool, signatures: %+v", result.Signatures())
}
if len(result.Signatures()) != 1 || !result.Signatures()[0].TrustedChain {
t.Errorf("expected TrustedChain=true with the correct root pool, got %+v", result.Signatures())
}
})
t.Run("unrelated root is untrusted", func(t *testing.T) {
otherPKI := testpki.NewTestPKI(t)
otherPKI.StartCRLServer()
defer otherPKI.Close()
verifyDoc, err := pdfsign.Open(bytes.NewReader(signed.Bytes()), int64(signed.Len()))
if err != nil {
t.Fatalf("Open: %v", err)
}
result := verifyDoc.Verify().TrustedRoots(otherPKI.RootPool())
if result.Valid() {
t.Fatal("expected Valid()==false against an unrelated root pool")
}
if len(result.Signatures()) != 1 || result.Signatures()[0].TrustedChain {
t.Errorf("expected TrustedChain=false against an unrelated root pool, got %+v", result.Signatures())
}
})
t.Run("no trusted roots and no TrustSelfSigned is untrusted by default", func(t *testing.T) {
verifyDoc, err := pdfsign.Open(bytes.NewReader(signed.Bytes()), int64(signed.Len()))
if err != nil {
t.Fatalf("Open: %v", err)
}
result := verifyDoc.Verify()
if result.Valid() {
t.Fatal("expected Valid()==false by default with no TrustedRoots and no TrustSelfSigned")
}
})
}
// TestVerify_ConcurrentAccessorCalls proves that once a VerifyBuilder is
// configured, calling its result accessors (Valid, Signatures, Err, Count)
// concurrently from multiple goroutines is safe: verification runs exactly
// once and every goroutine observes the same result. Run with -race to
// exercise the guarantee.
func TestVerify_ConcurrentAccessorCalls(t *testing.T) {
pki := testpki.NewTestPKI(t)
pki.StartCRLServer()
defer pki.Close()
key, cert := pki.IssueLeaf("Concurrent Tester")
doc, err := pdfsign.OpenFile("testfiles/testfile_form.pdf")
if err != nil {
t.Fatalf("OpenFile: %v", err)
}
doc.Sign(key, cert, pki.Chain()...).Reason("Concurrency test")
var signed bytes.Buffer
if _, err := doc.Write(&signed); err != nil {
t.Fatalf("Write: %v", err)
}
verifyDoc, err := pdfsign.Open(bytes.NewReader(signed.Bytes()), int64(signed.Len()))
if err != nil {
t.Fatalf("Open: %v", err)
}
result := verifyDoc.Verify().TrustedRoots(pki.RootPool())
const goroutines = 50
var wg sync.WaitGroup
valids := make([]bool, goroutines)
counts := make([]int, goroutines)
errs := make([]error, goroutines)
for i := 0; i < goroutines; i++ {
wg.Add(1)
go func(i int) {
defer wg.Done()
valids[i] = result.Valid()
counts[i] = result.Count()
errs[i] = result.Err()
}(i)
}
wg.Wait()
for i := 1; i < goroutines; i++ {
if valids[i] != valids[0] || counts[i] != counts[0] || errs[i] != errs[0] {
t.Fatalf("inconsistent result across goroutines: goroutine 0 = (valid=%v, count=%d, err=%v), goroutine %d = (valid=%v, count=%d, err=%v)",
valids[0], counts[0], errs[0], i, valids[i], counts[i], errs[i])
}
}
if !valids[0] || counts[0] != 1 {
t.Fatalf("expected a single valid signature, got valid=%v count=%d", valids[0], counts[0])
}
}
// TestVerify_HTTPTimeoutIsApplied proves VerifyBuilder.HTTPTimeout actually
// bounds external OCSP/CRL requests instead of being a no-op silently
// dropped by doExecute (as it previously was): a signer certificate whose
// OCSP responder never replies must make Valid() return quickly once a
// short HTTPTimeout is configured, rather than wait out the server's full
// (deliberately longer) response delay.
//
// The signer needs a real issuer in its verified chain: applyRevocationStatus
// only attempts an external OCSP check when the chain has more than one
// certificate (chain[0][1], the issuer, is required to build the OCSP
// request) - a self-signed leaf never reaches that code path at all, which
// would make this test pass regardless of whether HTTPTimeout is wired up.
func TestVerify_HTTPTimeoutIsApplied(t *testing.T) {
slowOCSP := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
time.Sleep(2 * time.Second)
w.WriteHeader(http.StatusOK)
}))
defer slowOCSP.Close()
pki := testpki.NewTestPKI(t)
pki.StartCRLServer()
defer pki.Close()
issuerCert := pki.IntermediateCerts[len(pki.IntermediateCerts)-1]
issuerKey := pki.IntermediateKeys[len(pki.IntermediateKeys)-1]
key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
t.Fatal(err)
}
template := &x509.Certificate{
SerialNumber: big.NewInt(1),
Subject: pkix.Name{CommonName: "Slow OCSP Test"},
NotBefore: time.Now().Add(-time.Hour),
NotAfter: time.Now().Add(time.Hour),
KeyUsage: x509.KeyUsageDigitalSignature,
UnknownExtKeyUsage: []asn1.ObjectIdentifier{{1, 3, 6, 1, 5, 5, 7, 3, 36}},
OCSPServer: []string{slowOCSP.URL},
}
certDER, err := x509.CreateCertificate(rand.Reader, template, issuerCert, key.Public(), issuerKey)
if err != nil {
t.Fatal(err)
}
cert, err := x509.ParseCertificate(certDER)
if err != nil {
t.Fatal(err)
}
doc, err := pdfsign.OpenFile("testfiles/testfile_form.pdf")
if err != nil {
t.Fatal(err)
}
// Disable sign-time revocation embedding: by default, signing also
// fetches OCSP/CRL data to embed for LTV, which would otherwise hit the
// same slow OCSP server here and confuse what this test measures.
doc.Sign(key, cert, pki.Chain()...).
Reason("HTTPTimeout test").
RevocationFunction(func(cert, issuer *x509.Certificate, i *revocation.InfoArchival) error {
return nil
})
var buf bytes.Buffer
if _, err := doc.Write(&buf); err != nil {
t.Fatal(err)
}
signedDoc, err := pdfsign.Open(bytes.NewReader(buf.Bytes()), int64(buf.Len()))
if err != nil {
t.Fatal(err)
}
start := time.Now()
signedDoc.Verify().TrustedRoots(pki.RootPool()).ExternalChecks(true).HTTPTimeout(200 * time.Millisecond).Valid()
elapsed := time.Since(start)
if elapsed >= time.Second {
t.Errorf("expected HTTPTimeout(200ms) to abort the slow OCSP request well before the server's 2s response, took %v", elapsed)
}
}
// TestVerify_ContextCancellation proves VerifyBuilder.Context actually
// bounds external OCSP/CRL requests: cancelling the supplied context must
// make Valid() return quickly even though HTTPTimeout is left at its much
// longer default, and even though the OCSP responder never replies.
func TestVerify_ContextCancellation(t *testing.T) {
slowOCSP := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
time.Sleep(2 * time.Second)
w.WriteHeader(http.StatusOK)
}))
defer slowOCSP.Close()
pki := testpki.NewTestPKI(t)
pki.StartCRLServer()
defer pki.Close()
issuerCert := pki.IntermediateCerts[len(pki.IntermediateCerts)-1]
issuerKey := pki.IntermediateKeys[len(pki.IntermediateKeys)-1]
key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
t.Fatal(err)
}
template := &x509.Certificate{
SerialNumber: big.NewInt(1),
Subject: pkix.Name{CommonName: "Context Cancellation Test"},
NotBefore: time.Now().Add(-time.Hour),
NotAfter: time.Now().Add(time.Hour),
KeyUsage: x509.KeyUsageDigitalSignature,
UnknownExtKeyUsage: []asn1.ObjectIdentifier{{1, 3, 6, 1, 5, 5, 7, 3, 36}},
OCSPServer: []string{slowOCSP.URL},
}
certDER, err := x509.CreateCertificate(rand.Reader, template, issuerCert, key.Public(), issuerKey)
if err != nil {
t.Fatal(err)
}
cert, err := x509.ParseCertificate(certDER)
if err != nil {
t.Fatal(err)
}
doc, err := pdfsign.OpenFile("testfiles/testfile_form.pdf")
if err != nil {
t.Fatal(err)
}
doc.Sign(key, cert, pki.Chain()...).
Reason("Context cancellation test").
RevocationFunction(func(cert, issuer *x509.Certificate, i *revocation.InfoArchival) error {
return nil
})
var buf bytes.Buffer
if _, err := doc.Write(&buf); err != nil {
t.Fatal(err)
}
signedDoc, err := pdfsign.Open(bytes.NewReader(buf.Bytes()), int64(buf.Len()))
if err != nil {
t.Fatal(err)
}
ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond)
defer cancel()
start := time.Now()
signedDoc.Verify().TrustedRoots(pki.RootPool()).ExternalChecks(true).Context(ctx).Valid()
elapsed := time.Since(start)
if elapsed >= time.Second {
t.Errorf("expected Context cancellation at 200ms to abort the slow OCSP request well before the server's 2s response, took %v", elapsed)
}
}
// TestSign_ContextCancellation proves SignBuilder.Context actually bounds
// the TSA HTTP request: cancelling the supplied context must make Write()
// return quickly (with an error) even though the TSA responder never
// replies, rather than hang until it does.
func TestSign_ContextCancellation(t *testing.T) {
slowTSA := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
time.Sleep(2 * time.Second)
w.WriteHeader(http.StatusOK)
}))
defer slowTSA.Close()
doc, err := pdfsign.OpenFile("testfiles/testfile_form.pdf")
if err != nil {
t.Fatal(err)
}
ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond)
defer cancel()
doc.Timestamp(slowTSA.URL).Context(ctx)
var buf bytes.Buffer
start := time.Now()
_, err = doc.Write(&buf)
elapsed := time.Since(start)
if err == nil {
t.Fatal("expected Write to fail when the TSA request is cancelled by Context")
}
if elapsed >= time.Second {
t.Errorf("expected Context cancellation at 200ms to abort the slow TSA request well before the server's 2s response, took %v", elapsed)
}
}
// TestVerify_TimestampInfoIsPopulated proves that an embedded RFC 3161
// timestamp's details (time, authority, certificate) surface through
// SignatureVerifyResult.Timestamp. Previously doExecute's Signer-to-
// SignatureVerifyResult mapping never copied verify.Signer.TimeStamp over,
// so this field was always nil even for signatures with a valid embedded
// timestamp.
func TestVerify_TimestampInfoIsPopulated(t *testing.T) {
pki := testpki.NewTestPKI(t)
pki.StartCRLServer()
defer pki.Close()
tsaURL := testpki.StartMockTSA(t)
key, cert := pki.IssueLeaf("Timestamp Info Tester")
doc, err := pdfsign.OpenFile("testfiles/testfile_form.pdf")
if err != nil {
t.Fatalf("OpenFile: %v", err)
}
doc.Sign(key, cert, pki.Chain()...).Reason("Timestamp info test").Timestamp(tsaURL)
var signed bytes.Buffer
if _, err := doc.Write(&signed); err != nil {
t.Fatalf("Write: %v", err)
}
verifyDoc, err := pdfsign.Open(bytes.NewReader(signed.Bytes()), int64(signed.Len()))
if err != nil {
t.Fatalf("Open: %v", err)
}
result := verifyDoc.Verify().TrustedRoots(pki.RootPool())
if err := result.Err(); err != nil {
t.Fatalf("verify: %v", err)
}
sigs := result.Signatures()
if len(sigs) != 1 {
t.Fatalf("expected 1 signature, got %d", len(sigs))
}
ts := sigs[0].Timestamp
if ts == nil {
t.Fatal("expected Timestamp to be populated for a signature with an embedded RFC 3161 timestamp")
}
if ts.Time.IsZero() {
t.Error("expected Timestamp.Time to be set")
}
if ts.Certificate == nil {
t.Error("expected Timestamp.Certificate to be set")
}
if ts.Authority != "Mock TSA" {
t.Errorf("expected Timestamp.Authority = %q, got %q", "Mock TSA", ts.Authority)
}
}
// Integration verification tests for specific options are covered in pdf_test.go