parsimony/internal/router/commands.go
tgiachi daea68f69d feat(router): RequestJoin for callers that are not an LMTP session
- RequestJoin(listAddress, addr) reuses join: the same open-policy check, the
  silence for active members, the confirmation mail and the store rate limits
- it returns nil for an unknown or closed list, a member and a rate limited
  request, and an error only for internal failures
- tests: confirmation mail and confirming it, nothing revealed, a bounce
  disabled member can rejoin, a database failure is reported
2026-11-10 12:35:17 +01:00

236 lines
7.4 KiB
Go

package router
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"log"
"mime"
"net/mail"
"strconv"
"strings"
"time"
"codeberg.org/squidd/parsimony/internal/store"
)
func (r *Router) secret() ([]byte, error) {
r.secretOnce.Do(func() { r.secretVal, r.secretErr = r.store.Secret() })
return r.secretVal, r.secretErr
}
// mac signs a member id for one purpose ("bounce" or "unsub"), so a token
// made for one use cannot be replayed for another.
func (r *Router) mac(purpose string, memberID int64) string {
key, err := r.secret()
if err != nil {
return ""
}
h := hmac.New(sha256.New, key)
fmt.Fprintf(h, "%s:%d", purpose, memberID)
return hex.EncodeToString(h.Sum(nil))[:12]
}
// bounceAddress returns the VERP envelope sender for a member, or "" on error.
func (r *Router) bounceAddress(l store.List, memberID int64) string {
mac := r.mac("bounce", memberID)
if mac == "" {
return ""
}
return fmt.Sprintf("%s+bounce-%d-%s@%s", l.Name, memberID, mac, l.Domain)
}
// Command handles list command addresses such as dev+join@example.org.
// handled is false when rcpt is a plain list address (use Route for those).
func (r *Router) Command(sender, rcpt string, data []byte) (handled bool, err error) {
local, domain, ok := strings.Cut(strings.ToLower(strings.TrimSpace(rcpt)), "@")
if !ok {
return false, nil
}
name, tag, hasTag := strings.Cut(local, "+")
if !hasTag {
return false, nil
}
l, err := r.store.FindList(name + "@" + domain)
if errors.Is(err, store.ErrNotFound) {
return true, ErrUnknownList
}
if err != nil {
return true, err
}
if tag == "join" || tag == "leave" || strings.HasPrefix(tag, "confirm-") {
if why, robot := robotReason(l, sender, data); robot {
log.Printf("ignore a subscription command for %s from %q: %s", l.Address(), sender, why)
return true, nil
}
}
switch {
case tag == "join":
return true, r.join(l, sender)
case tag == "leave":
return true, r.leave(l, sender)
case strings.HasPrefix(tag, "confirm-"):
return true, r.confirm(l, strings.TrimPrefix(tag, "confirm-"))
case tag == "bounce":
return true, nil // system mail without a token: nothing to learn from it
case strings.HasPrefix(tag, "bounce-"):
return true, r.bounce(l, strings.TrimPrefix(tag, "bounce-"), data)
}
return true, ErrUnknownList
}
func (r *Router) join(l store.List, sender string) error {
if l.JoinPolicy != store.JoinOpen {
return ErrJoinClosed
}
// A member disabled by bounces is treated like a non-member: confirming re-enables it.
if ok, err := r.store.IsActiveMember(l.ID, sender); err != nil || ok {
return err // active members get no mail: it would leak membership
}
return r.askConfirmation(l, sender, store.ActionJoin)
}
// RequestJoin does what the +join command does for addr, for a caller that is not an LMTP session
// (the public subscribe form): there is no envelope sender to check, so the caller must have
// validated addr. It returns nil whenever nothing should be revealed: an unknown or closed list, an
// active member, a request the store rate limits. It returns an error only for internal failures.
func (r *Router) RequestJoin(listAddress, addr string) error {
l, err := r.store.FindList(listAddress)
if errors.Is(err, store.ErrNotFound) {
return nil
}
if err != nil {
return err
}
if err := r.join(l, addr); err != nil && !errors.Is(err, ErrJoinClosed) {
return err
}
return nil
}
func (r *Router) leave(l store.List, sender string) error {
if ok, err := r.store.IsMember(l.ID, sender); err != nil || !ok {
return err
}
return r.askConfirmation(l, sender, store.ActionLeave)
}
func (r *Router) askConfirmation(l store.List, addr, action string) error {
token, created, err := r.store.CreatePending(l.ID, addr, action)
if err != nil || !created {
return err
}
verb, subject := "join", "Confirm your subscription to "+l.Title
if action == store.ActionLeave {
verb, subject = "leave", "Confirm your unsubscription from "+l.Title
}
msg := fmt.Sprintf("From: %s\r\nTo: %s\r\nReply-To: %s+confirm-%s@%s\r\nSubject: %s\r\nDate: %s\r\n"+
"Message-ID: <%s.%s@%s>\r\nAuto-Submitted: auto-generated\r\nContent-Type: text/plain; charset=utf-8\r\n\r\n"+
"Someone, probably you, asked to %s %s.\r\n\r\n"+
"To confirm, just reply to this message. The request expires in 72 hours.\r\n"+
"If you did not ask for this, ignore this message and nothing will happen.\r\n",
(&mail.Address{Name: l.Title, Address: l.Address()}).String(),
(&mail.Address{Address: addr}).String(),
l.Name, token, l.Domain,
mime.QEncoding.Encode("utf-8", subject),
time.Now().Format(time.RFC1123Z),
token[:8], strconv.FormatInt(time.Now().UnixNano(), 36), l.Domain,
verb, l.Address())
return r.enqueue([]byte(msg), []store.NewOutbound{{From: l.Name + "+bounce@" + l.Domain, Rcpt: addr}})
}
func (r *Router) confirm(l store.List, token string) error {
// The token is used up only if the action happens: a closed list or a database error leaves it
// valid, and two replies to the same mail cannot both apply.
_, err := r.store.ConfirmPending(token, l.ID, func(p store.Pending) error {
if p.Action == store.ActionJoin && l.JoinPolicy != store.JoinOpen {
return ErrJoinClosed
}
return nil
})
if errors.Is(err, store.ErrNotFound) {
return ErrBadToken
}
return err
}
func (r *Router) bounce(l store.List, tag string, data []byte) error {
idStr, mac, ok := strings.Cut(tag, "-")
id, err := strconv.ParseInt(idStr, 10, 64)
if !ok || err != nil {
return ErrBadToken
}
want := r.mac("bounce", id)
if want == "" || !hmac.Equal([]byte(mac), []byte(want)) {
return ErrBadToken
}
m, err := r.store.MemberByID(id)
if errors.Is(err, store.ErrNotFound) || (err == nil && m.ListID != l.ID) {
return ErrBadToken
}
if err != nil {
return err
}
if isHardBounce(data) {
_, err = r.store.RecordHardBounce(m.ID, store.BounceThreshold)
}
return err
}
// UnsubscribeToken returns the signed token used in one-click unsubscribe links
// for a member, or "" if the secret is unavailable.
func (r *Router) UnsubscribeToken(memberID int64) string {
mac := r.mac("unsub", memberID)
if mac == "" {
return ""
}
return fmt.Sprintf("%d-%s", memberID, mac)
}
// parseUnsubscribe verifies a token and returns the member id.
func (r *Router) parseUnsubscribe(token string) (int64, error) {
idStr, mac, ok := strings.Cut(token, "-")
id, err := strconv.ParseInt(idStr, 10, 64)
if !ok || err != nil || id <= 0 {
return 0, ErrBadToken
}
want := r.mac("unsub", id)
if want == "" || !hmac.Equal([]byte(mac), []byte(want)) {
return 0, ErrBadToken
}
return id, nil
}
// CheckUnsubscribe validates a token and returns the list it belongs to,
// without changing anything. ErrGone means the member is already unsubscribed.
func (r *Router) CheckUnsubscribe(token string) (store.List, error) {
id, err := r.parseUnsubscribe(token)
if err != nil {
return store.List{}, err
}
m, err := r.store.MemberByID(id)
if errors.Is(err, store.ErrNotFound) {
return store.List{}, ErrGone
}
if err != nil {
return store.List{}, err
}
return r.store.GetList(m.ListID)
}
// Unsubscribe removes the member behind a valid token. Repeating it succeeds,
// because mail clients may send the one-click request more than once.
func (r *Router) Unsubscribe(token string) error {
id, err := r.parseUnsubscribe(token)
if err != nil {
return err
}
if err := r.store.DeleteMember(id); err != nil && !errors.Is(err, store.ErrNotFound) {
return err
}
return nil
}