diff --git a/README.md b/README.md index 348ae61..2ffca73 100644 --- a/README.md +++ b/README.md @@ -677,6 +677,7 @@ Add-to recipients are not part of this body — they are added later via `POST / | `400` | Missing/invalid fields, empty `to`, `topic` set together with `pid`, or `pid` not found | | `403` | `from` does not match authenticated user | | `409` | `pid` references a terminal message, which cannot be replied to | +| `409` | A `to` recipient is not a participant of the message `pid` names (see [send](#post-fmsgidsend)) | | `413` | `data` is larger than `FMSG_API_MAX_DATA_SIZE` | ### GET `/fmsg/:id` @@ -814,6 +815,7 @@ Updates a draft message. Only the owner (`from`) may update, and the message mus | `403` | Not the owner, or message already sent | | `404` | Message not found | | `409` | `pid` references a terminal message, which cannot be replied to | +| `409` | A `to` recipient is not a participant of the message `pid` names (see [send](#post-fmsgidsend)) | | `413` | `data` is larger than `FMSG_API_MAX_DATA_SIZE`, or `data` plus attachments is larger than `FMSG_API_MAX_MSG_SIZE` | ### DELETE `/fmsg/:id` @@ -911,8 +913,16 @@ be *sent* when it is a complete, valid fmsg message — at least one well-formed recipient, a `type`, and a supported `version`. An incomplete draft is refused with `400` listing every problem. -For a reply (a draft with `pid`), the route first verifies that every remote -recipient domain can actually accept it: per the fmsg spec a host rejects a +For a reply (a draft with `pid`), every `to` recipient must be a participant +of the message it replies to: that message's sender and recipients or, when +`pid` names an add-to batch by its sha256, also the batch's adder and the +recipients it added. Someone only added in a batch has the batch, not the +original, so a reply that includes them must name the batch. Otherwise the +send is refused with `409` naming who isn't a participant. Create and update +refuse the same reply, so that a draft that could never be sent isn't written. + +The route then verifies that the domain of every remote `to` recipient can +actually accept the reply: per the fmsg spec a host rejects a reply whose parent it has not stored (response code 6), so if the parent was never addressed to a recipient's domain — or every delivery attempt of the parent to that domain by this host concluded in rejection — the send is @@ -925,6 +935,10 @@ third-party delivery's outcome, so the reply is attempted and the wire's originating domain always passes (it retains its outgoing messages). Local recipients are unaffected. +Recipients added to the reply itself (`POST /fmsg/:id/add-to` on the draft) +are outside both checks: they are sent the reply as an add-to message, which +their host accepts in full without holding the reply's parent. + The sender's send limits are then checked against the message's size, the body plus its attachments (see [Quotas](#quotas)). A refusal leaves the message a draft, and carries a `code` naming the limit: @@ -943,6 +957,7 @@ a recipient over one is not delivered and its `response_code` is `101`. | `403` | Not the owner, or the sender is no longer in fmsgid or accepting new messages | | `404` | Message not found | | `409` | Message already sent | +| `409` | A reply's `to` recipient is not a participant of the message it replies to | | `409` | Reply can never be accepted by one or more remote recipient domains (parent never addressed there, or its delivery there failed) | | `413` | Message is bigger than the sender's per-message send size (`send_size_per_msg_limit`) | | `422` | Sender's total sent bytes would exceed its limit, `storage limit reached` (`send_size_total_limit`) | diff --git a/internal/handlers/finalization_integration_test.go b/internal/handlers/finalization_integration_test.go index 48f01ba..4466311 100644 --- a/internal/handlers/finalization_integration_test.go +++ b/internal/handlers/finalization_integration_test.go @@ -350,3 +350,71 @@ func TestFinalizationCommitFailureDoesNotReturnSuccess(t *testing.T) { t.Fatal("rejected commit changed draft", got) } } + +// A reply's recipients must all hold the message it names: someone only added +// in a batch holds the batch, not the original. Send is the gate; drafting +// refuses the same reply, since it could never be sent. +func TestReplyRecipientsMustHoldParent(t *testing.T) { + a := newFinalizationAPI(t) + alice, bob, carol, dave := "@alice@example.com", "@bob@example.com", "@carol@example.com", "@dave@example.com" + orig := a.sendAs(t, alice, []string{bob}, "hello", nil) + batch := jsonResponse(t, a.request(alice, "POST", "/fmsg/"+orig+"/add-to", map[string]any{"add_to": []string{carol}}), 200) + batchHash := batch["sha256"].(string) + got := jsonResponse(t, a.request(alice, "GET", "/fmsg/"+orig, nil), 200) + origHash := got["sha256"].(string) + + reply := func(from string, to []string, pid any) map[string]any { + return map[string]any{"version": 1, "from": from, "to": to, "type": "text/plain;charset=UTF-8", "data": "re", "pid": pid} + } + draft := func(from string, to []string, pid any) *httptest.ResponseRecorder { + return a.request(from, "POST", "/fmsg", reply(from, to, pid)) + } + draftID := func(from string, to []string, pid any) string { + t.Helper() + return fmt.Sprintf("%.0f", jsonResponse(t, draft(from, to, pid), 201)["id"]) + } + send := func(from, id string) *httptest.ResponseRecorder { + return a.request(from, "POST", "/fmsg/"+id+"/send", map[string]any{}) + } + + // Drafting: on create and on update. + for _, pid := range []any{mustID(t, orig), origHash} { + if w := draft(alice, []string{bob, carol}, pid); w.Code != 409 || !strings.Contains(w.Body.String(), carol) { + t.Fatalf("added recipient on a reply to the original: %d %s", w.Code, w.Body) + } + } + if w := draft(alice, []string{bob, dave}, batchHash); w.Code != 409 || !strings.Contains(w.Body.String(), dave) { + t.Fatalf("stranger on a reply to the batch: %d %s", w.Code, w.Body) + } + id := draftID(alice, []string{bob}, mustID(t, orig)) + if w := a.request(alice, "PUT", "/fmsg/"+id, reply(alice, []string{bob, carol}, mustID(t, orig))); w.Code != 409 || !strings.Contains(w.Body.String(), carol) { + t.Fatalf("added recipient put on a draft reply to the original: %d %s", w.Code, w.Body) + } + + // Sending: a draft that names such a recipient anyway (one stored before + // drafting checked) still can't leave. + if _, err := a.pool.Exec(context.Background(), `INSERT INTO msg_to (msg_id, addr) VALUES ($1, $2)`, mustID(t, id), carol); err != nil { + t.Fatal(err) + } + if w := send(alice, id); w.Code != 409 || !strings.Contains(w.Body.String(), carol) { + t.Fatalf("send of a reply to the original with an added recipient: %d %s", w.Code, w.Body) + } + + if w := send(alice, draftID(alice, []string{bob, carol}, batchHash)); w.Code != 200 { + t.Fatalf("reply to the batch: %d %s", w.Code, w.Body) + } + if w := send(bob, draftID(bob, []string{alice}, mustID(t, orig))); w.Code != 200 { + t.Fatalf("reply to the original: %d %s", w.Code, w.Body) + } + if w := send(carol, draftID(carol, []string{alice, bob}, batchHash)); w.Code != 200 { + t.Fatalf("added recipient's reply to the batch: %d %s", w.Code, w.Body) + } + + // Someone added to the reply itself needs neither the parent nor a host + // that holds it: they get the reply as an add-to message, in full. + id = draftID(alice, []string{bob}, mustID(t, orig)) + jsonResponse(t, a.request(alice, "POST", "/fmsg/"+id+"/add-to", map[string]any{"add_to": []string{dave, "@erin@remote.example"}}), 200) + if w := send(alice, id); w.Code != 200 { + t.Fatalf("reply with recipients added to it: %d %s", w.Code, w.Body) + } +} diff --git a/internal/handlers/messages.go b/internal/handlers/messages.go index 61023eb..bfc1c35 100644 --- a/internal/handlers/messages.go +++ b/internal/handlers/messages.go @@ -226,8 +226,11 @@ func undeliverableReplyDomains(replyDomains []string, parentFromDomain string, b return blocked } -// remoteRecipientDomains returns the reply's recipient domains excluding the -// local domain, deduplicated case-insensitively. +// remoteRecipientDomains returns the domains of the reply's to recipients, +// excluding the local domain, deduplicated case-insensitively. Recipients +// added to the reply (add-to) don't count: their hosts are sent an add-to +// message naming the reply, not the reply's parent, and accept it in full +// without holding either (SPEC §10.3 step 7). func remoteRecipientDomains(msg *models.Message, localDomain string) []string { seen := map[string]bool{} var out []string @@ -243,11 +246,6 @@ func remoteRecipientDomains(msg *models.Message, localDomain string) []string { for _, a := range msg.To { add(a) } - for _, b := range msg.AddTo { - for _, a := range b.To { - add(a) - } - } return out } @@ -591,6 +589,10 @@ func (h *MessageHandler) Create(c *gin.Context) { if !h.validateParent(c, msg.PID) { return } + // A reply nobody could send isn't worth drafting. + if !h.checkReplyRecipients(c, &msg.Message) { + return + } // Detect zip (deflate) content by checking for the zip magic bytes. msg.Deflate = false // wire compression is chosen only at finalization @@ -873,6 +875,9 @@ func (h *MessageHandler) Update(c *gin.Context) { if !h.validateParent(c, msg.PID) { return } + if !h.checkReplyRecipients(c, &msg.Message) { + return + } if int64(len(msg.Data)) > h.MaxDataSize { c.JSON(http.StatusRequestEntityTooLarge, gin.H{"error": "message data exceeds maximum size"}) @@ -1059,6 +1064,11 @@ func (h *MessageHandler) Send(c *gin.Context) { return } + // Every recipient of a reply must have the parent it names. + if !h.checkReplyRecipients(c, existing) { + return + } + // A reply can only be accepted by hosts that store its parent (SPEC // §10.3, reject code 6). Refuse now — with the reason — when a remote // recipient domain can never accept it, rather than letting the reply diff --git a/internal/handlers/messages_test.go b/internal/handlers/messages_test.go index 72066c1..7ee982c 100644 --- a/internal/handlers/messages_test.go +++ b/internal/handlers/messages_test.go @@ -347,8 +347,9 @@ func TestRemoteRecipientDomains(t *testing.T) { {To: []string{"@d@other.example", "@e@local.example"}}, }, } + // Added recipients take the reply as an add-to message: no parent needed. got := remoteRecipientDomains(msg, "local.example") - if len(got) != 2 || !strings.EqualFold(got[0], "remote.example") || !strings.EqualFold(got[1], "other.example") { + if len(got) != 1 || !strings.EqualFold(got[0], "remote.example") { t.Fatalf("domains = %v", got) } } diff --git a/internal/handlers/reply_participants.go b/internal/handlers/reply_participants.go new file mode 100644 index 0000000..2423c7b --- /dev/null +++ b/internal/handlers/reply_participants.go @@ -0,0 +1,116 @@ +package handlers + +import ( + "context" + "errors" + "fmt" + "log" + "net/http" + "strings" + + "github.com/gin-gonic/gin" + "github.com/jackc/pgx/v5" + + "github.com/markmnl/fmsg-webapi/internal/models" +) + +// A reply is accepted only by hosts that hold its parent (SPEC §10.3, reject +// code 6). Every recipient of a reply must therefore already have the parent +// it names: a participant of that message. The participants of a message are +// its sender and recipients; those of an add-to batch are also the batch's +// adder and the recipients it added (a batch goes to every participant +// domain, SPEC "Notes on Adding Recipients"). Someone only added in a batch +// has the batch, not the original, so a reply that includes them must name +// the batch by its sha256; anyone new is brought in with add-to. +// +// That is the rule for the reply's to. Recipients added to the reply itself +// (add-to, on the draft or once sent) are outside it: they get the reply as +// an add-to message, whose pid names the reply rather than the reply's +// parent, and a host that doesn't hold a message someone is added to takes +// it as a full delivery (SPEC §10.3 step 7). + +// replyParticipants returns the lower-cased participants of the parent a +// reply names: parentID, or the add-to batch of it whose hash is psha256. +func (h *MessageHandler) replyParticipants(ctx context.Context, parentID int64, psha256 *string) (map[string]bool, error) { + out := map[string]bool{} + var from string + if err := h.q().QueryRow(ctx, `SELECT from_addr FROM msg WHERE id = $1`, parentID).Scan(&from); err != nil { + return nil, err + } + out[strings.ToLower(from)] = true + rows, err := h.q().Query(ctx, `SELECT addr FROM msg_to WHERE msg_id = $1`, parentID) + if err != nil { + return nil, err + } + for rows.Next() { + var a string + if err := rows.Scan(&a); err != nil { + rows.Close() + return nil, err + } + out[strings.ToLower(a)] = true + } + rows.Close() + if err := rows.Err(); err != nil { + return nil, err + } + if psha256 == nil || *psha256 == "" { + return out, nil + } + var batchID int64 + var adder string + err = h.q().QueryRow(ctx, `SELECT id, add_to_from FROM msg_add_to_batch WHERE msg_id = $1 AND sha256 = decode($2, 'hex')`, parentID, *psha256).Scan(&batchID, &adder) + if errors.Is(err, pgx.ErrNoRows) { + return out, nil // the parent named by its own hash + } + if err != nil { + return nil, err + } + out[strings.ToLower(adder)] = true + rows, err = h.q().Query(ctx, `SELECT addr FROM msg_add_to WHERE msg_id = $1 AND batch_id = $2`, parentID, batchID) + if err != nil { + return nil, err + } + defer rows.Close() + for rows.Next() { + var a string + if err := rows.Scan(&a); err != nil { + return nil, err + } + out[strings.ToLower(a)] = true + } + return out, rows.Err() +} + +// checkReplyRecipients answers 409 and reports false when a reply has a +// recipient who isn't a participant of the parent it names. Send is the gate; +// create and update check too, so that a draft that could never be sent +// isn't written. +func (h *MessageHandler) checkReplyRecipients(c *gin.Context, msg *models.Message) bool { + if msg.PID == nil { + return true + } + parts, err := h.replyParticipants(c.Request.Context(), *msg.PID, msg.PSHA256) + if err != nil { + log.Printf("verify reply recipients against parent %d: %v", *msg.PID, err) + c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to verify reply recipients"}) + return false + } + var missing []string + seen := map[string]bool{} + for _, a := range msg.To { + k := strings.ToLower(a) + if !parts[k] && !seen[k] { + seen[k] = true + missing = append(missing, a) + } + } + if len(missing) == 0 { + return true + } + c.JSON(http.StatusConflict, gin.H{"error": fmt.Sprintf( + "a reply's recipients must all have the message it replies to: %s %s not a participant of it — "+ + "reply to their add-to batch (by its sha256) if they were added, or add them to the message (add-to)", + strings.Join(missing, ", "), map[bool]string{true: "is", false: "are"}[len(missing) == 1])}) + return false +} diff --git a/internal/handlers/trash_integration_test.go b/internal/handlers/trash_integration_test.go index 69db000..83e0d4d 100644 --- a/internal/handlers/trash_integration_test.go +++ b/internal/handlers/trash_integration_test.go @@ -183,7 +183,24 @@ func TestPurge(t *testing.T) { a := newFinalizationAPIWithID(t, usage.handler()) ctx := context.Background() root := a.sendAs(t, alice, []string{bob, alice}, "root", nil) - reply := a.sendAs(t, bob, []string{alice, bob, carol}, "reply", mustID(t, root)) + reply := a.sendAs(t, bob, []string{alice, bob}, "reply", mustID(t, root)) + // Carol holds the reply but never had the root: a reply can't be sent + // that way through the API, but a stored one can end up so (a remote + // host's delivery, or the root deleted here since), so set it up directly. + // (Triggers off: finalized recipients are otherwise immutable.) + tx, err := a.pool.Begin(ctx) + if err != nil { + t.Fatal(err) + } + if _, err := tx.Exec(ctx, `SET LOCAL session_replication_role = replica`); err != nil { + t.Fatal(err) + } + if _, err := tx.Exec(ctx, `INSERT INTO msg_to (msg_id, addr, time_delivered) VALUES ($1, $2, $3)`, mustID(t, reply), carol, now()); err != nil { + t.Fatal(err) + } + if err := tx.Commit(ctx); err != nil { + t.Fatal(err) + } var body, hash string if err := a.pool.QueryRow(ctx, `SELECT filepath, encode(sha256,'hex') FROM msg WHERE id = $1`, mustID(t, root)).Scan(&body, &hash); err != nil { t.Fatal(err)