Repository navigation
Expand file tree
/
Copy pathmain_test.go
More file actions
296 lines (270 loc) · 8.59 KB
/
Copy pathmain_test.go
File metadata and controls
296 lines (270 loc) · 8.59 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
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
package main
import (
"bytes"
"crypto/sha256"
"encoding/hex"
"html/template"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"
"time"
)
func TestClientIP(t *testing.T) {
cases := []struct {
name string
realIP bool
xff string
want string
}{
{"disabled ignores header", false, "203.0.113.5", "10.0.0.1"},
{"first entry wins", true, "203.0.113.5, 10.0.0.2", "203.0.113.5"},
{"ipv6 with whitespace", true, " 2001:db8::1 ", "2001:db8::1"},
{"garbage falls back", true, "garbage, 10.0.0.2", "10.0.0.1"},
{"missing header falls back", true, "", "10.0.0.1"},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
s := &server{config: Config{EnableRealIP: c.realIP}}
r := httptest.NewRequest(http.MethodPost, "/join", nil)
r.RemoteAddr = "10.0.0.1:1234"
r.Header.Set("X-Real-IP", "198.51.100.9") // must never be used
if c.xff != "" {
r.Header.Set("X-Forwarded-For", c.xff)
}
if got := s.clientIP(r); got != c.want {
t.Errorf("got %q, want %q", got, c.want)
}
})
}
}
func TestLimiterKey(t *testing.T) {
cases := []struct{ in, want string }{
{"203.0.113.5", "203.0.113.5"},
{"::ffff:203.0.113.5", "203.0.113.5"},
{"2001:db8:1:2:aaaa::1", "2001:db8:1:2::/64"},
{"2001:db8:1:3::1", "2001:db8:1:3::/64"},
{"garbage", "garbage"},
}
for _, c := range cases {
if got := limiterKey(c.in); got != c.want {
t.Errorf("limiterKey(%q) = %q, want %q", c.in, got, c.want)
}
}
}
func TestRateLimiterSharesIPv6Prefix(t *testing.T) {
rl := &rateLimiter{addrs: make(map[string]*addrState)}
rl.recordFailure(limiterKey("2001:db8:1:2::1"))
if d := rl.retryAfter(limiterKey("2001:db8:1:2:ffff:ffff:ffff:ffff")); d <= 0 {
t.Errorf("address in same /64 should be blocked, got %v", d)
}
if d := rl.retryAfter(limiterKey("2001:db8:1:3::1")); d != 0 {
t.Errorf("address in different /64 should not be blocked, got %v", d)
}
if n := rl.activeIPs(); n != 1 {
t.Errorf("want 1 limiter entry, got %d", n)
}
}
func TestRateLimiter(t *testing.T) {
rl := &rateLimiter{addrs: make(map[string]*addrState)}
if d := rl.retryAfter("a"); d != 0 {
t.Fatalf("unknown addr should not be blocked, got %v", d)
}
rl.recordFailure("a")
if d := rl.retryAfter("a"); d <= 0 || d > rlDelayBase {
t.Errorf("after one failure want block up to %v, got %v", rlDelayBase, d)
}
for i := 0; i < 100; i++ {
rl.recordFailure("a")
}
if d := rl.retryAfter("a"); d > rlDelayMax {
t.Errorf("block should be capped at %v, got %v", rlDelayMax, d)
}
if d := rl.retryAfter("b"); d != 0 {
t.Errorf("other addr must not be affected, got %v", d)
}
if n := rl.activeIPs(); n != 1 {
t.Errorf("want 1 tracked IP, got %d", n)
}
rl.reset("a")
if d := rl.retryAfter("a"); d != 0 {
t.Errorf("reset should clear block, got %v", d)
}
// A stale entry not yet evicted must not carry its old failure count.
for i := 0; i < 5; i++ {
rl.recordFailure("old")
}
rl.addrs["old"].lastSeen = time.Now().Add(-rlResetAfter - time.Minute)
rl.recordFailure("old")
if f := rl.addrs["old"].failures; f != 1 {
t.Errorf("stale entry should restart counting, got %d failures", f)
}
// Requests no longer evict; only the cleanup does.
rl.recordFailure("stale")
rl.addrs["stale"].lastSeen = time.Now().Add(-rlResetAfter - time.Minute)
rl.recordFailure("fresh")
rl.retryAfter("fresh")
if _, ok := rl.addrs["stale"]; !ok {
t.Error("requests should not scan the table for stale entries")
}
rl.evictStale()
if _, ok := rl.addrs["stale"]; ok {
t.Error("stale entry should have been evicted")
}
if _, ok := rl.addrs["fresh"]; !ok {
t.Error("fresh entry should have been kept")
}
}
func TestBBBURL(t *testing.T) {
base, _ := url.Parse("https://bbb.example.com/bigbluebutton/")
cfg := Config{BBBURL: base, BBBSecret: "s3cret"}
params := url.Values{"meetingID": {"room a"}, "fullName": {"Jäne & Co"}}
got, err := url.Parse(bbbURL(cfg, "join", params))
if err != nil {
t.Fatal(err)
}
if got.Path != "/bigbluebutton/api/join" {
t.Errorf("path = %q", got.Path)
}
q := got.Query()
if q.Get("fullName") != "Jäne & Co" || q.Get("meetingID") != "room a" {
t.Errorf("params not preserved: %v", q)
}
// Checksum is SHA256(call + query-without-checksum + secret).
q.Del("checksum")
sum := sha256.Sum256([]byte("join" + q.Encode() + "s3cret"))
if want := hex.EncodeToString(sum[:]); got.Query().Get("checksum") != want {
t.Errorf("checksum = %q, want %q", got.Query().Get("checksum"), want)
}
}
func TestCreateMeetingAndJoinURL(t *testing.T) {
var gotQuery url.Values
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
gotQuery = r.URL.Query()
_, _ = w.Write([]byte(`<response><returncode>SUCCESS</returncode>` +
`<meetingID>r1</meetingID><createTime>123</createTime></response>`))
}))
defer srv.Close()
base, _ := url.Parse(srv.URL + "/bbb/")
cfg := Config{BBBURL: base, BBBSecret: "x", FrontendURL: "https://meet.example.com"}
resp, err := createMeeting(cfg, Room{ID: "r1", Name: "Room", Record: true}, srv.Client())
if err != nil {
t.Fatal(err)
}
if resp.MeetingID != "r1" || resp.CreateTime != "123" {
t.Errorf("unexpected response %+v", resp)
}
if gotQuery.Get("record") != "true" || gotQuery.Get("logoutURL") != cfg.FrontendURL {
t.Errorf("unexpected create params %v", gotQuery)
}
join, _ := url.Parse(generateJoinURL(cfg, resp.MeetingID, resp.CreateTime, "Jane", "VIEWER"))
q := join.Query()
if q.Get("createTime") != "123" || q.Get("role") != "VIEWER" || q.Get("checksum") == "" {
t.Errorf("unexpected join params %v", q)
}
}
func TestIndexTemplateConsent(t *testing.T) {
tmpl := template.Must(template.ParseFS(staticFiles, "static/index.html"))
rooms := []Room{{ID: "a", Name: "A"}, {ID: "b", Name: "B", Record: true}}
s := &server{config: Config{Rooms: rooms}}
render := func(errCode, room string) string {
var buf bytes.Buffer
if err := tmpl.Execute(&buf, s.indexData(errCode, "", room)); err != nil {
t.Fatal(err)
}
return buf.String()
}
out := render("password", "b")
for _, want := range []string{
errorMessages["password"],
`data-record="false"`,
`data-record="true"`,
`B (rec)`,
`id="consent-wrap" class="consent-wrap">`,
`name="recording_consent" id="recording_consent" required>`,
} {
if !strings.Contains(out, want) {
t.Errorf("missing %q", want)
}
}
out = render("<b>bogus</b>", "a")
if strings.Contains(out, "bogus") || !strings.Contains(out, `class="consent-wrap" hidden>`) {
t.Errorf("unknown error code rendered or consent not hidden")
}
}
func TestLoadRooms(t *testing.T) {
set := func(kv ...string) {
for i := 0; i < len(kv); i += 2 {
t.Setenv(kv[i], kv[i+1])
}
}
set("ROOM_1_ID", "a", "ROOM_1_NAME", "A", "ROOM_1_RECORD", "True",
"ROOM_2_ID", "b", "ROOM_2_NAME", "B")
rooms, err := loadRooms()
if err != nil || len(rooms) != 2 {
t.Fatalf("got %v rooms, err %v", len(rooms), err)
}
if !rooms[0].Record || rooms[1].Record {
t.Errorf("record parsing wrong: %+v", rooms)
}
if findRoom(rooms, "missing").ID != "a" {
t.Error("unknown room should fall back to the first room")
}
set("ROOM_2_NAME", "")
if _, err := loadRooms(); err == nil || !strings.Contains(err.Error(), "ROOM_2_NAME") {
t.Errorf("missing name should fail, got %v", err)
}
set("ROOM_2_NAME", "B", "ROOM_2_ID", "a")
if _, err := loadRooms(); err == nil || !strings.Contains(err.Error(), "duplicates") {
t.Errorf("duplicate id should fail, got %v", err)
}
set("ROOM_1_ID", "")
if _, err := loadRooms(); err == nil {
t.Error("no rooms should fail")
}
}
func TestStaticNoDirListing(t *testing.T) {
h := noDirListing(http.FileServer(http.FS(staticFiles)))
cases := []struct {
path string
want int
}{
{"/static/", http.StatusNotFound},
{"/static/css/", http.StatusNotFound},
{"/static/css/style.css", http.StatusOK},
}
for _, c := range cases {
t.Run(c.path, func(t *testing.T) {
w := httptest.NewRecorder()
h.ServeHTTP(w, httptest.NewRequest(http.MethodGet, c.path, nil))
if w.Code != c.want {
t.Errorf("got %d, want %d", w.Code, c.want)
}
})
}
}
func TestValidName(t *testing.T) {
cases := []struct {
name string
want bool
}{
{"", false},
{"Jane Smith", true},
{strings.Repeat("a", maxNameLength), true},
{strings.Repeat("a", maxNameLength+1), false},
{strings.Repeat("名", maxNameLength), true},
{strings.Repeat("名", maxNameLength+1), false},
{strings.Repeat("😀", maxNameLength), true},
{"Jane\x00Smith", false},
{"Jane\tSmith", false},
{"Jane\nSmith", false},
{"Jane\u0085Smith", false},
{"Jane\xffSmith", false},
}
for _, c := range cases {
if got := validName(c.name); got != c.want {
t.Errorf("validName(%q) = %v, want %v", c.name, got, c.want)
}
}
}