21 "golang.org/x/crypto/bcrypt"
23 "github.com/mjl-/sherpa"
25 "github.com/mjl-/mox/config"
26 "github.com/mjl-/mox/dns"
27 "github.com/mjl-/mox/mlog"
28 "github.com/mjl-/mox/mox-"
29 "github.com/mjl-/mox/mtasts"
30 "github.com/mjl-/mox/queue"
31 "github.com/mjl-/mox/store"
32 "github.com/mjl-/mox/webauth"
35var ctxbg = context.Background()
39 webauth.BadAuthDelay = 0
42func tneedErrorCode(t *testing.T, code string, fn func()) {
49 t.Fatalf("expected sherpa user error, saw success")
51 if err, ok := x.(*sherpa.Error); !ok {
53 t.Fatalf("expected sherpa error, saw %#v", x)
54 } else if err.Code != code {
56 t.Fatalf("expected sherpa error code %q, saw other sherpa error %#v", code, err)
63func tcheck(t *testing.T, err error, msg string) {
66 t.Fatalf("%s: %s", msg, err)
70func tcompare(t *testing.T, got, expect any) {
72 if !reflect.DeepEqual(got, expect) {
73 t.Fatalf("got:\n%#v\nexpected:\n%#v", got, expect)
77func readBody(r io.Reader) string {
78 buf, err := io.ReadAll(r)
80 return fmt.Sprintf("read error: %s", err)
82 return fmt.Sprintf("data: %q", buf)
85func TestAdminAuth(t *testing.T) {
86 os.RemoveAll("../testdata/webadmin/data")
87 mox.ConfigStaticPath = filepath.FromSlash("../testdata/webadmin/mox.conf")
88 mox.ConfigDynamicPath = filepath.Join(filepath.Dir(mox.ConfigStaticPath), "domains.conf")
89 mox.MustLoadConfig(true, false)
91 adminpwhash, err := bcrypt.GenerateFromPassword([]byte("moxtest123"), bcrypt.DefaultCost)
92 tcheck(t, err, "generate bcrypt hash")
94 path := mox.ConfigDirPath(mox.Conf.Static.AdminPasswordFile)
95 err = os.WriteFile(path, adminpwhash, 0660)
96 tcheck(t, err, "write password file")
99 api := Admin{cookiePath: "/admin/"}
100 apiHandler, err := makeSherpaHandler(api.cookiePath, false)
101 tcheck(t, err, "sherpa handler")
103 respRec := httptest.NewRecorder()
104 reqInfo := requestInfo{"", respRec, &http.Request{RemoteAddr: "127.0.0.1:1234"}}
105 ctx := context.WithValue(ctxbg, requestInfoCtxKey, reqInfo)
107 // Missing login token.
108 tneedErrorCode(t, "user:error", func() { api.Login(ctx, "", "moxtest123") })
110 // Login with loginToken.
111 loginCookie := &http.Cookie{Name: "webadminlogin"}
112 loginCookie.Value = api.LoginPrep(ctx)
113 reqInfo.Request.Header = http.Header{"Cookie": []string{loginCookie.String()}}
115 csrfToken := api.Login(ctx, loginCookie.Value, "moxtest123")
116 var sessionCookie *http.Cookie
117 for _, c := range respRec.Result().Cookies() {
118 if c.Name == "webadminsession" {
123 if sessionCookie == nil {
124 t.Fatalf("missing session cookie")
127 // Valid loginToken, but bad credentials.
128 loginCookie.Value = api.LoginPrep(ctx)
129 reqInfo.Request.Header = http.Header{"Cookie": []string{loginCookie.String()}}
130 tneedErrorCode(t, "user:loginFailed", func() { api.Login(ctx, loginCookie.Value, "badauth") })
132 type httpHeaders [][2]string
133 ctJSON := [2]string{"Content-Type", "application/json; charset=utf-8"}
135 cookieOK := &http.Cookie{Name: "webadminsession", Value: sessionCookie.Value}
136 cookieBad := &http.Cookie{Name: "webadminsession", Value: "AAAAAAAAAAAAAAAAAAAAAA"}
137 hdrSessionOK := [2]string{"Cookie", cookieOK.String()}
138 hdrSessionBad := [2]string{"Cookie", cookieBad.String()}
139 hdrCSRFOK := [2]string{"x-mox-csrf", string(csrfToken)}
140 hdrCSRFBad := [2]string{"x-mox-csrf", "AAAAAAAAAAAAAAAAAAAAAA"}
142 testHTTP := func(method, path string, headers httpHeaders, expStatusCode int, expHeaders httpHeaders, check func(resp *http.Response)) {
145 req := httptest.NewRequest(method, path, nil)
146 for _, kv := range headers {
147 req.Header.Add(kv[0], kv[1])
149 rr := httptest.NewRecorder()
150 rr.Body = &bytes.Buffer{}
151 handle(apiHandler, false, rr, req)
152 if rr.Code != expStatusCode {
153 t.Fatalf("got status %d, expected %d (%s)", rr.Code, expStatusCode, readBody(rr.Body))
157 for _, h := range expHeaders {
158 if resp.Header.Get(h[0]) != h[1] {
159 t.Fatalf("for header %q got value %q, expected %q", h[0], resp.Header.Get(h[0]), h[1])
167 testHTTPAuthAPI := func(method, path string, expStatusCode int, expHeaders httpHeaders, check func(resp *http.Response)) {
169 testHTTP(method, path, httpHeaders{hdrCSRFOK, hdrSessionOK}, expStatusCode, expHeaders, check)
172 userAuthError := func(resp *http.Response, expCode string) {
175 var response struct {
176 Error *sherpa.Error `json:"error"`
178 err := json.NewDecoder(resp.Body).Decode(&response)
179 tcheck(t, err, "parsing response as json")
180 if response.Error == nil {
181 t.Fatalf("expected sherpa error with code %s, no error", expCode)
183 if response.Error.Code != expCode {
184 t.Fatalf("got sherpa error code %q, expected %s", response.Error.Code, expCode)
187 badAuth := func(resp *http.Response) {
189 userAuthError(resp, "user:badAuth")
191 noAuth := func(resp *http.Response) {
193 userAuthError(resp, "user:noAuth")
196 testHTTP("POST", "/api/Bogus", httpHeaders{}, http.StatusOK, nil, noAuth)
197 testHTTP("POST", "/api/Bogus", httpHeaders{hdrCSRFBad}, http.StatusOK, nil, noAuth)
198 testHTTP("POST", "/api/Bogus", httpHeaders{hdrSessionBad}, http.StatusOK, nil, noAuth)
199 testHTTP("POST", "/api/Bogus", httpHeaders{hdrCSRFBad, hdrSessionBad}, http.StatusOK, nil, badAuth)
200 testHTTP("POST", "/api/Bogus", httpHeaders{hdrCSRFOK}, http.StatusOK, nil, noAuth)
201 testHTTP("POST", "/api/Bogus", httpHeaders{hdrSessionOK}, http.StatusOK, nil, noAuth)
202 testHTTP("POST", "/api/Bogus", httpHeaders{hdrCSRFBad, hdrSessionOK}, http.StatusOK, nil, badAuth)
203 testHTTP("POST", "/api/Bogus", httpHeaders{hdrCSRFOK, hdrSessionBad}, http.StatusOK, nil, badAuth)
204 testHTTPAuthAPI("GET", "/api/Transports", http.StatusMethodNotAllowed, nil, nil)
205 testHTTPAuthAPI("POST", "/api/Transports", http.StatusOK, httpHeaders{ctJSON}, nil)
207 // Logout needs session token.
208 reqInfo.SessionToken = store.SessionToken(strings.SplitN(sessionCookie.Value, " ", 2)[0])
209 ctx = context.WithValue(ctxbg, requestInfoCtxKey, reqInfo)
212 tneedErrorCode(t, "server:error", func() { api.Logout(ctx) })
215func TestAdmin(t *testing.T) {
216 os.RemoveAll("../testdata/webadmin/data")
217 defer os.RemoveAll("../testdata/webadmin/dkim")
218 mox.ConfigStaticPath = filepath.FromSlash("../testdata/webadmin/mox.conf")
219 mox.ConfigDynamicPath = filepath.Join(filepath.Dir(mox.ConfigStaticPath), "domains.conf")
220 mox.MustLoadConfig(true, false)
222 tcheck(t, err, "queue init")
226 mrl := api.RetiredList(ctxbg, queue.RetiredFilter{}, queue.RetiredSort{})
227 tcompare(t, len(mrl), 0)
229 n := api.HookQueueSize(ctxbg)
232 hl := api.HookList(ctxbg, queue.HookFilter{}, queue.HookSort{})
233 tcompare(t, len(hl), 0)
235 n = api.HookNextAttemptSet(ctxbg, queue.HookFilter{}, 0)
238 n = api.HookNextAttemptAdd(ctxbg, queue.HookFilter{}, 0)
241 hrl := api.HookRetiredList(ctxbg, queue.HookRetiredFilter{}, queue.HookRetiredSort{})
242 tcompare(t, len(hrl), 0)
244 n = api.HookCancel(ctxbg, queue.HookFilter{})
248 api.DomainConfig(ctxbg, "mox.example")
249 tneedErrorCode(t, "user:error", func() { api.DomainConfig(ctxbg, "bogus.example") })
251 api.AccountRoutesSave(ctxbg, "mjl", []config.Route{{Transport: "direct"}})
252 tneedErrorCode(t, "user:error", func() { api.AccountRoutesSave(ctxbg, "mjl", []config.Route{{Transport: "bogus"}}) })
253 api.AccountRoutesSave(ctxbg, "mjl", nil)
255 api.DomainRoutesSave(ctxbg, "mox.example", []config.Route{{Transport: "direct"}})
256 tneedErrorCode(t, "user:error", func() { api.DomainRoutesSave(ctxbg, "mox.example", []config.Route{{Transport: "bogus"}}) })
257 api.DomainRoutesSave(ctxbg, "mox.example", nil)
259 api.RoutesSave(ctxbg, []config.Route{{Transport: "direct"}})
260 tneedErrorCode(t, "user:error", func() { api.RoutesSave(ctxbg, []config.Route{{Transport: "bogus"}}) })
261 api.RoutesSave(ctxbg, nil)
263 api.DomainDescriptionSave(ctxbg, "mox.example", "description")
264 tneedErrorCode(t, "server:error", func() { api.DomainDescriptionSave(ctxbg, "mox.example", "newline not ok\n") }) // todo: user error
265 tneedErrorCode(t, "user:error", func() { api.DomainDescriptionSave(ctxbg, "bogus.example", "unknown domain") })
266 api.DomainDescriptionSave(ctxbg, "mox.example", "") // Restore.
268 api.DomainClientSettingsDomainSave(ctxbg, "mox.example", "mail.mox.example")
269 tneedErrorCode(t, "user:error", func() { api.DomainClientSettingsDomainSave(ctxbg, "mox.example", "bogus domain") })
270 tneedErrorCode(t, "user:error", func() { api.DomainClientSettingsDomainSave(ctxbg, "bogus.example", "unknown.example") })
271 api.DomainClientSettingsDomainSave(ctxbg, "mox.example", "") // Restore.
273 api.DomainLocalpartConfigSave(ctxbg, "mox.example", "-", true)
274 tneedErrorCode(t, "user:error", func() { api.DomainLocalpartConfigSave(ctxbg, "bogus.example", "", false) })
275 api.DomainLocalpartConfigSave(ctxbg, "mox.example", "", false) // Restore.
277 api.DomainDMARCAddressSave(ctxbg, "mox.example", "dmarc-reports", "", "mjl", "DMARC")
278 tneedErrorCode(t, "user:error", func() { api.DomainDMARCAddressSave(ctxbg, "bogus.example", "dmarc-reports", "", "mjl", "DMARC") })
279 tneedErrorCode(t, "user:error", func() { api.DomainDMARCAddressSave(ctxbg, "mox.example", "dmarc-reports", "", "bogus", "DMARC") })
280 api.DomainDMARCAddressSave(ctxbg, "mox.example", "", "", "", "") // Restore.
282 api.DomainTLSRPTAddressSave(ctxbg, "mox.example", "tls-reports", "", "mjl", "TLSRPT")
283 tneedErrorCode(t, "user:error", func() { api.DomainTLSRPTAddressSave(ctxbg, "bogus.example", "tls-reports", "", "mjl", "TLSRPT") })
284 tneedErrorCode(t, "user:error", func() { api.DomainTLSRPTAddressSave(ctxbg, "mox.example", "tls-reports", "", "bogus", "TLSRPT") })
285 api.DomainTLSRPTAddressSave(ctxbg, "mox.example", "", "", "", "") // Restore.
287 // todo: cannot enable mta-sts because we have no listener, which would require a tls cert for the domain.
288 // api.DomainMTASTSSave(ctxbg, "mox.example", "id0", mtasts.ModeEnforce, time.Hour, []string{"mail.mox.example"})
289 tneedErrorCode(t, "user:error", func() {
290 api.DomainMTASTSSave(ctxbg, "bogus.example", "id0", mtasts.ModeEnforce, time.Hour, []string{"mail.mox.example"})
292 tneedErrorCode(t, "user:error", func() {
293 api.DomainMTASTSSave(ctxbg, "mox.example", "invalid id", mtasts.ModeEnforce, time.Hour, []string{"mail.mox.example"})
295 tneedErrorCode(t, "user:error", func() {
296 api.DomainMTASTSSave(ctxbg, "mox.example", "id0", mtasts.Mode("bogus"), time.Hour, []string{"mail.mox.example"})
298 tneedErrorCode(t, "user:error", func() {
299 api.DomainMTASTSSave(ctxbg, "mox.example", "id0", mtasts.ModeEnforce, time.Hour, []string{"*.*.mail.mox.example"})
301 api.DomainMTASTSSave(ctxbg, "mox.example", "", mtasts.ModeNone, 0, nil) // Restore.
303 api.DomainDKIMAdd(ctxbg, "mox.example", "testsel", "ed25519", "sha256", true, true, true, nil, 24*time.Hour)
304 tneedErrorCode(t, "user:error", func() {
305 api.DomainDKIMAdd(ctxbg, "mox.example", "testsel", "ed25519", "sha256", true, true, true, nil, 24*time.Hour)
306 }) // Duplicate selector.
307 tneedErrorCode(t, "user:error", func() {
308 api.DomainDKIMAdd(ctxbg, "bogus.example", "testsel", "ed25519", "sha256", true, true, true, nil, 24*time.Hour)
310 conf := api.DomainConfig(ctxbg, "mox.example")
311 api.DomainDKIMSave(ctxbg, "mox.example", conf.DKIM.Selectors, conf.DKIM.Sign)
312 api.DomainDKIMSave(ctxbg, "mox.example", conf.DKIM.Selectors, []string{"testsel"})
313 tneedErrorCode(t, "user:error", func() { api.DomainDKIMSave(ctxbg, "mox.example", conf.DKIM.Selectors, []string{"bogus"}) })
314 tneedErrorCode(t, "user:error", func() { api.DomainDKIMSave(ctxbg, "mox.example", nil, []string{}) }) // Cannot remove selectors with save.
315 tneedErrorCode(t, "user:error", func() { api.DomainDKIMSave(ctxbg, "bogus.example", nil, []string{}) })
316 moreSel := map[string]config.Selector{
317 "testsel": conf.DKIM.Selectors["testsel"],
318 "testsel2": conf.DKIM.Selectors["testsel2"],
320 tneedErrorCode(t, "user:error", func() { api.DomainDKIMSave(ctxbg, "mox.example", moreSel, []string{}) }) // Cannot add selectors with save.
321 api.DomainDKIMRemove(ctxbg, "mox.example", "testsel")
322 tneedErrorCode(t, "user:error", func() { api.DomainDKIMRemove(ctxbg, "mox.example", "testsel") }) // Already removed.
323 tneedErrorCode(t, "user:error", func() { api.DomainDKIMRemove(ctxbg, "bogus.example", "testsel") })
326 alias := config.Alias{Addresses: []string{"mjl@mox.example"}}
327 api.AliasAdd(ctxbg, "support", "mox.example", alias)
328 tneedErrorCode(t, "user:error", func() { api.AliasAdd(ctxbg, "support", "mox.example", alias) }) // Already present.
329 tneedErrorCode(t, "user:error", func() { api.AliasAdd(ctxbg, "Support", "mox.example", alias) }) // Duplicate, canonical.
330 tneedErrorCode(t, "user:error", func() { api.AliasAdd(ctxbg, "support", "bogus.example", alias) }) // Unknown domain.
331 tneedErrorCode(t, "user:error", func() { api.AliasAdd(ctxbg, "support2", "mox.example", config.Alias{}) }) // No addresses.
333 api.AliasUpdate(ctxbg, "support", "mox.example", true, true, true)
334 tneedErrorCode(t, "user:error", func() { api.AliasUpdate(ctxbg, "bogus", "mox.example", true, true, true) }) // Unknown alias localpart.
335 tneedErrorCode(t, "user:error", func() { api.AliasUpdate(ctxbg, "support", "bogus.example", true, true, true) }) // Unknown alias domain.
337 tneedErrorCode(t, "user:error", func() {
338 api.AliasAddressesAdd(ctxbg, "support", "mox.example", []string{"mjl2@mox.example", "mjl2@mox.example"})
339 }) // Cannot add twice.
340 api.AliasAddressesAdd(ctxbg, "support", "mox.example", []string{"mjl2@mox.example"})
341 tneedErrorCode(t, "user:error", func() { api.AliasAddressesAdd(ctxbg, "support", "mox.example", []string{"mjl2@mox.example"}) }) // Already present.
342 tneedErrorCode(t, "user:error", func() { api.AliasAddressesAdd(ctxbg, "support", "mox.example", []string{"bogus@mox.example"}) }) // Unknown dest localpart.
343 tneedErrorCode(t, "user:error", func() { api.AliasAddressesAdd(ctxbg, "support", "mox.example", []string{"bogus@bogus.example"}) }) // Unknown dest domain.
344 tneedErrorCode(t, "user:error", func() { api.AliasAddressesAdd(ctxbg, "support2", "mox.example", []string{"mjl@mox.example"}) }) // Unknown alias localpart.
345 tneedErrorCode(t, "user:error", func() { api.AliasAddressesAdd(ctxbg, "support", "bogus.example", []string{"mjl@mox.example"}) }) // Unknown alias localpart.
346 tneedErrorCode(t, "user:error", func() { api.AliasAddressesAdd(ctxbg, "support", "mox.example", []string{"support@mox.example"}) }) // Alias cannot be destination.
348 tneedErrorCode(t, "user:error", func() { api.AliasAddressesRemove(ctxbg, "support", "mox.example", []string{}) }) // Need at least 1 address.
349 tneedErrorCode(t, "user:error", func() { api.AliasAddressesRemove(ctxbg, "support", "mox.example", []string{"bogus@mox.example"}) }) // Not a member.
350 tneedErrorCode(t, "user:error", func() { api.AliasAddressesRemove(ctxbg, "support", "mox.example", []string{"bogus@bogus.example"}) }) // Not member, unknown domain.
351 tneedErrorCode(t, "user:error", func() { api.AliasAddressesRemove(ctxbg, "support2", "mox.example", []string{"mjl@mox.example"}) }) // Unknown alias localpart.
352 tneedErrorCode(t, "user:error", func() { api.AliasAddressesRemove(ctxbg, "support", "bogus.example", []string{"mjl@mox.example"}) }) // Unknown alias domain.
353 tneedErrorCode(t, "user:error", func() {
354 api.AliasAddressesRemove(ctxbg, "support", "mox.example", []string{"mjl@mox.example", "mjl2@mox.example"})
355 }) // Cannot leave zero addresses.
356 api.AliasAddressesRemove(ctxbg, "support", "mox.example", []string{"mjl@mox.example"})
358 api.AliasRemove(ctxbg, "support", "mox.example") // Restore.
359 tneedErrorCode(t, "user:error", func() { api.AliasRemove(ctxbg, "support", "mox.example") }) // No longer exists.
360 tneedErrorCode(t, "user:error", func() { api.AliasRemove(ctxbg, "support", "bogus.example") }) // Unknown alias domain.
364func TestCheckDomain(t *testing.T) {
365 // NOTE: we aren't currently looking at the results, having the code paths executed is better than nothing.
367 log := mlog.New("webadmin", nil)
369 resolver := dns.MockResolver{
370 MX: map[string][]*net.MX{
371 "mox.example.": {{Host: "mail.mox.example.", Pref: 10}},
373 A: map[string][]string{
374 "mail.mox.example.": {"127.0.0.2"},
376 AAAA: map[string][]string{
377 "mail.mox.example.": {"127.0.0.2"},
379 TXT: map[string][]string{
380 "mox.example.": {"v=spf1 mx -all"},
381 "test._domainkey.mox.example.": {"v=DKIM1;h=sha256;k=ed25519;p=ln5zd/JEX4Jy60WAhUOv33IYm2YZMyTQAdr9stML504="},
382 "_dmarc.mox.example.": {"v=DMARC1; p=reject; rua=mailto:mjl@mox.example"},
383 "_smtp._tls.mox.example": {"v=TLSRPTv1; rua=mailto:tlsrpt@mox.example;"},
384 "_mta-sts.mox.example": {"v=STSv1; id=20160831085700Z"},
386 CNAME: map[string]string{},
389 listener := config.Listener{
390 IPs: []string{"127.0.0.2"},
391 Hostname: "mox.example",
392 HostnameDomain: dns.Domain{ASCII: "mox.example"},
394 listener.SMTP.Enabled = true
395 listener.AutoconfigHTTPS.Enabled = true
396 listener.MTASTSHTTPS.Enabled = true
398 mox.Conf.Static.Listeners = map[string]config.Listener{
401 domain := config.Domain{
403 Selectors: map[string]config.Selector{
405 HashEffective: "sha256",
406 HeadersEffective: []string{"From", "Date", "Subject"},
407 Key: ed25519.NewKeyFromSeed(make([]byte, 32)), // warning: fake zero key, do not copy this code.
408 Domain: dns.Domain{ASCII: "test"},
411 HashEffective: "sha256",
412 HeadersEffective: []string{"From", "Date", "Subject"},
413 Key: ed25519.NewKeyFromSeed(make([]byte, 32)), // warning: fake zero key, do not copy this code.
414 Domain: dns.Domain{ASCII: "missing"},
417 Sign: []string{"test", "test2"},
420 mox.Conf.Dynamic.Domains = map[string]config.Domain{
421 "mox.example": domain,
424 // Make a dialer that fails immediately before actually connecting.
425 done := make(chan struct{})
427 dialer := &net.Dialer{Deadline: time.Now().Add(-time.Second), Cancel: done}
429 checkDomain(ctxbg, resolver, dialer, "mox.example")
430 // todo: check returned data
432 Admin{}.Domains(ctxbg) // todo: check results
433 dnsblsStatus(ctxbg, log, resolver) // todo: check results