-
Notifications
You must be signed in to change notification settings - Fork 1
/
tracker_test.go
241 lines (209 loc) · 6.28 KB
/
tracker_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
// Copyright 2020 Mike Helmick
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package chaff
import (
"encoding/base64"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
"time"
"github.com/google/go-cmp/cmp"
)
func TestRandomData(t *testing.T) {
t.Parallel()
d := RandomData(0)
if d != "" {
t.Fatalf("expected empty string, got: %q", d)
}
d = RandomData(MaxRandomBytes * 2)
b, err := base64.StdEncoding.DecodeString(d)
if err != nil {
t.Fatal(err)
}
if l := len(b); l < int(float32(MaxRandomBytes)*0.99) || l > int(float32(MaxRandomBytes)*1.01) {
t.Fatalf("length is outside of 1pct of expected, want: %d got: %d", MaxRandomBytes, l)
}
}
func checkLength(t *testing.T, expected int, length int) {
t.Helper()
lower := float64(expected) * 0.99
upper := float64(expected) * 1.01
if l := float64(length); l < lower || l > upper {
t.Errorf("genrated data not within 1%% of %v, %v - %v, got %v", expected, lower, upper, l)
}
}
func TestChaff(t *testing.T) {
t.Parallel()
track := New()
defer track.Close()
// Seed the tracker with a single request.
track.recordRequest(&request{25, 250, 100})
w := httptest.NewRecorder()
r, err := http.NewRequest("GET", "/", strings.NewReader(""))
if err != nil {
t.Fatalf("http.NewRequest: %v", err)
}
before := time.Now()
track.ServeHTTP(w, r)
after := time.Now()
if d := after.Sub(before); d < 25*time.Millisecond {
t.Errorf("not enough time passed, want >= 25ms, got: %v", d)
}
if w.Code != http.StatusOK {
t.Errorf("wrong code, want: %v, got: %v", http.StatusOK, w.Code)
}
if header := w.Header().Get(Header); header == "" {
t.Errorf("expected header '%v' missing", Header)
} else {
checkLength(t, 100, len(header))
}
checkLength(t, 250, len(w.Body.Bytes()))
}
func TestTracking(t *testing.T) {
t.Parallel()
track := New()
defer track.Close()
{
want := &request{}
got := track.CalculateProfile()
if diff := cmp.Diff(want, got, cmp.AllowUnexported(request{})); diff != "" {
t.Errorf("mismatch (-want, +got):\n%s", diff)
}
}
for i := 0; i <= DefaultCapacity*2; i++ {
wrapped := track.Track(
http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
time.Sleep(1 * time.Millisecond)
w.WriteHeader(http.StatusAccepted)
w.Header().Add("padding", strings.Repeat("a", i+1))
fmt.Fprintf(w, "%s", strings.Repeat("b", i+1))
}))
recorder := httptest.NewRecorder()
request, err := http.NewRequest("GET", "/", strings.NewReader(""))
if err != nil {
t.Fatalf("http.NewRequest: %v", err)
}
wrapped.ServeHTTP(recorder, request)
if recorder.Code != http.StatusAccepted {
t.Fatalf("wrong error code: want: %v, got: %v", http.StatusAccepted, recorder.Code)
}
}
got := track.CalculateProfile()
// requests are fast enough that 1ms is reasonable.
// sum(101:200)/100 -> 150
// for header there is an extra 7 bytes for header name
want := &request{1, 150, 157}
if diff := cmp.Diff(want, got, cmp.AllowUnexported(request{})); diff != "" {
t.Errorf("mismatch (-want, +got):\n%s", diff)
}
}
func TestMax(t *testing.T) {
t.Parallel()
track := New(WithMaxLatency(25))
defer track.Close()
var wg sync.WaitGroup
for i := 0; i <= DefaultCapacity*2; i++ {
wrapped := track.Track(
http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
time.Sleep(50 * time.Millisecond)
w.WriteHeader(http.StatusAccepted)
w.Header().Add("padding", strings.Repeat("a", i+1))
fmt.Fprintf(w, "%s", strings.Repeat("b", i+1))
}))
recorder := httptest.NewRecorder()
request, err := http.NewRequest("GET", "/", strings.NewReader(""))
if err != nil {
t.Fatalf("http.NewRequest: %v", err)
}
wg.Add(1)
go func(t *testing.T) {
defer wg.Done()
t.Helper()
wrapped.ServeHTTP(recorder, request)
if recorder.Code != http.StatusAccepted {
t.Fatalf("wrong error code: want: %v, got: %v", http.StatusAccepted, recorder.Code)
}
}(t)
}
wg.Wait()
got := track.CalculateProfile()
// Only checking latency
wantLatency := uint64(25)
if diff := cmp.Diff(wantLatency, got.latencyMs); diff != "" {
t.Errorf("mismatch (-want, +got):\n%s", diff)
}
}
func TestJSONMiddleware(t *testing.T) {
t.Parallel()
type result struct {
Name string `json:"name"`
}
jsonCount, nonJSONCount := 0, 0
write := func(s string) interface{} {
jsonCount += 1
d, _ := json.Marshal(result{s})
t.Logf("writing json: %v %v", result{s}, d)
return result{s}
}
tracker, err := NewTracker(NewJSONResponder(write), DefaultCapacity)
if err != nil {
t.Fatalf("error creating tracker: %v", err)
}
defer tracker.Close()
// Start the server
srv := httptest.NewServer(tracker.HandleTrack(HeaderDetector("X-Chaff"),
http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
nonJSONCount += 1
w.Write([]byte("HERE"))
})))
defer srv.Close()
// Send a non-chaff request.
t.Logf("Getting non-chaff")
if _, err := http.Get(srv.URL); err != nil {
t.Fatalf("error connecting to server %v", err)
} else if nonJSONCount != 1 {
t.Errorf("nonJSONCount = %d, expected 1", nonJSONCount)
} else if jsonCount != 0 {
t.Errorf("jsonCount = %d, expected 0", jsonCount)
}
nonJSONCount, jsonCount = 0, 0
// Send a chaff request
req, err := http.NewRequest("GET", srv.URL, nil)
if err != nil {
t.Fatalf("error creating request %v", err)
}
req.Header.Add("X-Chaff", "true")
client := http.Client{}
t.Logf("Getting chaff")
resp, err := client.Do(req)
if err != nil {
t.Fatalf("error getting chaff: %v", err)
} else if jsonCount != 1 {
t.Errorf("jsonCount = %d, expected 1", jsonCount)
} else if nonJSONCount != 0 {
t.Errorf("nonJSONCount = %d, expected 0", nonJSONCount)
}
t.Logf("%v", resp.Header)
defer resp.Body.Close()
dat, err := ioutil.ReadAll(resp.Body)
if err != nil {
t.Fatalf("error reading response: %v", err)
}
t.Logf(string(dat))
}