package mailfront import ( "bytes" "context" "encoding/json" "errors" "log/slog" "net" "net/http" "net/url" "strings" "time" "git.kilimanjaro.io/sovrn/internal/appview/ui" "git.kilimanjaro.io/sovrn/internal/authbroker" "git.kilimanjaro.io/sovrn/internal/iplimit" "git.kilimanjaro.io/sovrn/internal/site" "git.kilimanjaro.io/sovrn/internal/webmailhint" ) // Server is mailfront's HTTP surface. type Server struct { Cache *Cache Hints *webmailhint.Keys // Lookup reads a handle's or DID's public service record. Lookup func(ctx context.Context, identifier string) (*authbroker.ServiceRecord, error) // PublicHost is mailfront's own name (mail.sovrn.at). Customer front // doors are mail. CNAMEs to it (D38). PublicHost string // ExtraCellHosts allows cell names outside sovrn.at (dev/test). ExtraCellHosts []string // Limit rate-limits sign-ins per client IP. Limit *iplimit.Limiter // StaleAfter: /healthz fails when no poll has reached every cell for // this long. StaleAfter time.Duration // FallbackAsk is another service's on-demand TLS check that Caddy's one // global ask URL must also cover (vlpds's /tls-check for handle hosts on // a box running a PDS node). Names mailfront doesn't serve are asked // there. Empty: refused. FallbackAsk string // HTTP is the client for FallbackAsk. HTTP *http.Client } // Handler mounts the routes. /tls-ask and /healthz are for Caddy and // monitoring on loopback; the edge must not proxy them. func (s *Server) Handler() http.Handler { mux := http.NewServeMux() mux.HandleFunc("GET /{$}", s.form) mux.HandleFunc("POST /go", s.goPost) mux.HandleFunc("GET /go", s.goGet) mux.HandleFunc("GET /tls-ask", s.tlsAsk) mux.HandleFunc("GET /healthz", s.healthz) // The page's assets: the app's stylesheet, fonts and bundle, and the // landing site's plates and icons. mux.Handle("GET /static/", ui.StaticHandler()) mux.Handle("GET /assets/", ui.AssetsHandler()) if site, err := site.New(); err == nil { files := site.Files() for _, p := range []string{"GET /plates/", "GET /favicon.svg", "GET /favicon.png"} { mux.Handle(p, files) } } else { slog.Error("mailfront: landing build missing; pages render without plates and icons", "err", err) } return mux } // form is the one field: handle or email address. On a customer's // mail. front door it is prefilled with "@". func (s *Server) form(w http.ResponseWriter, r *http.Request) { prefill := "" if d, ok := s.customerDomain(r); ok { prefill = "@" + d } writePage(w, http.StatusOK, page{Kind: "form", Title: "Sign in to your mail", Identifier: prefill}) } // customerDomain returns when the request came in on // mail. for a hosted domain. func (s *Server) customerDomain(r *http.Request) (string, bool) { host := requestHost(r) if host == s.PublicHost { return "", false } d, ok := strings.CutPrefix(host, "mail.") if !ok { return "", false } if _, hosted, err := s.Cache.Cell(r.Context(), d); err != nil || !hosted { return "", false } return d, true } func (s *Server) goPost(w http.ResponseWriter, r *http.Request) { if s.Limit != nil && !s.Limit.Allow(r) { writePage(w, http.StatusTooManyRequests, page{Title: "Too many attempts", Body: "Please wait a minute and try again."}) return } id := webmailhint.NormalizeIdentifier(r.PostFormValue("identifier")) if id == "" || strings.HasPrefix(id, "@") { writePage(w, http.StatusOK, page{Kind: "form", Title: "Sign in to your mail", Identifier: id, Error: "Enter your handle or your full email address."}) return } s.route(w, r, id, 0) } // goGet takes a sign-in a cell sent back: the domain isn't (or is no longer) // hosted there, or its record named no cell. nothere evicts the stale entry. func (s *Server) goGet(w http.ResponseWriter, r *http.Request) { if s.Limit != nil && !s.Limit.Allow(r) { writePage(w, http.StatusTooManyRequests, page{Title: "Too many attempts", Body: "Please wait a minute and try again."}) return } h, err := s.Hints.Verify(r.URL.Query().Get("hint")) if err != nil { http.Redirect(w, r, "/", http.StatusSeeOther) return } id := webmailhint.NormalizeIdentifier(h.Identifier) if cell := r.URL.Query().Get("nothere"); cell != "" && webmailhint.IsEmail(id) { s.Cache.Evict(r.Context(), webmailhint.Domain(id), cell) } s.route(w, r, id, h.Hop) } // route sends identifier to its home cell's /webmail/start. func (s *Server) route(w http.ResponseWriter, r *http.Request, id string, hop int) { ctx := r.Context() if hop > webmailhint.MaxHops { slog.WarnContext(ctx, "mailfront: hop bound reached", "hop", hop) writePage(w, http.StatusOK, notFoundPage()) return } var cell string if webmailhint.IsEmail(id) { domain := webmailhint.Domain(id) c, ok, err := s.Cache.Lookup(ctx, domain) if err != nil { slog.ErrorContext(ctx, "mailfront: lookup", "err", err) writePage(w, http.StatusInternalServerError, page{Title: "Something went wrong", Body: "Please try again in a minute."}) return } if !ok { writePage(w, http.StatusOK, page{Kind: "form", Title: "Sign in to your mail", Identifier: id, Error: "sovrn doesn't host mail for " + domain + ". Check the address, or sign in with your handle."}) return } cell = c } else { rec, err := s.Lookup(ctx, id) switch { case errors.Is(err, authbroker.ErrNoServiceRecord): writePage(w, http.StatusOK, notFoundPage()) return case errors.Is(err, authbroker.ErrPDSUnavailable): writePage(w, http.StatusServiceUnavailable, page{Title: "Account info unavailable", Body: "We couldn't reach your account's server. Please try again in a minute.", Link: "/", LinkText: "Try again"}) return case errors.Is(err, authbroker.ErrMalformedRecord): slog.WarnContext(ctx, "mailfront: malformed service record", "identifier", id, "err", err) writePage(w, http.StatusInternalServerError, supportPage()) return case err != nil: writePage(w, http.StatusOK, page{Kind: "form", Title: "Sign in to your mail", Identifier: id, Error: "We couldn't find that account. Check the handle and try again."}) return } target, ok := authbroker.IsCellRedirectTarget(rec.Appview, s.PublicHost, s.ExtraCellHosts) if !ok { slog.WarnContext(ctx, "mailfront: service record names no cell", "identifier", id, "appview", rec.Appview) writePage(w, http.StatusInternalServerError, supportPage()) return } u, _ := url.Parse(target) cell = u.Host } hint, err := s.Hints.Sign(id, hop) if err != nil { slog.ErrorContext(ctx, "mailfront: sign hint", "err", err) writePage(w, http.StatusInternalServerError, page{Title: "Something went wrong", Body: "Please try again in a minute."}) return } http.Redirect(w, r, "https://"+cell+"/webmail/start?hint="+url.QueryEscape(hint), http.StatusSeeOther) } // tlsAsk answers Caddy's on-demand TLS check: certificates for mailfront's // own name and mail.; any other name is FallbackAsk's call. func (s *Server) tlsAsk(w http.ResponseWriter, r *http.Request) { name := strings.ToLower(strings.TrimSuffix(r.URL.Query().Get("domain"), ".")) if name == s.PublicHost { w.WriteHeader(http.StatusOK) return } if d, ok := strings.CutPrefix(name, "mail."); ok { if _, hosted, err := s.Cache.Cell(r.Context(), d); err == nil && hosted { w.WriteHeader(http.StatusOK) return } } if s.FallbackAsk != "" && name != "" { w.WriteHeader(s.askFallback(r.Context(), name)) return } http.NotFound(w, r) } // askFallback relays the question; anything but a clear 200 is a refusal. func (s *Server) askFallback(ctx context.Context, name string) int { client := s.HTTP if client == nil { client = &http.Client{Timeout: 5 * time.Second} } u := s.FallbackAsk + sepFor(s.FallbackAsk) + "domain=" + url.QueryEscape(name) req, err := http.NewRequestWithContext(ctx, http.MethodGet, u, nil) if err != nil { return http.StatusNotFound } resp, err := client.Do(req) if err != nil { slog.WarnContext(ctx, "mailfront: fallback ask", "err", err) return http.StatusServiceUnavailable } resp.Body.Close() if resp.StatusCode == http.StatusOK { return http.StatusOK } return http.StatusNotFound } func sepFor(u string) string { if strings.Contains(u, "?") { return "&" } return "?" } func (s *Server) healthz(w http.ResponseWriter, r *http.Request) { n, fresh, err := s.Cache.Status(r.Context()) status := http.StatusOK stale := s.StaleAfter > 0 && time.Since(fresh) > s.StaleAfter if err != nil || stale { status = http.StatusServiceUnavailable } w.Header().Set("Content-Type", "application/json") w.WriteHeader(status) out := map[string]any{"ok": status == http.StatusOK, "domains": n} if !fresh.IsZero() { out["allCellsAnsweredAt"] = fresh.UTC().Format(time.RFC3339) } _ = json.NewEncoder(w).Encode(out) } func requestHost(r *http.Request) string { host := r.Host if h, _, err := net.SplitHostPort(host); err == nil { host = h } return strings.ToLower(strings.TrimSuffix(host, ".")) } func notFoundPage() page { return page{Kind: "form", Title: "No sovrn mailbox found", Body: "We couldn't find a sovrn mailbox for that handle or address. Check it and try again, or ask your mail domain's admin."} } func supportPage() page { return page{Title: "Account record problem", Body: "Something is wrong with your account record. Please contact help@sovrn.at and mention this page.", Link: "mailto:help@sovrn.at", LinkText: "help@sovrn.at"} } type page struct { Kind string Title string Body string Error string Identifier string Link string LinkText string } // writePage renders the app's mail sign-in page (ui.MailSignIn); Handler // serves the stylesheet, fonts, script bundle and plates it loads. func writePage(w http.ResponseWriter, status int, p page) { up := ui.MailSignInPage{Title: p.Title, Body: p.Body, Error: p.Error, Link: p.Link, LinkText: p.LinkText} if p.Kind == "form" { up.Form = &ui.MailSignInForm{Action: "/go", Identifier: p.Identifier} } var buf bytes.Buffer if err := ui.MailSignIn(up).Render(context.Background(), &buf); err != nil { slog.Error("mailfront: render", "err", err) http.Error(w, p.Title, http.StatusInternalServerError) return } w.Header().Set("Content-Type", "text/html; charset=utf-8") w.Header().Set("Cache-Control", "no-store") w.Header().Set("X-Frame-Options", "DENY") w.Header().Set("Content-Security-Policy", "default-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; font-src 'self'; img-src 'self'; base-uri 'none'; frame-ancestors 'none'") w.WriteHeader(status) _, _ = buf.WriteTo(w) }