forked from juneym/gor
-
Notifications
You must be signed in to change notification settings - Fork 0
/
middleware_test.go
226 lines (180 loc) · 5.5 KB
/
middleware_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
package main
import (
"bytes"
"crypto/rand"
"encoding/hex"
"net/http"
"net/http/httptest"
"net/http/httputil"
"strings"
"sync"
"testing"
"time"
"github.com/buger/goreplay/capture"
"github.com/buger/goreplay/proto"
)
type fakeServiceCb func(string, int, []byte)
// Simple service that generate token on request, and require this token for accesing to secure area
func NewFakeSecureService(wg *sync.WaitGroup, cb fakeServiceCb) *httptest.Server {
activeTokens := make([]string, 0)
var mu sync.Mutex
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
mu.Lock()
defer mu.Unlock()
switch req.URL.Path {
case "/token":
// Generate random token
tokenLength := 10
buf := make([]byte, tokenLength)
rand.Read(buf)
token := hex.EncodeToString(buf)
activeTokens = append(activeTokens, token)
w.Write([]byte(token))
cb(req.URL.Path, 200, []byte(token))
case "/secure":
token := req.URL.Query().Get("token")
tokenFound := false
for _, t := range activeTokens {
if t == token {
tokenFound = true
break
}
}
if tokenFound {
w.WriteHeader(http.StatusAccepted)
cb(req.URL.Path, 202, nil)
} else {
w.WriteHeader(http.StatusForbidden)
cb(req.URL.Path, 403, nil)
}
}
wg.Done()
}))
return server
}
func TestFakeSecureService(t *testing.T) {
var resp, token []byte
wg := new(sync.WaitGroup)
server := NewFakeSecureService(wg, func(path string, status int, resp []byte) {
})
defer server.Close()
wg.Add(3)
client := NewHTTPClient(&HTTPOutputConfig{}).Client
rep, _ := client.Get(server.URL + "/token")
resp, _ = httputil.DumpResponse(rep, true)
token = proto.Body(resp)
// Right token
rep, _ = client.Get(server.URL + "/secure?token=" + string(token))
resp, _ = httputil.DumpResponse(rep, true)
if !bytes.Equal(proto.Status(resp), []byte("202")) {
t.Error("Valid token should return status 202:", string(proto.Status(resp)))
}
// Wrong tokens forbidden
rep, _ = client.Get(server.URL + "/secure?token=wrong")
resp, _ = httputil.DumpResponse(rep, true)
if !bytes.Equal(proto.Status(resp), []byte("403")) {
t.Error("Wrong token should returns status 403:", string(proto.Status(resp)))
}
wg.Wait()
}
func TestEchoMiddleware(t *testing.T) {
wg := new(sync.WaitGroup)
from := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Env", "prod")
w.Header().Set("RequestPath", r.URL.Path)
wg.Done()
}))
defer from.Close()
to := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Env", "test")
w.Header().Set("RequestPath", r.URL.Path)
wg.Done()
}))
defer to.Close()
// Catch traffic from one service
fromAddr := strings.Replace(from.Listener.Addr().String(), "[::]", "127.0.0.1", -1)
conf := RAWInputConfig{
Engine: capture.EnginePcap,
Expire: testRawExpire,
Protocol: ProtocolHTTP,
TrackResponse: true,
}
input := NewRAWInput(fromAddr, conf)
// And redirect to another
output := NewHTTPOutput(to.URL, &HTTPOutputConfig{})
plugins := &InOutPlugins{
Inputs: []PluginReader{input},
Outputs: []PluginWriter{output},
}
plugins.All = append(plugins.All, input, output)
// Start Gor
emitter := NewEmitter()
emitter.Start(plugins, "echo -n && GOR_TEST=true && ./examples/middleware/echo.sh")
// Wait till middleware initialization
time.Sleep(100 * time.Millisecond)
// Should receive 2 requests from original + 2 from replayed
client := NewHTTPClient(output.(*HTTPOutput).config).Client
for i := 0; i < 10; i++ {
wg.Add(2)
// Request should be echoed
client.Get(to.URL + "/a")
time.Sleep(5 * time.Millisecond)
client.Get(to.URL + "/b")
time.Sleep(5 * time.Millisecond)
}
wg.Wait()
emitter.Close()
}
func TestTokenMiddleware(t *testing.T) {
var resp, token []byte
wg := new(sync.WaitGroup)
from := NewFakeSecureService(wg, func(path string, status int, tok []byte) {
time.Sleep(10 * time.Millisecond)
})
defer from.Close()
to := NewFakeSecureService(wg, func(path string, status int, tok []byte) {
switch path {
case "/secure":
if status != 202 {
t.Error("Server should receive valid rewritten token")
}
}
time.Sleep(10 * time.Millisecond)
})
defer to.Close()
Settings.Middleware = "echo -n && GOR_TEST=true && go run ./examples/middleware/token_modifier.go"
fromAddr := strings.Replace(from.Listener.Addr().String(), "[::]", "127.0.0.1", -1)
conf := RAWInputConfig{
Engine: capture.EnginePcap,
Expire: testRawExpire,
Protocol: ProtocolHTTP,
TrackResponse: true,
}
// Catch traffic from one service
input := NewRAWInput(fromAddr, conf)
// And redirect to another
output := NewHTTPOutput(to.URL, &HTTPOutputConfig{})
plugins := &InOutPlugins{
Inputs: []PluginReader{input},
Outputs: []PluginWriter{output},
}
plugins.All = append(plugins.All, input, output)
// Start Gor
emitter := NewEmitter()
emitter.Start(plugins, Settings.Middleware)
// Should receive 2 requests from original + 2 from replayed
wg.Add(2)
client := NewHTTPClient(&HTTPOutputConfig{}).Client
// Sending traffic to original service
rep, _ := client.Get(to.URL + "/token")
resp, _ = httputil.DumpResponse(rep, true)
token = proto.Body(resp)
rep, _ = client.Get(to.URL + "/secure?token=" + string(token))
resp, _ = httputil.DumpResponse(rep, true)
if !bytes.Equal(proto.Status(resp), []byte("202")) {
t.Error("Valid token should return 202:", proto.Status(resp))
}
wg.Wait()
emitter.Close()
Settings.Middleware = ""
}