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"
25 "github.com/mjl-/bstore"
26 "github.com/mjl-/sherpa"
27 "github.com/mjl-/sherpadoc"
28 "github.com/mjl-/sherpaprom"
30 "github.com/mjl-/mox/admin"
31 "github.com/mjl-/mox/config"
32 "github.com/mjl-/mox/mlog"
33 "github.com/mjl-/mox/mox-"
34 "github.com/mjl-/mox/moxvar"
35 "github.com/mjl-/mox/queue"
36 "github.com/mjl-/mox/smtp"
37 "github.com/mjl-/mox/store"
38 "github.com/mjl-/mox/webapi"
39 "github.com/mjl-/mox/webauth"
40 "github.com/mjl-/mox/webhook"
41 "github.com/mjl-/mox/webops"
44var pkglog = mlog.New("webaccount", nil)
47var accountapiJSON []byte
49//go:embed account.html
55var webaccountFile = &mox.WebappFile{
58 HTMLPath: filepath.FromSlash("webaccount/account.html"),
59 JSPath: filepath.FromSlash("webaccount/account.js"),
60 CustomStem: "webaccount",
63var accountDoc = mustParseAPI("account", accountapiJSON)
65func mustParseAPI(api string, buf []byte) (doc sherpadoc.Section) {
66 err := json.Unmarshal(buf, &doc)
68 pkglog.Fatalx("parsing webaccount api docs", err, slog.String("api", api))
73var sherpaHandlerOpts *sherpa.HandlerOpts
75func makeSherpaHandler(cookiePath string, isForwarded bool) (http.Handler, error) {
76 return sherpa.NewHandler("/api/", moxvar.Version, Account{cookiePath, isForwarded}, &accountDoc, sherpaHandlerOpts)
80 collector, err := sherpaprom.NewCollector("moxaccount", nil)
82 pkglog.Fatalx("creating sherpa prometheus collector", err)
85 sherpaHandlerOpts = &sherpa.HandlerOpts{Collector: collector, AdjustFunctionNames: "none", NoCORS: true}
87 _, err = makeSherpaHandler("", false)
89 pkglog.Fatalx("sherpa handler", err)
92 mox.NewWebaccountHandler = func(basePath string, isForwarded bool) http.Handler {
93 return http.HandlerFunc(Handler(basePath, isForwarded))
97// Handler returns a handler for the webaccount endpoints, customized for the
99func Handler(cookiePath string, isForwarded bool) func(w http.ResponseWriter, r *http.Request) {
100 sh, err := makeSherpaHandler(cookiePath, isForwarded)
101 return func(w http.ResponseWriter, r *http.Request) {
103 http.Error(w, "500 - internal server error - cannot handle requests", http.StatusInternalServerError)
106 handle(sh, isForwarded, w, r)
110func xcheckf(ctx context.Context, err error, format string, args ...any) {
114 // If caller tried saving a config that is invalid, or because of a bad request, cause a user error.
115 if errors.Is(err, mox.ErrConfig) || errors.Is(err, admin.ErrRequest) {
116 xcheckuserf(ctx, err, format, args...)
119 msg := fmt.Sprintf(format, args...)
120 errmsg := fmt.Sprintf("%s: %s", msg, err)
121 pkglog.WithContext(ctx).Errorx(msg, err)
122 code := "server:error"
123 if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
126 panic(&sherpa.Error{Code: code, Message: errmsg})
129func xcheckuserf(ctx context.Context, err error, format string, args ...any) {
133 msg := fmt.Sprintf(format, args...)
134 errmsg := fmt.Sprintf("%s: %s", msg, err)
135 pkglog.WithContext(ctx).Errorx(msg, err)
136 panic(&sherpa.Error{Code: "user:error", Message: errmsg})
139// Account exports web API functions for the account web interface. All its
140// methods are exported under api/. Function calls require valid HTTP
141// Authentication credentials of a user.
143 cookiePath string // From listener, for setting authentication cookies.
144 isForwarded bool // From listener, whether we look at X-Forwarded-* headers.
147func handle(apiHandler http.Handler, isForwarded bool, w http.ResponseWriter, r *http.Request) {
148 ctx := context.WithValue(r.Context(), mlog.CidKey, mox.Cid())
149 log := pkglog.WithContext(ctx).With(slog.String("userauth", ""))
151 // Without authentication. The token is unguessable.
152 if r.URL.Path == "/importprogress" {
153 if r.Method != "GET" {
154 http.Error(w, "405 - method not allowed - get required", http.StatusMethodNotAllowed)
159 token := q.Get("token")
161 http.Error(w, "400 - bad request - missing token", http.StatusBadRequest)
165 flusher, ok := w.(http.Flusher)
167 log.Error("internal error: ResponseWriter not a http.Flusher")
168 http.Error(w, "500 - internal error - cannot access underlying connection", 500)
172 l := importListener{token, make(chan importEvent, 100), make(chan bool, 1)}
173 importers.Register <- &l
176 http.Error(w, "400 - bad request - unknown token, import may have finished more than a minute ago", http.StatusBadRequest)
180 importers.Unregister <- &l
184 h.Set("Content-Type", "text/event-stream")
185 h.Set("Cache-Control", "no-cache")
186 _, err := w.Write([]byte(": keepalive\n\n"))
195 case e := <-l.Events:
196 _, err := w.Write(e.SSEMsg)
208 // HTML/JS can be retrieved without authentication.
209 if r.URL.Path == "/" {
212 webaccountFile.Serve(ctx, log, w, r)
214 http.Error(w, "405 - method not allowed - use get", http.StatusMethodNotAllowed)
217 } else if r.URL.Path == "/licenses.txt" {
222 http.Error(w, "405 - method not allowed - use get", http.StatusMethodNotAllowed)
227 isAPI := strings.HasPrefix(r.URL.Path, "/api/")
228 // Only allow POST for calls, they will not work cross-domain without CORS.
229 if isAPI && r.URL.Path != "/api/" && r.Method != "POST" {
230 http.Error(w, "405 - method not allowed - use post", http.StatusMethodNotAllowed)
234 var loginAddress, accName string
235 var sessionToken store.SessionToken
236 // All other URLs, except the login endpoint require some authentication.
237 if r.URL.Path != "/api/LoginPrep" && r.URL.Path != "/api/Login" {
239 isExport := r.URL.Path == "/export"
240 requireCSRF := isAPI || r.URL.Path == "/import" || isExport
241 accName, sessionToken, loginAddress, ok = webauth.Check(ctx, log, webauth.Accounts, "webaccount", isForwarded, w, r, isAPI, requireCSRF, isExport)
243 // Response has been written already.
249 reqInfo := requestInfo{loginAddress, accName, sessionToken, w, r}
250 ctx = context.WithValue(ctx, requestInfoCtxKey, reqInfo)
251 apiHandler.ServeHTTP(w, r.WithContext(ctx))
257 webops.Export(log, accName, w, r)
260 if r.Method != "POST" {
261 http.Error(w, "405 - method not allowed - post required", http.StatusMethodNotAllowed)
265 f, _, err := r.FormFile("file")
267 if errors.Is(err, http.ErrMissingFile) {
268 http.Error(w, "400 - bad request - missing file", http.StatusBadRequest)
270 http.Error(w, "500 - internal server error - "+err.Error(), http.StatusInternalServerError)
276 log.Check(err, "closing form file")
278 skipMailboxPrefix := r.FormValue("skipMailboxPrefix")
279 tmpf, err := os.CreateTemp("", "mox-import")
281 http.Error(w, "500 - internal server error - "+err.Error(), http.StatusInternalServerError)
286 store.CloseRemoveTempFile(log, tmpf, "upload")
289 if _, err := io.Copy(tmpf, f); err != nil {
290 log.Errorx("copying import to temporary file", err)
291 http.Error(w, "500 - internal server error - "+err.Error(), http.StatusInternalServerError)
294 token, isUserError, err := importStart(log, accName, tmpf, skipMailboxPrefix)
296 log.Errorx("starting import", err, slog.Bool("usererror", isUserError))
298 http.Error(w, "400 - bad request - "+err.Error(), http.StatusBadRequest)
300 http.Error(w, "500 - internal server error - "+err.Error(), http.StatusInternalServerError)
304 tmpf = nil // importStart is now responsible for cleanup.
306 w.Header().Set("Content-Type", "application/json")
307 _ = json.NewEncoder(w).Encode(ImportProgress{Token: token})
314// ImportProgress is returned after uploading a file to import.
315type ImportProgress struct {
316 // For fetching progress, or cancelling an import.
322var requestInfoCtxKey ctxKey = "requestInfo"
324type requestInfo struct {
327 SessionToken store.SessionToken
328 Response http.ResponseWriter
329 Request *http.Request // For Proto and TLS connection state during message submit.
332// LoginPrep returns a login token, and also sets it as cookie. Both must be
333// present in the call to Login.
334func (w Account) LoginPrep(ctx context.Context) string {
335 log := pkglog.WithContext(ctx)
336 reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
339 _, err := cryptorand.Read(data[:])
340 xcheckf(ctx, err, "generate token")
341 loginToken := base64.RawURLEncoding.EncodeToString(data[:])
343 webauth.LoginPrep(ctx, log, "webaccount", w.cookiePath, w.isForwarded, reqInfo.Response, reqInfo.Request, loginToken)
348// Login returns a session token for the credentials, or fails with error code
349// "user:badLogin". Call LoginPrep to get a loginToken.
350func (w Account) Login(ctx context.Context, loginToken, username, password string) store.CSRFToken {
351 log := pkglog.WithContext(ctx)
352 reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
354 csrfToken, err := webauth.Login(ctx, log, webauth.Accounts, "webaccount", w.cookiePath, w.isForwarded, reqInfo.Response, reqInfo.Request, loginToken, username, password)
355 if _, ok := err.(*sherpa.Error); ok {
358 xcheckf(ctx, err, "login")
362// Logout invalidates the session token.
363func (w Account) Logout(ctx context.Context) {
364 log := pkglog.WithContext(ctx)
365 reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
367 err := webauth.Logout(ctx, log, webauth.Accounts, "webaccount", w.cookiePath, w.isForwarded, reqInfo.Response, reqInfo.Request, reqInfo.AccountName, reqInfo.SessionToken)
368 xcheckf(ctx, err, "logout")
371// SetPassword saves a new password for the account, invalidating the previous password.
372// Sessions are not interrupted, and will keep working. New login attempts must use the new password.
373// Password must be at least 8 characters.
374func (Account) SetPassword(ctx context.Context, password string) {
375 log := pkglog.WithContext(ctx)
376 if len(password) < 8 {
377 panic(&sherpa.Error{Code: "user:error", Message: "password must be at least 8 characters"})
380 reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
381 acc, err := store.OpenAccount(log, reqInfo.AccountName)
382 xcheckf(ctx, err, "open account")
385 log.Check(err, "closing account")
388 // Retrieve session, resetting password invalidates it.
389 ls, err := store.SessionUse(ctx, log, reqInfo.AccountName, reqInfo.SessionToken, "")
390 xcheckf(ctx, err, "get session")
392 err = acc.SetPassword(log, password)
393 xcheckf(ctx, err, "setting password")
395 // Session has been invalidated. Add it again.
396 err = store.SessionAddToken(ctx, log, &ls)
397 xcheckf(ctx, err, "restoring session after password reset")
400// Account returns information about the account.
401// StorageUsed is the sum of the sizes of all messages, in bytes.
402// StorageLimit is the maximum storage that can be used, or 0 if there is no limit.
403func (Account) Account(ctx context.Context) (account config.Account, storageUsed, storageLimit int64, suppressions []webapi.Suppression) {
404 log := pkglog.WithContext(ctx)
405 reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
407 acc, err := store.OpenAccount(log, reqInfo.AccountName)
408 xcheckf(ctx, err, "open account")
411 log.Check(err, "closing account")
414 var accConf config.Account
415 acc.WithRLock(func() {
416 accConf, _ = acc.Conf()
418 storageLimit = acc.QuotaMessageSize()
419 err := acc.DB.Read(ctx, func(tx *bstore.Tx) error {
420 du := store.DiskUsage{ID: 1}
422 storageUsed = du.MessageSize
425 xcheckf(ctx, err, "get disk usage")
428 suppressions, err = queue.SuppressionList(ctx, reqInfo.AccountName)
429 xcheckf(ctx, err, "list suppressions")
431 return accConf, storageUsed, storageLimit, suppressions
434// AccountSaveFullName saves the full name (used as display name in email messages)
436func (Account) AccountSaveFullName(ctx context.Context, fullName string) {
437 reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
438 err := admin.AccountSave(ctx, reqInfo.AccountName, func(acc *config.Account) {
439 acc.FullName = fullName
441 xcheckf(ctx, err, "saving account full name")
444// DestinationSave updates a destination.
445// OldDest is compared against the current destination. If it does not match, an
446// error is returned. Otherwise newDest is saved and the configuration reloaded.
447func (Account) DestinationSave(ctx context.Context, destName string, oldDest, newDest config.Destination) {
448 reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
450 err := admin.AccountSave(ctx, reqInfo.AccountName, func(conf *config.Account) {
451 curDest, ok := conf.Destinations[destName]
453 xcheckuserf(ctx, errors.New("not found"), "looking up destination")
455 if !curDest.Equal(oldDest) {
456 xcheckuserf(ctx, errors.New("modified"), "checking stored destination")
459 // Keep fields we manage.
460 newDest.DMARCReports = curDest.DMARCReports
461 newDest.HostTLSReports = curDest.HostTLSReports
462 newDest.DomainTLSReports = curDest.DomainTLSReports
464 // Make copy of reference values.
465 nd := map[string]config.Destination{}
466 for dn, d := range conf.Destinations {
469 nd[destName] = newDest
470 conf.Destinations = nd
472 xcheckf(ctx, err, "saving destination")
475// ImportAbort aborts an import that is in progress. If the import exists and isn't
476// finished, no changes will have been made by the import.
477func (Account) ImportAbort(ctx context.Context, importToken string) error {
478 req := importAbortRequest{importToken, make(chan error)}
479 importers.Abort <- req
480 return <-req.Response
483// Types exposes types not used in API method signatures, such as the import form upload.
484func (Account) Types() (importProgress ImportProgress) {
488// SuppressionList lists the addresses on the suppression list of this account.
489func (Account) SuppressionList(ctx context.Context) (suppressions []webapi.Suppression) {
490 reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
491 l, err := queue.SuppressionList(ctx, reqInfo.AccountName)
492 xcheckf(ctx, err, "list suppressions")
496// SuppressionAdd adds an email address to the suppression list.
497func (Account) SuppressionAdd(ctx context.Context, address string, manual bool, reason string) (suppression webapi.Suppression) {
498 reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
499 addr, err := smtp.ParseAddress(address)
500 xcheckuserf(ctx, err, "parsing address")
501 sup := webapi.Suppression{
502 Account: reqInfo.AccountName,
506 err = queue.SuppressionAdd(ctx, addr.Path(), &sup)
507 if err != nil && errors.Is(err, bstore.ErrUnique) {
508 xcheckuserf(ctx, err, "add suppression")
510 xcheckf(ctx, err, "add suppression")
514// SuppressionRemove removes the email address from the suppression list.
515func (Account) SuppressionRemove(ctx context.Context, address string) {
516 reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
517 addr, err := smtp.ParseAddress(address)
518 xcheckuserf(ctx, err, "parsing address")
519 err = queue.SuppressionRemove(ctx, reqInfo.AccountName, addr.Path())
520 if err != nil && err == bstore.ErrAbsent {
521 xcheckuserf(ctx, err, "remove suppression")
523 xcheckf(ctx, err, "remove suppression")
526// OutgoingWebhookSave saves a new webhook url for outgoing deliveries. If url
527// is empty, the webhook is disabled. If authorization is non-empty it is used for
528// the Authorization header in HTTP requests. Events specifies the outgoing events
529// to be delivered, or all if empty/nil.
530func (Account) OutgoingWebhookSave(ctx context.Context, url, authorization string, events []string) {
531 reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
532 err := admin.AccountSave(ctx, reqInfo.AccountName, func(acc *config.Account) {
534 acc.OutgoingWebhook = nil
536 acc.OutgoingWebhook = &config.OutgoingWebhook{URL: url, Authorization: authorization, Events: events}
539 xcheckf(ctx, err, "saving account outgoing webhook")
542// OutgoingWebhookTest makes a test webhook call to urlStr, with optional
543// authorization. If the HTTP request is made this call will succeed also for
544// non-2xx HTTP status codes.
545func (Account) OutgoingWebhookTest(ctx context.Context, urlStr, authorization string, data webhook.Outgoing) (code int, response string, errmsg string) {
546 log := pkglog.WithContext(ctx)
548 xvalidURL(ctx, urlStr)
549 log.Debug("making webhook test call for outgoing message", slog.String("url", urlStr))
552 enc := json.NewEncoder(&b)
553 enc.SetIndent("", "\t")
554 enc.SetEscapeHTML(false)
555 err := enc.Encode(data)
556 xcheckf(ctx, err, "encoding outgoing webhook data")
558 code, response, err = queue.HookPost(ctx, log, 1, 1, urlStr, authorization, b.String())
562 log.Debugx("result for webhook test call for outgoing message", err, slog.Int("code", code), slog.String("response", response))
563 return code, response, errmsg
566// IncomingWebhookSave saves a new webhook url for incoming deliveries. If url is
567// empty, the webhook is disabled. If authorization is not empty, it is used in
568// the Authorization header in requests.
569func (Account) IncomingWebhookSave(ctx context.Context, url, authorization string) {
570 reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
571 err := admin.AccountSave(ctx, reqInfo.AccountName, func(acc *config.Account) {
573 acc.IncomingWebhook = nil
575 acc.IncomingWebhook = &config.IncomingWebhook{URL: url, Authorization: authorization}
578 xcheckf(ctx, err, "saving account incoming webhook")
581func xvalidURL(ctx context.Context, s string) {
582 u, err := url.Parse(s)
583 xcheckuserf(ctx, err, "parsing url")
584 if u.Scheme != "http" && u.Scheme != "https" {
585 xcheckuserf(ctx, errors.New("scheme must be http or https"), "parsing url")
589// IncomingWebhookTest makes a test webhook HTTP delivery request to urlStr,
590// with optional authorization header. If the HTTP call is made, this function
591// returns non-error regardless of HTTP status code.
592func (Account) IncomingWebhookTest(ctx context.Context, urlStr, authorization string, data webhook.Incoming) (code int, response string, errmsg string) {
593 log := pkglog.WithContext(ctx)
595 xvalidURL(ctx, urlStr)
596 log.Debug("making webhook test call for incoming message", slog.String("url", urlStr))
599 enc := json.NewEncoder(&b)
600 enc.SetEscapeHTML(false)
601 enc.SetIndent("", "\t")
602 err := enc.Encode(data)
603 xcheckf(ctx, err, "encoding incoming webhook data")
604 code, response, err = queue.HookPost(ctx, log, 1, 1, urlStr, authorization, b.String())
608 log.Debugx("result for webhook test call for incoming message", err, slog.Int("code", code), slog.String("response", response))
609 return code, response, errmsg
612// FromIDLoginAddressesSave saves new login addresses to enable unique SMTP
613// MAIL FROM addresses ("fromid") for deliveries from the queue.
614func (Account) FromIDLoginAddressesSave(ctx context.Context, loginAddresses []string) {
615 reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
616 err := admin.AccountSave(ctx, reqInfo.AccountName, func(acc *config.Account) {
617 acc.FromIDLoginAddresses = loginAddresses
619 xcheckf(ctx, err, "saving account fromid login addresses")
622// KeepRetiredPeriodsSave saves periods to save retired messages and webhooks.
623func (Account) KeepRetiredPeriodsSave(ctx context.Context, keepRetiredMessagePeriod, keepRetiredWebhookPeriod time.Duration) {
624 reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
625 err := admin.AccountSave(ctx, reqInfo.AccountName, func(acc *config.Account) {
626 acc.KeepRetiredMessagePeriod = keepRetiredMessagePeriod
627 acc.KeepRetiredWebhookPeriod = keepRetiredWebhookPeriod
629 xcheckf(ctx, err, "saving account keep retired periods")
632// AutomaticJunkFlagsSave saves settings for automatically marking messages as
633// junk/nonjunk when moved to mailboxes matching certain regular expressions.
634func (Account) AutomaticJunkFlagsSave(ctx context.Context, enabled bool, junkRegexp, neutralRegexp, notJunkRegexp string) {
635 reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
636 err := admin.AccountSave(ctx, reqInfo.AccountName, func(acc *config.Account) {
637 acc.AutomaticJunkFlags = config.AutomaticJunkFlags{
639 JunkMailboxRegexp: junkRegexp,
640 NeutralMailboxRegexp: neutralRegexp,
641 NotJunkMailboxRegexp: notJunkRegexp,
644 xcheckf(ctx, err, "saving account automatic junk flags")
647// JunkFilterSave saves junk filter settings. If junkFilter is nil, the junk filter
648// is disabled. Otherwise all fields except Threegrams are stored.
649func (Account) JunkFilterSave(ctx context.Context, junkFilter *config.JunkFilter) {
650 reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
651 err := admin.AccountSave(ctx, reqInfo.AccountName, func(acc *config.Account) {
652 if junkFilter == nil {
656 old := acc.JunkFilter
657 acc.JunkFilter = junkFilter
658 acc.JunkFilter.Params.Threegrams = false
660 acc.JunkFilter.Params.Threegrams = old.Params.Threegrams
663 xcheckf(ctx, err, "saving account junk filter settings")
666// RejectsSave saves the RejectsMailbox and KeepRejects settings.
667func (Account) RejectsSave(ctx context.Context, mailbox string, keep bool) {
668 reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
669 err := admin.AccountSave(ctx, reqInfo.AccountName, func(acc *config.Account) {
670 acc.RejectsMailbox = mailbox
671 acc.KeepRejects = keep
673 xcheckf(ctx, err, "saving account rejects settings")
676func (Account) TLSPublicKeys(ctx context.Context) ([]store.TLSPublicKey, error) {
677 reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
678 return store.TLSPublicKeyList(ctx, reqInfo.AccountName)
681func (Account) TLSPublicKeyAdd(ctx context.Context, loginAddress, name string, noIMAPPreauth bool, certPEM string) (store.TLSPublicKey, error) {
682 reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
684 block, rest := pem.Decode([]byte(certPEM))
687 err = errors.New("no pem data found")
688 } else if block.Type != "CERTIFICATE" {
689 err = fmt.Errorf("unexpected type %q, need CERTIFICATE", block.Type)
690 } else if len(rest) != 0 {
691 err = errors.New("only single pem block allowed")
693 xcheckuserf(ctx, err, "parsing pem file")
695 tpk, err := store.ParseTLSPublicKeyCert(block.Bytes)
696 xcheckuserf(ctx, err, "parsing certificate")
700 tpk.Account = reqInfo.AccountName
701 tpk.LoginAddress = loginAddress
702 tpk.NoIMAPPreauth = noIMAPPreauth
703 err = store.TLSPublicKeyAdd(ctx, &tpk)
704 if err != nil && errors.Is(err, bstore.ErrUnique) {
705 xcheckuserf(ctx, err, "add tls public key")
707 xcheckf(ctx, err, "add tls public key")
712func xtlspublickey(ctx context.Context, account string, fingerprint string) store.TLSPublicKey {
713 tpk, err := store.TLSPublicKeyGet(ctx, fingerprint)
714 if err == nil && tpk.Account != account {
715 err = bstore.ErrAbsent
717 if err == bstore.ErrAbsent {
718 xcheckuserf(ctx, err, "get tls public key")
720 xcheckf(ctx, err, "get tls public key")
724func (Account) TLSPublicKeyRemove(ctx context.Context, fingerprint string) error {
725 reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
726 xtlspublickey(ctx, reqInfo.AccountName, fingerprint)
727 return store.TLSPublicKeyRemove(ctx, fingerprint)
730func (Account) TLSPublicKeyUpdate(ctx context.Context, pubKey store.TLSPublicKey) error {
731 reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
732 tpk := xtlspublickey(ctx, reqInfo.AccountName, pubKey.Fingerprint)
733 log := pkglog.WithContext(ctx)
734 acc, _, err := store.OpenEmail(log, pubKey.LoginAddress)
735 if err == nil && acc.Name != reqInfo.AccountName {
736 err = store.ErrUnknownCredentials
740 log.Check(xerr, "close account")
742 if err == store.ErrUnknownCredentials {
743 xcheckuserf(ctx, errors.New("unknown address"), "looking up address")
745 tpk.Name = pubKey.Name
746 tpk.LoginAddress = pubKey.LoginAddress
747 tpk.NoIMAPPreauth = pubKey.NoIMAPPreauth
748 err = store.TLSPublicKeyUpdate(ctx, &tpk)
749 xcheckf(ctx, err, "updating tls public key")