-
Notifications
You must be signed in to change notification settings - Fork 2
/
handler_test.go
199 lines (181 loc) · 7.06 KB
/
handler_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
package httpsign
import (
"bytes"
"fmt"
"github.com/stretchr/testify/assert"
"io"
"log"
"net/http"
"net/http/httptest"
"strings"
"testing"
)
func Test_WrapHandler(t *testing.T) {
fetchVerifier := func(r *http.Request) (string, *Verifier) {
sigName := "sig1"
verifier, _ := NewHMACSHA256Verifier(bytes.Repeat([]byte{1}, 64), nil,
Headers("@method"))
return sigName, verifier
}
fetchSigner := func(res http.Response, r *http.Request) (string, *Signer) {
sigName := "sig1"
signer, _ := NewHMACSHA256Signer(bytes.Repeat([]byte{0}, 64), NewSignConfig().SetKeyID("key"),
Headers("@status", "bar", "date", "Content-Digest"))
return sigName, signer
}
simpleHandler := func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(200)
w.Header().Set("bar", "baz and baz again")
_, _ = fmt.Fprintln(w, "Hello, client")
_, _ = fmt.Fprintln(w, "Hello again")
}
config := NewHandlerConfig().SetFetchVerifier(fetchVerifier).
SetFetchSigner(fetchSigner).SetDigestSchemesSend([]string{DigestSha256}).SetDigestSchemesRecv([]string{DigestSha256})
ts := httptest.NewServer(WrapHandler(http.HandlerFunc(simpleHandler), *config))
defer ts.Close()
signer, err := NewHMACSHA256Signer(bytes.Repeat([]byte{1}, 64), NewSignConfig().SetKeyID("key"),
Headers("@method", "content-digest", "@request-target"))
assert.NoError(t, err)
verifier, err := NewHMACSHA256Verifier(bytes.Repeat([]byte{0}, 64), NewVerifyConfig().SetKeyID("key"), *NewFields())
assert.NoError(t, err)
client := NewDefaultClient(NewClientConfig().SetSignatureName("sig1").SetSigner(signer).SetVerifier(verifier).SetDigestSchemesSend([]string{DigestSha256}))
res, err := client.Post(ts.URL+"?foo", "text/plain", strings.NewReader("Message body here"))
assert.NoError(t, err)
if res != nil {
_, err = io.ReadAll(res.Body)
_ = res.Body.Close()
assert.NoError(t, err)
assert.Equal(t, res.Status, "200 OK", "Bad status returned")
}
}
// test various failures
func TestWrapHandlerServerSigns(t *testing.T) {
serverSignsTestCase := func(t *testing.T, nilSigner, dontSignResponse, earlyExpires, noSigner, badKey, badAlgs, verifyRequest bool) {
// Callback to let the server locate its signing key and configuration
var signConfig *SignConfig
if !earlyExpires {
signConfig = nil
} else {
signConfig = NewSignConfig().SetExpires(2000)
}
fetchSigner := func(res http.Response, r *http.Request) (string, *Signer) {
sigName := "sig1"
signer, _ := NewHMACSHA256Signer(bytes.Repeat([]byte{0}, 64), signConfig.SetKeyID("key1"),
Headers("@status", "bar", "date"))
return sigName, signer
}
badFetchSigner := func(res http.Response, r *http.Request) (string, *Signer) {
return "just a name", nil
}
simpleHandler := func(w http.ResponseWriter, r *http.Request) { // this handler gets wrapped
w.WriteHeader(200)
w.Header().Set("bar", "baz me")
_, _ = fmt.Fprintln(w, "Hello, client")
}
// Configure the wrapper and set it up
var config *HandlerConfig
if !nilSigner {
if !noSigner {
config = NewHandlerConfig().SetFetchSigner(fetchSigner)
} else {
config = NewHandlerConfig().SetFetchSigner(badFetchSigner)
}
} else {
config = NewHandlerConfig().SetFetchSigner(nil)
}
if dontSignResponse {
config = config.SetFetchSigner(nil)
}
if verifyRequest {
serverVerifier, _ := NewHMACSHA256Verifier(bytes.Repeat([]byte{9}, 64), NewVerifyConfig().SetKeyID("key"), *NewFields())
config = config.SetFetchVerifier(func(r *http.Request) (sigName string, verifier *Verifier) {
return "sig333", serverVerifier
})
}
ts := httptest.NewServer(WrapHandler(http.HandlerFunc(simpleHandler), *config))
defer ts.Close()
// HTTP client code
var key []byte
if !badKey {
key = bytes.Repeat([]byte{0}, 64)
} else {
key = bytes.Repeat([]byte{3}, 64)
}
verifyConfig := NewVerifyConfig().SetKeyID("key")
if badAlgs {
verifyConfig = verifyConfig.SetAllowedAlgs([]string{"zuzu"})
}
verifier, _ := NewHMACSHA256Verifier(key, verifyConfig, *NewFields())
client := NewDefaultClient(NewClientConfig().SetSignatureName("sig1").SetVerifier(verifier))
res, err := client.Get(ts.URL)
if err == nil && res.StatusCode == 200 {
t.Errorf("Surprise! Server sent 200 OK and signature validation was successful.")
}
}
nilSigner := func(t *testing.T) {
serverSignsTestCase(t, true, false, false, false, false, false, false)
}
dontSignResponse := func(t *testing.T) {
serverSignsTestCase(t, false, true, false, false, false, false, false)
}
earlyExpires := func(t *testing.T) {
serverSignsTestCase(t, false, false, true, false, false, false, false)
}
noSigner := func(t *testing.T) {
serverSignsTestCase(t, false, false, false, true, false, false, false)
}
badKey := func(t *testing.T) {
serverSignsTestCase(t, false, false, false, false, true, false, false)
}
badAlgs := func(t *testing.T) {
serverSignsTestCase(t, false, false, false, false, false, true, false)
}
failVerify := func(t *testing.T) {
serverSignsTestCase(t, false, false, false, false, false, false, true)
}
t.Run("nil Signer", nilSigner)
t.Run("don't sign response", dontSignResponse)
t.Run("early expires field", earlyExpires)
t.Run("bad fetch Signer", noSigner)
t.Run("wrong verification key", badKey)
t.Run("failed algorithm check", badAlgs)
t.Run("failed request verification", failVerify)
}
func TestWrapHandlerServerFails(t *testing.T) { // non-default verify handler
// Set up a test server
simpleHandler := func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(200)
w.Header().Set("Content-Type", "text/plain")
_, _ = fmt.Fprintf(w, "Hey client, you sent a signature with these parameters: %s\n",
r.Header.Get("Signature-Input"))
}
verifyFailed := func(w http.ResponseWriter, r *http.Request, logger *log.Logger, err error) {
w.WriteHeader(599)
if err == nil { // should not happen
t.Errorf("Test failed, handler received an error: %v", err)
}
if logger != nil {
log.Println("Could not verify request signature: " + err.Error())
}
_, _ = fmt.Fprintln(w, "Could not verify request signature")
}
fetchVerifier := func(r *http.Request) (string, *Verifier) {
sigName := "sig1"
verifier, _ := NewHMACSHA256Verifier(bytes.Repeat([]byte{0}, 64), NewVerifyConfig().SetKeyID("key"),
Headers("@method"))
return sigName, verifier
}
config := NewHandlerConfig().SetReqNotVerified(verifyFailed).SetFetchVerifier(fetchVerifier)
ts := httptest.NewServer(WrapHandler(http.HandlerFunc(simpleHandler), *config))
defer ts.Close()
// Client code starts here
// Create a signer and a wrapped HTTP client (we set SignCreated to false to make the response deterministic,
// don't do that in production.)
signer, _ := NewHMACSHA256Signer(bytes.Repeat([]byte{1}, 64),
NewSignConfig().SetKeyID("key1").SignCreated(false), Headers("@method"))
client := NewDefaultClient(NewClientConfig().SetSignatureName("sig22").SetSigner(signer)) // sign, don't verify
// Send an HTTP GET, get response -- signing and verification happen behind the scenes
res, err := client.Get(ts.URL)
assert.NoError(t, err, "Get failed")
assert.Equal(t, res.StatusCode, 599, "Verification did not fail?")
}