1// Package webaccount provides a web app for users to view and change their account
2// settings, and to import/export email.
8 cryptorand "crypto/rand"
27 "github.com/mjl-/bstore"
28 "github.com/mjl-/sherpa"
29 "github.com/mjl-/sherpadoc"
30 "github.com/mjl-/sherpaprom"
32 "github.com/mjl-/mox/admin"
33 "github.com/mjl-/mox/config"
34 "github.com/mjl-/mox/mlog"
35 "github.com/mjl-/mox/mox-"
36 "github.com/mjl-/mox/moxvar"
37 "github.com/mjl-/mox/queue"
38 "github.com/mjl-/mox/smtp"
39 "github.com/mjl-/mox/store"
40 "github.com/mjl-/mox/webapi"
41 "github.com/mjl-/mox/webauth"
42 "github.com/mjl-/mox/webhook"
43 "github.com/mjl-/mox/webops"
46var pkglog = mlog.New("webaccount", nil)
49var accountapiJSON []byte
51//go:embed account.html
57var webaccountFile = &mox.WebappFile{
60 HTMLPath: filepath.FromSlash("webaccount/account.html"),
61 JSPath: filepath.FromSlash("webaccount/account.js"),
62 CustomStem: "webaccount",
65var accountDoc = mustParseAPI("account", accountapiJSON)
67func mustParseAPI(api string, buf []byte) (doc sherpadoc.Section) {
68 err := json.Unmarshal(buf, &doc)
70 pkglog.Fatalx("parsing webaccount api docs", err, slog.String("api", api))
75var sherpaHandlerOpts *sherpa.HandlerOpts
77func makeSherpaHandler(cookiePath string, isForwarded bool) (http.Handler, error) {
78 return sherpa.NewHandler("/api/", moxvar.Version, Account{cookiePath, isForwarded}, &accountDoc, sherpaHandlerOpts)
82 collector, err := sherpaprom.NewCollector("moxaccount", nil)
84 pkglog.Fatalx("creating sherpa prometheus collector", err)
87 sherpaHandlerOpts = &sherpa.HandlerOpts{Collector: collector, AdjustFunctionNames: "none", NoCORS: true}
89 _, err = makeSherpaHandler("", false)
91 pkglog.Fatalx("sherpa handler", err)
94 mox.NewWebaccountHandler = func(basePath string, isForwarded bool) http.Handler {
95 return http.HandlerFunc(Handler(basePath, isForwarded))
99// Handler returns a handler for the webaccount endpoints, customized for the
101func Handler(cookiePath string, isForwarded bool) func(w http.ResponseWriter, r *http.Request) {
102 sh, err := makeSherpaHandler(cookiePath, isForwarded)
103 return func(w http.ResponseWriter, r *http.Request) {
105 http.Error(w, "500 - internal server error - cannot handle requests", http.StatusInternalServerError)
108 handle(sh, isForwarded, w, r)
112func xcheckf(ctx context.Context, err error, format string, args ...any) {
116 // If caller tried saving a config that is invalid, or because of a bad request, cause a user error.
117 if errors.Is(err, mox.ErrConfig) || errors.Is(err, admin.ErrRequest) {
118 xcheckuserf(ctx, err, format, args...)
121 msg := fmt.Sprintf(format, args...)
122 errmsg := fmt.Sprintf("%s: %s", msg, err)
123 pkglog.WithContext(ctx).Errorx(msg, err)
124 code := "server:error"
125 if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
128 panic(&sherpa.Error{Code: code, Message: errmsg})
131func xcheckuserf(ctx context.Context, err error, format string, args ...any) {
135 msg := fmt.Sprintf(format, args...)
136 errmsg := fmt.Sprintf("%s: %s", msg, err)
137 pkglog.WithContext(ctx).Errorx(msg, err)
138 panic(&sherpa.Error{Code: "user:error", Message: errmsg})
141// Account exports web API functions for the account web interface. All its
142// methods are exported under api/. Function calls require valid HTTP
143// Authentication credentials of a user.
145 cookiePath string // From listener, for setting authentication cookies.
146 isForwarded bool // From listener, whether we look at X-Forwarded-* headers.
149func handle(apiHandler http.Handler, isForwarded bool, w http.ResponseWriter, r *http.Request) {
150 ctx := context.WithValue(r.Context(), mlog.CidKey, mox.Cid())
151 log := pkglog.WithContext(ctx).With(slog.String("userauth", ""))
153 // Without authentication. The token is unguessable.
154 if r.URL.Path == "/importprogress" {
155 if r.Method != "GET" {
156 http.Error(w, "405 - method not allowed - get required", http.StatusMethodNotAllowed)
161 token := q.Get("token")
163 http.Error(w, "400 - bad request - missing token", http.StatusBadRequest)
167 flusher, ok := w.(http.Flusher)
169 log.Error("internal error: ResponseWriter not a http.Flusher")
170 http.Error(w, "500 - internal error - cannot access underlying connection", 500)
174 l := importListener{token, make(chan importEvent, 100), make(chan bool, 1)}
175 importers.Register <- &l
178 http.Error(w, "400 - bad request - unknown token, import may have finished more than a minute ago", http.StatusBadRequest)
182 importers.Unregister <- &l
186 h.Set("Content-Type", "text/event-stream")
187 h.Set("Cache-Control", "no-cache")
188 _, err := w.Write([]byte(": keepalive\n\n"))
197 case e := <-l.Events:
198 _, err := w.Write(e.SSEMsg)
210 // HTML/JS can be retrieved without authentication.
211 if r.URL.Path == "/" {
214 webaccountFile.Serve(ctx, log, w, r)
216 http.Error(w, "405 - method not allowed - use get", http.StatusMethodNotAllowed)
219 } else if r.URL.Path == "/licenses.txt" {
224 http.Error(w, "405 - method not allowed - use get", http.StatusMethodNotAllowed)
229 isAPI := strings.HasPrefix(r.URL.Path, "/api/")
230 // Only allow POST for calls, they will not work cross-domain without CORS.
231 if isAPI && r.URL.Path != "/api/" && r.Method != "POST" {
232 http.Error(w, "405 - method not allowed - use post", http.StatusMethodNotAllowed)
236 var loginAddress, accName string
237 var sessionToken store.SessionToken
238 // All other URLs, except the login endpoint require some authentication.
239 if r.URL.Path != "/api/LoginPrep" && r.URL.Path != "/api/Login" {
241 isExport := r.URL.Path == "/export"
242 requireCSRF := isAPI || r.URL.Path == "/import" || isExport
243 accName, sessionToken, loginAddress, ok = webauth.Check(ctx, log, webauth.Accounts, "webaccount", isForwarded, w, r, isAPI, requireCSRF, isExport)
245 // Response has been written already.
251 reqInfo := requestInfo{loginAddress, accName, sessionToken, w, r}
252 ctx = context.WithValue(ctx, requestInfoCtxKey, reqInfo)
253 apiHandler.ServeHTTP(w, r.WithContext(ctx))
259 webops.Export(log, accName, w, r)
262 if r.Method != "POST" {
263 http.Error(w, "405 - method not allowed - post required", http.StatusMethodNotAllowed)
267 f, _, err := r.FormFile("file")
269 if errors.Is(err, http.ErrMissingFile) {
270 http.Error(w, "400 - bad request - missing file", http.StatusBadRequest)
272 http.Error(w, "500 - internal server error - "+err.Error(), http.StatusInternalServerError)
278 log.Check(err, "closing form file")
280 skipMailboxPrefix := r.FormValue("skipMailboxPrefix")
281 tmpf, err := os.CreateTemp("", "mox-import")
283 http.Error(w, "500 - internal server error - "+err.Error(), http.StatusInternalServerError)
288 store.CloseRemoveTempFile(log, tmpf, "upload")
291 if _, err := io.Copy(tmpf, f); err != nil {
292 log.Errorx("copying import to temporary file", err)
293 http.Error(w, "500 - internal server error - "+err.Error(), http.StatusInternalServerError)
296 token, isUserError, err := importStart(log, accName, tmpf, skipMailboxPrefix)
298 log.Errorx("starting import", err, slog.Bool("usererror", isUserError))
300 http.Error(w, "400 - bad request - "+err.Error(), http.StatusBadRequest)
302 http.Error(w, "500 - internal server error - "+err.Error(), http.StatusInternalServerError)
306 tmpf = nil // importStart is now responsible for cleanup.
308 w.Header().Set("Content-Type", "application/json")
309 _ = json.NewEncoder(w).Encode(ImportProgress{Token: token})
316// ImportProgress is returned after uploading a file to import.
317type ImportProgress struct {
318 // For fetching progress, or cancelling an import.
324var requestInfoCtxKey ctxKey = "requestInfo"
326type requestInfo struct {
329 SessionToken store.SessionToken
330 Response http.ResponseWriter
331 Request *http.Request // For Proto and TLS connection state during message submit.
334// LoginPrep returns a login token, and also sets it as cookie. Both must be
335// present in the call to Login.
336func (w Account) LoginPrep(ctx context.Context) string {
337 log := pkglog.WithContext(ctx)
338 reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
341 cryptorand.Read(data[:])
342 loginToken := base64.RawURLEncoding.EncodeToString(data[:])
344 webauth.LoginPrep(ctx, log, "webaccount", w.cookiePath, w.isForwarded, reqInfo.Response, reqInfo.Request, loginToken)
349// Login returns a session token for the credentials, or fails with error code
350// "user:badLogin". Call LoginPrep to get a loginToken.
351func (w Account) Login(ctx context.Context, loginToken, username, password string) store.CSRFToken {
352 log := pkglog.WithContext(ctx)
353 reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
355 csrfToken, err := webauth.Login(ctx, log, webauth.Accounts, "webaccount", w.cookiePath, w.isForwarded, reqInfo.Response, reqInfo.Request, loginToken, username, password)
356 if _, ok := err.(*sherpa.Error); ok {
359 xcheckf(ctx, err, "login")
363// Logout invalidates the session token.
364func (w Account) Logout(ctx context.Context) {
365 log := pkglog.WithContext(ctx)
366 reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
368 err := webauth.Logout(ctx, log, webauth.Accounts, "webaccount", w.cookiePath, w.isForwarded, reqInfo.Response, reqInfo.Request, reqInfo.AccountName, reqInfo.SessionToken)
369 xcheckf(ctx, err, "logout")
372// Version returns the version, goos and goarch.
373func (Account) Version(ctx context.Context) (version, goos, goarch string) {
374 return moxvar.Version, runtime.GOOS, runtime.GOARCH
377// SetPassword saves a new password for the account, invalidating the previous
380// Sessions are not interrupted, and will keep working. New login attempts must use
383// Password must be at least 8 characters.
385// Setting a user-supplied password is not allowed if NoCustomPassword is set
387func (Account) SetPassword(ctx context.Context, password string) {
388 log := pkglog.WithContext(ctx)
389 if len(password) < 8 {
390 panic(&sherpa.Error{Code: "user:error", Message: "password must be at least 8 characters"})
393 reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
394 acc, err := store.OpenAccount(log, reqInfo.AccountName, false)
395 xcheckf(ctx, err, "open account")
398 log.Check(err, "closing account")
401 accConf, _ := acc.Conf()
402 if accConf.NoCustomPassword {
403 xcheckuserf(ctx, errors.New("custom password not allowed"), "setting password")
406 // Retrieve session, resetting password invalidates it.
407 ls, err := store.SessionUse(ctx, log, reqInfo.AccountName, reqInfo.SessionToken, "")
408 xcheckf(ctx, err, "get session")
410 err = acc.SetPassword(log, password)
411 xcheckf(ctx, err, "setting password")
413 // Session has been invalidated. Add it again.
414 err = store.SessionAddToken(ctx, log, &ls)
415 xcheckf(ctx, err, "restoring session after password reset")
418// GeneratePassword sets a new randomly generated password for the current account.
419// Sessions are not interrupted, and will keep working.
420func (Account) GeneratePassword(ctx context.Context) (password string) {
421 log := pkglog.WithContext(ctx)
423 reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
424 acc, err := store.OpenAccount(log, reqInfo.AccountName, false)
425 xcheckf(ctx, err, "open account")
428 log.Check(err, "closing account")
431 password = mox.GeneratePassword()
433 // Retrieve session, resetting password invalidates it.
434 ls, err := store.SessionUse(ctx, log, reqInfo.AccountName, reqInfo.SessionToken, "")
435 xcheckf(ctx, err, "get session")
437 err = acc.SetPassword(log, password)
438 xcheckf(ctx, err, "setting password")
440 // Session has been invalidated. Add it again.
441 err = store.SessionAddToken(ctx, log, &ls)
442 xcheckf(ctx, err, "restoring session after password reset")
447// Account returns information about the account.
448// StorageUsed is the sum of the sizes of all messages, in bytes.
449// StorageLimit is the maximum storage that can be used, or 0 if there is no limit.
450func (Account) Account(ctx context.Context) (account config.Account, storageUsed, storageLimit int64, suppressions []webapi.Suppression) {
451 log := pkglog.WithContext(ctx)
452 reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
454 acc, err := store.OpenAccount(log, reqInfo.AccountName, false)
455 xcheckf(ctx, err, "open account")
458 log.Check(err, "closing account")
461 var accConf config.Account
462 acc.WithRLock(func() {
463 accConf, _ = acc.Conf()
465 storageLimit = acc.QuotaMessageSize()
466 err := acc.DB.Read(ctx, func(tx *bstore.Tx) error {
467 du := store.DiskUsage{ID: 1}
469 storageUsed = du.MessageSize
472 xcheckf(ctx, err, "get disk usage")
475 suppressions, err = queue.SuppressionList(ctx, reqInfo.AccountName)
476 xcheckf(ctx, err, "list suppressions")
478 return accConf, storageUsed, storageLimit, suppressions
481// AccountSaveFullName saves the full name (used as display name in email messages)
483func (Account) AccountSaveFullName(ctx context.Context, fullName string) {
484 reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
485 err := admin.AccountSave(ctx, reqInfo.AccountName, func(acc *config.Account) {
486 acc.FullName = fullName
488 xcheckf(ctx, err, "saving account full name")
491// DestinationSave updates a destination.
492// OldDest is compared against the current destination. If it does not match, an
493// error is returned. Otherwise newDest is saved and the configuration reloaded.
494func (Account) DestinationSave(ctx context.Context, destName string, oldDest, newDest config.Destination) {
495 reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
497 err := admin.AccountSave(ctx, reqInfo.AccountName, func(conf *config.Account) {
498 curDest, ok := conf.Destinations[destName]
500 xcheckuserf(ctx, errors.New("not found"), "looking up destination")
502 if !curDest.Equal(oldDest) {
503 xcheckuserf(ctx, errors.New("modified"), "checking stored destination")
506 // Keep fields we manage.
507 newDest.DMARCReports = curDest.DMARCReports
508 newDest.HostTLSReports = curDest.HostTLSReports
509 newDest.DomainTLSReports = curDest.DomainTLSReports
511 // Make copy of reference values.
512 nd := map[string]config.Destination{}
513 maps.Copy(nd, conf.Destinations)
514 nd[destName] = newDest
515 conf.Destinations = nd
517 xcheckf(ctx, err, "saving destination")
520// ImportAbort aborts an import that is in progress. If the import exists and isn't
521// finished, no changes will have been made by the import.
522func (Account) ImportAbort(ctx context.Context, importToken string) error {
523 req := importAbortRequest{importToken, make(chan error)}
524 importers.Abort <- req
525 return <-req.Response
528// Types exposes types not used in API method signatures, such as the import form upload.
529func (Account) Types() (importProgress ImportProgress) {
533// SuppressionList lists the addresses on the suppression list of this account.
534func (Account) SuppressionList(ctx context.Context) (suppressions []webapi.Suppression) {
535 reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
536 l, err := queue.SuppressionList(ctx, reqInfo.AccountName)
537 xcheckf(ctx, err, "list suppressions")
541// SuppressionAdd adds an email address to the suppression list.
542func (Account) SuppressionAdd(ctx context.Context, address string, manual bool, reason string) (suppression webapi.Suppression) {
543 reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
544 addr, err := smtp.ParseAddress(address)
545 xcheckuserf(ctx, err, "parsing address")
546 sup := webapi.Suppression{
547 Account: reqInfo.AccountName,
551 err = queue.SuppressionAdd(ctx, addr.Path(), &sup)
552 if err != nil && errors.Is(err, bstore.ErrUnique) {
553 xcheckuserf(ctx, err, "add suppression")
555 xcheckf(ctx, err, "add suppression")
559// SuppressionRemove removes the email address from the suppression list.
560func (Account) SuppressionRemove(ctx context.Context, address string) {
561 reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
562 addr, err := smtp.ParseAddress(address)
563 xcheckuserf(ctx, err, "parsing address")
564 err = queue.SuppressionRemove(ctx, reqInfo.AccountName, addr.Path())
565 if err != nil && err == bstore.ErrAbsent {
566 xcheckuserf(ctx, err, "remove suppression")
568 xcheckf(ctx, err, "remove suppression")
571// OutgoingWebhookSave saves a new webhook url for outgoing deliveries. If url
572// is empty, the webhook is disabled. If authorization is non-empty it is used for
573// the Authorization header in HTTP requests. Events specifies the outgoing events
574// to be delivered, or all if empty/nil.
575func (Account) OutgoingWebhookSave(ctx context.Context, url, authorization string, events []string) {
576 reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
577 err := admin.AccountSave(ctx, reqInfo.AccountName, func(acc *config.Account) {
579 acc.OutgoingWebhook = nil
581 acc.OutgoingWebhook = &config.OutgoingWebhook{URL: url, Authorization: authorization, Events: events}
584 xcheckf(ctx, err, "saving account outgoing webhook")
587// OutgoingWebhookTest makes a test webhook call to urlStr, with optional
588// authorization. If the HTTP request is made this call will succeed also for
589// non-2xx HTTP status codes.
590func (Account) OutgoingWebhookTest(ctx context.Context, urlStr, authorization string, data webhook.Outgoing) (code int, response string, errmsg string) {
591 log := pkglog.WithContext(ctx)
593 xvalidURL(ctx, urlStr)
594 log.Debug("making webhook test call for outgoing message", slog.String("url", urlStr))
597 enc := json.NewEncoder(&b)
598 enc.SetIndent("", "\t")
599 enc.SetEscapeHTML(false)
600 err := enc.Encode(data)
601 xcheckf(ctx, err, "encoding outgoing webhook data")
603 code, response, err = queue.HookPost(ctx, log, 1, 1, urlStr, authorization, b.String())
607 log.Debugx("result for webhook test call for outgoing message", err, slog.Int("code", code), slog.String("response", response))
608 return code, response, errmsg
611// IncomingWebhookSave saves a new webhook url for incoming deliveries. If url is
612// empty, the webhook is disabled. If authorization is not empty, it is used in
613// the Authorization header in requests.
614func (Account) IncomingWebhookSave(ctx context.Context, url, authorization string) {
615 reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
616 err := admin.AccountSave(ctx, reqInfo.AccountName, func(acc *config.Account) {
618 acc.IncomingWebhook = nil
620 acc.IncomingWebhook = &config.IncomingWebhook{URL: url, Authorization: authorization}
623 xcheckf(ctx, err, "saving account incoming webhook")
626func xvalidURL(ctx context.Context, s string) {
627 u, err := url.Parse(s)
628 xcheckuserf(ctx, err, "parsing url")
629 if u.Scheme != "http" && u.Scheme != "https" {
630 xcheckuserf(ctx, errors.New("scheme must be http or https"), "parsing url")
634// IncomingWebhookTest makes a test webhook HTTP delivery request to urlStr,
635// with optional authorization header. If the HTTP call is made, this function
636// returns non-error regardless of HTTP status code.
637func (Account) IncomingWebhookTest(ctx context.Context, urlStr, authorization string, data webhook.Incoming) (code int, response string, errmsg string) {
638 log := pkglog.WithContext(ctx)
640 xvalidURL(ctx, urlStr)
641 log.Debug("making webhook test call for incoming message", slog.String("url", urlStr))
644 enc := json.NewEncoder(&b)
645 enc.SetEscapeHTML(false)
646 enc.SetIndent("", "\t")
647 err := enc.Encode(data)
648 xcheckf(ctx, err, "encoding incoming webhook data")
649 code, response, err = queue.HookPost(ctx, log, 1, 1, urlStr, authorization, b.String())
653 log.Debugx("result for webhook test call for incoming message", err, slog.Int("code", code), slog.String("response", response))
654 return code, response, errmsg
657// FromIDLoginAddressesSave saves new login addresses to enable unique SMTP
658// MAIL FROM addresses ("fromid") for deliveries from the queue.
659func (Account) FromIDLoginAddressesSave(ctx context.Context, loginAddresses []string) {
660 reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
661 err := admin.AccountSave(ctx, reqInfo.AccountName, func(acc *config.Account) {
662 acc.FromIDLoginAddresses = loginAddresses
664 xcheckf(ctx, err, "saving account fromid login addresses")
667// KeepRetiredPeriodsSave saves periods to save retired messages and webhooks.
668func (Account) KeepRetiredPeriodsSave(ctx context.Context, keepRetiredMessagePeriod, keepRetiredWebhookPeriod time.Duration) {
669 reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
670 err := admin.AccountSave(ctx, reqInfo.AccountName, func(acc *config.Account) {
671 acc.KeepRetiredMessagePeriod = keepRetiredMessagePeriod
672 acc.KeepRetiredWebhookPeriod = keepRetiredWebhookPeriod
674 xcheckf(ctx, err, "saving account keep retired periods")
677// AutomaticJunkFlagsSave saves settings for automatically marking messages as
678// junk/nonjunk when moved to mailboxes matching certain regular expressions.
679func (Account) AutomaticJunkFlagsSave(ctx context.Context, enabled bool, junkRegexp, neutralRegexp, notJunkRegexp string) {
680 reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
681 err := admin.AccountSave(ctx, reqInfo.AccountName, func(acc *config.Account) {
682 acc.AutomaticJunkFlags = config.AutomaticJunkFlags{
684 JunkMailboxRegexp: junkRegexp,
685 NeutralMailboxRegexp: neutralRegexp,
686 NotJunkMailboxRegexp: notJunkRegexp,
689 xcheckf(ctx, err, "saving account automatic junk flags")
692// JunkFilterSave saves junk filter settings. If junkFilter is nil, the junk filter
693// is disabled. Otherwise all fields except Threegrams are stored.
694func (Account) JunkFilterSave(ctx context.Context, junkFilter *config.JunkFilter) {
695 reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
696 err := admin.AccountSave(ctx, reqInfo.AccountName, func(acc *config.Account) {
697 if junkFilter == nil {
701 old := acc.JunkFilter
702 acc.JunkFilter = junkFilter
703 acc.JunkFilter.Params.Threegrams = false
705 acc.JunkFilter.Params.Threegrams = old.Params.Threegrams
708 xcheckf(ctx, err, "saving account junk filter settings")
711// RejectsSave saves the RejectsMailbox and KeepRejects settings.
712func (Account) RejectsSave(ctx context.Context, mailbox string, keep bool) {
713 reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
714 err := admin.AccountSave(ctx, reqInfo.AccountName, func(acc *config.Account) {
715 acc.RejectsMailbox = mailbox
716 acc.KeepRejects = keep
718 xcheckf(ctx, err, "saving account rejects settings")
721func (Account) TLSPublicKeys(ctx context.Context) ([]store.TLSPublicKey, error) {
722 reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
723 return store.TLSPublicKeyList(ctx, reqInfo.AccountName)
726func (Account) TLSPublicKeyAdd(ctx context.Context, loginAddress, name string, noIMAPPreauth bool, certPEM string) (store.TLSPublicKey, error) {
727 reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
729 block, rest := pem.Decode([]byte(certPEM))
732 err = errors.New("no pem data found")
733 } else if block.Type != "CERTIFICATE" {
734 err = fmt.Errorf("unexpected type %q, need CERTIFICATE", block.Type)
735 } else if len(rest) != 0 {
736 err = errors.New("only single pem block allowed")
738 xcheckuserf(ctx, err, "parsing pem file")
740 tpk, err := store.ParseTLSPublicKeyCert(block.Bytes)
741 xcheckuserf(ctx, err, "parsing certificate")
745 tpk.Account = reqInfo.AccountName
746 tpk.LoginAddress = loginAddress
747 tpk.NoIMAPPreauth = noIMAPPreauth
748 err = store.TLSPublicKeyAdd(ctx, &tpk)
749 if err != nil && errors.Is(err, bstore.ErrUnique) {
750 xcheckuserf(ctx, err, "add tls public key")
752 xcheckf(ctx, err, "add tls public key")
757func xtlspublickey(ctx context.Context, account string, fingerprint string) store.TLSPublicKey {
758 tpk, err := store.TLSPublicKeyGet(ctx, fingerprint)
759 if err == nil && tpk.Account != account {
760 err = bstore.ErrAbsent
762 if err == bstore.ErrAbsent {
763 xcheckuserf(ctx, err, "get tls public key")
765 xcheckf(ctx, err, "get tls public key")
769func (Account) TLSPublicKeyRemove(ctx context.Context, fingerprint string) error {
770 reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
771 xtlspublickey(ctx, reqInfo.AccountName, fingerprint)
772 return store.TLSPublicKeyRemove(ctx, fingerprint)
775func (Account) TLSPublicKeyUpdate(ctx context.Context, pubKey store.TLSPublicKey) error {
776 reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
777 tpk := xtlspublickey(ctx, reqInfo.AccountName, pubKey.Fingerprint)
778 log := pkglog.WithContext(ctx)
779 acc, _, _, err := store.OpenEmail(log, pubKey.LoginAddress, false)
780 if err == nil && acc.Name != reqInfo.AccountName {
781 err = store.ErrUnknownCredentials
785 log.Check(xerr, "close account")
787 if err == store.ErrUnknownCredentials {
788 xcheckuserf(ctx, errors.New("unknown address"), "looking up address")
790 tpk.Name = pubKey.Name
791 tpk.LoginAddress = pubKey.LoginAddress
792 tpk.NoIMAPPreauth = pubKey.NoIMAPPreauth
793 err = store.TLSPublicKeyUpdate(ctx, &tpk)
794 xcheckf(ctx, err, "updating tls public key")
798func (Account) LoginAttempts(ctx context.Context, limit int) []store.LoginAttempt {
799 reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
800 l, err := store.LoginAttemptList(ctx, reqInfo.AccountName, limit)
801 xcheckf(ctx, err, "listing login attempts")
805func (Account) IMAPSave(ctx context.Context, capabilitiesDisabled []string) {
806 // Basic check for capabilities.
807 for _, s := range capabilitiesDisabled {
808 if strings.ToUpper(s) != s {
809 xcheckuserf(ctx, errors.New("capability must be in upper case"), "checking capabilities")
811 for _, c := range s {
813 xcheckuserf(ctx, errors.New("capability cannot contain control characters"), "checking capabilities")
818 reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
819 err := admin.AccountSave(ctx, reqInfo.AccountName, func(acc *config.Account) {
820 acc.IMAPCapabilitiesDisabled = capabilitiesDisabled
822 xcheckf(ctx, err, "saving disabled imap capabilities")