-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmain_test.go
396 lines (353 loc) · 10.5 KB
/
main_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
package main
import (
"bytes"
"context"
"encoding/json"
"fmt"
"log"
"log/slog"
"net/http"
"net/http/httptest"
"net/url"
"os"
"path/filepath"
"reflect"
"strings"
"testing"
"time"
"golang.org/x/mod/module"
"golang.org/x/mod/sumdb"
"golang.org/x/mod/sumdb/dirhash"
"github.com/mjl-/bstore"
"github.com/mjl-/mox/dns"
"github.com/mjl-/mox/smtp"
"github.com/mjl-/mox/webapi"
"github.com/mjl-/mox/webhook"
"github.com/mjl-/sherpa"
)
// todo: test rate limits, imap/submission, more backing off, webhook delivery failure handling and HookCancel/HookKick api calls.
var ctxbg = context.Background()
func tcheckf(t *testing.T, err error, format string, args ...any) {
if err != nil {
t.Helper()
t.Fatalf("%s: %s", fmt.Sprintf(format, args...), err)
}
}
func tcompare(t *testing.T, got, exp any) {
if !reflect.DeepEqual(got, exp) {
t.Helper()
t.Fatalf("got %v, expected %v (%#v != %#v)", got, exp, got, exp)
}
}
func thttppost(t *testing.T, mux http.Handler, path string, data url.Values, expCode int) {
t.Helper()
req := httptest.NewRequest("POST", path, strings.NewReader(data.Encode()))
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
w := httptest.NewRecorder()
mux.ServeHTTP(w, req)
if w.Code != expCode {
t.Fatalf("http post to %s: got status %d, expected %d", path, w.Code, expCode)
}
}
func thttpget(t *testing.T, mux http.Handler, path string, headers map[string]string, expCode int) {
t.Helper()
req := httptest.NewRequest("GET", path, nil)
for k, v := range headers {
req.Header.Add(k, v)
}
w := httptest.NewRecorder()
mux.ServeHTTP(w, req)
if w.Code != expCode {
t.Fatalf("http post to %s: got status %d, expected %d", path, w.Code, expCode)
}
}
func thttpsherpa(t *testing.T, mux http.Handler, path string, csrf, session string, params []any, expCode string) {
t.Helper()
body, err := json.Marshal(map[string]any{"params": params})
tcheckf(t, err, "marshal request")
req := httptest.NewRequest("POST", path, bytes.NewReader(body))
req.Header.Add("Content-Type", "application/json")
if csrf != "" {
req.Header.Add("x-csrf", csrf)
}
if session != "" {
c := http.Cookie{
Name: "gopherwatchsession",
Value: session,
HttpOnly: true,
SameSite: http.SameSiteStrictMode,
}
req.AddCookie(&c)
}
w := httptest.NewRecorder()
mux.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Fatalf("http post to %s: got status %d, expected 200 ok", path, w.Code)
}
var resp struct {
Error *sherpa.Error `json:"error"`
Result any `json:"result"`
}
err = json.Unmarshal(w.Body.Bytes(), &resp)
tcheckf(t, err, "unmarshal body")
if (expCode == "") != (resp.Error == nil) || expCode != "" && resp.Error.Code != expCode {
t.Fatalf("expected code %q, got error %v", expCode, resp.Error)
}
}
func tneederr(t *testing.T, code string, fn func()) {
t.Helper()
defer func() {
t.Helper()
x := recover()
// We panic so we get stack traces in the error.
if x == nil {
panic(fmt.Sprintf("expected error code %q, got no error", code))
}
err, ok := x.(*sherpa.Error)
if !ok {
panic(fmt.Sprintf("expected error code %q, got other panic type %T %v", code, x, x))
}
if err.Code != code {
panic(fmt.Sprintf("expected error code %q, got %q", code, err.Code))
}
}()
fn()
}
func tneedmail(t *testing.T, subject string) moxtx {
t.Helper()
return tneedmail0(t, config.SubjectPrefix+subject)
}
func tneedmail0(t *testing.T, subject string) moxtx {
t.Helper()
select {
case mailSubmitted <- struct{}{}:
// Trigger mox webhook for outgoing delivery.
case <-time.After(time.Second):
t.Fatalf("no mail submission within 1s")
}
select {
case <-mailDelivered:
// Wait for mail delivery.
case <-time.After(time.Second):
t.Fatalf("no mail received within 1s")
}
if len(moxapiTx) != 1 {
t.Fatalf("mails sent %#v", moxapiTx)
}
tcompare(t, len(moxapiTx), 1)
tx := moxapiTx[0]
tcompare(t, tx.Subject, subject)
moxapiTx = nil
return tx
}
var sumsrv *sumdb.TestServer
var sumhttpsrv *httptest.Server
var sumindex []indexMod
const testskey = "PRIVATE+KEY+localhost+7af406a6+AR65vBDzmd0yI/rsoMwbg5sYgFWIF2Z3TgtWaGxWEu1+"
const testvkey = "localhost+7af406a6+AfWA0P/5hn0K1/QybqsBg3fD+9XzPNB/v1QG73x/K8Gi"
type indexMod struct {
Path string
Version string
Timestamp time.Time
}
func gosumOK(path, version string) ([]byte, error) {
escpath, err := module.EscapePath(path)
if err != nil {
return nil, err
}
escvers, err := module.EscapeVersion(version)
if err != nil {
return nil, err
}
h1, err := dirhash.Hash1(nil, nil)
if err != nil {
return nil, err
}
sumindex = append(sumindex, indexMod{path, version, time.Now()})
s := fmt.Sprintf("%s %s %s\n%s %s/go.mod %s\n", escpath, escvers, h1, escpath, escvers, h1)
return []byte(s), nil
}
var gosum = gosumOK
func tresetTree() {
if sumhttpsrv != nil {
sumhttpsrv.Close()
}
os.RemoveAll("testdata/tmp/data/cache")
sumindex = nil
sumsrv = sumdb.NewTestServer(testskey, func(path, version string) ([]byte, error) {
return gosum(path, version)
})
sumhttpsrv = httptest.NewServer(sumdb.NewServer(sumsrv))
config.SumDB.BaseURL = sumhttpsrv.URL
if _, err := bstore.QueryDB[ModuleVersion](ctxbg, database).Delete(); err != nil {
panic(fmt.Sprintf("delete module versions: %v", err))
}
cops := ops{URL: config.SumDB.BaseURL}
tlogclient = NewClient(config.SumDB.VerifierKey, &cops)
if err := tlogclient.init(); err != nil {
panic(fmt.Sprintf("tlogclient init: %v", err))
}
if _, err := initTlog(); err != nil {
panic(fmt.Sprintf("tlog init: %v", err))
}
}
func indexHandler(w http.ResponseWriter, r *http.Request) {
for _, m := range sumindex {
if err := json.NewEncoder(w).Encode(m); err != nil {
break
}
}
}
type moxtx struct {
webapi.SendRequest
webapi.SendResult
}
var moxapiTx []moxtx
var moxapiCount int64
var moxhookout *httptest.Server
var moxhookin *httptest.Server
var mailSubmitted = make(chan struct{})
var mailDelivered = make(chan struct{})
var outgoingEvent = webhook.EventDelivered
func moxapiHandler(w http.ResponseWriter, r *http.Request) {
// Calls by gopherwatch to mox, typically to send an email.
if r.URL.Path == "/MessageFlagsAdd" {
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(webapi.MessageFlagsAddResult{})
return
}
if r.URL.Path != "/Send" {
http.NotFound(w, r)
return
}
reqstr := r.PostFormValue("request")
var req webapi.SendRequest
err := json.Unmarshal([]byte(reqstr), &req)
if err != nil {
log.Printf("parsing send request: %v", err)
http.Error(w, "500 - server error - "+err.Error(), http.StatusInternalServerError)
return
}
moxapiCount++
result := webapi.SendResult{
MessageID: random() + "@localhost",
Submissions: []webapi.Submission{
{
Address: req.To[0].Address,
QueueMsgID: moxapiCount,
FromID: random(),
},
},
}
// Send webhook for success.
out := webhook.Outgoing{
Event: outgoingEvent,
QueueMsgID: result.Submissions[0].QueueMsgID,
FromID: result.Submissions[0].FromID,
MessageID: result.MessageID,
Subject: req.Subject,
WebhookQueued: time.Now(),
Extra: req.Extra,
}
outbuf, err := json.Marshal(out)
if err != nil {
log.Printf("marshal mox outgoing webhook: %v", err)
http.Error(w, "500 - server error - "+err.Error(), http.StatusInternalServerError)
return
}
u := moxhookout.URL + config.Mox.Webhook.OutgoingPath
outreq, err := http.NewRequest("POST", u, bytes.NewReader(outbuf))
if err != nil {
log.Printf("request for outgoing webhook: %v", err)
http.Error(w, "500 - server error - "+err.Error(), http.StatusInternalServerError)
return
}
outreq.Header.Set("Content-Type", "application/json")
outreq.SetBasicAuth(config.Mox.Webhook.Username, config.Mox.Webhook.Password)
moxapiTx = append(moxapiTx, moxtx{req, result})
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(result)
go func() {
<-mailSubmitted // Interaction with test, waiting for SendID/FromID to be registered.
outresp, err := http.DefaultClient.Do(outreq)
if err != nil {
log.Printf("http transaction for outgoing webhook: %v", err)
http.Error(w, "500 - server error - "+err.Error(), http.StatusInternalServerError)
return
}
if outresp.StatusCode != http.StatusOK {
log.Printf("http transaction status for outgoing webhook: %v", outresp.Status)
http.Error(w, "500 - server error - "+err.Error(), http.StatusInternalServerError)
return
}
mailDelivered <- struct{}{}
}()
}
func TestMain(t *testing.M) {
log.SetFlags(0)
loglevel.Set(slog.LevelDebug)
dataDir = "testdata/tmp/data"
os.RemoveAll(dataDir)
dbpath := "testdata/tmp/gopherwatch.db"
os.MkdirAll(filepath.Dir(dbpath), 0750)
os.Remove(dbpath)
ratelimitSumdb = makeLimiter(windowLimit(time.Second, 1000, 1000, 1000))
fakemox := httptest.NewServer(http.HandlerFunc(moxapiHandler))
moxhookout = httptest.NewServer(http.HandlerFunc(webhookOutgoing))
moxhookin = httptest.NewServer(http.HandlerFunc(webhookIncoming))
fakeindex := httptest.NewServer(http.HandlerFunc(indexHandler))
config = Config{
BaseURL: "http://localhost",
TokenSecret: "test1234",
ServiceName: "gw test",
Admin: Admin{
Address: "[email protected]",
AddressParsed: smtp.Address{Localpart: "gopherwatch", Domain: dns.Domain{ASCII: "gw.example"}},
Password: "admin1234",
},
SubjectPrefix: "gwtest: ",
DailyMetaMessagesMax: 100,
EmailUpdateInterval: 0,
SumDB: SumDB{
// BaseURL is set below with a call to tresetTree.
VerifierKey: testvkey,
QueryLatestInterval: time.Hour, // We manually forward the tlog during tests.
},
IndexBaseURL: fakeindex.URL,
SignupAddress: "[email protected]",
KeywordPrefix: "gw:",
Mox: &Mox{
WebAPI: WebAPI{
BaseURL: fakemox.URL + "/",
Username: "mox@localhost",
Password: "test1234",
},
Webhook: Webhook{
OutgoingPath: "/out",
IncomingPath: "/in",
Username: "gw@localhost",
Password: "test1234",
},
},
WebhooksAllowInternalIPs: true,
SkipModulePrefixes: []string{"mirror.localhost/"},
SkipModulePaths: []string{"huge.localhost"},
DNS: &DNS{
Domain: "gw.example.",
NS: []NS{
{Name: "ns0", IPs: []string{"127.0.0.1", "::1"}},
},
SOAMailbox: "mjl.gw.example.",
TTL: 60,
NegativeTTL: 60,
MetaTTL: 300,
},
}
config.DNS.ECDSA.PrivateKey, config.DNS.ECDSA.PublicKey = xecdsaGen()
err := parseDNSConfig(config.DNS)
xfatalf(err, "parse dns config")
servePrep(dbpath)
resetTree = true // For each test that inits the tlog.
tresetTree()
os.Exit(t.Run())
}