-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
procrastiproxy_test.go
705 lines (572 loc) · 17.9 KB
/
procrastiproxy_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
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
package procrastiproxy
import (
"errors"
"fmt"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"
"time"
"github.com/stretchr/testify/require"
)
func TestRunCLIWithoutRequiredInputsErrors(t *testing.T) {
err := RunCLI()
require.Error(t, err)
}
func TestInvalidTimeFlagsRejected(t *testing.T) {
type TestCase struct {
Name string
BlockTimeStart string
BlockTimeEnd string
Want error
}
testCases := []TestCase{
{
Name: "Invalid BlockTimeStart rejected",
BlockTimeStart: "IamInvalid",
BlockTimeEnd: "5:00PM",
Want: InvalidTimeFormatError{},
},
{
Name: "Invalid BlockTimeEnd rejected",
BlockTimeStart: "8:10AM",
BlockTimeEnd: "45difyr8&E&FDG",
Want: InvalidTimeFormatError{},
},
{
Name: "Invalid BlockTimeStart and BlockTimeEnd values rejected",
BlockTimeStart: "ThisisntValid",
BlockTimeEnd: "AndNeitherIsThis",
Want: InvalidTimeFormatError{},
},
{
Name: "Valid start and end times accepted",
BlockTimeStart: "8:30AM",
BlockTimeEnd: "6:00PM",
Want: nil,
},
}
for _, tc := range testCases {
t.Run(tc.Name, func(t *testing.T) {
err := parseStartAndEndTimes(tc.BlockTimeStart, tc.BlockTimeEnd)
if tc.Want == nil && err == nil {
return
}
if !errors.As(err, &tc.Want) {
t.Logf("%s - wanted error of type %T but got %T", tc.Name, tc.Want, err)
t.Fail()
}
})
}
}
func TestGetList(t *testing.T) {
p := NewProcrastiproxy()
maybeList := p.GetList()
require.NotNil(t, maybeList)
}
func TestListAddResultsInExpectedElements(t *testing.T) {
type TestCase struct {
Name string
ElementsToAdd []string
}
testCases := []TestCase{
{
Name: "When adding 1 element",
ElementsToAdd: []string{"one"},
},
{
Name: "When adding 3 elements",
ElementsToAdd: []string{"thing1", "thing2", "thing3"},
},
{
Name: "When adding 4 elements",
ElementsToAdd: []string{"one fish", "two fish", "red fish", "blue fish"},
},
}
for _, tc := range testCases {
tc := tc
p := NewProcrastiproxy()
// Reset the list singleton before each test case is run
l := p.GetList()
t.Run(tc.Name, func(t *testing.T) {
for _, item := range tc.ElementsToAdd {
l.Add(item)
}
require.Equal(t, len(tc.ElementsToAdd), l.Length())
require.True(t, SlicesAreEqual(tc.ElementsToAdd, l.All()))
})
}
}
func TestListClear(t *testing.T) {
type TestCase struct {
Name string
ElementsToAdd []string
}
testCases := []TestCase{
{
Name: "List clear removes three elements",
ElementsToAdd: []string{"one", "two", "three"},
},
{
Name: "List clear removes ten elements",
ElementsToAdd: []string{"one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten"},
},
}
for _, tc := range testCases {
tc := tc
p := NewProcrastiproxy()
l := p.GetList()
t.Run(tc.Name, func(t *testing.T) {
for _, item := range tc.ElementsToAdd {
l.Add(item)
}
if len(tc.ElementsToAdd) != l.Length() {
t.Errorf("Expected len(tc.ElementsToAdd): %d to equal length of list: %d", len(tc.ElementsToAdd), l.Length())
}
// Clear the list and ensure it contains no elements
l.Clear()
if l.Length() != 0 {
t.Errorf("Expected test list to have zero members after calling l.Clear() but got length of %d", l.Length())
}
})
}
}
func TestListRemoveResultsInExpectedElements(t *testing.T) {
type TestCase struct {
Name string
ElementsToAdd []string
ElementsToRemove []string
Want []string
}
testCases := []TestCase{
{
Name: "Removing 2 elements",
ElementsToAdd: []string{"one", "two", "three", "four"},
ElementsToRemove: []string{"one", "two"},
Want: []string{"three", "four"},
},
}
for _, tc := range testCases {
p := NewProcrastiproxy()
l := p.GetList()
t.Run(tc.Name, func(t *testing.T) {
for _, item := range tc.ElementsToAdd {
l.Add(item)
}
for _, item := range tc.ElementsToRemove {
l.Remove(item)
}
require.Equal(t, len(tc.Want), l.Length())
})
}
}
// TestHostBlocking ensures that you can access a host via the block list aware handler before it is added to the block list,
// but not after it is added to the block list
func TestHostBlocking(t *testing.T) {
t.Parallel()
p := NewProcrastiproxy()
// Create a test server to mimic reddit.com
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
fmt.Fprintln(w, "OK")
}))
defer ts.Close()
// First, ensure that the target host can be reached before it is added to the block list
fr := httptest.NewRequest("GET", ts.URL, strings.NewReader(""))
fw := httptest.NewRecorder()
http.HandlerFunc(p.blockListAwareHandler).ServeHTTP(fw, fr)
if fw.Code != http.StatusOK {
t.Logf("Wanted HTTP StatusCode: %d for URL prior to adding host to block list: %s but got: %d\n", http.StatusOK, ts.URL, fw.Code)
}
u, parseErr := url.Parse(ts.URL)
require.NoError(t, parseErr)
AddHostToBlockList(p.GetList(), u.Host)
// Next, ensure the same host cannot be accessed after being added to the block list
r := httptest.NewRequest("GET", ts.URL, strings.NewReader(""))
w := httptest.NewRecorder()
http.HandlerFunc(p.blockListAwareHandler).ServeHTTP(w, r)
if w.Code != http.StatusForbidden {
t.Logf("Wanted HTTP StatusCode: %d for URL after adding host to block list: %s but got: %d\n", http.StatusForbidden, ts.URL, w.Code)
t.Fail()
}
}
// TestProxiedHost ensures that you can use the proxyHandler to do "pass-through" network requests
func TestProxiedHost(t *testing.T) {
t.Parallel()
p := NewProcrastiproxy()
// Create a test server to mimic reddit.com
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
fmt.Fprintln(w, "OK")
}))
defer ts.Close()
// First, ensure that the target host can be reached before it is added to the block list
r := httptest.NewRequest("GET", ts.URL, strings.NewReader(""))
w := httptest.NewRecorder()
http.HandlerFunc(p.proxyHandler).ServeHTTP(w, r)
if w.Code != http.StatusOK {
t.Logf("Wanted HTTP StatusCode: %d for URL: %s but got: %d\n", http.StatusOK, ts.URL, w.Code)
t.Fail()
}
}
func TestTimeAwareHandler(t *testing.T) {
type TestCase struct {
Name string
StartBlockTime string
EndBlockTime string
Now func() time.Time
Want int
}
testCases := []TestCase{
{
Name: "Request is forbidden when made 1 minute after block window begins",
StartBlockTime: "9:00AM",
EndBlockTime: "5:00PM",
Now: func() time.Time {
n := time.Now()
// Create a "fake" date time to use for the Procrastiproxy's Now method that is set to be 9:01AM
test := time.Date(n.Year(), n.Month(), n.Day(), 9, 1, 0, 0, time.UTC)
return test
},
Want: http.StatusForbidden,
},
{
Name: "Request is forbidden when made 3 hours after block window begins",
StartBlockTime: "9:00AM",
EndBlockTime: "5:00PM",
Now: func() time.Time {
n := time.Now()
// Create a "fake" date time to use for the Procrastiproxy's Now method that is set to be 12 noon
test := time.Date(n.Year(), n.Month(), n.Day(), 12, 0, 0, 0, time.UTC)
return test
},
Want: http.StatusForbidden,
},
{
Name: "Request is allowed when made 22 hours before block window begins",
StartBlockTime: "9:00AM",
EndBlockTime: "5:00PM",
Now: func() time.Time {
n := time.Now()
// Create a "fake" date time to use for the Procrastiproxy's Now method that is set to be 6:00AM
test := time.Date(n.Year(), n.Month(), n.Day(), 6, 0, 0, 0, time.UTC)
return test
},
Want: http.StatusOK,
},
{
Name: "Request is allowed when made 3 minutes before block window begins",
StartBlockTime: "9:00AM",
EndBlockTime: "5:00PM",
Now: func() time.Time {
n := time.Now()
// Create a "fake" date time to use for the Procrastiproxy's Now method that is set to be 8:57AM
test := time.Date(n.Year(), n.Month(), n.Day(), 8, 57, 0, 0, time.UTC)
return test
},
Want: http.StatusOK,
},
{
Name: "Request is allowed when made 1 minute after block window ends",
StartBlockTime: "9:00AM",
EndBlockTime: "5:00PM",
Now: func() time.Time {
n := time.Now()
// Create a "fake" date time to use for the Procrastiproxy's Now method that is set to be 5:01PM
test := time.Date(n.Year(), n.Month(), n.Day(), 17, 1, 0, 0, time.UTC)
return test
},
Want: http.StatusOK,
},
}
for _, tc := range testCases {
tc := tc
t.Run(tc.Name, func(t *testing.T) {
p := NewProcrastiproxy()
p.Now = tc.Now
testHost := "example.com"
testHostURL := fmt.Sprintf("http://%s", testHost)
AddHostToBlockList(p.GetList(), testHost)
parseErr := parseStartAndEndTimes(tc.StartBlockTime, tc.EndBlockTime)
require.NoError(t, parseErr)
p.ConfigureProxyTimeSettings(tc.StartBlockTime, tc.EndBlockTime)
fr := httptest.NewRequest("GET", testHostURL, strings.NewReader(""))
rw := httptest.NewRecorder()
http.HandlerFunc(p.timeAwareHandler).ServeHTTP(rw, fr)
if rw.Code != tc.Want {
t.Logf("Wanted status code: %d for test: %s but got: %d", tc.Want, tc.Name, rw.Code)
t.Fail()
}
})
}
}
// TestAdminHandlerBlocksHostsDynamicallt ensures that you can dynamically add a new host to the block list
// via the admin/block endpoint, that will be respected for all subsequent requests
func TestAdminHandlerBlocksHostsDynamically(t *testing.T) {
t.Parallel()
p := NewProcrastiproxy()
// Sanity check the initial block list is empty
require.Equal(t, p.GetList().Length(), 0)
testHost := "docker.com"
// Sanity check that we can initially reach the target host because it has not yet been blocked
testHostURL := "http://docker.com"
fr := httptest.NewRequest("GET", testHostURL, strings.NewReader(""))
rw := httptest.NewRecorder()
http.HandlerFunc(p.blockListAwareHandler).ServeHTTP(rw, fr)
if rw.Code != http.StatusOK {
t.Logf("Wanted HTTP StatusCode: %d for URL: %s but got: %d\n", http.StatusOK, testHostURL, rw.Code)
t.Fail()
}
// Now, dynamically block the same target host by making a request to the admin block endpoint, passing the host info
testURL := fmt.Sprintf("http://localhost:8000/admin/block/%s", testHost)
r := httptest.NewRequest("GET", testURL, strings.NewReader(""))
w := httptest.NewRecorder()
http.HandlerFunc(p.adminHandler).ServeHTTP(w, r)
if w.Code != http.StatusOK {
t.Logf("Wanted HTTP StatusCode: %d for URL: %s but got: %d\n", http.StatusOK, testURL, w.Code)
t.Fail()
}
// Finally, ensure the host we just dynamically added to the block list is found
require.True(t, p.GetList().Contains(testHost))
require.Equal(t, p.GetList().Length(), 1)
// Ensure that, attempting to hit the same host now fails because it is blocked at the proxy level
ar := httptest.NewRequest("GET", testHostURL, strings.NewReader(""))
aw := httptest.NewRecorder()
http.HandlerFunc(p.blockListAwareHandler).ServeHTTP(aw, ar)
if aw.Code != http.StatusForbidden {
t.Logf("Wanted HTTP StatusCode: %d for URL: %s but got: %d\n", http.StatusForbidden, testHostURL, aw.Code)
t.Fail()
}
}
// TestAdminHandlerUnblocksHostsDynamically ensures that a blocked host can be removed from the block list via the admin/unblock endpoint
func TestAdminHandlerUnblocksHostsDynamically(t *testing.T) {
t.Parallel()
p := NewProcrastiproxy()
testHost := "wikipedia.com"
testHostURL := fmt.Sprintf("http://%s", testHost)
// Pre-populate the list with the test host
p.GetList().Add(testHost)
require.True(t, p.GetList().Contains(testHost))
// Sanity check that you cannot get the blocked test host to begin with
fr := httptest.NewRequest("GET", testHostURL, strings.NewReader(""))
rw := httptest.NewRecorder()
http.HandlerFunc(p.blockListAwareHandler).ServeHTTP(rw, fr)
if rw.Code != http.StatusForbidden {
t.Logf("Wanted HTTP StatusCode: %d for URL: %s but got: %d\n", http.StatusForbidden, testHostURL, rw.Code)
t.Fail()
}
// Now, dynamically unblock the same test host by making a request to the admin unblock endpoint
testAdminURL := fmt.Sprintf("http://localhost:8000/admin/unblock/%s", testHost)
r := httptest.NewRequest("GET", testAdminURL, strings.NewReader(""))
w := httptest.NewRecorder()
http.HandlerFunc(p.adminHandler).ServeHTTP(w, r)
if w.Code != http.StatusOK {
t.Logf("Wanted HTTP StatusCode: %d for URL: %s but got: %d\n", http.StatusOK, testAdminURL, w.Code)
t.Fail()
}
// Ensure the host we just dynamically removed from the block list is no longer found on it
require.False(t, p.GetList().Contains(testHost))
require.Equal(t, p.GetList().Length(), 0)
// Ensure that we can access the test host now that it has been unblocked via the admin endpoint
ar := httptest.NewRequest("GET", testHostURL, strings.NewReader(""))
aw := httptest.NewRecorder()
http.HandlerFunc(p.blockListAwareHandler).ServeHTTP(aw, ar)
if aw.Code != http.StatusOK {
t.Logf("Wanted HTTP StatusCode: %d for URL: %s but got: %d\n", http.StatusOK, testHostURL, aw.Code)
t.Fail()
}
}
func TestWithinBlockWindow_IsTrue(t *testing.T) {
testCases := []struct {
Name string
CheckTime string
}{
{
Name: "At start time",
CheckTime: "9:00AM",
},
{
Name: "1 minute after start time",
CheckTime: "9:01AM",
},
{
Name: "1 minute before end time",
CheckTime: "4:59PM",
},
{
Name: "2 hours after start time",
CheckTime: "11:00AM",
},
{
Name: "3 hours after start time",
CheckTime: "12:00PM",
},
{
Name: "4 hours after start time",
CheckTime: "1:00PM",
},
{
Name: "1 hour before end time",
CheckTime: "4:00PM",
},
}
for _, tc := range testCases {
t.Run(tc.Name, func(t *testing.T) {
// Create a new instance of Procrastiproxy
p := NewProcrastiproxy()
// Configure its timing window
p.ConfigureProxyTimeSettings("9:00AM", "5:00PM")
parsedCheckTime, parseErr := time.Parse(time.Kitchen, tc.CheckTime)
if parseErr != nil {
t.Logf("Error parsing check time: %s - error: %s\n", tc.CheckTime, parseErr)
}
// Test the WithinBlockWindow method
got := p.WithinBlockWindow(parsedCheckTime)
t.Logf("tc.CheckTime: %s\n", tc.CheckTime)
if !got {
t.Logf("Wanted: %v for WithinBlockWindow (%v, %v), but got: %v\n", true, tc.CheckTime, p.GetProxyTimeSettings(), got)
t.Fail()
}
})
}
}
func TestWithinBlockWindow_IsFalse(t *testing.T) {
testCases := []struct {
Name string
CheckTime string
}{
{
Name: "At end time",
CheckTime: "5:00PM",
},
{
Name: "1 hour before start time",
CheckTime: "8:00AM",
},
{
Name: "1 minute before start time",
CheckTime: "8:59AM",
},
{
Name: "2 hours after end time",
CheckTime: "7:00PM",
},
{
Name: "3 hours after end time",
CheckTime: "8:00PM",
},
{
Name: "4 hours after end time",
CheckTime: "9:00PM",
},
{
Name: "1 minute after end time",
CheckTime: "5:01PM",
},
}
for _, tc := range testCases {
t.Run(tc.Name, func(t *testing.T) {
// Create a new instance of Procrastiproxy
p := NewProcrastiproxy()
// Configure its timing window
p.ConfigureProxyTimeSettings("9:00AM", "5:00PM")
parsedCheckTime, parseErr := time.Parse(time.Kitchen, tc.CheckTime)
if parseErr != nil {
t.Logf("Error parsing check time: %s - error: %s\n", tc.CheckTime, parseErr)
}
// Test the WithinBlockWindow method
got := p.WithinBlockWindow(parsedCheckTime)
t.Logf("tc.CheckTime: %s\n", tc.CheckTime)
if got {
t.Logf("Wanted: %v for WithinBlockWindow (%v, %v), but got: %v\n", false, tc.CheckTime, p.GetProxyTimeSettings(), got)
t.Fail()
}
})
}
}
func TestValidateBlockListInputErrorsOnEmptyMemberSlice(t *testing.T) {
err := validateBlockListInput([]string{})
require.Error(t, err)
if emptyBlockListErr, ok := err.(EmptyBlockListError); !ok {
t.Logf("Expected error of type: %T, but got: %T", EmptyBlockListError{}, emptyBlockListErr)
t.Fail()
}
}
func TestParseBlockListInput(t *testing.T) {
type TestCase struct {
Name string
InputString string
Want []string
}
testCases := []TestCase{
{
Name: "single block host input",
InputString: "reddit.com",
Want: []string{"reddit.com"},
},
{
Name: "two block hosts input",
InputString: "reddit.com,nytimes.com",
Want: []string{"reddit.com", "nytimes.com"},
},
{
Name: "three block hosts input",
InputString: "reddit.com,nytimes.com,twitter.com",
Want: []string{"reddit.com", "nytimes.com", "twitter.com"},
},
}
for _, tc := range testCases {
l := NewList()
t.Run(tc.Name, func(t *testing.T) {
err := parseBlockListInput(&tc.InputString, l)
require.NoError(t, err)
// Ensure list has expected members following parsing
for _, member := range tc.Want {
require.True(t, l.Contains(member))
//Also sanity check that hostIsBlocked returns true
require.True(t, hostIsOnBlockList(member, l))
}
})
}
}
func TestParseStartAndEndTimes(t *testing.T) {
type TestCase struct {
Name string
StartTimeString string
EndTimeString string
}
testCases := []TestCase{
{
Name: "top of the hour",
StartTimeString: "9:00AM",
EndTimeString: "5:00PM",
},
{
Name: "minutes defined",
StartTimeString: "9:38AM",
EndTimeString: "5:14PM",
},
{
Name: "15 minute block window",
StartTimeString: "9:00AM",
EndTimeString: "9:15AM",
},
{
Name: "1 minute block window",
StartTimeString: "9:00AM",
EndTimeString: "9:01AM",
},
{
Name: "18 hour block window",
StartTimeString: "12:00AM",
EndTimeString: "6:00PM",
},
}
for _, tc := range testCases {
t.Run(tc.Name, func(t *testing.T) {
err := parseStartAndEndTimes(tc.StartTimeString, tc.EndTimeString)
require.NoError(t, err)
})
}
}