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)
90 err := store.Init(ctxbg)
91 tcheck(t, err, "store init")
94 tcheck(t, err, "store close")
97 adminpwhash, err := bcrypt.GenerateFromPassword([]byte("moxtest123"), bcrypt.DefaultCost)
98 tcheck(t, err, "generate bcrypt hash")
100 path := mox.ConfigDirPath(mox.Conf.Static.AdminPasswordFile)
101 err = os.WriteFile(path, adminpwhash, 0660)
102 tcheck(t, err, "write password file")
103 defer os.Remove(path)
105 api := Admin{cookiePath: "/admin/"}
106 apiHandler, err := makeSherpaHandler(api.cookiePath, false)
107 tcheck(t, err, "sherpa handler")
109 respRec := httptest.NewRecorder()
110 reqInfo := requestInfo{"", respRec, &http.Request{RemoteAddr: "127.0.0.1:1234"}}
111 ctx := context.WithValue(ctxbg, requestInfoCtxKey, reqInfo)
113 // Missing login token.
114 tneedErrorCode(t, "user:error", func() { api.Login(ctx, "", "moxtest123") })
116 // Login with loginToken.
117 loginCookie := &http.Cookie{Name: "webadminlogin"}
118 loginCookie.Value = api.LoginPrep(ctx)
119 reqInfo.Request.Header = http.Header{"Cookie": []string{loginCookie.String()}}
121 csrfToken := api.Login(ctx, loginCookie.Value, "moxtest123")
122 var sessionCookie *http.Cookie
123 for _, c := range respRec.Result().Cookies() {
124 if c.Name == "webadminsession" {
129 if sessionCookie == nil {
130 t.Fatalf("missing session cookie")
133 // Valid loginToken, but bad credentials.
134 loginCookie.Value = api.LoginPrep(ctx)
135 reqInfo.Request.Header = http.Header{"Cookie": []string{loginCookie.String()}}
136 tneedErrorCode(t, "user:loginFailed", func() { api.Login(ctx, loginCookie.Value, "badauth") })
138 type httpHeaders [][2]string
139 ctJSON := [2]string{"Content-Type", "application/json; charset=utf-8"}
141 cookieOK := &http.Cookie{Name: "webadminsession", Value: sessionCookie.Value}
142 cookieBad := &http.Cookie{Name: "webadminsession", Value: "AAAAAAAAAAAAAAAAAAAAAA"}
143 hdrSessionOK := [2]string{"Cookie", cookieOK.String()}
144 hdrSessionBad := [2]string{"Cookie", cookieBad.String()}
145 hdrCSRFOK := [2]string{"x-mox-csrf", string(csrfToken)}
146 hdrCSRFBad := [2]string{"x-mox-csrf", "AAAAAAAAAAAAAAAAAAAAAA"}
148 testHTTP := func(method, path string, headers httpHeaders, expStatusCode int, expHeaders httpHeaders, check func(resp *http.Response)) {
151 req := httptest.NewRequest(method, path, nil)
152 for _, kv := range headers {
153 req.Header.Add(kv[0], kv[1])
155 rr := httptest.NewRecorder()
156 rr.Body = &bytes.Buffer{}
157 handle(apiHandler, false, rr, req)
158 if rr.Code != expStatusCode {
159 t.Fatalf("got status %d, expected %d (%s)", rr.Code, expStatusCode, readBody(rr.Body))
163 for _, h := range expHeaders {
164 if resp.Header.Get(h[0]) != h[1] {
165 t.Fatalf("for header %q got value %q, expected %q", h[0], resp.Header.Get(h[0]), h[1])
173 testHTTPAuthAPI := func(method, path string, expStatusCode int, expHeaders httpHeaders, check func(resp *http.Response)) {
175 testHTTP(method, path, httpHeaders{hdrCSRFOK, hdrSessionOK}, expStatusCode, expHeaders, check)
178 userAuthError := func(resp *http.Response, expCode string) {
181 var response struct {
182 Error *sherpa.Error `json:"error"`
184 err := json.NewDecoder(resp.Body).Decode(&response)
185 tcheck(t, err, "parsing response as json")
186 if response.Error == nil {
187 t.Fatalf("expected sherpa error with code %s, no error", expCode)
189 if response.Error.Code != expCode {
190 t.Fatalf("got sherpa error code %q, expected %s", response.Error.Code, expCode)
193 badAuth := func(resp *http.Response) {
195 userAuthError(resp, "user:badAuth")
197 noAuth := func(resp *http.Response) {
199 userAuthError(resp, "user:noAuth")
202 testHTTP("POST", "/api/Bogus", httpHeaders{}, http.StatusOK, nil, noAuth)
203 testHTTP("POST", "/api/Bogus", httpHeaders{hdrCSRFBad}, http.StatusOK, nil, noAuth)
204 testHTTP("POST", "/api/Bogus", httpHeaders{hdrSessionBad}, http.StatusOK, nil, noAuth)
205 testHTTP("POST", "/api/Bogus", httpHeaders{hdrCSRFBad, hdrSessionBad}, http.StatusOK, nil, badAuth)
206 testHTTP("POST", "/api/Bogus", httpHeaders{hdrCSRFOK}, http.StatusOK, nil, noAuth)
207 testHTTP("POST", "/api/Bogus", httpHeaders{hdrSessionOK}, http.StatusOK, nil, noAuth)
208 testHTTP("POST", "/api/Bogus", httpHeaders{hdrCSRFBad, hdrSessionOK}, http.StatusOK, nil, badAuth)
209 testHTTP("POST", "/api/Bogus", httpHeaders{hdrCSRFOK, hdrSessionBad}, http.StatusOK, nil, badAuth)
210 testHTTPAuthAPI("GET", "/api/Transports", http.StatusMethodNotAllowed, nil, nil)
211 testHTTPAuthAPI("POST", "/api/Transports", http.StatusOK, httpHeaders{ctJSON}, nil)
213 // Logout needs session token.
214 reqInfo.SessionToken = store.SessionToken(strings.SplitN(sessionCookie.Value, " ", 2)[0])
215 ctx = context.WithValue(ctxbg, requestInfoCtxKey, reqInfo)
218 tneedErrorCode(t, "server:error", func() { api.Logout(ctx) })
221func TestAdmin(t *testing.T) {
222 os.RemoveAll("../testdata/webadmin/data")
223 defer os.RemoveAll("../testdata/webadmin/dkim")
224 mox.ConfigStaticPath = filepath.FromSlash("../testdata/webadmin/mox.conf")
225 mox.ConfigDynamicPath = filepath.Join(filepath.Dir(mox.ConfigStaticPath), "domains.conf")
226 mox.MustLoadConfig(true, false)
228 tcheck(t, err, "queue init")
229 defer queue.Shutdown()
233 mrl := api.RetiredList(ctxbg, queue.RetiredFilter{}, queue.RetiredSort{})
234 tcompare(t, len(mrl), 0)
236 n := api.HookQueueSize(ctxbg)
239 hl := api.HookList(ctxbg, queue.HookFilter{}, queue.HookSort{})
240 tcompare(t, len(hl), 0)
242 n = api.HookNextAttemptSet(ctxbg, queue.HookFilter{}, 0)
245 n = api.HookNextAttemptAdd(ctxbg, queue.HookFilter{}, 0)
248 hrl := api.HookRetiredList(ctxbg, queue.HookRetiredFilter{}, queue.HookRetiredSort{})
249 tcompare(t, len(hrl), 0)
251 n = api.HookCancel(ctxbg, queue.HookFilter{})
255 api.DomainConfig(ctxbg, "mox.example")
256 tneedErrorCode(t, "user:error", func() { api.DomainConfig(ctxbg, "bogus.example") })
258 api.AccountRoutesSave(ctxbg, "mjl", []config.Route{{Transport: "direct"}})
259 tneedErrorCode(t, "user:error", func() { api.AccountRoutesSave(ctxbg, "mjl", []config.Route{{Transport: "bogus"}}) })
260 api.AccountRoutesSave(ctxbg, "mjl", nil)
262 api.DomainRoutesSave(ctxbg, "mox.example", []config.Route{{Transport: "direct"}})
263 tneedErrorCode(t, "user:error", func() { api.DomainRoutesSave(ctxbg, "mox.example", []config.Route{{Transport: "bogus"}}) })
264 api.DomainRoutesSave(ctxbg, "mox.example", nil)
266 api.RoutesSave(ctxbg, []config.Route{{Transport: "direct"}})
267 tneedErrorCode(t, "user:error", func() { api.RoutesSave(ctxbg, []config.Route{{Transport: "bogus"}}) })
268 api.RoutesSave(ctxbg, nil)
270 api.DomainDescriptionSave(ctxbg, "mox.example", "description")
271 tneedErrorCode(t, "server:error", func() { api.DomainDescriptionSave(ctxbg, "mox.example", "newline not ok\n") }) // todo: user error
272 tneedErrorCode(t, "user:error", func() { api.DomainDescriptionSave(ctxbg, "bogus.example", "unknown domain") })
273 api.DomainDescriptionSave(ctxbg, "mox.example", "") // Restore.
275 api.DomainClientSettingsDomainSave(ctxbg, "mox.example", "mail.mox.example")
276 tneedErrorCode(t, "user:error", func() { api.DomainClientSettingsDomainSave(ctxbg, "mox.example", "bogus domain") })
277 tneedErrorCode(t, "user:error", func() { api.DomainClientSettingsDomainSave(ctxbg, "bogus.example", "unknown.example") })
278 api.DomainClientSettingsDomainSave(ctxbg, "mox.example", "") // Restore.
280 api.DomainLocalpartConfigSave(ctxbg, "mox.example", "-", true)
281 tneedErrorCode(t, "user:error", func() { api.DomainLocalpartConfigSave(ctxbg, "bogus.example", "", false) })
282 api.DomainLocalpartConfigSave(ctxbg, "mox.example", "", false) // Restore.
284 api.DomainDMARCAddressSave(ctxbg, "mox.example", "dmarc-reports", "", "mjl", "DMARC")
285 tneedErrorCode(t, "user:error", func() { api.DomainDMARCAddressSave(ctxbg, "bogus.example", "dmarc-reports", "", "mjl", "DMARC") })
286 tneedErrorCode(t, "user:error", func() { api.DomainDMARCAddressSave(ctxbg, "mox.example", "dmarc-reports", "", "bogus", "DMARC") })
287 api.DomainDMARCAddressSave(ctxbg, "mox.example", "", "", "", "") // Restore.
289 api.DomainTLSRPTAddressSave(ctxbg, "mox.example", "tls-reports", "", "mjl", "TLSRPT")
290 tneedErrorCode(t, "user:error", func() { api.DomainTLSRPTAddressSave(ctxbg, "bogus.example", "tls-reports", "", "mjl", "TLSRPT") })
291 tneedErrorCode(t, "user:error", func() { api.DomainTLSRPTAddressSave(ctxbg, "mox.example", "tls-reports", "", "bogus", "TLSRPT") })
292 api.DomainTLSRPTAddressSave(ctxbg, "mox.example", "", "", "", "") // Restore.
294 // todo: cannot enable mta-sts because we have no listener, which would require a tls cert for the domain.
295 // api.DomainMTASTSSave(ctxbg, "mox.example", "id0", mtasts.ModeEnforce, time.Hour, []string{"mail.mox.example"})
296 tneedErrorCode(t, "user:error", func() {
297 api.DomainMTASTSSave(ctxbg, "bogus.example", "id0", mtasts.ModeEnforce, time.Hour, []string{"mail.mox.example"})
299 tneedErrorCode(t, "user:error", func() {
300 api.DomainMTASTSSave(ctxbg, "mox.example", "invalid id", mtasts.ModeEnforce, time.Hour, []string{"mail.mox.example"})
302 tneedErrorCode(t, "user:error", func() {
303 api.DomainMTASTSSave(ctxbg, "mox.example", "id0", mtasts.Mode("bogus"), time.Hour, []string{"mail.mox.example"})
305 tneedErrorCode(t, "user:error", func() {
306 api.DomainMTASTSSave(ctxbg, "mox.example", "id0", mtasts.ModeEnforce, time.Hour, []string{"*.*.mail.mox.example"})
308 api.DomainMTASTSSave(ctxbg, "mox.example", "", mtasts.ModeNone, 0, nil) // Restore.
310 api.DomainDKIMAdd(ctxbg, "mox.example", "testsel", "ed25519", "sha256", true, true, true, nil, 24*time.Hour)
311 tneedErrorCode(t, "user:error", func() {
312 api.DomainDKIMAdd(ctxbg, "mox.example", "testsel", "ed25519", "sha256", true, true, true, nil, 24*time.Hour)
313 }) // Duplicate selector.
314 tneedErrorCode(t, "user:error", func() {
315 api.DomainDKIMAdd(ctxbg, "bogus.example", "testsel", "ed25519", "sha256", true, true, true, nil, 24*time.Hour)
317 conf := api.DomainConfig(ctxbg, "mox.example")
318 api.DomainDKIMSave(ctxbg, "mox.example", conf.DKIM.Selectors, conf.DKIM.Sign)
319 api.DomainDKIMSave(ctxbg, "mox.example", conf.DKIM.Selectors, []string{"testsel"})
320 tneedErrorCode(t, "user:error", func() { api.DomainDKIMSave(ctxbg, "mox.example", conf.DKIM.Selectors, []string{"bogus"}) })
321 tneedErrorCode(t, "user:error", func() { api.DomainDKIMSave(ctxbg, "mox.example", nil, []string{}) }) // Cannot remove selectors with save.
322 tneedErrorCode(t, "user:error", func() { api.DomainDKIMSave(ctxbg, "bogus.example", nil, []string{}) })
323 moreSel := map[string]config.Selector{
324 "testsel": conf.DKIM.Selectors["testsel"],
325 "testsel2": conf.DKIM.Selectors["testsel2"],
327 tneedErrorCode(t, "user:error", func() { api.DomainDKIMSave(ctxbg, "mox.example", moreSel, []string{}) }) // Cannot add selectors with save.
328 api.DomainDKIMRemove(ctxbg, "mox.example", "testsel")
329 tneedErrorCode(t, "user:error", func() { api.DomainDKIMRemove(ctxbg, "mox.example", "testsel") }) // Already removed.
330 tneedErrorCode(t, "user:error", func() { api.DomainDKIMRemove(ctxbg, "bogus.example", "testsel") })
333 alias := config.Alias{Addresses: []string{"mjl@mox.example"}}
334 api.AliasAdd(ctxbg, "support", "mox.example", alias)
335 tneedErrorCode(t, "user:error", func() { api.AliasAdd(ctxbg, "support", "mox.example", alias) }) // Already present.
336 tneedErrorCode(t, "user:error", func() { api.AliasAdd(ctxbg, "Support", "mox.example", alias) }) // Duplicate, canonical.
337 tneedErrorCode(t, "user:error", func() { api.AliasAdd(ctxbg, "support", "bogus.example", alias) }) // Unknown domain.
338 tneedErrorCode(t, "user:error", func() { api.AliasAdd(ctxbg, "support2", "mox.example", config.Alias{}) }) // No addresses.
340 api.AliasUpdate(ctxbg, "support", "mox.example", true, true, true)
341 tneedErrorCode(t, "user:error", func() { api.AliasUpdate(ctxbg, "bogus", "mox.example", true, true, true) }) // Unknown alias localpart.
342 tneedErrorCode(t, "user:error", func() { api.AliasUpdate(ctxbg, "support", "bogus.example", true, true, true) }) // Unknown alias domain.
344 tneedErrorCode(t, "user:error", func() {
345 api.AliasAddressesAdd(ctxbg, "support", "mox.example", []string{"mjl2@mox.example", "mjl2@mox.example"})
346 }) // Cannot add twice.
347 api.AliasAddressesAdd(ctxbg, "support", "mox.example", []string{"mjl2@mox.example"})
348 tneedErrorCode(t, "user:error", func() { api.AliasAddressesAdd(ctxbg, "support", "mox.example", []string{"mjl2@mox.example"}) }) // Already present.
349 tneedErrorCode(t, "user:error", func() { api.AliasAddressesAdd(ctxbg, "support", "mox.example", []string{"bogus@mox.example"}) }) // Unknown dest localpart.
350 tneedErrorCode(t, "user:error", func() { api.AliasAddressesAdd(ctxbg, "support", "mox.example", []string{"bogus@bogus.example"}) }) // Unknown dest domain.
351 tneedErrorCode(t, "user:error", func() { api.AliasAddressesAdd(ctxbg, "support2", "mox.example", []string{"mjl@mox.example"}) }) // Unknown alias localpart.
352 tneedErrorCode(t, "user:error", func() { api.AliasAddressesAdd(ctxbg, "support", "bogus.example", []string{"mjl@mox.example"}) }) // Unknown alias localpart.
353 tneedErrorCode(t, "user:error", func() { api.AliasAddressesAdd(ctxbg, "support", "mox.example", []string{"support@mox.example"}) }) // Alias cannot be destination.
355 tneedErrorCode(t, "user:error", func() { api.AliasAddressesRemove(ctxbg, "support", "mox.example", []string{}) }) // Need at least 1 address.
356 tneedErrorCode(t, "user:error", func() { api.AliasAddressesRemove(ctxbg, "support", "mox.example", []string{"bogus@mox.example"}) }) // Not a member.
357 tneedErrorCode(t, "user:error", func() { api.AliasAddressesRemove(ctxbg, "support", "mox.example", []string{"bogus@bogus.example"}) }) // Not member, unknown domain.
358 tneedErrorCode(t, "user:error", func() { api.AliasAddressesRemove(ctxbg, "support2", "mox.example", []string{"mjl@mox.example"}) }) // Unknown alias localpart.
359 tneedErrorCode(t, "user:error", func() { api.AliasAddressesRemove(ctxbg, "support", "bogus.example", []string{"mjl@mox.example"}) }) // Unknown alias domain.
360 tneedErrorCode(t, "user:error", func() {
361 api.AliasAddressesRemove(ctxbg, "support", "mox.example", []string{"mjl@mox.example", "mjl2@mox.example"})
362 }) // Cannot leave zero addresses.
363 api.AliasAddressesRemove(ctxbg, "support", "mox.example", []string{"mjl@mox.example"})
365 api.AliasRemove(ctxbg, "support", "mox.example") // Restore.
366 tneedErrorCode(t, "user:error", func() { api.AliasRemove(ctxbg, "support", "mox.example") }) // No longer exists.
367 tneedErrorCode(t, "user:error", func() { api.AliasRemove(ctxbg, "support", "bogus.example") }) // Unknown alias domain.
371func TestCheckDomain(t *testing.T) {
372 // NOTE: we aren't currently looking at the results, having the code paths executed is better than nothing.
374 log := mlog.New("webadmin", nil)
376 resolver := dns.MockResolver{
377 MX: map[string][]*net.MX{
378 "mox.example.": {{Host: "mail.mox.example.", Pref: 10}},
380 A: map[string][]string{
381 "mail.mox.example.": {"127.0.0.2"},
383 AAAA: map[string][]string{
384 "mail.mox.example.": {"127.0.0.2"},
386 TXT: map[string][]string{
387 "mox.example.": {"v=spf1 mx -all"},
388 "test._domainkey.mox.example.": {"v=DKIM1;h=sha256;k=ed25519;p=ln5zd/JEX4Jy60WAhUOv33IYm2YZMyTQAdr9stML504="},
389 "_dmarc.mox.example.": {"v=DMARC1; p=reject; rua=mailto:mjl@mox.example"},
390 "_smtp._tls.mox.example": {"v=TLSRPTv1; rua=mailto:tlsrpt@mox.example;"},
391 "_mta-sts.mox.example": {"v=STSv1; id=20160831085700Z"},
393 CNAME: map[string]string{},
396 listener := config.Listener{
397 IPs: []string{"127.0.0.2"},
398 Hostname: "mox.example",
399 HostnameDomain: dns.Domain{ASCII: "mox.example"},
401 listener.SMTP.Enabled = true
402 listener.AutoconfigHTTPS.Enabled = true
403 listener.MTASTSHTTPS.Enabled = true
405 mox.Conf.Static.Listeners = map[string]config.Listener{
408 domain := config.Domain{
410 Selectors: map[string]config.Selector{
412 HashEffective: "sha256",
413 HeadersEffective: []string{"From", "Date", "Subject"},
414 Key: ed25519.NewKeyFromSeed(make([]byte, 32)), // warning: fake zero key, do not copy this code.
415 Domain: dns.Domain{ASCII: "test"},
418 HashEffective: "sha256",
419 HeadersEffective: []string{"From", "Date", "Subject"},
420 Key: ed25519.NewKeyFromSeed(make([]byte, 32)), // warning: fake zero key, do not copy this code.
421 Domain: dns.Domain{ASCII: "missing"},
424 Sign: []string{"test", "test2"},
427 mox.Conf.Dynamic.Domains = map[string]config.Domain{
428 "mox.example": domain,
431 // Make a dialer that fails immediately before actually connecting.
432 done := make(chan struct{})
434 dialer := &net.Dialer{Deadline: time.Now().Add(-time.Second), Cancel: done}
436 checkDomain(ctxbg, resolver, dialer, "mox.example")
437 // todo: check returned data
439 Admin{}.Domains(ctxbg) // todo: check results
440 dnsblsStatus(ctxbg, log, resolver) // todo: check results