-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexample_test.go
More file actions
100 lines (80 loc) · 2.32 KB
/
Copy pathexample_test.go
File metadata and controls
100 lines (80 loc) · 2.32 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
package urlsign_test
import (
"errors"
"fmt"
"net/http"
"net/url"
"time"
"lowbit.dev/urlsign"
)
// Example demonstrates issuing a signed URL and then verifying it.
func Example() {
s, err := urlsign.NewSigner([]byte("supersecret"), time.Hour)
if err != nil {
panic(err)
}
signed, err := s.Sign("https://cdn.example.com/files/report.pdf")
if err != nil {
panic(err)
}
fmt.Println(s.Verify(signed))
// Output: <nil>
}
// ExampleNewSigner shows the two constructor error cases.
func ExampleNewSigner() {
_, err := urlsign.NewSigner(nil, time.Hour)
fmt.Println(err)
_, err = urlsign.NewSigner([]byte("key"), 0)
fmt.Println(err)
// Output:
// key must not be empty
// ttl must be positive
}
// ExampleSigner_Sign shows that Sign preserves existing query params and appends exp and sig.
func ExampleSigner_Sign() {
s, _ := urlsign.NewSigner([]byte("secret"), time.Hour)
signed, err := s.Sign("https://example.com/dl?format=pdf")
if err != nil {
panic(err)
}
u, _ := url.Parse(signed)
q := u.Query()
fmt.Println(q.Get("format"))
fmt.Println(q.Get("exp") != "")
fmt.Println(q.Get("sig") != "")
// Output:
// pdf
// true
// true
}
// ExampleSigner_Verify shows a successful verification and the error returned for an unsigned URL.
func ExampleSigner_Verify() {
s, _ := urlsign.NewSigner([]byte("secret"), time.Hour)
signed, _ := s.Sign("https://example.com/files/report.pdf")
fmt.Println(s.Verify(signed))
fmt.Println(s.Verify("https://example.com/files/report.pdf"))
// Output:
// <nil>
// missing signature parameters
}
// ExampleSigner_Verify_tampered shows that modifying any query parameter after signing is detected.
func ExampleSigner_Verify_tampered() {
s, _ := urlsign.NewSigner([]byte("secret"), time.Hour)
signed, _ := s.Sign("https://example.com/dl?format=pdf")
u, _ := url.Parse(signed)
q := u.Query()
q.Set("format", "csv")
u.RawQuery = q.Encode()
err := s.Verify(u.String())
fmt.Println(errors.Is(err, urlsign.ErrInvalidSig))
// Output: true
}
// ExampleSigner_VerifyRequest shows verification via an incoming *http.Request.
func ExampleSigner_VerifyRequest() {
s, _ := urlsign.NewSigner([]byte("secret"), time.Hour)
signed, _ := s.Sign("https://example.com/artifacts/report.pdf")
u, _ := url.Parse(signed)
r := &http.Request{URL: u}
fmt.Println(s.VerifyRequest(r))
// Output: <nil>
}