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"
26 "github.com/mjl-/bstore"
27 "github.com/mjl-/sherpa"
28 "github.com/mjl-/sherpadoc"
29 "github.com/mjl-/sherpaprom"
31 "github.com/mjl-/mox/admin"
32 "github.com/mjl-/mox/config"
33 "github.com/mjl-/mox/mlog"
34 "github.com/mjl-/mox/mox-"
35 "github.com/mjl-/mox/moxvar"
36 "github.com/mjl-/mox/queue"
37 "github.com/mjl-/mox/smtp"
38 "github.com/mjl-/mox/store"
39 "github.com/mjl-/mox/webapi"
40 "github.com/mjl-/mox/webauth"
41 "github.com/mjl-/mox/webhook"
42 "github.com/mjl-/mox/webops"
45var pkglog = mlog.New("webaccount", nil)
48var accountapiJSON []byte
50//go:embed account.html
56var webaccountFile = &mox.WebappFile{
59 HTMLPath: filepath.FromSlash("webaccount/account.html"),
60 JSPath: filepath.FromSlash("webaccount/account.js"),
61 CustomStem: "webaccount",
64var accountDoc = mustParseAPI("account", accountapiJSON)
66func mustParseAPI(api string, buf []byte) (doc sherpadoc.Section) {
67 err := json.Unmarshal(buf, &doc)
69 pkglog.Fatalx("parsing webaccount api docs", err, slog.String("api", api))
74var sherpaHandlerOpts *sherpa.HandlerOpts
76func makeSherpaHandler(cookiePath string, isForwarded bool) (http.Handler, error) {
77 return sherpa.NewHandler("/api/", moxvar.Version, Account{cookiePath, isForwarded}, &accountDoc, sherpaHandlerOpts)
81 collector, err := sherpaprom.NewCollector("moxaccount", nil)
83 pkglog.Fatalx("creating sherpa prometheus collector", err)
86 sherpaHandlerOpts = &sherpa.HandlerOpts{Collector: collector, AdjustFunctionNames: "none", NoCORS: true}
88 _, err = makeSherpaHandler("", false)
90 pkglog.Fatalx("sherpa handler", err)
93 mox.NewWebaccountHandler = func(basePath string, isForwarded bool) http.Handler {
94 return http.HandlerFunc(Handler(basePath, isForwarded))
98// Handler returns a handler for the webaccount endpoints, customized for the
100func Handler(cookiePath string, isForwarded bool) func(w http.ResponseWriter, r *http.Request) {
101 sh, err := makeSherpaHandler(cookiePath, isForwarded)
102 return func(w http.ResponseWriter, r *http.Request) {
104 http.Error(w, "500 - internal server error - cannot handle requests", http.StatusInternalServerError)
107 handle(sh, isForwarded, w, r)
111func xcheckf(ctx context.Context, err error, format string, args ...any) {
115 // If caller tried saving a config that is invalid, or because of a bad request, cause a user error.
116 if errors.Is(err, mox.ErrConfig) || errors.Is(err, admin.ErrRequest) {
117 xcheckuserf(ctx, err, format, args...)
120 msg := fmt.Sprintf(format, args...)
121 errmsg := fmt.Sprintf("%s: %s", msg, err)
122 pkglog.WithContext(ctx).Errorx(msg, err)
123 code := "server:error"
124 if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
127 panic(&sherpa.Error{Code: code, Message: errmsg})
130func xcheckuserf(ctx context.Context, err error, format string, args ...any) {
134 msg := fmt.Sprintf(format, args...)
135 errmsg := fmt.Sprintf("%s: %s", msg, err)
136 pkglog.WithContext(ctx).Errorx(msg, err)
137 panic(&sherpa.Error{Code: "user:error", Message: errmsg})
140// Account exports web API functions for the account web interface. All its
141// methods are exported under api/. Function calls require valid HTTP
142// Authentication credentials of a user.
144 cookiePath string // From listener, for setting authentication cookies.
145 isForwarded bool // From listener, whether we look at X-Forwarded-* headers.
148func handle(apiHandler http.Handler, isForwarded bool, w http.ResponseWriter, r *http.Request) {
149 ctx := context.WithValue(r.Context(), mlog.CidKey, mox.Cid())
150 log := pkglog.WithContext(ctx).With(slog.String("userauth", ""))
152 // Without authentication. The token is unguessable.
153 if r.URL.Path == "/importprogress" {
154 if r.Method != "GET" {
155 http.Error(w, "405 - method not allowed - get required", http.StatusMethodNotAllowed)
160 token := q.Get("token")
162 http.Error(w, "400 - bad request - missing token", http.StatusBadRequest)
166 flusher, ok := w.(http.Flusher)
168 log.Error("internal error: ResponseWriter not a http.Flusher")
169 http.Error(w, "500 - internal error - cannot access underlying connection", 500)
173 l := importListener{token, make(chan importEvent, 100), make(chan bool, 1)}
174 importers.Register <- &l
177 http.Error(w, "400 - bad request - unknown token, import may have finished more than a minute ago", http.StatusBadRequest)
181 importers.Unregister <- &l
185 h.Set("Content-Type", "text/event-stream")
186 h.Set("Cache-Control", "no-cache")
187 _, err := w.Write([]byte(": keepalive\n\n"))
196 case e := <-l.Events:
197 _, err := w.Write(e.SSEMsg)
209 // HTML/JS can be retrieved without authentication.
210 if r.URL.Path == "/" {
213 webaccountFile.Serve(ctx, log, w, r)
215 http.Error(w, "405 - method not allowed - use get", http.StatusMethodNotAllowed)
218 } else if r.URL.Path == "/licenses.txt" {
223 http.Error(w, "405 - method not allowed - use get", http.StatusMethodNotAllowed)
228 isAPI := strings.HasPrefix(r.URL.Path, "/api/")
229 // Only allow POST for calls, they will not work cross-domain without CORS.
230 if isAPI && r.URL.Path != "/api/" && r.Method != "POST" {
231 http.Error(w, "405 - method not allowed - use post", http.StatusMethodNotAllowed)
235 var loginAddress, accName string
236 var sessionToken store.SessionToken
237 // All other URLs, except the login endpoint require some authentication.
238 if r.URL.Path != "/api/LoginPrep" && r.URL.Path != "/api/Login" {
240 isExport := r.URL.Path == "/export"
241 requireCSRF := isAPI || r.URL.Path == "/import" || isExport
242 accName, sessionToken, loginAddress, ok = webauth.Check(ctx, log, webauth.Accounts, "webaccount", isForwarded, w, r, isAPI, requireCSRF, isExport)
244 // Response has been written already.
250 reqInfo := requestInfo{loginAddress, accName, sessionToken, w, r}
251 ctx = context.WithValue(ctx, requestInfoCtxKey, reqInfo)
252 apiHandler.ServeHTTP(w, r.WithContext(ctx))
258 webops.Export(log, accName, w, r)
261 if r.Method != "POST" {
262 http.Error(w, "405 - method not allowed - post required", http.StatusMethodNotAllowed)
266 f, _, err := r.FormFile("file")
268 if errors.Is(err, http.ErrMissingFile) {
269 http.Error(w, "400 - bad request - missing file", http.StatusBadRequest)
271 http.Error(w, "500 - internal server error - "+err.Error(), http.StatusInternalServerError)
277 log.Check(err, "closing form file")
279 skipMailboxPrefix := r.FormValue("skipMailboxPrefix")
280 tmpf, err := os.CreateTemp("", "mox-import")
282 http.Error(w, "500 - internal server error - "+err.Error(), http.StatusInternalServerError)
287 store.CloseRemoveTempFile(log, tmpf, "upload")
290 if _, err := io.Copy(tmpf, f); err != nil {
291 log.Errorx("copying import to temporary file", err)
292 http.Error(w, "500 - internal server error - "+err.Error(), http.StatusInternalServerError)
295 token, isUserError, err := importStart(log, accName, tmpf, skipMailboxPrefix)
297 log.Errorx("starting import", err, slog.Bool("usererror", isUserError))
299 http.Error(w, "400 - bad request - "+err.Error(), http.StatusBadRequest)
301 http.Error(w, "500 - internal server error - "+err.Error(), http.StatusInternalServerError)
305 tmpf = nil // importStart is now responsible for cleanup.
307 w.Header().Set("Content-Type", "application/json")
308 _ = json.NewEncoder(w).Encode(ImportProgress{Token: token})
315// ImportProgress is returned after uploading a file to import.
316type ImportProgress struct {
317 // For fetching progress, or cancelling an import.
323var requestInfoCtxKey ctxKey = "requestInfo"
325type requestInfo struct {
328 SessionToken store.SessionToken
329 Response http.ResponseWriter
330 Request *http.Request // For Proto and TLS connection state during message submit.
333// LoginPrep returns a login token, and also sets it as cookie. Both must be
334// present in the call to Login.
335func (w Account) LoginPrep(ctx context.Context) string {
336 log := pkglog.WithContext(ctx)
337 reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
340 _, err := cryptorand.Read(data[:])
341 xcheckf(ctx, err, "generate token")
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 for dn, d := range conf.Destinations {
516 nd[destName] = newDest
517 conf.Destinations = nd
519 xcheckf(ctx, err, "saving destination")
522// ImportAbort aborts an import that is in progress. If the import exists and isn't
523// finished, no changes will have been made by the import.
524func (Account) ImportAbort(ctx context.Context, importToken string) error {
525 req := importAbortRequest{importToken, make(chan error)}
526 importers.Abort <- req
527 return <-req.Response
530// Types exposes types not used in API method signatures, such as the import form upload.
531func (Account) Types() (importProgress ImportProgress) {
535// SuppressionList lists the addresses on the suppression list of this account.
536func (Account) SuppressionList(ctx context.Context) (suppressions []webapi.Suppression) {
537 reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
538 l, err := queue.SuppressionList(ctx, reqInfo.AccountName)
539 xcheckf(ctx, err, "list suppressions")
543// SuppressionAdd adds an email address to the suppression list.
544func (Account) SuppressionAdd(ctx context.Context, address string, manual bool, reason string) (suppression webapi.Suppression) {
545 reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
546 addr, err := smtp.ParseAddress(address)
547 xcheckuserf(ctx, err, "parsing address")
548 sup := webapi.Suppression{
549 Account: reqInfo.AccountName,
553 err = queue.SuppressionAdd(ctx, addr.Path(), &sup)
554 if err != nil && errors.Is(err, bstore.ErrUnique) {
555 xcheckuserf(ctx, err, "add suppression")
557 xcheckf(ctx, err, "add suppression")
561// SuppressionRemove removes the email address from the suppression list.
562func (Account) SuppressionRemove(ctx context.Context, address string) {
563 reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
564 addr, err := smtp.ParseAddress(address)
565 xcheckuserf(ctx, err, "parsing address")
566 err = queue.SuppressionRemove(ctx, reqInfo.AccountName, addr.Path())
567 if err != nil && err == bstore.ErrAbsent {
568 xcheckuserf(ctx, err, "remove suppression")
570 xcheckf(ctx, err, "remove suppression")
573// OutgoingWebhookSave saves a new webhook url for outgoing deliveries. If url
574// is empty, the webhook is disabled. If authorization is non-empty it is used for
575// the Authorization header in HTTP requests. Events specifies the outgoing events
576// to be delivered, or all if empty/nil.
577func (Account) OutgoingWebhookSave(ctx context.Context, url, authorization string, events []string) {
578 reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
579 err := admin.AccountSave(ctx, reqInfo.AccountName, func(acc *config.Account) {
581 acc.OutgoingWebhook = nil
583 acc.OutgoingWebhook = &config.OutgoingWebhook{URL: url, Authorization: authorization, Events: events}
586 xcheckf(ctx, err, "saving account outgoing webhook")
589// OutgoingWebhookTest makes a test webhook call to urlStr, with optional
590// authorization. If the HTTP request is made this call will succeed also for
591// non-2xx HTTP status codes.
592func (Account) OutgoingWebhookTest(ctx context.Context, urlStr, authorization string, data webhook.Outgoing) (code int, response string, errmsg string) {
593 log := pkglog.WithContext(ctx)
595 xvalidURL(ctx, urlStr)
596 log.Debug("making webhook test call for outgoing message", slog.String("url", urlStr))
599 enc := json.NewEncoder(&b)
600 enc.SetIndent("", "\t")
601 enc.SetEscapeHTML(false)
602 err := enc.Encode(data)
603 xcheckf(ctx, err, "encoding outgoing webhook data")
605 code, response, err = queue.HookPost(ctx, log, 1, 1, urlStr, authorization, b.String())
609 log.Debugx("result for webhook test call for outgoing message", err, slog.Int("code", code), slog.String("response", response))
610 return code, response, errmsg
613// IncomingWebhookSave saves a new webhook url for incoming deliveries. If url is
614// empty, the webhook is disabled. If authorization is not empty, it is used in
615// the Authorization header in requests.
616func (Account) IncomingWebhookSave(ctx context.Context, url, authorization string) {
617 reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
618 err := admin.AccountSave(ctx, reqInfo.AccountName, func(acc *config.Account) {
620 acc.IncomingWebhook = nil
622 acc.IncomingWebhook = &config.IncomingWebhook{URL: url, Authorization: authorization}
625 xcheckf(ctx, err, "saving account incoming webhook")
628func xvalidURL(ctx context.Context, s string) {
629 u, err := url.Parse(s)
630 xcheckuserf(ctx, err, "parsing url")
631 if u.Scheme != "http" && u.Scheme != "https" {
632 xcheckuserf(ctx, errors.New("scheme must be http or https"), "parsing url")
636// IncomingWebhookTest makes a test webhook HTTP delivery request to urlStr,
637// with optional authorization header. If the HTTP call is made, this function
638// returns non-error regardless of HTTP status code.
639func (Account) IncomingWebhookTest(ctx context.Context, urlStr, authorization string, data webhook.Incoming) (code int, response string, errmsg string) {
640 log := pkglog.WithContext(ctx)
642 xvalidURL(ctx, urlStr)
643 log.Debug("making webhook test call for incoming message", slog.String("url", urlStr))
646 enc := json.NewEncoder(&b)
647 enc.SetEscapeHTML(false)
648 enc.SetIndent("", "\t")
649 err := enc.Encode(data)
650 xcheckf(ctx, err, "encoding incoming webhook data")
651 code, response, err = queue.HookPost(ctx, log, 1, 1, urlStr, authorization, b.String())
655 log.Debugx("result for webhook test call for incoming message", err, slog.Int("code", code), slog.String("response", response))
656 return code, response, errmsg
659// FromIDLoginAddressesSave saves new login addresses to enable unique SMTP
660// MAIL FROM addresses ("fromid") for deliveries from the queue.
661func (Account) FromIDLoginAddressesSave(ctx context.Context, loginAddresses []string) {
662 reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
663 err := admin.AccountSave(ctx, reqInfo.AccountName, func(acc *config.Account) {
664 acc.FromIDLoginAddresses = loginAddresses
666 xcheckf(ctx, err, "saving account fromid login addresses")
669// KeepRetiredPeriodsSave saves periods to save retired messages and webhooks.
670func (Account) KeepRetiredPeriodsSave(ctx context.Context, keepRetiredMessagePeriod, keepRetiredWebhookPeriod time.Duration) {
671 reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
672 err := admin.AccountSave(ctx, reqInfo.AccountName, func(acc *config.Account) {
673 acc.KeepRetiredMessagePeriod = keepRetiredMessagePeriod
674 acc.KeepRetiredWebhookPeriod = keepRetiredWebhookPeriod
676 xcheckf(ctx, err, "saving account keep retired periods")
679// AutomaticJunkFlagsSave saves settings for automatically marking messages as
680// junk/nonjunk when moved to mailboxes matching certain regular expressions.
681func (Account) AutomaticJunkFlagsSave(ctx context.Context, enabled bool, junkRegexp, neutralRegexp, notJunkRegexp string) {
682 reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
683 err := admin.AccountSave(ctx, reqInfo.AccountName, func(acc *config.Account) {
684 acc.AutomaticJunkFlags = config.AutomaticJunkFlags{
686 JunkMailboxRegexp: junkRegexp,
687 NeutralMailboxRegexp: neutralRegexp,
688 NotJunkMailboxRegexp: notJunkRegexp,
691 xcheckf(ctx, err, "saving account automatic junk flags")
694// JunkFilterSave saves junk filter settings. If junkFilter is nil, the junk filter
695// is disabled. Otherwise all fields except Threegrams are stored.
696func (Account) JunkFilterSave(ctx context.Context, junkFilter *config.JunkFilter) {
697 reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
698 err := admin.AccountSave(ctx, reqInfo.AccountName, func(acc *config.Account) {
699 if junkFilter == nil {
703 old := acc.JunkFilter
704 acc.JunkFilter = junkFilter
705 acc.JunkFilter.Params.Threegrams = false
707 acc.JunkFilter.Params.Threegrams = old.Params.Threegrams
710 xcheckf(ctx, err, "saving account junk filter settings")
713// RejectsSave saves the RejectsMailbox and KeepRejects settings.
714func (Account) RejectsSave(ctx context.Context, mailbox string, keep bool) {
715 reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
716 err := admin.AccountSave(ctx, reqInfo.AccountName, func(acc *config.Account) {
717 acc.RejectsMailbox = mailbox
718 acc.KeepRejects = keep
720 xcheckf(ctx, err, "saving account rejects settings")
723func (Account) TLSPublicKeys(ctx context.Context) ([]store.TLSPublicKey, error) {
724 reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
725 return store.TLSPublicKeyList(ctx, reqInfo.AccountName)
728func (Account) TLSPublicKeyAdd(ctx context.Context, loginAddress, name string, noIMAPPreauth bool, certPEM string) (store.TLSPublicKey, error) {
729 reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
731 block, rest := pem.Decode([]byte(certPEM))
734 err = errors.New("no pem data found")
735 } else if block.Type != "CERTIFICATE" {
736 err = fmt.Errorf("unexpected type %q, need CERTIFICATE", block.Type)
737 } else if len(rest) != 0 {
738 err = errors.New("only single pem block allowed")
740 xcheckuserf(ctx, err, "parsing pem file")
742 tpk, err := store.ParseTLSPublicKeyCert(block.Bytes)
743 xcheckuserf(ctx, err, "parsing certificate")
747 tpk.Account = reqInfo.AccountName
748 tpk.LoginAddress = loginAddress
749 tpk.NoIMAPPreauth = noIMAPPreauth
750 err = store.TLSPublicKeyAdd(ctx, &tpk)
751 if err != nil && errors.Is(err, bstore.ErrUnique) {
752 xcheckuserf(ctx, err, "add tls public key")
754 xcheckf(ctx, err, "add tls public key")
759func xtlspublickey(ctx context.Context, account string, fingerprint string) store.TLSPublicKey {
760 tpk, err := store.TLSPublicKeyGet(ctx, fingerprint)
761 if err == nil && tpk.Account != account {
762 err = bstore.ErrAbsent
764 if err == bstore.ErrAbsent {
765 xcheckuserf(ctx, err, "get tls public key")
767 xcheckf(ctx, err, "get tls public key")
771func (Account) TLSPublicKeyRemove(ctx context.Context, fingerprint string) error {
772 reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
773 xtlspublickey(ctx, reqInfo.AccountName, fingerprint)
774 return store.TLSPublicKeyRemove(ctx, fingerprint)
777func (Account) TLSPublicKeyUpdate(ctx context.Context, pubKey store.TLSPublicKey) error {
778 reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
779 tpk := xtlspublickey(ctx, reqInfo.AccountName, pubKey.Fingerprint)
780 log := pkglog.WithContext(ctx)
781 acc, _, _, err := store.OpenEmail(log, pubKey.LoginAddress, false)
782 if err == nil && acc.Name != reqInfo.AccountName {
783 err = store.ErrUnknownCredentials
787 log.Check(xerr, "close account")
789 if err == store.ErrUnknownCredentials {
790 xcheckuserf(ctx, errors.New("unknown address"), "looking up address")
792 tpk.Name = pubKey.Name
793 tpk.LoginAddress = pubKey.LoginAddress
794 tpk.NoIMAPPreauth = pubKey.NoIMAPPreauth
795 err = store.TLSPublicKeyUpdate(ctx, &tpk)
796 xcheckf(ctx, err, "updating tls public key")
800func (Account) LoginAttempts(ctx context.Context, limit int) []store.LoginAttempt {
801 reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
802 l, err := store.LoginAttemptList(ctx, reqInfo.AccountName, limit)
803 xcheckf(ctx, err, "listing login attempts")