1package http
2
3import (
4 "bytes"
5 "net/http"
6 "net/http/httptest"
7 "os"
8 "path/filepath"
9 "strings"
10 "testing"
11
12 "github.com/mjl-/mox/dns"
13 "github.com/mjl-/mox/mox-"
14)
15
16func TestServeHTTP(t *testing.T) {
17 os.RemoveAll("../testdata/web/data")
18 mox.ConfigStaticPath = filepath.FromSlash("../testdata/web/mox.conf")
19 mox.ConfigDynamicPath = filepath.Join(filepath.Dir(mox.ConfigStaticPath), "domains.conf")
20 mox.MustLoadConfig(true, false)
21
22 srv := &serve{
23 PathHandlers: []pathHandler{
24 {
25 HostMatch: func(dom dns.Domain) bool {
26 return strings.HasPrefix(dom.ASCII, "mta-sts.")
27 },
28 Path: "/.well-known/mta-sts.txt",
29 Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
30 w.Write([]byte("mta-sts!"))
31 }),
32 },
33 },
34 Webserver: true,
35 }
36
37 test := func(method, target string, expCode int, expContent string, expHeaders map[string]string) {
38 t.Helper()
39
40 req := httptest.NewRequest(method, target, nil)
41 rw := httptest.NewRecorder()
42 rw.Body = &bytes.Buffer{}
43 srv.ServeHTTP(rw, req)
44 resp := rw.Result()
45 if resp.StatusCode != expCode {
46 t.Fatalf("got statuscode %d, expected %d", resp.StatusCode, expCode)
47 }
48 if expContent != "" {
49 s := rw.Body.String()
50 if s != expContent {
51 t.Fatalf("got response data %q, expected %q", s, expContent)
52 }
53 }
54 for k, v := range expHeaders {
55 if xv := resp.Header.Get(k); xv != v {
56 t.Fatalf("got %q for header %q, expected %q", xv, k, v)
57 }
58 }
59 }
60
61 test("GET", "http://mta-sts.mox.example/.well-known/mta-sts.txt", http.StatusOK, "mta-sts!", nil)
62 test("GET", "http://mox.example/.well-known/mta-sts.txt", http.StatusNotFound, "", nil) // mta-sts endpoint not in this domain.
63 test("GET", "http://mta-sts.mox.example/static/", http.StatusNotFound, "", nil) // static not served on this domain.
64 test("GET", "http://mta-sts.mox.example/other", http.StatusNotFound, "", nil)
65 test("GET", "http://mox.example/static/", http.StatusOK, "html\n", map[string]string{"X-Test": "mox"}) // index.html is served
66 test("GET", "http://mox.example/static/index.html", http.StatusOK, "html\n", map[string]string{"X-Test": "mox"})
67 test("GET", "http://mox.example/static/dir/", http.StatusOK, "", map[string]string{"X-Test": "mox"}) // Dir listing.
68 test("GET", "http://mox.example/other", http.StatusNotFound, "", nil)
69}
70