feat(mail-admin): read-only account view for mail.produktor.io (#74)
- admin/: Go stdlib-only HTTP viewer, lists accounts from config/postfix-accounts.cf with per-mailbox message counts (INBOX and total, same numbers doveadm reports) and storage; quota from dovecot-quotas.cf; Basic Auth from .env; offline tests vs fixtures (go test -race ./...) - compose: mail-admin service, build admin/Dockerfile, publishes 127.0.0.1:19945 / 172.17.0.1:19945; config and mail-data mounted :ro, no docker socket - NPM proxy host 66: location /admin/ -> 172.17.0.1:19945 - README: account admin section
This commit is contained in:
+228
@@ -0,0 +1,228 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"crypto/subtle"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"html/template"
|
||||
"io/fs"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// server is the read-only mail accounts viewer.
|
||||
type server struct {
|
||||
accountsPath string // config/postfix-accounts.cf
|
||||
quotaPath string // config/dovecot-quotas.cf
|
||||
maildirRoot string // data/mail-data
|
||||
basePath string // URL prefix when served behind NPM ("" = root)
|
||||
user, pass string // Basic Auth credentials
|
||||
}
|
||||
|
||||
// viewAccount is one row of the account table.
|
||||
type viewAccount struct {
|
||||
Email string `json:"email"`
|
||||
Messages int64 `json:"messages"` // INBOX messages
|
||||
Total int64 `json:"total"` // messages across all mailboxes
|
||||
Storage int64 `json:"storage"` // bytes across all mailboxes
|
||||
Quota string `json:"quota"` // limit from dovecot-quotas.cf, "" = none
|
||||
LastMessage time.Time `json:"last_message"` // newest message mtime
|
||||
}
|
||||
|
||||
type accountsResponse struct {
|
||||
Updated time.Time `json:"updated"`
|
||||
Accounts []viewAccount `json:"accounts"`
|
||||
}
|
||||
|
||||
var templateFuncs = template.FuncMap{
|
||||
"humanBytes": humanBytes,
|
||||
"formatTime": func(t time.Time) string { return t.UTC().Format("2006-01-02 15:04 MST") },
|
||||
}
|
||||
|
||||
var indexTmpl = template.Must(template.New("index").Funcs(templateFuncs).Parse(`<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>Mail admin — produktor.io</title>
|
||||
<style>
|
||||
:root { color-scheme: light dark; }
|
||||
body { font: 14px/1.5 system-ui, sans-serif; margin: 2rem auto; max-width: 56rem; padding: 0 1rem; }
|
||||
table { border-collapse: collapse; width: 100%; }
|
||||
th, td { text-align: left; padding: .45rem .6rem; border-bottom: 1px solid #4446; }
|
||||
th { border-bottom-width: 2px; }
|
||||
td.num { text-align: right; font-variant-numeric: tabular-nums; }
|
||||
a { color: #3b82f6; }
|
||||
.meta { color: #888; margin: .5rem 0 1.5rem; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<h1>Mail accounts — mail.produktor.io</h1>
|
||||
<p class="meta">Source: <code>config/postfix-accounts.cf</code> (read-only). Updated {{.Updated | formatTime}} · <a href="{{.Base}}api/accounts">JSON</a></p>
|
||||
<table>
|
||||
<thead><tr><th>Address</th><th class="num">INBOX</th><th class="num">Total</th><th class="num">Storage</th><th>Quota</th><th>Last message</th></tr></thead>
|
||||
<tbody>
|
||||
{{range .Accounts}}
|
||||
<tr><td>{{.Email}}</td><td class="num">{{.Messages}}</td><td class="num">{{.Total}}</td><td class="num">{{.Storage | humanBytes}}</td><td>{{if .Quota}}{{.Quota}}{{else}}—{{end}}</td><td>{{if .LastMessage.IsZero}}—{{else}}{{.LastMessage | formatTime}}{{end}}</td></tr>
|
||||
{{end}}
|
||||
</tbody>
|
||||
</table>
|
||||
<p class="meta">Read-only view. Mailbox contents are managed via docker-mailserver (doveadm / Roundcube login).</p>
|
||||
</body>
|
||||
</html>`))
|
||||
|
||||
func humanBytes(b int64) string {
|
||||
switch {
|
||||
case b >= 1<<30:
|
||||
return trimFrac(float64(b)/(1<<30)) + " GiB"
|
||||
case b >= 1<<20:
|
||||
return trimFrac(float64(b)/(1<<20)) + " MiB"
|
||||
case b >= 1<<10:
|
||||
return trimFrac(float64(b)/(1<<10)) + " KiB"
|
||||
default:
|
||||
return trimFrac(float64(b)) + " B"
|
||||
}
|
||||
}
|
||||
|
||||
func trimFrac(f float64) string {
|
||||
s := strings.TrimRight(strings.TrimRight(strconv.FormatFloat(f, 'f', 1, 64), "0"), ".")
|
||||
if s == "-0" || s == "" {
|
||||
return "0"
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
func (s *server) handler() http.Handler {
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("/", s.route)
|
||||
return s.basicAuth(mux)
|
||||
}
|
||||
|
||||
// route strips the configured basePath prefix (NPM location /admin/) and
|
||||
// dispatches to the page or the JSON API. Direct access without the prefix
|
||||
// is redirected there.
|
||||
func (s *server) route(w http.ResponseWriter, r *http.Request) {
|
||||
path := r.URL.Path
|
||||
if s.basePath != "" {
|
||||
switch {
|
||||
case path == "/":
|
||||
http.Redirect(w, r, s.basePath+"/", http.StatusFound)
|
||||
return
|
||||
case path == s.basePath:
|
||||
http.Redirect(w, r, s.basePath+"/", http.StatusFound)
|
||||
return
|
||||
case strings.HasPrefix(path, s.basePath+"/"):
|
||||
path = strings.TrimPrefix(path, s.basePath)
|
||||
default:
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
}
|
||||
switch {
|
||||
case path == "/" || path == "/index.html":
|
||||
s.handleIndex(w, r)
|
||||
case path == "/api/accounts":
|
||||
s.handleAPI(w, r)
|
||||
default:
|
||||
http.NotFound(w, r)
|
||||
}
|
||||
}
|
||||
|
||||
// basicAuth protects every route with HTTP Basic Auth credentials from the
|
||||
// environment (the same pattern as the other produktor internal UIs).
|
||||
func (s *server) basicAuth(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
user, pass, ok := r.BasicAuth()
|
||||
userOK := subtle.ConstantTimeCompare([]byte(user), []byte(s.user)) == 1
|
||||
passOK := subtle.ConstantTimeCompare([]byte(pass), []byte(s.pass)) == 1
|
||||
if !ok || !userOK || !passOK {
|
||||
w.Header().Set("WWW-Authenticate", `Basic realm="mail-admin"`)
|
||||
http.Error(w, "unauthorized", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
// collect builds the full account view: accounts file + per-mailbox stats.
|
||||
func (s *server) collect() (accountsResponse, error) {
|
||||
f, err := os.Open(s.accountsPath)
|
||||
if err != nil {
|
||||
return accountsResponse{}, err
|
||||
}
|
||||
accounts, err := parseAccounts(f)
|
||||
f.Close()
|
||||
if err != nil {
|
||||
return accountsResponse{}, err
|
||||
}
|
||||
quotas, err := s.loadQuotas()
|
||||
if err != nil {
|
||||
return accountsResponse{}, err
|
||||
}
|
||||
resp := accountsResponse{Updated: time.Now().UTC()}
|
||||
for _, a := range accounts {
|
||||
va := viewAccount{Email: a.Email, Quota: quotas[a.Email]}
|
||||
local, domain, ok := strings.Cut(a.Email, "@")
|
||||
if ok && local != "" && domain != "" {
|
||||
st, err := statMaildir(filepath.Join(s.maildirRoot, domain, local))
|
||||
if err != nil {
|
||||
log.Printf("statMaildir(%s): %v", a.Email, err)
|
||||
continue
|
||||
}
|
||||
va.Messages, va.Total, va.Storage, va.LastMessage = st.Messages, st.Total, st.Storage, st.Newest
|
||||
}
|
||||
resp.Accounts = append(resp.Accounts, va)
|
||||
}
|
||||
sort.Slice(resp.Accounts, func(i, j int) bool {
|
||||
return resp.Accounts[i].Email < resp.Accounts[j].Email
|
||||
})
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
func (s *server) loadQuotas() (map[string]string, error) {
|
||||
f, err := os.Open(s.quotaPath)
|
||||
if err != nil {
|
||||
if errors.Is(err, fs.ErrNotExist) {
|
||||
return map[string]string{}, nil // no quota file: no limits
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
defer f.Close()
|
||||
return parseQuotas(f)
|
||||
}
|
||||
|
||||
func (s *server) handleIndex(w http.ResponseWriter, r *http.Request) {
|
||||
resp, err := s.collect()
|
||||
if err != nil {
|
||||
log.Printf("collect: %v", err)
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
if err := indexTmpl.Execute(w, struct {
|
||||
Updated time.Time
|
||||
Accounts []viewAccount
|
||||
Base string
|
||||
}{resp.Updated, resp.Accounts, s.basePath + "/"}); err != nil {
|
||||
log.Printf("render: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *server) handleAPI(w http.ResponseWriter, r *http.Request) {
|
||||
resp, err := s.collect()
|
||||
if err != nil {
|
||||
log.Printf("collect: %v", err)
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
enc := json.NewEncoder(w)
|
||||
enc.SetIndent("", " ")
|
||||
enc.Encode(resp)
|
||||
}
|
||||
Reference in New Issue
Block a user