mirror of
https://github.com/mjl-/mox.git
synced 2024-12-27 17:03:47 +03:00
28fae96a9b
getting mox to compile required changing code in only a few places where package "syscall" was used: for accessing file access times and for umask handling. an open problem is how to start a process as an unprivileged user on windows. that's why "mox serve" isn't implemented yet. and just finding a way to implement it now may not be good enough in the near future: we may want to starting using a more complete privilege separation approach, with a process handling sensitive tasks (handling private keys, authentication), where we may want to pass file descriptors between processes. how would that work on windows? anyway, getting mox to compile for windows doesn't mean it works properly on windows. the largest issue: mox would normally open a file, rename or remove it, and finally close it. this happens during message delivery. that doesn't work on windows, the rename/remove would fail because the file is still open. so this commit swaps many "remove" and "close" calls. renames are a longer story: message delivery had two ways to deliver: with "consuming" the (temporary) message file (which would rename it to its final destination), and without consuming (by hardlinking the file, falling back to copying). the last delivery to a recipient of a message (and the only one in the common case of a single recipient) would consume the message, and the earlier recipients would not. during delivery, the already open message file was used, to parse the message. we still want to use that open message file, and the caller now stays responsible for closing it, but we no longer try to rename (consume) the file. we always hardlink (or copy) during delivery (this works on windows), and the caller is responsible for closing and removing (in that order) the original temporary file. this does cost one syscall more. but it makes the delivery code (responsibilities) a bit simpler. there is one more obvious issue: the file system path separator. mox already used the "filepath" package to join paths in many places, but not everywhere. and it still used strings with slashes for local file access. with this commit, the code now uses filepath.FromSlash for path strings with slashes, uses "filepath" in a few more places where it previously didn't. also switches from "filepath" to regular "path" package when handling mailbox names in a few places, because those always use forward slashes, regardless of local file system conventions. windows can handle forward slashes when opening files, so test code that passes path strings with forward slashes straight to go stdlib file i/o functions are left unchanged to reduce code churn. the regular non-test code, or test code that uses path strings in places other than standard i/o functions, does have the paths converted for consistent paths (otherwise we would end up with paths with mixed forward/backward slashes in log messages). windows cannot dup a listening socket. for "mox localserve", it isn't important, and we can work around the issue. the current approach for "mox serve" (forking a process and passing file descriptors of listening sockets on "privileged" ports) won't work on windows. perhaps it isn't needed on windows, and any user can listen on "privileged" ports? that would be welcome. on windows, os.Open cannot open a directory, so we cannot call Sync on it after message delivery. a cursory internet search indicates that directories cannot be synced on windows. the story is probably much more nuanced than that, with long deep technical details/discussions/disagreement/confusion, like on unix. for "mox localserve" we can get away with making syncdir a no-op.
229 lines
6.4 KiB
Go
229 lines
6.4 KiB
Go
package webaccount
|
|
|
|
import (
|
|
"archive/tar"
|
|
"archive/zip"
|
|
"bytes"
|
|
"compress/gzip"
|
|
"context"
|
|
"encoding/base64"
|
|
"encoding/json"
|
|
"fmt"
|
|
"io"
|
|
"mime/multipart"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"os"
|
|
"path"
|
|
"path/filepath"
|
|
"sort"
|
|
"strings"
|
|
"testing"
|
|
|
|
"github.com/mjl-/bstore"
|
|
|
|
"github.com/mjl-/mox/mlog"
|
|
"github.com/mjl-/mox/mox-"
|
|
"github.com/mjl-/mox/store"
|
|
)
|
|
|
|
var ctxbg = context.Background()
|
|
|
|
func tcheck(t *testing.T, err error, msg string) {
|
|
t.Helper()
|
|
if err != nil {
|
|
t.Fatalf("%s: %s", msg, err)
|
|
}
|
|
}
|
|
|
|
func TestAccount(t *testing.T) {
|
|
os.RemoveAll("../testdata/httpaccount/data")
|
|
mox.ConfigStaticPath = filepath.FromSlash("../testdata/httpaccount/mox.conf")
|
|
mox.ConfigDynamicPath = filepath.Join(filepath.Dir(mox.ConfigStaticPath), "domains.conf")
|
|
mox.MustLoadConfig(true, false)
|
|
acc, err := store.OpenAccount("mjl")
|
|
tcheck(t, err, "open account")
|
|
defer func() {
|
|
err = acc.Close()
|
|
tcheck(t, err, "closing account")
|
|
}()
|
|
defer store.Switchboard()()
|
|
|
|
log := mlog.New("store")
|
|
|
|
test := func(userpass string, expect string) {
|
|
t.Helper()
|
|
|
|
w := httptest.NewRecorder()
|
|
r := httptest.NewRequest("GET", "/ignored", nil)
|
|
authhdr := "Basic " + base64.StdEncoding.EncodeToString([]byte(userpass))
|
|
r.Header.Add("Authorization", authhdr)
|
|
_, accName := CheckAuth(ctxbg, log, "webaccount", w, r)
|
|
if accName != expect {
|
|
t.Fatalf("got %q, expected %q", accName, expect)
|
|
}
|
|
}
|
|
|
|
const authOK = "mjl@mox.example:test1234"
|
|
const authBad = "mjl@mox.example:badpassword"
|
|
|
|
authCtx := context.WithValue(ctxbg, authCtxKey, "mjl")
|
|
|
|
test(authOK, "") // No password set yet.
|
|
Account{}.SetPassword(authCtx, "test1234")
|
|
test(authOK, "mjl")
|
|
test(authBad, "")
|
|
|
|
fullName, _, dests := Account{}.Account(authCtx)
|
|
Account{}.DestinationSave(authCtx, "mjl@mox.example", dests["mjl@mox.example"], dests["mjl@mox.example"]) // todo: save modified value and compare it afterwards
|
|
|
|
Account{}.AccountSaveFullName(authCtx, fullName+" changed") // todo: check if value was changed
|
|
Account{}.AccountSaveFullName(authCtx, fullName)
|
|
|
|
go ImportManage()
|
|
|
|
// Import mbox/maildir tgz/zip.
|
|
testImport := func(filename string, expect int) {
|
|
t.Helper()
|
|
|
|
var reqBody bytes.Buffer
|
|
mpw := multipart.NewWriter(&reqBody)
|
|
part, err := mpw.CreateFormFile("file", path.Base(filename))
|
|
tcheck(t, err, "creating form file")
|
|
buf, err := os.ReadFile(filename)
|
|
tcheck(t, err, "reading file")
|
|
_, err = part.Write(buf)
|
|
tcheck(t, err, "write part")
|
|
err = mpw.Close()
|
|
tcheck(t, err, "close multipart writer")
|
|
|
|
r := httptest.NewRequest("POST", "/import", &reqBody)
|
|
r.Header.Add("Content-Type", mpw.FormDataContentType())
|
|
r.Header.Add("Authorization", "Basic "+base64.StdEncoding.EncodeToString([]byte(authOK)))
|
|
w := httptest.NewRecorder()
|
|
Handle(w, r)
|
|
if w.Code != http.StatusOK {
|
|
t.Fatalf("import, got status code %d, expected 200: %s", w.Code, w.Body.Bytes())
|
|
}
|
|
m := map[string]string{}
|
|
if err := json.Unmarshal(w.Body.Bytes(), &m); err != nil {
|
|
t.Fatalf("parsing import response: %v", err)
|
|
}
|
|
token := m["ImportToken"]
|
|
|
|
l := importListener{token, make(chan importEvent, 100), make(chan bool)}
|
|
importers.Register <- &l
|
|
if !<-l.Register {
|
|
t.Fatalf("register failed")
|
|
}
|
|
defer func() {
|
|
importers.Unregister <- &l
|
|
}()
|
|
count := 0
|
|
loop:
|
|
for {
|
|
e := <-l.Events
|
|
if e.Event == nil {
|
|
continue
|
|
}
|
|
switch x := e.Event.(type) {
|
|
case importCount:
|
|
count += x.Count
|
|
case importProblem:
|
|
t.Fatalf("unexpected problem: %q", x.Message)
|
|
case importStep:
|
|
case importDone:
|
|
break loop
|
|
case importAborted:
|
|
t.Fatalf("unexpected aborted import")
|
|
default:
|
|
panic(fmt.Sprintf("missing case for Event %#v", e))
|
|
}
|
|
}
|
|
if count != expect {
|
|
t.Fatalf("imported %d messages, expected %d", count, expect)
|
|
}
|
|
}
|
|
testImport(filepath.FromSlash("../testdata/importtest.mbox.zip"), 2)
|
|
testImport(filepath.FromSlash("../testdata/importtest.maildir.tgz"), 2)
|
|
|
|
// Check there are messages, with the right flags.
|
|
acc.DB.Read(ctxbg, func(tx *bstore.Tx) error {
|
|
_, err = bstore.QueryTx[store.Message](tx).FilterEqual("Expunged", false).FilterIn("Keywords", "other").FilterIn("Keywords", "test").Get()
|
|
tcheck(t, err, `fetching message with keywords "other" and "test"`)
|
|
|
|
mb, err := acc.MailboxFind(tx, "importtest")
|
|
tcheck(t, err, "looking up mailbox importtest")
|
|
if mb == nil {
|
|
t.Fatalf("missing mailbox importtest")
|
|
}
|
|
sort.Strings(mb.Keywords)
|
|
if strings.Join(mb.Keywords, " ") != "other test" {
|
|
t.Fatalf(`expected mailbox keywords "other" and "test", got %v`, mb.Keywords)
|
|
}
|
|
|
|
n, err := bstore.QueryTx[store.Message](tx).FilterEqual("Expunged", false).FilterIn("Keywords", "custom").Count()
|
|
tcheck(t, err, `fetching message with keyword "custom"`)
|
|
if n != 2 {
|
|
t.Fatalf(`got %d messages with keyword "custom", expected 2`, n)
|
|
}
|
|
|
|
mb, err = acc.MailboxFind(tx, "maildir")
|
|
tcheck(t, err, "looking up mailbox maildir")
|
|
if mb == nil {
|
|
t.Fatalf("missing mailbox maildir")
|
|
}
|
|
if strings.Join(mb.Keywords, " ") != "custom" {
|
|
t.Fatalf(`expected mailbox keywords "custom", got %v`, mb.Keywords)
|
|
}
|
|
|
|
return nil
|
|
})
|
|
|
|
testExport := func(httppath string, iszip bool, expectFiles int) {
|
|
t.Helper()
|
|
|
|
r := httptest.NewRequest("GET", httppath, nil)
|
|
r.Header.Add("Authorization", "Basic "+base64.StdEncoding.EncodeToString([]byte(authOK)))
|
|
w := httptest.NewRecorder()
|
|
Handle(w, r)
|
|
if w.Code != http.StatusOK {
|
|
t.Fatalf("export, got status code %d, expected 200: %s", w.Code, w.Body.Bytes())
|
|
}
|
|
var count int
|
|
if iszip {
|
|
buf := w.Body.Bytes()
|
|
zr, err := zip.NewReader(bytes.NewReader(buf), int64(len(buf)))
|
|
tcheck(t, err, "reading zip")
|
|
for _, f := range zr.File {
|
|
if !strings.HasSuffix(f.Name, "/") {
|
|
count++
|
|
}
|
|
}
|
|
} else {
|
|
gzr, err := gzip.NewReader(w.Body)
|
|
tcheck(t, err, "gzip reader")
|
|
tr := tar.NewReader(gzr)
|
|
for {
|
|
h, err := tr.Next()
|
|
if err == io.EOF {
|
|
break
|
|
}
|
|
tcheck(t, err, "next file in tar")
|
|
if !strings.HasSuffix(h.Name, "/") {
|
|
count++
|
|
}
|
|
_, err = io.Copy(io.Discard, tr)
|
|
tcheck(t, err, "reading from tar")
|
|
}
|
|
}
|
|
if count != expectFiles {
|
|
t.Fatalf("export, has %d files, expected %d", count, expectFiles)
|
|
}
|
|
}
|
|
|
|
testExport("/mail-export-maildir.tgz", false, 6) // 2 mailboxes, each with 2 messages and a dovecot-keyword file
|
|
testExport("/mail-export-maildir.zip", true, 6)
|
|
testExport("/mail-export-mbox.tgz", false, 2)
|
|
testExport("/mail-export-mbox.zip", true, 2)
|
|
}
|