diff --git a/README.md b/README.md
index 348ae61..16d1c9c 100644
--- a/README.md
+++ b/README.md
@@ -46,7 +46,7 @@ HTTP API providing user/client message handling for an fmsg host. Exposes CRUD o
| `FMSG_API_PORT` | `443` (TLS) / `8000` (plain) | TCP port to listen on. |
| `FMSG_ID_URL` | `http://127.0.0.1:8080` | Base URL of the fmsgid identity service |
| `FMSG_API_MAX_DATA_SIZE`| `10` | Maximum message data size in megabytes |
-| `FMSG_API_MAX_ATTACH_SIZE`| `10` | Maximum attachment file size in megabytes |
+| `FMSG_API_MAX_ATTACH_SIZE`| `10` | Maximum attachment file size in megabytes (HTTP `ReadTimeout` of 60s and `WriteTimeout` of 65s bound upload/download duration) |
| `FMSG_API_MAX_MSG_SIZE`| `20` | Maximum total message size (data + attachments) in megabytes |
| `FMSG_API_SHORT_TEXT_SIZE`| `768` | Maximum bytes of message body returned inline as `short_text` for `text/*` UTF-8 messages |
| `FMSG_RETRY_MAX_AGE` | `86400` | Seconds fmsgd keeps retrying a delivery after the message was sent (its `FMSG_RETRY_MAX_AGE`; set both the same). A delivery older than this has been given up on and no longer keeps a deleted-for-good message on the host. |
@@ -1152,6 +1152,7 @@ and send time. Ancestors the caller is not a participant of appear as
| ------ | --------- |
| `404` | Message not found |
| `403` | Authenticated user is not a participant of the requested message |
+| `413` | Aggregate inline text exceeds 32 MiB (`thread_too_large`) |
### GET `/fmsg/:id/thread/messages`
diff --git a/cmd/fmsg-webapi/apikey_cli.go b/cmd/fmsg-webapi/apikey_cli.go
index 5164c40..8088dc2 100644
--- a/cmd/fmsg-webapi/apikey_cli.go
+++ b/cmd/fmsg-webapi/apikey_cli.go
@@ -2,6 +2,7 @@ package main
import (
"context"
+ "errors"
"flag"
"fmt"
"net/http"
@@ -57,23 +58,26 @@ func runAPIKeyCreate(ctx context.Context, args []string) error {
// Match the self-service sub-account flow: derived addresses are created in
// fmsgid, in the owner's quota pool, before their API key is persisted, and
// one used before is reinstated.
- reinstated, err := middleware.RegisterLinkedFmsgID(idURL, subAddr, *owner)
+ created, reinstated, err := middleware.RegisterLinkedFmsgIDContext(ctx, idURL, subAddr, *owner)
if err != nil {
return fmt.Errorf("registering derived address with fmsgid: %w", err)
}
+ if err := requireAcceptingCLIAddress(idURL, subAddr, "derived address"); err != nil {
+ return err
+ }
granted := false
- if reinstated {
+ conflict := false
+ if created || reinstated {
defer func() {
- if !granted {
- if err := middleware.DisableFmsgID(idURL, subAddr); err != nil {
- fmt.Fprintf(os.Stderr, "re-disabling reinstated address %s: %v\n", subAddr, err)
+ if !granted && !conflict {
+ disableCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+ defer cancel()
+ if err := middleware.DisableFmsgIDContext(disableCtx, idURL, subAddr); err != nil {
+ fmt.Fprintf(os.Stderr, "disabling address %s after failed create: %v\n", subAddr, err)
}
}
}()
}
- if err := requireAcceptingCLIAddress(idURL, subAddr, "derived address"); err != nil {
- return err
- }
database, err := db.New(ctx, "")
if err != nil {
return err
@@ -82,6 +86,9 @@ func runAPIKeyCreate(ctx context.Context, args []string) error {
store := apiauth.NewStore(database)
if err := store.Create(ctx, *owner, *agent, subAddr, key.ID, hash, allowed, expires); err != nil {
+ if errors.Is(err, apiauth.ErrAlreadyExists) {
+ conflict = true
+ }
return err
}
granted = true
diff --git a/cmd/fmsg-webapi/apikey_cli_integration_test.go b/cmd/fmsg-webapi/apikey_cli_integration_test.go
index 3676bb1..99c958f 100644
--- a/cmd/fmsg-webapi/apikey_cli_integration_test.go
+++ b/cmd/fmsg-webapi/apikey_cli_integration_test.go
@@ -301,23 +301,43 @@ func TestAPIKeyExchangeRejectsUnregisteredDerivedAddress(t *testing.T) {
}
// TestAPIKeyCLICreateReinstates creates a derived sub-account whose address was
-// used before: fmsgid reinstates it, the CLI says so, and when the grant can't
-// be created the address is stopped accepting new messages again.
+// used before: fmsgid reinstates it, the CLI says so; when the grant can't be
+// created due to a non-conflict error (e.g. limit exceeded), the address is
+// stopped accepting new messages again; on conflict (ErrAlreadyExists, such as
+// a concurrent winner), the active address is left untouched.
func TestAPIKeyCLICreateReinstates(t *testing.T) {
- for _, conflict := range []bool{false, true} {
- t.Run(fmt.Sprintf("conflict=%v", conflict), func(t *testing.T) {
+ for _, mode := range []string{"success", "limit_exceeded", "conflict"} {
+ t.Run(mode, func(t *testing.T) {
database := newAPIKeyCLIDB(t)
const owner = "@alice@example.com"
const target = "@alice_bot@example.com"
- if conflict {
+ store := apiauth.NewStore(database)
+ switch mode {
+ case "conflict":
key, err := apiauth.GenerateAPIKey()
if err != nil {
t.Fatal(err)
}
- if err := apiauth.NewStore(database).Create(context.Background(), owner, "bot", target, key.ID,
+ if err := store.Create(context.Background(), owner, "bot", target, key.ID,
apiauth.HashAPIKey(key.Value), []string{"127.0.0.0/8"}, time.Now().Add(time.Hour)); err != nil {
t.Fatal(err)
}
+ case "limit_exceeded":
+ for i := range apiauth.DefaultMaxSubAccounts {
+ key, err := apiauth.GenerateAPIKey()
+ if err != nil {
+ t.Fatal(err)
+ }
+ agent := fmt.Sprintf("other%d", i)
+ addr, err := apiauth.DeriveSubAccountAddr(owner, agent)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := store.Create(context.Background(), owner, agent, addr, key.ID,
+ apiauth.HashAPIKey(key.Value), []string{"127.0.0.0/8"}, time.Now().Add(time.Hour)); err != nil {
+ t.Fatal(err)
+ }
+ }
}
var mu sync.Mutex
accepting := false // the address exists and was disabled
@@ -357,17 +377,25 @@ func TestAPIKeyCLICreateReinstates(t *testing.T) {
"-expires", time.Now().Add(time.Hour).UTC().Format(time.RFC3339)})
mu.Lock()
defer mu.Unlock()
- if conflict {
+ switch mode {
+ case "limit_exceeded":
if err == nil {
- t.Fatal("create succeeded despite an existing grant")
+ t.Fatal("create succeeded despite exceeding sub-account limit")
}
if accepting {
t.Fatal("address left reinstated although its grant wasn't created")
}
- return
- }
- if err != nil || !strings.Contains(output, "\nreinstated=true\n") || !accepting {
- t.Fatalf("create: err=%v accepting=%v output=%q", err, accepting, output)
+ case "conflict":
+ if err == nil {
+ t.Fatal("create succeeded despite an existing grant")
+ }
+ if !accepting {
+ t.Fatal("conflicting create disabled an already-granted address")
+ }
+ default:
+ if err != nil || !strings.Contains(output, "\nreinstated=true\n") || !accepting {
+ t.Fatalf("create: err=%v accepting=%v output=%q", err, accepting, output)
+ }
}
})
}
diff --git a/cmd/fmsg-webapi/main.go b/cmd/fmsg-webapi/main.go
index c15e113..449a08f 100644
--- a/cmd/fmsg-webapi/main.go
+++ b/cmd/fmsg-webapi/main.go
@@ -7,8 +7,10 @@ import (
"log"
"net/http"
"os"
+ "os/signal"
"strconv"
"strings"
+ "syscall"
"time"
"github.com/MicahParks/keyfunc/v3"
@@ -83,8 +85,12 @@ func main() {
pushIconURL := envOrDefault("FMSG_PUSH_ICON_URL", "/icon-192.png")
pushEnabled := vapidPublic != "" && vapidPrivate != "" && vapidSubject != ""
+ // Root context cancelled on SIGINT/SIGTERM for graceful shutdown of the
+ // HTTP server, JWKS refresher, LISTEN/NOTIFY hub, and Web Push workers.
+ ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
+ defer stop()
+
// Connect to PostgreSQL (uses standard PG* environment variables).
- ctx := context.Background()
database, err := db.New(ctx, "")
if err != nil {
log.Fatalf("failed to connect to database: %v", err)
@@ -170,7 +176,14 @@ func main() {
// The hub also dispatches a Web Push for every new_msg notification.
hub.SetPushNotifier(pushHandler.NotifyNewMsg)
}
- go hub.Run(context.Background())
+ // The hub runs on its own context so it keeps LISTENing for notifications
+ // from in-flight HTTP requests while the server drains on shutdown.
+ hubCtx, cancelHub := context.WithCancel(context.Background())
+ hubDone := make(chan struct{})
+ go func() {
+ defer close(hubDone)
+ hub.Run(hubCtx)
+ }()
wsHandler := handlers.NewWSHandler(jwtVerifier, hub, corsOrigins)
var tokenHandler *handlers.TokenHandler
@@ -185,26 +198,65 @@ func main() {
srv := &http.Server{
Handler: router,
ReadHeaderTimeout: 10 * time.Second,
+ ReadTimeout: 60 * time.Second,
WriteTimeout: 65 * time.Second, // generous, to allow large file transfers
IdleTimeout: 120 * time.Second,
MaxHeaderBytes: 1 << 20, // 1 MB
}
+ serveErr := make(chan error, 1)
if tlsEnabled {
port := envOrDefault("FMSG_API_PORT", "443")
srv.Addr = ":" + port
log.Printf("fmsg-webapi starting on :%s (HTTPS)", port)
srv.TLSConfig = &tls.Config{MinVersion: tls.VersionTLS12}
- if err = srv.ListenAndServeTLS(tlsCert, tlsKey); err != nil && !errors.Is(err, http.ErrServerClosed) {
- log.Fatalf("server error: %v", err)
- }
+ go func() {
+ if err := srv.ListenAndServeTLS(tlsCert, tlsKey); err != nil && !errors.Is(err, http.ErrServerClosed) {
+ serveErr <- err
+ }
+ close(serveErr)
+ }()
} else {
port := envOrDefault("FMSG_API_PORT", "8000")
srv.Addr = ":" + port
log.Printf("fmsg-webapi starting on :%s (plain HTTP)", port)
- if err = srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
+ go func() {
+ if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
+ serveErr <- err
+ }
+ close(serveErr)
+ }()
+ }
+
+ select {
+ case err := <-serveErr:
+ stop()
+ cancelHub()
+ <-hubDone
+ pushDrainCtx, cancelPushDrain := context.WithTimeout(context.Background(), 5*time.Second)
+ if closeErr := hub.CloseContext(pushDrainCtx); closeErr != nil {
+ log.Printf("push shutdown error: %v", closeErr)
+ }
+ cancelPushDrain()
+ if err != nil {
log.Fatalf("server error: %v", err)
}
+ case <-ctx.Done():
+ log.Println("fmsg-webapi shutting down...")
+ stop()
+ shutCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancel()
+ if err := srv.Shutdown(shutCtx); err != nil {
+ log.Printf("server shutdown error: %v", err)
+ }
+ <-serveErr
+ cancelHub()
+ <-hubDone
+ pushDrainCtx, cancelPushDrain := context.WithTimeout(context.Background(), 5*time.Second)
+ defer cancelPushDrain()
+ if err := hub.CloseContext(pushDrainCtx); err != nil {
+ log.Printf("push shutdown error: %v", err)
+ }
}
}
diff --git a/internal/apiauth/store.go b/internal/apiauth/store.go
index bdfa9c3..5631597 100644
--- a/internal/apiauth/store.go
+++ b/internal/apiauth/store.go
@@ -138,6 +138,12 @@ func (s *Store) createGrant(ctx context.Context, ownerAddr, agent, subAddr, gran
}
defer tx.Rollback(ctx) //nolint:errcheck
+ // Serialize concurrent grant creations for the same owner so max_sub_accounts
+ // cannot be bypassed via a read-then-insert race.
+ if _, err := tx.Exec(ctx, `SELECT pg_advisory_xact_lock(hashtext(lower($1)))`, ownerAddr); err != nil {
+ return err
+ }
+
max, err := maxSubAccountsTx(ctx, tx, ownerAddr)
if err != nil {
return err
diff --git a/internal/db/db.go b/internal/db/db.go
index 56ad92a..3b3ac70 100644
--- a/internal/db/db.go
+++ b/internal/db/db.go
@@ -22,6 +22,7 @@ func New(ctx context.Context, dsn string) (*DB, error) {
return nil, fmt.Errorf("db: failed to create pool: %w", err)
}
if err = pool.Ping(ctx); err != nil {
+ pool.Close()
return nil, fmt.Errorf("db: failed to ping: %w", err)
}
return &DB{Pool: pool}, nil
diff --git a/internal/handlers/attachments.go b/internal/handlers/attachments.go
index 25adac9..47576ee 100644
--- a/internal/handlers/attachments.go
+++ b/internal/handlers/attachments.go
@@ -57,7 +57,7 @@ func (h *AttachmentHandler) Upload(c *gin.Context) {
return
}
- if fromAddr != identity {
+ if !sameAddr(fromAddr, identity) {
c.JSON(http.StatusForbidden, gin.H{"error": "only the owner may upload attachments"})
return
}
@@ -66,9 +66,19 @@ func (h *AttachmentHandler) Upload(c *gin.Context) {
return
}
+ // Bound request body before parsing multipart form data (allow 1 MiB for
+ // multipart framing overhead while rejecting unbounded uploads).
+ if h.MaxAttachSize > 0 {
+ limitRequestBody(c, h.MaxAttachSize+1<<20)
+ }
+
// Expect multipart file upload with field "file".
file, header, err := c.Request.FormFile("file")
if err != nil {
+ if isMaxBytesError(err) {
+ c.JSON(http.StatusRequestEntityTooLarge, gin.H{"error": "attachment exceeds maximum size"})
+ return
+ }
c.JSON(http.StatusBadRequest, gin.H{"error": "file field required"})
return
}
@@ -89,11 +99,8 @@ func (h *AttachmentHandler) Upload(c *gin.Context) {
return
}
- // Resolve collision-safe filepath.
- finalPath := resolveFilePath(dir, intendedFilename)
-
- // Write file to disk (limit read to MaxAttachSize + 1 to detect oversized uploads).
- dst, err := os.OpenFile(finalPath, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0640)
+ // Atomically create a collision-safe file to avoid Stat-then-Open TOCTOU races.
+ dst, finalPath, err := createUniqueAttachmentFile(dir, intendedFilename)
if err != nil {
log.Printf("upload attachment: open file: %v", err)
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to save attachment"})
@@ -103,6 +110,10 @@ func (h *AttachmentHandler) Upload(c *gin.Context) {
closeErr := dst.Close()
if err != nil || closeErr != nil {
_ = os.Remove(finalPath)
+ if isMaxBytesError(err) {
+ c.JSON(http.StatusRequestEntityTooLarge, gin.H{"error": "attachment exceeds maximum size"})
+ return
+ }
log.Printf("upload attachment: write: %v / %v", err, closeErr)
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to write attachment"})
return
@@ -117,22 +128,25 @@ func (h *AttachmentHandler) Upload(c *gin.Context) {
createdFile(c, finalPath)
// Check total message size and persist attachment in a transaction to
// prevent concurrent uploads from exceeding MaxMsgSize.
- tx, err := h.q().Begin(ctx)
+ tx, commit, rollback, err := beginOrReuseTx(ctx, h.q())
if err != nil {
_ = os.Remove(finalPath)
log.Printf("upload attachment: begin tx: %v", err)
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to record attachment"})
return
}
- defer tx.Rollback(ctx)
+ defer rollback()
- // Lock the message row and compute current total size.
+ // Lock the message row and compute current total size excluding any
+ // attachment being overwritten with the same filename.
var currentTotal int64
+ var prevPath string
if err = tx.QueryRow(ctx,
- `SELECT m.size + COALESCE((SELECT SUM(filesize) FROM msg_attachment WHERE msg_id = m.id), 0)
+ `SELECT m.size + COALESCE((SELECT SUM(filesize) FROM msg_attachment WHERE msg_id = m.id AND filename <> $2), 0),
+ COALESCE((SELECT filepath FROM msg_attachment WHERE msg_id = m.id AND filename = $2), '')
FROM msg m WHERE m.id = $1 FOR UPDATE`,
- msgID,
- ).Scan(¤tTotal); err != nil {
+ msgID, intendedFilename,
+ ).Scan(¤tTotal, &prevPath); err != nil {
_ = os.Remove(finalPath)
log.Printf("upload attachment: total size check: %v", err)
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to check message size"})
@@ -158,13 +172,19 @@ func (h *AttachmentHandler) Upload(c *gin.Context) {
return
}
- if err = tx.Commit(ctx); err != nil {
+ if err = commit(); err != nil {
_ = os.Remove(finalPath)
log.Printf("upload attachment: commit: %v", err)
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to record attachment"})
return
}
+ if prevPath != "" && prevPath != finalPath {
+ if cleanPrev, ok := safeDataPath(prevPath, h.DataDir); ok {
+ afterCommit(c, func() { _ = os.Remove(cleanPrev) })
+ }
+ }
+
c.JSON(http.StatusCreated, gin.H{"filename": intendedFilename, "size": written})
}
@@ -198,13 +218,23 @@ func (h *AttachmentHandler) Download(c *gin.Context) {
}
return
}
- if draftHidden([]string{identity}, fromAddr, timeSent) || purgedFor(ctx, h.q(), identity, msgID) {
+ if draftHidden([]string{identity}, fromAddr, timeSent) {
+ c.JSON(http.StatusNotFound, gin.H{"error": "message not found"})
+ return
+ }
+ purged, err := purgedFor(ctx, h.q(), identity, msgID)
+ if err != nil {
+ log.Printf("download attachment: trash state %d: %v", msgID, err)
+ c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to retrieve message"})
+ return
+ }
+ if purged {
c.JSON(http.StatusNotFound, gin.H{"error": "message not found"})
return
}
// Check recipients (to or add_to) if not owner.
- if fromAddr != identity {
+ if !sameAddr(fromAddr, identity) {
var recipientCount int
if err = h.q().QueryRow(ctx,
`SELECT COUNT(*) FROM (
@@ -235,9 +265,8 @@ func (h *AttachmentHandler) Download(c *gin.Context) {
}
// Path traversal protection: ensure the stored path is within DataDir.
- cleanPath := filepath.Clean(storedPath)
- cleanDataDir := filepath.Clean(h.DataDir)
- if !strings.HasPrefix(cleanPath, cleanDataDir+string(filepath.Separator)) {
+ cleanPath, ok := safeDataPath(storedPath, h.DataDir)
+ if !ok {
log.Printf("download attachment: path traversal attempt: %s", storedPath)
c.JSON(http.StatusForbidden, gin.H{"error": "access denied"})
return
@@ -277,7 +306,7 @@ func (h *AttachmentHandler) DeleteAttachment(c *gin.Context) {
return
}
- if fromAddr != identity {
+ if !sameAddr(fromAddr, identity) {
c.JSON(http.StatusForbidden, gin.H{"error": "only the owner may delete attachments"})
return
}
@@ -311,28 +340,35 @@ func (h *AttachmentHandler) DeleteAttachment(c *gin.Context) {
}
// Remove file from disk.
- cleanPath := filepath.Clean(storedPath)
- cleanDataDir := filepath.Clean(h.DataDir)
- if strings.HasPrefix(cleanPath, cleanDataDir+string(filepath.Separator)) {
+ if cleanPath, ok := safeDataPath(storedPath, h.DataDir); ok {
afterCommit(c, func() { _ = os.Remove(cleanPath) })
}
c.Status(http.StatusNoContent)
}
-// resolveFilePath returns a path under dir for filename, incrementing a suffix
-// until no collision is found.
-func resolveFilePath(dir, filename string) string {
+// createUniqueAttachmentFile atomically creates a new file under dir for
+// filename, appending an incrementing numeric suffix on collision.
+func createUniqueAttachmentFile(dir, filename string) (*os.File, string, error) {
candidate := filepath.Join(dir, filename)
- if _, err := os.Stat(candidate); os.IsNotExist(err) {
- return candidate
+ f, err := os.OpenFile(candidate, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0640)
+ if err == nil {
+ return f, candidate, nil
+ }
+ if !errors.Is(err, os.ErrExist) {
+ return nil, "", err
}
ext := filepath.Ext(filename)
base := strings.TrimSuffix(filename, ext)
- for i := 1; ; i++ {
+ for i := 1; i <= 10000; i++ {
candidate = filepath.Join(dir, fmt.Sprintf("%s_%d%s", base, i, ext))
- if _, err := os.Stat(candidate); os.IsNotExist(err) {
- return candidate
+ f, err = os.OpenFile(candidate, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0640)
+ if err == nil {
+ return f, candidate, nil
+ }
+ if !errors.Is(err, os.ErrExist) {
+ return nil, "", err
}
}
+ return nil, "", fmt.Errorf("too many attachment filename collisions for %q", filename)
}
diff --git a/internal/handlers/attachments_test.go b/internal/handlers/attachments_test.go
new file mode 100644
index 0000000..a1d71b2
--- /dev/null
+++ b/internal/handlers/attachments_test.go
@@ -0,0 +1,201 @@
+package handlers
+
+import (
+ "bytes"
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "path/filepath"
+ "strings"
+ "sync"
+ "testing"
+
+ "github.com/gin-gonic/gin"
+ "github.com/markmnl/fmsg-webapi/internal/middleware"
+)
+
+func TestCreateUniqueAttachmentFile_CollisionAndConcurrentAtomic(t *testing.T) {
+ dir := t.TempDir()
+
+ // Sequential collisions get incremented suffixes.
+ f1, p1, err := createUniqueAttachmentFile(dir, "report.pdf")
+ if err != nil {
+ t.Fatalf("first create: %v", err)
+ }
+ _ = f1.Close()
+ if filepath.Base(p1) != "report.pdf" {
+ t.Fatalf("first path = %q, want report.pdf", p1)
+ }
+
+ f2, p2, err := createUniqueAttachmentFile(dir, "report.pdf")
+ if err != nil {
+ t.Fatalf("second create: %v", err)
+ }
+ _ = f2.Close()
+ if filepath.Base(p2) != "report_1.pdf" {
+ t.Fatalf("second path = %q, want report_1.pdf", p2)
+ }
+
+ // Concurrent creations for the same filename must all succeed with distinct files.
+ const workers = 16
+ var wg sync.WaitGroup
+ paths := make([]string, workers)
+ errs := make([]error, workers)
+ wg.Add(workers)
+ for i := range workers {
+ go func(idx int) {
+ defer wg.Done()
+ f, p, err := createUniqueAttachmentFile(dir, "concurrent.txt")
+ if err != nil {
+ errs[idx] = err
+ return
+ }
+ _, _ = f.WriteString("data")
+ _ = f.Close()
+ paths[idx] = p
+ }(i)
+ }
+ wg.Wait()
+
+ seen := make(map[string]bool, workers)
+ for i := range workers {
+ if errs[i] != nil {
+ t.Fatalf("worker %d failed: %v", i, errs[i])
+ }
+ if seen[paths[i]] {
+ t.Fatalf("duplicate path returned to concurrent callers: %q", paths[i])
+ }
+ seen[paths[i]] = true
+ if _, err := os.Stat(paths[i]); err != nil {
+ t.Fatalf("created file missing: %v", err)
+ }
+ }
+}
+
+func TestLimitRequestBodyRejectsOversizedJSON(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+ w := httptest.NewRecorder()
+ c, _ := gin.CreateTestContext(w)
+ body := `{"data":"` + strings.Repeat("x", 2048) + `"}`
+ c.Request = httptest.NewRequest(http.MethodPost, "/fmsg", bytes.NewBufferString(body))
+ c.Request.Header.Set("Content-Type", "application/json")
+
+ limitRequestBody(c, 128)
+ var in struct {
+ Data string `json:"data"`
+ }
+ err := c.ShouldBindJSON(&in)
+ if err == nil {
+ t.Fatal("expected error for oversized body")
+ }
+ if !isMaxBytesError(err) {
+ t.Fatalf("expected MaxBytesError, got %T: %v", err, err)
+ }
+}
+
+func TestLimitJSONBody_AllowsEscapedHTMLAndRejectsOversized(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+ const maxDataSize = int64(1 << 20) // 1 MiB
+
+ // Go's encoding/json escapes '<', '>', '&' to 6 bytes (\u003c, \u003e, \u0026).
+ // A <= 1 MiB HTML/symbol payload expands to ~3x-5.8x on the wire — well past
+ // the old 2x+1MiB cap (3 MiB) — and must still bind cleanly.
+ cases := []struct {
+ name string
+ data string
+ }{
+ {
+ name: "html_table_cells_3x",
+ data: strings.Repeat("
| ", 116000), // 1,044,000 B decoded -> ~3.36 MB JSON
+ },
+ {
+ name: "angle_brackets_near_6x",
+ data: strings.Repeat("<>&", 340000), // 1,020,000 B decoded -> ~6.12 MB JSON
+ },
+ }
+
+ h := &MessageHandler{MaxDataSize: maxDataSize}
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ if int64(len(tc.data)) > maxDataSize {
+ t.Fatalf("test fixture decoded len %d > maxDataSize %d", len(tc.data), maxDataSize)
+ }
+ wire, err := json.Marshal(map[string]any{
+ "from": "@other@example.com",
+ "to": []string{"@bob@example.com"},
+ "type": "text/html",
+ "data": tc.data,
+ })
+ if err != nil {
+ t.Fatalf("marshal fixture: %v", err)
+ }
+ if int64(len(wire)) <= maxDataSize*2+(1<<20) {
+ t.Fatalf("fixture wire size %d did not exceed old 2x+1MiB cap %d", len(wire), maxDataSize*2+(1<<20))
+ }
+
+ w := httptest.NewRecorder()
+ c, _ := gin.CreateTestContext(w)
+ c.Request = httptest.NewRequest(http.MethodPost, "/fmsg", bytes.NewReader(wire))
+ c.Request.Header.Set("Content-Type", "application/json")
+ c.Set(middleware.IdentityKey, "@alice@example.com")
+
+ h.Create(c)
+ // Should pass JSON binding (no 413) and hit the ownership check (403).
+ if w.Code == http.StatusRequestEntityTooLarge {
+ t.Fatalf("valid escaped body (wire=%d, decoded=%d) was rejected with 413", len(wire), len(tc.data))
+ }
+ if w.Code != http.StatusForbidden {
+ t.Fatalf("status = %d, want 403 after passing body bind; body=%s", w.Code, w.Body.String())
+ }
+ })
+ }
+
+ // A wire body exceeding 6*MaxDataSize + 1 MiB must be rejected with 413.
+ t.Run("over_6x_plus_1MiB_returns_413", func(t *testing.T) {
+ oversized := `{"from":"@alice@example.com","to":["@bob@example.com"],"data":"` +
+ strings.Repeat("a", int(maxDataSize*6+(1<<20)+1024)) + `"}`
+ w := httptest.NewRecorder()
+ c, _ := gin.CreateTestContext(w)
+ c.Request = httptest.NewRequest(http.MethodPost, "/fmsg", strings.NewReader(oversized))
+ c.Request.Header.Set("Content-Type", "application/json")
+ c.Set(middleware.IdentityKey, "@alice@example.com")
+
+ h.Create(c)
+ if w.Code != http.StatusRequestEntityTooLarge {
+ t.Fatalf("oversized status = %d, want 413; body=%s", w.Code, w.Body.String())
+ }
+ })
+}
+
+func TestResolveIDStashesInContext(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+ w := httptest.NewRecorder()
+ c, _ := gin.CreateTestContext(w)
+ c.Params = gin.Params{{Key: "id", Value: "42"}}
+
+ // First call parses numeric id and stashes it.
+ id, ok := resolveID(c, nil)
+ if !ok || id != 42 {
+ t.Fatalf("resolveID numeric = (%d, %v), want (42, true)", id, ok)
+ }
+
+ // Simulate hash ID already stashed by atomic(): second call must return
+ // the stashed ID without querying DB (nil queries would panic otherwise).
+ hash := strings.Repeat("a", 64)
+ c.Params = gin.Params{{Key: "id", Value: hash}}
+ c.Set(resolvedMsgIDKey, cachedResolvedID{raw: hash, id: 77})
+ id, ok = resolveID(c, nil)
+ if !ok || id != 77 {
+ t.Fatalf("resolveID cached hash = (%d, %v), want (77, true)", id, ok)
+ }
+}
+
+func TestAttachmentCaseInsensitiveOwner(t *testing.T) {
+ if !sameAddr("@Alice@Example.COM", "@alice@example.com") {
+ t.Fatal("expected case-insensitive owner match")
+ }
+ if sameAddr("@alice@example.com", "@bob@example.com") {
+ t.Fatal("expected distinct addresses not to match")
+ }
+}
diff --git a/internal/handlers/count.go b/internal/handlers/count.go
index 50b698d..2f8b780 100644
--- a/internal/handlers/count.go
+++ b/internal/handlers/count.go
@@ -33,14 +33,19 @@ func (h *MessageHandler) Count(c *gin.Context) {
}
var threads int64
err = h.q().QueryRow(ctx,
- `WITH vis AS (
+ `WITH candidate AS (
+ SELECT id FROM msg WHERE lower(from_addr) = ANY($1)
+ UNION
+ SELECT msg_id AS id FROM msg_to WHERE lower(addr) = ANY($1)
+ UNION
+ SELECT msg_id AS id FROM msg_add_to WHERE lower(addr) = ANY($1)
+ ),
+ vis AS (
SELECT m.id, m.pid
- FROM msg m
+ FROM candidate c
+ JOIN msg m ON m.id = c.id
CROSS JOIN LATERAL (SELECT CASE WHEN $2 THEN fmsg_api_trash_state($3, m.id) END AS state) t
WHERE m.time_sent IS NOT NULL
- AND (lower(m.from_addr) = ANY($1)
- OR EXISTS (SELECT 1 FROM msg_to mt WHERE mt.msg_id = m.id AND lower(mt.addr) = ANY($1))
- OR EXISTS (SELECT 1 FROM msg_add_to mat WHERE mat.msg_id = m.id AND lower(mat.addr) = ANY($1)))
AND `+trashFilter+`
)
SELECT count(*) FROM vis v
diff --git a/internal/handlers/edits.go b/internal/handlers/edits.go
index d8a8410..13bfd7e 100644
--- a/internal/handlers/edits.go
+++ b/internal/handlers/edits.go
@@ -41,23 +41,58 @@ func editShape(hasPid, noReply, terminal, important, hasAddTo bool, mediaType st
attachments == 0 && isEditMediaType(mediaType)
}
-// readBody reads a stored message body. An empty path is an empty body.
-func (h *MessageHandler) readBody(dataPath string) ([]byte, bool) {
+// readBodyErr reads a stored message body, distinguishing disk I/O errors
+// from unsafe paths. An empty path is an empty body.
+func (h *MessageHandler) readBodyErr(dataPath string) ([]byte, bool, error) {
if dataPath == "" {
- return nil, true
+ return nil, true, nil
}
cleanPath, ok := safeDataPath(dataPath, h.DataDir)
if !ok {
- return nil, false
+ return nil, false, nil
}
data, err := os.ReadFile(cleanPath)
if err != nil {
if !errors.Is(err, os.ErrNotExist) {
log.Printf("edit: read %s: %v", cleanPath, err)
}
- return nil, false
+ return nil, false, err
+ }
+ return data, true, nil
+}
+
+// readBody reads a stored message body. An empty path is an empty body.
+func (h *MessageHandler) readBody(dataPath string) ([]byte, bool) {
+ data, ok, _ := h.readBodyErr(dataPath)
+ return data, ok
+}
+
+// bodyLenErr returns the byte length of a stored message body without reading
+// its contents, distinguishing disk I/O errors from unsafe paths. An empty path
+// is an empty body.
+func (h *MessageHandler) bodyLenErr(dataPath string) (int, bool, error) {
+ if dataPath == "" {
+ return 0, true, nil
+ }
+ cleanPath, ok := safeDataPath(dataPath, h.DataDir)
+ if !ok {
+ return 0, false, nil
+ }
+ fi, err := os.Stat(cleanPath)
+ if err != nil {
+ if !errors.Is(err, os.ErrNotExist) {
+ log.Printf("edit: stat %s: %v", cleanPath, err)
+ }
+ return 0, false, err
}
- return data, true
+ return int(fi.Size()), true, nil
+}
+
+// bodyLen returns the byte length of a stored message body without reading its
+// contents. An empty path is an empty body.
+func (h *MessageHandler) bodyLen(dataPath string) (int, bool) {
+ n, ok, _ := h.bodyLenErr(dataPath)
+ return n, ok
}
// editLimit bounds the size of edited data this server will produce for a
@@ -67,9 +102,9 @@ func (h *MessageHandler) editLimit(subjectLen int) int64 {
}
// editSubject reports the subject of msgID when msgID is an edit message.
-// Used to flag edit messages and by the WebSocket hub to route an arriving
-// edit as an edit event.
-func (h *MessageHandler) editSubject(ctx context.Context, msgID int64) (int64, bool) {
+// Transient DB or disk errors are returned so callers (such as the WebSocket
+// hub classification cache) do not pin a false negative.
+func (h *MessageHandler) editSubject(ctx context.Context, msgID int64) (int64, bool, error) {
var pid int64
var size int
var dataPath, subjectPath string
@@ -79,26 +114,33 @@ func (h *MessageHandler) editSubject(ctx context.Context, msgID int64) (int64, b
WHERE r.id = $1 AND `+editRowFilter, msgID, edit.MediaType,
).Scan(&pid, &size, &dataPath, &subjectPath)
if err != nil {
- if !errors.Is(err, pgx.ErrNoRows) {
- log.Printf("edit subject of %d: %v", msgID, err)
+ if errors.Is(err, pgx.ErrNoRows) {
+ return 0, false, nil
}
- return 0, false
+ log.Printf("edit subject of %d: %v", msgID, err)
+ return 0, false, err
}
if size == 0 {
- return pid, true
+ return pid, true, nil
+ }
+ subjectLen, ok, err := h.bodyLenErr(subjectPath)
+ if err != nil {
+ return 0, false, err
}
- subject, ok := h.readBody(subjectPath)
if !ok {
- return 0, false
+ return 0, false, nil
+ }
+ doc, ok, err := h.readBodyErr(dataPath)
+ if err != nil {
+ return 0, false, err
}
- doc, ok := h.readBody(dataPath)
if !ok {
- return 0, false
+ return 0, false, nil
}
- if _, err := edit.Check(doc, len(subject)); err != nil {
- return 0, false
+ if _, err := edit.Check(doc, subjectLen); err != nil {
+ return 0, false, nil
}
- return pid, true
+ return pid, true, nil
}
// editRowFilter selects sent messages r having the shape of an edit of their
@@ -146,9 +188,9 @@ func (e *effectiveEdit) edited() *models.Edited {
// loadEffectiveEdits returns the effective edit of each of the given subjects
// that has one. Edit-shaped messages whose data is not a well-formed edit
// document for the subject are ordinary messages and are skipped.
-func (h *MessageHandler) loadEffectiveEdits(ctx context.Context, subjectIDs []int64) map[int64]*effectiveEdit {
+func (h *MessageHandler) loadEffectiveEdits(ctx context.Context, subjectIDs []int64) (map[int64]*effectiveEdit, error) {
if len(subjectIDs) == 0 {
- return nil
+ return nil, nil
}
rows, err := h.q().Query(ctx, `
SELECT r.pid, r.id, r.time_sent, r.sha256, r.size, r.filepath, s.filepath
@@ -157,8 +199,7 @@ func (h *MessageHandler) loadEffectiveEdits(ctx context.Context, subjectIDs []in
subjectIDs, edit.MediaType,
)
if err != nil {
- log.Printf("load edits: %v", err)
- return nil
+ return nil, err
}
bySubject := make(map[int64][]editRow)
subjectPaths := make(map[int64]string)
@@ -168,16 +209,14 @@ func (h *MessageHandler) loadEffectiveEdits(ctx context.Context, subjectIDs []in
var subjectPath string
if err := rows.Scan(&subjectID, &r.msgID, &r.time, &r.hash, &r.size, &r.dataPath, &subjectPath); err != nil {
rows.Close()
- log.Printf("load edits: scan: %v", err)
- return nil
+ return nil, err
}
bySubject[subjectID] = append(bySubject[subjectID], r)
subjectPaths[subjectID] = subjectPath
}
rows.Close()
if err := rows.Err(); err != nil {
- log.Printf("load edits: %v", err)
- return nil
+ return nil, err
}
result := make(map[int64]*effectiveEdit, len(bySubject))
@@ -224,7 +263,7 @@ func (h *MessageHandler) loadEffectiveEdits(ctx context.Context, subjectIDs []in
break
}
}
- return result
+ return result, nil
}
// shortTextOf returns the short_text preview of in-memory body data, as
@@ -242,26 +281,87 @@ func (h *MessageHandler) shortTextOf(data []byte, mimeType string) string {
return string(data)
}
-// populateListEdits fills Edit and Edited on every list item and replaces the
-// preview of an edited item with one of its edited data.
-func (h *MessageHandler) populateListEdits(ctx context.Context, items []messageListItem) {
+// populateListEdits fills Edit and Edited on every list item and sets the
+// preview of an edited item from its edited data. It returns the set of item
+// IDs whose preview was populated from an applied edit so callers can skip
+// reading the unedited body from disk.
+func (h *MessageHandler) populateListEdits(ctx context.Context, items []messageListItem) (map[int64]bool, error) {
ids := make([]int64, len(items))
- for i := range items {
- ids[i] = items[i].ID
- }
- edits := h.loadEffectiveEdits(ctx, ids)
+ var editCandidates []int64
for i := range items {
it := &items[i]
+ ids[i] = it.ID
if editShape(it.HasPid, it.NoReply, it.Terminal, it.Important, it.HasAddTo, it.Type, len(it.Attachments)) {
- _, it.Edit = h.editSubject(ctx, it.ID)
+ editCandidates = append(editCandidates, it.ID)
}
+ }
+
+ isEdit := make(map[int64]bool, len(editCandidates))
+ if len(editCandidates) > 0 {
+ type candidateRow struct {
+ id int64
+ size int
+ dataPath string
+ subjectPath string
+ }
+ rows, err := h.q().Query(ctx, `
+ SELECT r.id, r.size, r.filepath, s.filepath
+ FROM msg r JOIN msg s ON s.id = r.pid
+ WHERE r.id = ANY($1) AND `+editRowFilter,
+ editCandidates, edit.MediaType,
+ )
+ if err != nil {
+ return nil, err
+ }
+ var candRows []candidateRow
+ for rows.Next() {
+ var cr candidateRow
+ if err := rows.Scan(&cr.id, &cr.size, &cr.dataPath, &cr.subjectPath); err != nil {
+ rows.Close()
+ return nil, err
+ }
+ candRows = append(candRows, cr)
+ }
+ rows.Close()
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ for _, cr := range candRows {
+ if cr.size == 0 {
+ isEdit[cr.id] = true
+ continue
+ }
+ subjectLen, ok := h.bodyLen(cr.subjectPath)
+ if !ok {
+ continue
+ }
+ doc, ok := h.readBody(cr.dataPath)
+ if !ok {
+ continue
+ }
+ if _, err := edit.Check(doc, subjectLen); err == nil {
+ isEdit[cr.id] = true
+ }
+ }
+ }
+
+ edits, err := h.loadEffectiveEdits(ctx, ids)
+ if err != nil {
+ return nil, err
+ }
+ applied := make(map[int64]bool)
+ for i := range items {
+ it := &items[i]
+ it.Edit = isEdit[it.ID]
if eff := edits[it.ID]; eff != nil {
it.Edited = eff.edited()
if eff.applied {
it.ShortText = h.shortTextOf(eff.data, it.Type)
+ applied[it.ID] = true
}
}
}
+ return applied, nil
}
// without returns addrs less addr, deduplicated case-insensitively, in order.
@@ -330,8 +430,14 @@ func (h *MessageHandler) Edit(c *gin.Context) {
return
}
+ limitJSONBody(c, h.MaxDataSize)
+
var in editInput
if err := c.ShouldBindJSON(&in); err != nil {
+ if isMaxBytesError(err) {
+ c.JSON(http.StatusRequestEntityTooLarge, gin.H{"error": "message data exceeds maximum size"})
+ return
+ }
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
@@ -351,7 +457,17 @@ func (h *MessageHandler) Edit(c *gin.Context) {
}
return
}
- if draftHidden([]string{identity}, subject.From, subject.Time) || purgedFor(ctx, h.q(), identity, msgID) {
+ if draftHidden([]string{identity}, subject.From, subject.Time) {
+ c.JSON(http.StatusNotFound, gin.H{"error": "message not found"})
+ return
+ }
+ purged, err := purgedFor(ctx, h.q(), identity, msgID)
+ if err != nil {
+ log.Printf("edit %d: trash state: %v", msgID, err)
+ c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to retrieve message"})
+ return
+ }
+ if purged {
c.JSON(http.StatusNotFound, gin.H{"error": "message not found"})
return
}
@@ -381,7 +497,13 @@ func (h *MessageHandler) Edit(c *gin.Context) {
c.JSON(http.StatusNotFound, gin.H{"error": "message data not available"})
return
}
- current := h.loadEffectiveEdits(ctx, []int64{msgID})[msgID]
+ editsMap, err := h.loadEffectiveEdits(ctx, []int64{msgID})
+ if err != nil {
+ log.Printf("edit %d: load edits: %v", msgID, err)
+ c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to load edits"})
+ return
+ }
+ current := editsMap[msgID]
// Idempotency: nothing is sent when the effective data would not change.
var doc []byte
@@ -431,13 +553,13 @@ func (h *MessageHandler) Edit(c *gin.Context) {
return
}
now := float64(time.Now().UnixMicro()) / 1e6
- tx, err := h.q().Begin(ctx)
+ tx, commit, rollback, err := beginOrReuseTx(ctx, h.q())
if err != nil {
log.Printf("edit %d: begin: %v", msgID, err)
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to send edit"})
return
}
- defer tx.Rollback(ctx)
+ defer rollback()
var files message.Files
onRollback(c, func() { files.Cleanup() })
@@ -467,9 +589,9 @@ func (h *MessageHandler) Edit(c *gin.Context) {
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to send edit"})
return
}
- for _, addr := range t.to {
- if _, err := tx.Exec(ctx, "INSERT INTO msg_to (msg_id, addr) VALUES ($1, $2)", editID, addr); err != nil {
- log.Printf("edit %d: insert recipient %s: %v", msgID, addr, err)
+ if len(t.to) > 0 {
+ if _, err := tx.Exec(ctx, "INSERT INTO msg_to (msg_id, addr) SELECT $1, unnest($2::text[])", editID, t.to); err != nil {
+ log.Printf("edit %d: insert recipients: %v", msgID, err)
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to send edit"})
return
}
@@ -485,7 +607,7 @@ func (h *MessageHandler) Edit(c *gin.Context) {
firstHash = hash
}
}
- if err := tx.Commit(ctx); err != nil {
+ if err := commit(); err != nil {
log.Printf("edit %d: commit: %v", msgID, err)
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to send edit"})
return
@@ -494,11 +616,12 @@ func (h *MessageHandler) Edit(c *gin.Context) {
// fmsgd's outbound sender skips the local domain, so local recipients
// have their delivery resolved here, as Send does.
afterCommit(c, func() {
+ postCtx := context.WithoutCancel(ctx)
plain := *h
plain.query = nil
for i, t := range targets {
- plain.recordSend(identity, now, size)
- plain.resolveLocalDelivery(ctx, "msg_to", editIDs[i], h.LocalDomain, t.to)
+ plain.recordSend(postCtx, identity, now, size)
+ plain.resolveLocalDelivery(postCtx, "msg_to", editIDs[i], h.LocalDomain, t.to)
}
})
diff --git a/internal/handlers/edits_integration_test.go b/internal/handlers/edits_integration_test.go
index a1d90cd..1df8275 100644
--- a/internal/handlers/edits_integration_test.go
+++ b/internal/handlers/edits_integration_test.go
@@ -229,7 +229,7 @@ func TestEditIgnoresForgedAndMalformed(t *testing.T) {
t.Fatalf("data = %q", got)
}
for _, rid := range []int64{forged, malformed} {
- if _, ok := a.h.editSubject(ctx, rid); ok {
+ if _, ok, _ := a.h.editSubject(ctx, rid); ok {
t.Errorf("message %d recognised as an edit", rid)
}
}
diff --git a/internal/handlers/hub.go b/internal/handlers/hub.go
index 331f5cf..06796b4 100644
--- a/internal/handlers/hub.go
+++ b/internal/handlers/hub.go
@@ -7,6 +7,7 @@ import (
"strconv"
"strings"
"sync"
+ syncatomic "sync/atomic"
"time"
"github.com/jackc/pgx/v5"
@@ -32,6 +33,72 @@ type wsEnvelope struct {
Data any `json:"data"`
}
+const (
+ defaultPushWorkers = 8
+ defaultPushQueueSize = 256
+ msgClassCacheSize = 1024
+)
+
+type msgClassKind uint8
+
+const (
+ msgClassNormal msgClassKind = iota
+ msgClassReaction
+ msgClassEdit
+)
+
+type msgClassification struct {
+ kind msgClassKind
+ subject int64
+}
+
+// msgClassCache is a bounded FIFO cache of immutable sent-message
+// classifications (normal / reaction / edit) so K-recipient fan-out does not
+// repeat DB and disk classification queries for every recipient.
+type msgClassCache struct {
+ mu sync.Mutex
+ m map[int64]msgClassification
+ ring [msgClassCacheSize]int64
+ pos int
+ full bool
+}
+
+func (c *msgClassCache) get(id int64) (msgClassification, bool) {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ if c.m == nil {
+ return msgClassification{}, false
+ }
+ v, ok := c.m[id]
+ return v, ok
+}
+
+func (c *msgClassCache) put(id int64, cls msgClassification) {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ if c.m == nil {
+ c.m = make(map[int64]msgClassification, msgClassCacheSize)
+ }
+ if _, exists := c.m[id]; exists {
+ return
+ }
+ if c.full {
+ delete(c.m, c.ring[c.pos])
+ }
+ c.ring[c.pos] = id
+ c.m[id] = cls
+ c.pos++
+ if c.pos == len(c.ring) {
+ c.pos = 0
+ c.full = true
+ }
+}
+
+type pushJob struct {
+ msgID int64
+ addr string
+}
+
// Hub maintains the set of connected WebSocket clients and fans out database
// notifications to the clients they pertain to. A single dedicated PostgreSQL
// connection LISTENs on new_msg for the whole process, so the number of
@@ -43,23 +110,42 @@ type Hub struct {
buildItem func(ctx context.Context, msgID int64, recipient string) (*messageListItem, error)
// notifyPush, when non-nil, dispatches a Web Push for a new_msg
- // notification. It runs independently of WebSocket fan-out so pushes are
- // delivered even when the recipient has no live WebSocket.
+ // notification. It runs on a bounded worker pool independently of
+ // WebSocket fan-out so pushes are delivered even when the recipient has no
+ // live WebSocket.
notifyPush func(ctx context.Context, msgID int64, addr string)
// reactionSubject, when non-nil, reports the subject message of msgID
// when msgID is an FMSG-005 reaction. A reaction is pushed to its
// recipients as a reaction event carrying the refreshed subject, never
- // as new_msg.
- reactionSubject func(ctx context.Context, msgID int64) (int64, bool)
+ // as new_msg. Transient errors are returned so the hub does not cache a
+ // false negative.
+ reactionSubject func(ctx context.Context, msgID int64) (int64, bool, error)
// editSubject, when non-nil, reports the subject message of msgID when
// msgID is an FMSG-008 edit. An edit is pushed to its recipients as an
// edit event carrying the refreshed subject, never as a new message.
- editSubject func(ctx context.Context, msgID int64) (int64, bool)
+ // Transient errors are returned so the hub does not cache a false negative.
+ editSubject func(ctx context.Context, msgID int64) (int64, bool, error)
+
+ // indicatorParticipants and threadRoot split indicator audience lookup so
+ // routeIndicator can skip the recursive root CTE when no participant has a
+ // connected WebSocket. indicatorAudience is kept as a fallback hook for
+ // tests.
+ indicatorParticipants func(ctx context.Context, msgID int64) ([]string, error)
+ threadRoot func(ctx context.Context, msgID int64) (int64, error)
+ indicatorAudience func(ctx context.Context, msgID int64) ([]string, int64, error)
+
+ classCache msgClassCache
- // indicatorAudience reports a message's participants and its thread's
- // first message, for FMSG-006 indicators.
- indicatorAudience func(ctx context.Context, msgID int64) ([]string, int64, error)
+ pushWorkers int
+ pushQueueSize int
+ pushMu sync.Mutex
+ pushCh chan pushJob
+ pushCtx context.Context
+ pushCancel context.CancelFunc
+ pushClosed bool
+ pushWG sync.WaitGroup
+ pushDrops syncatomic.Uint64
mu sync.RWMutex
// registry maps a lower-cased user address to the set of that user's
@@ -73,14 +159,102 @@ func (h *Hub) SetPushNotifier(fn func(ctx context.Context, msgID int64, addr str
h.notifyPush = fn
}
+// PushDrops returns the total number of Web Push jobs dropped because the
+// bounded push queue was full.
+func (h *Hub) PushDrops() uint64 {
+ return h.pushDrops.Load()
+}
+
+// Close shuts down the bounded Web Push worker pool, cancelling queued and
+// in-flight pushes and waiting until all workers have exited.
+func (h *Hub) Close() {
+ _ = h.CloseContext(context.Background())
+}
+
+// CloseContext shuts down the bounded Web Push worker pool, cancelling its
+// push context so queued jobs are skipped and in-flight pushes abort promptly,
+// and waits for workers to exit until ctx is cancelled.
+func (h *Hub) CloseContext(ctx context.Context) error {
+ h.pushMu.Lock()
+ if !h.pushClosed {
+ h.pushClosed = true
+ if h.pushCancel != nil {
+ h.pushCancel()
+ }
+ if h.pushCh != nil {
+ close(h.pushCh)
+ }
+ }
+ h.pushMu.Unlock()
+
+ if ctx == nil {
+ h.pushWG.Wait()
+ return nil
+ }
+ done := make(chan struct{})
+ go func() {
+ h.pushWG.Wait()
+ close(done)
+ }()
+ select {
+ case <-done:
+ return nil
+ case <-ctx.Done():
+ return ctx.Err()
+ }
+}
+
+func (h *Hub) enqueuePush(msgID int64, addr string) {
+ h.pushMu.Lock()
+ if h.pushClosed {
+ h.pushMu.Unlock()
+ return
+ }
+ if h.pushCh == nil {
+ workers := h.pushWorkers
+ if workers <= 0 {
+ workers = defaultPushWorkers
+ }
+ qsize := h.pushQueueSize
+ if qsize <= 0 {
+ qsize = defaultPushQueueSize
+ }
+ h.pushCtx, h.pushCancel = context.WithCancel(context.Background())
+ h.pushCh = make(chan pushJob, qsize)
+ h.pushWG.Add(workers)
+ for range workers {
+ go h.pushWorker(h.pushCtx)
+ }
+ }
+ select {
+ case h.pushCh <- pushJob{msgID: msgID, addr: addr}:
+ default:
+ drops := h.pushDrops.Add(1)
+ log.Printf("ws hub: push queue full, dropping push for msg %d to %s (total dropped: %d)", msgID, addr, drops)
+ }
+ h.pushMu.Unlock()
+}
+
+func (h *Hub) pushWorker(pushCtx context.Context) {
+ defer h.pushWG.Done()
+ for job := range h.pushCh {
+ if pushCtx.Err() != nil {
+ return
+ }
+ h.notifyPush(pushCtx, job.msgID, job.addr)
+ }
+}
+
// NewHub creates a Hub that builds pushed message payloads via msgs.
func NewHub(msgs *MessageHandler) *Hub {
return &Hub{
- buildItem: msgs.messageItemFor,
- reactionSubject: msgs.reactionSubject,
- editSubject: msgs.editSubject,
- indicatorAudience: msgs.indicatorAudience,
- registry: make(map[string]map[*wsClient]struct{}),
+ buildItem: msgs.messageItemFor,
+ reactionSubject: msgs.reactionSubject,
+ editSubject: msgs.editSubject,
+ indicatorParticipants: msgs.indicatorParticipants,
+ threadRoot: msgs.threadRoot,
+ indicatorAudience: msgs.indicatorAudience,
+ registry: make(map[string]map[*wsClient]struct{}),
}
}
@@ -184,33 +358,67 @@ func (h *Hub) listen(ctx context.Context, onConnected func()) error {
}
}
+// classifyNewMsg classifies an immutable sent message once and caches the
+// result so multi-recipient fan-out avoids repeated DB/disk queries. Transient
+// classification errors are not cached so subsequent recipients retry.
+func (h *Hub) classifyNewMsg(ctx context.Context, msgID int64) msgClassification {
+ if h.reactionSubject == nil && h.editSubject == nil {
+ return msgClassification{kind: msgClassNormal}
+ }
+ if cls, ok := h.classCache.get(msgID); ok {
+ return cls
+ }
+ cls := msgClassification{kind: msgClassNormal}
+ cacheable := true
+ if h.reactionSubject != nil {
+ subject, ok, err := h.reactionSubject(ctx, msgID)
+ if err != nil {
+ cacheable = false
+ } else if ok {
+ cls = msgClassification{kind: msgClassReaction, subject: subject}
+ }
+ }
+ if cls.kind == msgClassNormal && h.editSubject != nil {
+ subject, ok, err := h.editSubject(ctx, msgID)
+ if err != nil {
+ cacheable = false
+ } else if ok {
+ cls = msgClassification{kind: msgClassEdit, subject: subject}
+ }
+ }
+ if cacheable {
+ h.classCache.put(msgID, cls)
+ }
+ return cls
+}
+
// route handles one notification on channel for message msgID and address
// addr.
func (h *Hub) route(ctx context.Context, channel string, msgID int64, addr string) {
switch channel {
case "new_msg":
- if h.reactionSubject != nil {
- if subject, ok := h.reactionSubject(ctx, msgID); ok {
- // FMSG-005: a reaction is a low-priority event on its
- // subject, not a new message. No Web Push is sent.
- h.dispatch(ctx, subject, addr, eventReaction)
- return
- }
+ if h.notifyPush == nil && !h.hasClients(addr) {
+ return
}
- if h.editSubject != nil {
- if subject, ok := h.editSubject(ctx, msgID); ok {
- // FMSG-008: an edit is a low-priority event on its
- // subject, not a new message. No Web Push is sent.
- h.dispatch(ctx, subject, addr, eventEdit)
- return
- }
+ cls := h.classifyNewMsg(ctx, msgID)
+ switch cls.kind {
+ case msgClassReaction:
+ // FMSG-005: a reaction is a low-priority event on its
+ // subject, not a new message. No Web Push is sent.
+ h.dispatch(ctx, cls.subject, addr, eventReaction)
+ return
+ case msgClassEdit:
+ // FMSG-008: an edit is a low-priority event on its
+ // subject, not a new message. No Web Push is sent.
+ h.dispatch(ctx, cls.subject, addr, eventEdit)
+ return
}
- // Web Push runs in its own goroutine: it is network I/O to many
+ // Web Push runs on a bounded worker pool: it is network I/O to many
// endpoints and must not stall the single listener. It is
// dispatched here, alongside (not inside) dispatch, so a push is
// sent even when the recipient has no live WebSocket.
if h.notifyPush != nil {
- go h.notifyPush(ctx, msgID, addr)
+ h.enqueuePush(msgID, addr)
}
h.dispatch(ctx, msgID, addr, eventNewMsg)
case "delivered":
@@ -308,6 +516,20 @@ func (h *Hub) dispatchTrash(ctx context.Context, msgID int64, addr string) {
h.send(clients, msgID, wsEnvelope{Type: eventTrash, Data: item})
}
+// hasClients reports whether at least one client is connected as addr.
+func (h *Hub) hasClients(addr string) bool {
+ h.mu.RLock()
+ defer h.mu.RUnlock()
+ return len(h.registry[strings.ToLower(addr)]) > 0
+}
+
+// hasAnyClients reports whether any WebSocket client is currently connected.
+func (h *Hub) hasAnyClients() bool {
+ h.mu.RLock()
+ defer h.mu.RUnlock()
+ return len(h.registry) > 0
+}
+
// clientsOf lists the clients connected as addr.
func (h *Hub) clientsOf(addr string) []*wsClient {
h.mu.RLock()
@@ -320,6 +542,26 @@ func (h *Hub) clientsOf(addr string) []*wsClient {
return clients
}
+// clientsOfParticipants collects connected clients for every unique address in
+// addrs except exclude, under a single RLock acquisition.
+func (h *Hub) clientsOfParticipants(addrs []string, exclude string) []*wsClient {
+ seen := map[string]bool{strings.ToLower(exclude): true}
+ h.mu.RLock()
+ defer h.mu.RUnlock()
+ var clients []*wsClient
+ for _, a := range addrs {
+ k := strings.ToLower(a)
+ if seen[k] {
+ continue
+ }
+ seen[k] = true
+ for c := range h.registry[k] {
+ clients = append(clients, c)
+ }
+ }
+ return clients
+}
+
// send marshals env and queues it on each client.
func (h *Hub) send(clients []*wsClient, msgID int64, env wsEnvelope) {
payload, err := json.Marshal(env)
@@ -350,26 +592,38 @@ func (h *Hub) routeIndicator(ctx context.Context, payload string) {
log.Printf("ws hub: ignoring malformed indicator payload %q", payload)
return
}
- if h.indicatorAudience == nil {
- return
- }
- addrs, root, err := h.indicatorAudience(ctx, ind.ID)
- if err != nil {
- log.Printf("ws hub: indicator on %d: %v", ind.ID, err)
+ if !h.hasAnyClients() {
return
}
- ind.RootID = root
var clients []*wsClient
- seen := map[string]bool{strings.ToLower(ind.From): true}
- for _, a := range addrs {
- k := strings.ToLower(a)
- if seen[k] {
- continue
+ if h.indicatorParticipants != nil && h.threadRoot != nil {
+ addrs, err := h.indicatorParticipants(ctx, ind.ID)
+ if err != nil {
+ log.Printf("ws hub: indicator on %d: %v", ind.ID, err)
+ return
}
- seen[k] = true
- clients = append(clients, h.clientsOf(a)...)
- }
- if len(clients) == 0 {
+ clients = h.clientsOfParticipants(addrs, ind.From)
+ if len(clients) == 0 {
+ return
+ }
+ root, err := h.threadRoot(ctx, ind.ID)
+ if err != nil {
+ log.Printf("ws hub: indicator root on %d: %v", ind.ID, err)
+ return
+ }
+ ind.RootID = root
+ } else if h.indicatorAudience != nil {
+ addrs, root, err := h.indicatorAudience(ctx, ind.ID)
+ if err != nil {
+ log.Printf("ws hub: indicator on %d: %v", ind.ID, err)
+ return
+ }
+ clients = h.clientsOfParticipants(addrs, ind.From)
+ if len(clients) == 0 {
+ return
+ }
+ ind.RootID = root
+ } else {
return
}
h.send(clients, ind.ID, wsEnvelope{Type: eventIndicator, Data: ind})
diff --git a/internal/handlers/hub_test.go b/internal/handlers/hub_test.go
index cb64810..888e98b 100644
--- a/internal/handlers/hub_test.go
+++ b/internal/handlers/hub_test.go
@@ -3,7 +3,10 @@ package handlers
import (
"context"
"encoding/json"
+ "errors"
+ syncatomic "sync/atomic"
"testing"
+ "time"
)
func newTestHub() *Hub {
@@ -126,3 +129,274 @@ func TestParseNotifyPayload(t *testing.T) {
}
}
}
+
+func TestHubRoute_SkipsClassificationWhenNoPushAndNoClients(t *testing.T) {
+ var reactCalls, editCalls int
+ hub := newTestHub()
+ hub.reactionSubject = func(_ context.Context, _ int64) (int64, bool, error) {
+ reactCalls++
+ return 0, false, nil
+ }
+ hub.editSubject = func(_ context.Context, _ int64) (int64, bool, error) {
+ editCalls++
+ return 0, false, nil
+ }
+
+ hub.route(context.Background(), "new_msg", 42, "@offline@x")
+ if reactCalls != 0 || editCalls != 0 {
+ t.Fatalf("classification called for offline user with push disabled: react=%d edit=%d", reactCalls, editCalls)
+ }
+}
+
+func TestHubRoute_CachesClassificationAcrossRecipients(t *testing.T) {
+ var reactCalls, editCalls int
+ hub := newTestHub()
+ hub.reactionSubject = func(_ context.Context, id int64) (int64, bool, error) {
+ reactCalls++
+ if id == 100 {
+ return 10, true, nil
+ }
+ return 0, false, nil
+ }
+ hub.editSubject = func(_ context.Context, _ int64) (int64, bool, error) {
+ editCalls++
+ return 0, false, nil
+ }
+
+ alice := newTestClient("@alice@x")
+ bob := newTestClient("@bob@x")
+ carol := newTestClient("@carol@x")
+ hub.Register(alice)
+ hub.Register(bob)
+ hub.Register(carol)
+
+ for _, addr := range []string{"@alice@x", "@bob@x", "@carol@x"} {
+ hub.route(context.Background(), "new_msg", 100, addr)
+ }
+ if reactCalls != 1 || editCalls != 0 {
+ t.Fatalf("reaction classification calls = (%d, %d), want (1, 0)", reactCalls, editCalls)
+ }
+
+ // Normal message across multiple recipients also classifies only once.
+ for _, addr := range []string{"@alice@x", "@bob@x", "@carol@x"} {
+ hub.route(context.Background(), "new_msg", 200, addr)
+ }
+ if reactCalls != 2 || editCalls != 1 {
+ t.Fatalf("normal classification calls = (%d, %d), want (2, 1)", reactCalls, editCalls)
+ }
+
+ // Cache ring remains strictly bounded to msgClassCacheSize.
+ var cache msgClassCache
+ for i := int64(1); i <= msgClassCacheSize+50; i++ {
+ cache.put(i, msgClassification{kind: msgClassNormal})
+ }
+ if got := len(cache.m); got != msgClassCacheSize {
+ t.Fatalf("msgClassCache size = %d, want %d", got, msgClassCacheSize)
+ }
+ if _, ok := cache.get(1); ok {
+ t.Fatal("oldest entry should have been evicted from msgClassCache")
+ }
+ if _, ok := cache.get(msgClassCacheSize + 50); !ok {
+ t.Fatal("newest entry should still be in msgClassCache")
+ }
+}
+
+func TestHubRoute_DoesNotCacheTransientClassificationError(t *testing.T) {
+ var reactCalls, editCalls int
+ transientErr := errors.New("transient db timeout")
+
+ hub := newTestHub()
+ hub.reactionSubject = func(_ context.Context, id int64) (int64, bool, error) {
+ reactCalls++
+ if id == 300 {
+ if reactCalls == 1 {
+ return 0, false, transientErr
+ }
+ return 10, true, nil
+ }
+ return 0, false, nil
+ }
+ hub.editSubject = func(_ context.Context, id int64) (int64, bool, error) {
+ editCalls++
+ if id == 400 {
+ if editCalls == 1 {
+ return 0, false, transientErr
+ }
+ return 20, true, nil
+ }
+ return 0, false, nil
+ }
+
+ alice := newTestClient("@alice@x")
+ bob := newTestClient("@bob@x")
+ carol := newTestClient("@carol@x")
+ hub.Register(alice)
+ hub.Register(bob)
+ hub.Register(carol)
+
+ // First recipient hits a transient reaction classification error: must NOT cache.
+ hub.route(context.Background(), "new_msg", 300, "@alice@x")
+ // Second recipient re-runs classification, succeeds as a reaction, and caches.
+ hub.route(context.Background(), "new_msg", 300, "@bob@x")
+ // Third recipient uses the cached reaction classification.
+ hub.route(context.Background(), "new_msg", 300, "@carol@x")
+
+ if reactCalls != 2 {
+ t.Fatalf("reactionSubject calls = %d, want 2 (retry after transient error, then cache)", reactCalls)
+ }
+ for _, c := range []*wsClient{bob, carol} {
+ select {
+ case raw := <-c.send:
+ var env struct {
+ Type string `json:"type"`
+ Data messageListItem `json:"data"`
+ }
+ if err := json.Unmarshal(raw, &env); err != nil {
+ t.Fatalf("unmarshal: %v", err)
+ }
+ if env.Type != eventReaction || env.Data.ID != 10 {
+ t.Fatalf("%s got (%s, %d), want (%s, 10)", c.addr, env.Type, env.Data.ID, eventReaction)
+ }
+ default:
+ t.Fatalf("%s did not receive reaction event", c.addr)
+ }
+ }
+
+ // Drain alice's fallback frame from the transient error.
+ <-alice.send
+
+ // Transient edit classification error is also not cached.
+ editCalls = 0
+ hub.route(context.Background(), "new_msg", 400, "@alice@x")
+ hub.route(context.Background(), "new_msg", 400, "@bob@x")
+ hub.route(context.Background(), "new_msg", 400, "@carol@x")
+ if editCalls != 2 {
+ t.Fatalf("editSubject calls = %d, want 2 (retry after transient error, then cache)", editCalls)
+ }
+ for _, c := range []*wsClient{bob, carol} {
+ select {
+ case raw := <-c.send:
+ var env struct {
+ Type string `json:"type"`
+ Data messageListItem `json:"data"`
+ }
+ if err := json.Unmarshal(raw, &env); err != nil {
+ t.Fatalf("unmarshal: %v", err)
+ }
+ if env.Type != eventEdit || env.Data.ID != 20 {
+ t.Fatalf("%s got (%s, %d), want (%s, 20)", c.addr, env.Type, env.Data.ID, eventEdit)
+ }
+ default:
+ t.Fatalf("%s did not receive edit event", c.addr)
+ }
+ }
+}
+
+func TestHubPushWorkerPool_BoundedConcurrencyAndDrain(t *testing.T) {
+ hub := newTestHub()
+ hub.pushWorkers = 2
+ hub.pushQueueSize = 16
+
+ const total = 8
+ allDone := make(chan struct{})
+ var inFlight, maxInFlight, completed syncatomic.Int32
+ hub.SetPushNotifier(func(_ context.Context, _ int64, _ string) {
+ cur := inFlight.Add(1)
+ for {
+ prev := maxInFlight.Load()
+ if cur <= prev || maxInFlight.CompareAndSwap(prev, cur) {
+ break
+ }
+ }
+ time.Sleep(15 * time.Millisecond)
+ inFlight.Add(-1)
+ if completed.Add(1) == total {
+ close(allDone)
+ }
+ })
+
+ for i := int64(1); i <= total; i++ {
+ hub.route(context.Background(), "new_msg", i, "@offline@x")
+ }
+ select {
+ case <-allDone:
+ case <-time.After(2 * time.Second):
+ t.Fatalf("timed out waiting for pushes: completed=%d/%d", completed.Load(), total)
+ }
+ hub.Close()
+
+ if got := completed.Load(); got != total {
+ t.Fatalf("completed pushes = %d, want %d", got, total)
+ }
+ if got := maxInFlight.Load(); got > 2 {
+ t.Fatalf("max concurrent pushes = %d, exceeds worker pool bound 2", got)
+ }
+}
+
+func TestHubCloseContext_CancelsQueuedAndInFlightPushes(t *testing.T) {
+ hub := newTestHub()
+ hub.pushWorkers = 2
+ hub.pushQueueSize = 4
+
+ started := make(chan struct{}, 2)
+ var called, cancelled syncatomic.Int32
+ hub.SetPushNotifier(func(ctx context.Context, _ int64, _ string) {
+ called.Add(1)
+ started <- struct{}{}
+ <-ctx.Done()
+ cancelled.Add(1)
+ })
+
+ // Fill both workers, fill the 4-slot queue, and trigger 2 drops.
+ for i := int64(1); i <= 8; i++ {
+ hub.route(context.Background(), "new_msg", i, "@offline@x")
+ if i == 2 {
+ // Wait until both workers have pulled their jobs before filling the queue.
+ <-started
+ <-started
+ }
+ }
+ if got := hub.PushDrops(); got != 2 {
+ t.Fatalf("PushDrops() = %d, want 2", got)
+ }
+
+ closeCtx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
+ defer cancel()
+ start := time.Now()
+ if err := hub.CloseContext(closeCtx); err != nil {
+ t.Fatalf("CloseContext returned error: %v", err)
+ }
+ if elapsed := time.Since(start); elapsed > 500*time.Millisecond {
+ t.Fatalf("CloseContext took %s, expected prompt cancellation well before deadline", elapsed)
+ }
+ if got := called.Load(); got != 2 {
+ t.Fatalf("notifyPush called %d times, want 2 (queued jobs should be skipped after cancel)", got)
+ }
+ if got := cancelled.Load(); got != 2 {
+ t.Fatalf("in-flight pushes observing cancellation = %d, want 2", got)
+ }
+}
+
+func TestHubCloseContext_RespectsDeadlineWhenWorkerBlocks(t *testing.T) {
+ hub := newTestHub()
+ hub.pushWorkers = 1
+ hub.pushQueueSize = 1
+
+ started := make(chan struct{})
+ release := make(chan struct{})
+ t.Cleanup(func() { close(release) })
+ hub.SetPushNotifier(func(_ context.Context, _ int64, _ string) {
+ close(started)
+ <-release
+ })
+
+ hub.route(context.Background(), "new_msg", 1, "@offline@x")
+ <-started
+
+ closeCtx, cancel := context.WithTimeout(context.Background(), 30*time.Millisecond)
+ defer cancel()
+ err := hub.CloseContext(closeCtx)
+ if !errors.Is(err, context.DeadlineExceeded) {
+ t.Fatalf("CloseContext err = %v, want context.DeadlineExceeded", err)
+ }
+}
diff --git a/internal/handlers/indicators.go b/internal/handlers/indicators.go
index 83625c5..66b3fa9 100644
--- a/internal/handlers/indicators.go
+++ b/internal/handlers/indicators.go
@@ -56,8 +56,9 @@ type indicateInput struct {
// indicatorThrottle drops indicators set more often than indicatorMinInterval
// for one address on one message. Clears are never throttled.
type indicatorThrottle struct {
- mu sync.Mutex
- last map[string]time.Time
+ mu sync.Mutex
+ last map[string]time.Time
+ lastSweep time.Time
}
var throttle = &indicatorThrottle{last: map[string]time.Time{}}
@@ -65,15 +66,19 @@ var throttle = &indicatorThrottle{last: map[string]time.Time{}}
func (t *indicatorThrottle) allow(key string, now time.Time) bool {
t.mu.Lock()
defer t.mu.Unlock()
+ if t.last == nil {
+ t.last = make(map[string]time.Time)
+ }
if prev, ok := t.last[key]; ok && now.Sub(prev) < indicatorMinInterval {
return false
}
- if len(t.last) > 10000 {
+ if len(t.last) > 10000 && (t.lastSweep.IsZero() || now.Sub(t.lastSweep) >= indicatorMinInterval) {
for k, v := range t.last {
if now.Sub(v) >= indicatorMinInterval {
delete(t.last, k)
}
}
+ t.lastSweep = now
}
t.last[key] = now
return true
@@ -113,7 +118,19 @@ func (h *MessageHandler) Indicate(c *gin.Context) {
}
ctx := c.Request.Context()
- subject, _, err := h.fetchMessage(ctx, msgID)
+ var fromAddr string
+ var timeSent *float64
+ var terminal, participant bool
+ var trashState *string
+ err := h.q().QueryRow(ctx, `
+ SELECT m.from_addr, m.time_sent, m.is_terminal,
+ (lower(m.from_addr) = $2
+ OR EXISTS (SELECT 1 FROM msg_to WHERE msg_id = m.id AND lower(addr) = $2)
+ OR EXISTS (SELECT 1 FROM msg_add_to WHERE msg_id = m.id AND lower(addr) = $2)),
+ CASE WHEN EXISTS (SELECT 1 FROM fmsg_api_trash WHERE addr = $2)
+ THEN fmsg_api_trash_state($2, m.id) END
+ FROM msg m WHERE m.id = $1`, msgID, strings.ToLower(identity),
+ ).Scan(&fromAddr, &timeSent, &terminal, &participant, &trashState)
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
c.JSON(http.StatusNotFound, gin.H{"error": "message not found"})
@@ -123,19 +140,19 @@ func (h *MessageHandler) Indicate(c *gin.Context) {
}
return
}
- if draftHidden([]string{identity}, subject.From, subject.Time) || purgedFor(ctx, h.q(), identity, msgID) {
+ if draftHidden([]string{identity}, fromAddr, timeSent) || (trashState != nil && *trashState == trashPurged) {
c.JSON(http.StatusNotFound, gin.H{"error": "message not found"})
return
}
- if !strings.EqualFold(subject.From, identity) && !isRecipient(subject.To, identity) && !addToContains(subject.AddTo, identity) {
+ if !participant {
c.JSON(http.StatusForbidden, gin.H{"error": "only participants may show an indicator on a message"})
return
}
- if subject.Time == nil {
+ if timeSent == nil {
c.JSON(http.StatusConflict, gin.H{"error": "cannot show an indicator on a draft"})
return
}
- if subject.Terminal {
+ if terminal {
c.JSON(http.StatusConflict, gin.H{"error": "message is terminal; it cannot be replied to"})
return
}
@@ -157,33 +174,37 @@ func (h *MessageHandler) Indicate(c *gin.Context) {
c.Status(http.StatusAccepted)
}
-// indicatorAudience returns every participant of message msgID (its sender,
-// recipients, and each add-to batch's adder and added recipients) and the id
-// of its thread's first message.
-func (h *MessageHandler) indicatorAudience(ctx context.Context, msgID int64) ([]string, int64, error) {
+// indicatorParticipants returns every participant of message msgID (its sender,
+// recipients, and each add-to batch's adder and added recipients).
+func (h *MessageHandler) indicatorParticipants(ctx context.Context, msgID int64) ([]string, error) {
rows, err := h.q().Query(ctx, `
SELECT from_addr FROM msg WHERE id = $1
UNION SELECT addr FROM msg_to WHERE msg_id = $1
UNION SELECT add_to_from FROM msg_add_to_batch WHERE msg_id = $1
UNION SELECT addr FROM msg_add_to WHERE msg_id = $1`, msgID)
if err != nil {
- return nil, 0, err
+ return nil, err
}
var addrs []string
for rows.Next() {
var a string
if err := rows.Scan(&a); err != nil {
rows.Close()
- return nil, 0, err
+ return nil, err
}
addrs = append(addrs, a)
}
rows.Close()
if err := rows.Err(); err != nil {
- return nil, 0, err
+ return nil, err
}
+ return addrs, nil
+}
+
+// threadRoot returns the id of msgID's thread's first message.
+func (h *MessageHandler) threadRoot(ctx context.Context, msgID int64) (int64, error) {
var root int64
- err = h.q().QueryRow(ctx, `
+ err := h.q().QueryRow(ctx, `
WITH RECURSIVE chain AS (
SELECT id, pid, 0 AS depth FROM msg WHERE id = $1
UNION ALL
@@ -191,10 +212,25 @@ func (h *MessageHandler) indicatorAudience(ctx context.Context, msgID int64) ([]
)
SELECT id FROM chain ORDER BY depth DESC LIMIT 1`, msgID).Scan(&root)
if err != nil && !errors.Is(err, pgx.ErrNoRows) {
- return nil, 0, err
+ return 0, err
}
if root == 0 {
root = msgID
}
+ return root, nil
+}
+
+// indicatorAudience returns every participant of message msgID (its sender,
+// recipients, and each add-to batch's adder and added recipients) and the id
+// of its thread's first message.
+func (h *MessageHandler) indicatorAudience(ctx context.Context, msgID int64) ([]string, int64, error) {
+ addrs, err := h.indicatorParticipants(ctx, msgID)
+ if err != nil {
+ return nil, 0, err
+ }
+ root, err := h.threadRoot(ctx, msgID)
+ if err != nil {
+ return nil, 0, err
+ }
return addrs, root, nil
}
diff --git a/internal/handlers/indicators_test.go b/internal/handlers/indicators_test.go
index af1f68e..01edca2 100644
--- a/internal/handlers/indicators_test.go
+++ b/internal/handlers/indicators_test.go
@@ -4,6 +4,7 @@ import (
"context"
"encoding/json"
"errors"
+ "fmt"
"testing"
"time"
)
@@ -74,3 +75,85 @@ func TestIndicatorThrottle(t *testing.T) {
t.Error("allowed again after the interval")
}
}
+
+func TestIndicatorThrottle_SweepThrottled(t *testing.T) {
+ th := &indicatorThrottle{last: make(map[string]time.Time, 10005)}
+ t0 := time.Unix(1000, 0)
+ // Seed >10000 active entries at t0.
+ for i := range 10002 {
+ th.last[fmt.Sprintf("u%d|1", i)] = t0
+ }
+
+ // First call triggers sweep (none expired yet) and records lastSweep = t0+100ms.
+ t1 := t0.Add(100 * time.Millisecond)
+ if !th.allow("fresh1|1", t1) {
+ t.Fatal("fresh1 refused")
+ }
+ if !th.lastSweep.Equal(t1) {
+ t.Fatalf("lastSweep = %v, want %v", th.lastSweep, t1)
+ }
+
+ // At t0 + indicatorMinInterval, the original 10002 entries are expired, but
+ // less than indicatorMinInterval has passed since lastSweep (t1), so sweep
+ // must NOT run yet.
+ t2 := t0.Add(indicatorMinInterval)
+ if !th.allow("fresh2|1", t2) {
+ t.Fatal("fresh2 refused")
+ }
+ if len(th.last) < 10000 {
+ t.Fatalf("sweep ran prematurely before indicatorMinInterval elapsed since lastSweep: len=%d", len(th.last))
+ }
+
+ // Once indicatorMinInterval has elapsed since lastSweep, sweep runs and
+ // evicts the expired entries.
+ t3 := t1.Add(indicatorMinInterval)
+ if !th.allow("fresh3|1", t3) {
+ t.Fatal("fresh3 refused")
+ }
+ if len(th.last) > 5 {
+ t.Fatalf("sweep did not evict expired entries after interval: len=%d", len(th.last))
+ }
+}
+
+func TestHubRouteIndicator_SkipsThreadRootWhenNoParticipantConnected(t *testing.T) {
+ hub := newTestHub()
+ rootCalls := 0
+ hub.indicatorParticipants = func(_ context.Context, _ int64) ([]string, error) {
+ return []string{"@alice@x", "@bob@x"}, nil
+ }
+ hub.threadRoot = func(_ context.Context, _ int64) (int64, error) {
+ rootCalls++
+ return 3, nil
+ }
+
+ // Only an unrelated user (dave) is connected: threadRoot must be skipped.
+ dave := newTestClient("@dave@x")
+ hub.Register(dave)
+ hub.routeIndicator(context.Background(), `{"id":7,"from":"@bob@x","emoji":"✍️","ttl":6}`)
+ if rootCalls != 0 {
+ t.Fatalf("threadRoot called %d times when no participant connected, want 0", rootCalls)
+ }
+
+ // Once alice connects, threadRoot is queried and alice receives the indicator.
+ alice := newTestClient("@alice@x")
+ hub.Register(alice)
+ hub.routeIndicator(context.Background(), `{"id":7,"from":"@bob@x","emoji":"✍️","ttl":6}`)
+ if rootCalls != 1 {
+ t.Fatalf("threadRoot called %d times, want 1", rootCalls)
+ }
+ select {
+ case payload := <-alice.send:
+ var env struct {
+ Type string `json:"type"`
+ Data Indicator `json:"data"`
+ }
+ if err := json.Unmarshal(payload, &env); err != nil {
+ t.Fatal(err)
+ }
+ if env.Type != eventIndicator || env.Data.RootID != 3 {
+ t.Fatalf("unexpected indicator envelope: %+v", env)
+ }
+ default:
+ t.Fatal("alice did not receive indicator")
+ }
+}
diff --git a/internal/handlers/messages.go b/internal/handlers/messages.go
index 61023eb..59507a5 100644
--- a/internal/handlers/messages.go
+++ b/internal/handlers/messages.go
@@ -129,6 +129,11 @@ func formatDeliveredISO(t *float64) *string {
// lookup), since usage changes with every message. Errors talking to fmsgid
// are logged and left pending (no status written) rather than treated as a
// delivery failure; a failure to record usage is only logged.
+// localDeliveryOpTimeout bounds each individual database operation inside
+// resolveLocalDelivery so one stalled query cannot hang indefinitely while
+// large recipient fan-outs are not cut short by a single shared deadline.
+const localDeliveryOpTimeout = 5 * time.Second
+
func (h *MessageHandler) resolveLocalDelivery(ctx context.Context, table string, msgID int64, localDomain string, addrs []string) {
now := float64(time.Now().UnixMicro()) / 1e6
query := "UPDATE " + table + " SET time_delivered = $1, response_code = $2 WHERE msg_id = $3 AND addr = $4 AND time_delivered IS NULL AND response_code IS NULL"
@@ -138,13 +143,16 @@ func (h *MessageHandler) resolveLocalDelivery(ctx context.Context, table string,
if !strings.EqualFold(domain, localDomain) {
continue // remote — fmsgd handles this
}
- detail, status, err := middleware.FetchFmsgIDDetail(h.IDURL, addr)
+ detail, status, err := middleware.FetchFmsgIDDetailContext(ctx, h.IDURL, addr)
if err != nil {
log.Printf("resolve local delivery: fmsgid check %s: %v", addr, err)
continue
}
if size < 0 && status == http.StatusOK {
- if size, err = h.messageStoredSize(ctx, msgID); err != nil {
+ sizeCtx, cancelSize := context.WithTimeout(ctx, localDeliveryOpTimeout)
+ size, err = h.messageStoredSize(sizeCtx, msgID)
+ cancelSize()
+ if err != nil {
log.Printf("resolve local delivery: size of msg %d: %v", msgID, err)
size = -1
continue
@@ -161,7 +169,9 @@ func (h *MessageHandler) resolveLocalDelivery(ctx context.Context, table string,
} else if code == responseCodeUserFull {
log.Printf("resolve local delivery: msg %d to %s refused: over a receive limit", msgID, addr)
}
- tag, err := h.q().Exec(ctx, query, delivered, code, msgID, addr)
+ updateCtx, cancelUpdate := context.WithTimeout(ctx, localDeliveryOpTimeout)
+ tag, err := h.q().Exec(updateCtx, query, delivered, code, msgID, addr)
+ cancelUpdate()
if err != nil {
log.Printf("resolve local delivery: update %s msg %d addr %s: %v", table, msgID, addr, err)
continue
@@ -169,7 +179,7 @@ func (h *MessageHandler) resolveLocalDelivery(ctx context.Context, table string,
// Record usage only for the delivery made here, never for a row
// another request had already resolved.
if delivered != nil && tag.RowsAffected() > 0 {
- if err := middleware.RecordFmsgIDRecv(h.IDURL, addr, now, size); err != nil {
+ if err := middleware.RecordFmsgIDRecvContext(ctx, h.IDURL, addr, now, size); err != nil {
log.Printf("resolve local delivery: record recv usage %s msg %d: %v", addr, msgID, err)
}
}
@@ -370,14 +380,13 @@ func (h *MessageHandler) List(c *gin.Context) {
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to list messages"})
return
}
- defer rows.Close()
-
var messages []messageListItem
var msgIDs []int64
for rows.Next() {
var m messageListItem
var dataPath string
if err := rows.Scan(&m.ID, &m.Version, &m.PID, &m.NoReply, &m.Important, &m.Deflate, &m.Terminal, &m.Time, &m.SHA256, &m.PSHA256, &m.From, &m.Topic, &m.Type, &m.Size, &dataPath, &m.TimeRead, &m.Trash); err != nil {
+ rows.Close()
log.Printf("list messages scan: %v", err)
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to list messages"})
return
@@ -385,53 +394,27 @@ func (h *MessageHandler) List(c *gin.Context) {
m.HasPid = m.PID != nil
m.Read = m.TimeRead != nil
m.dataPath = dataPath
- m.ShortText = h.extractShortText(dataPath, m.Type)
messages = append(messages, m)
msgIDs = append(msgIDs, m.ID)
}
+ rows.Close()
+ if err := rows.Err(); err != nil {
+ log.Printf("list messages rows: %v", err)
+ c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to list messages"})
+ return
+ }
if len(messages) == 0 {
c.JSON(http.StatusOK, []messageListItem{})
return
}
- // Batch-load recipients.
- toMap, toDeliveryMap := h.loadRecipients(ctx, msgIDs)
- for i := range messages {
- messages[i].To = toMap[messages[i].ID]
- messages[i].ToDelivery = toDeliveryMap[messages[i].ID]
- }
-
- // Batch-load add_to batches.
- addToMap := h.loadAddToBatches(ctx, msgIDs)
- for i := range messages {
- messages[i].AddTo = addToMap[messages[i].ID]
- messages[i].HasAddTo = len(messages[i].AddTo) > 0
- }
-
- // Batch-load attachments.
- attRows, err := h.q().Query(ctx,
- "SELECT msg_id, filename, filesize FROM msg_attachment WHERE msg_id = ANY($1)",
- msgIDs,
- )
- if err == nil {
- attMap := make(map[int64][]models.Attachment)
- for attRows.Next() {
- var id int64
- var a models.Attachment
- if scanErr := attRows.Scan(&id, &a.Filename, &a.Size); scanErr == nil {
- attMap[id] = append(attMap[id], a)
- }
- }
- attRows.Close()
- for i := range messages {
- messages[i].Attachments = attMap[messages[i].ID]
- }
+ if err := h.enrichMessageList(ctx, messages, msgIDs); err != nil {
+ log.Printf("list messages enrich: %v", err)
+ c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to list messages"})
+ return
}
- h.populateListReactions(ctx, messages)
- h.populateListEdits(ctx, messages)
-
c.JSON(http.StatusOK, messages)
}
@@ -482,7 +465,6 @@ func (h *MessageHandler) Sent(c *gin.Context) {
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to list sent messages"})
return
}
- defer rows.Close()
var messages []messageListItem
var msgIDs []int64
@@ -490,68 +472,112 @@ func (h *MessageHandler) Sent(c *gin.Context) {
var m messageListItem
var dataPath string
if err := rows.Scan(&m.ID, &m.Version, &m.PID, &m.NoReply, &m.Important, &m.Deflate, &m.Terminal, &m.Time, &m.SHA256, &m.PSHA256, &m.From, &m.Topic, &m.Type, &m.Size, &dataPath, &m.Trash); err != nil {
+ rows.Close()
log.Printf("list sent messages scan: %v", err)
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to list sent messages"})
return
}
m.HasPid = m.PID != nil
m.dataPath = dataPath
- m.ShortText = h.extractShortText(dataPath, m.Type)
messages = append(messages, m)
msgIDs = append(msgIDs, m.ID)
}
+ rows.Close()
+ if err := rows.Err(); err != nil {
+ log.Printf("list sent messages rows: %v", err)
+ c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to list sent messages"})
+ return
+ }
if len(messages) == 0 {
c.JSON(http.StatusOK, []messageListItem{})
return
}
- // Batch-load recipients.
- toMap, toDeliveryMap := h.loadRecipients(ctx, msgIDs)
+ if err := h.enrichMessageList(ctx, messages, msgIDs); err != nil {
+ log.Printf("list sent messages enrich: %v", err)
+ c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to list sent messages"})
+ return
+ }
+
+ c.JSON(http.StatusOK, messages)
+}
+
+// enrichMessageList batch-loads recipients, add-to batches, attachments,
+// reactions, edits, and body previews for a scanned page of list items.
+func (h *MessageHandler) enrichMessageList(ctx context.Context, messages []messageListItem, msgIDs []int64) error {
+ toMap, toDeliveryMap, err := h.loadRecipients(ctx, msgIDs)
+ if err != nil {
+ return err
+ }
for i := range messages {
messages[i].To = toMap[messages[i].ID]
messages[i].ToDelivery = toDeliveryMap[messages[i].ID]
}
- // Batch-load add_to batches.
- addToMap := h.loadAddToBatches(ctx, msgIDs)
+ addToMap, err := h.loadAddToBatches(ctx, msgIDs)
+ if err != nil {
+ return err
+ }
for i := range messages {
messages[i].AddTo = addToMap[messages[i].ID]
messages[i].HasAddTo = len(messages[i].AddTo) > 0
}
- // Batch-load attachments.
attRows, err := h.q().Query(ctx,
"SELECT msg_id, filename, filesize FROM msg_attachment WHERE msg_id = ANY($1)",
msgIDs,
)
- if err == nil {
- attMap := make(map[int64][]models.Attachment)
- for attRows.Next() {
- var id int64
- var a models.Attachment
- if scanErr := attRows.Scan(&id, &a.Filename, &a.Size); scanErr == nil {
- attMap[id] = append(attMap[id], a)
- }
- }
- attRows.Close()
- for i := range messages {
- messages[i].Attachments = attMap[messages[i].ID]
+ if err != nil {
+ return err
+ }
+ attMap := make(map[int64][]models.Attachment)
+ for attRows.Next() {
+ var id int64
+ var a models.Attachment
+ if scanErr := attRows.Scan(&id, &a.Filename, &a.Size); scanErr != nil {
+ attRows.Close()
+ return scanErr
}
+ attMap[id] = append(attMap[id], a)
+ }
+ attRows.Close()
+ if err := attRows.Err(); err != nil {
+ return err
+ }
+ for i := range messages {
+ messages[i].Attachments = attMap[messages[i].ID]
}
- h.populateListReactions(ctx, messages)
- h.populateListEdits(ctx, messages)
-
- c.JSON(http.StatusOK, messages)
+ if err := h.populateListReactions(ctx, messages); err != nil {
+ return err
+ }
+ appliedEdits, err := h.populateListEdits(ctx, messages)
+ if err != nil {
+ return err
+ }
+ // Extract disk previews after closing DB cursors, skipping messages whose
+ // preview was already built from an applied FMSG-008 edit.
+ for i := range messages {
+ if !appliedEdits[messages[i].ID] {
+ messages[i].ShortText = h.extractShortText(messages[i].dataPath, messages[i].Type)
+ }
+ }
+ return nil
}
// Create handles POST /fmsg — creates a draft message.
func (h *MessageHandler) Create(c *gin.Context) {
identity := middleware.GetIdentity(c)
+ limitJSONBody(c, h.MaxDataSize)
+
var msg messageInput
if err := c.ShouldBindJSON(&msg); err != nil {
+ if isMaxBytesError(err) {
+ c.JSON(http.StatusRequestEntityTooLarge, gin.H{"error": "message data exceeds maximum size"})
+ return
+ }
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
@@ -587,11 +613,6 @@ func (h *MessageHandler) Create(c *gin.Context) {
ctx := c.Request.Context()
- // Validate PID references an existing, non-terminal message.
- if !h.validateParent(c, msg.PID) {
- return
- }
-
// Detect zip (deflate) content by checking for the zip magic bytes.
msg.Deflate = false // wire compression is chosen only at finalization
@@ -631,16 +652,14 @@ func (h *MessageHandler) Create(c *gin.Context) {
return
}
- // Insert recipients.
- for _, addr := range msg.To {
- if _, err = h.q().Exec(ctx,
- "INSERT INTO msg_to (msg_id, addr) VALUES ($1, $2) ON CONFLICT DO NOTHING",
- msgID, addr,
- ); err != nil {
- log.Printf("create message: insert recipient %s: %v", addr, err)
- c.JSON(500, gin.H{"error": "failed to save recipients"})
- return
- }
+ // Insert recipients in a single batched statement.
+ if _, err = h.q().Exec(ctx,
+ "INSERT INTO msg_to (msg_id, addr) SELECT $1, unnest($2::text[]) ON CONFLICT DO NOTHING",
+ msgID, msg.To,
+ ); err != nil {
+ log.Printf("create message: insert recipients: %v", err)
+ c.JSON(500, gin.H{"error": "failed to save recipients"})
+ return
}
c.JSON(http.StatusCreated, gin.H{"id": msgID})
@@ -696,21 +715,35 @@ func (h *MessageHandler) Get(c *gin.Context) {
msg.Trash = &trash
}
- // Compute ShortText only after authorization has been confirmed.
- msg.ShortText = h.extractShortText(dataPath, msg.Type)
+ // Compute reactions, edits, and ShortText only after authorization has been confirmed.
msg.Reaction = h.reactionOf(msg.HasPid, msg.NoReply, msg.Terminal, msg.Important, msg.HasAddTo, msg.Type, msg.Size, len(msg.Attachments), dataPath)
- msg.Reactions = h.loadReactions(ctx, []int64{msgID})[msgID]
+ reactionsMap, err := h.loadReactions(ctx, []int64{msgID})
+ if err != nil {
+ log.Printf("get message %d: reactions: %v", msgID, err)
+ c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to retrieve message"})
+ return
+ }
+ msg.Reactions = reactionsMap[msgID]
if msg.Reactions == nil {
msg.Reactions = []models.Reaction{}
}
if editShape(msg.HasPid, msg.NoReply, msg.Terminal, msg.Important, msg.HasAddTo, msg.Type, len(msg.Attachments)) {
- _, msg.Edit = h.editSubject(ctx, msgID)
+ _, msg.Edit, _ = h.editSubject(ctx, msgID)
}
- if eff := h.loadEffectiveEdits(ctx, []int64{msgID})[msgID]; eff != nil {
+ editsMap, err := h.loadEffectiveEdits(ctx, []int64{msgID})
+ if err != nil {
+ log.Printf("get message %d: edits: %v", msgID, err)
+ c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to retrieve message"})
+ return
+ }
+ if eff := editsMap[msgID]; eff != nil && eff.applied {
msg.Edited = eff.edited()
- if eff.applied {
- msg.ShortText = h.shortTextOf(eff.data, msg.Type)
+ msg.ShortText = h.shortTextOf(eff.data, msg.Type)
+ } else {
+ if eff != nil {
+ msg.Edited = eff.edited()
}
+ msg.ShortText = h.extractShortText(dataPath, msg.Type)
}
// Populate per-recipient read state for the calling user. The sender
@@ -764,7 +797,17 @@ func (h *MessageHandler) DownloadData(c *gin.Context) {
}
return
}
- if draftHidden(addrs, fromAddr, timeSent) || purgedFor(ctx, h.q(), addrs[0], msgID) {
+ if draftHidden(addrs, fromAddr, timeSent) {
+ c.JSON(http.StatusNotFound, gin.H{"error": "message not found"})
+ return
+ }
+ purged, err := purgedFor(ctx, h.q(), addrs[0], msgID)
+ if err != nil {
+ log.Printf("download data: trash state %d: %v", msgID, err)
+ c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to retrieve message"})
+ return
+ }
+ if purged {
c.JSON(http.StatusNotFound, gin.H{"error": "message not found"})
return
}
@@ -787,7 +830,13 @@ func (h *MessageHandler) DownloadData(c *gin.Context) {
// FMSG-008: an edited message downloads as edited unless the original
// is asked for.
if c.Query("original") != "true" {
- if eff := h.loadEffectiveEdits(ctx, []int64{msgID})[msgID]; eff != nil && eff.applied {
+ editsMap, err := h.loadEffectiveEdits(ctx, []int64{msgID})
+ if err != nil {
+ log.Printf("download data %d: edits: %v", msgID, err)
+ c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to retrieve message"})
+ return
+ }
+ if eff := editsMap[msgID]; eff != nil && eff.applied {
name := "data"
if dataPath != "" {
name = filepath.Base(dataPath)
@@ -847,8 +896,14 @@ func (h *MessageHandler) Update(c *gin.Context) {
return
}
+ limitJSONBody(c, h.MaxDataSize)
+
var msg messageInput
if err := c.ShouldBindJSON(&msg); err != nil {
+ if isMaxBytesError(err) {
+ c.JSON(http.StatusRequestEntityTooLarge, gin.H{"error": "message data exceeds maximum size"})
+ return
+ }
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
@@ -870,10 +925,6 @@ func (h *MessageHandler) Update(c *gin.Context) {
return
}
- if !h.validateParent(c, msg.PID) {
- return
- }
-
if int64(len(msg.Data)) > h.MaxDataSize {
c.JSON(http.StatusRequestEntityTooLarge, gin.H{"error": "message data exceeds maximum size"})
return
@@ -915,18 +966,18 @@ func (h *MessageHandler) Update(c *gin.Context) {
return
}
- // Replace recipients.
+ // Replace recipients in a single batched statement.
if _, err = h.q().Exec(ctx, "DELETE FROM msg_to WHERE msg_id = $1", msgID); err != nil {
log.Printf("update message %d delete recipients: %v", msgID, err)
c.JSON(500, gin.H{"error": "failed to update recipients"})
return
}
- for _, addr := range msg.To {
+ if len(msg.To) > 0 {
if _, err = h.q().Exec(ctx,
- "INSERT INTO msg_to (msg_id, addr) VALUES ($1, $2) ON CONFLICT DO NOTHING",
- msgID, addr,
+ "INSERT INTO msg_to (msg_id, addr) SELECT $1, unnest($2::text[]) ON CONFLICT DO NOTHING",
+ msgID, msg.To,
); err != nil {
- log.Printf("update message %d insert recipient %s: %v", msgID, addr, err)
+ log.Printf("update message %d insert recipients: %v", msgID, err)
c.JSON(500, gin.H{"error": "failed to update recipients"})
return
}
@@ -950,7 +1001,7 @@ func (h *MessageHandler) Delete(c *gin.Context) {
}
ctx := c.Request.Context()
- existing, _, err := h.fetchMessage(ctx, msgID)
+ existing, dataPath, err := h.fetchMessage(ctx, msgID)
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
c.JSON(http.StatusNotFound, gin.H{"error": "message not found"})
@@ -972,30 +1023,45 @@ func (h *MessageHandler) Delete(c *gin.Context) {
return
}
- // Remove attachment files from disk.
+ // Collect attachment files to remove after commit.
rows, err := h.q().Query(ctx, "SELECT filepath FROM msg_attachment WHERE msg_id = $1", msgID)
- if err == nil {
- var paths []string
- for rows.Next() {
- var p string
- if scanErr := rows.Scan(&p); scanErr == nil {
- paths = append(paths, p)
- }
- }
- rows.Close()
- for _, p := range paths {
- afterCommit(c, func() { _ = os.Remove(p) })
+ if err != nil {
+ log.Printf("delete message %d: fetch attachments: %v", msgID, err)
+ c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to delete message"})
+ return
+ }
+ var paths []string
+ for rows.Next() {
+ var p string
+ if scanErr := rows.Scan(&p); scanErr != nil {
+ rows.Close()
+ log.Printf("delete message %d: scan attachment: %v", msgID, scanErr)
+ c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to delete message"})
+ return
}
+ paths = append(paths, p)
+ }
+ rows.Close()
+ if err := rows.Err(); err != nil {
+ log.Printf("delete message %d: attachment rows: %v", msgID, err)
+ c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to delete message"})
+ return
}
if _, err = h.q().Exec(ctx, "DELETE FROM msg_attachment WHERE msg_id = $1", msgID); err != nil {
log.Printf("delete message %d: delete attachments: %v", msgID, err)
+ c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to delete attachments"})
+ return
}
if _, err = h.q().Exec(ctx, "DELETE FROM msg_to WHERE msg_id = $1", msgID); err != nil {
log.Printf("delete message %d: delete recipients: %v", msgID, err)
+ c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to delete recipients"})
+ return
}
if _, err = h.q().Exec(ctx, "DELETE FROM msg_add_to WHERE msg_id = $1", msgID); err != nil {
log.Printf("delete message %d: delete add_to recipients: %v", msgID, err)
+ c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to delete recipients"})
+ return
}
if _, err = h.q().Exec(ctx, `DELETE FROM msg_add_to_notify WHERE batch_id IN (SELECT id FROM msg_add_to_batch WHERE msg_id=$1)`, msgID); err != nil {
@@ -1006,9 +1072,6 @@ func (h *MessageHandler) Delete(c *gin.Context) {
c.JSON(500, gin.H{"error": "failed to delete batches"})
return
}
- // Get data filepath before deleting.
- var dataPath string
- _ = h.q().QueryRow(ctx, "SELECT filepath FROM msg WHERE id = $1", msgID).Scan(&dataPath)
if _, err = h.q().Exec(ctx, "DELETE FROM msg WHERE id = $1", msgID); err != nil {
log.Printf("delete message %d: %v", msgID, err)
@@ -1016,6 +1079,10 @@ func (h *MessageHandler) Delete(c *gin.Context) {
return
}
+ for _, p := range paths {
+ path := p
+ afterCommit(c, func() { _ = os.Remove(path) })
+ }
if dataPath != "" {
afterCommit(c, func() { _ = os.Remove(dataPath) })
}
@@ -1111,12 +1178,13 @@ func (h *MessageHandler) Send(c *gin.Context) {
// fmsgd's outbound sender skips the local domain entirely, so local
// recipients need their delivery status resolved here instead.
afterCommit(c, func() {
+ postCtx := context.WithoutCancel(ctx)
plain := *h
plain.query = nil
- plain.recordSend(existing.From, now, size)
- plain.resolveLocalDelivery(ctx, "msg_to", msgID, h.LocalDomain, existing.To)
+ plain.recordSend(postCtx, existing.From, now, size)
+ plain.resolveLocalDelivery(postCtx, "msg_to", msgID, h.LocalDomain, existing.To)
for _, b := range existing.AddTo {
- plain.resolveLocalDelivery(ctx, "msg_add_to", msgID, h.LocalDomain, b.To)
+ plain.resolveLocalDelivery(postCtx, "msg_add_to", msgID, h.LocalDomain, b.To)
}
})
c.JSON(http.StatusOK, gin.H{"id": msgID, "time": now, "sha256": hex.EncodeToString(hash)})
@@ -1156,7 +1224,17 @@ func (h *MessageHandler) MarkRead(c *gin.Context) {
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to mark message read"})
return
}
- if !recipient || purgedFor(ctx, h.q(), identity, msgID) {
+ if !recipient {
+ c.JSON(http.StatusNotFound, gin.H{"error": "message not found"})
+ return
+ }
+ purged, err := purgedFor(ctx, h.q(), identity, msgID)
+ if err != nil {
+ log.Printf("mark read %d: trash state: %v", msgID, err)
+ c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to mark message read"})
+ return
+ }
+ if purged {
c.JSON(http.StatusNotFound, gin.H{"error": "message not found"})
return
}
@@ -1250,7 +1328,17 @@ func (h *MessageHandler) AddRecipients(c *gin.Context) {
}
return
}
- if draftHidden([]string{identity}, fromAddr, timeSent) || purgedFor(ctx, h.q(), identity, msgID) {
+ if draftHidden([]string{identity}, fromAddr, timeSent) {
+ c.JSON(http.StatusNotFound, gin.H{"error": "message not found"})
+ return
+ }
+ purged, err := purgedFor(ctx, h.q(), identity, msgID)
+ if err != nil {
+ log.Printf("add recipients: trash state %d: %v", msgID, err)
+ c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to retrieve message"})
+ return
+ }
+ if purged {
c.JSON(http.StatusNotFound, gin.H{"error": "message not found"})
return
}
@@ -1304,13 +1392,13 @@ func (h *MessageHandler) AddRecipients(c *gin.Context) {
// Insert the new add_to recipients and record who added them. Both run in a
// single transaction so a partial failure leaves the message unchanged.
- tx, err := h.q().Begin(ctx)
+ tx, commit, rollback, err := beginOrReuseTx(ctx, h.q())
if err != nil {
log.Printf("add recipients: begin tx for msg %d: %v", msgID, err)
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to add recipients"})
return
}
- defer tx.Rollback(ctx)
+ defer rollback()
// Each add-to is recorded as a batch row capturing who added the recipients
// and when, then the recipients are inserted referencing that batch.
@@ -1326,15 +1414,13 @@ func (h *MessageHandler) AddRecipients(c *gin.Context) {
return
}
- for _, addr := range input.AddTo {
- if _, err = tx.Exec(ctx,
- "INSERT INTO msg_add_to (msg_id, batch_id, addr) VALUES ($1, $2, $3) ON CONFLICT DO NOTHING",
- msgID, batchID, addr,
- ); err != nil {
- log.Printf("add recipients: insert %s into msg %d: %v", addr, msgID, err)
- c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to add recipients"})
- return
- }
+ if _, err = tx.Exec(ctx,
+ "INSERT INTO msg_add_to (msg_id, batch_id, addr) SELECT $1, $2, unnest($3::text[]) ON CONFLICT DO NOTHING",
+ msgID, batchID, input.AddTo,
+ ); err != nil {
+ log.Printf("add recipients: insert into msg %d: %v", msgID, err)
+ c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to add recipients"})
+ return
}
// SPEC §10.2: an add-to message is delivered to every participant domain
@@ -1370,7 +1456,7 @@ func (h *MessageHandler) AddRecipients(c *gin.Context) {
c.JSON(500, gin.H{"error": "failed to finalize add-to batch"})
return
}
- if err = tx.Commit(ctx); err != nil {
+ if err = commit(); err != nil {
log.Printf("add recipients: commit tx for msg %d: %v", msgID, err)
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to add recipients"})
return
@@ -1384,9 +1470,10 @@ func (h *MessageHandler) AddRecipients(c *gin.Context) {
// federated participant on a different domain than the recipients they add.
if timeSent != nil {
afterCommit(c, func() {
+ postCtx := context.WithoutCancel(ctx)
plain := *h
plain.query = nil
- plain.resolveLocalDelivery(ctx, "msg_add_to", msgID, h.LocalDomain, input.AddTo)
+ plain.resolveLocalDelivery(postCtx, "msg_add_to", msgID, h.LocalDomain, input.AddTo)
})
}
@@ -1400,7 +1487,7 @@ func (h *MessageHandler) AddRecipients(c *gin.Context) {
// loadRecipients loads the direct (msg_to) recipients for the given messages,
// keyed by msg_id, along with each recipient's delivery status.
-func (h *MessageHandler) loadRecipients(ctx context.Context, msgIDs []int64) (map[int64][]string, map[int64][]models.RecipientDelivery) {
+func (h *MessageHandler) loadRecipients(ctx context.Context, msgIDs []int64) (map[int64][]string, map[int64][]models.RecipientDelivery, error) {
toMap := make(map[int64][]string)
deliveryMap := make(map[int64][]models.RecipientDelivery)
rows, err := h.q().Query(ctx,
@@ -1408,8 +1495,7 @@ func (h *MessageHandler) loadRecipients(ctx context.Context, msgIDs []int64) (ma
msgIDs,
)
if err != nil {
- log.Printf("load recipients: %v", err)
- return toMap, deliveryMap
+ return nil, nil, err
}
defer rows.Close()
for rows.Next() {
@@ -1418,8 +1504,7 @@ func (h *MessageHandler) loadRecipients(ctx context.Context, msgIDs []int64) (ma
var timeDelivered *float64
var responseCode *int16
if scanErr := rows.Scan(&id, &addr, &timeDelivered, &responseCode); scanErr != nil {
- log.Printf("load recipients scan: %v", scanErr)
- continue
+ return nil, nil, scanErr
}
toMap[id] = append(toMap[id], addr)
deliveryMap[id] = append(deliveryMap[id], models.RecipientDelivery{
@@ -1428,7 +1513,10 @@ func (h *MessageHandler) loadRecipients(ctx context.Context, msgIDs []int64) (ma
ResponseCode: int16PtrToIntPtr(responseCode),
})
}
- return toMap, deliveryMap
+ if err := rows.Err(); err != nil {
+ return nil, nil, err
+ }
+ return toMap, deliveryMap, nil
}
// int16PtrToIntPtr converts a nullable Postgres smallint scan target to *int
@@ -1447,7 +1535,7 @@ func int16PtrToIntPtr(v *int16) *int {
// status. A LEFT JOIN is used so a batch whose addresses were all already
// present still records the provenance of the add-to. Batches are ordered by
// their insertion order (batch id).
-func (h *MessageHandler) loadAddToBatches(ctx context.Context, msgIDs []int64) map[int64][]models.AddToBatch {
+func (h *MessageHandler) loadAddToBatches(ctx context.Context, msgIDs []int64) (map[int64][]models.AddToBatch, error) {
result := make(map[int64][]models.AddToBatch)
rows, err := h.q().Query(ctx,
`SELECT b.msg_id, b.id, b.add_to_from, b.time_added, encode(b.sha256,'hex'), mat.addr, mat.time_delivered, mat.response_code
@@ -1458,8 +1546,7 @@ func (h *MessageHandler) loadAddToBatches(ctx context.Context, msgIDs []int64) m
msgIDs,
)
if err != nil {
- log.Printf("load add_to batches: %v", err)
- return result
+ return nil, err
}
defer rows.Close()
@@ -1474,8 +1561,7 @@ func (h *MessageHandler) loadAddToBatches(ctx context.Context, msgIDs []int64) m
var timeDelivered *float64
var responseCode *int16
if err := rows.Scan(&msgID, &batchID, &addToFrom, &timeAdded, &hash, &addr, &timeDelivered, &responseCode); err != nil {
- log.Printf("load add_to batches scan: %v", err)
- continue
+ return nil, err
}
i, ok := idx[batchID]
if !ok {
@@ -1497,7 +1583,10 @@ func (h *MessageHandler) loadAddToBatches(ctx context.Context, msgIDs []int64) m
})
}
}
- return result
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return result, nil
}
// fetchMessage loads a message with its recipients and attachments from the DB.
@@ -1521,24 +1610,37 @@ func (h *MessageHandler) fetchMessage(ctx context.Context, msgID int64) (*models
msg.HasPid = pid != nil
// Load recipients.
- toMap, toDeliveryMap := h.loadRecipients(ctx, []int64{msgID})
+ toMap, toDeliveryMap, err := h.loadRecipients(ctx, []int64{msgID})
+ if err != nil {
+ return nil, "", err
+ }
msg.To = toMap[msgID]
msg.ToDelivery = toDeliveryMap[msgID]
// Load add_to batches.
- msg.AddTo = h.loadAddToBatches(ctx, []int64{msgID})[msgID]
+ addToMap, err := h.loadAddToBatches(ctx, []int64{msgID})
+ if err != nil {
+ return nil, "", err
+ }
+ msg.AddTo = addToMap[msgID]
msg.HasAddTo = len(msg.AddTo) > 0
// Load attachments.
attRows, err := h.q().Query(ctx, "SELECT filename, filesize FROM msg_attachment WHERE msg_id = $1", msgID)
- if err == nil {
- for attRows.Next() {
- var a models.Attachment
- if scanErr := attRows.Scan(&a.Filename, &a.Size); scanErr == nil {
- msg.Attachments = append(msg.Attachments, a)
- }
+ if err != nil {
+ return nil, "", err
+ }
+ for attRows.Next() {
+ var a models.Attachment
+ if scanErr := attRows.Scan(&a.Filename, &a.Size); scanErr != nil {
+ attRows.Close()
+ return nil, "", scanErr
}
- attRows.Close()
+ msg.Attachments = append(msg.Attachments, a)
+ }
+ attRows.Close()
+ if err := attRows.Err(); err != nil {
+ return nil, "", err
}
return msg, dataPath, nil
@@ -1574,23 +1676,33 @@ func (h *MessageHandler) messageItemFor(ctx context.Context, msgID int64, recipi
Topic: msg.Topic,
Type: msg.Type,
Size: msg.Size,
- ShortText: h.extractShortText(dataPath, msg.Type),
Attachments: msg.Attachments,
dataPath: dataPath,
}
item.Reaction = h.reactionOf(item.HasPid, item.NoReply, item.Terminal, item.Important, item.HasAddTo, item.Type, item.Size, len(item.Attachments), dataPath)
- item.Reactions = h.loadReactions(ctx, []int64{msgID})[msgID]
+ reactionsMap, err := h.loadReactions(ctx, []int64{msgID})
+ if err != nil {
+ return nil, err
+ }
+ item.Reactions = reactionsMap[msgID]
if item.Reactions == nil {
item.Reactions = []models.Reaction{}
}
if editShape(item.HasPid, item.NoReply, item.Terminal, item.Important, item.HasAddTo, item.Type, len(item.Attachments)) {
- _, item.Edit = h.editSubject(ctx, msgID)
+ _, item.Edit, _ = h.editSubject(ctx, msgID)
}
- if eff := h.loadEffectiveEdits(ctx, []int64{msgID})[msgID]; eff != nil {
+ editsMap, err := h.loadEffectiveEdits(ctx, []int64{msgID})
+ if err != nil {
+ return nil, err
+ }
+ if eff := editsMap[msgID]; eff != nil && eff.applied {
item.Edited = eff.edited()
- if eff.applied {
- item.ShortText = h.shortTextOf(eff.data, item.Type)
+ item.ShortText = h.shortTextOf(eff.data, item.Type)
+ } else {
+ if eff != nil {
+ item.Edited = eff.edited()
}
+ item.ShortText = h.extractShortText(dataPath, item.Type)
}
// Populate the recipient's per-recipient read state, mirroring Get.
@@ -1923,33 +2035,6 @@ func validatePidRelations(pid *int64, topic string) error {
return nil
}
-// validateParent checks a draft's pid, when set, references an existing
-// message that is not terminal, writing the error response and returning
-// false otherwise. A terminal message is a leaf: no message may reference it
-// via pid (fmsg Specification v0.6.0 §3), and the database refuses such a row
-// too; checking here gives the caller a clear answer instead.
-func (h *MessageHandler) validateParent(c *gin.Context, pid *int64) bool {
- if pid == nil {
- return true
- }
- var terminal bool
- err := h.q().QueryRow(c.Request.Context(), "SELECT is_terminal FROM msg WHERE id = $1", *pid).Scan(&terminal)
- if errors.Is(err, pgx.ErrNoRows) {
- c.JSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("PID %d not found", *pid)})
- return false
- }
- if err != nil {
- log.Printf("validate pid %d: %v", *pid, err)
- c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to validate pid"})
- return false
- }
- if terminal {
- c.JSON(http.StatusConflict, gin.H{"error": fmt.Sprintf("PID %d is terminal; it cannot be replied to", *pid)})
- return false
- }
- return true
-}
-
// checkDistinctRecipients returns an error if any address in to or addTo
// appears more than once (case-insensitive).
func checkDistinctRecipients(to, addTo []string) error {
diff --git a/internal/handlers/push.go b/internal/handlers/push.go
index c894028..55408d4 100644
--- a/internal/handlers/push.go
+++ b/internal/handlers/push.go
@@ -5,8 +5,10 @@ import (
"encoding/json"
"errors"
"fmt"
+ "io"
"log"
"net/http"
+ "strings"
"time"
webpush "github.com/SherClockHolmes/webpush-go"
@@ -17,10 +19,14 @@ import (
"github.com/markmnl/fmsg-webapi/internal/middleware"
)
-// pushTimeout caps how long a single new_msg push fan-out may take. It runs on
-// a fresh context so a listener reconnect cannot cancel in-flight sends.
+// pushTimeout caps how long a single new_msg push fan-out may take. It derives
+// from the hub's push context so listener reconnects cannot cancel in-flight
+// sends while graceful shutdown aborts them promptly.
const pushTimeout = 30 * time.Second
+// pushRequestTimeout caps each individual HTTP request to a Web Push endpoint.
+const pushRequestTimeout = 10 * time.Second
+
// pushTTL is the seconds a push service should retain an undelivered message.
const pushTTL = 86400
@@ -33,6 +39,7 @@ type PushHandler struct {
vapidPrivate string
vapidSubject string
iconURL string
+ httpClient *http.Client
// send delivers one encrypted push and returns the HTTP status of the
// push service. It is a field so tests can substitute a fake transport.
@@ -42,6 +49,8 @@ type PushHandler struct {
// NewPushHandler creates a PushHandler. vapidPublic/vapidPrivate are URL-safe
// base64 VAPID keys; vapidSubject is the VAPID "sub" (e.g. "mailto:admin@example.com").
func NewPushHandler(database *db.DB, msgs *MessageHandler, vapidPublic, vapidPrivate, vapidSubject, iconURL string) *PushHandler {
+ tr := http.DefaultTransport.(*http.Transport).Clone()
+ tr.MaxIdleConnsPerHost = 16
h := &PushHandler{
DB: database,
msgs: msgs,
@@ -49,6 +58,10 @@ func NewPushHandler(database *db.DB, msgs *MessageHandler, vapidPublic, vapidPri
vapidPrivate: vapidPrivate,
vapidSubject: vapidSubject,
iconURL: iconURL,
+ httpClient: &http.Client{
+ Transport: tr,
+ Timeout: pushRequestTimeout,
+ },
}
h.send = h.sendNotification
return h
@@ -140,8 +153,11 @@ func (h *PushHandler) Unsubscribe(c *gin.Context) {
// recipient addr. It is invoked by the WebSocket hub for each new_msg
// notification and runs independently of WebSocket fan-out, so a recipient with
// no live WebSocket is still notified.
-func (h *PushHandler) NotifyNewMsg(_ context.Context, msgID int64, addr string) {
- ctx, cancel := context.WithTimeout(context.Background(), pushTimeout)
+func (h *PushHandler) NotifyNewMsg(ctx context.Context, msgID int64, addr string) {
+ if ctx == nil {
+ ctx = context.Background()
+ }
+ ctx, cancel := context.WithTimeout(ctx, pushTimeout)
defer cancel()
// Load the recipient's subscriptions first; an address with none costs
@@ -158,36 +174,68 @@ func (h *PushHandler) NotifyNewMsg(_ context.Context, msgID int64, addr string)
var subs []subRow
for rows.Next() {
var s subRow
- if scanErr := rows.Scan(&s.endpoint, &s.p256dh, &s.auth); scanErr == nil {
- subs = append(subs, s)
+ if scanErr := rows.Scan(&s.endpoint, &s.p256dh, &s.auth); scanErr != nil {
+ rows.Close()
+ log.Printf("push notify: scan subscriptions for %s: %v", addr, scanErr)
+ return
}
+ subs = append(subs, s)
}
rows.Close()
- if len(subs) == 0 {
+ if err := rows.Err(); err != nil {
+ log.Printf("push notify: iterate subscriptions for %s: %v", addr, err)
return
}
-
- rootID, err := h.rootMsgID(ctx, msgID)
- if err != nil {
- log.Printf("push notify: resolve root of message %d: %v", msgID, err)
+ if len(subs) == 0 {
return
}
- item, err := h.msgs.messageItemFor(ctx, msgID, addr)
- if err != nil {
- log.Printf("push notify: build message %d for %s: %v", msgID, addr, err)
+ // Load only the message fields needed for push filtering and payload
+ // construction rather than building a full message list item.
+ var fromAddr, mediaType, dataPath string
+ var pid *int64
+ var noReply, terminal, important, hasAttachments, hasAddTo bool
+ var size int
+ var trashState *string
+ if err := h.DB.Pool.QueryRow(ctx, `
+ SELECT m.from_addr, m.pid, m.no_reply, m.is_terminal, m.is_important,
+ m.type, m.size, m.filepath,
+ EXISTS (SELECT 1 FROM msg_attachment a WHERE a.msg_id = m.id),
+ EXISTS (SELECT 1 FROM msg_add_to_batch b WHERE b.msg_id = m.id),
+ CASE WHEN EXISTS (SELECT 1 FROM fmsg_api_trash WHERE addr = $2)
+ THEN fmsg_api_trash_state($2, m.id) END
+ FROM msg m
+ WHERE m.id = $1`, msgID, strings.ToLower(addr),
+ ).Scan(&fromAddr, &pid, &noReply, &terminal, &important, &mediaType, &size, &dataPath, &hasAttachments, &hasAddTo, &trashState); err != nil {
+ log.Printf("push notify: load message %d for %s: %v", msgID, addr, err)
return
}
- if item.Reaction != nil {
+ if trashState != nil {
+ return // in the recipient's trash or purged: they aren't told
+ }
+ attCount := 0
+ if hasAttachments {
+ attCount = 1
+ }
+ if h.msgs.reactionOf(pid != nil, noReply, terminal, important, hasAddTo, mediaType, size, attCount, dataPath) != nil {
return // FMSG-005: a reaction does not warrant a notification
}
- if item.Edit {
- return // FMSG-008: nor does an edit
+ if editShape(pid != nil, noReply, terminal, important, hasAddTo, mediaType, attCount) {
+ if _, isEdit, _ := h.msgs.editSubject(ctx, msgID); isEdit {
+ return // FMSG-008: nor does an edit
+ }
}
- if item.purged || item.Trash != nil {
- return // in the recipient's trash: they aren't told
+
+ rootID, err := h.rootMsgID(ctx, msgID)
+ if err != nil {
+ log.Printf("push notify: resolve root of message %d: %v", msgID, err)
+ return
}
+ item := &messageListItem{
+ From: fromAddr,
+ ShortText: h.msgs.extractShortText(dataPath, mediaType),
+ }
payload, err := json.Marshal(buildPushPayload(item, rootID, h.iconURL))
if err != nil {
log.Printf("push notify: marshal message %d: %v", msgID, err)
@@ -195,6 +243,9 @@ func (h *PushHandler) NotifyNewMsg(_ context.Context, msgID int64, addr string)
}
for _, s := range subs {
+ if ctx.Err() != nil {
+ return
+ }
sub := &webpush.Subscription{
Endpoint: s.endpoint,
Keys: webpush.Keys{P256dh: s.p256dh, Auth: s.auth},
@@ -266,15 +317,20 @@ func (h *PushHandler) rootMsgID(ctx context.Context, msgID int64) (int64, error)
// sendNotification is the production send implementation: it encrypts and POSTs
// one push via VAPID and returns the push service's HTTP status code.
func (h *PushHandler) sendNotification(ctx context.Context, payload []byte, sub *webpush.Subscription) (int, error) {
- resp, err := webpush.SendNotificationWithContext(ctx, payload, sub, &webpush.Options{
+ opts := &webpush.Options{
Subscriber: h.vapidSubject,
VAPIDPublicKey: h.vapidPublic,
VAPIDPrivateKey: h.vapidPrivate,
TTL: pushTTL,
- })
+ HTTPClient: h.httpClient,
+ }
+ resp, err := webpush.SendNotificationWithContext(ctx, payload, sub, opts)
if err != nil {
return 0, err
}
- defer resp.Body.Close()
+ defer func() {
+ _, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, 64<<10))
+ _ = resp.Body.Close()
+ }()
return resp.StatusCode, nil
}
diff --git a/internal/handlers/quota.go b/internal/handlers/quota.go
index c05355d..a0a4d59 100644
--- a/internal/handlers/quota.go
+++ b/internal/handlers/quota.go
@@ -96,7 +96,7 @@ func checkSendLimits(d *middleware.FmsgIDDetail, size int64) *sendLimitError {
// with fmsgid's current usage (never the cached lookup). Otherwise it answers
// with the refusal and returns false.
func (h *MessageHandler) checkSendQuota(c *gin.Context, sender string, size int64) bool {
- detail, status, err := middleware.FetchFmsgIDDetail(h.IDURL, sender)
+ detail, status, err := middleware.FetchFmsgIDDetailContext(c.Request.Context(), h.IDURL, sender)
if err != nil {
log.Printf("send quota: fmsgid detail %s: %v", sender, err)
c.JSON(http.StatusServiceUnavailable, gin.H{"error": "identity service unavailable"})
@@ -124,8 +124,8 @@ func (h *MessageHandler) checkSendQuota(c *gin.Context, sender string, size int6
// recordSend records one sent message of size bytes for sender at ts. A
// failure is logged: the message has been sent.
-func (h *MessageHandler) recordSend(sender string, ts float64, size int64) {
- if err := middleware.RecordFmsgIDSend(h.IDURL, sender, ts, size); err != nil {
+func (h *MessageHandler) recordSend(ctx context.Context, sender string, ts float64, size int64) {
+ if err := middleware.RecordFmsgIDSendContext(ctx, h.IDURL, sender, ts, size); err != nil {
log.Printf("record send usage: %s: %v", sender, err)
}
}
diff --git a/internal/handlers/reactions.go b/internal/handlers/reactions.go
index a410fcb..c7a0bc2 100644
--- a/internal/handlers/reactions.go
+++ b/internal/handlers/reactions.go
@@ -49,35 +49,43 @@ func reactionShape(hasPid, noReply, terminal, important, hasAddTo bool, mediaTyp
isReactionMediaType(mediaType)
}
-// readReactionData reads a shape-matching message's body and returns the emoji
-// it carries ("" clears) and whether the body is a valid reaction body.
-func (h *MessageHandler) readReactionData(dataPath string, size int) (string, bool) {
+// readReactionDataErr reads a shape-matching message's body and returns the
+// emoji it carries ("" clears), whether the body is a valid reaction body, and
+// any disk I/O error encountered while reading it.
+func (h *MessageHandler) readReactionDataErr(dataPath string, size int) (string, bool, error) {
if size == 0 {
- return "", true
+ return "", true, nil
}
cleanPath, ok := safeDataPath(dataPath, h.DataDir)
if !ok {
- return "", false
+ return "", false, nil
}
f, err := os.Open(cleanPath)
if err != nil {
if !errors.Is(err, os.ErrNotExist) {
log.Printf("reaction data: open %s: %v", cleanPath, err)
}
- return "", false
+ return "", false, err
}
defer f.Close()
buf := make([]byte, maxReactionBytes+1)
n, err := io.ReadFull(f, buf)
if err != nil && !errors.Is(err, io.EOF) && !errors.Is(err, io.ErrUnexpectedEOF) {
log.Printf("reaction data: read %s: %v", cleanPath, err)
- return "", false
+ return "", false, err
}
s := string(buf[:n])
if !emoji.IsSingle(s) {
- return "", false
+ return "", false, nil
}
- return s, true
+ return s, true, nil
+}
+
+// readReactionData reads a shape-matching message's body and returns the emoji
+// it carries ("" clears) and whether the body is a valid reaction body.
+func (h *MessageHandler) readReactionData(dataPath string, size int) (string, bool) {
+ s, ok, _ := h.readReactionDataErr(dataPath, size)
+ return s, ok
}
// reactionOf returns the reaction a message carries, or nil when the message
@@ -93,9 +101,10 @@ func (h *MessageHandler) reactionOf(hasPid, noReply, terminal, important, hasAdd
return &s
}
-// reactionSubject reports the subject of msgID when msgID is a reaction. Used
-// by the WebSocket hub to route an arriving reaction as a reaction event.
-func (h *MessageHandler) reactionSubject(ctx context.Context, msgID int64) (int64, bool) {
+// reactionSubject reports the subject of msgID when msgID is a reaction.
+// Transient DB or disk errors are returned so callers (such as the WebSocket
+// hub classification cache) do not pin a false negative.
+func (h *MessageHandler) reactionSubject(ctx context.Context, msgID int64) (int64, bool, error) {
var pid *int64
var noReply, terminal, important, hasAddTo bool
var mediaType, dataPath string
@@ -107,15 +116,23 @@ func (h *MessageHandler) reactionSubject(ctx context.Context, msgID int64) (int6
FROM msg m WHERE m.id = $1`, msgID,
).Scan(&pid, &noReply, &terminal, &important, &mediaType, &size, &dataPath, &attachments, &hasAddTo)
if err != nil {
- if !errors.Is(err, pgx.ErrNoRows) {
- log.Printf("reaction subject of %d: %v", msgID, err)
+ if errors.Is(err, pgx.ErrNoRows) {
+ return 0, false, nil
}
- return 0, false
+ log.Printf("reaction subject of %d: %v", msgID, err)
+ return 0, false, err
}
- if pid == nil || h.reactionOf(true, noReply, terminal, important, hasAddTo, mediaType, size, attachments, dataPath) == nil {
- return 0, false
+ if pid == nil || !reactionShape(true, noReply, terminal, important, hasAddTo, mediaType, size, attachments) {
+ return 0, false, nil
}
- return *pid, true
+ _, ok, err := h.readReactionDataErr(dataPath, size)
+ if err != nil {
+ return 0, false, err
+ }
+ if !ok {
+ return 0, false, nil
+ }
+ return *pid, true, nil
}
// reactionRow is one stored reaction message on a subject.
@@ -231,30 +248,33 @@ func (h *MessageHandler) loadReactionRows(ctx context.Context, subjectIDs []int6
}
// loadReactions returns the effective reactions on each of the given subjects.
-func (h *MessageHandler) loadReactions(ctx context.Context, subjectIDs []int64) map[int64][]models.Reaction {
+func (h *MessageHandler) loadReactions(ctx context.Context, subjectIDs []int64) (map[int64][]models.Reaction, error) {
rows, err := h.loadReactionRows(ctx, subjectIDs, "")
if err != nil {
- log.Printf("load reactions: %v", err)
- return nil
+ return nil, err
}
- return effectiveReactions(rows)
+ return effectiveReactions(rows), nil
}
// populateListReactions fills Reaction and Reactions on every list item.
-func (h *MessageHandler) populateListReactions(ctx context.Context, items []messageListItem) {
+func (h *MessageHandler) populateListReactions(ctx context.Context, items []messageListItem) error {
ids := make([]int64, len(items))
for i := range items {
it := &items[i]
it.Reaction = h.reactionOf(it.HasPid, it.NoReply, it.Terminal, it.Important, it.HasAddTo, it.Type, it.Size, len(it.Attachments), it.dataPath)
ids[i] = it.ID
}
- reactions := h.loadReactions(ctx, ids)
+ reactions, err := h.loadReactions(ctx, ids)
+ if err != nil {
+ return err
+ }
for i := range items {
items[i].Reactions = reactions[items[i].ID]
if items[i].Reactions == nil {
items[i].Reactions = []models.Reaction{}
}
}
+ return nil
}
// reactionRecipients returns a subject's participants other than the reactor,
@@ -326,7 +346,17 @@ func (h *MessageHandler) React(c *gin.Context) {
return
}
- if draftHidden([]string{identity}, subject.From, subject.Time) || purgedFor(ctx, h.q(), identity, msgID) {
+ if draftHidden([]string{identity}, subject.From, subject.Time) {
+ c.JSON(http.StatusNotFound, gin.H{"error": "message not found"})
+ return
+ }
+ purged, err := purgedFor(ctx, h.q(), identity, msgID)
+ if err != nil {
+ log.Printf("react to %d: trash state: %v", msgID, err)
+ c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to retrieve message"})
+ return
+ }
+ if purged {
c.JSON(http.StatusNotFound, gin.H{"error": "message not found"})
return
}
@@ -410,13 +440,13 @@ func (h *MessageHandler) React(c *gin.Context) {
return
}
now := float64(time.Now().UnixMicro()) / 1e6
- tx, err := h.q().Begin(ctx)
+ tx, commit, rollback, err := beginOrReuseTx(ctx, h.q())
if err != nil {
log.Printf("react to %d: begin: %v", msgID, err)
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to send reaction"})
return
}
- defer tx.Rollback(ctx)
+ defer rollback()
var reactionID int64
if err := tx.QueryRow(ctx,
@@ -441,9 +471,9 @@ func (h *MessageHandler) React(c *gin.Context) {
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to send reaction"})
return
}
- for _, addr := range recipients {
- if _, err := tx.Exec(ctx, "INSERT INTO msg_to (msg_id, addr) VALUES ($1, $2)", reactionID, addr); err != nil {
- log.Printf("react to %d: insert recipient %s: %v", msgID, addr, err)
+ if len(recipients) > 0 {
+ if _, err := tx.Exec(ctx, "INSERT INTO msg_to (msg_id, addr) SELECT $1, unnest($2::text[])", reactionID, recipients); err != nil {
+ log.Printf("react to %d: insert recipients: %v", msgID, err)
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to send reaction"})
return
}
@@ -456,7 +486,7 @@ func (h *MessageHandler) React(c *gin.Context) {
c.JSON(500, gin.H{"error": "failed to finalize reaction"})
return
}
- if err := tx.Commit(ctx); err != nil {
+ if err := commit(); err != nil {
log.Printf("react to %d: commit: %v", msgID, err)
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to send reaction"})
return
@@ -465,10 +495,11 @@ func (h *MessageHandler) React(c *gin.Context) {
// fmsgd's outbound sender skips the local domain, so local recipients
// have their delivery resolved here, as Send does.
afterCommit(c, func() {
+ postCtx := context.WithoutCancel(ctx)
plain := *h
plain.query = nil
- plain.recordSend(identity, now, size)
- plain.resolveLocalDelivery(ctx, "msg_to", reactionID, h.LocalDomain, recipients)
+ plain.recordSend(postCtx, identity, now, size)
+ plain.resolveLocalDelivery(postCtx, "msg_to", reactionID, h.LocalDomain, recipients)
})
c.JSON(http.StatusCreated, gin.H{"id": reactionID, "time": now, "sha256": hex.EncodeToString(hash)})
diff --git a/internal/handlers/reactions_test.go b/internal/handlers/reactions_test.go
index 8e2478c..be9761b 100644
--- a/internal/handlers/reactions_test.go
+++ b/internal/handlers/reactions_test.go
@@ -153,20 +153,20 @@ func TestHubDispatch_ReactionRoutesToSubject(t *testing.T) {
built = append(built, msgID)
return &messageListItem{ID: msgID}, nil
},
- reactionSubject: func(_ context.Context, msgID int64) (int64, bool) {
+ reactionSubject: func(_ context.Context, msgID int64) (int64, bool, error) {
if msgID == 42 {
- return 7, true
+ return 7, true, nil
}
- return 0, false
+ return 0, false, nil
},
registry: make(map[string]map[*wsClient]struct{}),
}
c := &wsClient{addr: "@bob@example.com", send: make(chan []byte, 4)}
hub.Register(c)
- subject, ok := hub.reactionSubject(context.Background(), 42)
- if !ok || subject != 7 {
- t.Fatalf("reactionSubject(42) = %d,%v", subject, ok)
+ subject, ok, err := hub.reactionSubject(context.Background(), 42)
+ if err != nil || !ok || subject != 7 {
+ t.Fatalf("reactionSubject(42) = %d,%v,%v", subject, ok, err)
}
hub.dispatch(context.Background(), subject, "@bob@example.com", eventReaction)
select {
diff --git a/internal/handlers/references.go b/internal/handlers/references.go
index fb36b70..3f21d18 100644
--- a/internal/handlers/references.go
+++ b/internal/handlers/references.go
@@ -5,6 +5,7 @@ import (
"encoding/hex"
"encoding/json"
"errors"
+ "log"
"net/http"
"strconv"
@@ -13,6 +14,13 @@ import (
"github.com/markmnl/fmsg-webapi/internal/middleware"
)
+const resolvedMsgIDKey = "resolvedMsgID"
+
+type cachedResolvedID struct {
+ raw string
+ id int64
+}
+
func decodeHash(s string) ([]byte, error) {
if len(s) != 64 {
return nil, errors.New("hash must contain 64 hexadecimal characters")
@@ -22,8 +30,17 @@ func decodeHash(s string) ([]byte, error) {
func resolveID(c *gin.Context, q queries) (int64, bool) {
s := c.Param("id")
+ if v, ok := c.Get(resolvedMsgIDKey); ok {
+ if cached, ok := v.(cachedResolvedID); ok && cached.raw == s {
+ return cached.id, true
+ }
+ }
if len(s) != 64 {
- return parseID(c)
+ id, ok := parseID(c)
+ if ok {
+ c.Set(resolvedMsgIDKey, cachedResolvedID{raw: s, id: id})
+ }
+ return id, ok
}
hash, err := decodeHash(s)
if err != nil {
@@ -40,6 +57,7 @@ func resolveID(c *gin.Context, q queries) (int64, bool) {
c.JSON(500, gin.H{"error": "failed to resolve message"})
return 0, false
}
+ c.Set(resolvedMsgIDKey, cachedResolvedID{raw: s, id: id})
return id, true
}
@@ -78,9 +96,19 @@ func (h *MessageHandler) resolveParent(c *gin.Context, in *messageInput) bool {
var terminal bool
var batchID *int64
if hash != nil {
- err = h.q().QueryRow(ctx, `SELECT m.id,m.sha256,m.time_sent,m.is_terminal,b.id
- FROM msg m LEFT JOIN msg_add_to_batch b ON b.msg_id=m.id AND b.sha256=$1
- WHERE m.sha256=$1 OR b.id IS NOT NULL ORDER BY b.id NULLS FIRST LIMIT 1`, hash).Scan(&id, &canonical, &sent, &terminal, &batchID)
+ err = h.q().QueryRow(ctx, `SELECT id, sha256, time_sent, is_terminal, batch_id
+ FROM (
+ SELECT m.id, m.sha256, m.time_sent, m.is_terminal, NULL::bigint AS batch_id
+ FROM msg m
+ WHERE m.sha256 = $1
+ UNION ALL
+ SELECT m.id, m.sha256, m.time_sent, m.is_terminal, b.id AS batch_id
+ FROM msg_add_to_batch b
+ JOIN msg m ON m.id = b.msg_id
+ WHERE b.sha256 = $1
+ ) p
+ ORDER BY batch_id NULLS FIRST
+ LIMIT 1`, hash).Scan(&id, &canonical, &sent, &terminal, &batchID)
} else {
err = h.q().QueryRow(ctx, `SELECT sha256,time_sent,is_terminal FROM msg WHERE id=$1`, id).Scan(&canonical, &sent, &terminal)
}
@@ -105,7 +133,13 @@ func (h *MessageHandler) resolveParent(c *gin.Context, in *messageInput) bool {
return false
}
// A parent deleted for good no longer exists for the caller.
- if purgedFor(ctx, h.q(), middleware.GetIdentity(c), id) {
+ purged, err := purgedFor(ctx, h.q(), middleware.GetIdentity(c), id)
+ if err != nil {
+ log.Printf("resolve parent %d: trash state: %v", id, err)
+ c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to validate parent"})
+ return false
+ }
+ if purged {
c.JSON(400, gin.H{"error": "parent message not found"})
return false
}
diff --git a/internal/handlers/subaccounts.go b/internal/handlers/subaccounts.go
index 2b25d2e..f5c72ca 100644
--- a/internal/handlers/subaccounts.go
+++ b/internal/handlers/subaccounts.go
@@ -1,6 +1,7 @@
package handlers
import (
+ "context"
"errors"
"log"
"net/http"
@@ -137,7 +138,7 @@ func (h *SubAccountHandler) Create(c *gin.Context) {
// them in fmsgid automatically, in the owner's quota pool, rather than
// requiring a manual step. One already in the owner's pool was theirs
// before and is reinstated; one held by anyone else is refused.
- reinstated, err := middleware.RegisterLinkedFmsgID(h.idURL, subAddr, owner)
+ created, reinstated, err := middleware.RegisterLinkedFmsgIDContext(c.Request.Context(), h.idURL, subAddr, owner)
if errors.Is(err, middleware.ErrLinkedAddressTaken) {
c.JSON(http.StatusConflict, gin.H{"error": "that name is already taken; choose another"})
return
@@ -147,19 +148,20 @@ func (h *SubAccountHandler) Create(c *gin.Context) {
c.JSON(http.StatusServiceUnavailable, gin.H{"error": "identity service unavailable"})
return
}
- // undo a reinstatement if no grant comes of it, so a deleted address
- // doesn't start accepting new messages again without one
+ // Undo registration or reinstatement if no grant comes of it, so a
+ // newly-registered or deleted address doesn't stay accepting new messages
+ // without a grant. An already-active address or a concurrent create that
+ // won the race (ErrAlreadyExists) is left untouched so an active grant is
+ // never disabled.
granted := false
- if reinstated {
+ conflict := false
+ if created || reinstated {
defer func() {
- if !granted {
+ if !granted && !conflict {
disableAfterFailedCreate(h.idURL, subAddr)
}
}()
}
- if !checkAcceptingFmsgID(c, h.idURL, subAddr) {
- return
- }
key, hash, err := newPlaintextKey()
if err != nil {
@@ -168,6 +170,9 @@ func (h *SubAccountHandler) Create(c *gin.Context) {
return
}
if err := h.store.Create(c.Request.Context(), owner, in.Agent, subAddr, key.ID, hash, in.AllowedCIDRs, expires); err != nil {
+ if errors.Is(err, apiauth.ErrAlreadyExists) {
+ conflict = true
+ }
respondSubAccountStoreError(c, err)
return
}
@@ -186,12 +191,14 @@ func (h *SubAccountHandler) Create(c *gin.Context) {
})
}
-// disableAfterFailedCreate stops a reinstated derived address accepting new
-// messages again after its grant couldn't be created. It is best effort: the
-// create has already failed, so a failure here is only logged.
+// disableAfterFailedCreate stops a newly-registered or reinstated derived
+// address accepting new messages after its grant couldn't be created. It is
+// best effort: the create has already failed, so a failure here is only logged.
func disableAfterFailedCreate(idURL, addr string) {
- if err := middleware.DisableFmsgID(idURL, addr); err != nil {
- log.Printf("sub-account create: re-disabling reinstated address after failure: addr=%s: %v", addr, err)
+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+ defer cancel()
+ if err := middleware.DisableFmsgIDContext(ctx, idURL, addr); err != nil {
+ log.Printf("sub-account create: disabling address after failure: addr=%s: %v", addr, err)
}
}
@@ -306,7 +313,7 @@ func (h *SubAccountHandler) Delete(c *gin.Context) {
// sub-account again reinstates it. A delegated identity is an address in
// its own right and is left as it is.
if account.GrantType == apiauth.GrantTypeDerivedSubAccount {
- if err := middleware.DisableFmsgID(h.idURL, account.Addr); err != nil {
+ if err := middleware.DisableFmsgIDContext(c.Request.Context(), h.idURL, account.Addr); err != nil {
log.Printf("sub-account delete: fmsgid disable: addr=%s: %v", account.Addr, err)
c.JSON(http.StatusServiceUnavailable, gin.H{"error": "identity service unavailable"})
return
@@ -350,7 +357,7 @@ func newPlaintextKey() (apiauth.APIKey, []byte, error) {
}
func checkAcceptingFmsgID(c *gin.Context, idURL, addr string) bool {
- code, accepting, err := middleware.CheckFmsgID(idURL, addr)
+ code, accepting, err := middleware.CheckFmsgIDContext(c.Request.Context(), idURL, addr)
if err != nil {
log.Printf("sub-account fmsgid check: addr=%s: %v", addr, err)
c.JSON(http.StatusServiceUnavailable, gin.H{"error": "identity service unavailable"})
diff --git a/internal/handlers/thread.go b/internal/handlers/thread.go
index 4bef22d..5c0860b 100644
--- a/internal/handlers/thread.go
+++ b/internal/handlers/thread.go
@@ -26,6 +26,8 @@ const threadMaxHops = 100
const defaultThreadTextBytes int64 = 32 << 20
+var errThreadTooLarge = errors.New("thread text exceeds limit")
+
type threadBody struct {
Type string `json:"type"`
Size int `json:"size"`
@@ -96,12 +98,41 @@ func threadDownloadPath(id int64, filename string) string {
}
func populateThreadBodies(messages []threadMessage, dataDir string, maxTextBytes int64) error {
+ return populateThreadBodiesWithEdits(messages, dataDir, maxTextBytes, nil)
+}
+
+func populateThreadBodiesWithEdits(messages []threadMessage, dataDir string, maxTextBytes int64, edits map[int64]*effectiveEdit) error {
var textBytes int64
for i := range messages {
m := &messages[i]
if !m.Visible {
continue
}
+ if eff := edits[m.ID]; eff != nil {
+ m.Edited = eff.edited()
+ if eff.applied {
+ key := partCacheKey(hex.EncodeToString(eff.hash), "body", 0, "")
+ m.Body = &threadBody{
+ Type: m.Type,
+ Size: len(eff.data),
+ Download: threadDownloadPath(m.ID, ""),
+ CacheKey: key,
+ Cacheable: key != "",
+ }
+ if isTextType(m.Type) {
+ textBytes += int64(len(eff.data))
+ if textBytes > maxTextBytes {
+ return fmt.Errorf("%w: %d bytes", errThreadTooLarge, maxTextBytes)
+ }
+ if utf8.Valid(eff.data) {
+ text := string(eff.data)
+ m.Body.Text = &text
+ m.Body.Download = ""
+ }
+ }
+ continue
+ }
+ }
key := partCacheKey(m.MessageSHA256, "body", 0, "")
m.Body = &threadBody{Type: m.Type, Size: m.Size, Download: threadDownloadPath(m.ID, ""), CacheKey: key, Cacheable: key != ""}
if !isTextType(m.Type) {
@@ -109,7 +140,13 @@ func populateThreadBodies(messages []threadMessage, dataDir string, maxTextBytes
}
textBytes += int64(m.Size)
if textBytes > maxTextBytes {
- return fmt.Errorf("thread text exceeds %d bytes", maxTextBytes)
+ return fmt.Errorf("%w: %d bytes", errThreadTooLarge, maxTextBytes)
+ }
+ if m.dataPath == "" {
+ empty := ""
+ m.Body.Text = &empty
+ m.Body.Download = ""
+ continue
}
cleanPath, ok := safeDataPath(m.dataPath, dataDir)
if !ok {
@@ -119,6 +156,12 @@ func populateThreadBodies(messages []threadMessage, dataDir string, maxTextBytes
if err != nil {
return fmt.Errorf("read message %d body: %w", m.ID, err)
}
+ if int64(len(raw)) > int64(m.Size) {
+ textBytes += int64(len(raw)) - int64(m.Size)
+ if textBytes > maxTextBytes {
+ return fmt.Errorf("%w: %d bytes", errThreadTooLarge, maxTextBytes)
+ }
+ }
if utf8.Valid(raw) {
text := string(raw)
m.Body.Text = &text
@@ -128,6 +171,55 @@ func populateThreadBodies(messages []threadMessage, dataDir string, maxTextBytes
return nil
}
+func populateThreadTextEntries(entries []threadEntry, paths map[int64]string, edits map[int64]*effectiveEdit, dataDir string, maxTextBytes int64) error {
+ var textBytes int64
+ for i := range entries {
+ e := &entries[i]
+ if !e.Readable || !isTextType(e.Type) {
+ continue
+ }
+ if eff := edits[e.ID]; eff != nil && eff.applied {
+ // FMSG-008: an edited message renders as edited.
+ textBytes += int64(len(eff.data))
+ if textBytes > maxTextBytes {
+ return fmt.Errorf("%w: %d bytes", errThreadTooLarge, maxTextBytes)
+ }
+ e.Body = string(eff.data)
+ e.Text = true
+ continue
+ }
+ textBytes += int64(e.Size)
+ if textBytes > maxTextBytes {
+ return fmt.Errorf("%w: %d bytes", errThreadTooLarge, maxTextBytes)
+ }
+ dataPath := paths[e.ID]
+ if dataPath == "" {
+ e.Body = ""
+ e.Text = true
+ continue
+ }
+ cleanPath, ok := safeDataPath(dataPath, dataDir)
+ if !ok {
+ log.Printf("thread text: path traversal attempt: %s", dataPath)
+ continue
+ }
+ raw, rerr := os.ReadFile(cleanPath)
+ if rerr != nil {
+ log.Printf("thread text: read %d: %v", e.ID, rerr)
+ continue
+ }
+ if int64(len(raw)) > int64(e.Size) {
+ textBytes += int64(len(raw)) - int64(e.Size)
+ if textBytes > maxTextBytes {
+ return fmt.Errorf("%w: %d bytes", errThreadTooLarge, maxTextBytes)
+ }
+ }
+ e.Body = string(raw)
+ e.Text = true
+ }
+ return nil
+}
+
func loadThreadRelations(ctx context.Context, tx pgx.Tx, messages []threadMessage) error {
var ids []int64
byID := make(map[int64]*threadMessage)
@@ -271,41 +363,6 @@ func isTextType(mimeType string) bool {
// text, root first. The caller must be a participant of the requested
// message; ancestors the caller is not a participant of appear as
// placeholders (a recipient added mid-thread cannot read what came before).
-// applyThreadEdits presents each visible message that has an effective
-// FMSG-008 edit as edited: its body becomes the edited data, cached under the
-// edit message's hash since the subject's own hash no longer identifies it.
-func (h *MessageHandler) applyThreadEdits(ctx context.Context, messages []threadMessage) {
- var ids []int64
- for i := range messages {
- if messages[i].Visible {
- ids = append(ids, messages[i].ID)
- }
- }
- edits := h.loadEffectiveEdits(ctx, ids)
- for i := range messages {
- m := &messages[i]
- eff := edits[m.ID]
- if !m.Visible || eff == nil {
- continue
- }
- m.Edited = eff.edited()
- if !eff.applied || m.Body == nil {
- continue
- }
- key := partCacheKey(hex.EncodeToString(eff.hash), "body", 0, "")
- m.Body.Size = len(eff.data)
- m.Body.CacheKey = key
- m.Body.Cacheable = key != ""
- m.Body.Text = nil
- m.Body.Download = threadDownloadPath(m.ID, "")
- if isTextType(m.Type) && utf8.Valid(eff.data) {
- text := string(eff.data)
- m.Body.Text = &text
- m.Body.Download = ""
- }
- }
-}
-
func (h *MessageHandler) ThreadText(c *gin.Context) {
addrs, err := h.visibleAddrs(c)
if err != nil {
@@ -325,9 +382,17 @@ func (h *MessageHandler) ThreadText(c *gin.Context) {
return
}
// A message deleted for good is not found, as for one that doesn't exist.
- if hasTrash && purgedFor(ctx, h.q(), addrs[0], msgID) {
- c.JSON(http.StatusNotFound, gin.H{"error": "message not found"})
- return
+ if hasTrash {
+ purged, perr := purgedFor(ctx, h.q(), addrs[0], msgID)
+ if perr != nil {
+ log.Printf("thread text: trash state %d: %v", msgID, perr)
+ c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to retrieve thread"})
+ return
+ }
+ if purged {
+ c.JSON(http.StatusNotFound, gin.H{"error": "message not found"})
+ return
+ }
}
rows, err := h.q().Query(ctx, `
@@ -353,7 +418,6 @@ func (h *MessageHandler) ThreadText(c *gin.Context) {
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to retrieve thread"})
return
}
- defer rows.Close()
var entries []threadEntry
paths := map[int64]string{}
@@ -361,6 +425,7 @@ func (h *MessageHandler) ThreadText(c *gin.Context) {
var e threadEntry
var dataPath string
if err := rows.Scan(&e.ID, &e.From, &e.TimeSent, &e.Type, &e.Size, &dataPath, &e.Readable); err != nil {
+ rows.Close()
log.Printf("thread text: scan: %v", err)
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to retrieve thread"})
return
@@ -368,6 +433,7 @@ func (h *MessageHandler) ThreadText(c *gin.Context) {
paths[e.ID] = dataPath
entries = append(entries, e)
}
+ rows.Close()
if err := rows.Err(); err != nil && !errors.Is(err, pgx.ErrNoRows) {
log.Printf("thread text: rows %d: %v", msgID, err)
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to retrieve thread"})
@@ -395,35 +461,21 @@ func (h *MessageHandler) ThreadText(c *gin.Context) {
entryIDs = append(entryIDs, entries[i].ID)
}
}
- edits := h.loadEffectiveEdits(ctx, entryIDs)
+ edits, err := h.loadEffectiveEdits(ctx, entryIDs)
+ if err != nil {
+ log.Printf("thread text: load edits %d: %v", msgID, err)
+ c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to retrieve thread"})
+ return
+ }
- for i := range entries {
- e := &entries[i]
- if !e.Readable || !isTextType(e.Type) {
- continue
- }
- if eff := edits[e.ID]; eff != nil && eff.applied {
- // FMSG-008: an edited message renders as edited.
- e.Body = string(eff.data)
- e.Text = true
- continue
- }
- dataPath := paths[e.ID]
- if dataPath == "" {
- continue
- }
- cleanPath, ok := safeDataPath(dataPath, h.DataDir)
- if !ok {
- log.Printf("thread text: path traversal attempt: %s", dataPath)
- continue
- }
- raw, rerr := os.ReadFile(cleanPath)
- if rerr != nil {
- log.Printf("thread text: read %d: %v", e.ID, rerr)
- continue
+ if err := populateThreadTextEntries(entries, paths, edits, h.DataDir, defaultThreadTextBytes); err != nil {
+ if errors.Is(err, errThreadTooLarge) {
+ c.JSON(http.StatusRequestEntityTooLarge, gin.H{"error": err.Error(), "code": "thread_too_large"})
+ return
}
- e.Body = string(raw)
- e.Text = true
+ log.Printf("thread text: bodies %d: %v", msgID, err)
+ c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to retrieve thread"})
+ return
}
c.Data(http.StatusOK, "text/plain; charset=utf-8", []byte(renderThreadText(entries)))
@@ -450,9 +502,17 @@ func (h *MessageHandler) ThreadMessages(c *gin.Context) {
return
}
// A message deleted for good is not found, as for one that doesn't exist.
- if hasTrash && purgedFor(ctx, h.q(), addrs[0], msgID) {
- c.JSON(http.StatusNotFound, gin.H{"error": "message not found"})
- return
+ if hasTrash {
+ purged, perr := purgedFor(ctx, h.q(), addrs[0], msgID)
+ if perr != nil {
+ log.Printf("thread messages: trash state %d: %v", msgID, perr)
+ c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to retrieve thread"})
+ return
+ }
+ if purged {
+ c.JSON(http.StatusNotFound, gin.H{"error": "message not found"})
+ return
+ }
}
tx, err := h.DB.Pool.BeginTx(ctx, pgx.TxOptions{IsoLevel: pgx.RepeatableRead, AccessMode: pgx.ReadOnly})
if err != nil {
@@ -538,12 +598,26 @@ func (h *MessageHandler) ThreadMessages(c *gin.Context) {
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to retrieve thread"})
return
}
+ var visibleIDs []int64
+ for i := range messages {
+ if messages[i].Visible {
+ visibleIDs = append(visibleIDs, messages[i].ID)
+ }
+ }
+ txHandler := *h
+ txHandler.query = tx
+ edits, err := txHandler.loadEffectiveEdits(ctx, visibleIDs)
+ if err != nil {
+ log.Printf("thread messages: edits %d: %v", msgID, err)
+ c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to retrieve thread"})
+ return
+ }
if err = tx.Commit(ctx); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to retrieve thread"})
return
}
- if err = populateThreadBodies(messages, h.DataDir, defaultThreadTextBytes); err != nil {
- if strings.Contains(err.Error(), "exceeds") {
+ if err = populateThreadBodiesWithEdits(messages, h.DataDir, defaultThreadTextBytes, edits); err != nil {
+ if errors.Is(err, errThreadTooLarge) {
c.JSON(http.StatusRequestEntityTooLarge, gin.H{"error": err.Error(), "code": "thread_too_large"})
return
}
@@ -551,7 +625,6 @@ func (h *MessageHandler) ThreadMessages(c *gin.Context) {
c.JSON(http.StatusInternalServerError, gin.H{"error": "thread data is unavailable", "code": "thread_data_unavailable"})
return
}
- h.applyThreadEdits(ctx, messages)
complete := true
for i := range messages {
if !messages[i].Visible {
diff --git a/internal/handlers/thread_test.go b/internal/handlers/thread_test.go
index 678af03..34ff1c6 100644
--- a/internal/handlers/thread_test.go
+++ b/internal/handlers/thread_test.go
@@ -2,6 +2,7 @@ package handlers
import (
"encoding/json"
+ "errors"
"os"
"path/filepath"
"strings"
@@ -98,3 +99,94 @@ func TestThreadAttachmentCacheKey(t *testing.T) {
t.Fatalf("hashless message must not be cacheable: %q", got)
}
}
+
+func TestPopulateThreadBodies_EmptyDataPathAndSizeLimit(t *testing.T) {
+ dir := t.TempDir()
+ messages := []threadMessage{
+ {ID: 1, Visible: true, Type: "text/plain", Size: 0, MessageSHA256: "abc", dataPath: ""},
+ }
+ if err := populateThreadBodies(messages, dir, 10); err != nil {
+ t.Fatalf("empty dataPath failed: %v", err)
+ }
+ if messages[0].Body == nil || messages[0].Body.Text == nil || *messages[0].Body.Text != "" || messages[0].Body.Download != "" {
+ t.Fatalf("expected empty inlined text body, got %#v", messages[0].Body)
+ }
+
+ bigPath := filepath.Join(dir, "big.txt")
+ if err := os.WriteFile(bigPath, []byte("0123456789"), 0600); err != nil {
+ t.Fatal(err)
+ }
+ over := []threadMessage{
+ {ID: 2, Visible: true, Type: "text/plain", Size: 10, dataPath: bigPath},
+ }
+ err := populateThreadBodies(over, dir, 5)
+ if !errors.Is(err, errThreadTooLarge) {
+ t.Fatalf("expected errThreadTooLarge, got %v", err)
+ }
+}
+
+func TestPopulateThreadBodiesWithEdits_SkipsUneditedDiskRead(t *testing.T) {
+ dir := t.TempDir()
+ messages := []threadMessage{
+ {ID: 1, Visible: true, Type: "text/plain", Size: 5, dataPath: filepath.Join(dir, "missing-original.txt")},
+ }
+ edits := map[int64]*effectiveEdit{
+ 1: {msgID: 99, time: 123, hash: []byte{0xde, 0xad}, applied: true, data: []byte("edited")},
+ }
+ if err := populateThreadBodiesWithEdits(messages, dir, 10, edits); err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ if messages[0].Body == nil || messages[0].Body.Text == nil || *messages[0].Body.Text != "edited" {
+ t.Fatalf("expected edited text body, got %#v", messages[0].Body)
+ }
+ if messages[0].Body.CacheKey != "sha256:dead:body" {
+ t.Fatalf("unexpected cache key: %q", messages[0].Body.CacheKey)
+ }
+
+ // Edited body exceeding maxTextBytes must return errThreadTooLarge.
+ if err := populateThreadBodiesWithEdits(messages, dir, 3, edits); !errors.Is(err, errThreadTooLarge) {
+ t.Fatalf("expected errThreadTooLarge for edited body, got %v", err)
+ }
+}
+
+func TestPopulateThreadTextEntries_SizeLimitAndEmptyBody(t *testing.T) {
+ dir := t.TempDir()
+ p := filepath.Join(dir, "body.txt")
+ if err := os.WriteFile(p, []byte("hello world"), 0600); err != nil {
+ t.Fatal(err)
+ }
+
+ entries := []threadEntry{
+ {ID: 1, Type: "text/plain", Size: 0, Readable: true},
+ {ID: 2, Type: "text/plain", Size: 11, Readable: true},
+ }
+ paths := map[int64]string{1: "", 2: p}
+ if err := populateThreadTextEntries(entries, paths, nil, dir, 20); err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ if !entries[0].Text || entries[0].Body != "" {
+ t.Fatalf("empty dataPath entry = %+v, want Text=true Body=\"\"", entries[0])
+ }
+ if !entries[1].Text || entries[1].Body != "hello world" {
+ t.Fatalf("file entry = %+v, want Text=true Body=\"hello world\"", entries[1])
+ }
+
+ // Exceeding maxTextBytes returns errThreadTooLarge.
+ entries2 := []threadEntry{
+ {ID: 2, Type: "text/plain", Size: 11, Readable: true},
+ }
+ if err := populateThreadTextEntries(entries2, paths, nil, dir, 10); !errors.Is(err, errThreadTooLarge) {
+ t.Fatalf("expected errThreadTooLarge, got %v", err)
+ }
+
+ // Edited entry exceeding maxTextBytes also returns errThreadTooLarge.
+ entries3 := []threadEntry{
+ {ID: 1, Type: "text/plain", Size: 0, Readable: true},
+ }
+ edits := map[int64]*effectiveEdit{
+ 1: {msgID: 50, applied: true, data: []byte("0123456789")},
+ }
+ if err := populateThreadTextEntries(entries3, paths, edits, dir, 5); !errors.Is(err, errThreadTooLarge) {
+ t.Fatalf("expected errThreadTooLarge for edited thread text, got %v", err)
+ }
+}
diff --git a/internal/handlers/transaction.go b/internal/handlers/transaction.go
index ef5aed1..81b9ef7 100644
--- a/internal/handlers/transaction.go
+++ b/internal/handlers/transaction.go
@@ -75,6 +75,43 @@ func afterCommit(c *gin.Context, f func()) {
f()
}
}
+// beginOrReuseTx returns q directly when it is already a pgx.Tx (inside Atomic),
+// avoiding a redundant SAVEPOINT round-trip. When reusing an outer transaction,
+// commit and rollback are no-ops because Atomic commits on <400 responses and
+// rolls back on >=400 responses.
+func beginOrReuseTx(ctx context.Context, q queries) (pgx.Tx, func() error, func(), error) {
+ if existing, ok := q.(pgx.Tx); ok {
+ return existing, func() error { return nil }, func() {}, nil
+ }
+ tx, err := q.Begin(ctx)
+ if err != nil {
+ return nil, nil, nil, err
+ }
+ return tx, func() error { return tx.Commit(ctx) }, func() { _ = tx.Rollback(ctx) }, nil
+}
+
+// limitRequestBody bounds c.Request.Body with http.MaxBytesReader when limit > 0.
+func limitRequestBody(c *gin.Context, limit int64) {
+ if limit > 0 && c.Request != nil && c.Request.Body != nil {
+ c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, limit)
+ }
+}
+
+// limitJSONBody bounds a JSON message request body carrying a data string of up
+// to maxDataSize decoded bytes. A 6x multiplier accommodates worst-case JSON
+// string escaping (e.g. HTML characters escaped as \u003c or ASCII-escaped
+// non-ASCII runes) plus 1 MiB for envelope metadata.
+func limitJSONBody(c *gin.Context, maxDataSize int64) {
+ if maxDataSize > 0 {
+ limitRequestBody(c, maxDataSize*6+(1<<20))
+ }
+}
+
+func isMaxBytesError(err error) bool {
+ var maxErr *http.MaxBytesError
+ return errors.As(err, &maxErr)
+}
+
func createdFile(c *gin.Context, path string) { onRollback(c, func() { _ = os.Remove(path) }) }
func atomic(c *gin.Context, database *db.DB, next func(pgx.Tx)) {
diff --git a/internal/handlers/trash.go b/internal/handlers/trash.go
index ac0ff76..d79dda3 100644
--- a/internal/handlers/trash.go
+++ b/internal/handlers/trash.go
@@ -44,13 +44,13 @@ func trashStateQ(ctx context.Context, q queries, addr string, msgID int64) (stri
}
// purgedFor reports whether msgID is deleted for good by addr. Lookup errors
-// are logged and treated as not purged.
-func purgedFor(ctx context.Context, q queries, addr string, msgID int64) bool {
+// are propagated so callers fail closed instead of exposing purged messages.
+func purgedFor(ctx context.Context, q queries, addr string, msgID int64) (bool, error) {
state, err := trashStateQ(ctx, q, addr, msgID)
if err != nil {
- log.Printf("trash state of %d for %s: %v", msgID, addr, err)
+ return false, err
}
- return state == trashPurged
+ return state == trashPurged, nil
}
// hasTrash reports whether addr has deleted anything.
@@ -136,10 +136,14 @@ func (h *MessageHandler) trashSubtree(ctx context.Context, addr string, msgID in
// notifyTrash tells addr's connections that ids moved in or out of the trash.
// The notifications are sent when the transaction commits.
func (h *MessageHandler) notifyTrash(ctx context.Context, addr string, ids []int64) {
- for _, id := range ids {
- if _, err := h.q().Exec(ctx, `SELECT pg_notify('msg_trash', $1)`, fmt.Sprintf("%d,%s", id, addr)); err != nil {
- log.Printf("trash %d: notify: %v", id, err)
- }
+ if len(ids) == 0 {
+ return
+ }
+ if _, err := h.q().Exec(ctx,
+ `SELECT pg_notify('msg_trash', id::text || ',' || $2) FROM unnest($1::bigint[]) AS id`,
+ ids, addr,
+ ); err != nil {
+ log.Printf("trash notify %s: %v", addr, err)
}
}
@@ -217,7 +221,17 @@ func (h *MessageHandler) Restore(c *gin.Context) {
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to restore message"})
return
}
- if !ok || purgedFor(ctx, h.q(), identity, msgID) {
+ if !ok {
+ c.JSON(http.StatusNotFound, gin.H{"error": "message not found"})
+ return
+ }
+ purged, err := purgedFor(ctx, h.q(), identity, msgID)
+ if err != nil {
+ log.Printf("restore %d: trash state: %v", msgID, err)
+ c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to restore message"})
+ return
+ }
+ if purged {
c.JSON(http.StatusNotFound, gin.H{"error": "message not found"})
return
}
@@ -295,12 +309,13 @@ func (h *MessageHandler) purge(c *gin.Context, identity string, msgID int64, thr
if h.IDURL != "" && len(releases) > 0 {
idURL := h.IDURL
afterCommit(c, func() {
+ postCtx := context.WithoutCancel(ctx)
for _, r := range releases {
var err error
if r.send {
- err = middleware.ReleaseFmsgIDSend(idURL, identity, now, r.size)
+ err = middleware.ReleaseFmsgIDSendContext(postCtx, idURL, identity, now, r.size)
} else {
- err = middleware.ReleaseFmsgIDRecv(idURL, identity, now, r.size)
+ err = middleware.ReleaseFmsgIDRecvContext(postCtx, idURL, identity, now, r.size)
}
if err != nil {
log.Printf("release usage of %s: %v", identity, err)
@@ -351,15 +366,66 @@ func (h *MessageHandler) markPurged(ctx context.Context, identity string, ids []
// delete once the transaction commits.
func (h *MessageHandler) removeUnheld(ctx context.Context, ids []int64) (int, []string, error) {
var removed int
- var files []string
+ purgeEnabled := false
+ type pathPair struct {
+ raw string
+ clean string
+ }
+ seenPaths := make(map[string]struct{})
+ var candidates []pathPair
+ var rawPaths []string
for _, id := range ids {
- gone, paths, err := h.removeIfUnheld(ctx, id)
+ gone, paths, err := h.removeIfUnheld(ctx, id, &purgeEnabled)
if err != nil {
return 0, nil, err
}
if gone {
removed++
- files = append(files, paths...)
+ for _, p := range paths {
+ clean, ok := safeDataPath(p, h.DataDir)
+ if !ok {
+ continue
+ }
+ if _, dup := seenPaths[p]; dup {
+ continue
+ }
+ seenPaths[p] = struct{}{}
+ candidates = append(candidates, pathPair{raw: p, clean: clean})
+ rawPaths = append(rawPaths, p)
+ }
+ }
+ }
+ if len(rawPaths) == 0 {
+ return removed, nil, nil
+ }
+ // Check in one batched query which candidate filepaths are still referenced
+ // by any remaining message or attachment row.
+ rows, err := h.q().Query(ctx, `
+ SELECT DISTINCT p FROM (
+ SELECT filepath AS p FROM msg WHERE filepath = ANY($1)
+ UNION ALL
+ SELECT filepath AS p FROM msg_attachment WHERE filepath = ANY($1)
+ ) used`, rawPaths)
+ if err != nil {
+ return 0, nil, err
+ }
+ shared := make(map[string]bool)
+ for rows.Next() {
+ var p string
+ if err := rows.Scan(&p); err != nil {
+ rows.Close()
+ return 0, nil, err
+ }
+ shared[p] = true
+ }
+ rows.Close()
+ if err := rows.Err(); err != nil {
+ return 0, nil, err
+ }
+ var files []string
+ for _, c := range candidates {
+ if !shared[c.raw] {
+ files = append(files, c.clean)
}
}
return removed, files, nil
@@ -482,7 +548,7 @@ func (h *MessageHandler) retryMaxAge() float64 {
// in dd.sql). A delivery fmsgd has given up on doesn't keep the message. It
// returns whether it was removed and the stored files to delete once the
// transaction commits.
-func (h *MessageHandler) removeIfUnheld(ctx context.Context, msgID int64) (bool, []string, error) {
+func (h *MessageHandler) removeIfUnheld(ctx context.Context, msgID int64, purgeEnabled *bool) (bool, []string, error) {
var held, pending bool
now := float64(time.Now().UnixMicro()) / 1e6
err := h.q().QueryRow(ctx, `SELECT
@@ -520,11 +586,19 @@ func (h *MessageHandler) removeIfUnheld(ctx context.Context, msgID int64) (bool,
paths = append(paths, p)
}
rows.Close()
+ if err := rows.Err(); err != nil {
+ return false, nil, err
+ }
// fmsgd keeps sent messages immutable unless the transaction says it is
- // purging (fmsgd dd.sql, protect_msg_parts).
+ // purging (fmsgd dd.sql, protect_msg_parts). Enable once per transaction.
+ if !*purgeEnabled {
+ if _, err := h.q().Exec(ctx, `SET LOCAL fmsg.purge = 'on'`); err != nil {
+ return false, nil, fmt.Errorf("SET LOCAL fmsg.purge = 'on': %w", err)
+ }
+ *purgeEnabled = true
+ }
for _, q := range []string{
- `SET LOCAL fmsg.purge = 'on'`,
`UPDATE msg SET pid = NULL WHERE pid = $1`,
`DELETE FROM msg_add_to_notify WHERE batch_id IN (SELECT id FROM msg_add_to_batch WHERE msg_id = $1)`,
`DELETE FROM msg_add_to WHERE msg_id = $1`,
@@ -533,33 +607,10 @@ func (h *MessageHandler) removeIfUnheld(ctx context.Context, msgID int64) (bool,
`DELETE FROM msg_attachment WHERE msg_id = $1`,
`DELETE FROM msg WHERE id = $1`,
} {
- var err error
- if strings.Contains(q, "$1") {
- _, err = h.q().Exec(ctx, q, msgID)
- } else {
- _, err = h.q().Exec(ctx, q)
- }
- if err != nil {
+ if _, err := h.q().Exec(ctx, q, msgID); err != nil {
return false, nil, fmt.Errorf("%s: %w", q, err)
}
}
- // Only delete files inside the data directory that no other message
- // still uses.
- var files []string
- for _, p := range paths {
- clean, ok := safeDataPath(p, h.DataDir)
- if !ok {
- continue
- }
- var shared bool
- if err := h.q().QueryRow(ctx, `SELECT EXISTS (SELECT 1 FROM msg WHERE filepath = $1)
- OR EXISTS (SELECT 1 FROM msg_attachment WHERE filepath = $1)`, p).Scan(&shared); err != nil {
- return false, nil, err
- }
- if !shared {
- files = append(files, clean)
- }
- }
- return true, files, nil
+ return true, paths, nil
}
diff --git a/internal/handlers/ws.go b/internal/handlers/ws.go
index 9b728f3..ab9e7f7 100644
--- a/internal/handlers/ws.go
+++ b/internal/handlers/ws.go
@@ -55,10 +55,7 @@ func NewWSHandler(verifier *middleware.Verifier, hub *Hub, allowedOrigins []stri
// Non-browser client (no Origin header).
return true
}
- if len(allowedOrigins) == 0 {
- return true
- }
- if slices.Contains(allowedOrigins, origin) {
+ if len(allowedOrigins) == 0 || slices.Contains(allowedOrigins, "*") || slices.Contains(allowedOrigins, origin) {
return true
}
log.Printf("ws: rejected upgrade from origin %q", origin)
@@ -159,6 +156,7 @@ func (c *wsClient) close() {
func (c *wsClient) writePump() {
ticker := time.NewTicker(wsPingPeriod)
defer ticker.Stop()
+ defer c.close()
for {
select {
case payload := <-c.send:
diff --git a/internal/handlers/ws_test.go b/internal/handlers/ws_test.go
index 288fe79..c6f012d 100644
--- a/internal/handlers/ws_test.go
+++ b/internal/handlers/ws_test.go
@@ -1,11 +1,15 @@
package handlers
import (
+ "net/http"
"net/http/httptest"
"net/url"
+ "strings"
"testing"
+ "time"
"github.com/gin-gonic/gin"
+ "github.com/gorilla/websocket"
)
func TestActAsParam(t *testing.T) {
@@ -37,3 +41,69 @@ func TestActAsParam(t *testing.T) {
})
}
}
+
+func TestWSCheckOrigin(t *testing.T) {
+ tests := []struct {
+ name string
+ allowed []string
+ origin string
+ want bool
+ }{
+ {name: "no origin header allowed", allowed: []string{"https://app.example.com"}, origin: "", want: true},
+ {name: "empty allowlist allows any", allowed: nil, origin: "https://any.example.com", want: true},
+ {name: "exact match allowed", allowed: []string{"https://app.example.com"}, origin: "https://app.example.com", want: true},
+ {name: "unlisted origin rejected", allowed: []string{"https://app.example.com"}, origin: "https://evil.example.com", want: false},
+ {name: "wildcard allows any origin", allowed: []string{"*"}, origin: "https://anywhere.example.com", want: true},
+ {name: "wildcard among origins allows any", allowed: []string{"https://a.example.com", "*"}, origin: "https://b.example.com", want: true},
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ h := NewWSHandler(nil, nil, tt.allowed)
+ req := httptest.NewRequest(http.MethodGet, "/fmsg/ws", nil)
+ if tt.origin != "" {
+ req.Header.Set("Origin", tt.origin)
+ }
+ if got := h.upgrader.CheckOrigin(req); got != tt.want {
+ t.Errorf("CheckOrigin(%q) with allowed=%v = %v, want %v", tt.origin, tt.allowed, got, tt.want)
+ }
+ })
+ }
+}
+
+func TestWSWritePumpClosesClientOnWriteError(t *testing.T) {
+ clientCh := make(chan *wsClient, 1)
+ upgrader := websocket.Upgrader{CheckOrigin: func(*http.Request) bool { return true }}
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ conn, err := upgrader.Upgrade(w, r, nil)
+ if err != nil {
+ return
+ }
+ c := &wsClient{
+ conn: conn,
+ addr: "@alice@example.com",
+ send: make(chan []byte, 4),
+ done: make(chan struct{}),
+ }
+ clientCh <- c
+ c.writePump()
+ }))
+ defer srv.Close()
+
+ wsURL := "ws" + strings.TrimPrefix(srv.URL, "http")
+ peer, _, err := websocket.DefaultDialer.Dial(wsURL, nil)
+ if err != nil {
+ t.Fatalf("dial: %v", err)
+ }
+ c := <-clientCh
+
+ // Close both ends' underlying socket so the server's next write fails.
+ _ = peer.Close()
+ _ = c.conn.UnderlyingConn().Close()
+ c.send <- []byte(`{"type":"new_msg"}`)
+
+ select {
+ case <-c.done:
+ case <-time.After(2 * time.Second):
+ t.Fatal("writePump did not close client on write error")
+ }
+}
diff --git a/internal/middleware/fmsgid_test.go b/internal/middleware/fmsgid_test.go
index a81ec34..cd2dc2e 100644
--- a/internal/middleware/fmsgid_test.go
+++ b/internal/middleware/fmsgid_test.go
@@ -187,3 +187,35 @@ func TestCheckFmsgIDEscapesAddress(t *testing.T) {
t.Fatalf("lookup: code=%d, accepting=%v, err=%v", code, accepting, err)
}
}
+
+func TestRegisterLinkedFmsgIDContextReportsCreatedAndReinstated(t *testing.T) {
+ cases := []struct {
+ name string
+ status int
+ body string
+ wantCreated bool
+ wantReinstated bool
+ }{
+ {name: "created json", status: http.StatusCreated, body: `{"created":true,"reinstated":false}`, wantCreated: true},
+ {name: "reinstated json", status: http.StatusOK, body: `{"created":false,"reinstated":true}`, wantReinstated: true},
+ {name: "already active json", status: http.StatusOK, body: `{"created":false,"reinstated":false}`},
+ {name: "legacy 201 empty body", status: http.StatusCreated, body: "", wantCreated: true},
+ {name: "legacy 200 empty body", status: http.StatusOK, body: ""},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ w.WriteHeader(tc.status)
+ _, _ = w.Write([]byte(tc.body))
+ }))
+ defer srv.Close()
+ created, reinstated, err := RegisterLinkedFmsgIDContext(t.Context(), srv.URL, "@alice_bot@example.com", "@alice@example.com")
+ if err != nil {
+ t.Fatalf("unexpected err: %v", err)
+ }
+ if created != tc.wantCreated || reinstated != tc.wantReinstated {
+ t.Fatalf("got (created=%v, reinstated=%v), want (%v, %v)", created, reinstated, tc.wantCreated, tc.wantReinstated)
+ }
+ })
+ }
+}
diff --git a/internal/middleware/fmsgid_usage.go b/internal/middleware/fmsgid_usage.go
index 27a2832..034ea22 100644
--- a/internal/middleware/fmsgid_usage.go
+++ b/internal/middleware/fmsgid_usage.go
@@ -2,6 +2,7 @@ package middleware
import (
"bytes"
+ "context"
"encoding/json"
"errors"
"fmt"
@@ -37,8 +38,13 @@ type FmsgIDDetail struct {
// that is 200. A limit fmsgid leaves out is unlimited. A 200 answer also
// refreshes the cached lookup CheckFmsgID uses.
func FetchFmsgIDDetail(idURL, addr string) (*FmsgIDDetail, int, error) {
+ return FetchFmsgIDDetailContext(context.Background(), idURL, addr)
+}
+
+// FetchFmsgIDDetailContext is like FetchFmsgIDDetail, using ctx for the HTTP request.
+func FetchFmsgIDDetailContext(ctx context.Context, idURL, addr string) (*FmsgIDDetail, int, error) {
lookupURL := fmsgIDAddressURL(idURL, addr)
- req, err := http.NewRequest(http.MethodGet, lookupURL, nil)
+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, lookupURL, nil)
if err != nil {
return nil, 0, err
}
@@ -46,7 +52,7 @@ func FetchFmsgIDDetail(idURL, addr string) (*FmsgIDDetail, int, error) {
if err != nil {
return nil, 0, err
}
- defer resp.Body.Close()
+ defer drainAndClose(resp.Body)
if resp.StatusCode != http.StatusOK {
return nil, resp.StatusCode, nil
}
@@ -66,46 +72,67 @@ func FetchFmsgIDDetail(idURL, addr string) (*FmsgIDDetail, int, error) {
detail := raw.FmsgIDDetail
detail.AcceptingNew = *raw.AcceptingNew
- fmsgIDCache.Store(lookupURL, fmsgIDEntry{
- expires: time.Now().Add(fmsgIDCacheTTL),
+ now := time.Now()
+ fmsgIDCache.set(fmsgIDCacheKey(idURL, addr), fmsgIDEntry{
+ expires: now.Add(fmsgIDCacheTTL),
code: http.StatusOK,
acceptingNew: detail.AcceptingNew,
- })
+ }, now)
return &detail, http.StatusOK, nil
}
// RecordFmsgIDRecv records with fmsgid that addr received a message of size
// bytes at ts (seconds since the Unix epoch).
func RecordFmsgIDRecv(idURL, addr string, ts float64, size int64) error {
- return postFmsgIDUsage(idURL, "recv", addr, ts, size)
+ return RecordFmsgIDRecvContext(context.Background(), idURL, addr, ts, size)
+}
+
+// RecordFmsgIDRecvContext is like RecordFmsgIDRecv, using ctx for the HTTP request.
+func RecordFmsgIDRecvContext(ctx context.Context, idURL, addr string, ts float64, size int64) error {
+ return postFmsgIDUsage(ctx, idURL, "recv", addr, ts, size)
}
// RecordFmsgIDSend records with fmsgid that addr sent a message of size bytes
// at ts (seconds since the Unix epoch).
func RecordFmsgIDSend(idURL, addr string, ts float64, size int64) error {
- return postFmsgIDUsage(idURL, "send", addr, ts, size)
+ return RecordFmsgIDSendContext(context.Background(), idURL, addr, ts, size)
+}
+
+// RecordFmsgIDSendContext is like RecordFmsgIDSend, using ctx for the HTTP request.
+func RecordFmsgIDSendContext(ctx context.Context, idURL, addr string, ts float64, size int64) error {
+ return postFmsgIDUsage(ctx, idURL, "send", addr, ts, size)
}
// ReleaseFmsgIDSend gives back to addr the storage of a message it sent that
// is deleted for good: size bytes come off its sent size total, not off its
// daily usage.
func ReleaseFmsgIDSend(idURL, addr string, ts float64, size int64) error {
- return postFmsgIDUsage(idURL, "send/release", addr, ts, size)
+ return ReleaseFmsgIDSendContext(context.Background(), idURL, addr, ts, size)
+}
+
+// ReleaseFmsgIDSendContext is like ReleaseFmsgIDSend, using ctx for the HTTP request.
+func ReleaseFmsgIDSendContext(ctx context.Context, idURL, addr string, ts float64, size int64) error {
+ return postFmsgIDUsage(ctx, idURL, "send/release", addr, ts, size)
}
// ReleaseFmsgIDRecv gives back to addr the storage of a message it received
// that is deleted for good: size bytes come off its received size total, not
// off its daily usage.
func ReleaseFmsgIDRecv(idURL, addr string, ts float64, size int64) error {
- return postFmsgIDUsage(idURL, "recv/release", addr, ts, size)
+ return ReleaseFmsgIDRecvContext(context.Background(), idURL, addr, ts, size)
+}
+
+// ReleaseFmsgIDRecvContext is like ReleaseFmsgIDRecv, using ctx for the HTTP request.
+func ReleaseFmsgIDRecvContext(ctx context.Context, idURL, addr string, ts float64, size int64) error {
+ return postFmsgIDUsage(ctx, idURL, "recv/release", addr, ts, size)
}
-func postFmsgIDUsage(idURL, part, addr string, ts float64, size int64) error {
+func postFmsgIDUsage(ctx context.Context, idURL, part, addr string, ts float64, size int64) error {
payload, err := json.Marshal(map[string]any{"address": addr, "ts": ts, "size": size})
if err != nil {
return err
}
- req, err := http.NewRequest(http.MethodPost, strings.TrimRight(idURL, "/")+"/fmsgid/"+part, bytes.NewReader(payload))
+ req, err := http.NewRequestWithContext(ctx, http.MethodPost, strings.TrimRight(idURL, "/")+"/fmsgid/"+part, bytes.NewReader(payload))
if err != nil {
return err
}
@@ -114,7 +141,7 @@ func postFmsgIDUsage(idURL, part, addr string, ts float64, size int64) error {
if err != nil {
return err
}
- defer resp.Body.Close()
+ defer drainAndClose(resp.Body)
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("POST /fmsgid/%s returned %d", part, resp.StatusCode)
}
diff --git a/internal/middleware/jwt.go b/internal/middleware/jwt.go
index 467d55c..f5d2138 100644
--- a/internal/middleware/jwt.go
+++ b/internal/middleware/jwt.go
@@ -5,6 +5,7 @@ import (
"bytes"
"context"
"crypto/ed25519"
+ "encoding/base64"
"encoding/json"
"errors"
"fmt"
@@ -96,6 +97,7 @@ type Verifier struct {
addressClaim string
apiParser *jwt.Parser
apiPublicKey ed25519.PublicKey
+ apiIssuer string
apiKeys APIKeyChecker
idURL string
}
@@ -150,6 +152,7 @@ func NewVerifier(cfg Config) (*Verifier, error) {
cfg.APIAudience = apiauth.DefaultTokenAudience
}
v.apiPublicKey = cfg.APIPublicKey
+ v.apiIssuer = cfg.APIIssuer
v.apiKeys = cfg.APIKeys
v.apiParser = jwt.NewParser(
jwt.WithValidMethods([]string{jwt.SigningMethodEdDSA.Alg()}),
@@ -176,6 +179,28 @@ func (v *Verifier) Authenticate(tokenStr string) (addr string, status int, msg s
}
func (v *Verifier) AuthenticateRequest(ctx context.Context, tokenStr, remoteAddr, actAs string) (authResult, int, string) {
+ // When both IdP JWKS and first-party API token auth are configured, peek
+ // at the unverified header/claims to route first-party API tokens directly
+ // to local Ed25519 verification instead of scanning the JWKS key set first.
+ if v.idpParser != nil && v.apiParser != nil && looksLikeAPIToken(tokenStr, v.apiIssuer) {
+ res, err := v.authenticateAPIToken(ctx, tokenStr, remoteAddr, actAs)
+ if err == nil {
+ return res, http.StatusOK, ""
+ }
+ if status, msg, ok := authFailureFromError(err); ok {
+ return authResult{}, status, msg
+ }
+ res, err = v.authenticateIdP(ctx, tokenStr, actAs)
+ if err == nil {
+ return res, http.StatusOK, ""
+ }
+ if status, msg, ok := authFailureFromError(err); ok {
+ return authResult{}, status, msg
+ }
+ log.Printf("auth rejected: reason=parse_error")
+ return authResult{}, http.StatusUnauthorized, "invalid token"
+ }
+
if v.idpParser != nil {
res, err := v.authenticateIdP(ctx, tokenStr, actAs)
if err == nil {
@@ -198,6 +223,44 @@ func (v *Verifier) AuthenticateRequest(ctx context.Context, tokenStr, remoteAddr
return authResult{}, http.StatusUnauthorized, "invalid token"
}
+// looksLikeAPIToken inspects the unverified JWT header and payload to detect
+// first-party API tokens (which carry no kid header and have iss == apiIssuer).
+// The token is still cryptographically verified before being accepted.
+func looksLikeAPIToken(tokenStr, apiIssuer string) bool {
+ if apiIssuer == "" {
+ return false
+ }
+ hdrB64, rest, ok := strings.Cut(tokenStr, ".")
+ if !ok {
+ return false
+ }
+ payloadB64, sigB64, ok := strings.Cut(rest, ".")
+ if !ok || strings.Contains(sigB64, ".") {
+ return false
+ }
+ hdrRaw, err := base64.RawURLEncoding.DecodeString(hdrB64)
+ if err != nil {
+ return false
+ }
+ var hdr struct {
+ Kid string `json:"kid"`
+ }
+ if err := json.Unmarshal(hdrRaw, &hdr); err != nil || hdr.Kid != "" {
+ return false
+ }
+ payloadRaw, err := base64.RawURLEncoding.DecodeString(payloadB64)
+ if err != nil {
+ return false
+ }
+ var claims struct {
+ Iss string `json:"iss"`
+ }
+ if err := json.Unmarshal(payloadRaw, &claims); err != nil {
+ return false
+ }
+ return claims.Iss == apiIssuer
+}
+
func (v *Verifier) authenticateIdP(ctx context.Context, tokenStr, actAs string) (authResult, error) {
claims := jwt.MapClaims{}
if _, err := v.idpParser.ParseWithClaims(tokenStr, claims, v.idpKeyFunc); err != nil {
@@ -215,7 +278,7 @@ func (v *Verifier) authenticateIdP(ctx context.Context, tokenStr, actAs string)
log.Printf("auth rejected: reason=no_address_claim claim=%q sub=%q", v.addressClaim, sub)
return authResult{}, authError{status: http.StatusForbidden, msg: "no fmsg account for this identity"}
}
- if status, msg := validateIdentity(owner, v.idURL); status != http.StatusOK {
+ if status, msg := validateIdentity(ctx, owner, v.idURL); status != http.StatusOK {
return authResult{}, authError{status: status, msg: msg}
}
res := authResult{Addr: owner, OwnerAddr: owner, AuthType: AuthTypeIdP}
@@ -256,7 +319,7 @@ func (v *Verifier) authenticateIdP(ctx context.Context, tokenStr, actAs string)
if err := v.apiKeys.ValidateActAs(ctx, owner, actAs); err != nil {
return authResult{}, err
}
- if status, msg := validateIdentity(actAs, v.idURL); status != http.StatusOK {
+ if status, msg := validateIdentity(ctx, actAs, v.idURL); status != http.StatusOK {
return authResult{}, authError{status: status, msg: msg}
}
res.Addr = actAs
@@ -319,7 +382,7 @@ func (v *Verifier) authenticateAPIToken(ctx context.Context, tokenStr, remoteAdd
if err := v.apiKeys.ValidateToken(ctx, claims.APIKeyID, claims.OwnerAddr, subAddr, remoteAddr); err != nil {
return authResult{}, err
}
- if status, msg := validateIdentity(subAddr, v.idURL); status != http.StatusOK {
+ if status, msg := validateIdentity(ctx, subAddr, v.idURL); status != http.StatusOK {
return authResult{}, authError{status: status, msg: msg}
}
return authResult{Addr: subAddr, OwnerAddr: claims.OwnerAddr, AuthType: AuthTypeAPI}, nil
@@ -353,12 +416,12 @@ func authFailureFromError(err error) (int, string, bool) {
return 0, "", false
}
-func validateIdentity(addr, idURL string) (int, string) {
+func validateIdentity(ctx context.Context, addr, idURL string) (int, string) {
if !IsValidAddr(addr) {
log.Printf("auth rejected: reason=invalid_addr addr=%q", addr)
return http.StatusUnauthorized, "invalid identity"
}
- code, accepting, err := CheckFmsgID(idURL, addr)
+ code, accepting, err := CheckFmsgIDContext(ctx, idURL, addr)
if err != nil {
log.Printf("fmsgid check error for %s: %v", addr, err)
return http.StatusServiceUnavailable, "identity service unavailable"
@@ -469,11 +532,32 @@ func IsValidAddr(addr string) bool {
return strings.Contains(rest, "@")
}
-// fmsgIDClient is a dedicated HTTP client with a bounded timeout so that a
-// slow or hung fmsgid never blocks an API request goroutine indefinitely.
-var fmsgIDClient = &http.Client{Timeout: 5 * time.Second}
+// fmsgIDClient is a dedicated HTTP client with a bounded timeout and pooled
+// per-host idle connections so fmsgid lookups reuse keep-alive sockets and never
+// block an API request goroutine indefinitely.
+var fmsgIDClient = newFmsgIDClient()
+
+func newFmsgIDClient() *http.Client {
+ tr := http.DefaultTransport.(*http.Transport).Clone()
+ tr.MaxIdleConnsPerHost = 32
+ return &http.Client{
+ Timeout: 5 * time.Second,
+ Transport: tr,
+ }
+}
-const fmsgIDCacheTTL = 30 * time.Second
+func drainAndClose(body io.ReadCloser) {
+ if body == nil {
+ return
+ }
+ _, _ = io.Copy(io.Discard, io.LimitReader(body, 64<<10))
+ _ = body.Close()
+}
+
+const (
+ fmsgIDCacheTTL = 30 * time.Second
+ fmsgIDCacheMaxEntries = 4096
+)
type fmsgIDEntry struct {
expires time.Time
@@ -481,7 +565,80 @@ type fmsgIDEntry struct {
acceptingNew bool
}
-var fmsgIDCache sync.Map // map[string]fmsgIDEntry, key = address lookup URL
+type boundedFmsgIDCache struct {
+ mu sync.RWMutex
+ entries map[string]fmsgIDEntry
+ maxEntries int
+}
+
+func newBoundedFmsgIDCache(maxEntries int) *boundedFmsgIDCache {
+ return &boundedFmsgIDCache{
+ entries: make(map[string]fmsgIDEntry),
+ maxEntries: maxEntries,
+ }
+}
+
+func (c *boundedFmsgIDCache) get(key string, now time.Time) (fmsgIDEntry, bool) {
+ c.mu.RLock()
+ entry, ok := c.entries[key]
+ c.mu.RUnlock()
+ if !ok {
+ return fmsgIDEntry{}, false
+ }
+ if !now.Before(entry.expires) {
+ c.delete(key)
+ return fmsgIDEntry{}, false
+ }
+ return entry, true
+}
+
+func (c *boundedFmsgIDCache) set(key string, entry fmsgIDEntry, now time.Time) {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ if c.entries == nil {
+ c.entries = make(map[string]fmsgIDEntry)
+ }
+ maxEntries := c.maxEntries
+ if maxEntries <= 0 {
+ maxEntries = fmsgIDCacheMaxEntries
+ }
+ if _, exists := c.entries[key]; !exists && len(c.entries) >= maxEntries {
+ for k, e := range c.entries {
+ if !now.Before(e.expires) {
+ delete(c.entries, k)
+ }
+ }
+ if len(c.entries) >= maxEntries {
+ // Evict the soonest-to-expire entries in a single pass so the cache
+ // stays strictly bounded without repeated full-map scans under lock.
+ target := maxEntries - max(1, maxEntries/8)
+ evictCount := len(c.entries) - target
+ type keyExp struct {
+ key string
+ expires time.Time
+ }
+ items := make([]keyExp, 0, len(c.entries))
+ for k, e := range c.entries {
+ items = append(items, keyExp{key: k, expires: e.expires})
+ }
+ slices.SortFunc(items, func(a, b keyExp) int {
+ return a.expires.Compare(b.expires)
+ })
+ for i := 0; i < evictCount && i < len(items); i++ {
+ delete(c.entries, items[i].key)
+ }
+ }
+ }
+ c.entries[key] = entry
+}
+
+func (c *boundedFmsgIDCache) delete(key string) {
+ c.mu.Lock()
+ delete(c.entries, key)
+ c.mu.Unlock()
+}
+
+var fmsgIDCache = newBoundedFmsgIDCache(fmsgIDCacheMaxEntries)
var fmsgIDGroup singleflight.Group
@@ -492,23 +649,30 @@ type fmsgIDResult struct {
// CheckFmsgID queries the fmsgid service for a user address.
func CheckFmsgID(idURL, addr string) (int, bool, error) {
- lookupURL := fmsgIDAddressURL(idURL, addr)
- if v, ok := fmsgIDCache.Load(lookupURL); ok {
- entry := v.(fmsgIDEntry)
- if time.Now().Before(entry.expires) {
- return entry.code, entry.acceptingNew, nil
- }
- fmsgIDCache.Delete(lookupURL)
+ return CheckFmsgIDContext(context.Background(), idURL, addr)
+}
+
+// CheckFmsgIDContext queries the fmsgid service for a user address using ctx.
+func CheckFmsgIDContext(ctx context.Context, idURL, addr string) (int, bool, error) {
+ cacheKey := fmsgIDCacheKey(idURL, addr)
+ now := time.Now()
+ if entry, ok := fmsgIDCache.get(cacheKey, now); ok {
+ return entry.code, entry.acceptingNew, nil
+ }
+ if err := ctx.Err(); err != nil {
+ return 0, false, err
}
- v, err, _ := fmsgIDGroup.Do(lookupURL, func() (any, error) {
- if v, ok := fmsgIDCache.Load(lookupURL); ok {
- entry := v.(fmsgIDEntry)
- if time.Now().Before(entry.expires) {
- return fmsgIDResult{code: entry.code, acceptingNew: entry.acceptingNew}, nil
- }
+ lookupURL := fmsgIDAddressURL(idURL, addr)
+ v, err, _ := fmsgIDGroup.Do(cacheKey, func() (any, error) {
+ if entry, ok := fmsgIDCache.get(cacheKey, time.Now()); ok {
+ return fmsgIDResult{code: entry.code, acceptingNew: entry.acceptingNew}, nil
}
- return fetchFmsgID(lookupURL)
+ // Detach cancellation inside singleflight so one caller cancelling
+ // cannot fail another caller sharing the same in-flight lookup.
+ reqCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second)
+ defer cancel()
+ return fetchFmsgID(reqCtx, lookupURL, cacheKey)
})
if err != nil {
return 0, false, err
@@ -555,20 +719,36 @@ var errFmsgIDNoAcceptingNew = errors.New("fmsgid does not support accepting_new
// ErrLinkedAddressTaken. reinstated reports whether it had stopped accepting
// new messages (e.g. its grant was deleted).
func RegisterLinkedFmsgID(idURL, addr, owner string) (reinstated bool, err error) {
+ _, reinstated, err = RegisterLinkedFmsgIDContext(context.Background(), idURL, addr, owner)
+ return reinstated, err
+}
+
+// RegisterLinkedFmsgIDContext is like RegisterLinkedFmsgID, using ctx and
+// reporting both whether the address was newly created and whether it was
+// reinstated from disabled state.
+func RegisterLinkedFmsgIDContext(ctx context.Context, idURL, addr, owner string) (created, reinstated bool, err error) {
accepting := true
- resp, err := postFmsgIDAddress(idURL, fmsgIDAddressReq{Address: addr, AcceptingNew: &accepting, QuotaPool: owner, Claim: true})
+ resp, status, err := postFmsgIDAddress(ctx, idURL, fmsgIDAddressReq{Address: addr, AcceptingNew: &accepting, QuotaPool: owner, Claim: true})
if err != nil {
- return false, err
+ return false, false, err
}
- return resp != nil && resp.Reinstated, nil
+ if resp == nil {
+ return status == http.StatusCreated, false, nil
+ }
+ return resp.Created, resp.Reinstated, nil
}
// DisableFmsgID stops addr accepting new messages in fmsgid, so fmsg hosts
// refuse new messages to it. The address, its messages and its usage are kept,
// so its owner can reinstate it with RegisterLinkedFmsgID.
func DisableFmsgID(idURL, addr string) error {
+ return DisableFmsgIDContext(context.Background(), idURL, addr)
+}
+
+// DisableFmsgIDContext is like DisableFmsgID, using ctx for the HTTP request.
+func DisableFmsgIDContext(ctx context.Context, idURL, addr string) error {
accepting := false
- resp, err := postFmsgIDAddress(idURL, fmsgIDAddressReq{Address: addr, AcceptingNew: &accepting})
+ resp, _, err := postFmsgIDAddress(ctx, idURL, fmsgIDAddressReq{Address: addr, AcceptingNew: &accepting})
if err != nil {
return err
}
@@ -580,52 +760,65 @@ func DisableFmsgID(idURL, addr string) error {
// postFmsgIDAddress POSTs req to fmsgid's /fmsgid and drops the cached lookup
// of the address. The response is nil when fmsgid answers without a body.
-func postFmsgIDAddress(idURL string, req fmsgIDAddressReq) (*fmsgIDAddressResp, error) {
+func postFmsgIDAddress(ctx context.Context, idURL string, req fmsgIDAddressReq) (*fmsgIDAddressResp, int, error) {
payload, err := json.Marshal(req)
if err != nil {
- return nil, err
+ return nil, 0, err
}
- url := strings.TrimRight(idURL, "/") + "/fmsgid"
- resp, err := fmsgIDClient.Post(url, "application/json", bytes.NewReader(payload)) //nolint:gosec // URL constructed from trusted config
+ u := strings.TrimRight(idURL, "/") + "/fmsgid"
+ httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, u, bytes.NewReader(payload))
if err != nil {
- return nil, err
+ return nil, 0, err
}
- defer resp.Body.Close()
+ httpReq.Header.Set("Content-Type", "application/json")
+ resp, err := doFmsgID(httpReq)
+ if err != nil {
+ return nil, 0, err
+ }
+ defer drainAndClose(resp.Body)
// whatever fmsgid did, the cached lookup may now be stale
- fmsgIDCache.Delete(fmsgIDAddressURL(idURL, req.Address))
+ fmsgIDCache.delete(fmsgIDCacheKey(idURL, req.Address))
if resp.StatusCode == http.StatusConflict && req.Claim {
- return nil, ErrLinkedAddressTaken
+ return nil, resp.StatusCode, ErrLinkedAddressTaken
}
if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusCreated {
- return nil, fmt.Errorf("fmsgid registration failed: status %d", resp.StatusCode)
+ return nil, resp.StatusCode, fmt.Errorf("fmsgid registration failed: status %d", resp.StatusCode)
}
body, err := io.ReadAll(io.LimitReader(resp.Body, 64<<10))
if err != nil {
- return nil, fmt.Errorf("reading fmsgid registration response: %w", err)
+ return nil, resp.StatusCode, fmt.Errorf("reading fmsgid registration response: %w", err)
}
if len(bytes.TrimSpace(body)) == 0 {
- return nil, nil
+ return nil, resp.StatusCode, nil
}
var out fmsgIDAddressResp
if err := json.Unmarshal(body, &out); err != nil {
- return nil, fmt.Errorf("decoding fmsgid registration response: %w", err)
+ return nil, resp.StatusCode, fmt.Errorf("decoding fmsgid registration response: %w", err)
}
- return &out, nil
+ return &out, resp.StatusCode, nil
}
func fmsgIDAddressURL(idURL, addr string) string {
return strings.TrimRight(idURL, "/") + "/fmsgid/" + url.PathEscape(addr)
}
-func fetchFmsgID(lookupURL string) (fmsgIDResult, error) {
- resp, err := fmsgIDClient.Get(lookupURL) //nolint:gosec // URL constructed from trusted config + escaped addr
+func fmsgIDCacheKey(idURL, addr string) string {
+ return fmsgIDAddressURL(idURL, strings.ToLower(addr))
+}
+
+func fetchFmsgID(ctx context.Context, lookupURL, cacheKey string) (fmsgIDResult, error) {
+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, lookupURL, nil)
if err != nil {
return fmsgIDResult{}, err
}
- defer resp.Body.Close()
+ resp, err := doFmsgID(req)
+ if err != nil {
+ return fmsgIDResult{}, err
+ }
+ defer drainAndClose(resp.Body)
if resp.StatusCode == http.StatusNotFound {
return fmsgIDResult{code: http.StatusNotFound}, nil
@@ -644,10 +837,11 @@ func fetchFmsgID(lookupURL string) (fmsgIDResult, error) {
return fmsgIDResult{}, errors.New("fmsgid address response is missing acceptingNew")
}
- fmsgIDCache.Store(lookupURL, fmsgIDEntry{
- expires: time.Now().Add(fmsgIDCacheTTL),
+ now := time.Now()
+ fmsgIDCache.set(cacheKey, fmsgIDEntry{
+ expires: now.Add(fmsgIDCacheTTL),
code: http.StatusOK,
acceptingNew: *result.AcceptingNew,
- })
+ }, now)
return fmsgIDResult{code: http.StatusOK, acceptingNew: *result.AcceptingNew}, nil
}
diff --git a/internal/middleware/jwt_test.go b/internal/middleware/jwt_test.go
index 7c53492..09df2c2 100644
--- a/internal/middleware/jwt_test.go
+++ b/internal/middleware/jwt_test.go
@@ -6,8 +6,10 @@ import (
"crypto/rand"
"encoding/json"
"errors"
+ "fmt"
"net/http"
"net/http/httptest"
+ "sync/atomic"
"testing"
"time"
@@ -410,3 +412,103 @@ func TestAPITokenMode_ConfigValidation(t *testing.T) {
t.Fatal("missing API key checker: expected error")
}
}
+
+func TestDualAuth_APITokenFastPathSkipsJWKS(t *testing.T) {
+ srv := fmsgIDServer(t, http.StatusOK, true)
+ defer srv.Close()
+
+ idpPriv, baseJWKS := newEdDSAFixture(t)
+ var jwksCalls atomic.Int32
+ countingJWKS := func(tok *jwt.Token) (any, error) {
+ jwksCalls.Add(1)
+ return baseJWKS(tok)
+ }
+
+ _, apiPriv, err := ed25519.GenerateKey(rand.Reader)
+ if err != nil {
+ t.Fatal(err)
+ }
+ apiIssuer := apiauth.NewTokenIssuer(apiPriv, apiauth.DefaultTokenIssuer, apiauth.DefaultTokenAudience, time.Hour)
+ apiTok, _, err := apiIssuer.Mint("@alice@example.com", "@alice_bot@example.com", "kid1", time.Now())
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ mw, err := New(Config{
+ JWKS: countingJWKS,
+ Issuer: testIssuer,
+ Audience: testAudience,
+ AddressClaim: testAddressClaim,
+ APIPublicKey: apiIssuer.PublicKey(),
+ APIIssuer: apiIssuer.Issuer(),
+ APIAudience: apiIssuer.Audience(),
+ APIKeys: fakeAPIKeys{},
+ IDURL: srv.URL,
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ if w := runMiddleware(t, mw, apiTok, ""); w.Code != http.StatusOK {
+ t.Fatalf("API token expected 200, got %d body=%s", w.Code, w.Body.String())
+ }
+ if got := jwksCalls.Load(); got != 0 {
+ t.Fatalf("JWKS keyfunc was called %d times for a first-party API token, want 0", got)
+ }
+
+ idpTok := signEdDSA(t, idpPriv, "prod-1", providerClaims("@alice@example.com"))
+ if w := runMiddleware(t, mw, idpTok, ""); w.Code != http.StatusOK {
+ t.Fatalf("IdP token expected 200, got %d body=%s", w.Code, w.Body.String())
+ }
+ if got := jwksCalls.Load(); got != 1 {
+ t.Fatalf("JWKS keyfunc was called %d times for IdP token, want 1", got)
+ }
+}
+
+func TestFmsgIDCache_CaseInsensitiveAndBounded(t *testing.T) {
+ // 1. Bounded eviction on boundedFmsgIDCache evicts soonest-to-expire entries.
+ cache := newBoundedFmsgIDCache(4)
+ now := time.Unix(1000, 0)
+ for i := range 10 {
+ cache.set(fmt.Sprintf("k%d", i), fmsgIDEntry{
+ expires: now.Add(time.Duration(i+1) * time.Second),
+ code: http.StatusOK,
+ acceptingNew: true,
+ }, now)
+ if got := len(cache.entries); got > 4 {
+ t.Fatalf("cache size = %d after insert %d, exceeds max 4", got, i)
+ }
+ }
+ for _, k := range []string{"k0", "k1", "k2", "k3", "k4", "k5"} {
+ if _, ok := cache.get(k, now); ok {
+ t.Fatalf("expected earlier-expiring entry %s to be evicted", k)
+ }
+ }
+ for _, k := range []string{"k6", "k7", "k8", "k9"} {
+ if _, ok := cache.get(k, now); !ok {
+ t.Fatalf("expected later-expiring entry %s to remain cached", k)
+ }
+ }
+ // Expired entries are evicted on lookup and on insert.
+ if _, ok := cache.get("k9", now.Add(time.Minute)); ok {
+ t.Fatal("expected expired entry to miss")
+ }
+
+ // 2. CheckFmsgID normalizes address case for cache keys.
+ var hits atomic.Int32
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ hits.Add(1)
+ _ = json.NewEncoder(w).Encode(map[string]bool{"acceptingNew": true})
+ }))
+ defer srv.Close()
+
+ if code, ok, err := CheckFmsgID(srv.URL, "@MixedCase@Example.COM"); err != nil || code != http.StatusOK || !ok {
+ t.Fatalf("first lookup: code=%d ok=%v err=%v", code, ok, err)
+ }
+ if code, ok, err := CheckFmsgID(srv.URL, "@mixedcase@example.com"); err != nil || code != http.StatusOK || !ok {
+ t.Fatalf("second lookup: code=%d ok=%v err=%v", code, ok, err)
+ }
+ if got := hits.Load(); got != 1 {
+ t.Fatalf("fmsgid hits = %d, want 1 (case-insensitive cache hit)", got)
+ }
+}